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

divio / django-cms / #30167

24 Nov 2025 12:49PM UTC coverage: 89.964% (+14.8%) from 75.132%
#30167

push

travis-ci

web-flow
Merge 565a22220 into 5f080488d

1337 of 2146 branches covered (62.3%)

9206 of 10233 relevant lines covered (89.96%)

11.2 hits per line

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

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

5
import $ from 'jquery';
6

7
import { Helpers, KEYS } from './cms.base';
8
import PageTreeDropdowns from './cms.pagetree.dropdown';
9
import PageTreeStickyHeader from './cms.pagetree.stickyheader';
10
// switched from commonjs 'lodash' bundle to per-method ESM imports for better tree-shaking
11
import debounce from 'lodash-es/debounce.js';
12
import without from 'lodash-es/without.js';
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
class PageTree {
25
    constructor(options) {
26
        // options are loaded from the pagetree html node
27
        var opts = $('.js-cms-pagetree').data('json');
21✔
28

29
        this.options = $.extend(true, {}, {
21✔
30
            pasteSelector: '.js-cms-tree-item-paste'
31
        }, opts, options);
32

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

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

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

48
        this._setupLanguages();
21✔
49

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

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

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

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

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

91
            // eslint-disable-next-line no-undef
92
            const url = new URL(window.location.href);
×
93

94
            url.searchParams.delete('language');
×
95
            url.searchParams.set('language', newLanguage);
×
96

97
            window.location.href = url.toString();
×
98
        });
99
    }
100

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

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

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

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

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

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

174
                    return obj;
20✔
175
                }
176
            };
177
        }
178

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

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

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

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

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

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

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

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

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

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

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

300
            that._dropdowns.closeAllDropdowns();
×
301

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

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

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

316
        var isCopyClassAdded = false;
21✔
317

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

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

334
            // styling the #jstree-marker dynamically on dnd_move.vakata
335
            // because jsTree doesn't support RTL on this specific case
336
            // and sets the 'left' property without checking document direction
337
            var ins = $.jstree.reference(data.event.target);
×
338

339
            // make sure we're hovering over a tree node
340
            if (ins) {
×
341
                var marker = $('#jstree-marker');
×
342
                var root = $('#changelist');
×
343
                var column = $(data.data.origin.element);
×
344

345
                var hover = ins.settings.dnd.large_drop_target ?
×
346
                    $(data.event.target)
347
                        .closest('.jstree-node') :
348
                    $(data.event.target)
349
                        .closest('.jstree-anchor').parent();
350

351
                var width = root.width() - (column.width() - hover.width());
×
352

353
                marker.css({
×
354
                    left: `${root.offset().left}px`,
355
                    width: `${width}px`
356
                });
357
            }
358
        });
359

360
        this.ui.document.on('dnd_stop.vakata', function(e, data) {
21✔
361
            var element = $(data.element);
×
362
            var node = element.parent();
×
363

364
            node.removeClass('jstree-is-dragging jstree-is-dragging-copy');
×
365
            data.data.nodes.forEach(function(nodeId) {
×
366
                var descendantIds = that._getDescendantsIds(nodeId);
×
367

368
                [nodeId].concat(descendantIds).forEach(function(id) {
×
369
                    $('.jsgrid_' + id + '_col').removeClass('jstree-is-dragging jstree-is-dragging-copy');
×
370
                });
371
            });
372
        });
373

374
        // store moved position node
375
        this.ui.tree.on('move_node.jstree copy_node.jstree', function(e, obj) {
21✔
376
            if ((!that.clipboard.type && e.type !== 'copy_node') || that.clipboard.type === 'cut') {
×
377
                that._moveNode(that._getNodePosition(obj)).done(function() {
×
378
                    var instance = that.ui.tree.jstree(true);
×
379

380
                    instance._hide_grid(instance.get_node(obj.parent));
×
381
                    if (obj.parent === '#' || (obj.node && obj.node.data && obj.node.data.isHome)) {
×
382
                        instance.refresh();
×
383
                    } else {
384
                        // have to refresh parent, because refresh only
385
                        // refreshes children of the node, never the node itself
386
                        instance.refresh_node(obj.parent);
×
387
                    }
388
                });
389
            } else {
390
                that._copyNode(obj);
×
391
            }
392
            // we need to open the parent node if we trigger an element
393
            // if not already opened
394
            that.ui.tree.jstree('open_node', obj.parent);
×
395
        });
396

397
        // set event for cut and paste
398
        this.ui.container.on(this.click, '.js-cms-tree-item-cut', function(e) {
21✔
399
            e.preventDefault();
×
400
            that._cutOrCopy({ type: 'cut', element: $(this) });
×
401
        });
402

403
        // set event for cut and paste
404
        this.ui.container.on(this.click, '.js-cms-tree-item-copy', function(e) {
21✔
405
            e.preventDefault();
×
406
            that._cutOrCopy({ type: 'copy', element: $(this) });
×
407
        });
408

409
        // attach events to paste
410
        this.ui.container.on(this.click, this.options.pasteSelector, function(e) {
21✔
411
            e.preventDefault();
×
412
            if ($(this).hasClass('cms-pagetree-dropdown-item-disabled')) {
×
413
                return;
×
414
            }
415
            that._paste(e);
×
416
        });
417

418
        // advanced settings link handling
419
        this.ui.container.on(this.click, '.js-cms-tree-advanced-settings', function(e) {
21✔
420
            if (e.shiftKey) {
×
421
                e.preventDefault();
×
422
                var link = $(this);
×
423

424
                if (link.data('url')) {
×
425
                    window.location.href = link.data('url');
×
426
                }
427
            }
428
        });
429

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

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

436
            this._storeNodeId(nodeData.data.id);
×
437
        });
438

439
        // add events for error reload (messagelist)
440
        this.ui.document.on(this.click, '.messagelist .cms-tree-reload', function(e) {
21✔
441
            e.preventDefault();
×
442
            that._reloadHelper();
×
443
        });
444

445

446
        // additional event handlers
447
        this._setupDropdowns();
21✔
448
        this._setupSearch();
21✔
449

450
        // make sure ajax post requests are working
451
        this._setAjaxPost('.js-cms-tree-item-menu a');
21✔
452
        this._setAjaxPost('.js-cms-tree-lang-trigger');
21✔
453
        this._setAjaxPost('.js-cms-tree-item-set-home a');
21✔
454

455
        this._setupPageView();
21✔
456
        this._setupStickyHeader();
21✔
457

458
        this.ui.tree.on('ready.jstree', () => this._getClipboard());
21✔
459
    }
460

461
    _getClipboard() {
462
        this.clipboard = CMS.settings.pageClipboard || this.clipboard;
1✔
463

464
        if (this.clipboard.type && this.clipboard.origin) {
1!
465
            this._enablePaste();
×
466
            this._updatePasteHelpersState();
×
467
        }
468
    }
469

470
    /**
471
     * Helper to process the cut and copy events.
472
     *
473
     * @method _cutOrCopy
474
     * @param {Object} [obj]
475
     * @param {Number} [obj.type] either 'cut' or 'copy'
476
     * @param {Number} [obj.element] originated trigger element
477
     * @private
478
     * @returns {Boolean|void}
479
     */
480
    _cutOrCopy(obj) {
481
        // prevent actions if you try to copy a page with an apphook
482
        if (obj.type === 'copy' && obj.element.data().apphook) {
×
483
            this.showError(this.options.lang.apphook);
×
484
            return false;
×
485
        }
486

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

489
        // resets if we click again
490
        if (this.clipboard.type === obj.type && jsTreeId === this.clipboard.id) {
×
491
            this.clipboard.type = null;
×
492
            this.clipboard.id = null;
×
493
            this.clipboard.origin = null;
×
494
            this.clipboard.source_site = null;
×
495
            this._disablePaste();
×
496
        } else {
497
            this.clipboard.origin = obj.element.data().id; // this._getNodeId(obj.element);
×
498
            this.clipboard.type = obj.type;
×
499
            this.clipboard.id = jsTreeId;
×
500
            this.clipboard.source_site = this.options.site;
×
501
            this._updatePasteHelpersState();
×
502
        }
503
        if (this.clipboard.type === 'copy' || !this.clipboard.type) {
×
504
            CMS.settings.pageClipboard = this.clipboard;
×
505
            Helpers.setSettings(CMS.settings);
×
506
        }
507
    }
508

509
    /**
510
     * Helper to process the paste event.
511
     *
512
     * @method _paste
513
     * @param {$.Event} event click event
514
     * @private
515
     */
516
    _paste(event) {
517
        // hide helpers after we picked one
518
        this._disablePaste();
5✔
519

520
        var copyFromId = this._getNodeId(
5✔
521
            $(`.js-cms-pagetree-options[data-id="${this.clipboard.origin}"]`).closest('.jstree-grid-cell')
522
        );
523
        var copyToId = this._getNodeId($(event.currentTarget));
5✔
524

525
        if (this.clipboard.source_site === this.options.site) {
5!
526
            if (this.clipboard.type === 'cut') {
×
527
                this.ui.tree.jstree('cut', copyFromId);
×
528
            } else {
529
                this.ui.tree.jstree('copy', copyFromId);
×
530
            }
531

532
            this.clipboard.isPasting = true;
×
533
            this.ui.tree.jstree('paste', copyToId, 'last');
×
534
        } else {
535
            const dummyId = this.ui.tree.jstree('create_node', copyToId, 'Loading', 'last');
5✔
536

537
            if (this.ui.tree.length) {
5!
538
                this.ui.tree.jstree('cut', dummyId);
5✔
539
                this.clipboard.isPasting = true;
5✔
540
                this.ui.tree.jstree('paste', copyToId, 'last');
5✔
541
            } else {
542
                if (this.clipboard.type === 'copy') {
×
543
                    this._copyNode();
×
544
                }
545
                if (this.clipboard.type === 'cut') {
×
546
                    this._moveNode();
×
547
                }
548
            }
549
        }
550

551
        this.clipboard.id = null;
5✔
552
        this.clipboard.type = null;
5✔
553
        this.clipboard.origin = null;
5✔
554
        this.clipboard.isPasting = false;
5✔
555
        CMS.settings.pageClipboard = this.clipboard;
5✔
556
        Helpers.setSettings(CMS.settings);
5✔
557
    }
558

559
    /**
560
     * Retreives a list of nodes from local storage.
561
     *
562
     * @method _getStoredNodeIds
563
     * @private
564
     * @returns {Array} list of ids
565
     */
566
    _getStoredNodeIds() {
567
        return CMS.settings.pagetree || [];
20✔
568
    }
569

570
    /**
571
     * Stores a node in local storage.
572
     *
573
     * @method _storeNodeId
574
     * @private
575
     * @param {String} id to be stored
576
     * @returns {String} id that has been stored
577
     */
578
    _storeNodeId(id) {
579
        var number = id;
×
580
        var storage = this._getStoredNodeIds();
×
581

582
        // store value only if it isn't there yet
583
        if (storage.indexOf(number) === -1) {
×
584
            storage.push(number);
×
585
        }
586

587
        CMS.settings.pagetree = storage;
×
588
        Helpers.setSettings(CMS.settings);
×
589

590
        return number;
×
591
    }
592

593
    /**
594
     * Removes a node in local storage.
595
     *
596
     * @method _removeNodeId
597
     * @private
598
     * @param {String} id to be stored
599
     * @returns {String} id that has been removed
600
     */
601
    _removeNodeId(id) {
602
        const instance = this.ui.tree.jstree(true);
×
603
        const childrenIds = instance.get_node({
×
604
            id: CMS.$(`[data-node-id=${id}]`).attr('id')
605
        }).children_d;
606

607
        const idsToRemove = [id].concat(
×
608
            childrenIds.map(childId => {
609
                const node = instance.get_node({ id: childId });
×
610

611
                if (!node || !node.data) {
×
612
                    return node;
×
613
                }
614

615
                return node.data.nodeId;
×
616
            })
617
        );
618

619
        const storage = without(this._getStoredNodeIds(), ...idsToRemove);
×
620

621
        CMS.settings.pagetree = storage;
×
622
        Helpers.setSettings(CMS.settings);
×
623

624
        return id;
×
625
    }
626

627
    /**
628
     * Moves a node after drag & drop.
629
     *
630
     * @method _moveNode
631
     * @param {Object} [obj]
632
     * @param {Number} [obj.id] current element id for url matching
633
     * @param {Number} [obj.target] target sibling or parent
634
     * @param {Number} [obj.position] either `left`, `right` or `last-child`
635
     * @returns {$.Deferred} ajax request object
636
     * @private
637
     */
638
    _moveNode(obj) {
639
        var that = this;
×
640

641
        if (!obj.id && this.clipboard.type === 'cut' && this.clipboard.origin) {
×
642
            obj.id = this.clipboard.origin;
×
643
            obj.source_site = this.clipboard.source_site;
×
644
        } else {
645
            obj.site = that.options.site;
×
646
        }
647

648
        return $.ajax({
×
649
            method: 'post',
650
            url: that.options.urls.move.replace('{id}', obj.id),
651
            data: obj
652
        })
653
            .done(function(r) {
654
                if (r.status && r.status === 400) { // eslint-disable-line
×
655
                    that.showError(r.content);
×
656
                } else {
657
                    that._showSuccess(obj.id);
×
658
                }
659
            })
660
            .fail(function(error) {
661
                that.showError(error.statusText);
×
662
            });
663
    }
664

665
    /**
666
     * Copies a node into the selected node.
667
     *
668
     * @method _copyNode
669
     * @param {Object} obj page obj
670
     * @private
671
     */
672
    _copyNode(obj) {
673
        var that = this;
×
674
        var node = { position: 0 };
×
675

676
        if (obj) {
×
677
            node = that._getNodePosition(obj);
×
678
        }
679

680
        var data = {
×
681
            // obj.original.data.id is for drag copy
682
            id: this.clipboard.origin || obj.original.data.id,
×
683
            position: node.position
684
        };
685

686
        if (this.clipboard.source_site) {
×
687
            data.source_site = this.clipboard.source_site;
×
688
        } else {
689
            data.source_site = this.options.site;
×
690
        }
691

692
        // if there is no target provided, the node lands in root
693
        if (node.target) {
×
694
            data.target = node.target;
×
695
        }
696

697
        if (that.options.permission) {
×
698
            // we need to load a dialog first, to check if permissions should
699
            // be copied or not
700
            $.ajax({
×
701
                method: 'post',
702
                url: that.options.urls.copyPermission.replace('{id}', data.id),
703
                data: data
704
                // the dialog is loaded via the ajax respons originating from
705
                // `templates/admin/cms/page/tree/copy_premissions.html`
706
            })
707
                .done(function(dialog) {
708
                    that.ui.dialog.append(dialog);
×
709
                })
710
                .fail(function(error) {
711
                    that.showError(error.statusText);
×
712
                });
713

714
            // attach events to the permission dialog
715
            this.ui.dialog
×
716
                .off(this.click, '.cancel')
717
                .on(this.click, '.cancel', function(e) {
718
                    e.preventDefault();
×
719
                    // remove just copied node
720
                    that.ui.tree.jstree('delete_node', obj.node.id);
×
721
                    $('.js-cms-dialog').remove();
×
722
                    $('.js-cms-dialog-dimmer').remove();
×
723
                })
724
                .off(this.click, '.submit')
725
                .on(this.click, '.submit', function(e) {
726
                    e.preventDefault();
×
727
                    var submitButton = $(this);
×
728
                    var formData = submitButton.closest('form').serialize().split('&');
×
729

730
                    submitButton.prop('disabled', true);
×
731

732
                    // loop through form data and attach to obj
733
                    for (var i = 0; i < formData.length; i++) {
×
734
                        data[formData[i].split('=')[0]] = formData[i].split('=')[1];
×
735
                    }
736

737
                    that._saveCopiedNode(data);
×
738
                });
739
        } else {
740
            this._saveCopiedNode(data);
×
741
        }
742
    }
743

744
    /**
745
     * Sends the request to copy a node.
746
     *
747
     * @method _saveCopiedNode
748
     * @private
749
     * @param {Object} data node position information
750
     * @returns {$.Deferred}
751
     */
752
    _saveCopiedNode(data) {
753
        var that = this;
×
754

755
        // send the real ajax request for copying the plugin
756
        return $.ajax({
×
757
            method: 'post',
758
            url: that.options.urls.copy.replace('{id}', data.id),
759
            data: data
760
        })
761
            .done(function(r) {
762
                if (r.status && r.status === 400) { // eslint-disable-line
×
763
                    that.showError(r.content);
×
764
                } else {
765
                    that._reloadHelper();
×
766
                }
767
            })
768
            .fail(function(error) {
769
                that.showError(error.statusText);
×
770
            });
771
    }
772

773
    /**
774
     * Returns element from any sub nodes.
775
     *
776
     * @method _getElement
777
     * @private
778
     * @param {jQuery} el jQuery node form where to search
779
     * @returns {String} jsTree node element id
780
     */
781
    _getNodeId(el) {
782
        var cls = el.closest('.jstree-grid-cell').attr('class');
2✔
783

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

788
    /**
789
     * Gets the new node position after moving.
790
     *
791
     * @method _getNodePosition
792
     * @private
793
     * @param {Object} obj jstree move object
794
     * @returns {Object} evaluated object with params
795
     */
796
    _getNodePosition(obj) {
797
        var data = {};
×
798
        var node = this.ui.tree.jstree('get_node', obj.node.parent);
×
799

800
        data.position = obj.position;
×
801

802
        // jstree indicates no parent with `#`, in this case we do not
803
        // need to set the target attribute at all
804
        if (obj.parent !== '#') {
×
805
            data.target = node.data.id;
×
806
        }
807

808
        // some functions like copy create a new element with a new id,
809
        // in this case we need to set `data.id` manually
810
        if (obj.node && obj.node.data) {
×
811
            data.id = obj.node.data.id;
×
812
        }
813

814
        return data;
×
815
    }
816

817
    /**
818
     * Sets up general tooltips that can have a list of links or content.
819
     *
820
     * @method _setupDropdowns
821
     * @private
822
     */
823
    _setupDropdowns() {
824
        this._dropdowns = new PageTreeDropdowns({
21✔
825
            container: this.ui.container
826
        });
827
    }
828

829
    /**
830
     * Handles page view click. Usual use case is that after you click
831
     * on view page in the pagetree - sideframe is no longer needed,
832
     * so we close it.
833
     *
834
     * @method _setupPageView
835
     * @private
836
     */
837
    _setupPageView() {
838
        var win = Helpers._getWindow();
25✔
839
        var parent = win.parent ? win.parent : win;
25✔
840

841
        this.ui.container.on(this.click, '.js-cms-pagetree-page-view', function() {
25✔
842
            parent.CMS.API.Helpers.setSettings(
3✔
843
                $.extend(true, {}, CMS.settings, {
844
                    sideframe: {
845
                        url: null,
846
                        hidden: true
847
                    }
848
                })
849
            );
850
        });
851
    }
852

853
    /**
854
     * @method _setupStickyHeader
855
     * @private
856
     */
857
    _setupStickyHeader() {
858
        var that = this;
21✔
859

860
        that.ui.tree.on('ready.jstree', function() {
21✔
861
            that.header = new PageTreeStickyHeader({
×
862
                container: that.ui.container
863
            });
864
        });
865
    }
866

867
    /**
868
     * Triggers the links `href` as ajax post request.
869
     *
870
     * @method _setAjaxPost
871
     * @private
872
     * @param {jQuery} trigger jQuery link target
873
     */
874
    _setAjaxPost(trigger) {
875
        var that = this;
63✔
876

877
        this.ui.container.on(this.click, trigger, function(e) {
63✔
878
            e.preventDefault();
×
879

880
            var element = $(this);
×
881

882
            if (element.closest('.cms-pagetree-dropdown-item-disabled').length) {
×
883
                return;
×
884
            }
885
            if (element.attr('target') === '_top') {
×
886
                // Post to target="_top" requires to create a form and submit it
887
                var parent = window;
×
888

889
                if (window.parent) {
×
890
                    parent = window.parent;
×
891
                }
892
                let formToken = document.querySelector('form input[name="csrfmiddlewaretoken"]');
×
893
                let csrfToken = '<input type="hidden" name="csrfmiddlewaretoken" value="' +
×
894
                    ((formToken ? formToken.value : formToken) || window.CMS.config.csrf) + '">';
×
895

896
                $('<form method="post" action="' + element.attr('href') + '">' +
×
897
                    csrfToken + '</form>')
898
                    .appendTo($(parent.document.body))
899
                    .submit();
900
                return;
×
901
            }
902
            try {
×
903
                window.top.CMS.API.Toolbar.showLoader();
×
904
            } catch {}
905

906
            $.ajax({
×
907
                method: 'post',
908
                url: $(this).attr('href')
909
            })
910
                .done(function() {
911
                    try {
×
912
                        window.top.CMS.API.Toolbar.hideLoader();
×
913
                    } catch {}
914

915
                    if (window.self === window.top) {
×
916
                        // simply reload the page
917
                        that._reloadHelper();
×
918
                    } else {
919
                        Helpers.reloadBrowser('REFRESH_PAGE');
×
920
                    }
921
                })
922
                .fail(function(error) {
923
                    try {
×
924
                        window.top.CMS.API.Toolbar.hideLoader();
×
925
                    } catch {}
926
                    that.showError(error.responseText ? error.responseText : error.statusText);
×
927
                });
928
        });
929
    }
930

931
    /**
932
     * Sets events for the search on the header.
933
     *
934
     * @method _setupSearch
935
     * @private
936
     */
937
    _setupSearch() {
938
        var that = this;
21✔
939
        var click = this.click + '.search';
21✔
940

941
        var filterActive = false;
21✔
942
        var filterTrigger = this.ui.container.find('.js-cms-pagetree-header-filter-trigger');
21✔
943
        var filterContainer = this.ui.container.find('.js-cms-pagetree-header-filter-container');
21✔
944
        var filterClose = filterContainer.find('.js-cms-pagetree-header-search-close');
21✔
945
        var filterClass = 'cms-pagetree-header-filter-active';
21✔
946
        var pageTreeHeader = $('.cms-pagetree-header');
21✔
947

948
        var visibleForm = this.ui.container.find('.js-cms-pagetree-header-search');
21✔
949
        var hiddenForm = this.ui.container.find('.js-cms-pagetree-header-search-copy form');
21✔
950

951
        var searchContainer = this.ui.container.find('.cms-pagetree-header-filter');
21✔
952
        var searchField = searchContainer.find('#field-searchbar');
21✔
953
        var timeout = 200;
21✔
954

955
        // add active class when focusing the search field
956
        searchField.on('focus', function(e) {
21✔
957
            e.stopImmediatePropagation();
×
958
            pageTreeHeader.addClass(filterClass);
×
959
        });
960
        searchField.on('blur', function(e) {
21✔
961
            e.stopImmediatePropagation();
×
962
            // timeout is required to prevent the search field from jumping
963
            // between enlarging and shrinking
964
            setTimeout(function() {
×
965
                if (!filterActive) {
×
966
                    pageTreeHeader.removeClass(filterClass);
×
967
                }
968
            }, timeout);
969
            that.ui.document.off(click);
×
970
        });
971

972
        // shows/hides filter box
973
        filterTrigger.add(filterClose).on(click, function(e) {
21✔
974
            e.preventDefault();
×
975
            e.stopImmediatePropagation();
×
976
            if (filterActive) {
×
977
                filterContainer.hide();
×
978
                pageTreeHeader.removeClass(filterClass);
×
979
                that.ui.document.off(click);
×
980
                filterActive = false;
×
981
            } else {
982
                filterContainer.show();
×
983
                pageTreeHeader.addClass(filterClass);
×
984
                that.ui.document.on(click, function() {
×
985
                    filterActive = true;
×
986
                    filterTrigger.trigger(click);
×
987
                });
988
                filterActive = true;
×
989
            }
990
        });
991

992
        // prevent closing when on filter container
993
        filterContainer.on('click', function(e) {
21✔
994
            e.stopImmediatePropagation();
×
995
        });
996

997
        // add hidden fields to the form to maintain filter params
998
        visibleForm.append(hiddenForm.find('input[type="hidden"]'));
21✔
999
    }
1000

1001
    /**
1002
     * Shows paste helpers.
1003
     *
1004
     * @method _enablePaste
1005
     * @param {String} [selector=this.options.pasteSelector] jquery selector
1006
     * @private
1007
     */
1008
    _enablePaste(selector) {
1009
        var sel = typeof selector === 'undefined'
2✔
1010
            ? this.options.pasteSelector
1011
            : selector + ' ' + this.options.pasteSelector;
1012
        var dropdownSel = '.js-cms-pagetree-actions-dropdown';
2✔
1013

1014
        if (typeof selector !== 'undefined') {
2✔
1015
            dropdownSel = selector + ' .js-cms-pagetree-actions-dropdown';
1✔
1016
        }
1017

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

1022
        var data = {};
2✔
1023

1024
        if (this.clipboard.type === 'cut') {
2!
1025
            data.has_cut = true;
×
1026
        } else {
1027
            data.has_copy = true;
2✔
1028
        }
1029
        // not loaded actions dropdown have to be updated as well
1030
        $(dropdownSel).data('lazyUrlData', data);
2✔
1031
    }
1032

1033
    /**
1034
     * Hides paste helpers.
1035
     *
1036
     * @method _disablePaste
1037
     * @param {String} [selector=this.options.pasteSelector] jquery selector
1038
     * @private
1039
     */
1040
    _disablePaste(selector) {
1041
        var sel = typeof selector === 'undefined'
2✔
1042
            ? this.options.pasteSelector
1043
            : selector + ' ' + this.options.pasteSelector;
1044
        var dropdownSel = '.js-cms-pagetree-actions-dropdown';
2✔
1045

1046
        if (typeof selector !== 'undefined') {
2✔
1047
            dropdownSel = selector + ' .js-cms-pagetree-actions-dropdown';
1✔
1048
        }
1049

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

1054
        // not loaded actions dropdown have to be updated as well
1055
        $(dropdownSel).removeData('lazyUrlData');
2✔
1056
    }
1057

1058
    /**
1059
     * Updates the current state of the helpers after `after_open.jstree`
1060
     * or `_cutOrCopy` is triggered.
1061
     *
1062
     * @method _updatePasteHelpersState
1063
     * @private
1064
     */
1065
    _updatePasteHelpersState() {
1066
        var that = this;
4✔
1067

1068
        if (this.clipboard.type && this.clipboard.id) {
4✔
1069
            this._enablePaste();
3✔
1070
        }
1071

1072
        // hide cut element and it's descendants' paste helpers if it is visible
1073
        if (
4✔
1074
            this.clipboard.type === 'cut' &&
8✔
1075
            this.clipboard.origin &&
1076
            this.options.site === this.clipboard.source_site
1077
        ) {
1078
            var descendantIds = this._getDescendantsIds(this.clipboard.id);
2✔
1079
            var nodes = [this.clipboard.id];
2✔
1080

1081
            if (descendantIds && descendantIds.length) {
2✔
1082
                nodes = nodes.concat(descendantIds);
1✔
1083
            }
1084

1085
            nodes.forEach(function(id) {
2✔
1086
                that._disablePaste('.jsgrid_' + id + '_col');
4✔
1087
            });
1088
        }
1089
    }
1090

1091
    /**
1092
     * Shows success message on node after successful action.
1093
     *
1094
     * @method _showSuccess
1095
     * @param {Number} id id of the element to add the success class
1096
     * @private
1097
     */
1098
    _showSuccess(id) {
1099
        var element = this.ui.tree.find('li[data-id="' + id + '"]');
×
1100

1101
        element.addClass('cms-tree-node-success');
×
1102
        setTimeout(function() {
×
1103
            element.removeClass('cms-tree-node-success');
×
1104
        }, this.successTimer);
1105
        // hide elements
1106
        this._disablePaste();
×
1107
        this.clipboard.id = null;
×
1108
    }
1109

1110
    /**
1111
     * Checks if we should reload the iframe or entire window. For this we
1112
     * need to skip `CMS.API.Helpers.reloadBrowser();`.
1113
     *
1114
     * @method _reloadHelper
1115
     * @private
1116
     */
1117
    _reloadHelper() {
1118
        if (window.self === window.top) {
×
1119
            Helpers.reloadBrowser();
×
1120
        } else {
1121
            window.location.reload();
×
1122
        }
1123
    }
1124

1125
    /**
1126
     * Displays an error within the django UI.
1127
     *
1128
     * @method showError
1129
     * @param {String} message string message to display
1130
     */
1131
    showError(message) {
1132
        var messages = $('.messagelist');
×
1133
        var breadcrumb = $('.breadcrumbs');
×
1134
        var reload = this.options.lang.reload;
×
1135
        var tpl =
1136
            '' +
×
1137
            '<ul class="messagelist">' +
1138
            '   <li class="error">' +
1139
            '       {msg} ' +
1140
            '       <a href="#reload" class="cms-tree-reload"> ' +
1141
            reload +
1142
            ' </a>' +
1143
            '   </li>' +
1144
            '</ul>';
1145
        var msg = tpl.replace('{msg}', '<strong>' + this.options.lang.error + '</strong> ' + message);
×
1146

1147
        if (messages.length) {
×
1148
            messages.replaceWith(msg);
×
1149
        } else {
1150
            breadcrumb.after(msg);
×
1151
        }
1152
    }
1153

1154
    /**
1155
     * @method _getDescendantsIds
1156
     * @private
1157
     * @param {String} nodeId jstree id of the node, e.g. j1_3
1158
     * @returns {String[]} array of ids
1159
     */
1160
    _getDescendantsIds(nodeId) {
1161
        return this.ui.tree.jstree(true).get_node(nodeId).children_d;
2✔
1162
    }
1163

1164
    /**
1165
     * @method _hasPermision
1166
     * @private
1167
     * @param {Object} node jstree node
1168
     * @param {String} permission move / add
1169
     * @returns {Boolean}
1170
     */
1171
    _hasPermission(node, permission) {
1172
        if (node.id === '#' && permission === 'add') {
×
1173
            return this.options.hasAddRootPermission;
×
1174
        } else if (node.id === '#') {
×
1175
            return false;
×
1176
        }
1177

1178
        return node.li_attr['data-' + permission + '-permission'] === 'true';
×
1179
    }
1180

1181
    static _init() {
1182
        new PageTree();
1✔
1183
    }
1184
}
1185

1186
// shorthand for jQuery(document).ready();
1187
$(function() {
1✔
1188
    // load cms settings beforehand
1189
    // have to set toolbar to "expanded" by default
1190
    // otherwise initialization will be incorrect when you
1191
    // go first to pages and then to normal page
1192
    window.CMS.config = {
1✔
1193
        isPageTree: true,
1194
        settings: {
1195
            toolbar: 'expanded',
1196
            version: __CMS_VERSION__
1197
        },
1198
        urls: {
1199
            settings: $('.js-cms-pagetree').data('settings-url')
1200
        }
1201
    };
1202
    window.CMS.settings = Helpers.getSettings();
1✔
1203
    // autoload the pagetree
1204
    CMS.PageTree._init();
1✔
1205
});
1206

1207
// Define default options on the prototype for test compatibility
1208
PageTree.prototype.options = {
1✔
1209
    pasteSelector: '.js-cms-tree-item-paste'
1210
};
1211

1212
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