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

divio / django-cms / #29444

19 Feb 2025 08:03AM UTC coverage: 75.287% (-0.03%) from 75.316%
#29444

push

travis-ci

web-flow
Merge 6879a7be6 into 4777a022c

1071 of 1620 branches covered (66.11%)

166 of 216 new or added lines in 3 files covered. (76.85%)

276 existing lines in 2 files now uncovered.

2559 of 3399 relevant lines covered (75.29%)

26.35 hits per line

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

59.04
/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
            // so it's possible that multiple plugins (more often generics) are rendered
127
            // in different places. e.g. page menu in the header and in the footer
128
            // so first, we find all the template tags, then put them in a structure like this:
129
            // [[start, end], [start, end], ...]
130
            //
131
            // in case of plugins it means that it's aliased plugin or a plugin in a duplicated
132
            // static placeholder (for whatever reason)
133
            const contentWrappers = wrapper.toArray().reduce((wrappers, elem) => {
136✔
134
                if (elem.classList.contains('cms-plugin-start') || wrappers.length === 0) {
274✔
135
                    // start new wrapper
136
                    wrappers.push([elem]);
137✔
137
                } else {
138
                    // belongs to previous wrapper
139
                    wrappers.at(-1).push(elem);
137✔
140
                }
141

142
                return wrappers;
274✔
143
            }, []);
144

145
            if (contentWrappers[0][0].tagName === 'TEMPLATE') {
136!
146
                // then - if the content is bracketed by two template tages - we map that structure into an array of
147
                // jquery collections from which we filter out empty ones
148
                contents = contentWrappers
136✔
149
                    .map(items => {
150
                        const templateStart = $(items[0]);
137✔
151
                        const className = templateStart.attr('class').replace('cms-plugin-start', '');
137✔
152
                        const position = templateStart.attr('data-cms-position');
137✔
153
                        let itemContents = $(nextUntil(templateStart[0], container));
137✔
154

155
                        itemContents.each((index, el) => {
137✔
156
                            // if it's a non-space top-level text node - wrap it in `cms-plugin`
157
                            if (el.nodeType === Node.TEXT_NODE && !el.textContent.match(/^\s*$/)) {
158✔
158
                                var element = $(el);
10✔
159

160
                                element.wrap('<cms-plugin class="cms-plugin-text-node"></cms-plugin>');
10✔
161
                                itemContents[index] = element.parent()[0];
10✔
162
                            }
163
                        });
164

165
                        // otherwise we don't really need text nodes or comment nodes or empty text nodes
166
                        itemContents = itemContents.filter(function() {
137✔
167
                            return this.nodeType !== Node.TEXT_NODE && this.nodeType !== Node.COMMENT_NODE;
158✔
168
                        });
169

170
                        itemContents.addClass(`cms-plugin ${className}`);
137✔
171
                        itemContents.first().addClass('cms-plugin-start').attr('data-cms-position', position);
137✔
172
                        itemContents.last().addClass('cms-plugin-end').attr('data-cms-position', position);
137✔
173
                        return itemContents;
137✔
174
                    })
175
                    .filter(v => v.length);
137✔
176

177
                wrapper.filter('template').remove();
136✔
178
                if (contents.length) {
136!
179
                    // and then reduce it to one big collection
180
                    contents = contents.reduce((collection, items) => collection.add(items), $());
137✔
181
                }
182
            } else {
NEW
183
                contents = wrapper;
×
184
            }
185
        } else {
186
            contents = wrapper;
43✔
187
        }
188

189
        // in clipboard can be non-existent
190
        if (!contents.length) {
179✔
191
            contents = $('<div></div>');
11✔
192
        }
193

194
        this.ui = this.ui || {};
179✔
195
        this.ui.container = contents;
179✔
196
    },
197

198
    /**
199
     * Sets up behaviours and ui for placeholder.
200
     *
201
     * @method _setPlaceholder
202
     * @private
203
     */
204
    _setPlaceholder: function() {
205
        var that = this;
23✔
206

207
        this.ui.dragbar = $('.cms-dragbar-' + this.options.placeholder_id);
23✔
208
        this.ui.draggables = this.ui.dragbar.closest('.cms-dragarea').find('> .cms-draggables');
23✔
209
        this.ui.submenu = this.ui.dragbar.find('.cms-submenu-settings');
23✔
210
        var title = this.ui.dragbar.find('.cms-dragbar-title');
23✔
211
        var togglerLinks = this.ui.dragbar.find('.cms-dragbar-toggler a');
23✔
212
        var expanded = 'cms-dragbar-title-expanded';
23✔
213

214
        // register the subnav on the placeholder
215
        this._setSettingsMenu(this.ui.submenu);
23✔
216
        this._setAddPluginModal(this.ui.dragbar.find('.cms-submenu-add'));
23✔
217

218
        // istanbul ignore next
219
        CMS.settings.dragbars = CMS.settings.dragbars || []; // expanded dragbars array
220

221
        // enable expanding/collapsing globally within the placeholder
222
        togglerLinks.off(Plugin.click).on(Plugin.click, function(e) {
23✔
223
            e.preventDefault();
×
UNCOV
224
            if (title.hasClass(expanded)) {
×
225
                that._collapseAll(title);
×
226
            } else {
UNCOV
227
                that._expandAll(title);
×
228
            }
229
        });
230

231
        if ($.inArray(this.options.placeholder_id, CMS.settings.dragbars) !== -1) {
23!
UNCOV
232
            title.addClass(expanded);
×
233
        }
234

235
        this._checkIfPasteAllowed();
23✔
236
    },
237

238
    /**
239
     * Sets up behaviours and ui for plugin.
240
     *
241
     * @method _setPlugin
242
     * @private
243
     */
244
    _setPlugin: function() {
245
        if (isStructureReady()) {
130!
246
            this._setPluginStructureEvents();
130✔
247
        }
248
        if (isContentReady()) {
130!
249
            this._setPluginContentEvents();
130✔
250
        }
251
    },
252

253
    _setPluginStructureEvents: function _setPluginStructureEvents() {
254
        var that = this;
130✔
255

256
        // filling up ui object
257
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
130✔
258
        this.ui.dragitem = this.ui.draggable.find('> .cms-dragitem');
130✔
259
        this.ui.draggables = this.ui.draggable.find('> .cms-draggables');
130✔
260
        this.ui.submenu = this.ui.dragitem.find('.cms-submenu');
130✔
261

262
        this.ui.draggable.data('cms', this.options);
130✔
263

264
        this.ui.dragitem.on(Plugin.doubleClick, this._dblClickToEditHandler.bind(this));
130✔
265

266
        // adds listener for all plugin updates
267
        this.ui.draggable.off('cms-plugins-update').on('cms-plugins-update', function(e, eventData) {
130✔
UNCOV
268
            e.stopPropagation();
×
UNCOV
269
            that.movePlugin(null, eventData);
×
270
        });
271

272
        // adds listener for copy/paste updates
273
        this.ui.draggable.off('cms-paste-plugin-update').on('cms-paste-plugin-update', function(e, eventData) {
130✔
274
            e.stopPropagation();
5✔
275

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

278
            // find out new placeholder id
279
            var placeholder_id = that._getId(dragitem.closest('.cms-dragarea'));
5✔
280

281
            // if placeholder_id is empty, cancel
282
            if (!placeholder_id) {
5!
UNCOV
283
                return false;
×
284
            }
285

286
            var data = dragitem.data('cms');
5✔
287

288
            data.target = placeholder_id;
5✔
289
            data.parent = that._getId(dragitem.parent().closest('.cms-draggable'));
5✔
290
            data.move_a_copy = true;
5✔
291

292
            // expand the plugin we paste to
293
            CMS.settings.states.push(data.parent);
5✔
294
            Helpers.setSettings(CMS.settings);
5✔
295

296
            that.movePlugin(data);
5✔
297
        });
298

299
        setTimeout(() => {
130✔
300
            this.ui.dragitem
130✔
301
                .on('mouseenter', e => {
302
                    e.stopPropagation();
×
UNCOV
303
                    if (!$document.data('expandmode')) {
×
304
                        return;
×
305
                    }
UNCOV
306
                    if (this.ui.draggable.find('> .cms-dragitem > .cms-plugin-disabled').length) {
×
307
                        return;
×
308
                    }
UNCOV
309
                    if (!CMS.API.StructureBoard.ui.container.hasClass('cms-structure-condensed')) {
×
310
                        return;
×
311
                    }
UNCOV
312
                    if (CMS.API.StructureBoard.dragging) {
×
UNCOV
313
                        return;
×
314
                    }
315
                    // eslint-disable-next-line no-magic-numbers
UNCOV
316
                    Plugin._highlightPluginContent(this.options.plugin_id, { successTimeout: 0, seeThrough: true });
×
317
                })
318
                .on('mouseleave', e => {
UNCOV
319
                    if (!CMS.API.StructureBoard.ui.container.hasClass('cms-structure-condensed')) {
×
320
                        return;
×
321
                    }
322
                    e.stopPropagation();
×
323
                    // eslint-disable-next-line no-magic-numbers
UNCOV
324
                    Plugin._removeHighlightPluginContent(this.options.plugin_id);
×
325
                });
326
            // attach event to the plugin menu
327
            this._setSettingsMenu(this.ui.submenu);
130✔
328

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

332
            // clickability of "Paste" menu item
333
            this._checkIfPasteAllowed();
130✔
334
        });
335
    },
336

337
    _dblClickToEditHandler: function _dblClickToEditHandler(e) {
UNCOV
338
        var that = this;
×
339
        var disabled = $(e.currentTarget).closest('.cms-drag-disabled');
×
340

UNCOV
341
        e.preventDefault();
×
342
        e.stopPropagation();
×
343

UNCOV
344
        if (!disabled.length) {
×
UNCOV
345
            that.editPlugin(
×
346
                Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
347
                that.options.plugin_name,
348
                that._getPluginBreadcrumbs()
349
            );
350
        }
351
    },
352

353
    _setPluginContentEvents: function _setPluginContentEvents() {
354
        const pluginDoubleClickEvent = this._getNamepacedEvent(Plugin.doubleClick);
130✔
355

356
        this.ui.container
130✔
357
            .off('mouseover.cms.plugins')
358
            .on('mouseover.cms.plugins', e => {
UNCOV
359
                if (!$document.data('expandmode')) {
×
360
                    return;
×
361
                }
UNCOV
362
                if (CMS.settings.mode !== 'structure') {
×
363
                    return;
×
364
                }
365
                e.stopPropagation();
×
366
                $('.cms-dragitem-success').remove();
×
UNCOV
367
                $('.cms-draggable-success').removeClass('cms-draggable-success');
×
UNCOV
368
                CMS.API.StructureBoard._showAndHighlightPlugin(0, true); // eslint-disable-line no-magic-numbers
×
369
            })
370
            .off('mouseout.cms.plugins')
371
            .on('mouseout.cms.plugins', e => {
UNCOV
372
                if (CMS.settings.mode !== 'structure') {
×
373
                    return;
×
374
                }
375
                e.stopPropagation();
×
376
                if (this.ui.draggable && this.ui.draggable.length) {
×
UNCOV
377
                    this.ui.draggable.find('.cms-dragitem-success').remove();
×
UNCOV
378
                    this.ui.draggable.removeClass('cms-draggable-success');
×
379
                }
380
                // Plugin._removeHighlightPluginContent(this.options.plugin_id);
381
            });
382

383
        if (!Plugin._isContainingMultiplePlugins(this.ui.container)) {
130✔
384
            $document
129✔
385
                .off(pluginDoubleClickEvent, `.cms-plugin-${this.options.plugin_id}`)
386
                .on(
387
                    pluginDoubleClickEvent,
388
                    `.cms-plugin-${this.options.plugin_id}`,
389
                    this._dblClickToEditHandler.bind(this)
390
                );
391
        }
392
    },
393

394
    /**
395
     * Sets up behaviours and ui for generics.
396
     * Generics do not show up in structure board.
397
     *
398
     * @method _setGeneric
399
     * @private
400
     */
401
    _setGeneric: function() {
402
        var that = this;
24✔
403

404
        // adds double click to edit
405
        this.ui.container.off(Plugin.doubleClick).on(Plugin.doubleClick, function(e) {
24✔
406
            e.preventDefault();
×
UNCOV
407
            e.stopPropagation();
×
UNCOV
408
            that.editPlugin(Helpers.updateUrlWithPath(that.options.urls.edit_plugin), that.options.plugin_name, []);
×
409
        });
410

411
        // adds edit tooltip
412
        this.ui.container
24✔
413
            .off(Plugin.pointerOverAndOut + ' ' + Plugin.touchStart)
414
            .on(Plugin.pointerOverAndOut + ' ' + Plugin.touchStart, function(e) {
UNCOV
415
                if (e.type !== 'touchstart') {
×
416
                    e.stopPropagation();
×
417
                }
UNCOV
418
                var name = that.options.plugin_name;
×
419
                var id = that.options.plugin_id;
×
420

UNCOV
421
                CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
422
            });
423
    },
424

425
    /**
426
     * Checks if paste is allowed into current plugin/placeholder based
427
     * on restrictions we have. Also determines which tooltip to show.
428
     *
429
     * WARNING: this relies on clipboard plugins always being instantiated
430
     * first, so they have data('cms') by the time this method is called.
431
     *
432
     * @method _checkIfPasteAllowed
433
     * @private
434
     * @returns {Boolean}
435
     */
436
    _checkIfPasteAllowed: function _checkIfPasteAllowed() {
437
        var pasteButton = this.ui.dropdown.find('[data-rel=paste]');
151✔
438
        var pasteItem = pasteButton.parent();
151✔
439

440
        if (!clipboardDraggable.length) {
151✔
441
            pasteItem.addClass('cms-submenu-item-disabled');
86✔
442
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
86✔
443
            pasteItem.find('.cms-submenu-item-paste-tooltip-empty').css('display', 'block');
86✔
444
            return false;
86✔
445
        }
446

447
        if (this.ui.draggable && this.ui.draggable.hasClass('cms-draggable-disabled')) {
65✔
448
            pasteItem.addClass('cms-submenu-item-disabled');
45✔
449
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
45✔
450
            pasteItem.find('.cms-submenu-item-paste-tooltip-disabled').css('display', 'block');
45✔
451
            return false;
45✔
452
        }
453

454
        var bounds = this.options.plugin_restriction;
20✔
455

456
        if (clipboardDraggable.data('cms')) {
20!
457
            var clipboardPluginData = clipboardDraggable.data('cms');
20✔
458
            var type = clipboardPluginData.plugin_type;
20✔
459
            var parent_bounds = $.grep(clipboardPluginData.plugin_parent_restriction, function(restriction) {
20✔
460
                // special case when PlaceholderPlugin has a parent restriction named "0"
461
                return restriction !== '0';
20✔
462
            });
463
            var currentPluginType = this.options.plugin_type;
20✔
464

465
            if (
20✔
466
                (bounds.length && $.inArray(type, bounds) === -1) ||
60!
467
                (parent_bounds.length && $.inArray(currentPluginType, parent_bounds) === -1)
468
            ) {
469
                pasteItem.addClass('cms-submenu-item-disabled');
15✔
470
                pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
15✔
471
                pasteItem.find('.cms-submenu-item-paste-tooltip-restricted').css('display', 'block');
15✔
472
                return false;
15✔
473
            }
474
        } else {
UNCOV
475
            return false;
×
476
        }
477

478
        pasteItem.find('a').removeAttr('tabindex').removeAttr('aria-disabled');
5✔
479
        pasteItem.removeClass('cms-submenu-item-disabled');
5✔
480

481
        return true;
5✔
482
    },
483

484
    /**
485
     * Calls api to create a plugin and then proceeds to edit it.
486
     *
487
     * @method addPlugin
488
     * @param {String} type type of the plugin, e.g "Bootstrap3ColumnCMSPlugin"
489
     * @param {String} name name of the plugin, e.g. "Column"
490
     * @param {String} parent id of a parent plugin
491
     * @param {Boolean} showAddForm if false, will NOT show the add form
492
     * @param {Number} position (optional) position of the plugin
493
     */
494
    // eslint-disable-next-line max-params
495
    addPlugin: function(type, name, parent, showAddForm = true, position) {
2✔
496
        var params = {
4✔
497
            placeholder_id: this.options.placeholder_id,
498
            plugin_type: type,
499
            cms_path: path,
500
            plugin_language: CMS.config.request.language,
501
            plugin_position: position || this._getPluginAddPosition()
8✔
502
        };
503

504
        if (parent) {
4✔
505
            params.plugin_parent = parent;
2✔
506
        }
507
        var url = this.options.urls.add_plugin + '?' + $.param(params);
4✔
508

509
        const modal = new Modal({
4✔
510
            onClose: this.options.onClose || false,
7✔
511
            redirectOnClose: this.options.redirectOnClose || false
7✔
512
        });
513

514
        if (showAddForm) {
4✔
515
            modal.open({
3✔
516
                url: url,
517
                title: name
518
            });
519
        } else {
520
            // Also open the modal but without the content. Instead create a form and immediately submit it.
521
            modal.open({
1✔
522
                url: '#',
523
                title: name
524
            });
525
            if (modal.ui) {
1!
526
                // Hide the plugin type selector modal if it's open
527
                modal.ui.modal.hide();
1✔
528
            }
529
            const contents = modal.ui.frame.find('iframe').contents();
1✔
530
            const body = contents.find('body');
1✔
531

532
            body.append(`<form method="post" action="${url}" style="display: none;">
1✔
533
                <input type="hidden" name="csrfmiddlewaretoken" value="${CMS.config.csrf}"></form>`);
534
            body.find('form').submit();
1✔
535
        }
536
        this.modal = modal;
4✔
537

538
        Helpers.removeEventListener('modal-closed.add-plugin');
4✔
539
        Helpers.addEventListener('modal-closed.add-plugin', (e, { instance }) => {
4✔
540
            if (instance !== modal) {
1!
UNCOV
541
                return;
×
542
            }
543
            Plugin._removeAddPluginPlaceholder();
1✔
544
        });
545
    },
546

547
    _getPluginAddPosition: function() {
UNCOV
548
        if (this.options.type === 'placeholder') {
×
UNCOV
549
            return $(`.cms-dragarea-${this.options.placeholder_id} .cms-draggable`).length + 1;
×
550
        }
551

552
        // assume plugin now
553
        // would prefer to get the information from the tree, but the problem is that the flat data
554
        // isn't sorted by position
555
        const maybeChildren = this.ui.draggable.find('.cms-draggable');
×
556

UNCOV
557
        if (maybeChildren.length) {
×
558
            const lastChild = maybeChildren.last();
×
559

560
            const lastChildInstance = Plugin._getPluginById(this._getId(lastChild));
×
561

UNCOV
562
            return lastChildInstance.options.position + 1;
×
563
        }
564

UNCOV
565
        return this.options.position + 1;
×
566
    },
567

568
    /**
569
     * Opens the modal for editing a plugin.
570
     *
571
     * @method editPlugin
572
     * @param {String} url editing url
573
     * @param {String} name Name of the plugin, e.g. "Column"
574
     * @param {Object[]} breadcrumb array of objects representing a breadcrumb,
575
     *     each item is `{ title: 'string': url: 'string' }`
576
     */
577
    editPlugin: function(url, name, breadcrumb) {
578
        // trigger modal window
579
        var modal = new Modal({
3✔
580
            onClose: this.options.onClose || false,
6✔
581
            redirectOnClose: this.options.redirectOnClose || false
6✔
582
        });
583

584
        this.modal = modal;
3✔
585

586
        Helpers.removeEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin');
3✔
587
        Helpers.addEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin', (e, { instance }) => {
3✔
588
            if (instance === modal) {
1!
589
                // cannot be cached
590
                Plugin._removeAddPluginPlaceholder();
1✔
591
            }
592
        });
593
        modal.open({
3✔
594
            url: url,
595
            title: name,
596
            breadcrumbs: breadcrumb,
597
            width: 850
598
        });
599
    },
600

601
    /**
602
     * Used for copying _and_ pasting a plugin. If either of params
603
     * is present method assumes that it's "paste" and will make a call
604
     * to api to insert current plugin to specified `options.target_plugin_id`
605
     * or `options.target_placeholder_id`. Copying a plugin also first
606
     * clears the clipboard.
607
     *
608
     * @method copyPlugin
609
     * @param {Object} [opts=this.options]
610
     * @param {String} source_language
611
     * @returns {Boolean|void}
612
     */
613
    // eslint-disable-next-line complexity
614
    copyPlugin: function(opts, source_language) {
615
        // cancel request if already in progress
616
        if (CMS.API.locked) {
9✔
617
            return false;
1✔
618
        }
619
        CMS.API.locked = true;
8✔
620

621
        // set correct options (don't mutate them)
622
        var options = $.extend({}, opts || this.options);
8✔
623
        var sourceLanguage = source_language;
8✔
624
        let copyingFromLanguage = false;
8✔
625

626
        if (sourceLanguage) {
8✔
627
            copyingFromLanguage = true;
1✔
628
            options.target = options.placeholder_id;
1✔
629
            options.plugin_id = '';
1✔
630
            options.parent = '';
1✔
631
        } else {
632
            sourceLanguage = CMS.config.request.language;
7✔
633
        }
634

635
        var data = {
8✔
636
            source_placeholder_id: options.placeholder_id,
637
            source_plugin_id: options.plugin_id || '',
9✔
638
            source_language: sourceLanguage,
639
            target_plugin_id: options.parent || '',
16✔
640
            target_placeholder_id: options.target || CMS.config.clipboard.id,
15✔
641
            csrfmiddlewaretoken: CMS.config.csrf,
642
            target_language: CMS.config.request.language
643
        };
644
        var request = {
8✔
645
            type: 'POST',
646
            url: Helpers.updateUrlWithPath(options.urls.copy_plugin),
647
            data: data,
648
            success: function(response) {
649
                CMS.API.Messages.open({
2✔
650
                    message: CMS.config.lang.success
651
                });
652
                if (copyingFromLanguage) {
2!
UNCOV
653
                    CMS.API.StructureBoard.invalidateState('PASTE', $.extend({}, data, response));
×
654
                } else {
655
                    CMS.API.StructureBoard.invalidateState('COPY', response);
2✔
656
                }
657
                CMS.API.locked = false;
2✔
658
                hideLoader();
2✔
659
            },
660
            error: function(jqXHR) {
661
                CMS.API.locked = false;
3✔
662
                var msg = CMS.config.lang.error;
3✔
663

664
                // trigger error
665
                CMS.API.Messages.open({
3✔
666
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
4✔
667
                    error: true
668
                });
669
            }
670
        };
671

672
        $.ajax(request);
8✔
673
    },
674

675
    /**
676
     * Essentially clears clipboard and moves plugin to a clipboard
677
     * placholder through `movePlugin`.
678
     *
679
     * @method cutPlugin
680
     * @returns {Boolean|void}
681
     */
682
    cutPlugin: function() {
683
        // if cut is once triggered, prevent additional actions
684
        if (CMS.API.locked) {
9✔
685
            return false;
1✔
686
        }
687
        CMS.API.locked = true;
8✔
688

689
        var that = this;
8✔
690
        var data = {
8✔
691
            placeholder_id: CMS.config.clipboard.id,
692
            plugin_id: this.options.plugin_id,
693
            plugin_parent: '',
694
            target_language: CMS.config.request.language,
695
            csrfmiddlewaretoken: CMS.config.csrf
696
        };
697

698
        // move plugin
699
        $.ajax({
8✔
700
            type: 'POST',
701
            url: Helpers.updateUrlWithPath(that.options.urls.move_plugin),
702
            data: data,
703
            success: function(response) {
704
                CMS.API.locked = false;
4✔
705
                CMS.API.Messages.open({
4✔
706
                    message: CMS.config.lang.success
707
                });
708
                CMS.API.StructureBoard.invalidateState('CUT', $.extend({}, data, response));
4✔
709
                hideLoader();
4✔
710
            },
711
            error: function(jqXHR) {
712
                CMS.API.locked = false;
3✔
713
                var msg = CMS.config.lang.error;
3✔
714

715
                // trigger error
716
                CMS.API.Messages.open({
3✔
717
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
4✔
718
                    error: true
719
                });
720
                hideLoader();
3✔
721
            }
722
        });
723
    },
724

725
    /**
726
     * Method is called when you click on the paste button on the plugin.
727
     * Uses existing solution of `copyPlugin(options)`
728
     *
729
     * @method pastePlugin
730
     */
731
    pastePlugin: function() {
732
        var id = this._getId(clipboardDraggable);
5✔
733
        var eventData = {
5✔
734
            id: id
735
        };
736

737
        const clipboardDraggableClone = clipboardDraggable.clone(true, true);
5✔
738

739
        clipboardDraggableClone.appendTo(this.ui.draggables);
5✔
740
        if (this.options.plugin_id) {
5✔
741
            StructureBoard.actualizePluginCollapseStatus(this.options.plugin_id);
4✔
742
        }
743
        this.ui.draggables.trigger('cms-structure-update', [eventData]);
5✔
744
        clipboardDraggableClone.trigger('cms-paste-plugin-update', [eventData]);
5✔
745
    },
746

747
    /**
748
     * Moves plugin by querying the API and then updates some UI parts
749
     * to reflect that the page has changed.
750
     *
751
     * @method movePlugin
752
     * @param {Object} [opts=this.options]
753
     * @param {String} [opts.placeholder_id]
754
     * @param {String} [opts.plugin_id]
755
     * @param {String} [opts.plugin_parent]
756
     * @param {Boolean} [opts.move_a_copy]
757
     * @returns {Boolean|void}
758
     */
759
    movePlugin: function(opts) {
760
        // cancel request if already in progress
761
        if (CMS.API.locked) {
12✔
762
            return false;
1✔
763
        }
764
        CMS.API.locked = true;
11✔
765

766
        // set correct options
767
        const options = opts || this.options;
11✔
768

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

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

774
        // cancel here if we have no placeholder id
775
        if (placeholder_id === false) {
11✔
776
            return false;
1✔
777
        }
778
        const pluginParentElement = dragitem.parent().closest('.cms-draggable');
10✔
779
        const plugin_parent = this._getId(pluginParentElement);
10✔
780

781
        // gather the data for ajax request
782
        const data = {
10✔
783
            plugin_id: options.plugin_id,
784
            plugin_parent: plugin_parent || '',
20✔
785
            target_language: CMS.config.request.language,
786
            csrfmiddlewaretoken: CMS.config.csrf,
787
            move_a_copy: options.move_a_copy
788
        };
789

790
        if (Number(placeholder_id) === Number(options.placeholder_id)) {
10!
791
            Plugin._updatePluginPositions(options.placeholder_id);
10✔
792
        } else {
UNCOV
793
            data.placeholder_id = placeholder_id;
×
794

795
            Plugin._updatePluginPositions(placeholder_id);
×
UNCOV
796
            Plugin._updatePluginPositions(options.placeholder_id);
×
797
        }
798

799
        const position = this.options.position;
10✔
800

801
        data.target_position = position;
10✔
802

803
        showLoader();
10✔
804

805
        $.ajax({
10✔
806
            type: 'POST',
807
            url: Helpers.updateUrlWithPath(options.urls.move_plugin),
808
            data: data,
809
            success: response => {
810
                CMS.API.StructureBoard.invalidateState(
4✔
811
                    data.move_a_copy ? 'PASTE' : 'MOVE',
4!
812
                    $.extend({}, data, { placeholder_id: placeholder_id }, response)
813
                );
814

815
                // enable actions again
816
                CMS.API.locked = false;
4✔
817
                hideLoader();
4✔
818
            },
819
            error: jqXHR => {
820
                CMS.API.locked = false;
4✔
821
                const msg = CMS.config.lang.error;
4✔
822

823
                // trigger error
824
                CMS.API.Messages.open({
4✔
825
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
5✔
826
                    error: true
827
                });
828
                hideLoader();
4✔
829
            }
830
        });
831
    },
832

833
     /**
834
     * Changes the settings attributes on an initialised plugin.
835
     *
836
     * @method _setSettings
837
     * @param {Object} oldSettings current settings
838
     * @param {Object} newSettings new settings to be applied
839
     * @private
840
     */
841
    _setSettings: function _setSettings(oldSettings, newSettings) {
UNCOV
842
        var settings = $.extend(true, {}, oldSettings, newSettings);
×
UNCOV
843
        var plugin = $('.cms-plugin-' + settings.plugin_id);
×
UNCOV
844
        var draggable = $('.cms-draggable-' + settings.plugin_id);
×
845

846
        // set new setting on instance and plugin data
UNCOV
847
        this.options = settings;
×
UNCOV
848
        if (plugin.length) {
×
UNCOV
849
            var index = plugin.data('cms').findIndex(function(pluginData) {
×
UNCOV
850
                return pluginData.plugin_id === settings.plugin_id;
×
851
            });
852

UNCOV
853
            plugin.each(function() {
×
854
                $(this).data('cms')[index] = settings;
×
855
            });
856
        }
UNCOV
857
        if (draggable.length) {
×
UNCOV
858
            draggable.data('cms', settings);
×
859
        }
860
    },
861

862
    /**
863
     * Opens a modal to delete a plugin.
864
     *
865
     * @method deletePlugin
866
     * @param {String} url admin url for deleting a page
867
     * @param {String} name plugin name, e.g. "Column"
868
     * @param {Object[]} breadcrumb array of objects representing a breadcrumb,
869
     *     each item is `{ title: 'string': url: 'string' }`
870
     */
871
    deletePlugin: function(url, name, breadcrumb) {
872
        // trigger modal window
873
        var modal = new Modal({
2✔
874
            onClose: this.options.onClose || false,
4✔
875
            redirectOnClose: this.options.redirectOnClose || false
4✔
876
        });
877

878
        this.modal = modal;
2✔
879

880
        Helpers.removeEventListener('modal-loaded.delete-plugin');
2✔
881
        Helpers.addEventListener('modal-loaded.delete-plugin', (e, { instance }) => {
2✔
882
            if (instance === modal) {
5✔
883
                Plugin._removeAddPluginPlaceholder();
1✔
884
            }
885
        });
886
        modal.open({
2✔
887
            url: url,
888
            title: name,
889
            breadcrumbs: breadcrumb
890
        });
891
    },
892

893
    /**
894
     * Destroys the current plugin instance removing only the DOM listeners
895
     *
896
     * @method destroy
897
     * @param {Object}  options - destroy config options
898
     * @param {Boolean} options.mustCleanup - if true it will remove also the plugin UI components from the DOM
899
     * @returns {void}
900
     */
901
    destroy(options = {}) {
1✔
902
        const mustCleanup = options.mustCleanup || false;
2✔
903

904
        // close the plugin modal if it was open
905
        if (this.modal) {
2!
UNCOV
906
            this.modal.close();
×
907
            // unsubscribe to all the modal events
UNCOV
908
            this.modal.off();
×
909
        }
910

911
        if (mustCleanup) {
2✔
912
            this.cleanup();
1✔
913
        }
914

915
        // remove event bound to global elements like document or window
916
        $document.off(`.${this.uid}`);
2✔
917
        $window.off(`.${this.uid}`);
2✔
918
    },
919

920
    /**
921
     * Remove the plugin specific ui elements from the DOM
922
     *
923
     * @method cleanup
924
     * @returns {void}
925
     */
926
    cleanup() {
927
        // remove all the plugin UI DOM elements
928
        // notice that $.remove will remove also all the ui specific events
929
        // previously attached to them
930
        Object.keys(this.ui).forEach(el => this.ui[el].remove());
12✔
931
    },
932

933
    /**
934
     * Called after plugin is added through ajax.
935
     *
936
     * @method editPluginPostAjax
937
     * @param {Object} toolbar CMS.API.Toolbar instance (not used)
938
     * @param {Object} response response from server
939
     */
940
    editPluginPostAjax: function(toolbar, response) {
941
        this.editPlugin(Helpers.updateUrlWithPath(response.url), this.options.plugin_name, response.breadcrumb);
1✔
942
    },
943

944
    /**
945
     * _setSettingsMenu sets up event handlers for settings menu.
946
     *
947
     * @method _setSettingsMenu
948
     * @private
949
     * @param {jQuery} nav
950
     */
951
    _setSettingsMenu: function _setSettingsMenu(nav) {
952
        var that = this;
153✔
953

954
        this.ui.dropdown = nav.siblings('.cms-submenu-dropdown-settings');
153✔
955
        var dropdown = this.ui.dropdown;
153✔
956

957
        nav
153✔
958
            .off(Plugin.pointerUp)
959
            .on(Plugin.pointerUp, function(e) {
UNCOV
960
                e.preventDefault();
×
UNCOV
961
                e.stopPropagation();
×
UNCOV
962
                var trigger = $(this);
×
963

UNCOV
964
                if (trigger.hasClass('cms-btn-active')) {
×
UNCOV
965
                    Plugin._hideSettingsMenu(trigger);
×
966
                } else {
UNCOV
967
                    Plugin._hideSettingsMenu();
×
UNCOV
968
                    that._showSettingsMenu(trigger);
×
969
                }
970
            })
971
            .off(Plugin.touchStart)
972
            .on(Plugin.touchStart, function(e) {
973
                // required on some touch devices so
974
                // ui touch punch is not triggering mousemove
975
                // which in turn results in pep triggering pointercancel
976
                e.stopPropagation();
×
977
            });
978

979
        dropdown
153✔
980
            .off(Plugin.mouseEvents)
981
            .on(Plugin.mouseEvents, function(e) {
UNCOV
982
                e.stopPropagation();
×
983
            })
984
            .off(Plugin.touchStart)
985
            .on(Plugin.touchStart, function(e) {
986
                // required for scrolling on mobile
UNCOV
987
                e.stopPropagation();
×
988
            });
989

990
        that._setupActions(nav);
153✔
991
        // prevent propagation
992
        nav
153✔
993
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '))
994
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
UNCOV
995
                e.stopPropagation();
×
996
            });
997

998
        nav
153✔
999
            .siblings('.cms-quicksearch, .cms-submenu-dropdown-settings')
1000
            .off([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '))
1001
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
UNCOV
1002
                e.stopPropagation();
×
1003
            });
1004
    },
1005

1006
    /**
1007
     * Simplistic implementation, only scrolls down, only works in structuremode
1008
     * and highly depends on the styles of the structureboard to work correctly
1009
     *
1010
     * @method _scrollToElement
1011
     * @private
1012
     * @param {jQuery} el element to scroll to
1013
     * @param {Object} [opts]
1014
     * @param {Number} [opts.duration=200] time to scroll
1015
     * @param {Number} [opts.offset=50] distance in px to the bottom of the screen
1016
     */
1017
    _scrollToElement: function _scrollToElement(el, opts) {
1018
        var DEFAULT_DURATION = 200;
3✔
1019
        var DEFAULT_OFFSET = 50;
3✔
1020
        var duration = opts && opts.duration !== undefined ? opts.duration : DEFAULT_DURATION;
3✔
1021
        var offset = opts && opts.offset !== undefined ? opts.offset : DEFAULT_OFFSET;
3✔
1022
        var scrollable = el.offsetParent();
3✔
1023
        var scrollHeight = $window.height();
3✔
1024
        var scrollTop = scrollable.scrollTop();
3✔
1025
        var elPosition = el.position().top;
3✔
1026
        var elHeight = el.height();
3✔
1027
        var isInViewport = elPosition + elHeight + offset <= scrollHeight;
3✔
1028

1029
        if (!isInViewport) {
3✔
1030
            scrollable.animate(
2✔
1031
                {
1032
                    scrollTop: elPosition + offset + elHeight + scrollTop - scrollHeight
1033
                },
1034
                duration
1035
            );
1036
        }
1037
    },
1038

1039
    /**
1040
     * Opens a modal with traversable plugins list, adds a placeholder to where
1041
     * the plugin will be added.
1042
     *
1043
     * @method _setAddPluginModal
1044
     * @private
1045
     * @param {jQuery} nav modal trigger element
1046
     * @returns {Boolean|void}
1047
     */
1048
    _setAddPluginModal: function _setAddPluginModal(nav) {
1049
        if (nav.hasClass('cms-btn-disabled')) {
153✔
1050
            return false;
88✔
1051
        }
1052
        var that = this;
65✔
1053
        var modal;
1054
        var possibleChildClasses;
1055
        var isTouching;
1056
        var plugins;
1057

1058
        var initModal = once(function initModal() {
65✔
UNCOV
1059
            var placeholder = $(
×
1060
                '<div class="cms-add-plugin-placeholder">' + CMS.config.lang.addPluginPlaceholder + '</div>'
1061
            );
UNCOV
1062
            var dragItem = nav.closest('.cms-dragitem');
×
UNCOV
1063
            var isPlaceholder = !dragItem.length;
×
1064
            var childrenList;
1065

UNCOV
1066
            modal = new Modal({
×
1067
                minWidth: 400,
1068
                minHeight: 400
1069
            });
1070

1071
            if (isPlaceholder) {
×
UNCOV
1072
                childrenList = nav.closest('.cms-dragarea').find('> .cms-draggables');
×
1073
            } else {
1074
                childrenList = nav.closest('.cms-draggable').find('> .cms-draggables');
×
1075
            }
1076

UNCOV
1077
            Helpers.addEventListener('modal-loaded', (e, { instance }) => {
×
1078
                if (instance !== modal) {
×
UNCOV
1079
                    return;
×
1080
                }
1081

UNCOV
1082
                that._setupKeyboardTraversing();
×
1083
                if (childrenList.hasClass('cms-hidden') && !isPlaceholder) {
×
1084
                    that._toggleCollapsable(dragItem);
×
1085
                }
1086
                Plugin._removeAddPluginPlaceholder();
×
UNCOV
1087
                placeholder.appendTo(childrenList);
×
UNCOV
1088
                that._scrollToElement(placeholder);
×
1089
            });
1090

1091
            Helpers.addEventListener('modal-closed', (e, { instance }) => {
×
UNCOV
1092
                if (instance !== modal) {
×
UNCOV
1093
                    return;
×
1094
                }
1095
                Plugin._removeAddPluginPlaceholder();
×
1096
            });
1097

1098
            Helpers.addEventListener('modal-shown', (e, { instance }) => {
×
1099
                if (modal !== instance) {
×
1100
                    return;
×
1101
                }
UNCOV
1102
                var dropdown = $('.cms-modal-markup .cms-plugin-picker');
×
1103

1104
                if (!isTouching) {
×
1105
                    // only focus the field if using mouse
1106
                    // otherwise keyboard pops up
1107
                    dropdown.find('input').trigger('focus');
×
1108
                }
UNCOV
1109
                isTouching = false;
×
1110
            });
1111

1112
            plugins = nav.siblings('.cms-plugin-picker');
×
1113

1114
            that._setupQuickSearch(plugins);
×
1115
        });
1116

1117
        nav
65✔
1118
            .on(Plugin.touchStart, function(e) {
1119
                isTouching = true;
×
1120
                // required on some touch devices so
1121
                // ui touch punch is not triggering mousemove
1122
                // which in turn results in pep triggering pointercancel
UNCOV
1123
                e.stopPropagation();
×
1124
            })
1125
            .on(Plugin.pointerUp, function(e) {
1126
                e.preventDefault();
×
UNCOV
1127
                e.stopPropagation();
×
1128

UNCOV
1129
                Plugin._hideSettingsMenu();
×
1130

1131
                possibleChildClasses = that._getPossibleChildClasses();
×
UNCOV
1132
                var selectionNeeded = possibleChildClasses.filter(':not(.cms-submenu-item-title)').length !== 1;
×
1133

UNCOV
1134
                if (selectionNeeded) {
×
1135
                    initModal();
×
1136

1137
                    // since we don't know exact plugin parent (because dragndrop)
1138
                    // we need to know the parent id by the time we open "add plugin" dialog
1139
                    var pluginsCopy = that._updateWithMostUsedPlugins(
×
1140
                        plugins
1141
                            .clone(true, true)
1142
                            .data('parentId', that._getId(nav.closest('.cms-draggable')))
1143
                            .append(possibleChildClasses)
1144
                    );
1145

1146
                    modal.open({
×
1147
                        title: that.options.addPluginHelpTitle,
1148
                        html: pluginsCopy,
1149
                        width: 530,
1150
                        height: 400
1151
                    });
1152
                } else {
1153
                    // only one plugin available, no need to show the modal
1154
                    // instead directly add the single plugin
UNCOV
1155
                    const el = possibleChildClasses.find('a');  // only one result
×
UNCOV
1156
                    const pluginType = el.attr('href').replace('#', '');
×
UNCOV
1157
                    const showAddForm = el.data('addForm');
×
1158
                    const parentId = that._getId(nav.closest('.cms-draggable'));
×
1159

UNCOV
1160
                    that.addPlugin(pluginType, el.text(), parentId, showAddForm);
×
1161
                }
1162
            });
1163

1164
        // prevent propagation
1165
        nav.on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
65✔
UNCOV
1166
            e.stopPropagation();
×
1167
        });
1168

1169
        nav
65✔
1170
            .siblings('.cms-quicksearch, .cms-submenu-dropdown')
1171
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
1172
                e.stopPropagation();
×
1173
            });
1174
    },
1175

1176
    _updateWithMostUsedPlugins: function _updateWithMostUsedPlugins(plugins) {
UNCOV
1177
        const items = plugins.find('.cms-submenu-item');
×
1178
        // eslint-disable-next-line no-unused-vars
UNCOV
1179
        const mostUsedPlugins = toPairs(pluginUsageMap).sort(([x, a], [y, b]) => a - b).reverse();
×
UNCOV
1180
        const MAX_MOST_USED_PLUGINS = 5;
×
UNCOV
1181
        let count = 0;
×
1182

UNCOV
1183
        if (items.filter(':not(.cms-submenu-item-title)').length <= MAX_MOST_USED_PLUGINS) {
×
1184
            return plugins;
×
1185
        }
1186

UNCOV
1187
        let ref = plugins.find('.cms-quicksearch');
×
1188

1189
        mostUsedPlugins.forEach(([name]) => {
×
UNCOV
1190
            if (count === MAX_MOST_USED_PLUGINS) {
×
1191
                return;
×
1192
            }
1193
            const item = items.find(`[href=${name}]`);
×
1194

1195
            if (item.length) {
×
1196
                const clone = item.closest('.cms-submenu-item').clone(true, true);
×
1197

UNCOV
1198
                ref.after(clone);
×
1199
                ref = clone;
×
UNCOV
1200
                count += 1;
×
1201
            }
1202
        });
1203

UNCOV
1204
        if (count) {
×
1205
            plugins.find('.cms-quicksearch').after(
×
1206
                $(`<div class="cms-submenu-item cms-submenu-item-title" data-cms-most-used>
1207
                    <span>${CMS.config.lang.mostUsed}</span>
1208
                </div>`)
1209
            );
1210
        }
1211

1212
        return plugins;
×
1213
    },
1214

1215
    /**
1216
     * Returns a specific plugin namespaced event postfixing the plugin uid to it
1217
     * in order to properly manage it via jQuery $.on and $.off
1218
     *
1219
     * @method _getNamepacedEvent
1220
     * @private
1221
     * @param {String} base - plugin event type
1222
     * @param {String} additionalNS - additional namespace (like '.traverse' for example)
1223
     * @returns {String} a specific plugin event
1224
     *
1225
     * @example
1226
     *
1227
     * plugin._getNamepacedEvent(Plugin.click); // 'click.cms.plugin.42'
1228
     * plugin._getNamepacedEvent(Plugin.keyDown, '.traverse'); // 'keydown.cms.plugin.traverse.42'
1229
     */
1230
    _getNamepacedEvent(base, additionalNS = '') {
133✔
1231
        return `${base}${additionalNS ? '.'.concat(additionalNS) : ''}.${this.uid}`;
144✔
1232
    },
1233

1234
    /**
1235
     * Returns available plugin/placeholder child classes markup
1236
     * for "Add plugin" modal
1237
     *
1238
     * @method _getPossibleChildClasses
1239
     * @private
1240
     * @returns {jQuery} "add plugin" menu
1241
     */
1242
    _getPossibleChildClasses: function _getPossibleChildClasses() {
1243
        var that = this;
33✔
1244
        var childRestrictions = this.options.plugin_restriction;
33✔
1245
        // have to check the placeholder every time, since plugin could've been
1246
        // moved as part of another plugin
1247
        var placeholderId = that._getId(that.ui.submenu.closest('.cms-dragarea'));
33✔
1248
        var resultElements = $($('#cms-plugin-child-classes-' + placeholderId).html());
33✔
1249

1250
        if (childRestrictions && childRestrictions.length) {
33✔
1251
            resultElements = resultElements.filter(function() {
29✔
1252
                var item = $(this);
4,727✔
1253

1254
                return (
4,727✔
1255
                    item.hasClass('cms-submenu-item-title') ||
9,106✔
1256
                    childRestrictions.indexOf(item.find('a').attr('href')) !== -1
1257
                );
1258
            });
1259

1260
            resultElements = resultElements.filter(function(index) {
29✔
1261
                var item = $(this);
411✔
1262

1263
                return (
411✔
1264
                    !item.hasClass('cms-submenu-item-title') ||
1,182✔
1265
                    (item.hasClass('cms-submenu-item-title') &&
1266
                        (!resultElements.eq(index + 1).hasClass('cms-submenu-item-title') &&
1267
                            resultElements.eq(index + 1).length))
1268
                );
1269
            });
1270
        }
1271

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

1274
        return resultElements;
33✔
1275
    },
1276

1277
    /**
1278
     * Sets up event handlers for quicksearching in the plugin picker.
1279
     *
1280
     * @method _setupQuickSearch
1281
     * @private
1282
     * @param {jQuery} plugins plugins picker element
1283
     */
1284
    _setupQuickSearch: function _setupQuickSearch(plugins) {
UNCOV
1285
        var that = this;
×
UNCOV
1286
        var FILTER_DEBOUNCE_TIMER = 100;
×
UNCOV
1287
        var FILTER_PICK_DEBOUNCE_TIMER = 110;
×
1288

UNCOV
1289
        var handler = debounce(function() {
×
UNCOV
1290
            var input = $(this);
×
1291
            // have to always find the pluginsPicker in the handler
1292
            // because of how we move things into/out of the modal
UNCOV
1293
            var pluginsPicker = input.closest('.cms-plugin-picker');
×
1294

UNCOV
1295
            that._filterPluginsList(pluginsPicker, input);
×
1296
        }, FILTER_DEBOUNCE_TIMER);
1297

1298
        plugins.find('> .cms-quicksearch').find('input').on(Plugin.keyUp, handler).on(
×
1299
            Plugin.keyUp,
1300
            debounce(function(e) {
1301
                var input;
1302
                var pluginsPicker;
1303

UNCOV
1304
                if (e.keyCode === KEYS.ENTER) {
×
1305
                    input = $(this);
×
UNCOV
1306
                    pluginsPicker = input.closest('.cms-plugin-picker');
×
1307
                    pluginsPicker
×
1308
                        .find('.cms-submenu-item')
1309
                        .not('.cms-submenu-item-title')
1310
                        .filter(':visible')
1311
                        .first()
1312
                        .find('> a')
1313
                        .focus()
1314
                        .trigger('click');
1315
                }
1316
            }, FILTER_PICK_DEBOUNCE_TIMER)
1317
        );
1318
    },
1319

1320
    /**
1321
     * Sets up click handlers for various plugin/placeholder items.
1322
     * Items can be anywhere in the plugin dragitem, not only in dropdown.
1323
     *
1324
     * @method _setupActions
1325
     * @private
1326
     * @param {jQuery} nav dropdown trigger with the items
1327
     */
1328
    _setupActions: function _setupActions(nav) {
1329
        var items = '.cms-submenu-edit, .cms-submenu-item a';
163✔
1330
        var parent = nav.parent();
163✔
1331

1332
        parent.find('.cms-submenu-edit').off(Plugin.touchStart).on(Plugin.touchStart, function(e) {
163✔
1333
            // required on some touch devices so
1334
            // ui touch punch is not triggering mousemove
1335
            // which in turn results in pep triggering pointercancel
1336
            e.stopPropagation();
1✔
1337
        });
1338
        parent.find(items).off(Plugin.click).on(Plugin.click, nav, e => this._delegate(e));
163✔
1339
    },
1340

1341
    /**
1342
     * Handler for the "action" items
1343
     *
1344
     * @method _delegate
1345
     * @param {$.Event} e event
1346
     * @private
1347
     */
1348
    // eslint-disable-next-line complexity
1349
    _delegate: function _delegate(e) {
1350
        e.preventDefault();
13✔
1351
        e.stopPropagation();
13✔
1352

1353
        var nav;
1354
        var that = this;
13✔
1355

1356
        if (e.data && e.data.nav) {
13!
UNCOV
1357
            nav = e.data.nav;
×
1358
        }
1359

1360
        // show loader and make sure scroll doesn't jump
1361
        showLoader();
13✔
1362

1363
        var items = '.cms-submenu-edit, .cms-submenu-item a';
13✔
1364
        var el = $(e.target).closest(items);
13✔
1365

1366
        Plugin._hideSettingsMenu(nav);
13✔
1367

1368
        // set switch for subnav entries
1369
        switch (el.attr('data-rel')) {
13!
1370
            // eslint-disable-next-line no-case-declarations
1371
            case 'add':
1372
                const pluginType = el.attr('href').replace('#', '');
2✔
1373
                const showAddForm = el.data('addForm');
2✔
1374

1375
                Plugin._updateUsageCount(pluginType);
2✔
1376
                that.addPlugin(pluginType, el.text(), el.closest('.cms-plugin-picker').data('parentId'), showAddForm);
2✔
1377
                break;
2✔
1378
            case 'ajax_add':
1379
                CMS.API.Toolbar.openAjax({
1✔
1380
                    url: el.attr('href'),
1381
                    post: JSON.stringify(el.data('post')),
1382
                    text: el.data('text'),
1383
                    callback: $.proxy(that.editPluginPostAjax, that),
1384
                    onSuccess: el.data('on-success')
1385
                });
1386
                break;
1✔
1387
            case 'edit':
1388
                that.editPlugin(
1✔
1389
                    Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
1390
                    that.options.plugin_name,
1391
                    that._getPluginBreadcrumbs()
1392
                );
1393
                break;
1✔
1394
            case 'copy-lang':
1395
                that.copyPlugin(that.options, el.attr('data-language'));
1✔
1396
                break;
1✔
1397
            case 'copy':
1398
                if (el.parent().hasClass('cms-submenu-item-disabled')) {
2✔
1399
                    hideLoader();
1✔
1400
                } else {
1401
                    that.copyPlugin();
1✔
1402
                }
1403
                break;
2✔
1404
            case 'cut':
1405
                that.cutPlugin();
1✔
1406
                break;
1✔
1407
            case 'paste':
1408
                hideLoader();
2✔
1409
                if (!el.parent().hasClass('cms-submenu-item-disabled')) {
2✔
1410
                    that.pastePlugin();
1✔
1411
                }
1412
                break;
2✔
1413
            case 'delete':
1414
                that.deletePlugin(
1✔
1415
                    Helpers.updateUrlWithPath(that.options.urls.delete_plugin),
1416
                    that.options.plugin_name,
1417
                    that._getPluginBreadcrumbs()
1418
                );
1419
                break;
1✔
1420
            case 'highlight':
UNCOV
1421
                hideLoader();
×
1422
                // eslint-disable-next-line no-magic-numbers
UNCOV
1423
                window.location.hash = `cms-plugin-${this.options.plugin_id}`;
×
UNCOV
1424
                Plugin._highlightPluginContent(this.options.plugin_id, { seeThrough: true });
×
UNCOV
1425
                e.stopImmediatePropagation();
×
UNCOV
1426
                break;
×
1427
            default:
1428
                hideLoader();
2✔
1429
                CMS.API.Toolbar._delegate(el);
2✔
1430
        }
1431
    },
1432

1433
    /**
1434
     * Sets up keyboard traversing of plugin picker.
1435
     *
1436
     * @method _setupKeyboardTraversing
1437
     * @private
1438
     */
1439
    _setupKeyboardTraversing: function _setupKeyboardTraversing() {
1440
        var dropdown = $('.cms-modal-markup .cms-plugin-picker');
3✔
1441
        const keyDownTraverseEvent = this._getNamepacedEvent(Plugin.keyDown, 'traverse');
3✔
1442

1443
        if (!dropdown.length) {
3✔
1444
            return;
1✔
1445
        }
1446
        // add key events
1447
        $document.off(keyDownTraverseEvent);
2✔
1448
        // istanbul ignore next: not really possible to reproduce focus state in unit tests
1449
        $document.on(keyDownTraverseEvent, function(e) {
1450
            var anchors = dropdown.find('.cms-submenu-item:visible a');
1451
            var index = anchors.index(anchors.filter(':focus'));
1452

1453
            // bind arrow down and tab keys
1454
            if (e.keyCode === KEYS.DOWN || (e.keyCode === KEYS.TAB && !e.shiftKey)) {
1455
                e.preventDefault();
1456
                if (index >= 0 && index < anchors.length - 1) {
1457
                    anchors.eq(index + 1).focus();
1458
                } else {
1459
                    anchors.eq(0).focus();
1460
                }
1461
            }
1462

1463
            // bind arrow up and shift+tab keys
1464
            if (e.keyCode === KEYS.UP || (e.keyCode === KEYS.TAB && e.shiftKey)) {
1465
                e.preventDefault();
1466
                if (anchors.is(':focus')) {
1467
                    anchors.eq(index - 1).focus();
1468
                } else {
1469
                    anchors.eq(anchors.length).focus();
1470
                }
1471
            }
1472
        });
1473
    },
1474

1475
    /**
1476
     * Opens the settings menu for a plugin.
1477
     *
1478
     * @method _showSettingsMenu
1479
     * @private
1480
     * @param {jQuery} nav trigger element
1481
     */
1482
    _showSettingsMenu: function(nav) {
UNCOV
1483
        this._checkIfPasteAllowed();
×
1484

UNCOV
1485
        var dropdown = this.ui.dropdown;
×
UNCOV
1486
        var parents = nav.parentsUntil('.cms-dragarea').last();
×
UNCOV
1487
        var MIN_SCREEN_MARGIN = 10;
×
1488

UNCOV
1489
        nav.addClass('cms-btn-active');
×
UNCOV
1490
        parents.addClass('cms-z-index-9999');
×
1491

1492
        // set visible states
UNCOV
1493
        dropdown.show();
×
1494

1495
        // calculate dropdown positioning
UNCOV
1496
        if (
×
1497
            $window.height() + $window.scrollTop() - nav.offset().top - dropdown.height() <= MIN_SCREEN_MARGIN &&
×
1498
            nav.offset().top - dropdown.height() >= 0
1499
        ) {
UNCOV
1500
            dropdown.removeClass('cms-submenu-dropdown-top').addClass('cms-submenu-dropdown-bottom');
×
1501
        } else {
1502
            dropdown.removeClass('cms-submenu-dropdown-bottom').addClass('cms-submenu-dropdown-top');
×
1503
        }
1504
    },
1505

1506
    /**
1507
     * Filters given plugins list by a query.
1508
     *
1509
     * @method _filterPluginsList
1510
     * @private
1511
     * @param {jQuery} list plugins picker element
1512
     * @param {jQuery} input input, which value to filter plugins with
1513
     * @returns {Boolean|void}
1514
     */
1515
    _filterPluginsList: function _filterPluginsList(list, input) {
1516
        var items = list.find('.cms-submenu-item');
5✔
1517
        var titles = list.find('.cms-submenu-item-title');
5✔
1518
        var query = input.val();
5✔
1519

1520
        // cancel if query is zero
1521
        if (query === '') {
5✔
1522
            items.add(titles).show();
1✔
1523
            return false;
1✔
1524
        }
1525

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

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

1530
        var itemsToFilter = items.toArray().map(function(el) {
4✔
1531
            var element = $(el);
72✔
1532

1533
            return {
72✔
1534
                value: element.text(),
1535
                element: element
1536
            };
1537
        });
1538

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

1541
        items.hide();
4✔
1542
        filteredItems.forEach(function(item) {
4✔
1543
            item.element.show();
3✔
1544
        });
1545

1546
        // check if a title is matching
1547
        titles.filter(':visible').each(function(index, item) {
4✔
1548
            titles.hide();
1✔
1549
            $(item).nextUntil('.cms-submenu-item-title').show();
1✔
1550
        });
1551

1552
        // always display title of a category
1553
        items.filter(':visible').each(function(index, titleItem) {
4✔
1554
            var item = $(titleItem);
16✔
1555

1556
            if (item.prev().hasClass('cms-submenu-item-title')) {
16✔
1557
                item.prev().show();
2✔
1558
            } else {
1559
                item.prevUntil('.cms-submenu-item-title').last().prev().show();
14✔
1560
            }
1561
        });
1562

1563
        mostRecentItems.hide();
4✔
1564
    },
1565

1566
    /**
1567
     * Toggles collapsable item.
1568
     *
1569
     * @method _toggleCollapsable
1570
     * @private
1571
     * @param {jQuery} el element to toggle
1572
     * @returns {Boolean|void}
1573
     */
1574
    _toggleCollapsable: function toggleCollapsable(el) {
UNCOV
1575
        var that = this;
×
UNCOV
1576
        var id = that._getId(el.parent());
×
UNCOV
1577
        var draggable = el.closest('.cms-draggable');
×
1578
        var items;
1579

UNCOV
1580
        var settings = CMS.settings;
×
1581

UNCOV
1582
        settings.states = settings.states || [];
×
1583

UNCOV
1584
        if (!draggable || !draggable.length) {
×
UNCOV
1585
            return;
×
1586
        }
1587

1588
        // collapsable function and save states
1589
        if (el.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1590
            settings.states.splice($.inArray(id, settings.states), 1);
×
UNCOV
1591
            el
×
1592
                .removeClass('cms-dragitem-expanded')
1593
                .parent()
1594
                .find('> .cms-collapsable-container')
1595
                .addClass('cms-hidden');
1596

1597
            if ($document.data('expandmode')) {
×
UNCOV
1598
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
UNCOV
1599
                if (!items.length) {
×
UNCOV
1600
                    return false;
×
1601
                }
1602
                items.each(function() {
×
1603
                    var item = $(this);
×
1604

UNCOV
1605
                    if (item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1606
                        that._toggleCollapsable(item);
×
1607
                    }
1608
                });
1609
            }
1610
        } else {
1611
            settings.states.push(id);
×
1612
            el
×
1613
                .addClass('cms-dragitem-expanded')
1614
                .parent()
1615
                .find('> .cms-collapsable-container')
1616
                .removeClass('cms-hidden');
1617

1618
            if ($document.data('expandmode')) {
×
UNCOV
1619
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
UNCOV
1620
                if (!items.length) {
×
UNCOV
1621
                    return false;
×
1622
                }
1623
                items.each(function() {
×
1624
                    var item = $(this);
×
1625

UNCOV
1626
                    if (!item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1627
                        that._toggleCollapsable(item);
×
1628
                    }
1629
                });
1630
            }
1631
        }
1632

1633
        this._updatePlaceholderCollapseState();
×
1634

1635
        // make sure structurboard gets updated after expanding
1636
        $document.trigger('resize.sideframe');
×
1637

1638
        // save settings
1639
        Helpers.setSettings(settings);
×
1640
    },
1641

1642
    _updatePlaceholderCollapseState() {
UNCOV
1643
        if (this.options.type !== 'plugin' || !this.options.placeholder_id) {
×
UNCOV
1644
            return;
×
1645
        }
1646

UNCOV
1647
        const pluginsOfCurrentPlaceholder = CMS._plugins
×
1648
            .filter(([, o]) => o.placeholder_id === this.options.placeholder_id && o.type === 'plugin')
×
UNCOV
1649
            .map(([, o]) => o.plugin_id);
×
1650

1651
        const openedPlugins = CMS.settings.states;
×
UNCOV
1652
        const closedPlugins = difference(pluginsOfCurrentPlaceholder, openedPlugins);
×
UNCOV
1653
        const areAllRemainingPluginsLeafs = every(closedPlugins, id => {
×
UNCOV
1654
            return !find(
×
1655
                CMS._plugins,
1656
                ([, o]) => o.placeholder_id === this.options.placeholder_id && o.plugin_parent === id
×
1657
            );
1658
        });
1659
        const el = $(`.cms-dragarea-${this.options.placeholder_id} .cms-dragbar-title`);
×
1660
        var settings = CMS.settings;
×
1661

UNCOV
1662
        if (areAllRemainingPluginsLeafs) {
×
1663
            // meaning that all plugins in current placeholder are expanded
1664
            el.addClass('cms-dragbar-title-expanded');
×
1665

1666
            settings.dragbars = settings.dragbars || [];
×
UNCOV
1667
            settings.dragbars.push(this.options.placeholder_id);
×
1668
        } else {
UNCOV
1669
            el.removeClass('cms-dragbar-title-expanded');
×
1670

1671
            settings.dragbars = settings.dragbars || [];
×
1672
            settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1673
        }
1674
    },
1675

1676
    /**
1677
     * Sets up collabspable event handlers.
1678
     *
1679
     * @method _collapsables
1680
     * @private
1681
     * @returns {Boolean|void}
1682
     */
1683
    _collapsables: function() {
1684
        // one time setup
1685
        var that = this;
153✔
1686

1687
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
153✔
1688
        // cancel here if its not a draggable
1689
        if (!this.ui.draggable.length) {
153✔
1690
            return false;
38✔
1691
        }
1692

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

1695
        // check which button should be shown for collapsemenu
1696
        var els = this.ui.draggable.find('.cms-dragitem-collapsable');
115✔
1697
        var open = els.filter('.cms-dragitem-expanded');
115✔
1698

1699
        if (els.length === open.length && els.length + open.length !== 0) {
115!
UNCOV
1700
            this.ui.draggable.find('.cms-dragbar-title').addClass('cms-dragbar-title-expanded');
×
1701
        }
1702

1703
        // attach events to draggable
1704
        // debounce here required because on some devices click is not triggered,
1705
        // so we consolidate latest click and touch event to run the collapse only once
1706
        dragitem.find('> .cms-dragitem-text').on(
115✔
1707
            Plugin.touchEnd + ' ' + Plugin.click,
1708
            debounce(function() {
UNCOV
1709
                if (!dragitem.hasClass('cms-dragitem-collapsable')) {
×
UNCOV
1710
                    return;
×
1711
                }
1712
                that._toggleCollapsable(dragitem);
×
1713
            }, 0)
1714
        );
1715
    },
1716

1717
    /**
1718
     * Expands all the collapsables in the given placeholder.
1719
     *
1720
     * @method _expandAll
1721
     * @private
1722
     * @param {jQuery} el trigger element that is a child of a placeholder
1723
     * @returns {Boolean|void}
1724
     */
1725
    _expandAll: function(el) {
UNCOV
1726
        var that = this;
×
UNCOV
1727
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1728

1729
        // cancel if there are no items
UNCOV
1730
        if (!items.length) {
×
UNCOV
1731
            return false;
×
1732
        }
UNCOV
1733
        items.each(function() {
×
UNCOV
1734
            var item = $(this);
×
1735

UNCOV
1736
            if (!item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1737
                that._toggleCollapsable(item);
×
1738
            }
1739
        });
1740

UNCOV
1741
        el.addClass('cms-dragbar-title-expanded');
×
1742

1743
        var settings = CMS.settings;
×
1744

1745
        settings.dragbars = settings.dragbars || [];
×
1746
        settings.dragbars.push(this.options.placeholder_id);
×
UNCOV
1747
        Helpers.setSettings(settings);
×
1748
    },
1749

1750
    /**
1751
     * Collapses all the collapsables in the given placeholder.
1752
     *
1753
     * @method _collapseAll
1754
     * @private
1755
     * @param {jQuery} el trigger element that is a child of a placeholder
1756
     */
1757
    _collapseAll: function(el) {
1758
        var that = this;
×
1759
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1760

UNCOV
1761
        items.each(function() {
×
UNCOV
1762
            var item = $(this);
×
1763

UNCOV
1764
            if (item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1765
                that._toggleCollapsable(item);
×
1766
            }
1767
        });
1768

UNCOV
1769
        el.removeClass('cms-dragbar-title-expanded');
×
1770

1771
        var settings = CMS.settings;
×
1772

1773
        settings.dragbars = settings.dragbars || [];
×
1774
        settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
UNCOV
1775
        Helpers.setSettings(settings);
×
1776
    },
1777

1778
    /**
1779
     * Gets the id of the element, uses CMS.StructureBoard instance.
1780
     *
1781
     * @method _getId
1782
     * @private
1783
     * @param {jQuery} el element to get id from
1784
     * @returns {String}
1785
     */
1786
    _getId: function(el) {
1787
        return CMS.API.StructureBoard.getId(el);
36✔
1788
    },
1789

1790
    /**
1791
     * Gets the ids of the list of elements, uses CMS.StructureBoard instance.
1792
     *
1793
     * @method _getIds
1794
     * @private
1795
     * @param {jQuery} els elements to get id from
1796
     * @returns {String[]}
1797
     */
1798
    _getIds: function(els) {
UNCOV
1799
        return CMS.API.StructureBoard.getIds(els);
×
1800
    },
1801

1802
    /**
1803
     * Traverses the registry to find plugin parents
1804
     *
1805
     * @method _getPluginBreadcrumbs
1806
     * @returns {Object[]} array of breadcrumbs in `{ url, title }` format
1807
     * @private
1808
     */
1809
    _getPluginBreadcrumbs: function _getPluginBreadcrumbs() {
1810
        var breadcrumbs = [];
6✔
1811

1812
        breadcrumbs.unshift({
6✔
1813
            title: this.options.plugin_name,
1814
            url: this.options.urls.edit_plugin
1815
        });
1816

1817
        var findParentPlugin = function(id) {
6✔
1818
            return $.grep(CMS._plugins || [], function(pluginOptions) {
6✔
1819
                return pluginOptions[0] === 'cms-plugin-' + id;
10✔
1820
            })[0];
1821
        };
1822

1823
        var id = this.options.plugin_parent;
6✔
1824
        var data;
1825

1826
        while (id && id !== 'None') {
6✔
1827
            data = findParentPlugin(id);
6✔
1828

1829
            if (!data) {
6✔
1830
                break;
1✔
1831
            }
1832

1833
            breadcrumbs.unshift({
5✔
1834
                title: data[1].plugin_name,
1835
                url: data[1].urls.edit_plugin
1836
            });
1837
            id = data[1].plugin_parent;
5✔
1838
        }
1839

1840
        return breadcrumbs;
6✔
1841
    }
1842
});
1843

1844
Plugin.click = 'click.cms.plugin';
1✔
1845
Plugin.pointerUp = 'pointerup.cms.plugin';
1✔
1846
Plugin.pointerDown = 'pointerdown.cms.plugin';
1✔
1847
Plugin.pointerOverAndOut = 'pointerover.cms.plugin pointerout.cms.plugin';
1✔
1848
Plugin.doubleClick = 'dblclick.cms.plugin';
1✔
1849
Plugin.keyUp = 'keyup.cms.plugin';
1✔
1850
Plugin.keyDown = 'keydown.cms.plugin';
1✔
1851
Plugin.mouseEvents = 'mousedown.cms.plugin mousemove.cms.plugin mouseup.cms.plugin';
1✔
1852
Plugin.touchStart = 'touchstart.cms.plugin';
1✔
1853
Plugin.touchEnd = 'touchend.cms.plugin';
1✔
1854

1855
/**
1856
 * Updates plugin data in CMS._plugins / CMS._instances or creates new
1857
 * plugin instances if they didn't exist
1858
 *
1859
 * @method _updateRegistry
1860
 * @private
1861
 * @static
1862
 * @param {Object[]} plugins plugins data
1863
 */
1864
Plugin._updateRegistry = function _updateRegistry(plugins) {
1✔
UNCOV
1865
    plugins.forEach(pluginData => {
×
UNCOV
1866
        const pluginContainer = `cms-plugin-${pluginData.plugin_id}`;
×
UNCOV
1867
        const pluginIndex = findIndex(CMS._plugins, ([pluginStr]) => pluginStr === pluginContainer);
×
1868

UNCOV
1869
        if (pluginIndex === -1) {
×
UNCOV
1870
            CMS._plugins.push([pluginContainer, pluginData]);
×
UNCOV
1871
            CMS._instances.push(new Plugin(pluginContainer, pluginData));
×
1872
        } else {
UNCOV
1873
            Plugin.aliasPluginDuplicatesMap[pluginData.plugin_id] = false;
×
UNCOV
1874
            CMS._plugins[pluginIndex] = [pluginContainer, pluginData];
×
UNCOV
1875
            CMS._instances[pluginIndex] = new Plugin(pluginContainer, pluginData);
×
1876
        }
1877
    });
1878
};
1879

1880
/**
1881
 * Hides the opened settings menu. By default looks for any open ones.
1882
 *
1883
 * @method _hideSettingsMenu
1884
 * @static
1885
 * @private
1886
 * @param {jQuery} [navEl] element representing the subnav trigger
1887
 */
1888
Plugin._hideSettingsMenu = function(navEl) {
1✔
1889
    var nav = navEl || $('.cms-submenu-btn.cms-btn-active');
20✔
1890

1891
    if (!nav.length) {
20!
1892
        return;
20✔
1893
    }
UNCOV
1894
    nav.removeClass('cms-btn-active');
×
1895

1896
    // set correct active state
UNCOV
1897
    nav.closest('.cms-draggable').data('active', false);
×
UNCOV
1898
    $('.cms-z-index-9999').removeClass('cms-z-index-9999');
×
1899

UNCOV
1900
    nav.siblings('.cms-submenu-dropdown').hide();
×
UNCOV
1901
    nav.siblings('.cms-quicksearch').hide();
×
1902
    // reset search
UNCOV
1903
    nav.siblings('.cms-quicksearch').find('input').val('').trigger(Plugin.keyUp).blur();
×
1904

1905
    // reset relativity
1906
    $('.cms-dragbar').css('position', '');
×
1907
};
1908

1909
/**
1910
 * Initialises handlers that affect all plugins and don't make sense
1911
 * in context of each own plugin instance, e.g. listening for a click on a document
1912
 * to hide plugin settings menu should only be applied once, and not every time
1913
 * CMS.Plugin is instantiated.
1914
 *
1915
 * @method _initializeGlobalHandlers
1916
 * @static
1917
 * @private
1918
 */
1919
Plugin._initializeGlobalHandlers = function _initializeGlobalHandlers() {
1✔
1920
    var timer;
1921
    var clickCounter = 0;
6✔
1922

1923
    Plugin._updateClipboard();
6✔
1924

1925
    // Structureboard initialized too late
1926
    setTimeout(function() {
6✔
1927
        var pluginData = {};
6✔
1928
        var html = '';
6✔
1929

1930
        if (clipboardDraggable.length) {
6✔
1931
            pluginData = find(
5✔
1932
                CMS._plugins,
1933
                ([desc]) => desc === `cms-plugin-${CMS.API.StructureBoard.getId(clipboardDraggable)}`
10✔
1934
            )[1];
1935
            html = clipboardDraggable.parent().html();
5✔
1936
        }
1937
        if (CMS.API && CMS.API.Clipboard) {
6!
1938
            CMS.API.Clipboard.populate(html, pluginData);
6✔
1939
        }
1940
    }, 0);
1941

1942
    $document
6✔
1943
        .off(Plugin.pointerUp)
1944
        .off(Plugin.keyDown)
1945
        .off(Plugin.keyUp)
1946
        .off(Plugin.click, '.cms-plugin a, a:has(.cms-plugin), a.cms-plugin')
1947
        .on(Plugin.pointerUp, function() {
1948
            // call it as a static method, because otherwise we trigger it the
1949
            // amount of times CMS.Plugin is instantiated,
1950
            // which does not make much sense.
UNCOV
1951
            Plugin._hideSettingsMenu();
×
1952
        })
1953
        .on(Plugin.keyDown, function(e) {
1954
            if (e.keyCode === KEYS.SHIFT) {
26!
UNCOV
1955
                $document.data('expandmode', true);
×
UNCOV
1956
                try {
×
UNCOV
1957
                    $('.cms-plugin:hover').last().trigger('mouseenter');
×
UNCOV
1958
                    $('.cms-dragitem:hover').last().trigger('mouseenter');
×
1959
                } catch (err) {}
1960
            }
1961
        })
1962
        .on(Plugin.keyUp, function(e) {
1963
            if (e.keyCode === KEYS.SHIFT) {
23!
UNCOV
1964
                $document.data('expandmode', false);
×
UNCOV
1965
                try {
×
UNCOV
1966
                    $(':hover').trigger('mouseleave');
×
1967
                } catch (err) {}
1968
            }
1969
        })
1970
        .on(Plugin.click, '.cms-plugin a, a:has(.cms-plugin), a.cms-plugin', function(e) {
UNCOV
1971
            var DOUBLECLICK_DELAY = 300;
×
1972

1973
            // prevents single click from messing up the edit call
1974
            // don't go to the link if there is custom js attached to it
1975
            // or if it's clicked along with shift, ctrl, cmd
1976
            if (e.shiftKey || e.ctrlKey || e.metaKey || e.isDefaultPrevented()) {
×
1977
                return;
×
1978
            }
UNCOV
1979
            e.preventDefault();
×
UNCOV
1980
            if (++clickCounter === 1) {
×
UNCOV
1981
                timer = setTimeout(function() {
×
UNCOV
1982
                    var anchor = $(e.target).closest('a');
×
1983

UNCOV
1984
                    clickCounter = 0;
×
UNCOV
1985
                    window.open(anchor.attr('href'), anchor.attr('target') || '_self');
×
1986
                }, DOUBLECLICK_DELAY);
1987
            } else {
1988
                clearTimeout(timer);
×
1989
                clickCounter = 0;
×
1990
            }
1991
        });
1992

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

UNCOV
2002
        e.stopPropagation();
×
UNCOV
2003
        const pluginContainer = $(e.target).closest('.cms-plugin');
×
UNCOV
2004
        const allOptions = pluginContainer.data('cms');
×
2005

UNCOV
2006
        if (!allOptions || !allOptions.length) {
×
UNCOV
2007
            return;
×
2008
        }
2009

UNCOV
2010
        const options = allOptions[0];
×
2011

UNCOV
2012
        if (e.type === 'touchstart') {
×
UNCOV
2013
            CMS.API.Tooltip._forceTouchOnce();
×
2014
        }
2015
        var name = options.plugin_name;
×
2016
        var id = options.plugin_id;
×
UNCOV
2017
        var type = options.type;
×
2018

2019
        if (type === 'generic') {
×
UNCOV
2020
            return;
×
2021
        }
2022
        var placeholderId = CMS.API.StructureBoard.getId($(`.cms-draggable-${id}`).closest('.cms-dragarea'));
×
UNCOV
2023
        var placeholder = $('.cms-placeholder-' + placeholderId);
×
2024

2025
        if (placeholder.length && placeholder.data('cms')) {
×
UNCOV
2026
            name = placeholder.data('cms').name + ': ' + name;
×
2027
        }
2028

2029
        CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
2030
    });
2031

2032
    $document.on(Plugin.click, '.cms-dragarea-static .cms-dragbar', e => {
6✔
UNCOV
2033
        const placeholder = $(e.target).closest('.cms-dragarea');
×
2034

2035
        if (placeholder.hasClass('cms-dragarea-static-expanded') && e.isDefaultPrevented()) {
×
UNCOV
2036
            return;
×
2037
        }
2038

UNCOV
2039
        placeholder.toggleClass('cms-dragarea-static-expanded');
×
2040
    });
2041

2042
    $window.on('blur.cms', () => {
6✔
2043
        $document.data('expandmode', false);
6✔
2044
    });
2045
};
2046

2047
/**
2048
 * @method _isContainingMultiplePlugins
2049
 * @param {jQuery} node to check
2050
 * @static
2051
 * @private
2052
 * @returns {Boolean}
2053
 */
2054
Plugin._isContainingMultiplePlugins = function _isContainingMultiplePlugins(node) {
1✔
2055
    var currentData = node.data('cms');
130✔
2056

2057
    // istanbul ignore if
2058
    if (!currentData) {
130✔
2059
        throw new Error('Provided node is not a cms plugin.');
2060
    }
2061

2062
    var pluginIds = currentData.map(function(pluginData) {
130✔
2063
        return pluginData.plugin_id;
131✔
2064
    });
2065

2066
    if (pluginIds.length > 1) {
130✔
2067
        // another plugin already lives on the same node
2068
        // this only works because the plugins are rendered from
2069
        // the bottom to the top (leaf to root)
2070
        // meaning the deepest plugin is always first
2071
        return true;
1✔
2072
    }
2073

2074
    return false;
129✔
2075
};
2076

2077
/**
2078
 * Shows and immediately fades out a success notification (when
2079
 * plugin was successfully moved.
2080
 *
2081
 * @method _highlightPluginStructure
2082
 * @private
2083
 * @static
2084
 * @param {jQuery} el draggable element
2085
 */
2086
// eslint-disable-next-line no-magic-numbers
2087
Plugin._highlightPluginStructure = function _highlightPluginStructure(
1✔
2088
    el,
2089
    // eslint-disable-next-line no-magic-numbers
2090
    { successTimeout = 200, delay = 1500, seeThrough = false }
×
2091
) {
UNCOV
2092
    const tpl = $(`
×
2093
        <div class="cms-dragitem-success ${seeThrough ? 'cms-plugin-overlay-see-through' : ''}">
×
2094
        </div>
2095
    `);
2096

UNCOV
2097
    el.addClass('cms-draggable-success').append(tpl);
×
2098
    // start animation
UNCOV
2099
    if (successTimeout) {
×
UNCOV
2100
        setTimeout(() => {
×
UNCOV
2101
            tpl.fadeOut(successTimeout, function() {
×
UNCOV
2102
                $(this).remove();
×
UNCOV
2103
                el.removeClass('cms-draggable-success');
×
2104
            });
2105
        }, delay);
2106
    }
2107
    // make sure structurboard gets updated after success
UNCOV
2108
    $(Helpers._getWindow()).trigger('resize.sideframe');
×
2109
};
2110

2111
/**
2112
 * Highlights plugin in content mode
2113
 *
2114
 * @method _highlightPluginContent
2115
 * @private
2116
 * @static
2117
 * @param {String|Number} pluginId
2118
 */
2119
Plugin._highlightPluginContent = function _highlightPluginContent(
1✔
2120
    pluginId,
2121
    // eslint-disable-next-line no-magic-numbers
2122
    { successTimeout = 200, seeThrough = false, delay = 1500, prominent = false } = {}
5✔
2123
) {
2124
    var coordinates = {};
1✔
2125
    var positions = [];
1✔
2126
    var OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO = 0.2;
1✔
2127

2128
    $('.cms-plugin-' + pluginId).each(function() {
1✔
2129
        var el = $(this);
1✔
2130
        var offset = el.offset();
1✔
2131
        var ml = parseInt(el.css('margin-left'), 10);
1✔
2132
        var mr = parseInt(el.css('margin-right'), 10);
1✔
2133
        var mt = parseInt(el.css('margin-top'), 10);
1✔
2134
        var mb = parseInt(el.css('margin-bottom'), 10);
1✔
2135
        var width = el.outerWidth();
1✔
2136
        var height = el.outerHeight();
1✔
2137

2138
        if (width === 0 && height === 0) {
1!
UNCOV
2139
            return;
×
2140
        }
2141

2142
        if (isNaN(ml)) {
1!
UNCOV
2143
            ml = 0;
×
2144
        }
2145
        if (isNaN(mr)) {
1!
UNCOV
2146
            mr = 0;
×
2147
        }
2148
        if (isNaN(mt)) {
1!
UNCOV
2149
            mt = 0;
×
2150
        }
2151
        if (isNaN(mb)) {
1!
UNCOV
2152
            mb = 0;
×
2153
        }
2154

2155
        positions.push({
1✔
2156
            x1: offset.left - ml,
2157
            x2: offset.left + width + mr,
2158
            y1: offset.top - mt,
2159
            y2: offset.top + height + mb
2160
        });
2161
    });
2162

2163
    if (positions.length === 0) {
1!
2164
        return;
×
2165
    }
2166

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

2172
    coordinates.left = Math.min(...positions.map(pos => pos.x1));
1✔
2173
    coordinates.top = Math.min(...positions.map(pos => pos.y1)) - htmlMargin;
1✔
2174
    coordinates.width = Math.max(...positions.map(pos => pos.x2)) - coordinates.left;
1✔
2175
    coordinates.height = Math.max(...positions.map(pos => pos.y2)) - coordinates.top - htmlMargin;
1✔
2176

2177
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2178

2179
    $(
1✔
2180
        `
2181
        <div class="
2182
            cms-plugin-overlay
2183
            cms-dragitem-success
2184
            cms-plugin-overlay-${pluginId}
2185
            ${seeThrough ? 'cms-plugin-overlay-see-through' : ''}
1!
2186
            ${prominent ? 'cms-plugin-overlay-prominent' : ''}
1!
2187
        "
2188
            data-success-timeout="${successTimeout}"
2189
        >
2190
        </div>
2191
    `
2192
    )
2193
        .css(coordinates)
2194
        .css({
2195
            zIndex: 9999
2196
        })
2197
        .appendTo($('body'));
2198

2199
    if (successTimeout) {
1!
2200
        setTimeout(() => {
1✔
2201
            $(`.cms-plugin-overlay-${pluginId}`).fadeOut(successTimeout, function() {
1✔
2202
                $(this).remove();
1✔
2203
            });
2204
        }, delay);
2205
    }
2206
};
2207

2208
Plugin._clickToHighlightHandler = function _clickToHighlightHandler(e) {
1✔
UNCOV
2209
    if (CMS.settings.mode !== 'structure') {
×
UNCOV
2210
        return;
×
2211
    }
UNCOV
2212
    e.preventDefault();
×
UNCOV
2213
    e.stopPropagation();
×
2214
    // FIXME refactor into an object
UNCOV
2215
    CMS.API.StructureBoard._showAndHighlightPlugin(200, true); // eslint-disable-line no-magic-numbers
×
2216
};
2217

2218
Plugin._removeHighlightPluginContent = function(pluginId) {
1✔
UNCOV
2219
    $(`.cms-plugin-overlay-${pluginId}[data-success-timeout=0]`).remove();
×
2220
};
2221

2222
Plugin.aliasPluginDuplicatesMap = {};
1✔
2223
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2224

2225
// istanbul ignore next
2226
Plugin._initializeTree = function _initializeTree() {
2227
    const plugins = {};
2228

2229
    document.body.querySelectorAll(
2230
        'script[data-cms-plugin], ' +
2231
        'script[data-cms-placeholder], ' +
2232
        'script[data-cms-general]'
2233
    ).forEach(script => {
2234
        plugins[script.id] = JSON.parse(script.textContent || '{}');
2235
    });
2236

2237
    CMS._plugins = Object.entries(plugins);
2238
    CMS._instances = CMS._plugins.map(function(args) {
2239
        return new CMS.Plugin(args[0], args[1]);
2240
    });
2241

2242
    // return the cms plugin instances just created
2243
    return CMS._instances;
2244
};
2245

2246
Plugin._updateClipboard = function _updateClipboard() {
1✔
2247
    clipboardDraggable = $('.cms-draggable-from-clipboard:first');
7✔
2248
};
2249

2250
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2251
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2252

2253
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2254

2255
    if (Helpers._isStorageSupported) {
2!
UNCOV
2256
        localStorage.setItem('cms-plugin-usage', JSON.stringify(pluginUsageMap));
×
2257
    }
2258
};
2259

2260
Plugin._removeAddPluginPlaceholder = function removeAddPluginPlaceholder() {
1✔
2261
    // this can't be cached since they are created and destroyed all over the place
2262
    $('.cms-add-plugin-placeholder').remove();
10✔
2263
};
2264

2265
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2266
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2267
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2268

2269
    // Re-read front-end editable fields ("general" plugins) from DOM
2270
    document.body.querySelectorAll('script[data-cms-general]').forEach(script => {
4✔
UNCOV
2271
        CMS._plugins.push([script.id, JSON.parse(script.textContent)]);
×
2272
    });
2273
    // Remove duplicates
2274
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2275

2276
    CMS._instances.forEach(instance => {
4✔
2277
        if (instance.options.type === 'placeholder') {
5✔
2278
            instance._setupUI(`cms-placeholder-${instance.options.placeholder_id}`);
2✔
2279
            instance._ensureData();
2✔
2280
            instance.ui.container.data('cms', instance.options);
2✔
2281
            instance._setPlaceholder();
2✔
2282
        }
2283
    });
2284

2285
    CMS._instances.forEach(instance => {
4✔
2286
        if (instance.options.type === 'plugin') {
5✔
2287
            instance._setupUI(`cms-plugin-${instance.options.plugin_id}`);
2✔
2288
            instance._ensureData();
2✔
2289
            instance.ui.container.data('cms').push(instance.options);
2✔
2290
            instance._setPluginContentEvents();
2✔
2291
        }
2292
    });
2293

2294
    CMS._plugins.forEach(([type, opts]) => {
4✔
2295
        if (opts.type !== 'placeholder' && opts.type !== 'plugin') {
16✔
2296
            const instance = find(
8✔
2297
                CMS._instances,
2298
                i => i.options.type === opts.type && Number(i.options.plugin_id) === Number(opts.plugin_id)
13✔
2299
            );
2300

2301
            if (instance) {
8✔
2302
                // update
2303
                instance._setupUI(type);
1✔
2304
                instance._ensureData();
1✔
2305
                instance.ui.container.data('cms').push(instance.options);
1✔
2306
                instance._setGeneric();
1✔
2307
            } else {
2308
                // create
2309
                CMS._instances.push(new Plugin(type, opts));
7✔
2310
            }
2311
        }
2312
    });
2313
};
2314

2315
Plugin._getPluginById = function(id) {
1✔
2316
    return find(CMS._instances, ({ options }) => options.type === 'plugin' && Number(options.plugin_id) === Number(id));
20!
2317
};
2318

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

2324
    plugins.forEach((element, index) => {
10✔
2325
        const pluginId = CMS.API.StructureBoard.getId($(element));
20✔
2326
        const instance = Plugin._getPluginById(pluginId);
20✔
2327

2328
        if (!instance) {
20!
2329
            return;
20✔
2330
        }
2331

UNCOV
2332
        instance.options.position = index + 1;
×
2333
    });
2334
};
2335

2336
Plugin._recalculatePluginPositions = function(action, data) {
1✔
UNCOV
2337
    if (action === 'MOVE') {
×
2338
        // le sigh - recalculate all placeholders cause we don't know from where the
2339
        // plugin was moved from
UNCOV
2340
        filter(CMS._instances, ({ options }) => options.type === 'placeholder')
×
UNCOV
2341
            .map(({ options }) => options.placeholder_id)
×
UNCOV
2342
            .forEach(placeholder_id => Plugin._updatePluginPositions(placeholder_id));
×
UNCOV
2343
    } else if (data.placeholder_id) {
×
2344
        Plugin._updatePluginPositions(data.placeholder_id);
×
2345
    }
2346
};
2347

2348
// shorthand for jQuery(document).ready();
2349
$(Plugin._initializeGlobalHandlers);
1✔
2350

2351
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

© 2026 Coveralls, Inc