• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

divio / django-cms / #27677

25 Aug 2023 04:03PM UTC coverage: 76.775% (-0.6%) from 77.361%
#27677

push

travis-ci

web-flow
Update CHANGELOG.rst

1042 of 1539 branches covered (0.0%)

2519 of 3281 relevant lines covered (76.78%)

32.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

36.46
/cms/static/cms/js/modules/cms.pagetree.js
1
/*
2
 * Copyright https://github.com/divio/django-cms
3
 */
4

5
import $ from 'jquery';
6
import URL from 'urijs';
7

8
import Class from 'classjs';
9
import { Helpers, KEYS } from './cms.base';
10
import PageTreeDropdowns from './cms.pagetree.dropdown';
11
import PageTreeStickyHeader from './cms.pagetree.stickyheader';
12
import { debounce, without } from 'lodash';
13

14
import 'jstree';
15
import '../libs/jstree/jstree.grid.min';
16

17
/**
18
 * The pagetree is loaded via `/admin/cms/page` and has a custom admin
19
 * templates stored within `templates/admin/cms/page/tree`.
20
 *
21
 * @class PageTree
22
 * @namespace CMS
23
 */
24
var PageTree = new Class({
1✔
25
    options: {
26
        pasteSelector: '.js-cms-tree-item-paste'
27
    },
28
    initialize: function initialize(options) {
29
        // options are loaded from the pagetree html node
30
        var opts = $('.js-cms-pagetree').data('json');
21✔
31

32
        this.options = $.extend(true, {}, this.options, opts, options);
21✔
33

34
        // states and events
35
        this.click = 'click.cms.pagetree';
21✔
36
        this.clipboard = {
21✔
37
            id: null,
38
            origin: null,
39
            type: ''
40
        };
41
        this.successTimer = 1000;
21✔
42

43
        // elements
44
        this._setupUI();
21✔
45
        this._events();
21✔
46

47
        Helpers.csrf(this.options.csrf);
21✔
48

49
        this._setupLanguages();
21✔
50

51
        // cancel if pagetree is not available
52
        if ($.isEmptyObject(opts) || opts.empty) {
21✔
53
            this._getClipboard();
1✔
54
            // attach events to paste
55
            var that = this;
1✔
56

57
            this.ui.container.on(this.click, this.options.pasteSelector, function(e) {
1✔
58
                e.preventDefault();
×
59
                if ($(this).hasClass('cms-pagetree-dropdown-item-disabled')) {
×
60
                    return;
×
61
                }
62
                that._paste(e);
×
63
            });
64
        } else {
65
            this._setup();
20✔
66
        }
67
    },
68

69
    /**
70
     * Stores all jQuery references within `this.ui`.
71
     *
72
     * @method _setupUI
73
     * @private
74
     */
75
    _setupUI: function _setupUI() {
76
        var pagetree = $('.cms-pagetree');
21✔
77

78
        this.ui = {
21✔
79
            container: pagetree,
80
            document: $(document),
81
            tree: pagetree.find('.js-cms-pagetree'),
82
            dialog: $('.js-cms-tree-dialog'),
83
            siteForm: $('.js-cms-pagetree-site-form'),
84
            languagesSelect: $('.js-cms-pagetree-languages')
85
        };
86
    },
87

88
    _setupLanguages: function _setupLanguages() {
89
        this.ui.languagesSelect.on('change', () => {
21✔
90
            const newLanguage = this.ui.languagesSelect.val();
×
91

92
            const url = new URL(window.location.href).removeSearch('language')
×
93
                .addSearch('language', newLanguage).toString();
94

95
            window.location.href = url;
×
96
        });
97
    },
98

99
    /**
100
     * Setting up the jstree and the related columns.
101
     *
102
     * @method _setup
103
     * @private
104
     */
105
    _setup: function _setup() {
106
        var that = this;
20✔
107
        var columns = [];
20✔
108
        var obj = {
20✔
109
            language: this.options.lang.code,
110
            openNodes: []
111
        };
112
        var data = false;
20✔
113

114
        // setup column headings
115
        // eslint-disable-next-line no-shadow
116
        $.each(this.options.columns, function(index, obj) {
20✔
117
            if (obj.key === '') {
200✔
118
                // the first row is already populated, to avoid overwrites
119
                // just leave the "key" param empty
120
                columns.push({
20✔
121
                    wideValueClass: obj.wideValueClass,
122
                    wideValueClassPrefix: obj.wideValueClassPrefix,
123
                    header: obj.title,
124
                    width: obj.width || '1%',
20!
125
                    wideCellClass: obj.cls
126
                });
127
            } else {
128
                columns.push({
180✔
129
                    wideValueClass: obj.wideValueClass,
130
                    wideValueClassPrefix: obj.wideValueClassPrefix,
131
                    header: obj.title,
132
                    value: function(node) {
133
                        // it needs to have the "colde" format and not "col-de"
134
                        // as jstree will convert "col-de" to "colde"
135
                        // also we strip dashes, in case language code contains it
136
                        // e.g. zh-hans, zh-cn etc
137
                        if (node.data) {
×
138
                            return node.data['col' + obj.key.replace('-', '')];
×
139
                        }
140

141
                        return '';
×
142
                    },
143
                    width: obj.width || '1%',
360✔
144
                    wideCellClass: obj.cls
145
                });
146
            }
147
        });
148

149
        // prepare data
150
        if (!this.options.filtered) {
20!
151
            data = {
20✔
152
                url: this.options.urls.tree,
153
                cache: false,
154
                data: function(node) {
155
                    // '#' is rendered if its the root node, there we only
156
                    // care about `obj.openNodes`, in the following case
157
                    // we are requesting a specific node
158
                    if (node.id === '#') {
20!
159
                        obj.nodeId = null;
20✔
160
                    } else {
161
                        obj.nodeId = that._storeNodeId(node.data.nodeId);
×
162
                    }
163

164
                    // we need to store the opened items inside the localstorage
165
                    // as we have to load the pagetree with the previous opened
166
                    // state
167
                    obj.openNodes = that._getStoredNodeIds();
20✔
168

169
                    // we need to set the site id to get the correct tree
170
                    obj.site = that.options.site;
20✔
171

172
                    return obj;
20✔
173
                }
174
            };
175
        }
176

177
        // bind options to the jstree instance
178
        this.ui.tree.jstree({
20✔
179
            core: {
180
                // disable open/close animations
181
                animation: 0,
182
                // core setting to allow actions
183
                // eslint-disable-next-line max-params
184
                check_callback: function(operation, node, node_parent, node_position, more) {
185
                    if ((operation === 'move_node' || operation === 'copy_node') && more && more.pos) {
×
186
                        if (more.pos === 'i') {
×
187
                            $('#jstree-marker').addClass('jstree-marker-child');
×
188
                        } else {
189
                            $('#jstree-marker').removeClass('jstree-marker-child');
×
190
                        }
191
                    }
192

193
                    return that._hasPermission(node_parent, 'add');
×
194
                },
195
                // https://www.jstree.com/api/#/?f=$.jstree.defaults.core.data
196
                data: data,
197
                // strings used within jstree that are called using `get_string`
198
                strings: {
199
                    'Loading ...': this.options.lang.loading,
200
                    'New node': this.options.lang.newNode,
201
                    nodes: this.options.lang.nodes
202
                },
203
                error: function(error) {
204
                    // ignore warnings about dragging parent into child
205
                    var errorData = JSON.parse(error.data);
×
206

207
                    if (error.error === 'check' && errorData && errorData.chk === 'move_node') {
×
208
                        return;
×
209
                    }
210
                    that.showError(error.reason);
×
211
                },
212
                themes: {
213
                    name: 'django-cms'
214
                },
215
                // disable the multi selection of nodes for now
216
                multiple: false
217
            },
218
            // activate drag and drop plugin
219
            plugins: ['dnd', 'search', 'grid'],
220
            // https://www.jstree.com/api/#/?f=$.jstree.defaults.dnd
221
            dnd: {
222
                inside_pos: 'last',
223
                // disable the multi selection of nodes for now
224
                drag_selection: false,
225
                // disable dragging if filtered
226
                is_draggable: function(nodes) {
227
                    return that._hasPermission(nodes[0], 'move') && !that.options.filtered;
×
228
                },
229
                large_drop_target: true,
230
                copy: true,
231
                touch: 'selected'
232
            },
233
            // https://github.com/deitch/jstree-grid
234
            grid: {
235
                // columns are provided from base.html options
236
                width: '100%',
237
                columns: columns
238
            }
239
        });
240
    },
241

242
    /**
243
     * Sets up all the event handlers, such as opening and moving.
244
     *
245
     * @method _events
246
     * @private
247
     */
248
    _events: function _events() {
249
        var that = this;
21✔
250

251
        // set events for the nodeId updates
252
        this.ui.tree.on('after_close.jstree', function(e, el) {
21✔
253
            that._removeNodeId(el.node.data.nodeId);
×
254
        });
255

256
        this.ui.tree.on('after_open.jstree', function(e, el) {
21✔
257
            that._storeNodeId(el.node.data.nodeId);
×
258

259
            // `after_open` event can be triggered when pasting
260
            // is in progress (meaning we are pasting into a leaf node
261
            // in this case we do not need to update helpers state
262
            if (this.clipboard && !this.clipboard.isPasting) {
×
263
                that._updatePasteHelpersState();
×
264
            }
265
        });
266

267
        this.ui.document.on('keydown.pagetree.alt-mode', function(e) {
21✔
268
            if (e.keyCode === KEYS.SHIFT) {
466!
269
                that.ui.container.addClass('cms-pagetree-alt-mode');
×
270
            }
271
        });
272

273
        this.ui.document.on('keyup.pagetree.alt-mode', function(e) {
21✔
274
            if (e.keyCode === KEYS.SHIFT) {
463!
275
                that.ui.container.removeClass('cms-pagetree-alt-mode');
×
276
            }
277
        });
278

279
        $(window)
21✔
280
            .on(
281
                'mousemove.pagetree.alt-mode',
282
                debounce(function(e) {
283
                    if (e.shiftKey) {
1!
284
                        that.ui.container.addClass('cms-pagetree-alt-mode');
×
285
                    } else {
286
                        that.ui.container.removeClass('cms-pagetree-alt-mode');
1✔
287
                    }
288
                }, 200) // eslint-disable-line no-magic-numbers
289
            )
290
            .on('blur.cms', () => {
291
                that.ui.container.removeClass('cms-pagetree-alt-mode');
21✔
292
            });
293

294
        this.ui.document.on('dnd_start.vakata', function(e, data) {
21✔
295
            var element = $(data.element);
×
296
            var node = element.parent();
×
297

298
            that._dropdowns.closeAllDropdowns();
×
299

300
            node.addClass('jstree-is-dragging');
×
301
            data.data.nodes.forEach(function(nodeId) {
×
302
                var descendantIds = that._getDescendantsIds(nodeId);
×
303

304
                [nodeId].concat(descendantIds).forEach(function(id) {
×
305
                    $('.jsgrid_' + id + '_col').addClass('jstree-is-dragging');
×
306
                });
307
            });
308

309
            if (!node.hasClass('jstree-leaf')) {
×
310
                data.helper.addClass('is-stacked');
×
311
            }
312
        });
313

314
        var isCopyClassAdded = false;
21✔
315

316
        this.ui.document.on('dnd_move.vakata', function(e, data) {
21✔
317
            var isMovingCopy =
318
                data.data.origin &&
×
319
                (data.data.origin.settings.dnd.always_copy ||
320
                    (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey)));
321

322
            if (isMovingCopy) {
×
323
                if (!isCopyClassAdded) {
×
324
                    $('.jstree-is-dragging').addClass('jstree-is-dragging-copy');
×
325
                    isCopyClassAdded = true;
×
326
                }
327
            } else if (isCopyClassAdded) {
×
328
                $('.jstree-is-dragging').removeClass('jstree-is-dragging-copy');
×
329
                isCopyClassAdded = false;
×
330
            }
331
        });
332

333
        this.ui.document.on('dnd_stop.vakata', function(e, data) {
21✔
334
            var element = $(data.element);
×
335
            var node = element.parent();
×
336

337
            node.removeClass('jstree-is-dragging jstree-is-dragging-copy');
×
338
            data.data.nodes.forEach(function(nodeId) {
×
339
                var descendantIds = that._getDescendantsIds(nodeId);
×
340

341
                [nodeId].concat(descendantIds).forEach(function(id) {
×
342
                    $('.jsgrid_' + id + '_col').removeClass('jstree-is-dragging jstree-is-dragging-copy');
×
343
                });
344
            });
345
        });
346

347
        // store moved position node
348
        this.ui.tree.on('move_node.jstree copy_node.jstree', function(e, obj) {
21✔
349
            if ((!that.clipboard.type && e.type !== 'copy_node') || that.clipboard.type === 'cut') {
×
350
                that._moveNode(that._getNodePosition(obj)).done(function() {
×
351
                    var instance = that.ui.tree.jstree(true);
×
352

353
                    instance._hide_grid(instance.get_node(obj.parent));
×
354
                    if (obj.parent === '#' || (obj.node && obj.node.data && obj.node.data.isHome)) {
×
355
                        instance.refresh();
×
356
                    } else {
357
                        // have to refresh parent, because refresh only
358
                        // refreshes children of the node, never the node itself
359
                        instance.refresh_node(obj.parent);
×
360
                    }
361
                });
362
            } else {
363
                that._copyNode(obj);
×
364
            }
365
            // we need to open the parent node if we trigger an element
366
            // if not already opened
367
            that.ui.tree.jstree('open_node', obj.parent);
×
368
        });
369

370
        // set event for cut and paste
371
        this.ui.container.on(this.click, '.js-cms-tree-item-cut', function(e) {
21✔
372
            e.preventDefault();
×
373
            that._cutOrCopy({ type: 'cut', element: $(this) });
×
374
        });
375

376
        // set event for cut and paste
377
        this.ui.container.on(this.click, '.js-cms-tree-item-copy', function(e) {
21✔
378
            e.preventDefault();
×
379
            that._cutOrCopy({ type: 'copy', element: $(this) });
×
380
        });
381

382
        // attach events to paste
383
        this.ui.container.on(this.click, this.options.pasteSelector, function(e) {
21✔
384
            e.preventDefault();
×
385
            if ($(this).hasClass('cms-pagetree-dropdown-item-disabled')) {
×
386
                return;
×
387
            }
388
            that._paste(e);
×
389
        });
390

391
        // advanced settings link handling
392
        this.ui.container.on(this.click, '.js-cms-tree-advanced-settings', function(e) {
21✔
393
            if (e.shiftKey) {
×
394
                e.preventDefault();
×
395
                var link = $(this);
×
396

397
                if (link.data('url')) {
×
398
                    window.location.href = link.data('url');
×
399
                }
400
            }
401
        });
402

403
        // when adding new pages - expand nodes as well
404
        this.ui.container.on(this.click, '.js-cms-pagetree-add-page', e => {
21✔
405
            const treeId = this._getNodeId($(e.target));
×
406

407
            const nodeData = this.ui.tree.jstree('get_node', treeId);
×
408

409
            this._storeNodeId(nodeData.data.id);
×
410
        });
411

412
        // add events for error reload (messagelist)
413
        this.ui.document.on(this.click, '.messagelist .cms-tree-reload', function(e) {
21✔
414
            e.preventDefault();
×
415
            that._reloadHelper();
×
416
        });
417

418
        // propagate the sites dropdown "li > a" entries to the hidden sites form
419
        this.ui.container.find('.js-cms-pagetree-site-trigger').on(this.click, function(e) {
21✔
420
            e.preventDefault();
×
421
            var el = $(this);
×
422

423
            // prevent if parent is active
424
            if (el.parent().hasClass('active')) {
×
425
                return false;
×
426
            }
427
            that.ui.siteForm.find('select').val(el.data().id).end().submit();
×
428
        });
429

430
        // additional event handlers
431
        this._setupDropdowns();
21✔
432
        this._setupSearch();
21✔
433

434
        // make sure ajax post requests are working
435
        this._setAjaxPost('.js-cms-tree-item-menu a');
21✔
436
        this._setAjaxPost('.js-cms-tree-lang-trigger');
21✔
437
        this._setAjaxPost('.js-cms-tree-item-set-home a');
21✔
438

439
        this._setupPageView();
21✔
440
        this._setupStickyHeader();
21✔
441

442
        this.ui.tree.on('ready.jstree', () => this._getClipboard());
21✔
443
    },
444

445
    _getClipboard: function _getClipboard() {
446
        this.clipboard = CMS.settings.pageClipboard || this.clipboard;
1✔
447

448
        if (this.clipboard.type && this.clipboard.origin) {
1!
449
            this._enablePaste();
×
450
            this._updatePasteHelpersState();
×
451
        }
452
    },
453

454
    /**
455
     * Helper to process the cut and copy events.
456
     *
457
     * @method _cutOrCopy
458
     * @param {Object} [obj]
459
     * @param {Number} [obj.type] either 'cut' or 'copy'
460
     * @param {Number} [obj.element] originated trigger element
461
     * @private
462
     * @returns {Boolean|void}
463
     */
464
    _cutOrCopy: function _cutOrCopy(obj) {
465
        // prevent actions if you try to copy a page with an apphook
466
        if (obj.type === 'copy' && obj.element.data().apphook) {
×
467
            this.showError(this.options.lang.apphook);
×
468
            return false;
×
469
        }
470

471
        var jsTreeId = this._getNodeId(obj.element.closest('.jstree-grid-cell'));
×
472

473
        // resets if we click again
474
        if (this.clipboard.type === obj.type && jsTreeId === this.clipboard.id) {
×
475
            this.clipboard.type = null;
×
476
            this.clipboard.id = null;
×
477
            this.clipboard.origin = null;
×
478
            this.clipboard.source_site = null;
×
479
            this._disablePaste();
×
480
        } else {
481
            this.clipboard.origin = obj.element.data().id; // this._getNodeId(obj.element);
×
482
            this.clipboard.type = obj.type;
×
483
            this.clipboard.id = jsTreeId;
×
484
            this.clipboard.source_site = this.options.site;
×
485
            this._updatePasteHelpersState();
×
486
        }
487
        if (this.clipboard.type === 'copy' || !this.clipboard.type) {
×
488
            CMS.settings.pageClipboard = this.clipboard;
×
489
            Helpers.setSettings(CMS.settings);
×
490
        }
491
    },
492

493
    /**
494
     * Helper to process the paste event.
495
     *
496
     * @method _paste
497
     * @param {$.Event} event click event
498
     * @private
499
     */
500
    _paste: function _paste(event) {
501
        // hide helpers after we picked one
502
        this._disablePaste();
5✔
503

504
        var copyFromId = this._getNodeId(
5✔
505
            $(`.js-cms-pagetree-options[data-id="${this.clipboard.origin}"]`).closest('.jstree-grid-cell')
506
        );
507
        var copyToId = this._getNodeId($(event.currentTarget));
5✔
508

509
        if (this.clipboard.source_site === this.options.site) {
5!
510
            if (this.clipboard.type === 'cut') {
×
511
                this.ui.tree.jstree('cut', copyFromId);
×
512
            } else {
513
                this.ui.tree.jstree('copy', copyFromId);
×
514
            }
515

516
            this.clipboard.isPasting = true;
×
517
            this.ui.tree.jstree('paste', copyToId, 'last');
×
518
        } else {
519
            const dummyId = this.ui.tree.jstree('create_node', copyToId, 'Loading', 'last');
5✔
520

521
            if (this.ui.tree.length) {
5!
522
                this.ui.tree.jstree('cut', dummyId);
5✔
523
                this.clipboard.isPasting = true;
5✔
524
                this.ui.tree.jstree('paste', copyToId, 'last');
5✔
525
            } else {
526
                if (this.clipboard.type === 'copy') {
×
527
                    this._copyNode();
×
528
                }
529
                if (this.clipboard.type === 'cut') {
×
530
                    this._moveNode();
×
531
                }
532
            }
533
        }
534

535
        this.clipboard.id = null;
5✔
536
        this.clipboard.type = null;
5✔
537
        this.clipboard.origin = null;
5✔
538
        this.clipboard.isPasting = false;
5✔
539
        CMS.settings.pageClipboard = this.clipboard;
5✔
540
        Helpers.setSettings(CMS.settings);
5✔
541
    },
542

543
    /**
544
     * Retreives a list of nodes from local storage.
545
     *
546
     * @method _getStoredNodeIds
547
     * @private
548
     * @returns {Array} list of ids
549
     */
550
    _getStoredNodeIds: function _getStoredNodeIds() {
551
        return CMS.settings.pagetree || [];
20✔
552
    },
553

554
    /**
555
     * Stores a node in local storage.
556
     *
557
     * @method _storeNodeId
558
     * @private
559
     * @param {String} id to be stored
560
     * @returns {String} id that has been stored
561
     */
562
    _storeNodeId: function _storeNodeId(id) {
563
        var number = id;
×
564
        var storage = this._getStoredNodeIds();
×
565

566
        // store value only if it isn't there yet
567
        if (storage.indexOf(number) === -1) {
×
568
            storage.push(number);
×
569
        }
570

571
        CMS.settings.pagetree = storage;
×
572
        Helpers.setSettings(CMS.settings);
×
573

574
        return number;
×
575
    },
576

577
    /**
578
     * Removes a node in local storage.
579
     *
580
     * @method _removeNodeId
581
     * @private
582
     * @param {String} id to be stored
583
     * @returns {String} id that has been removed
584
     */
585
    _removeNodeId: function _removeNodeId(id) {
586
        const instance = this.ui.tree.jstree(true);
×
587
        const childrenIds = instance.get_node({
×
588
            id: CMS.$(`[data-node-id=${id}]`).attr('id')
589
        }).children_d;
590

591
        const idsToRemove = [id].concat(
×
592
            childrenIds.map(childId => {
593
                const node = instance.get_node({ id: childId });
×
594

595
                if (!node || !node.data) {
×
596
                    return node;
×
597
                }
598

599
                return node.data.nodeId;
×
600
            })
601
        );
602

603
        const storage = without(this._getStoredNodeIds(), ...idsToRemove);
×
604

605
        CMS.settings.pagetree = storage;
×
606
        Helpers.setSettings(CMS.settings);
×
607

608
        return id;
×
609
    },
610

611
    /**
612
     * Moves a node after drag & drop.
613
     *
614
     * @method _moveNode
615
     * @param {Object} [obj]
616
     * @param {Number} [obj.id] current element id for url matching
617
     * @param {Number} [obj.target] target sibling or parent
618
     * @param {Number} [obj.position] either `left`, `right` or `last-child`
619
     * @returns {$.Deferred} ajax request object
620
     * @private
621
     */
622
    _moveNode: function _moveNode(obj) {
623
        var that = this;
×
624

625
        if (!obj.id && this.clipboard.type === 'cut' && this.clipboard.origin) {
×
626
            obj.id = this.clipboard.origin;
×
627
            obj.source_site = this.clipboard.source_site;
×
628
        } else {
629
            obj.site = that.options.site;
×
630
        }
631

632
        return $.ajax({
×
633
            method: 'post',
634
            url: that.options.urls.move.replace('{id}', obj.id),
635
            data: obj
636
        })
637
            .done(function(r) {
638
                if (r.status && r.status === 400) { // eslint-disable-line
×
639
                    that.showError(r.content);
×
640
                } else {
641
                    that._showSuccess(obj.id);
×
642
                }
643
            })
644
            .fail(function(error) {
645
                that.showError(error.statusText);
×
646
            });
647
    },
648

649
    /**
650
     * Copies a node into the selected node.
651
     *
652
     * @method _copyNode
653
     * @param {Object} obj page obj
654
     * @private
655
     */
656
    _copyNode: function _copyNode(obj) {
657
        var that = this;
×
658
        var node = { position: 0 };
×
659

660
        if (obj) {
×
661
            node = that._getNodePosition(obj);
×
662
        }
663

664
        var data = {
×
665
            // obj.original.data.id is for drag copy
666
            id: this.clipboard.origin || obj.original.data.id,
×
667
            position: node.position
668
        };
669

670
        if (this.clipboard.source_site) {
×
671
            data.source_site = this.clipboard.source_site;
×
672
        } else {
673
            data.source_site = this.options.site;
×
674
        }
675

676
        // if there is no target provided, the node lands in root
677
        if (node.target) {
×
678
            data.target = node.target;
×
679
        }
680

681
        if (that.options.permission) {
×
682
            // we need to load a dialog first, to check if permissions should
683
            // be copied or not
684
            $.ajax({
×
685
                method: 'post',
686
                url: that.options.urls.copyPermission.replace('{id}', data.id),
687
                data: data
688
                // the dialog is loaded via the ajax respons originating from
689
                // `templates/admin/cms/page/tree/copy_premissions.html`
690
            })
691
                .done(function(dialog) {
692
                    that.ui.dialog.append(dialog);
×
693
                })
694
                .fail(function(error) {
695
                    that.showError(error.statusText);
×
696
                });
697

698
            // attach events to the permission dialog
699
            this.ui.dialog
×
700
                .off(this.click, '.cancel')
701
                .on(this.click, '.cancel', function(e) {
702
                    e.preventDefault();
×
703
                    // remove just copied node
704
                    that.ui.tree.jstree('delete_node', obj.node.id);
×
705
                    $('.js-cms-dialog').remove();
×
706
                    $('.js-cms-dialog-dimmer').remove();
×
707
                })
708
                .off(this.click, '.submit')
709
                .on(this.click, '.submit', function(e) {
710
                    e.preventDefault();
×
711
                    var submitButton = $(this);
×
712
                    var formData = submitButton.closest('form').serialize().split('&');
×
713

714
                    submitButton.prop('disabled', true);
×
715

716
                    // loop through form data and attach to obj
717
                    for (var i = 0; i < formData.length; i++) {
×
718
                        data[formData[i].split('=')[0]] = formData[i].split('=')[1];
×
719
                    }
720

721
                    that._saveCopiedNode(data);
×
722
                });
723
        } else {
724
            this._saveCopiedNode(data);
×
725
        }
726
    },
727

728
    /**
729
     * Sends the request to copy a node.
730
     *
731
     * @method _saveCopiedNode
732
     * @private
733
     * @param {Object} data node position information
734
     * @returns {$.Deferred}
735
     */
736
    _saveCopiedNode: function _saveCopiedNode(data) {
737
        var that = this;
×
738

739
        // send the real ajax request for copying the plugin
740
        return $.ajax({
×
741
            method: 'post',
742
            url: that.options.urls.copy.replace('{id}', data.id),
743
            data: data
744
        })
745
            .done(function(r) {
746
                if (r.status && r.status === 400) { // eslint-disable-line
×
747
                    that.showError(r.content);
×
748
                } else {
749
                    that._reloadHelper();
×
750
                }
751
            })
752
            .fail(function(error) {
753
                that.showError(error.statusText);
×
754
            });
755
    },
756

757
    /**
758
     * Returns element from any sub nodes.
759
     *
760
     * @method _getElement
761
     * @private
762
     * @param {jQuery} el jQuery node form where to search
763
     * @returns {String} jsTree node element id
764
     */
765
    _getNodeId: function _getNodeId(el) {
766
        var cls = el.closest('.jstree-grid-cell').attr('class');
2✔
767

768
        // if it's not a cell, assume it's the root node
769
        return cls ? cls.replace(/.*jsgrid_(.+?)_col.*/, '$1') : '#';
2✔
770
    },
771

772
    /**
773
     * Gets the new node position after moving.
774
     *
775
     * @method _getNodePosition
776
     * @private
777
     * @param {Object} obj jstree move object
778
     * @returns {Object} evaluated object with params
779
     */
780
    _getNodePosition: function _getNodePosition(obj) {
781
        var data = {};
×
782
        var node = this.ui.tree.jstree('get_node', obj.node.parent);
×
783

784
        data.position = obj.position;
×
785

786
        // jstree indicates no parent with `#`, in this case we do not
787
        // need to set the target attribute at all
788
        if (obj.parent !== '#') {
×
789
            data.target = node.data.id;
×
790
        }
791

792
        // some functions like copy create a new element with a new id,
793
        // in this case we need to set `data.id` manually
794
        if (obj.node && obj.node.data) {
×
795
            data.id = obj.node.data.id;
×
796
        }
797

798
        return data;
×
799
    },
800

801
    /**
802
     * Sets up general tooltips that can have a list of links or content.
803
     *
804
     * @method _setupDropdowns
805
     * @private
806
     */
807
    _setupDropdowns: function _setupDropdowns() {
808
        this._dropdowns = new PageTreeDropdowns({
21✔
809
            container: this.ui.container
810
        });
811
    },
812

813
    /**
814
     * Handles page view click. Usual use case is that after you click
815
     * on view page in the pagetree - sideframe is no longer needed,
816
     * so we close it.
817
     *
818
     * @method _setupPageView
819
     * @private
820
     */
821
    _setupPageView: function _setupPageView() {
822
        var win = Helpers._getWindow();
25✔
823
        var parent = win.parent ? win.parent : win;
25✔
824

825
        this.ui.container.on(this.click, '.js-cms-pagetree-page-view', function() {
25✔
826
            parent.CMS.API.Helpers.setSettings(
3✔
827
                $.extend(true, {}, CMS.settings, {
828
                    sideframe: {
829
                        url: null,
830
                        hidden: true
831
                    }
832
                })
833
            );
834
        });
835
    },
836

837
    /**
838
     * @method _setupStickyHeader
839
     * @private
840
     */
841
    _setupStickyHeader: function _setupStickyHeader() {
842
        var that = this;
21✔
843

844
        that.ui.tree.on('ready.jstree', function() {
21✔
845
            that.header = new PageTreeStickyHeader({
×
846
                container: that.ui.container
847
            });
848
        });
849
    },
850

851
    /**
852
     * Triggers the links `href` as ajax post request.
853
     *
854
     * @method _setAjaxPost
855
     * @private
856
     * @param {jQuery} trigger jQuery link target
857
     */
858
    _setAjaxPost: function _setAjaxPost(trigger) {
859
        var that = this;
63✔
860

861
        this.ui.container.on(this.click, trigger, function(e) {
63✔
862
            e.preventDefault();
×
863

864
            var element = $(this);
×
865

866
            if (element.closest('.cms-pagetree-dropdown-item-disabled').length) {
×
867
                return;
×
868
            }
869
            if (element.attr('target') === '_top') {
×
870
                // Post to target="_top" requires to create a form and submit it
871
                var parent = window;
×
872

873
                if (window.parent) {
×
874
                    parent = window.parent;
×
875
                }
876
                let formToken = document.querySelector('form input[name="csrfmiddlewaretoken"]');
×
877
                let csrfToken = '<input type="hidden" name="csrfmiddlewaretoken" value="' +
×
878
                    ((formToken ? formToken.value : formToken) || window.CMS.config.csrf) + '">';
×
879

880
                $('<form method="post" action="' + element.attr('href') + '">' +
×
881
                    csrfToken + '</form>')
882
                    .appendTo($(parent.document.body))
883
                    .submit();
884
                return;
×
885
            }
886
            try {
×
887
                window.top.CMS.API.Toolbar.showLoader();
×
888
            } catch (err) {}
889

890
            $.ajax({
×
891
                method: 'post',
892
                url: $(this).attr('href')
893
            })
894
                .done(function() {
895
                    try {
×
896
                        window.top.CMS.API.Toolbar.hideLoader();
×
897
                    } catch (err) {}
898

899
                    if (window.self === window.top) {
×
900
                        // simply reload the page
901
                        that._reloadHelper();
×
902
                    } else {
903
                        Helpers.reloadBrowser('REFRESH_PAGE');
×
904
                    }
905
                })
906
                .fail(function(error) {
907
                    try {
×
908
                        window.top.CMS.API.Toolbar.hideLoader();
×
909
                    } catch (err) {}
910
                    that.showError(error.responseText ? error.responseText : error.statusText);
×
911
                });
912
        });
913
    },
914

915
    /**
916
     * Sets events for the search on the header.
917
     *
918
     * @method _setupSearch
919
     * @private
920
     */
921
    _setupSearch: function _setupSearch() {
922
        var that = this;
21✔
923
        var click = this.click + '.search';
21✔
924

925
        var filterActive = false;
21✔
926
        var filterTrigger = this.ui.container.find('.js-cms-pagetree-header-filter-trigger');
21✔
927
        var filterContainer = this.ui.container.find('.js-cms-pagetree-header-filter-container');
21✔
928
        var filterClose = filterContainer.find('.js-cms-pagetree-header-search-close');
21✔
929
        var filterClass = 'cms-pagetree-header-filter-active';
21✔
930
        var pageTreeHeader = $('.cms-pagetree-header');
21✔
931

932
        var visibleForm = this.ui.container.find('.js-cms-pagetree-header-search');
21✔
933
        var hiddenForm = this.ui.container.find('.js-cms-pagetree-header-search-copy form');
21✔
934

935
        var searchContainer = this.ui.container.find('.cms-pagetree-header-filter');
21✔
936
        var searchField = searchContainer.find('#field-searchbar');
21✔
937
        var timeout = 200;
21✔
938

939
        // add active class when focusing the search field
940
        searchField.on('focus', function(e) {
21✔
941
            e.stopImmediatePropagation();
×
942
            pageTreeHeader.addClass(filterClass);
×
943
        });
944
        searchField.on('blur', function(e) {
21✔
945
            e.stopImmediatePropagation();
×
946
            // timeout is required to prevent the search field from jumping
947
            // between enlarging and shrinking
948
            setTimeout(function() {
×
949
                if (!filterActive) {
×
950
                    pageTreeHeader.removeClass(filterClass);
×
951
                }
952
            }, timeout);
953
            that.ui.document.off(click);
×
954
        });
955

956
        // shows/hides filter box
957
        filterTrigger.add(filterClose).on(click, function(e) {
21✔
958
            e.preventDefault();
×
959
            e.stopImmediatePropagation();
×
960
            if (filterActive) {
×
961
                filterContainer.hide();
×
962
                pageTreeHeader.removeClass(filterClass);
×
963
                that.ui.document.off(click);
×
964
                filterActive = false;
×
965
            } else {
966
                filterContainer.show();
×
967
                pageTreeHeader.addClass(filterClass);
×
968
                that.ui.document.on(click, function() {
×
969
                    filterActive = true;
×
970
                    filterTrigger.trigger(click);
×
971
                });
972
                filterActive = true;
×
973
            }
974
        });
975

976
        // prevent closing when on filter container
977
        filterContainer.on('click', function(e) {
21✔
978
            e.stopImmediatePropagation();
×
979
        });
980

981
        // add hidden fields to the form to maintain filter params
982
        visibleForm.append(hiddenForm.find('input[type="hidden"]'));
21✔
983
    },
984

985
    /**
986
     * Shows paste helpers.
987
     *
988
     * @method _enablePaste
989
     * @param {String} [selector=this.options.pasteSelector] jquery selector
990
     * @private
991
     */
992
    _enablePaste: function _enablePaste(selector) {
993
        var sel = typeof selector === 'undefined'
2✔
994
            ? this.options.pasteSelector
995
            : selector + ' ' + this.options.pasteSelector;
996
        var dropdownSel = '.js-cms-pagetree-actions-dropdown';
2✔
997

998
        if (typeof selector !== 'undefined') {
2✔
999
            dropdownSel = selector + ' .js-cms-pagetree-actions-dropdown';
1✔
1000
        }
1001

1002
        // helpers are generated on the fly, so we need to reference
1003
        // them every single time
1004
        $(sel).removeClass('cms-pagetree-dropdown-item-disabled');
2✔
1005

1006
        var data = {};
2✔
1007

1008
        if (this.clipboard.type === 'cut') {
2!
1009
            data.has_cut = true;
×
1010
        } else {
1011
            data.has_copy = true;
2✔
1012
        }
1013
        // not loaded actions dropdown have to be updated as well
1014
        $(dropdownSel).data('lazyUrlData', data);
2✔
1015
    },
1016

1017
    /**
1018
     * Hides paste helpers.
1019
     *
1020
     * @method _disablePaste
1021
     * @param {String} [selector=this.options.pasteSelector] jquery selector
1022
     * @private
1023
     */
1024
    _disablePaste: function _disablePaste(selector) {
1025
        var sel = typeof selector === 'undefined'
2✔
1026
            ? this.options.pasteSelector
1027
            : selector + ' ' + this.options.pasteSelector;
1028
        var dropdownSel = '.js-cms-pagetree-actions-dropdown';
2✔
1029

1030
        if (typeof selector !== 'undefined') {
2✔
1031
            dropdownSel = selector + ' .js-cms-pagetree-actions-dropdown';
1✔
1032
        }
1033

1034
        // helpers are generated on the fly, so we need to reference
1035
        // them every single time
1036
        $(sel).addClass('cms-pagetree-dropdown-item-disabled');
2✔
1037

1038
        // not loaded actions dropdown have to be updated as well
1039
        $(dropdownSel).removeData('lazyUrlData');
2✔
1040
    },
1041

1042
    /**
1043
     * Updates the current state of the helpers after `after_open.jstree`
1044
     * or `_cutOrCopy` is triggered.
1045
     *
1046
     * @method _updatePasteHelpersState
1047
     * @private
1048
     */
1049
    _updatePasteHelpersState: function _updatePasteHelpersState() {
1050
        var that = this;
4✔
1051

1052
        if (this.clipboard.type && this.clipboard.id) {
4✔
1053
            this._enablePaste();
3✔
1054
        }
1055

1056
        // hide cut element and it's descendants' paste helpers if it is visible
1057
        if (
4✔
1058
            this.clipboard.type === 'cut' &&
8✔
1059
            this.clipboard.origin &&
1060
            this.options.site === this.clipboard.source_site
1061
        ) {
1062
            var descendantIds = this._getDescendantsIds(this.clipboard.id);
2✔
1063
            var nodes = [this.clipboard.id];
2✔
1064

1065
            if (descendantIds && descendantIds.length) {
2✔
1066
                nodes = nodes.concat(descendantIds);
1✔
1067
            }
1068

1069
            nodes.forEach(function(id) {
2✔
1070
                that._disablePaste('.jsgrid_' + id + '_col');
4✔
1071
            });
1072
        }
1073
    },
1074

1075
    /**
1076
     * Shows success message on node after successful action.
1077
     *
1078
     * @method _showSuccess
1079
     * @param {Number} id id of the element to add the success class
1080
     * @private
1081
     */
1082
    _showSuccess: function _showSuccess(id) {
1083
        var element = this.ui.tree.find('li[data-id="' + id + '"]');
×
1084

1085
        element.addClass('cms-tree-node-success');
×
1086
        setTimeout(function() {
×
1087
            element.removeClass('cms-tree-node-success');
×
1088
        }, this.successTimer);
1089
        // hide elements
1090
        this._disablePaste();
×
1091
        this.clipboard.id = null;
×
1092
    },
1093

1094
    /**
1095
     * Checks if we should reload the iframe or entire window. For this we
1096
     * need to skip `CMS.API.Helpers.reloadBrowser();`.
1097
     *
1098
     * @method _reloadHelper
1099
     * @private
1100
     */
1101
    _reloadHelper: function _reloadHelper() {
1102
        if (window.self === window.top) {
×
1103
            Helpers.reloadBrowser();
×
1104
        } else {
1105
            window.location.reload();
×
1106
        }
1107
    },
1108

1109
    /**
1110
     * Displays an error within the django UI.
1111
     *
1112
     * @method showError
1113
     * @param {String} message string message to display
1114
     */
1115
    showError: function showError(message) {
1116
        var messages = $('.messagelist');
×
1117
        var breadcrumb = $('.breadcrumbs');
×
1118
        var reload = this.options.lang.reload;
×
1119
        var tpl =
1120
            '' +
×
1121
            '<ul class="messagelist">' +
1122
            '   <li class="error">' +
1123
            '       {msg} ' +
1124
            '       <a href="#reload" class="cms-tree-reload"> ' +
1125
            reload +
1126
            ' </a>' +
1127
            '   </li>' +
1128
            '</ul>';
1129
        var msg = tpl.replace('{msg}', '<strong>' + this.options.lang.error + '</strong> ' + message);
×
1130

1131
        if (messages.length) {
×
1132
            messages.replaceWith(msg);
×
1133
        } else {
1134
            breadcrumb.after(msg);
×
1135
        }
1136
    },
1137

1138
    /**
1139
     * @method _getDescendantsIds
1140
     * @private
1141
     * @param {String} nodeId jstree id of the node, e.g. j1_3
1142
     * @returns {String[]} array of ids
1143
     */
1144
    _getDescendantsIds: function _getDescendantsIds(nodeId) {
1145
        return this.ui.tree.jstree(true).get_node(nodeId).children_d;
2✔
1146
    },
1147

1148
    /**
1149
     * @method _hasPermision
1150
     * @private
1151
     * @param {Object} node jstree node
1152
     * @param {String} permission move / add
1153
     * @returns {Boolean}
1154
     */
1155
    _hasPermission: function _hasPermision(node, permission) {
1156
        if (node.id === '#' && permission === 'add') {
×
1157
            return this.options.hasAddRootPermission;
×
1158
        } else if (node.id === '#') {
×
1159
            return false;
×
1160
        }
1161

1162
        return node.li_attr['data-' + permission + '-permission'] === 'true';
×
1163
    }
1164
});
1165

1166
PageTree._init = function() {
1✔
1167
    new PageTree();
1✔
1168
};
1169

1170
// shorthand for jQuery(document).ready();
1171
$(function() {
1✔
1172
    // load cms settings beforehand
1173
    // have to set toolbar to "expanded" by default
1174
    // otherwise initialization will be incorrect when you
1175
    // go first to pages and then to normal page
1176
    window.CMS.config = {
1✔
1177
        isPageTree: true,
1178
        settings: {
1179
            toolbar: 'expanded',
1180
            version: __CMS_VERSION__
1181
        },
1182
        urls: {
1183
            settings: $('.js-cms-pagetree').data('settings-url')
1184
        }
1185
    };
1186
    window.CMS.settings = Helpers.getSettings();
1✔
1187
    // autoload the pagetree
1188
    CMS.PageTree._init();
1✔
1189
});
1190

1191
export default PageTree;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc