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

divio / django-cms / #29891

26 Aug 2025 01:24AM UTC coverage: 75.132% (+0.07%) from 75.059%
#29891

push

travis-ci

web-flow
Merge 09573ad01 into de255061d

1079 of 1626 branches covered (66.36%)

2568 of 3418 relevant lines covered (75.13%)

26.22 hits per line

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

59.23
/cms/static/cms/js/modules/cms.plugins.js
1
/*
2
 * Copyright https://github.com/divio/django-cms
3
 */
4
import Modal from './cms.modal';
5
import StructureBoard from './cms.structureboard';
6
import $ from 'jquery';
7
import '../polyfills/array.prototype.findindex';
8
import nextUntil from './nextuntil';
9

10
import { toPairs, filter, isNaN, debounce, findIndex, find, every, uniqWith, once, difference, isEqual } from 'lodash';
11

12
import Class from 'classjs';
13
import { Helpers, KEYS, $window, $document, uid } from './cms.base';
14
import { showLoader, hideLoader } from './loader';
15
import { filter as fuzzyFilter } from 'fuzzaldrin';
16

17
var clipboardDraggable;
18
var path = window.location.pathname + window.location.search;
1✔
19

20
var pluginUsageMap = Helpers._isStorageSupported ? JSON.parse(localStorage.getItem('cms-plugin-usage') || '{}') : {};
1!
21

22
const isStructureReady = () =>
1✔
23
    CMS.config.settings.mode === 'structure' ||
×
24
    CMS.config.settings.legacy_mode ||
25
    CMS.API.StructureBoard._loadedStructure;
26
const isContentReady = () =>
1✔
27
    CMS.config.settings.mode !== 'structure' ||
×
28
    CMS.config.settings.legacy_mode ||
29
    CMS.API.StructureBoard._loadedContent;
30

31
/**
32
 * Class for handling Plugins / Placeholders or Generics.
33
 * Handles adding / moving / copying / pasting / menus etc
34
 * in structureboard.
35
 *
36
 * @class Plugin
37
 * @namespace CMS
38
 * @uses CMS.API.Helpers
39
 */
40
var Plugin = new Class({
1✔
41
    implement: [Helpers],
42

43
    options: {
44
        type: '', // bar, plugin or generic
45
        placeholder_id: null,
46
        plugin_type: '',
47
        plugin_id: null,
48
        plugin_parent: null,
49
        plugin_restriction: [],
50
        plugin_parent_restriction: [],
51
        urls: {
52
            add_plugin: '',
53
            edit_plugin: '',
54
            move_plugin: '',
55
            copy_plugin: '',
56
            delete_plugin: ''
57
        }
58
    },
59

60
    // these properties will be filled later
61
    modal: null,
62

63
    initialize: function initialize(container, options) {
64
        this.options = $.extend(true, {}, this.options, options);
179✔
65

66
        // create an unique for this component to use it internally
67
        this.uid = uid();
179✔
68

69
        this._setupUI(container);
179✔
70
        this._ensureData();
179✔
71

72
        if (this.options.type === 'plugin' && Plugin.aliasPluginDuplicatesMap[this.options.plugin_id]) {
179✔
73
            return;
1✔
74
        }
75
        if (this.options.type === 'placeholder' && Plugin.staticPlaceholderDuplicatesMap[this.options.placeholder_id]) {
178✔
76
            return;
1✔
77
        }
78

79
        // determine type of plugin
80
        switch (this.options.type) {
177✔
81
            case 'placeholder': // handler for placeholder bars
82
                Plugin.staticPlaceholderDuplicatesMap[this.options.placeholder_id] = true;
23✔
83
                this.ui.container.data('cms', this.options);
23✔
84
                this._setPlaceholder();
23✔
85
                if (isStructureReady()) {
23!
86
                    this._collapsables();
23✔
87
                }
88
                break;
23✔
89
            case 'plugin': // handler for all plugins
90
                this.ui.container.data('cms').push(this.options);
130✔
91
                Plugin.aliasPluginDuplicatesMap[this.options.plugin_id] = true;
130✔
92
                this._setPlugin();
130✔
93
                if (isStructureReady()) {
130!
94
                    this._collapsables();
130✔
95
                }
96
                break;
130✔
97
            default:
98
                // handler for static content
99
                this.ui.container.data('cms').push(this.options);
24✔
100
                this._setGeneric();
24✔
101
        }
102
    },
103

104
    _ensureData: function _ensureData() {
105
        // bind data element to the container (mutating!)
106
        if (!this.ui.container.data('cms')) {
179✔
107
            this.ui.container.data('cms', []);
174✔
108
        }
109
    },
110

111
    /**
112
     * Caches some jQuery references and sets up structure for
113
     * further initialisation.
114
     *
115
     * @method _setupUI
116
     * @private
117
     * @param {String} container `cms-plugin-${id}`
118
     */
119
    _setupUI: function setupUI(container) {
120
        const wrapper = $(`.${container}`);
179✔
121
        let contents;
122

123
        // have to check for cms-plugin, there can be a case when there are multiple
124
        // static placeholders or plugins rendered twice, there could be multiple wrappers on same page
125
        if (wrapper.length > 1 && container.match(/cms-plugin/)) {
179✔
126
            // Get array [[start, end], [start, end], ...]
127
            const contentWrappers = this._extractContentWrappers(wrapper);
136✔
128

129
            if (contentWrappers[0][0].tagName === 'TEMPLATE') {
136!
130
                // then - if the content is bracketed by two template tages - we map that structure into an array of
131
                // jquery collections from which we filter out empty ones
132
                contents = contentWrappers
136✔
133
                    .map(items => this._processTemplateGroup(items, container))
137✔
134
                    .filter(v => v.length);
137✔
135

136
                wrapper.filter('template').remove();
136✔
137
                if (contents.length) {
136!
138
                    // and then reduce it to one big collection
139
                    contents = contents.reduce((collection, items) => collection.add(items), $());
137✔
140
                }
141
            } else {
142
                contents = wrapper;
×
143
            }
144
        } else {
145
            contents = wrapper;
43✔
146
        }
147

148
        // in clipboard can be non-existent
149
        if (!contents.length) {
179✔
150
            contents = $('<div></div>');
11✔
151
        }
152

153
        this.ui = this.ui || {};
179✔
154
        this.ui.container = contents;
179✔
155
    },
156

157
    /**
158
     * Extracts the content wrappers from the given wrapper:
159
     * It is possible that multiple plugins (more often generics) are rendered
160
     * in different places. e.g. page menu in the header and in the footer
161
     * so first, we find all the template tags, then put them in a structure like this:
162
     * [[start, end], [start, end], ...]
163
     *
164
     * @method _extractContentWrappers
165
     * @private
166
     * @param {jQuery} wrapper
167
     * @returns {Array<Array<HTMLElement>>}
168
     */
169
    _extractContentWrappers: function (wrapper) {
170
        return wrapper.toArray().reduce((wrappers, elem) => {
136✔
171
            if (elem.classList.contains('cms-plugin-start') || wrappers.length === 0) {
274✔
172
                wrappers.push([elem]);
137✔
173
            } else {
174
                wrappers.at(-1).push(elem);
137✔
175
            }
176
            return wrappers;
274✔
177
        }, []);
178
    },
179

180
    /**
181
     * Processes the template group and returns a jQuery collection
182
     * of the content bracketed by ``cms-plugin-start`` and ``cms-plugin-end``.
183
     * It also wraps any top-level text nodes in ``cms-plugin`` elements.
184
     *
185
     * @method _processTemplateGroup
186
     * @private
187
     * @param {Array<HTMLElement>} items
188
     * @param {HTMLElement} container
189
     * @returns {jQuery}
190
     * @example
191
     * // Given the following HTML:
192
     * <template class="cms-plugin cms-plugin-4711 cms-plugin-start"></template>
193
     * <p>Some text</p>
194
     * <template class="cms-plugin cms-plugin-4711 cms-plugin-end"></template>
195
     *
196
     * // The following jQuery collection will be returned:
197
     * $('<p class="cms-plugin cms-plugin-4711 cms-plugin-start cms-plugin-end">Some text</p>')
198
     */
199
    _processTemplateGroup: function (items, container) {
200
        const templateStart = $(items[0]);
137✔
201
        const className = templateStart.attr('class').replace('cms-plugin-start', '');
137✔
202
        let itemContents = $(nextUntil(templateStart[0], container));
137✔
203

204
        itemContents.each((index, el) => {
137✔
205
            if (el.nodeType === Node.TEXT_NODE && !el.textContent.match(/^\s*$/)) {
158✔
206
                const element = $(el);
10✔
207

208
                element.wrap('<cms-plugin class="cms-plugin-text-node"></cms-plugin>');
10✔
209
                itemContents[index] = element.parent()[0];
10✔
210
            }
211
        });
212

213
        itemContents = itemContents.filter(function() {
137✔
214
            return this.nodeType !== Node.TEXT_NODE && this.nodeType !== Node.COMMENT_NODE;
158✔
215
        });
216

217
        itemContents.addClass(`cms-plugin ${className}`);
137✔
218
        itemContents.first().addClass('cms-plugin-start');
137✔
219
        itemContents.last().addClass('cms-plugin-end');
137✔
220

221
        return itemContents;
137✔
222
    },
223

224
    /**
225
     * Sets up behaviours and ui for placeholder.
226
     *
227
     * @method _setPlaceholder
228
     * @private
229
     */
230
    _setPlaceholder: function() {
231
        var that = this;
23✔
232

233
        this.ui.dragbar = $('.cms-dragbar-' + this.options.placeholder_id);
23✔
234
        this.ui.draggables = this.ui.dragbar.closest('.cms-dragarea').find('> .cms-draggables');
23✔
235
        this.ui.submenu = this.ui.dragbar.find('.cms-submenu-settings');
23✔
236
        var title = this.ui.dragbar.find('.cms-dragbar-title');
23✔
237
        var togglerLinks = this.ui.dragbar.find('.cms-dragbar-toggler a');
23✔
238
        var expanded = 'cms-dragbar-title-expanded';
23✔
239

240
        // register the subnav on the placeholder
241
        this._setSettingsMenu(this.ui.submenu);
23✔
242
        this._setAddPluginModal(this.ui.dragbar.find('.cms-submenu-add'));
23✔
243

244
        // istanbul ignore next
245
        CMS.settings.dragbars = CMS.settings.dragbars || []; // expanded dragbars array
246

247
        // enable expanding/collapsing globally within the placeholder
248
        togglerLinks.off(Plugin.click).on(Plugin.click, function(e) {
23✔
249
            e.preventDefault();
×
250
            if (title.hasClass(expanded)) {
×
251
                that._collapseAll(title);
×
252
            } else {
253
                that._expandAll(title);
×
254
            }
255
        });
256

257
        if ($.inArray(this.options.placeholder_id, CMS.settings.dragbars) !== -1) {
23!
258
            title.addClass(expanded);
×
259
        }
260

261
        this._checkIfPasteAllowed();
23✔
262
    },
263

264
    /**
265
     * Sets up behaviours and ui for plugin.
266
     *
267
     * @method _setPlugin
268
     * @private
269
     */
270
    _setPlugin: function() {
271
        if (isStructureReady()) {
130!
272
            this._setPluginStructureEvents();
130✔
273
        }
274
        if (isContentReady()) {
130!
275
            this._setPluginContentEvents();
130✔
276
        }
277
    },
278

279
    _setPluginStructureEvents: function _setPluginStructureEvents() {
280
        var that = this;
130✔
281

282
        // filling up ui object
283
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
130✔
284
        this.ui.dragitem = this.ui.draggable.find('> .cms-dragitem');
130✔
285
        this.ui.draggables = this.ui.draggable.find('> .cms-draggables');
130✔
286
        this.ui.submenu = this.ui.dragitem.find('.cms-submenu');
130✔
287

288
        this.ui.draggable.data('cms', this.options);
130✔
289

290
        this.ui.dragitem.on(Plugin.doubleClick, this._dblClickToEditHandler.bind(this));
130✔
291

292
        // adds listener for all plugin updates
293
        this.ui.draggable.off('cms-plugins-update').on('cms-plugins-update', function(e, eventData) {
130✔
294
            e.stopPropagation();
×
295
            that.movePlugin(null, eventData);
×
296
        });
297

298
        // adds listener for copy/paste updates
299
        this.ui.draggable.off('cms-paste-plugin-update').on('cms-paste-plugin-update', function(e, eventData) {
130✔
300
            e.stopPropagation();
5✔
301

302
            var dragitem = $(`.cms-draggable-${eventData.id}:last`);
5✔
303

304
            // find out new placeholder id
305
            var placeholder_id = that._getId(dragitem.closest('.cms-dragarea'));
5✔
306

307
            // if placeholder_id is empty, cancel
308
            if (!placeholder_id) {
5!
309
                return false;
×
310
            }
311

312
            var data = dragitem.data('cms');
5✔
313

314
            data.target = placeholder_id;
5✔
315
            data.parent = that._getId(dragitem.parent().closest('.cms-draggable'));
5✔
316
            data.move_a_copy = true;
5✔
317

318
            // expand the plugin we paste to
319
            CMS.settings.states.push(data.parent);
5✔
320
            Helpers.setSettings(CMS.settings);
5✔
321

322
            that.movePlugin(data);
5✔
323
        });
324

325
        setTimeout(() => {
130✔
326
            this.ui.dragitem
130✔
327
                .on('mouseenter', e => {
328
                    e.stopPropagation();
×
329
                    if (!$document.data('expandmode')) {
×
330
                        return;
×
331
                    }
332
                    if (this.ui.draggable.find('> .cms-dragitem > .cms-plugin-disabled').length) {
×
333
                        return;
×
334
                    }
335
                    if (!CMS.API.StructureBoard.ui.container.hasClass('cms-structure-condensed')) {
×
336
                        return;
×
337
                    }
338
                    if (CMS.API.StructureBoard.dragging) {
×
339
                        return;
×
340
                    }
341
                    // eslint-disable-next-line no-magic-numbers
342
                    Plugin._highlightPluginContent(this.options.plugin_id, { successTimeout: 0, seeThrough: true });
×
343
                })
344
                .on('mouseleave', e => {
345
                    if (!CMS.API.StructureBoard.ui.container.hasClass('cms-structure-condensed')) {
×
346
                        return;
×
347
                    }
348
                    e.stopPropagation();
×
349
                    // eslint-disable-next-line no-magic-numbers
350
                    Plugin._removeHighlightPluginContent(this.options.plugin_id);
×
351
                });
352
            // attach event to the plugin menu
353
            this._setSettingsMenu(this.ui.submenu);
130✔
354

355
            // attach events for the "Add plugin" modal
356
            this._setAddPluginModal(this.ui.dragitem.find('.cms-submenu-add'));
130✔
357

358
            // clickability of "Paste" menu item
359
            this._checkIfPasteAllowed();
130✔
360
        });
361
    },
362

363
    _dblClickToEditHandler: function _dblClickToEditHandler(e) {
364
        var that = this;
×
365
        var disabled = $(e.currentTarget).closest('.cms-drag-disabled');
×
366

367
        e.preventDefault();
×
368
        e.stopPropagation();
×
369

370
        if (!disabled.length) {
×
371
            that.editPlugin(
×
372
                Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
373
                that.options.plugin_name,
374
                that._getPluginBreadcrumbs()
375
            );
376
        }
377
    },
378

379
    _setPluginContentEvents: function _setPluginContentEvents() {
380
        const pluginDoubleClickEvent = this._getNamepacedEvent(Plugin.doubleClick);
130✔
381

382
        this.ui.container
130✔
383
            .off('mouseover.cms.plugins')
384
            .on('mouseover.cms.plugins', e => {
385
                if (!$document.data('expandmode')) {
×
386
                    return;
×
387
                }
388
                if (CMS.settings.mode !== 'structure') {
×
389
                    return;
×
390
                }
391
                e.stopPropagation();
×
392
                $('.cms-dragitem-success').remove();
×
393
                $('.cms-draggable-success').removeClass('cms-draggable-success');
×
394
                CMS.API.StructureBoard._showAndHighlightPlugin(0, true); // eslint-disable-line no-magic-numbers
×
395
            })
396
            .off('mouseout.cms.plugins')
397
            .on('mouseout.cms.plugins', e => {
398
                if (CMS.settings.mode !== 'structure') {
×
399
                    return;
×
400
                }
401
                e.stopPropagation();
×
402
                if (this.ui.draggable && this.ui.draggable.length) {
×
403
                    this.ui.draggable.find('.cms-dragitem-success').remove();
×
404
                    this.ui.draggable.removeClass('cms-draggable-success');
×
405
                }
406
                // Plugin._removeHighlightPluginContent(this.options.plugin_id);
407
            });
408

409
        if (!Plugin._isContainingMultiplePlugins(this.ui.container)) {
130✔
410
            $document
129✔
411
                .off(pluginDoubleClickEvent, `.cms-plugin-${this.options.plugin_id}`)
412
                .on(
413
                    pluginDoubleClickEvent,
414
                    `.cms-plugin-${this.options.plugin_id}`,
415
                    this._dblClickToEditHandler.bind(this)
416
                );
417
        }
418
    },
419

420
    /**
421
     * Sets up behaviours and ui for generics.
422
     * Generics do not show up in structure board.
423
     *
424
     * @method _setGeneric
425
     * @private
426
     */
427
    _setGeneric: function() {
428
        var that = this;
24✔
429

430
        // adds double click to edit
431
        this.ui.container.off(Plugin.doubleClick).on(Plugin.doubleClick, function(e) {
24✔
432
            e.preventDefault();
×
433
            e.stopPropagation();
×
434
            that.editPlugin(Helpers.updateUrlWithPath(that.options.urls.edit_plugin), that.options.plugin_name, []);
×
435
        });
436

437
        // adds edit tooltip
438
        this.ui.container
24✔
439
            .off(Plugin.pointerOverAndOut + ' ' + Plugin.touchStart)
440
            .on(Plugin.pointerOverAndOut + ' ' + Plugin.touchStart, function(e) {
441
                if (e.type !== 'touchstart') {
×
442
                    e.stopPropagation();
×
443
                }
444
                var name = that.options.plugin_name;
×
445
                var id = that.options.plugin_id;
×
446

447
                CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
448
            });
449
    },
450

451
    /**
452
     * Checks if paste is allowed into current plugin/placeholder based
453
     * on restrictions we have. Also determines which tooltip to show.
454
     *
455
     * WARNING: this relies on clipboard plugins always being instantiated
456
     * first, so they have data('cms') by the time this method is called.
457
     *
458
     * @method _checkIfPasteAllowed
459
     * @private
460
     * @returns {Boolean}
461
     */
462
    _checkIfPasteAllowed: function _checkIfPasteAllowed() {
463
        var pasteButton = this.ui.dropdown.find('[data-rel=paste]');
151✔
464
        var pasteItem = pasteButton.parent();
151✔
465

466
        if (!clipboardDraggable.length) {
151✔
467
            pasteItem.addClass('cms-submenu-item-disabled');
86✔
468
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
86✔
469
            pasteItem.find('.cms-submenu-item-paste-tooltip-empty').css('display', 'block');
86✔
470
            return false;
86✔
471
        }
472

473
        if (this.ui.draggable && this.ui.draggable.hasClass('cms-draggable-disabled')) {
65✔
474
            pasteItem.addClass('cms-submenu-item-disabled');
45✔
475
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
45✔
476
            pasteItem.find('.cms-submenu-item-paste-tooltip-disabled').css('display', 'block');
45✔
477
            return false;
45✔
478
        }
479

480
        var bounds = this.options.plugin_restriction;
20✔
481

482
        if (clipboardDraggable.data('cms')) {
20!
483
            var clipboardPluginData = clipboardDraggable.data('cms');
20✔
484
            var type = clipboardPluginData.plugin_type;
20✔
485
            var parent_bounds = $.grep(clipboardPluginData.plugin_parent_restriction, function(restriction) {
20✔
486
                // special case when PlaceholderPlugin has a parent restriction named "0"
487
                return restriction !== '0';
20✔
488
            });
489
            var currentPluginType = this.options.plugin_type;
20✔
490

491
            if (
20✔
492
                (bounds.length && $.inArray(type, bounds) === -1) ||
60!
493
                (parent_bounds.length && $.inArray(currentPluginType, parent_bounds) === -1)
494
            ) {
495
                pasteItem.addClass('cms-submenu-item-disabled');
15✔
496
                pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
15✔
497
                pasteItem.find('.cms-submenu-item-paste-tooltip-restricted').css('display', 'block');
15✔
498
                return false;
15✔
499
            }
500
        } else {
501
            return false;
×
502
        }
503

504
        pasteItem.find('a').removeAttr('tabindex').removeAttr('aria-disabled');
5✔
505
        pasteItem.removeClass('cms-submenu-item-disabled');
5✔
506

507
        return true;
5✔
508
    },
509

510
    /**
511
     * Calls api to create a plugin and then proceeds to edit it.
512
     *
513
     * @method addPlugin
514
     * @param {String} type type of the plugin, e.g "Bootstrap3ColumnCMSPlugin"
515
     * @param {String} name name of the plugin, e.g. "Column"
516
     * @param {String} parent id of a parent plugin
517
     * @param {Boolean} showAddForm if false, will NOT show the add form
518
     * @param {Number} position (optional) position of the plugin
519
     */
520
    // eslint-disable-next-line max-params
521
    addPlugin: function(type, name, parent, showAddForm = true, position) {
2✔
522
        var params = {
4✔
523
            placeholder_id: this.options.placeholder_id,
524
            plugin_type: type,
525
            cms_path: path,
526
            plugin_language: CMS.config.request.language,
527
            plugin_position: position || this._getPluginAddPosition()
8✔
528
        };
529

530
        if (parent) {
4✔
531
            params.plugin_parent = parent;
2✔
532
        }
533
        var url = this.options.urls.add_plugin + '?' + $.param(params);
4✔
534

535
        const modal = new Modal({
4✔
536
            onClose: this.options.onClose || false,
7✔
537
            redirectOnClose: this.options.redirectOnClose || false
7✔
538
        });
539

540
        if (showAddForm) {
4✔
541
            modal.open({
3✔
542
                url: url,
543
                title: name
544
            });
545
        } else {
546
            // Also open the modal but without the content. Instead create a form and immediately submit it.
547
            modal.open({
1✔
548
                url: '#',
549
                title: name
550
            });
551
            if (modal.ui) {
1!
552
                // Hide the plugin type selector modal if it's open
553
                modal.ui.modal.hide();
1✔
554
            }
555
            const contents = modal.ui.frame.find('iframe').contents();
1✔
556
            const body = contents.find('body');
1✔
557

558
            body.append(`<form method="post" action="${url}" style="display: none;">
1✔
559
                <input type="hidden" name="csrfmiddlewaretoken" value="${CMS.config.csrf}"></form>`);
560
            body.find('form').submit();
1✔
561
        }
562
        this.modal = modal;
4✔
563

564
        Helpers.removeEventListener('modal-closed.add-plugin');
4✔
565
        Helpers.addEventListener('modal-closed.add-plugin', (e, { instance }) => {
4✔
566
            if (instance !== modal) {
1!
567
                return;
×
568
            }
569
            Plugin._removeAddPluginPlaceholder();
1✔
570
        });
571
    },
572

573
    _getPluginAddPosition: function() {
574
        if (this.options.type === 'placeholder') {
×
575
            return $(`.cms-dragarea-${this.options.placeholder_id} .cms-draggable`).length + 1;
×
576
        }
577

578
        // assume plugin now
579
        // would prefer to get the information from the tree, but the problem is that the flat data
580
        // isn't sorted by position
581
        const maybeChildren = this.ui.draggable.find('.cms-draggable');
×
582

583
        if (maybeChildren.length) {
×
584
            const lastChild = maybeChildren.last();
×
585

586
            const lastChildInstance = Plugin._getPluginById(this._getId(lastChild));
×
587

588
            return lastChildInstance.options.position + 1;
×
589
        }
590

591
        return this.options.position + 1;
×
592
    },
593

594
    /**
595
     * Opens the modal for editing a plugin.
596
     *
597
     * @method editPlugin
598
     * @param {String} url editing url
599
     * @param {String} name Name of the plugin, e.g. "Column"
600
     * @param {Object[]} breadcrumb array of objects representing a breadcrumb,
601
     *     each item is `{ title: 'string': url: 'string' }`
602
     */
603
    editPlugin: function(url, name, breadcrumb) {
604
        // trigger modal window
605
        var modal = new Modal({
3✔
606
            onClose: this.options.onClose || false,
6✔
607
            redirectOnClose: this.options.redirectOnClose || false
6✔
608
        });
609

610
        this.modal = modal;
3✔
611

612
        Helpers.removeEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin');
3✔
613
        Helpers.addEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin', (e, { instance }) => {
3✔
614
            if (instance === modal) {
1!
615
                // cannot be cached
616
                Plugin._removeAddPluginPlaceholder();
1✔
617
            }
618
        });
619
        modal.open({
3✔
620
            url: url,
621
            title: name,
622
            breadcrumbs: breadcrumb,
623
            width: 850
624
        });
625
    },
626

627
    /**
628
     * Used for copying _and_ pasting a plugin. If either of params
629
     * is present method assumes that it's "paste" and will make a call
630
     * to api to insert current plugin to specified `options.target_plugin_id`
631
     * or `options.target_placeholder_id`. Copying a plugin also first
632
     * clears the clipboard.
633
     *
634
     * @method copyPlugin
635
     * @param {Object} [opts=this.options]
636
     * @param {String} source_language
637
     * @returns {Boolean|void}
638
     */
639
    // eslint-disable-next-line complexity
640
    copyPlugin: function(opts, source_language) {
641
        // cancel request if already in progress
642
        if (CMS.API.locked) {
9✔
643
            return false;
1✔
644
        }
645
        CMS.API.locked = true;
8✔
646

647
        // set correct options (don't mutate them)
648
        var options = $.extend({}, opts || this.options);
8✔
649
        var sourceLanguage = source_language;
8✔
650
        let copyingFromLanguage = false;
8✔
651

652
        if (sourceLanguage) {
8✔
653
            copyingFromLanguage = true;
1✔
654
            options.target = options.placeholder_id;
1✔
655
            options.plugin_id = '';
1✔
656
            options.parent = '';
1✔
657
        } else {
658
            sourceLanguage = CMS.config.request.language;
7✔
659
        }
660

661
        var data = {
8✔
662
            source_placeholder_id: options.placeholder_id,
663
            source_plugin_id: options.plugin_id || '',
9✔
664
            source_language: sourceLanguage,
665
            target_plugin_id: options.parent || '',
16✔
666
            target_placeholder_id: options.target || CMS.config.clipboard.id,
15✔
667
            csrfmiddlewaretoken: CMS.config.csrf,
668
            target_language: CMS.config.request.language
669
        };
670
        var request = {
8✔
671
            type: 'POST',
672
            url: Helpers.updateUrlWithPath(options.urls.copy_plugin),
673
            data: data,
674
            success: function(response) {
675
                CMS.API.Messages.open({
2✔
676
                    message: CMS.config.lang.success
677
                });
678
                if (copyingFromLanguage) {
2!
679
                    CMS.API.StructureBoard.invalidateState('PASTE', $.extend({}, data, response));
×
680
                } else {
681
                    CMS.API.StructureBoard.invalidateState('COPY', response);
2✔
682
                }
683
                CMS.API.locked = false;
2✔
684
                hideLoader();
2✔
685
            },
686
            error: function(jqXHR) {
687
                CMS.API.locked = false;
3✔
688
                var msg = CMS.config.lang.error;
3✔
689

690
                // trigger error
691
                CMS.API.Messages.open({
3✔
692
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
4✔
693
                    error: true
694
                });
695
            }
696
        };
697

698
        $.ajax(request);
8✔
699
    },
700

701
    /**
702
     * Essentially clears clipboard and moves plugin to a clipboard
703
     * placholder through `movePlugin`.
704
     *
705
     * @method cutPlugin
706
     * @returns {Boolean|void}
707
     */
708
    cutPlugin: function() {
709
        // if cut is once triggered, prevent additional actions
710
        if (CMS.API.locked) {
9✔
711
            return false;
1✔
712
        }
713
        CMS.API.locked = true;
8✔
714

715
        var that = this;
8✔
716
        var data = {
8✔
717
            placeholder_id: CMS.config.clipboard.id,
718
            plugin_id: this.options.plugin_id,
719
            plugin_parent: '',
720
            target_language: CMS.config.request.language,
721
            csrfmiddlewaretoken: CMS.config.csrf
722
        };
723

724
        // move plugin
725
        $.ajax({
8✔
726
            type: 'POST',
727
            url: Helpers.updateUrlWithPath(that.options.urls.move_plugin),
728
            data: data,
729
            success: function(response) {
730
                CMS.API.locked = false;
4✔
731
                CMS.API.Messages.open({
4✔
732
                    message: CMS.config.lang.success
733
                });
734
                CMS.API.StructureBoard.invalidateState('CUT', $.extend({}, data, response));
4✔
735
                hideLoader();
4✔
736
            },
737
            error: function(jqXHR) {
738
                CMS.API.locked = false;
3✔
739
                var msg = CMS.config.lang.error;
3✔
740

741
                // trigger error
742
                CMS.API.Messages.open({
3✔
743
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
4✔
744
                    error: true
745
                });
746
                hideLoader();
3✔
747
            }
748
        });
749
    },
750

751
    /**
752
     * Method is called when you click on the paste button on the plugin.
753
     * Uses existing solution of `copyPlugin(options)`
754
     *
755
     * @method pastePlugin
756
     */
757
    pastePlugin: function() {
758
        var id = this._getId(clipboardDraggable);
5✔
759
        var eventData = {
5✔
760
            id: id
761
        };
762

763
        const clipboardDraggableClone = clipboardDraggable.clone(true, true);
5✔
764

765
        clipboardDraggableClone.appendTo(this.ui.draggables);
5✔
766
        if (this.options.plugin_id) {
5✔
767
            StructureBoard.actualizePluginCollapseStatus(this.options.plugin_id);
4✔
768
        }
769
        this.ui.draggables.trigger('cms-structure-update', [eventData]);
5✔
770
        clipboardDraggableClone.trigger('cms-paste-plugin-update', [eventData]);
5✔
771
    },
772

773
    /**
774
     * Moves plugin by querying the API and then updates some UI parts
775
     * to reflect that the page has changed.
776
     *
777
     * @method movePlugin
778
     * @param {Object} [opts=this.options]
779
     * @param {String} [opts.placeholder_id]
780
     * @param {String} [opts.plugin_id]
781
     * @param {String} [opts.plugin_parent]
782
     * @param {Boolean} [opts.move_a_copy]
783
     * @returns {Boolean|void}
784
     */
785
    movePlugin: function(opts) {
786
        // cancel request if already in progress
787
        if (CMS.API.locked) {
12✔
788
            return false;
1✔
789
        }
790
        CMS.API.locked = true;
11✔
791

792
        // set correct options
793
        const options = opts || this.options;
11✔
794

795
        const dragitem = $(`.cms-draggable-${options.plugin_id}:last`);
11✔
796

797
        // SAVING POSITION
798
        const placeholder_id = this._getId(dragitem.parents('.cms-draggables').last().prevAll('.cms-dragbar').first());
11✔
799

800
        // cancel here if we have no placeholder id
801
        if (placeholder_id === false) {
11✔
802
            return false;
1✔
803
        }
804
        const pluginParentElement = dragitem.parent().closest('.cms-draggable');
10✔
805
        const plugin_parent = this._getId(pluginParentElement);
10✔
806

807
        // gather the data for ajax request
808
        const data = {
10✔
809
            plugin_id: options.plugin_id,
810
            plugin_parent: plugin_parent || '',
20✔
811
            target_language: CMS.config.request.language,
812
            csrfmiddlewaretoken: CMS.config.csrf,
813
            move_a_copy: options.move_a_copy
814
        };
815

816
        if (Number(placeholder_id) === Number(options.placeholder_id)) {
10!
817
            Plugin._updatePluginPositions(options.placeholder_id);
10✔
818
        } else {
819
            data.placeholder_id = placeholder_id;
×
820

821
            Plugin._updatePluginPositions(placeholder_id);
×
822
            Plugin._updatePluginPositions(options.placeholder_id);
×
823
        }
824

825
        const position = this.options.position;
10✔
826

827
        data.target_position = position;
10✔
828

829
        showLoader();
10✔
830

831
        $.ajax({
10✔
832
            type: 'POST',
833
            url: Helpers.updateUrlWithPath(options.urls.move_plugin),
834
            data: data,
835
            success: response => {
836
                CMS.API.StructureBoard.invalidateState(
4✔
837
                    data.move_a_copy ? 'PASTE' : 'MOVE',
4!
838
                    $.extend({}, data, { placeholder_id: placeholder_id }, response)
839
                );
840

841
                // enable actions again
842
                CMS.API.locked = false;
4✔
843
                hideLoader();
4✔
844
            },
845
            error: jqXHR => {
846
                CMS.API.locked = false;
4✔
847
                const msg = CMS.config.lang.error;
4✔
848

849
                // trigger error
850
                CMS.API.Messages.open({
4✔
851
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
5✔
852
                    error: true
853
                });
854
                hideLoader();
4✔
855
            }
856
        });
857
    },
858

859
     /**
860
     * Changes the settings attributes on an initialised plugin.
861
     *
862
     * @method _setSettings
863
     * @param {Object} oldSettings current settings
864
     * @param {Object} newSettings new settings to be applied
865
     * @private
866
     */
867
    _setSettings: function _setSettings(oldSettings, newSettings) {
868
        var settings = $.extend(true, {}, oldSettings, newSettings);
×
869
        var plugin = $('.cms-plugin-' + settings.plugin_id);
×
870
        var draggable = $('.cms-draggable-' + settings.plugin_id);
×
871

872
        // set new setting on instance and plugin data
873
        this.options = settings;
×
874
        if (plugin.length) {
×
875
            var index = plugin.data('cms').findIndex(function(pluginData) {
×
876
                return pluginData.plugin_id === settings.plugin_id;
×
877
            });
878

879
            plugin.each(function() {
×
880
                $(this).data('cms')[index] = settings;
×
881
            });
882
        }
883
        if (draggable.length) {
×
884
            draggable.data('cms', settings);
×
885
        }
886
    },
887

888
    /**
889
     * Opens a modal to delete a plugin.
890
     *
891
     * @method deletePlugin
892
     * @param {String} url admin url for deleting a page
893
     * @param {String} name plugin name, e.g. "Column"
894
     * @param {Object[]} breadcrumb array of objects representing a breadcrumb,
895
     *     each item is `{ title: 'string': url: 'string' }`
896
     */
897
    deletePlugin: function(url, name, breadcrumb) {
898
        // trigger modal window
899
        var modal = new Modal({
2✔
900
            onClose: this.options.onClose || false,
4✔
901
            redirectOnClose: this.options.redirectOnClose || false
4✔
902
        });
903

904
        this.modal = modal;
2✔
905

906
        Helpers.removeEventListener('modal-loaded.delete-plugin');
2✔
907
        Helpers.addEventListener('modal-loaded.delete-plugin', (e, { instance }) => {
2✔
908
            if (instance === modal) {
5✔
909
                Plugin._removeAddPluginPlaceholder();
1✔
910
            }
911
        });
912
        modal.open({
2✔
913
            url: url,
914
            title: name,
915
            breadcrumbs: breadcrumb
916
        });
917
    },
918

919
    /**
920
     * Destroys the current plugin instance removing only the DOM listeners
921
     *
922
     * @method destroy
923
     * @param {Object}  options - destroy config options
924
     * @param {Boolean} options.mustCleanup - if true it will remove also the plugin UI components from the DOM
925
     * @returns {void}
926
     */
927
    destroy(options = {}) {
1✔
928
        const mustCleanup = options.mustCleanup || false;
2✔
929

930
        // close the plugin modal if it was open
931
        if (this.modal) {
2!
932
            this.modal.close();
×
933
            // unsubscribe to all the modal events
934
            this.modal.off();
×
935
        }
936

937
        if (mustCleanup) {
2✔
938
            this.cleanup();
1✔
939
        }
940

941
        // remove event bound to global elements like document or window
942
        $document.off(`.${this.uid}`);
2✔
943
        $window.off(`.${this.uid}`);
2✔
944
    },
945

946
    /**
947
     * Remove the plugin specific ui elements from the DOM
948
     *
949
     * @method cleanup
950
     * @returns {void}
951
     */
952
    cleanup() {
953
        // remove all the plugin UI DOM elements
954
        // notice that $.remove will remove also all the ui specific events
955
        // previously attached to them
956
        Object.keys(this.ui).forEach(el => this.ui[el].remove());
12✔
957
    },
958

959
    /**
960
     * Called after plugin is added through ajax.
961
     *
962
     * @method editPluginPostAjax
963
     * @param {Object} toolbar CMS.API.Toolbar instance (not used)
964
     * @param {Object} response response from server
965
     */
966
    editPluginPostAjax: function(toolbar, response) {
967
        this.editPlugin(Helpers.updateUrlWithPath(response.url), this.options.plugin_name, response.breadcrumb);
1✔
968
    },
969

970
    /**
971
     * _setSettingsMenu sets up event handlers for settings menu.
972
     *
973
     * @method _setSettingsMenu
974
     * @private
975
     * @param {jQuery} nav
976
     */
977
    _setSettingsMenu: function _setSettingsMenu(nav) {
978
        var that = this;
153✔
979

980
        this.ui.dropdown = nav.siblings('.cms-submenu-dropdown-settings');
153✔
981
        var dropdown = this.ui.dropdown;
153✔
982

983
        nav
153✔
984
            .off(Plugin.pointerUp)
985
            .on(Plugin.pointerUp, function(e) {
986
                e.preventDefault();
×
987
                e.stopPropagation();
×
988
                var trigger = $(this);
×
989

990
                if (trigger.hasClass('cms-btn-active')) {
×
991
                    Plugin._hideSettingsMenu(trigger);
×
992
                } else {
993
                    Plugin._hideSettingsMenu();
×
994
                    that._showSettingsMenu(trigger);
×
995
                }
996
            })
997
            .off(Plugin.touchStart)
998
            .on(Plugin.touchStart, function(e) {
999
                // required on some touch devices so
1000
                // ui touch punch is not triggering mousemove
1001
                // which in turn results in pep triggering pointercancel
1002
                e.stopPropagation();
×
1003
            });
1004

1005
        dropdown
153✔
1006
            .off(Plugin.mouseEvents)
1007
            .on(Plugin.mouseEvents, function(e) {
1008
                e.stopPropagation();
×
1009
            })
1010
            .off(Plugin.touchStart)
1011
            .on(Plugin.touchStart, function(e) {
1012
                // required for scrolling on mobile
1013
                e.stopPropagation();
×
1014
            });
1015

1016
        that._setupActions(nav);
153✔
1017
        // prevent propagation
1018
        nav
153✔
1019
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '))
1020
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
1021
                e.stopPropagation();
×
1022
            });
1023

1024
        nav
153✔
1025
            .siblings('.cms-quicksearch, .cms-submenu-dropdown-settings')
1026
            .off([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '))
1027
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
1028
                e.stopPropagation();
×
1029
            });
1030
    },
1031

1032
    /**
1033
     * Simplistic implementation, only scrolls down, only works in structuremode
1034
     * and highly depends on the styles of the structureboard to work correctly
1035
     *
1036
     * @method _scrollToElement
1037
     * @private
1038
     * @param {jQuery} el element to scroll to
1039
     * @param {Object} [opts]
1040
     * @param {Number} [opts.duration=200] time to scroll
1041
     * @param {Number} [opts.offset=50] distance in px to the bottom of the screen
1042
     */
1043
    _scrollToElement: function _scrollToElement(el, opts) {
1044
        var DEFAULT_DURATION = 200;
3✔
1045
        var DEFAULT_OFFSET = 50;
3✔
1046
        var duration = opts && opts.duration !== undefined ? opts.duration : DEFAULT_DURATION;
3✔
1047
        var offset = opts && opts.offset !== undefined ? opts.offset : DEFAULT_OFFSET;
3✔
1048
        var scrollable = el.offsetParent();
3✔
1049
        var scrollHeight = $window.height();
3✔
1050
        var scrollTop = scrollable.scrollTop();
3✔
1051
        var elPosition = el.position().top;
3✔
1052
        var elHeight = el.height();
3✔
1053
        var isInViewport = elPosition + elHeight + offset <= scrollHeight;
3✔
1054

1055
        if (!isInViewport) {
3✔
1056
            scrollable.animate(
2✔
1057
                {
1058
                    scrollTop: elPosition + offset + elHeight + scrollTop - scrollHeight
1059
                },
1060
                duration
1061
            );
1062
        }
1063
    },
1064

1065
    /**
1066
     * Opens a modal with traversable plugins list, adds a placeholder to where
1067
     * the plugin will be added.
1068
     *
1069
     * @method _setAddPluginModal
1070
     * @private
1071
     * @param {jQuery} nav modal trigger element
1072
     * @returns {Boolean|void}
1073
     */
1074
    _setAddPluginModal: function _setAddPluginModal(nav) {
1075
        if (nav.hasClass('cms-btn-disabled')) {
153✔
1076
            return false;
88✔
1077
        }
1078
        var that = this;
65✔
1079
        var modal;
1080
        var possibleChildClasses;
1081
        var isTouching;
1082
        var plugins;
1083

1084
        var initModal = once(function initModal() {
65✔
1085
            var placeholder = $(
×
1086
                '<div class="cms-add-plugin-placeholder">' + CMS.config.lang.addPluginPlaceholder + '</div>'
1087
            );
1088
            var dragItem = nav.closest('.cms-dragitem');
×
1089
            var isPlaceholder = !dragItem.length;
×
1090
            var childrenList;
1091

1092
            modal = new Modal({
×
1093
                minWidth: 400,
1094
                minHeight: 400
1095
            });
1096

1097
            if (isPlaceholder) {
×
1098
                childrenList = nav.closest('.cms-dragarea').find('> .cms-draggables');
×
1099
            } else {
1100
                childrenList = nav.closest('.cms-draggable').find('> .cms-draggables');
×
1101
            }
1102

1103
            Helpers.addEventListener('modal-loaded', (e, { instance }) => {
×
1104
                if (instance !== modal) {
×
1105
                    return;
×
1106
                }
1107

1108
                that._setupKeyboardTraversing();
×
1109
                if (childrenList.hasClass('cms-hidden') && !isPlaceholder) {
×
1110
                    that._toggleCollapsable(dragItem);
×
1111
                }
1112
                Plugin._removeAddPluginPlaceholder();
×
1113
                placeholder.appendTo(childrenList);
×
1114
                that._scrollToElement(placeholder);
×
1115
            });
1116

1117
            Helpers.addEventListener('modal-closed', (e, { instance }) => {
×
1118
                if (instance !== modal) {
×
1119
                    return;
×
1120
                }
1121
                Plugin._removeAddPluginPlaceholder();
×
1122
            });
1123

1124
            Helpers.addEventListener('modal-shown', (e, { instance }) => {
×
1125
                if (modal !== instance) {
×
1126
                    return;
×
1127
                }
1128
                var dropdown = $('.cms-modal-markup .cms-plugin-picker');
×
1129

1130
                if (!isTouching) {
×
1131
                    // only focus the field if using mouse
1132
                    // otherwise keyboard pops up
1133
                    dropdown.find('input').trigger('focus');
×
1134
                }
1135
                isTouching = false;
×
1136
            });
1137

1138
            plugins = nav.siblings('.cms-plugin-picker');
×
1139

1140
            that._setupQuickSearch(plugins);
×
1141
        });
1142

1143
        nav
65✔
1144
            .on(Plugin.touchStart, function(e) {
1145
                isTouching = true;
×
1146
                // required on some touch devices so
1147
                // ui touch punch is not triggering mousemove
1148
                // which in turn results in pep triggering pointercancel
1149
                e.stopPropagation();
×
1150
            })
1151
            .on(Plugin.pointerUp, function(e) {
1152
                e.preventDefault();
×
1153
                e.stopPropagation();
×
1154

1155
                Plugin._hideSettingsMenu();
×
1156

1157
                possibleChildClasses = that._getPossibleChildClasses();
×
1158
                var selectionNeeded = possibleChildClasses.filter(':not(.cms-submenu-item-title)').length !== 1;
×
1159

1160
                if (selectionNeeded) {
×
1161
                    initModal();
×
1162

1163
                    // since we don't know exact plugin parent (because dragndrop)
1164
                    // we need to know the parent id by the time we open "add plugin" dialog
1165
                    var pluginsCopy = that._updateWithMostUsedPlugins(
×
1166
                        plugins
1167
                            .clone(true, true)
1168
                            .data('parentId', that._getId(nav.closest('.cms-draggable')))
1169
                            .append(possibleChildClasses)
1170
                    );
1171

1172
                    modal.open({
×
1173
                        title: that.options.addPluginHelpTitle,
1174
                        html: pluginsCopy,
1175
                        width: 530,
1176
                        height: 400
1177
                    });
1178
                } else {
1179
                    // only one plugin available, no need to show the modal
1180
                    // instead directly add the single plugin
1181
                    const el = possibleChildClasses.find('a');  // only one result
×
1182
                    const pluginType = el.attr('href').replace('#', '');
×
1183
                    const showAddForm = el.data('addForm');
×
1184
                    const parentId = that._getId(nav.closest('.cms-draggable'));
×
1185

1186
                    that.addPlugin(pluginType, el.text(), parentId, showAddForm);
×
1187
                }
1188
            });
1189

1190
        // prevent propagation
1191
        nav.on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
65✔
1192
            e.stopPropagation();
×
1193
        });
1194

1195
        nav
65✔
1196
            .siblings('.cms-quicksearch, .cms-submenu-dropdown')
1197
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
1198
                e.stopPropagation();
×
1199
            });
1200
    },
1201

1202
    _updateWithMostUsedPlugins: function _updateWithMostUsedPlugins(plugins) {
1203
        const items = plugins.find('.cms-submenu-item');
×
1204
        // eslint-disable-next-line no-unused-vars
1205
        const mostUsedPlugins = toPairs(pluginUsageMap).sort(([x, a], [y, b]) => a - b).reverse();
×
1206
        const MAX_MOST_USED_PLUGINS = 5;
×
1207
        let count = 0;
×
1208

1209
        if (items.filter(':not(.cms-submenu-item-title)').length <= MAX_MOST_USED_PLUGINS) {
×
1210
            return plugins;
×
1211
        }
1212

1213
        let ref = plugins.find('.cms-quicksearch');
×
1214

1215
        mostUsedPlugins.forEach(([name]) => {
×
1216
            if (count === MAX_MOST_USED_PLUGINS) {
×
1217
                return;
×
1218
            }
1219
            const item = items.find(`[href=${name}]`);
×
1220

1221
            if (item.length) {
×
1222
                const clone = item.closest('.cms-submenu-item').clone(true, true);
×
1223

1224
                ref.after(clone);
×
1225
                ref = clone;
×
1226
                count += 1;
×
1227
            }
1228
        });
1229

1230
        if (count) {
×
1231
            plugins.find('.cms-quicksearch').after(
×
1232
                $(`<div class="cms-submenu-item cms-submenu-item-title" data-cms-most-used>
1233
                    <span>${CMS.config.lang.mostUsed}</span>
1234
                </div>`)
1235
            );
1236
        }
1237

1238
        return plugins;
×
1239
    },
1240

1241
    /**
1242
     * Returns a specific plugin namespaced event postfixing the plugin uid to it
1243
     * in order to properly manage it via jQuery $.on and $.off
1244
     *
1245
     * @method _getNamepacedEvent
1246
     * @private
1247
     * @param {String} base - plugin event type
1248
     * @param {String} additionalNS - additional namespace (like '.traverse' for example)
1249
     * @returns {String} a specific plugin event
1250
     *
1251
     * @example
1252
     *
1253
     * plugin._getNamepacedEvent(Plugin.click); // 'click.cms.plugin.42'
1254
     * plugin._getNamepacedEvent(Plugin.keyDown, '.traverse'); // 'keydown.cms.plugin.traverse.42'
1255
     */
1256
    _getNamepacedEvent(base, additionalNS = '') {
133✔
1257
        return `${base}${additionalNS ? '.'.concat(additionalNS) : ''}.${this.uid}`;
144✔
1258
    },
1259

1260
    /**
1261
     * Returns available plugin/placeholder child classes markup
1262
     * for "Add plugin" modal
1263
     *
1264
     * @method _getPossibleChildClasses
1265
     * @private
1266
     * @returns {jQuery} "add plugin" menu
1267
     */
1268
    _getPossibleChildClasses: function _getPossibleChildClasses() {
1269
        var that = this;
33✔
1270
        var childRestrictions = this.options.plugin_restriction;
33✔
1271
        // have to check the placeholder every time, since plugin could've been
1272
        // moved as part of another plugin
1273
        var placeholderId = that._getId(that.ui.submenu.closest('.cms-dragarea'));
33✔
1274
        var resultElements = $($('#cms-plugin-child-classes-' + placeholderId).html());
33✔
1275

1276
        if (childRestrictions && childRestrictions.length) {
33✔
1277
            resultElements = resultElements.filter(function() {
29✔
1278
                var item = $(this);
4,727✔
1279

1280
                return (
4,727✔
1281
                    item.hasClass('cms-submenu-item-title') ||
9,106✔
1282
                    childRestrictions.indexOf(item.find('a').attr('href')) !== -1
1283
                );
1284
            });
1285

1286
            resultElements = resultElements.filter(function(index) {
29✔
1287
                var item = $(this);
411✔
1288

1289
                return (
411✔
1290
                    !item.hasClass('cms-submenu-item-title') ||
1,182✔
1291
                    (item.hasClass('cms-submenu-item-title') &&
1292
                        (!resultElements.eq(index + 1).hasClass('cms-submenu-item-title') &&
1293
                            resultElements.eq(index + 1).length))
1294
                );
1295
            });
1296
        }
1297

1298
        resultElements.find('a').on(Plugin.click, e => this._delegate(e));
33✔
1299

1300
        return resultElements;
33✔
1301
    },
1302

1303
    /**
1304
     * Sets up event handlers for quicksearching in the plugin picker.
1305
     *
1306
     * @method _setupQuickSearch
1307
     * @private
1308
     * @param {jQuery} plugins plugins picker element
1309
     */
1310
    _setupQuickSearch: function _setupQuickSearch(plugins) {
1311
        var that = this;
×
1312
        var FILTER_DEBOUNCE_TIMER = 100;
×
1313
        var FILTER_PICK_DEBOUNCE_TIMER = 110;
×
1314

1315
        var handler = debounce(function() {
×
1316
            var input = $(this);
×
1317
            // have to always find the pluginsPicker in the handler
1318
            // because of how we move things into/out of the modal
1319
            var pluginsPicker = input.closest('.cms-plugin-picker');
×
1320

1321
            that._filterPluginsList(pluginsPicker, input);
×
1322
        }, FILTER_DEBOUNCE_TIMER);
1323

1324
        plugins.find('> .cms-quicksearch').find('input').on(Plugin.keyUp, handler).on(
×
1325
            Plugin.keyUp,
1326
            debounce(function(e) {
1327
                var input;
1328
                var pluginsPicker;
1329

1330
                if (e.keyCode === KEYS.ENTER) {
×
1331
                    input = $(this);
×
1332
                    pluginsPicker = input.closest('.cms-plugin-picker');
×
1333
                    pluginsPicker
×
1334
                        .find('.cms-submenu-item')
1335
                        .not('.cms-submenu-item-title')
1336
                        .filter(':visible')
1337
                        .first()
1338
                        .find('> a')
1339
                        .focus()
1340
                        .trigger('click');
1341
                }
1342
            }, FILTER_PICK_DEBOUNCE_TIMER)
1343
        );
1344
    },
1345

1346
    /**
1347
     * Sets up click handlers for various plugin/placeholder items.
1348
     * Items can be anywhere in the plugin dragitem, not only in dropdown.
1349
     *
1350
     * @method _setupActions
1351
     * @private
1352
     * @param {jQuery} nav dropdown trigger with the items
1353
     */
1354
    _setupActions: function _setupActions(nav) {
1355
        var items = '.cms-submenu-edit, .cms-submenu-item a';
163✔
1356
        var parent = nav.parent();
163✔
1357

1358
        parent.find('.cms-submenu-edit').off(Plugin.touchStart).on(Plugin.touchStart, function(e) {
163✔
1359
            // required on some touch devices so
1360
            // ui touch punch is not triggering mousemove
1361
            // which in turn results in pep triggering pointercancel
1362
            e.stopPropagation();
1✔
1363
        });
1364
        parent.find(items).off(Plugin.click).on(Plugin.click, nav, e => this._delegate(e));
163✔
1365
    },
1366

1367
    /**
1368
     * Handler for the "action" items
1369
     *
1370
     * @method _delegate
1371
     * @param {$.Event} e event
1372
     * @private
1373
     */
1374
    // eslint-disable-next-line complexity
1375
    _delegate: function _delegate(e) {
1376
        e.preventDefault();
13✔
1377
        e.stopPropagation();
13✔
1378

1379
        var nav;
1380
        var that = this;
13✔
1381

1382
        if (e.data && e.data.nav) {
13!
1383
            nav = e.data.nav;
×
1384
        }
1385

1386
        // show loader and make sure scroll doesn't jump
1387
        showLoader();
13✔
1388

1389
        var items = '.cms-submenu-edit, .cms-submenu-item a';
13✔
1390
        var el = $(e.target).closest(items);
13✔
1391

1392
        Plugin._hideSettingsMenu(nav);
13✔
1393

1394
        // set switch for subnav entries
1395
        switch (el.attr('data-rel')) {
13!
1396
            // eslint-disable-next-line no-case-declarations
1397
            case 'add':
1398
                const pluginType = el.attr('href').replace('#', '');
2✔
1399
                const showAddForm = el.data('addForm');
2✔
1400

1401
                Plugin._updateUsageCount(pluginType);
2✔
1402
                that.addPlugin(pluginType, el.text(), el.closest('.cms-plugin-picker').data('parentId'), showAddForm);
2✔
1403
                break;
2✔
1404
            case 'ajax_add':
1405
                CMS.API.Toolbar.openAjax({
1✔
1406
                    url: el.attr('href'),
1407
                    post: JSON.stringify(el.data('post')),
1408
                    text: el.data('text'),
1409
                    callback: $.proxy(that.editPluginPostAjax, that),
1410
                    onSuccess: el.data('on-success')
1411
                });
1412
                break;
1✔
1413
            case 'edit':
1414
                that.editPlugin(
1✔
1415
                    Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
1416
                    that.options.plugin_name,
1417
                    that._getPluginBreadcrumbs()
1418
                );
1419
                break;
1✔
1420
            case 'copy-lang':
1421
                that.copyPlugin(that.options, el.attr('data-language'));
1✔
1422
                break;
1✔
1423
            case 'copy':
1424
                if (el.parent().hasClass('cms-submenu-item-disabled')) {
2✔
1425
                    hideLoader();
1✔
1426
                } else {
1427
                    that.copyPlugin();
1✔
1428
                }
1429
                break;
2✔
1430
            case 'cut':
1431
                that.cutPlugin();
1✔
1432
                break;
1✔
1433
            case 'paste':
1434
                hideLoader();
2✔
1435
                if (!el.parent().hasClass('cms-submenu-item-disabled')) {
2✔
1436
                    that.pastePlugin();
1✔
1437
                }
1438
                break;
2✔
1439
            case 'delete':
1440
                that.deletePlugin(
1✔
1441
                    Helpers.updateUrlWithPath(that.options.urls.delete_plugin),
1442
                    that.options.plugin_name,
1443
                    that._getPluginBreadcrumbs()
1444
                );
1445
                break;
1✔
1446
            case 'highlight':
1447
                hideLoader();
×
1448
                // eslint-disable-next-line no-magic-numbers
1449
                window.location.hash = `cms-plugin-${this.options.plugin_id}`;
×
1450
                Plugin._highlightPluginContent(this.options.plugin_id, { seeThrough: true });
×
1451
                e.stopImmediatePropagation();
×
1452
                break;
×
1453
            default:
1454
                hideLoader();
2✔
1455
                CMS.API.Toolbar._delegate(el);
2✔
1456
        }
1457
    },
1458

1459
    /**
1460
     * Sets up keyboard traversing of plugin picker.
1461
     *
1462
     * @method _setupKeyboardTraversing
1463
     * @private
1464
     */
1465
    _setupKeyboardTraversing: function _setupKeyboardTraversing() {
1466
        var dropdown = $('.cms-modal-markup .cms-plugin-picker');
3✔
1467
        const keyDownTraverseEvent = this._getNamepacedEvent(Plugin.keyDown, 'traverse');
3✔
1468

1469
        if (!dropdown.length) {
3✔
1470
            return;
1✔
1471
        }
1472
        // add key events
1473
        $document.off(keyDownTraverseEvent);
2✔
1474
        // istanbul ignore next: not really possible to reproduce focus state in unit tests
1475
        $document.on(keyDownTraverseEvent, function(e) {
1476
            var anchors = dropdown.find('.cms-submenu-item:visible a');
1477
            var index = anchors.index(anchors.filter(':focus'));
1478

1479
            // bind arrow down and tab keys
1480
            if (e.keyCode === KEYS.DOWN || (e.keyCode === KEYS.TAB && !e.shiftKey)) {
1481
                e.preventDefault();
1482
                if (index >= 0 && index < anchors.length - 1) {
1483
                    anchors.eq(index + 1).focus();
1484
                } else {
1485
                    anchors.eq(0).focus();
1486
                }
1487
            }
1488

1489
            // bind arrow up and shift+tab keys
1490
            if (e.keyCode === KEYS.UP || (e.keyCode === KEYS.TAB && e.shiftKey)) {
1491
                e.preventDefault();
1492
                if (anchors.is(':focus')) {
1493
                    anchors.eq(index - 1).focus();
1494
                } else {
1495
                    anchors.eq(anchors.length).focus();
1496
                }
1497
            }
1498
        });
1499
    },
1500

1501
    /**
1502
     * Opens the settings menu for a plugin.
1503
     *
1504
     * @method _showSettingsMenu
1505
     * @private
1506
     * @param {jQuery} nav trigger element
1507
     */
1508
    _showSettingsMenu: function(nav) {
1509
        this._checkIfPasteAllowed();
×
1510

1511
        var dropdown = this.ui.dropdown;
×
1512
        var parents = nav.parentsUntil('.cms-dragarea').last();
×
1513
        var MIN_SCREEN_MARGIN = 10;
×
1514

1515
        nav.addClass('cms-btn-active');
×
1516
        parents.addClass('cms-z-index-9999');
×
1517

1518
        // set visible states
1519
        dropdown.show();
×
1520

1521
        // calculate dropdown positioning
1522
        if (
×
1523
            $window.height() + $window.scrollTop() - nav.offset().top - dropdown.height() <= MIN_SCREEN_MARGIN &&
×
1524
            nav.offset().top - dropdown.height() >= 0
1525
        ) {
1526
            dropdown.removeClass('cms-submenu-dropdown-top').addClass('cms-submenu-dropdown-bottom');
×
1527
        } else {
1528
            dropdown.removeClass('cms-submenu-dropdown-bottom').addClass('cms-submenu-dropdown-top');
×
1529
        }
1530
    },
1531

1532
    /**
1533
     * Filters given plugins list by a query.
1534
     *
1535
     * @method _filterPluginsList
1536
     * @private
1537
     * @param {jQuery} list plugins picker element
1538
     * @param {jQuery} input input, which value to filter plugins with
1539
     * @returns {Boolean|void}
1540
     */
1541
    _filterPluginsList: function _filterPluginsList(list, input) {
1542
        var items = list.find('.cms-submenu-item');
5✔
1543
        var titles = list.find('.cms-submenu-item-title');
5✔
1544
        var query = input.val();
5✔
1545

1546
        // cancel if query is zero
1547
        if (query === '') {
5✔
1548
            items.add(titles).show();
1✔
1549
            return false;
1✔
1550
        }
1551

1552
        var mostRecentItems = list.find('.cms-submenu-item[data-cms-most-used]');
4✔
1553

1554
        mostRecentItems = mostRecentItems.add(mostRecentItems.nextUntil('.cms-submenu-item-title'));
4✔
1555

1556
        var itemsToFilter = items.toArray().map(function(el) {
4✔
1557
            var element = $(el);
72✔
1558

1559
            return {
72✔
1560
                value: element.text(),
1561
                element: element
1562
            };
1563
        });
1564

1565
        var filteredItems = fuzzyFilter(itemsToFilter, query, { key: 'value' });
4✔
1566

1567
        items.hide();
4✔
1568
        filteredItems.forEach(function(item) {
4✔
1569
            item.element.show();
3✔
1570
        });
1571

1572
        // check if a title is matching
1573
        titles.filter(':visible').each(function(index, item) {
4✔
1574
            titles.hide();
1✔
1575
            $(item).nextUntil('.cms-submenu-item-title').show();
1✔
1576
        });
1577

1578
        // always display title of a category
1579
        items.filter(':visible').each(function(index, titleItem) {
4✔
1580
            var item = $(titleItem);
16✔
1581

1582
            if (item.prev().hasClass('cms-submenu-item-title')) {
16✔
1583
                item.prev().show();
2✔
1584
            } else {
1585
                item.prevUntil('.cms-submenu-item-title').last().prev().show();
14✔
1586
            }
1587
        });
1588

1589
        mostRecentItems.hide();
4✔
1590
    },
1591

1592
    /**
1593
     * Toggles collapsable item.
1594
     *
1595
     * @method _toggleCollapsable
1596
     * @private
1597
     * @param {jQuery} el element to toggle
1598
     * @returns {Boolean|void}
1599
     */
1600
    _toggleCollapsable: function toggleCollapsable(el) {
1601
        var that = this;
×
1602
        var id = that._getId(el.parent());
×
1603
        var draggable = el.closest('.cms-draggable');
×
1604
        var items;
1605

1606
        var settings = CMS.settings;
×
1607

1608
        settings.states = settings.states || [];
×
1609

1610
        if (!draggable || !draggable.length) {
×
1611
            return;
×
1612
        }
1613

1614
        // collapsable function and save states
1615
        if (el.hasClass('cms-dragitem-expanded')) {
×
1616
            settings.states.splice($.inArray(id, settings.states), 1);
×
1617
            el
×
1618
                .removeClass('cms-dragitem-expanded')
1619
                .parent()
1620
                .find('> .cms-collapsable-container')
1621
                .addClass('cms-hidden');
1622

1623
            if ($document.data('expandmode')) {
×
1624
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
1625
                if (!items.length) {
×
1626
                    return false;
×
1627
                }
1628
                items.each(function() {
×
1629
                    var item = $(this);
×
1630

1631
                    if (item.hasClass('cms-dragitem-expanded')) {
×
1632
                        that._toggleCollapsable(item);
×
1633
                    }
1634
                });
1635
            }
1636
        } else {
1637
            settings.states.push(id);
×
1638
            el
×
1639
                .addClass('cms-dragitem-expanded')
1640
                .parent()
1641
                .find('> .cms-collapsable-container')
1642
                .removeClass('cms-hidden');
1643

1644
            if ($document.data('expandmode')) {
×
1645
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
1646
                if (!items.length) {
×
1647
                    return false;
×
1648
                }
1649
                items.each(function() {
×
1650
                    var item = $(this);
×
1651

1652
                    if (!item.hasClass('cms-dragitem-expanded')) {
×
1653
                        that._toggleCollapsable(item);
×
1654
                    }
1655
                });
1656
            }
1657
        }
1658

1659
        this._updatePlaceholderCollapseState();
×
1660

1661
        // make sure structurboard gets updated after expanding
1662
        $document.trigger('resize.sideframe');
×
1663

1664
        // save settings
1665
        Helpers.setSettings(settings);
×
1666
    },
1667

1668
    _updatePlaceholderCollapseState() {
1669
        if (this.options.type !== 'plugin' || !this.options.placeholder_id) {
×
1670
            return;
×
1671
        }
1672

1673
        const pluginsOfCurrentPlaceholder = CMS._plugins
×
1674
            .filter(([, o]) => o.placeholder_id === this.options.placeholder_id && o.type === 'plugin')
×
1675
            .map(([, o]) => o.plugin_id);
×
1676

1677
        const openedPlugins = CMS.settings.states;
×
1678
        const closedPlugins = difference(pluginsOfCurrentPlaceholder, openedPlugins);
×
1679
        const areAllRemainingPluginsLeafs = every(closedPlugins, id => {
×
1680
            return !find(
×
1681
                CMS._plugins,
1682
                ([, o]) => o.placeholder_id === this.options.placeholder_id && o.plugin_parent === id
×
1683
            );
1684
        });
1685
        const el = $(`.cms-dragarea-${this.options.placeholder_id} .cms-dragbar-title`);
×
1686
        var settings = CMS.settings;
×
1687

1688
        if (areAllRemainingPluginsLeafs) {
×
1689
            // meaning that all plugins in current placeholder are expanded
1690
            el.addClass('cms-dragbar-title-expanded');
×
1691

1692
            settings.dragbars = settings.dragbars || [];
×
1693
            settings.dragbars.push(this.options.placeholder_id);
×
1694
        } else {
1695
            el.removeClass('cms-dragbar-title-expanded');
×
1696

1697
            settings.dragbars = settings.dragbars || [];
×
1698
            settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1699
        }
1700
    },
1701

1702
    /**
1703
     * Sets up collabspable event handlers.
1704
     *
1705
     * @method _collapsables
1706
     * @private
1707
     * @returns {Boolean|void}
1708
     */
1709
    _collapsables: function() {
1710
        // one time setup
1711
        var that = this;
153✔
1712

1713
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
153✔
1714
        // cancel here if its not a draggable
1715
        if (!this.ui.draggable.length) {
153✔
1716
            return false;
38✔
1717
        }
1718

1719
        var dragitem = this.ui.draggable.find('> .cms-dragitem');
115✔
1720

1721
        // check which button should be shown for collapsemenu
1722
        var els = this.ui.draggable.find('.cms-dragitem-collapsable');
115✔
1723
        var open = els.filter('.cms-dragitem-expanded');
115✔
1724

1725
        if (els.length === open.length && els.length + open.length !== 0) {
115!
1726
            this.ui.draggable.find('.cms-dragbar-title').addClass('cms-dragbar-title-expanded');
×
1727
        }
1728

1729
        // attach events to draggable
1730
        // debounce here required because on some devices click is not triggered,
1731
        // so we consolidate latest click and touch event to run the collapse only once
1732
        dragitem.find('> .cms-dragitem-text').on(
115✔
1733
            Plugin.touchEnd + ' ' + Plugin.click,
1734
            debounce(function() {
1735
                if (!dragitem.hasClass('cms-dragitem-collapsable')) {
×
1736
                    return;
×
1737
                }
1738
                that._toggleCollapsable(dragitem);
×
1739
            }, 0)
1740
        );
1741
    },
1742

1743
    /**
1744
     * Expands all the collapsables in the given placeholder.
1745
     *
1746
     * @method _expandAll
1747
     * @private
1748
     * @param {jQuery} el trigger element that is a child of a placeholder
1749
     * @returns {Boolean|void}
1750
     */
1751
    _expandAll: function(el) {
1752
        var that = this;
×
1753
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1754

1755
        // cancel if there are no items
1756
        if (!items.length) {
×
1757
            return false;
×
1758
        }
1759
        items.each(function() {
×
1760
            var item = $(this);
×
1761

1762
            if (!item.hasClass('cms-dragitem-expanded')) {
×
1763
                that._toggleCollapsable(item);
×
1764
            }
1765
        });
1766

1767
        el.addClass('cms-dragbar-title-expanded');
×
1768

1769
        var settings = CMS.settings;
×
1770

1771
        settings.dragbars = settings.dragbars || [];
×
1772
        settings.dragbars.push(this.options.placeholder_id);
×
1773
        Helpers.setSettings(settings);
×
1774
    },
1775

1776
    /**
1777
     * Collapses all the collapsables in the given placeholder.
1778
     *
1779
     * @method _collapseAll
1780
     * @private
1781
     * @param {jQuery} el trigger element that is a child of a placeholder
1782
     */
1783
    _collapseAll: function(el) {
1784
        var that = this;
×
1785
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1786

1787
        items.each(function() {
×
1788
            var item = $(this);
×
1789

1790
            if (item.hasClass('cms-dragitem-expanded')) {
×
1791
                that._toggleCollapsable(item);
×
1792
            }
1793
        });
1794

1795
        el.removeClass('cms-dragbar-title-expanded');
×
1796

1797
        var settings = CMS.settings;
×
1798

1799
        settings.dragbars = settings.dragbars || [];
×
1800
        settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1801
        Helpers.setSettings(settings);
×
1802
    },
1803

1804
    /**
1805
     * Gets the id of the element, uses CMS.StructureBoard instance.
1806
     *
1807
     * @method _getId
1808
     * @private
1809
     * @param {jQuery} el element to get id from
1810
     * @returns {String}
1811
     */
1812
    _getId: function(el) {
1813
        return CMS.API.StructureBoard.getId(el);
36✔
1814
    },
1815

1816
    /**
1817
     * Gets the ids of the list of elements, uses CMS.StructureBoard instance.
1818
     *
1819
     * @method _getIds
1820
     * @private
1821
     * @param {jQuery} els elements to get id from
1822
     * @returns {String[]}
1823
     */
1824
    _getIds: function(els) {
1825
        return CMS.API.StructureBoard.getIds(els);
×
1826
    },
1827

1828
    /**
1829
     * Traverses the registry to find plugin parents
1830
     *
1831
     * @method _getPluginBreadcrumbs
1832
     * @returns {Object[]} array of breadcrumbs in `{ url, title }` format
1833
     * @private
1834
     */
1835
    _getPluginBreadcrumbs: function _getPluginBreadcrumbs() {
1836
        var breadcrumbs = [];
6✔
1837

1838
        breadcrumbs.unshift({
6✔
1839
            title: this.options.plugin_name,
1840
            url: this.options.urls.edit_plugin
1841
        });
1842

1843
        var findParentPlugin = function(id) {
6✔
1844
            return $.grep(CMS._plugins || [], function(pluginOptions) {
6✔
1845
                return pluginOptions[0] === 'cms-plugin-' + id;
10✔
1846
            })[0];
1847
        };
1848

1849
        var id = this.options.plugin_parent;
6✔
1850
        var data;
1851

1852
        while (id && id !== 'None') {
6✔
1853
            data = findParentPlugin(id);
6✔
1854

1855
            if (!data) {
6✔
1856
                break;
1✔
1857
            }
1858

1859
            breadcrumbs.unshift({
5✔
1860
                title: data[1].plugin_name,
1861
                url: data[1].urls.edit_plugin
1862
            });
1863
            id = data[1].plugin_parent;
5✔
1864
        }
1865

1866
        return breadcrumbs;
6✔
1867
    }
1868
});
1869

1870
Plugin.click = 'click.cms.plugin';
1✔
1871
Plugin.pointerUp = 'pointerup.cms.plugin';
1✔
1872
Plugin.pointerDown = 'pointerdown.cms.plugin';
1✔
1873
Plugin.pointerOverAndOut = 'pointerover.cms.plugin pointerout.cms.plugin';
1✔
1874
Plugin.doubleClick = 'dblclick.cms.plugin';
1✔
1875
Plugin.keyUp = 'keyup.cms.plugin';
1✔
1876
Plugin.keyDown = 'keydown.cms.plugin';
1✔
1877
Plugin.mouseEvents = 'mousedown.cms.plugin mousemove.cms.plugin mouseup.cms.plugin';
1✔
1878
Plugin.touchStart = 'touchstart.cms.plugin';
1✔
1879
Plugin.touchEnd = 'touchend.cms.plugin';
1✔
1880

1881
/**
1882
 * Updates plugin data in CMS._plugins / CMS._instances or creates new
1883
 * plugin instances if they didn't exist
1884
 *
1885
 * @method _updateRegistry
1886
 * @private
1887
 * @static
1888
 * @param {Object[]} plugins plugins data
1889
 */
1890
Plugin._updateRegistry = function _updateRegistry(plugins) {
1✔
1891
    plugins.forEach(pluginData => {
×
1892
        const pluginContainer = `cms-plugin-${pluginData.plugin_id}`;
×
1893
        const pluginIndex = findIndex(CMS._plugins, ([pluginStr]) => pluginStr === pluginContainer);
×
1894

1895
        if (pluginIndex === -1) {
×
1896
            CMS._plugins.push([pluginContainer, pluginData]);
×
1897
            CMS._instances.push(new Plugin(pluginContainer, pluginData));
×
1898
        } else {
1899
            Plugin.aliasPluginDuplicatesMap[pluginData.plugin_id] = false;
×
1900
            CMS._plugins[pluginIndex] = [pluginContainer, pluginData];
×
1901
            CMS._instances[pluginIndex] = new Plugin(pluginContainer, pluginData);
×
1902
        }
1903
    });
1904
};
1905

1906
/**
1907
 * Hides the opened settings menu. By default looks for any open ones.
1908
 *
1909
 * @method _hideSettingsMenu
1910
 * @static
1911
 * @private
1912
 * @param {jQuery} [navEl] element representing the subnav trigger
1913
 */
1914
Plugin._hideSettingsMenu = function(navEl) {
1✔
1915
    var nav = navEl || $('.cms-submenu-btn.cms-btn-active');
20✔
1916

1917
    if (!nav.length) {
20!
1918
        return;
20✔
1919
    }
1920
    nav.removeClass('cms-btn-active');
×
1921

1922
    // set correct active state
1923
    nav.closest('.cms-draggable').data('active', false);
×
1924
    $('.cms-z-index-9999').removeClass('cms-z-index-9999');
×
1925

1926
    nav.siblings('.cms-submenu-dropdown').hide();
×
1927
    nav.siblings('.cms-quicksearch').hide();
×
1928
    // reset search
1929
    nav.siblings('.cms-quicksearch').find('input').val('').trigger(Plugin.keyUp).blur();
×
1930

1931
    // reset relativity
1932
    $('.cms-dragbar').css('position', '');
×
1933
};
1934

1935
/**
1936
 * Initialises handlers that affect all plugins and don't make sense
1937
 * in context of each own plugin instance, e.g. listening for a click on a document
1938
 * to hide plugin settings menu should only be applied once, and not every time
1939
 * CMS.Plugin is instantiated.
1940
 *
1941
 * @method _initializeGlobalHandlers
1942
 * @static
1943
 * @private
1944
 */
1945
Plugin._initializeGlobalHandlers = function _initializeGlobalHandlers() {
1✔
1946
    var timer;
1947
    var clickCounter = 0;
6✔
1948

1949
    Plugin._updateClipboard();
6✔
1950

1951
    // Structureboard initialized too late
1952
    setTimeout(function() {
6✔
1953
        var pluginData = {};
6✔
1954
        var html = '';
6✔
1955

1956
        if (clipboardDraggable.length) {
6✔
1957
            pluginData = find(
5✔
1958
                CMS._plugins,
1959
                ([desc]) => desc === `cms-plugin-${CMS.API.StructureBoard.getId(clipboardDraggable)}`
10✔
1960
            )[1];
1961
            html = clipboardDraggable.parent().html();
5✔
1962
        }
1963
        if (CMS.API && CMS.API.Clipboard) {
6!
1964
            CMS.API.Clipboard.populate(html, pluginData);
6✔
1965
        }
1966
    }, 0);
1967

1968
    $document
6✔
1969
        .off(Plugin.pointerUp)
1970
        .off(Plugin.keyDown)
1971
        .off(Plugin.keyUp)
1972
        .off(Plugin.click, '.cms-plugin a, a:has(.cms-plugin), a.cms-plugin')
1973
        .on(Plugin.pointerUp, function() {
1974
            // call it as a static method, because otherwise we trigger it the
1975
            // amount of times CMS.Plugin is instantiated,
1976
            // which does not make much sense.
1977
            Plugin._hideSettingsMenu();
×
1978
        })
1979
        .on(Plugin.keyDown, function(e) {
1980
            if (e.keyCode === KEYS.SHIFT) {
26!
1981
                $document.data('expandmode', true);
×
1982
                try {
×
1983
                    $('.cms-plugin:hover').last().trigger('mouseenter');
×
1984
                    $('.cms-dragitem:hover').last().trigger('mouseenter');
×
1985
                } catch (err) {}
1986
            }
1987
        })
1988
        .on(Plugin.keyUp, function(e) {
1989
            if (e.keyCode === KEYS.SHIFT) {
23!
1990
                $document.data('expandmode', false);
×
1991
                try {
×
1992
                    $(':hover').trigger('mouseleave');
×
1993
                } catch (err) {}
1994
            }
1995
        })
1996
        .on(Plugin.click, '.cms-plugin a, a:has(.cms-plugin), a.cms-plugin', function(e) {
1997
            var DOUBLECLICK_DELAY = 300;
×
1998

1999
            // prevents single click from messing up the edit call
2000
            // don't go to the link if there is custom js attached to it
2001
            // or if it's clicked along with shift, ctrl, cmd
2002
            if (e.shiftKey || e.ctrlKey || e.metaKey || e.isDefaultPrevented()) {
×
2003
                return;
×
2004
            }
2005
            e.preventDefault();
×
2006
            if (++clickCounter === 1) {
×
2007
                timer = setTimeout(function() {
×
2008
                    var anchor = $(e.target).closest('a');
×
2009

2010
                    clickCounter = 0;
×
2011
                    window.open(anchor.attr('href'), anchor.attr('target') || '_self');
×
2012
                }, DOUBLECLICK_DELAY);
2013
            } else {
2014
                clearTimeout(timer);
×
2015
                clickCounter = 0;
×
2016
            }
2017
        });
2018

2019
    // have to delegate here because there might be plugins that
2020
    // have their content replaced by something dynamic. in case that tool
2021
    // copies the classes - double click to edit would still work
2022
    // also - do not try to highlight render_model_blocks, only actual plugins
2023
    $document.on(Plugin.click, '.cms-plugin:not([class*=cms-render-model])', Plugin._clickToHighlightHandler);
6✔
2024
    $document.on(`${Plugin.pointerOverAndOut} ${Plugin.touchStart}`, '.cms-plugin', function(e) {
6✔
2025
        // required for both, click and touch
2026
        // otherwise propagation won't work to the nested plugin
2027

2028
        e.stopPropagation();
×
2029
        const pluginContainer = $(e.target).closest('.cms-plugin');
×
2030
        const allOptions = pluginContainer.data('cms');
×
2031

2032
        if (!allOptions || !allOptions.length) {
×
2033
            return;
×
2034
        }
2035

2036
        const options = allOptions[0];
×
2037

2038
        if (e.type === 'touchstart') {
×
2039
            CMS.API.Tooltip._forceTouchOnce();
×
2040
        }
2041
        var name = options.plugin_name;
×
2042
        var id = options.plugin_id;
×
2043
        var type = options.type;
×
2044

2045
        if (type === 'generic') {
×
2046
            return;
×
2047
        }
2048
        var placeholderId = CMS.API.StructureBoard.getId($(`.cms-draggable-${id}`).closest('.cms-dragarea'));
×
2049
        var placeholder = $('.cms-placeholder-' + placeholderId);
×
2050

2051
        if (placeholder.length && placeholder.data('cms')) {
×
2052
            name = placeholder.data('cms').name + ': ' + name;
×
2053
        }
2054

2055
        CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
2056
    });
2057

2058
    $document.on(Plugin.click, '.cms-dragarea-static .cms-dragbar', e => {
6✔
2059
        const placeholder = $(e.target).closest('.cms-dragarea');
×
2060

2061
        if (placeholder.hasClass('cms-dragarea-static-expanded') && e.isDefaultPrevented()) {
×
2062
            return;
×
2063
        }
2064

2065
        placeholder.toggleClass('cms-dragarea-static-expanded');
×
2066
    });
2067

2068
    $window.on('blur.cms', () => {
6✔
2069
        $document.data('expandmode', false);
6✔
2070
    });
2071
};
2072

2073
/**
2074
 * @method _isContainingMultiplePlugins
2075
 * @param {jQuery} node to check
2076
 * @static
2077
 * @private
2078
 * @returns {Boolean}
2079
 */
2080
Plugin._isContainingMultiplePlugins = function _isContainingMultiplePlugins(node) {
1✔
2081
    var currentData = node.data('cms');
130✔
2082

2083
    // istanbul ignore if
2084
    if (!currentData) {
130✔
2085
        throw new Error('Provided node is not a cms plugin.');
2086
    }
2087

2088
    var pluginIds = currentData.map(function(pluginData) {
130✔
2089
        return pluginData.plugin_id;
131✔
2090
    });
2091

2092
    if (pluginIds.length > 1) {
130✔
2093
        // another plugin already lives on the same node
2094
        // this only works because the plugins are rendered from
2095
        // the bottom to the top (leaf to root)
2096
        // meaning the deepest plugin is always first
2097
        return true;
1✔
2098
    }
2099

2100
    return false;
129✔
2101
};
2102

2103
/**
2104
 * Shows and immediately fades out a success notification (when
2105
 * plugin was successfully moved.
2106
 *
2107
 * @method _highlightPluginStructure
2108
 * @private
2109
 * @static
2110
 * @param {jQuery} el draggable element
2111
 */
2112
// eslint-disable-next-line no-magic-numbers
2113
Plugin._highlightPluginStructure = function _highlightPluginStructure(
1✔
2114
    el,
2115
    // eslint-disable-next-line no-magic-numbers
2116
    { successTimeout = 200, delay = 1500, seeThrough = false }
×
2117
) {
2118
    const tpl = $(`
×
2119
        <div class="cms-dragitem-success ${seeThrough ? 'cms-plugin-overlay-see-through' : ''}">
×
2120
        </div>
2121
    `);
2122

2123
    el.addClass('cms-draggable-success').append(tpl);
×
2124
    // start animation
2125
    if (successTimeout) {
×
2126
        setTimeout(() => {
×
2127
            tpl.fadeOut(successTimeout, function() {
×
2128
                $(this).remove();
×
2129
                el.removeClass('cms-draggable-success');
×
2130
            });
2131
        }, delay);
2132
    }
2133
    // make sure structurboard gets updated after success
2134
    $(Helpers._getWindow()).trigger('resize.sideframe');
×
2135
};
2136

2137
/**
2138
 * Highlights plugin in content mode
2139
 *
2140
 * @method _highlightPluginContent
2141
 * @private
2142
 * @static
2143
 * @param {String|Number} pluginId
2144
 */
2145
Plugin._highlightPluginContent = function _highlightPluginContent(
1✔
2146
    pluginId,
2147
    // eslint-disable-next-line no-magic-numbers
2148
    { successTimeout = 200, seeThrough = false, delay = 1500, prominent = false } = {}
5✔
2149
) {
2150
    var coordinates = {};
1✔
2151
    var positions = [];
1✔
2152
    var OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO = 0.2;
1✔
2153

2154
    $('.cms-plugin-' + pluginId).each(function() {
1✔
2155
        var el = $(this);
1✔
2156
        var offset = el.offset();
1✔
2157
        var ml = parseInt(el.css('margin-left'), 10);
1✔
2158
        var mr = parseInt(el.css('margin-right'), 10);
1✔
2159
        var mt = parseInt(el.css('margin-top'), 10);
1✔
2160
        var mb = parseInt(el.css('margin-bottom'), 10);
1✔
2161
        var width = el.outerWidth();
1✔
2162
        var height = el.outerHeight();
1✔
2163

2164
        if (width === 0 && height === 0) {
1!
2165
            return;
×
2166
        }
2167

2168
        if (isNaN(ml)) {
1!
2169
            ml = 0;
×
2170
        }
2171
        if (isNaN(mr)) {
1!
2172
            mr = 0;
×
2173
        }
2174
        if (isNaN(mt)) {
1!
2175
            mt = 0;
×
2176
        }
2177
        if (isNaN(mb)) {
1!
2178
            mb = 0;
×
2179
        }
2180

2181
        positions.push({
1✔
2182
            x1: offset.left - ml,
2183
            x2: offset.left + width + mr,
2184
            y1: offset.top - mt,
2185
            y2: offset.top + height + mb
2186
        });
2187
    });
2188

2189
    if (positions.length === 0) {
1!
2190
        return;
×
2191
    }
2192

2193
    // turns out that offset calculation will be off by toolbar height if
2194
    // position is set to "relative" on html element.
2195
    var html = $('html');
1✔
2196
    var htmlMargin = html.css('position') === 'relative' ? parseInt($('html').css('margin-top'), 10) : 0;
1!
2197

2198
    coordinates.left = Math.min(...positions.map(pos => pos.x1));
1✔
2199
    coordinates.top = Math.min(...positions.map(pos => pos.y1)) - htmlMargin;
1✔
2200
    coordinates.width = Math.max(...positions.map(pos => pos.x2)) - coordinates.left;
1✔
2201
    coordinates.height = Math.max(...positions.map(pos => pos.y2)) - coordinates.top - htmlMargin;
1✔
2202

2203
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2204

2205
    $(
1✔
2206
        `
2207
        <div class="
2208
            cms-plugin-overlay
2209
            cms-dragitem-success
2210
            cms-plugin-overlay-${pluginId}
2211
            ${seeThrough ? 'cms-plugin-overlay-see-through' : ''}
1!
2212
            ${prominent ? 'cms-plugin-overlay-prominent' : ''}
1!
2213
        "
2214
            data-success-timeout="${successTimeout}"
2215
        >
2216
        </div>
2217
    `
2218
    )
2219
        .css(coordinates)
2220
        .css({
2221
            zIndex: 9999
2222
        })
2223
        .appendTo($('body'));
2224

2225
    if (successTimeout) {
1!
2226
        setTimeout(() => {
1✔
2227
            $(`.cms-plugin-overlay-${pluginId}`).fadeOut(successTimeout, function() {
1✔
2228
                $(this).remove();
1✔
2229
            });
2230
        }, delay);
2231
    }
2232
};
2233

2234
Plugin._clickToHighlightHandler = function _clickToHighlightHandler() {
1✔
2235
    if (CMS.settings.mode !== 'structure') {
×
2236
        return;
×
2237
    }
2238
    // FIXME refactor into an object
2239
    CMS.API.StructureBoard._showAndHighlightPlugin(200, true); // eslint-disable-line no-magic-numbers
×
2240
};
2241

2242
Plugin._removeHighlightPluginContent = function(pluginId) {
1✔
2243
    $(`.cms-plugin-overlay-${pluginId}[data-success-timeout=0]`).remove();
×
2244
};
2245

2246
Plugin.aliasPluginDuplicatesMap = {};
1✔
2247
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2248

2249
// istanbul ignore next
2250
Plugin._initializeTree = function _initializeTree() {
2251
    const plugins = {};
2252

2253
    document.body.querySelectorAll(
2254
        'script[data-cms-plugin], ' +
2255
        'script[data-cms-placeholder], ' +
2256
        'script[data-cms-general]'
2257
    ).forEach(script => {
2258
        plugins[script.id] = JSON.parse(script.textContent || '{}');
2259
    });
2260

2261
    CMS._plugins = Object.entries(plugins);
2262
    CMS._instances = CMS._plugins.map(function(args) {
2263
        return new CMS.Plugin(args[0], args[1]);
2264
    });
2265

2266
    // return the cms plugin instances just created
2267
    return CMS._instances;
2268
};
2269

2270
Plugin._updateClipboard = function _updateClipboard() {
1✔
2271
    clipboardDraggable = $('.cms-draggable-from-clipboard:first');
7✔
2272
};
2273

2274
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2275
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2276

2277
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2278

2279
    if (Helpers._isStorageSupported) {
2!
2280
        localStorage.setItem('cms-plugin-usage', JSON.stringify(pluginUsageMap));
×
2281
    }
2282
};
2283

2284
Plugin._removeAddPluginPlaceholder = function removeAddPluginPlaceholder() {
1✔
2285
    // this can't be cached since they are created and destroyed all over the place
2286
    $('.cms-add-plugin-placeholder').remove();
10✔
2287
};
2288

2289
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2290
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2291
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2292

2293
    // Re-read front-end editable fields ("general" plugins) from DOM
2294
    document.body.querySelectorAll('script[data-cms-general]').forEach(script => {
4✔
2295
        CMS._plugins.push([script.id, JSON.parse(script.textContent)]);
×
2296
    });
2297
    // Remove duplicates
2298
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2299

2300
    CMS._instances.forEach(instance => {
4✔
2301
        if (instance.options.type === 'placeholder') {
5✔
2302
            instance._setupUI(`cms-placeholder-${instance.options.placeholder_id}`);
2✔
2303
            instance._ensureData();
2✔
2304
            instance.ui.container.data('cms', instance.options);
2✔
2305
            instance._setPlaceholder();
2✔
2306
        }
2307
    });
2308

2309
    CMS._instances.forEach(instance => {
4✔
2310
        if (instance.options.type === 'plugin') {
5✔
2311
            instance._setupUI(`cms-plugin-${instance.options.plugin_id}`);
2✔
2312
            instance._ensureData();
2✔
2313
            instance.ui.container.data('cms').push(instance.options);
2✔
2314
            instance._setPluginContentEvents();
2✔
2315
        }
2316
    });
2317

2318
    CMS._plugins.forEach(([type, opts]) => {
4✔
2319
        if (opts.type !== 'placeholder' && opts.type !== 'plugin') {
16✔
2320
            const instance = find(
8✔
2321
                CMS._instances,
2322
                i => i.options.type === opts.type && Number(i.options.plugin_id) === Number(opts.plugin_id)
13✔
2323
            );
2324

2325
            if (instance) {
8✔
2326
                // update
2327
                instance._setupUI(type);
1✔
2328
                instance._ensureData();
1✔
2329
                instance.ui.container.data('cms').push(instance.options);
1✔
2330
                instance._setGeneric();
1✔
2331
            } else {
2332
                // create
2333
                CMS._instances.push(new Plugin(type, opts));
7✔
2334
            }
2335
        }
2336
    });
2337
};
2338

2339
Plugin._getPluginById = function(id) {
1✔
2340
    return find(CMS._instances, ({ options }) => options.type === 'plugin' && Number(options.plugin_id) === Number(id));
20!
2341
};
2342

2343
Plugin._updatePluginPositions = function(placeholder_id) {
1✔
2344
    // TODO can this be done in pure js? keep a tree model of the structure
2345
    // on the placeholder and update things there?
2346
    const plugins = $(`.cms-dragarea-${placeholder_id} .cms-draggable`).toArray();
10✔
2347

2348
    plugins.forEach((element, index) => {
10✔
2349
        const pluginId = CMS.API.StructureBoard.getId($(element));
20✔
2350
        const instance = Plugin._getPluginById(pluginId);
20✔
2351

2352
        if (!instance) {
20!
2353
            return;
20✔
2354
        }
2355

2356
        instance.options.position = index + 1;
×
2357
    });
2358
};
2359

2360
Plugin._recalculatePluginPositions = function(action, data) {
1✔
2361
    if (action === 'MOVE') {
×
2362
        // le sigh - recalculate all placeholders cause we don't know from where the
2363
        // plugin was moved from
2364
        filter(CMS._instances, ({ options }) => options.type === 'placeholder')
×
2365
            .map(({ options }) => options.placeholder_id)
×
2366
            .forEach(placeholder_id => Plugin._updatePluginPositions(placeholder_id));
×
2367
    } else if (data.placeholder_id) {
×
2368
        Plugin._updatePluginPositions(data.placeholder_id);
×
2369
    }
2370
};
2371

2372
// shorthand for jQuery(document).ready();
2373
$(Plugin._initializeGlobalHandlers);
1✔
2374

2375
export default Plugin;
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