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

divio / django-cms / #29071

19 Sep 2024 09:28AM UTC coverage: 76.257% (-0.09%) from 76.342%
#29071

push

travis-ci

web-flow
Merge b708e069b into 921c020cb

1044 of 1558 branches covered (67.01%)

1 of 6 new or added lines in 1 file covered. (16.67%)

175 existing lines in 1 file now uncovered.

2518 of 3302 relevant lines covered (76.26%)

26.92 hits per line

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

59.22
/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);
178✔
65

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

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

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

79
        // determine type of plugin
80
        switch (this.options.type) {
176✔
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);
129✔
91
                Plugin.aliasPluginDuplicatesMap[this.options.plugin_id] = true;
129✔
92
                this._setPlugin();
129✔
93
                if (isStructureReady()) {
129!
94
                    this._collapsables();
129✔
95
                }
96
                break;
129✔
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')) {
178✔
107
            this.ui.container.data('cms', []);
173✔
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
        var wrapper = $(`.${container}`);
178✔
121
        var 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/)) {
178✔
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
            var contentWrappers = wrapper.toArray().reduce((wrappers, elem, index) => {
135✔
134
                if (index === 0) {
272✔
135
                    wrappers[0].push(elem);
135✔
136
                    return wrappers;
135✔
137
                }
138

139
                var lastWrapper = wrappers[wrappers.length - 1];
137✔
140
                var lastItemInWrapper = lastWrapper[lastWrapper.length - 1];
137✔
141

142
                if ($(lastItemInWrapper).is('.cms-plugin-end')) {
137✔
143
                    wrappers.push([elem]);
1✔
144
                } else {
145
                    lastWrapper.push(elem);
136✔
146
                }
147

148
                return wrappers;
137✔
149
            }, [[]]);
150

151
            // then we map that structure into an array of jquery collections
152
            // from which we filter out empty ones
153
            contents = contentWrappers
135✔
154
                .map(items => {
155
                    var templateStart = $(items[0]);
136✔
156
                    var className = templateStart.attr('class').replace('cms-plugin-start', '');
136✔
157

158
                    var itemContents = $(nextUntil(templateStart[0], container));
136✔
159

160
                    $(items).filter('template').remove();
136✔
161

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

167
                            element.wrap('<cms-plugin class="cms-plugin-text-node"></cms-plugin>');
10✔
168
                            itemContents[index] = element.parent()[0];
10✔
169
                        }
170
                    });
171

172
                    // otherwise we don't really need text nodes or comment nodes or empty text nodes
173
                    itemContents = itemContents.filter(function() {
136✔
174
                        return this.nodeType !== Node.TEXT_NODE && this.nodeType !== Node.COMMENT_NODE;
157✔
175
                    });
176

177
                    itemContents.addClass(`cms-plugin ${className}`);
136✔
178

179
                    return itemContents;
136✔
180
                })
181
                .filter(v => v.length);
136✔
182

183
            if (contents.length) {
135!
184
                // and then reduce it to one big collection
185
                contents = contents.reduce((collection, items) => collection.add(items), $());
136✔
186
            }
187
        } else {
188
            contents = wrapper;
43✔
189
        }
190

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

196
        this.ui = this.ui || {};
178✔
197
        this.ui.container = contents;
178✔
198
    },
199

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

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

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

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

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

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

237
        this._checkIfPasteAllowed();
23✔
238
    },
239

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

255
    _setPluginStructureEvents: function _setPluginStructureEvents() {
256
        var that = this;
129✔
257

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

264
        this.ui.draggable.data('cms', this.options);
129✔
265

266
        this.ui.dragitem.on(Plugin.doubleClick, this._dblClickToEditHandler.bind(this));
129✔
267

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

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

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

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

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

288
            var data = dragitem.data('cms');
5✔
289

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

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

298
            that.movePlugin(data);
5✔
299
        });
300

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

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

334
            // clickability of "Paste" menu item
335
            this._checkIfPasteAllowed();
129✔
336
        });
337
    },
338

339
    _dblClickToEditHandler: function _dblClickToEditHandler(e) {
340
        var that = this;
×
UNCOV
341
        var disabled = $(e.currentTarget).closest('.cms-drag-disabled');
×
NEW
342
        var edit_disabled = $(e.currentTarget).closest('.cms-draggable').hasClass('cms-edit-disabled');
×
343

344
        e.preventDefault();
×
UNCOV
345
        e.stopPropagation();
×
346

NEW
347
        if (!disabled.length && !edit_disabled) {
×
UNCOV
348
            that.editPlugin(
×
349
                Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
350
                that.options.plugin_name,
351
                that._getPluginBreadcrumbs()
352
            );
353
        }
354
    },
355

356
    _setPluginContentEvents: function _setPluginContentEvents() {
357
        const pluginDoubleClickEvent = this._getNamepacedEvent(Plugin.doubleClick);
129✔
358

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

386
        if (!Plugin._isContainingMultiplePlugins(this.ui.container)) {
129✔
387
            // only allow editing by double-click if not disabled
388
            var selector = `.cms-plugin-${this.options.plugin_id}:not(.cms-edit-disabled)`;
128✔
389

390
            $document
128✔
391
                .off(pluginDoubleClickEvent, selector)
392
                .on(
393
                    pluginDoubleClickEvent,
394
                    selector,
395
                    this._dblClickToEditHandler.bind(this)
396
                );
397
        }
398
    },
399

400
    /**
401
     * Sets up behaviours and ui for generics.
402
     * Generics do not show up in structure board.
403
     *
404
     * @method _setGeneric
405
     * @private
406
     */
407
    _setGeneric: function() {
408
        var that = this;
24✔
409

410
        // adds double click to edit
411
        this.ui.container.off(Plugin.doubleClick).on(Plugin.doubleClick, function(e) {
24✔
UNCOV
412
            e.preventDefault();
×
UNCOV
413
            e.stopPropagation();
×
UNCOV
414
            that.editPlugin(Helpers.updateUrlWithPath(that.options.urls.edit_plugin), that.options.plugin_name, []);
×
415
        });
416

417
        // adds edit tooltip
418
        this.ui.container
24✔
419
            .off(Plugin.pointerOverAndOut + ' ' + Plugin.touchStart)
420
            .on(Plugin.pointerOverAndOut + ' ' + Plugin.touchStart, function(e) {
421
                if (e.type !== 'touchstart') {
×
422
                    e.stopPropagation();
×
423
                }
424
                var name = that.options.plugin_name;
×
UNCOV
425
                var id = that.options.plugin_id;
×
NEW
426
                var disabled = $(e.currentTarget).hasClass('.cms-edit-disabled');  // No tooltip for disabled plugins
×
427

NEW
428
                CMS.API.Tooltip.displayToggle(
×
429
                    (e.type === 'pointerover' || e.type === 'touchstart') && !disabled,
×
430
                    e,
431
                    name,
432
                    id
433
                );
434
            });
435
    },
436

437
    /**
438
     * Checks if paste is allowed into current plugin/placeholder based
439
     * on restrictions we have. Also determines which tooltip to show.
440
     *
441
     * WARNING: this relies on clipboard plugins always being instantiated
442
     * first, so they have data('cms') by the time this method is called.
443
     *
444
     * @method _checkIfPasteAllowed
445
     * @private
446
     * @returns {Boolean}
447
     */
448
    _checkIfPasteAllowed: function _checkIfPasteAllowed() {
449
        var pasteButton = this.ui.dropdown.find('[data-rel=paste]');
150✔
450
        var pasteItem = pasteButton.parent();
150✔
451

452
        if (!clipboardDraggable.length) {
150✔
453
            pasteItem.addClass('cms-submenu-item-disabled');
85✔
454
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
85✔
455
            pasteItem.find('.cms-submenu-item-paste-tooltip-empty').css('display', 'block');
85✔
456
            return false;
85✔
457
        }
458

459
        if (this.ui.draggable && this.ui.draggable.hasClass('cms-draggable-disabled')) {
65✔
460
            pasteItem.addClass('cms-submenu-item-disabled');
45✔
461
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
45✔
462
            pasteItem.find('.cms-submenu-item-paste-tooltip-disabled').css('display', 'block');
45✔
463
            return false;
45✔
464
        }
465

466
        var bounds = this.options.plugin_restriction;
20✔
467

468
        if (clipboardDraggable.data('cms')) {
20!
469
            var clipboardPluginData = clipboardDraggable.data('cms');
20✔
470
            var type = clipboardPluginData.plugin_type;
20✔
471
            var parent_bounds = $.grep(clipboardPluginData.plugin_parent_restriction, function(restriction) {
20✔
472
                // special case when PlaceholderPlugin has a parent restriction named "0"
473
                return restriction !== '0';
20✔
474
            });
475
            var currentPluginType = this.options.plugin_type;
20✔
476

477
            if (
20✔
478
                (bounds.length && $.inArray(type, bounds) === -1) ||
60!
479
                (parent_bounds.length && $.inArray(currentPluginType, parent_bounds) === -1)
480
            ) {
481
                pasteItem.addClass('cms-submenu-item-disabled');
15✔
482
                pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
15✔
483
                pasteItem.find('.cms-submenu-item-paste-tooltip-restricted').css('display', 'block');
15✔
484
                return false;
15✔
485
            }
486
        } else {
UNCOV
487
            return false;
×
488
        }
489

490
        pasteItem.find('a').removeAttr('tabindex').removeAttr('aria-disabled');
5✔
491
        pasteItem.removeClass('cms-submenu-item-disabled');
5✔
492

493
        return true;
5✔
494
    },
495

496
    /**
497
     * Calls api to create a plugin and then proceeds to edit it.
498
     *
499
     * @method addPlugin
500
     * @param {String} type type of the plugin, e.g "Bootstrap3ColumnCMSPlugin"
501
     * @param {String} name name of the plugin, e.g. "Column"
502
     * @param {String} parent id of a parent plugin
503
     */
504
    addPlugin: function(type, name, parent) {
505
        var params = {
3✔
506
            placeholder_id: this.options.placeholder_id,
507
            plugin_type: type,
508
            cms_path: path,
509
            plugin_language: CMS.config.request.language,
510
            plugin_position: this._getPluginAddPosition()
511
        };
512

513
        if (parent) {
3✔
514
            params.plugin_parent = parent;
1✔
515
        }
516
        var url = this.options.urls.add_plugin + '?' + $.param(params);
3✔
517
        var modal = new Modal({
3✔
518
            onClose: this.options.onClose || false,
5✔
519
            redirectOnClose: this.options.redirectOnClose || false
5✔
520
        });
521

522
        modal.open({
3✔
523
            url: url,
524
            title: name
525
        });
526

527
        this.modal = modal;
3✔
528

529
        Helpers.removeEventListener('modal-closed.add-plugin');
3✔
530
        Helpers.addEventListener('modal-closed.add-plugin', (e, { instance }) => {
3✔
531
            if (instance !== modal) {
1!
UNCOV
532
                return;
×
533
            }
534
            Plugin._removeAddPluginPlaceholder();
1✔
535
        });
536
    },
537

538
    _getPluginAddPosition: function() {
UNCOV
539
        if (this.options.type === 'placeholder') {
×
UNCOV
540
            return $(`.cms-dragarea-${this.options.placeholder_id} .cms-draggable`).length + 1;
×
541
        }
542

543
        // assume plugin now
544
        // would prefer to get the information from the tree, but the problem is that the flat data
545
        // isn't sorted by position
546
        const maybeChildren = this.ui.draggable.find('.cms-draggable');
×
547

548
        if (maybeChildren.length) {
×
UNCOV
549
            const lastChild = maybeChildren.last();
×
550

UNCOV
551
            const lastChildInstance = Plugin._getPluginById(this._getId(lastChild));
×
552

553
            return lastChildInstance.options.position + 1;
×
554
        }
555

UNCOV
556
        return this.options.position + 1;
×
557
    },
558

559
    /**
560
     * Opens the modal for editing a plugin.
561
     *
562
     * @method editPlugin
563
     * @param {String} url editing url
564
     * @param {String} name Name of the plugin, e.g. "Column"
565
     * @param {Object[]} breadcrumb array of objects representing a breadcrumb,
566
     *     each item is `{ title: 'string': url: 'string' }`
567
     */
568
    editPlugin: function(url, name, breadcrumb) {
569
        // trigger modal window
570
        var modal = new Modal({
3✔
571
            onClose: this.options.onClose || false,
6✔
572
            redirectOnClose: this.options.redirectOnClose || false
6✔
573
        });
574

575
        this.modal = modal;
3✔
576

577
        Helpers.removeEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin');
3✔
578
        Helpers.addEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin', (e, { instance }) => {
3✔
579
            if (instance === modal) {
1!
580
                // cannot be cached
581
                Plugin._removeAddPluginPlaceholder();
1✔
582
            }
583
        });
584
        modal.open({
3✔
585
            url: url,
586
            title: name,
587
            breadcrumbs: breadcrumb,
588
            width: 850
589
        });
590
    },
591

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

612
        // set correct options (don't mutate them)
613
        var options = $.extend({}, opts || this.options);
8✔
614
        var sourceLanguage = source_language;
8✔
615
        let copyingFromLanguage = false;
8✔
616

617
        if (sourceLanguage) {
8✔
618
            copyingFromLanguage = true;
1✔
619
            options.target = options.placeholder_id;
1✔
620
            options.plugin_id = '';
1✔
621
            options.parent = '';
1✔
622
        } else {
623
            sourceLanguage = CMS.config.request.language;
7✔
624
        }
625

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

655
                // trigger error
656
                CMS.API.Messages.open({
3✔
657
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
4✔
658
                    error: true
659
                });
660
            }
661
        };
662

663
        $.ajax(request);
8✔
664
    },
665

666
    /**
667
     * Essentially clears clipboard and moves plugin to a clipboard
668
     * placholder through `movePlugin`.
669
     *
670
     * @method cutPlugin
671
     * @returns {Boolean|void}
672
     */
673
    cutPlugin: function() {
674
        // if cut is once triggered, prevent additional actions
675
        if (CMS.API.locked) {
9✔
676
            return false;
1✔
677
        }
678
        CMS.API.locked = true;
8✔
679

680
        var that = this;
8✔
681
        var data = {
8✔
682
            placeholder_id: CMS.config.clipboard.id,
683
            plugin_id: this.options.plugin_id,
684
            plugin_parent: '',
685
            target_language: CMS.config.request.language,
686
            csrfmiddlewaretoken: CMS.config.csrf
687
        };
688

689
        // move plugin
690
        $.ajax({
8✔
691
            type: 'POST',
692
            url: Helpers.updateUrlWithPath(that.options.urls.move_plugin),
693
            data: data,
694
            success: function(response) {
695
                CMS.API.locked = false;
4✔
696
                CMS.API.Messages.open({
4✔
697
                    message: CMS.config.lang.success
698
                });
699
                CMS.API.StructureBoard.invalidateState('CUT', $.extend({}, data, response));
4✔
700
                hideLoader();
4✔
701
            },
702
            error: function(jqXHR) {
703
                CMS.API.locked = false;
3✔
704
                var msg = CMS.config.lang.error;
3✔
705

706
                // trigger error
707
                CMS.API.Messages.open({
3✔
708
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
4✔
709
                    error: true
710
                });
711
                hideLoader();
3✔
712
            }
713
        });
714
    },
715

716
    /**
717
     * Method is called when you click on the paste button on the plugin.
718
     * Uses existing solution of `copyPlugin(options)`
719
     *
720
     * @method pastePlugin
721
     */
722
    pastePlugin: function() {
723
        var id = this._getId(clipboardDraggable);
5✔
724
        var eventData = {
5✔
725
            id: id
726
        };
727

728
        const clipboardDraggableClone = clipboardDraggable.clone(true, true);
5✔
729

730
        clipboardDraggableClone.appendTo(this.ui.draggables);
5✔
731
        if (this.options.plugin_id) {
5✔
732
            StructureBoard.actualizePluginCollapseStatus(this.options.plugin_id);
4✔
733
        }
734
        this.ui.draggables.trigger('cms-structure-update', [eventData]);
5✔
735
        clipboardDraggableClone.trigger('cms-paste-plugin-update', [eventData]);
5✔
736
    },
737

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

757
        // set correct options
758
        var options = opts || this.options;
11✔
759

760
        var dragitem = $(`.cms-draggable-${options.plugin_id}:last`);
11✔
761

762
        // SAVING POSITION
763
        var placeholder_id = this._getId(dragitem.parents('.cms-draggables').last().prevAll('.cms-dragbar').first());
11✔
764

765
        // cancel here if we have no placeholder id
766
        if (placeholder_id === false) {
11✔
767
            return false;
1✔
768
        }
769
        var pluginParentElement = dragitem.parent().closest('.cms-draggable');
10✔
770
        var plugin_parent = this._getId(pluginParentElement);
10✔
771

772
        // gather the data for ajax request
773
        var data = {
10✔
774
            plugin_id: options.plugin_id,
775
            plugin_parent: plugin_parent || '',
20✔
776
            target_language: CMS.config.request.language,
777
            csrfmiddlewaretoken: CMS.config.csrf,
778
            move_a_copy: options.move_a_copy
779
        };
780

781
        if (Number(placeholder_id) === Number(options.placeholder_id)) {
10!
782
            Plugin._updatePluginPositions(options.placeholder_id);
10✔
783
        } else {
784
            data.placeholder_id = placeholder_id;
×
785

UNCOV
786
            Plugin._updatePluginPositions(placeholder_id);
×
UNCOV
787
            Plugin._updatePluginPositions(options.placeholder_id);
×
788
        }
789

790
        var position = this.options.position;
10✔
791

792
        data.target_position = position;
10✔
793

794
        showLoader();
10✔
795

796
        $.ajax({
10✔
797
            type: 'POST',
798
            url: Helpers.updateUrlWithPath(options.urls.move_plugin),
799
            data: data,
800
            success: function(response) {
801
                CMS.API.StructureBoard.invalidateState(
4✔
802
                    data.move_a_copy ? 'PASTE' : 'MOVE',
4!
803
                    $.extend({}, data, { placeholder_id: placeholder_id }, response)
804
                );
805

806
                // enable actions again
807
                CMS.API.locked = false;
4✔
808
                hideLoader();
4✔
809
            },
810
            error: function(jqXHR) {
811
                CMS.API.locked = false;
4✔
812
                var msg = CMS.config.lang.error;
4✔
813

814
                // trigger error
815
                CMS.API.Messages.open({
4✔
816
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
5✔
817
                    error: true
818
                });
819
                hideLoader();
4✔
820
            }
821
        });
822
    },
823

824
    /**
825
     * Changes the settings attributes on an initialised plugin.
826
     *
827
     * @method _setSettings
828
     * @param {Object} oldSettings current settings
829
     * @param {Object} newSettings new settings to be applied
830
     * @private
831
     */
832
    _setSettings: function _setSettings(oldSettings, newSettings) {
UNCOV
833
        var settings = $.extend(true, {}, oldSettings, newSettings);
×
UNCOV
834
        var plugin = $('.cms-plugin-' + settings.plugin_id);
×
835
        var draggable = $('.cms-draggable-' + settings.plugin_id);
×
836

837
        // set new setting on instance and plugin data
838
        this.options = settings;
×
UNCOV
839
        if (plugin.length) {
×
UNCOV
840
            var index = plugin.data('cms').findIndex(function(pluginData) {
×
841
                return pluginData.plugin_id === settings.plugin_id;
×
842
            });
843

UNCOV
844
            plugin.each(function() {
×
845
                $(this).data('cms')[index] = settings;
×
846
            });
847
        }
UNCOV
848
        if (draggable.length) {
×
UNCOV
849
            draggable.data('cms', settings);
×
850
        }
851
    },
852

853
    /**
854
     * Opens a modal to delete a plugin.
855
     *
856
     * @method deletePlugin
857
     * @param {String} url admin url for deleting a page
858
     * @param {String} name plugin name, e.g. "Column"
859
     * @param {Object[]} breadcrumb array of objects representing a breadcrumb,
860
     *     each item is `{ title: 'string': url: 'string' }`
861
     */
862
    deletePlugin: function(url, name, breadcrumb) {
863
        // trigger modal window
864
        var modal = new Modal({
2✔
865
            onClose: this.options.onClose || false,
4✔
866
            redirectOnClose: this.options.redirectOnClose || false
4✔
867
        });
868

869
        this.modal = modal;
2✔
870

871
        Helpers.removeEventListener('modal-loaded.delete-plugin');
2✔
872
        Helpers.addEventListener('modal-loaded.delete-plugin', (e, { instance }) => {
2✔
873
            if (instance === modal) {
5✔
874
                Plugin._removeAddPluginPlaceholder();
1✔
875
            }
876
        });
877
        modal.open({
2✔
878
            url: url,
879
            title: name,
880
            breadcrumbs: breadcrumb
881
        });
882
    },
883

884
    /**
885
     * Destroys the current plugin instance removing only the DOM listeners
886
     *
887
     * @method destroy
888
     * @param {Object}  options - destroy config options
889
     * @param {Boolean} options.mustCleanup - if true it will remove also the plugin UI components from the DOM
890
     * @returns {void}
891
     */
892
    destroy(options = {}) {
1✔
893
        const mustCleanup = options.mustCleanup || false;
2✔
894

895
        // close the plugin modal if it was open
896
        if (this.modal) {
2!
UNCOV
897
            this.modal.close();
×
898
            // unsubscribe to all the modal events
UNCOV
899
            this.modal.off();
×
900
        }
901

902
        if (mustCleanup) {
2✔
903
            this.cleanup();
1✔
904
        }
905

906
        // remove event bound to global elements like document or window
907
        $document.off(`.${this.uid}`);
2✔
908
        $window.off(`.${this.uid}`);
2✔
909
    },
910

911
    /**
912
     * Remove the plugin specific ui elements from the DOM
913
     *
914
     * @method cleanup
915
     * @returns {void}
916
     */
917
    cleanup() {
918
        // remove all the plugin UI DOM elements
919
        // notice that $.remove will remove also all the ui specific events
920
        // previously attached to them
921
        Object.keys(this.ui).forEach(el => this.ui[el].remove());
12✔
922
    },
923

924
    /**
925
     * Called after plugin is added through ajax.
926
     *
927
     * @method editPluginPostAjax
928
     * @param {Object} toolbar CMS.API.Toolbar instance (not used)
929
     * @param {Object} response response from server
930
     */
931
    editPluginPostAjax: function(toolbar, response) {
932
        this.editPlugin(Helpers.updateUrlWithPath(response.url), this.options.plugin_name, response.breadcrumb);
1✔
933
    },
934

935
    /**
936
     * _setSettingsMenu sets up event handlers for settings menu.
937
     *
938
     * @method _setSettingsMenu
939
     * @private
940
     * @param {jQuery} nav
941
     */
942
    _setSettingsMenu: function _setSettingsMenu(nav) {
943
        var that = this;
152✔
944

945
        this.ui.dropdown = nav.siblings('.cms-submenu-dropdown-settings');
152✔
946
        var dropdown = this.ui.dropdown;
152✔
947

948
        nav
152✔
949
            .off(Plugin.pointerUp)
950
            .on(Plugin.pointerUp, function(e) {
UNCOV
951
                e.preventDefault();
×
952
                e.stopPropagation();
×
953
                var trigger = $(this);
×
954

955
                if (trigger.hasClass('cms-btn-active')) {
×
956
                    Plugin._hideSettingsMenu(trigger);
×
957
                } else {
UNCOV
958
                    Plugin._hideSettingsMenu();
×
UNCOV
959
                    that._showSettingsMenu(trigger);
×
960
                }
961
            })
962
            .off(Plugin.touchStart)
963
            .on(Plugin.touchStart, function(e) {
964
                // required on some touch devices so
965
                // ui touch punch is not triggering mousemove
966
                // which in turn results in pep triggering pointercancel
UNCOV
967
                e.stopPropagation();
×
968
            });
969

970
        dropdown
152✔
971
            .off(Plugin.mouseEvents)
972
            .on(Plugin.mouseEvents, function(e) {
UNCOV
973
                e.stopPropagation();
×
974
            })
975
            .off(Plugin.touchStart)
976
            .on(Plugin.touchStart, function(e) {
977
                // required for scrolling on mobile
UNCOV
978
                e.stopPropagation();
×
979
            });
980

981
        that._setupActions(nav);
152✔
982
        // prevent propagation
983
        nav
152✔
984
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '))
985
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
UNCOV
986
                e.stopPropagation();
×
987
            });
988

989
        nav
152✔
990
            .siblings('.cms-quicksearch, .cms-submenu-dropdown-settings')
991
            .off([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '))
992
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
UNCOV
993
                e.stopPropagation();
×
994
            });
995
    },
996

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

1020
        if (!isInViewport) {
3✔
1021
            scrollable.animate(
2✔
1022
                {
1023
                    scrollTop: elPosition + offset + elHeight + scrollTop - scrollHeight
1024
                },
1025
                duration
1026
            );
1027
        }
1028
    },
1029

1030
    /**
1031
     * Opens a modal with traversable plugins list, adds a placeholder to where
1032
     * the plugin will be added.
1033
     *
1034
     * @method _setAddPluginModal
1035
     * @private
1036
     * @param {jQuery} nav modal trigger element
1037
     * @returns {Boolean|void}
1038
     */
1039
    _setAddPluginModal: function _setAddPluginModal(nav) {
1040
        if (nav.hasClass('cms-btn-disabled')) {
152✔
1041
            return false;
87✔
1042
        }
1043
        var that = this;
65✔
1044
        var modal;
1045
        var isTouching;
1046
        var plugins;
1047

1048
        var initModal = once(function initModal() {
65✔
1049
            var placeholder = $(
×
1050
                '<div class="cms-add-plugin-placeholder">' + CMS.config.lang.addPluginPlaceholder + '</div>'
1051
            );
UNCOV
1052
            var dragItem = nav.closest('.cms-dragitem');
×
1053
            var isPlaceholder = !dragItem.length;
×
1054
            var childrenList;
1055

UNCOV
1056
            modal = new Modal({
×
1057
                minWidth: 400,
1058
                minHeight: 400
1059
            });
1060

1061
            if (isPlaceholder) {
×
UNCOV
1062
                childrenList = nav.closest('.cms-dragarea').find('> .cms-draggables');
×
1063
            } else {
1064
                childrenList = nav.closest('.cms-draggable').find('> .cms-draggables');
×
1065
            }
1066

UNCOV
1067
            Helpers.addEventListener('modal-loaded', (e, { instance }) => {
×
UNCOV
1068
                if (instance !== modal) {
×
1069
                    return;
×
1070
                }
1071

UNCOV
1072
                that._setupKeyboardTraversing();
×
1073
                if (childrenList.hasClass('cms-hidden') && !isPlaceholder) {
×
1074
                    that._toggleCollapsable(dragItem);
×
1075
                }
UNCOV
1076
                Plugin._removeAddPluginPlaceholder();
×
UNCOV
1077
                placeholder.appendTo(childrenList);
×
1078
                that._scrollToElement(placeholder);
×
1079
            });
1080

UNCOV
1081
            Helpers.addEventListener('modal-closed', (e, { instance }) => {
×
1082
                if (instance !== modal) {
×
UNCOV
1083
                    return;
×
1084
                }
1085
                Plugin._removeAddPluginPlaceholder();
×
1086
            });
1087

UNCOV
1088
            Helpers.addEventListener('modal-shown', (e, { instance }) => {
×
1089
                if (modal !== instance) {
×
UNCOV
1090
                    return;
×
1091
                }
UNCOV
1092
                var dropdown = $('.cms-modal-markup .cms-plugin-picker');
×
1093

1094
                if (!isTouching) {
×
1095
                    // only focus the field if using mouse
1096
                    // otherwise keyboard pops up
UNCOV
1097
                    dropdown.find('input').trigger('focus');
×
1098
                }
1099
                isTouching = false;
×
1100
            });
1101

UNCOV
1102
            plugins = nav.siblings('.cms-plugin-picker');
×
1103

UNCOV
1104
            that._setupQuickSearch(plugins);
×
1105
        });
1106

1107
        nav
65✔
1108
            .on(Plugin.touchStart, function(e) {
UNCOV
1109
                isTouching = true;
×
1110
                // required on some touch devices so
1111
                // ui touch punch is not triggering mousemove
1112
                // which in turn results in pep triggering pointercancel
1113
                e.stopPropagation();
×
1114
            })
1115
            .on(Plugin.pointerUp, function(e) {
1116
                e.preventDefault();
×
UNCOV
1117
                e.stopPropagation();
×
1118

UNCOV
1119
                Plugin._hideSettingsMenu();
×
1120

UNCOV
1121
                initModal();
×
1122

1123
                // since we don't know exact plugin parent (because dragndrop)
1124
                // we need to know the parent id by the time we open "add plugin" dialog
UNCOV
1125
                var pluginsCopy = that._updateWithMostUsedPlugins(
×
1126
                    plugins
1127
                        .clone(true, true)
1128
                        .data('parentId', that._getId(nav.closest('.cms-draggable')))
1129
                        .append(that._getPossibleChildClasses())
1130
                );
1131

UNCOV
1132
                modal.open({
×
1133
                    title: that.options.addPluginHelpTitle,
1134
                    html: pluginsCopy,
1135
                    width: 530,
1136
                    height: 400
1137
                });
1138
            });
1139

1140
        // prevent propagation
1141
        nav.on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
65✔
UNCOV
1142
            e.stopPropagation();
×
1143
        });
1144

1145
        nav
65✔
1146
            .siblings('.cms-quicksearch, .cms-submenu-dropdown')
1147
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
UNCOV
1148
                e.stopPropagation();
×
1149
            });
1150
    },
1151

1152
    _updateWithMostUsedPlugins: function _updateWithMostUsedPlugins(plugins) {
1153
        const items = plugins.find('.cms-submenu-item');
×
1154
        // eslint-disable-next-line no-unused-vars
UNCOV
1155
        const mostUsedPlugins = toPairs(pluginUsageMap).sort(([x, a], [y, b]) => a - b).reverse();
×
1156
        const MAX_MOST_USED_PLUGINS = 5;
×
1157
        let count = 0;
×
1158

UNCOV
1159
        if (items.filter(':not(.cms-submenu-item-title)').length <= MAX_MOST_USED_PLUGINS) {
×
1160
            return plugins;
×
1161
        }
1162

1163
        let ref = plugins.find('.cms-quicksearch');
×
1164

UNCOV
1165
        mostUsedPlugins.forEach(([name]) => {
×
1166
            if (count === MAX_MOST_USED_PLUGINS) {
×
UNCOV
1167
                return;
×
1168
            }
1169
            const item = items.find(`[href=${name}]`);
×
1170

1171
            if (item.length) {
×
1172
                const clone = item.closest('.cms-submenu-item').clone(true, true);
×
1173

UNCOV
1174
                ref.after(clone);
×
UNCOV
1175
                ref = clone;
×
UNCOV
1176
                count += 1;
×
1177
            }
1178
        });
1179

UNCOV
1180
        if (count) {
×
UNCOV
1181
            plugins.find('.cms-quicksearch').after(
×
1182
                $(`<div class="cms-submenu-item cms-submenu-item-title" data-cms-most-used>
1183
                    <span>${CMS.config.lang.mostUsed}</span>
1184
                </div>`)
1185
            );
1186
        }
1187

UNCOV
1188
        return plugins;
×
1189
    },
1190

1191
    /**
1192
     * Returns a specific plugin namespaced event postfixing the plugin uid to it
1193
     * in order to properly manage it via jQuery $.on and $.off
1194
     *
1195
     * @method _getNamepacedEvent
1196
     * @private
1197
     * @param {String} base - plugin event type
1198
     * @param {String} additionalNS - additional namespace (like '.traverse' for example)
1199
     * @returns {String} a specific plugin event
1200
     *
1201
     * @example
1202
     *
1203
     * plugin._getNamepacedEvent(Plugin.click); // 'click.cms.plugin.42'
1204
     * plugin._getNamepacedEvent(Plugin.keyDown, '.traverse'); // 'keydown.cms.plugin.traverse.42'
1205
     */
1206
    _getNamepacedEvent(base, additionalNS = '') {
132✔
1207
        return `${base}${additionalNS ? '.'.concat(additionalNS) : ''}.${this.uid}`;
143✔
1208
    },
1209

1210
    /**
1211
     * Returns available plugin/placeholder child classes markup
1212
     * for "Add plugin" modal
1213
     *
1214
     * @method _getPossibleChildClasses
1215
     * @private
1216
     * @returns {jQuery} "add plugin" menu
1217
     */
1218
    _getPossibleChildClasses: function _getPossibleChildClasses() {
1219
        var that = this;
33✔
1220
        var childRestrictions = this.options.plugin_restriction;
33✔
1221
        // have to check the placeholder every time, since plugin could've been
1222
        // moved as part of another plugin
1223
        var placeholderId = that._getId(that.ui.submenu.closest('.cms-dragarea'));
33✔
1224
        var resultElements = $($('#cms-plugin-child-classes-' + placeholderId).html());
33✔
1225

1226
        if (childRestrictions && childRestrictions.length) {
33✔
1227
            resultElements = resultElements.filter(function() {
29✔
1228
                var item = $(this);
4,727✔
1229

1230
                return (
4,727✔
1231
                    item.hasClass('cms-submenu-item-title') ||
9,106✔
1232
                    childRestrictions.indexOf(item.find('a').attr('href')) !== -1
1233
                );
1234
            });
1235

1236
            resultElements = resultElements.filter(function(index) {
29✔
1237
                var item = $(this);
411✔
1238

1239
                return (
411✔
1240
                    !item.hasClass('cms-submenu-item-title') ||
1,182✔
1241
                    (item.hasClass('cms-submenu-item-title') &&
1242
                        (!resultElements.eq(index + 1).hasClass('cms-submenu-item-title') &&
1243
                            resultElements.eq(index + 1).length))
1244
                );
1245
            });
1246
        }
1247

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

1250
        return resultElements;
33✔
1251
    },
1252

1253
    /**
1254
     * Sets up event handlers for quicksearching in the plugin picker.
1255
     *
1256
     * @method _setupQuickSearch
1257
     * @private
1258
     * @param {jQuery} plugins plugins picker element
1259
     */
1260
    _setupQuickSearch: function _setupQuickSearch(plugins) {
UNCOV
1261
        var that = this;
×
1262
        var FILTER_DEBOUNCE_TIMER = 100;
×
1263
        var FILTER_PICK_DEBOUNCE_TIMER = 110;
×
1264

UNCOV
1265
        var handler = debounce(function() {
×
1266
            var input = $(this);
×
1267
            // have to always find the pluginsPicker in the handler
1268
            // because of how we move things into/out of the modal
UNCOV
1269
            var pluginsPicker = input.closest('.cms-plugin-picker');
×
1270

1271
            that._filterPluginsList(pluginsPicker, input);
×
1272
        }, FILTER_DEBOUNCE_TIMER);
1273

UNCOV
1274
        plugins.find('> .cms-quicksearch').find('input').on(Plugin.keyUp, handler).on(
×
1275
            Plugin.keyUp,
1276
            debounce(function(e) {
1277
                var input;
1278
                var pluginsPicker;
1279

1280
                if (e.keyCode === KEYS.ENTER) {
×
UNCOV
1281
                    input = $(this);
×
UNCOV
1282
                    pluginsPicker = input.closest('.cms-plugin-picker');
×
UNCOV
1283
                    pluginsPicker
×
1284
                        .find('.cms-submenu-item')
1285
                        .not('.cms-submenu-item-title')
1286
                        .filter(':visible')
1287
                        .first()
1288
                        .find('> a')
1289
                        .focus()
1290
                        .trigger('click');
1291
                }
1292
            }, FILTER_PICK_DEBOUNCE_TIMER)
1293
        );
1294
    },
1295

1296
    /**
1297
     * Sets up click handlers for various plugin/placeholder items.
1298
     * Items can be anywhere in the plugin dragitem, not only in dropdown.
1299
     *
1300
     * @method _setupActions
1301
     * @private
1302
     * @param {jQuery} nav dropdown trigger with the items
1303
     */
1304
    _setupActions: function _setupActions(nav) {
1305
        var items = '.cms-submenu-edit, .cms-submenu-item a';
162✔
1306
        var parent = nav.parent();
162✔
1307

1308
        parent.find('.cms-submenu-edit').off(Plugin.touchStart).on(Plugin.touchStart, function(e) {
162✔
1309
            // required on some touch devices so
1310
            // ui touch punch is not triggering mousemove
1311
            // which in turn results in pep triggering pointercancel
1312
            e.stopPropagation();
1✔
1313
        });
1314
        parent.find(items).off(Plugin.click).on(Plugin.click, nav, e => this._delegate(e));
162✔
1315
    },
1316

1317
    /**
1318
     * Handler for the "action" items
1319
     *
1320
     * @method _delegate
1321
     * @param {$.Event} e event
1322
     * @private
1323
     */
1324
    // eslint-disable-next-line complexity
1325
    _delegate: function _delegate(e) {
1326
        e.preventDefault();
13✔
1327
        e.stopPropagation();
13✔
1328

1329
        var nav;
1330
        var that = this;
13✔
1331

1332
        if (e.data && e.data.nav) {
13!
UNCOV
1333
            nav = e.data.nav;
×
1334
        }
1335

1336
        // show loader and make sure scroll doesn't jump
1337
        showLoader();
13✔
1338

1339
        var items = '.cms-submenu-edit, .cms-submenu-item a';
13✔
1340
        var el = $(e.target).closest(items);
13✔
1341

1342
        Plugin._hideSettingsMenu(nav);
13✔
1343

1344
        // set switch for subnav entries
1345
        switch (el.attr('data-rel')) {
13!
1346
            // eslint-disable-next-line no-case-declarations
1347
            case 'add':
1348
                const pluginType = el.attr('href').replace('#', '');
2✔
1349

1350
                Plugin._updateUsageCount(pluginType);
2✔
1351
                that.addPlugin(pluginType, el.text(), el.closest('.cms-plugin-picker').data('parentId'));
2✔
1352
                break;
2✔
1353
            case 'ajax_add':
1354
                CMS.API.Toolbar.openAjax({
1✔
1355
                    url: el.attr('href'),
1356
                    post: JSON.stringify(el.data('post')),
1357
                    text: el.data('text'),
1358
                    callback: $.proxy(that.editPluginPostAjax, that),
1359
                    onSuccess: el.data('on-success')
1360
                });
1361
                break;
1✔
1362
            case 'edit':
1363
                that.editPlugin(
1✔
1364
                    Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
1365
                    that.options.plugin_name,
1366
                    that._getPluginBreadcrumbs()
1367
                );
1368
                break;
1✔
1369
            case 'copy-lang':
1370
                that.copyPlugin(that.options, el.attr('data-language'));
1✔
1371
                break;
1✔
1372
            case 'copy':
1373
                if (el.parent().hasClass('cms-submenu-item-disabled')) {
2✔
1374
                    hideLoader();
1✔
1375
                } else {
1376
                    that.copyPlugin();
1✔
1377
                }
1378
                break;
2✔
1379
            case 'cut':
1380
                that.cutPlugin();
1✔
1381
                break;
1✔
1382
            case 'paste':
1383
                hideLoader();
2✔
1384
                if (!el.parent().hasClass('cms-submenu-item-disabled')) {
2✔
1385
                    that.pastePlugin();
1✔
1386
                }
1387
                break;
2✔
1388
            case 'delete':
1389
                that.deletePlugin(
1✔
1390
                    Helpers.updateUrlWithPath(that.options.urls.delete_plugin),
1391
                    that.options.plugin_name,
1392
                    that._getPluginBreadcrumbs()
1393
                );
1394
                break;
1✔
1395
            case 'highlight':
1396
                hideLoader();
×
1397
                // eslint-disable-next-line no-magic-numbers
1398
                window.location.hash = `cms-plugin-${this.options.plugin_id}`;
×
UNCOV
1399
                Plugin._highlightPluginContent(this.options.plugin_id, { seeThrough: true });
×
UNCOV
1400
                e.stopImmediatePropagation();
×
UNCOV
1401
                break;
×
1402
            default:
1403
                hideLoader();
2✔
1404
                CMS.API.Toolbar._delegate(el);
2✔
1405
        }
1406
    },
1407

1408
    /**
1409
     * Sets up keyboard traversing of plugin picker.
1410
     *
1411
     * @method _setupKeyboardTraversing
1412
     * @private
1413
     */
1414
    _setupKeyboardTraversing: function _setupKeyboardTraversing() {
1415
        var dropdown = $('.cms-modal-markup .cms-plugin-picker');
3✔
1416
        const keyDownTraverseEvent = this._getNamepacedEvent(Plugin.keyDown, 'traverse');
3✔
1417

1418
        if (!dropdown.length) {
3✔
1419
            return;
1✔
1420
        }
1421
        // add key events
1422
        $document.off(keyDownTraverseEvent);
2✔
1423
        // istanbul ignore next: not really possible to reproduce focus state in unit tests
1424
        $document.on(keyDownTraverseEvent, function(e) {
1425
            var anchors = dropdown.find('.cms-submenu-item:visible a');
1426
            var index = anchors.index(anchors.filter(':focus'));
1427

1428
            // bind arrow down and tab keys
1429
            if (e.keyCode === KEYS.DOWN || (e.keyCode === KEYS.TAB && !e.shiftKey)) {
1430
                e.preventDefault();
1431
                if (index >= 0 && index < anchors.length - 1) {
1432
                    anchors.eq(index + 1).focus();
1433
                } else {
1434
                    anchors.eq(0).focus();
1435
                }
1436
            }
1437

1438
            // bind arrow up and shift+tab keys
1439
            if (e.keyCode === KEYS.UP || (e.keyCode === KEYS.TAB && e.shiftKey)) {
1440
                e.preventDefault();
1441
                if (anchors.is(':focus')) {
1442
                    anchors.eq(index - 1).focus();
1443
                } else {
1444
                    anchors.eq(anchors.length).focus();
1445
                }
1446
            }
1447
        });
1448
    },
1449

1450
    /**
1451
     * Opens the settings menu for a plugin.
1452
     *
1453
     * @method _showSettingsMenu
1454
     * @private
1455
     * @param {jQuery} nav trigger element
1456
     */
1457
    _showSettingsMenu: function(nav) {
1458
        this._checkIfPasteAllowed();
×
1459

UNCOV
1460
        var dropdown = this.ui.dropdown;
×
1461
        var parents = nav.parentsUntil('.cms-dragarea').last();
×
1462
        var MIN_SCREEN_MARGIN = 10;
×
1463

UNCOV
1464
        nav.addClass('cms-btn-active');
×
1465
        parents.addClass('cms-z-index-9999');
×
1466

1467
        // set visible states
1468
        dropdown.show();
×
1469

1470
        // calculate dropdown positioning
UNCOV
1471
        if (
×
1472
            $window.height() + $window.scrollTop() - nav.offset().top - dropdown.height() <= MIN_SCREEN_MARGIN &&
×
1473
            nav.offset().top - dropdown.height() >= 0
1474
        ) {
UNCOV
1475
            dropdown.removeClass('cms-submenu-dropdown-top').addClass('cms-submenu-dropdown-bottom');
×
1476
        } else {
UNCOV
1477
            dropdown.removeClass('cms-submenu-dropdown-bottom').addClass('cms-submenu-dropdown-top');
×
1478
        }
1479
    },
1480

1481
    /**
1482
     * Filters given plugins list by a query.
1483
     *
1484
     * @method _filterPluginsList
1485
     * @private
1486
     * @param {jQuery} list plugins picker element
1487
     * @param {jQuery} input input, which value to filter plugins with
1488
     * @returns {Boolean|void}
1489
     */
1490
    _filterPluginsList: function _filterPluginsList(list, input) {
1491
        var items = list.find('.cms-submenu-item');
5✔
1492
        var titles = list.find('.cms-submenu-item-title');
5✔
1493
        var query = input.val();
5✔
1494

1495
        // cancel if query is zero
1496
        if (query === '') {
5✔
1497
            items.add(titles).show();
1✔
1498
            return false;
1✔
1499
        }
1500

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

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

1505
        var itemsToFilter = items.toArray().map(function(el) {
4✔
1506
            var element = $(el);
72✔
1507

1508
            return {
72✔
1509
                value: element.text(),
1510
                element: element
1511
            };
1512
        });
1513

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

1516
        items.hide();
4✔
1517
        filteredItems.forEach(function(item) {
4✔
1518
            item.element.show();
3✔
1519
        });
1520

1521
        // check if a title is matching
1522
        titles.filter(':visible').each(function(index, item) {
4✔
1523
            titles.hide();
1✔
1524
            $(item).nextUntil('.cms-submenu-item-title').show();
1✔
1525
        });
1526

1527
        // always display title of a category
1528
        items.filter(':visible').each(function(index, titleItem) {
4✔
1529
            var item = $(titleItem);
16✔
1530

1531
            if (item.prev().hasClass('cms-submenu-item-title')) {
16✔
1532
                item.prev().show();
2✔
1533
            } else {
1534
                item.prevUntil('.cms-submenu-item-title').last().prev().show();
14✔
1535
            }
1536
        });
1537

1538
        mostRecentItems.hide();
4✔
1539
    },
1540

1541
    /**
1542
     * Toggles collapsable item.
1543
     *
1544
     * @method _toggleCollapsable
1545
     * @private
1546
     * @param {jQuery} el element to toggle
1547
     * @returns {Boolean|void}
1548
     */
1549
    _toggleCollapsable: function toggleCollapsable(el) {
UNCOV
1550
        var that = this;
×
UNCOV
1551
        var id = that._getId(el.parent());
×
1552
        var draggable = el.closest('.cms-draggable');
×
1553
        var items;
1554

UNCOV
1555
        var settings = CMS.settings;
×
1556

1557
        settings.states = settings.states || [];
×
1558

UNCOV
1559
        if (!draggable || !draggable.length) {
×
UNCOV
1560
            return;
×
1561
        }
1562

1563
        // collapsable function and save states
UNCOV
1564
        if (el.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1565
            settings.states.splice($.inArray(id, settings.states), 1);
×
UNCOV
1566
            el
×
1567
                .removeClass('cms-dragitem-expanded')
1568
                .parent()
1569
                .find('> .cms-collapsable-container')
1570
                .addClass('cms-hidden');
1571

1572
            if ($document.data('expandmode')) {
×
UNCOV
1573
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
1574
                if (!items.length) {
×
1575
                    return false;
×
1576
                }
1577
                items.each(function() {
×
1578
                    var item = $(this);
×
1579

UNCOV
1580
                    if (item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1581
                        that._toggleCollapsable(item);
×
1582
                    }
1583
                });
1584
            }
1585
        } else {
UNCOV
1586
            settings.states.push(id);
×
UNCOV
1587
            el
×
1588
                .addClass('cms-dragitem-expanded')
1589
                .parent()
1590
                .find('> .cms-collapsable-container')
1591
                .removeClass('cms-hidden');
1592

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

UNCOV
1601
                    if (!item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1602
                        that._toggleCollapsable(item);
×
1603
                    }
1604
                });
1605
            }
1606
        }
1607

1608
        this._updatePlaceholderCollapseState();
×
1609

1610
        // make sure structurboard gets updated after expanding
1611
        $document.trigger('resize.sideframe');
×
1612

1613
        // save settings
UNCOV
1614
        Helpers.setSettings(settings);
×
1615
    },
1616

1617
    _updatePlaceholderCollapseState() {
UNCOV
1618
        if (this.options.type !== 'plugin' || !this.options.placeholder_id) {
×
1619
            return;
×
1620
        }
1621

UNCOV
1622
        const pluginsOfCurrentPlaceholder = CMS._plugins
×
1623
            .filter(([, o]) => o.placeholder_id === this.options.placeholder_id && o.type === 'plugin')
×
1624
            .map(([, o]) => o.plugin_id);
×
1625

1626
        const openedPlugins = CMS.settings.states;
×
UNCOV
1627
        const closedPlugins = difference(pluginsOfCurrentPlaceholder, openedPlugins);
×
1628
        const areAllRemainingPluginsLeafs = every(closedPlugins, id => {
×
UNCOV
1629
            return !find(
×
1630
                CMS._plugins,
1631
                ([, o]) => o.placeholder_id === this.options.placeholder_id && o.plugin_parent === id
×
1632
            );
1633
        });
1634
        const el = $(`.cms-dragarea-${this.options.placeholder_id} .cms-dragbar-title`);
×
UNCOV
1635
        var settings = CMS.settings;
×
1636

UNCOV
1637
        if (areAllRemainingPluginsLeafs) {
×
1638
            // meaning that all plugins in current placeholder are expanded
1639
            el.addClass('cms-dragbar-title-expanded');
×
1640

1641
            settings.dragbars = settings.dragbars || [];
×
UNCOV
1642
            settings.dragbars.push(this.options.placeholder_id);
×
1643
        } else {
1644
            el.removeClass('cms-dragbar-title-expanded');
×
1645

UNCOV
1646
            settings.dragbars = settings.dragbars || [];
×
UNCOV
1647
            settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1648
        }
1649
    },
1650

1651
    /**
1652
     * Sets up collabspable event handlers.
1653
     *
1654
     * @method _collapsables
1655
     * @private
1656
     * @returns {Boolean|void}
1657
     */
1658
    _collapsables: function() {
1659
        // one time setup
1660
        var that = this;
152✔
1661

1662
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
152✔
1663
        // cancel here if its not a draggable
1664
        if (!this.ui.draggable.length) {
152✔
1665
            return false;
38✔
1666
        }
1667

1668
        var dragitem = this.ui.draggable.find('> .cms-dragitem');
114✔
1669

1670
        // check which button should be shown for collapsemenu
1671
        var els = this.ui.draggable.find('.cms-dragitem-collapsable');
114✔
1672
        var open = els.filter('.cms-dragitem-expanded');
114✔
1673

1674
        if (els.length === open.length && els.length + open.length !== 0) {
114!
UNCOV
1675
            this.ui.draggable.find('.cms-dragbar-title').addClass('cms-dragbar-title-expanded');
×
1676
        }
1677

1678
        // attach events to draggable
1679
        // debounce here required because on some devices click is not triggered,
1680
        // so we consolidate latest click and touch event to run the collapse only once
1681
        dragitem.find('> .cms-dragitem-text').on(
114✔
1682
            Plugin.touchEnd + ' ' + Plugin.click,
1683
            debounce(function() {
1684
                if (!dragitem.hasClass('cms-dragitem-collapsable')) {
×
UNCOV
1685
                    return;
×
1686
                }
UNCOV
1687
                that._toggleCollapsable(dragitem);
×
1688
            }, 0)
1689
        );
1690
    },
1691

1692
    /**
1693
     * Expands all the collapsables in the given placeholder.
1694
     *
1695
     * @method _expandAll
1696
     * @private
1697
     * @param {jQuery} el trigger element that is a child of a placeholder
1698
     * @returns {Boolean|void}
1699
     */
1700
    _expandAll: function(el) {
UNCOV
1701
        var that = this;
×
1702
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1703

1704
        // cancel if there are no items
1705
        if (!items.length) {
×
1706
            return false;
×
1707
        }
1708
        items.each(function() {
×
1709
            var item = $(this);
×
1710

UNCOV
1711
            if (!item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1712
                that._toggleCollapsable(item);
×
1713
            }
1714
        });
1715

UNCOV
1716
        el.addClass('cms-dragbar-title-expanded');
×
1717

1718
        var settings = CMS.settings;
×
1719

UNCOV
1720
        settings.dragbars = settings.dragbars || [];
×
UNCOV
1721
        settings.dragbars.push(this.options.placeholder_id);
×
UNCOV
1722
        Helpers.setSettings(settings);
×
1723
    },
1724

1725
    /**
1726
     * Collapses all the collapsables in the given placeholder.
1727
     *
1728
     * @method _collapseAll
1729
     * @private
1730
     * @param {jQuery} el trigger element that is a child of a placeholder
1731
     */
1732
    _collapseAll: function(el) {
1733
        var that = this;
×
1734
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1735

1736
        items.each(function() {
×
1737
            var item = $(this);
×
1738

UNCOV
1739
            if (item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1740
                that._toggleCollapsable(item);
×
1741
            }
1742
        });
1743

UNCOV
1744
        el.removeClass('cms-dragbar-title-expanded');
×
1745

1746
        var settings = CMS.settings;
×
1747

UNCOV
1748
        settings.dragbars = settings.dragbars || [];
×
UNCOV
1749
        settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
UNCOV
1750
        Helpers.setSettings(settings);
×
1751
    },
1752

1753
    /**
1754
     * Gets the id of the element, uses CMS.StructureBoard instance.
1755
     *
1756
     * @method _getId
1757
     * @private
1758
     * @param {jQuery} el element to get id from
1759
     * @returns {String}
1760
     */
1761
    _getId: function(el) {
1762
        return CMS.API.StructureBoard.getId(el);
36✔
1763
    },
1764

1765
    /**
1766
     * Gets the ids of the list of elements, uses CMS.StructureBoard instance.
1767
     *
1768
     * @method _getIds
1769
     * @private
1770
     * @param {jQuery} els elements to get id from
1771
     * @returns {String[]}
1772
     */
1773
    _getIds: function(els) {
UNCOV
1774
        return CMS.API.StructureBoard.getIds(els);
×
1775
    },
1776

1777
    /**
1778
     * Traverses the registry to find plugin parents
1779
     *
1780
     * @method _getPluginBreadcrumbs
1781
     * @returns {Object[]} array of breadcrumbs in `{ url, title }` format
1782
     * @private
1783
     */
1784
    _getPluginBreadcrumbs: function _getPluginBreadcrumbs() {
1785
        var breadcrumbs = [];
6✔
1786

1787
        breadcrumbs.unshift({
6✔
1788
            title: this.options.plugin_name,
1789
            url: this.options.urls.edit_plugin
1790
        });
1791

1792
        var findParentPlugin = function(id) {
6✔
1793
            return $.grep(CMS._plugins || [], function(pluginOptions) {
6✔
1794
                return pluginOptions[0] === 'cms-plugin-' + id;
10✔
1795
            })[0];
1796
        };
1797

1798
        var id = this.options.plugin_parent;
6✔
1799
        var data;
1800

1801
        while (id && id !== 'None') {
6✔
1802
            data = findParentPlugin(id);
6✔
1803

1804
            if (!data) {
6✔
1805
                break;
1✔
1806
            }
1807

1808
            breadcrumbs.unshift({
5✔
1809
                title: data[1].plugin_name,
1810
                url: data[1].urls.edit_plugin
1811
            });
1812
            id = data[1].plugin_parent;
5✔
1813
        }
1814

1815
        return breadcrumbs;
6✔
1816
    }
1817
});
1818

1819
Plugin.click = 'click.cms.plugin';
1✔
1820
Plugin.pointerUp = 'pointerup.cms.plugin';
1✔
1821
Plugin.pointerDown = 'pointerdown.cms.plugin';
1✔
1822
Plugin.pointerOverAndOut = 'pointerover.cms.plugin pointerout.cms.plugin';
1✔
1823
Plugin.doubleClick = 'dblclick.cms.plugin';
1✔
1824
Plugin.keyUp = 'keyup.cms.plugin';
1✔
1825
Plugin.keyDown = 'keydown.cms.plugin';
1✔
1826
Plugin.mouseEvents = 'mousedown.cms.plugin mousemove.cms.plugin mouseup.cms.plugin';
1✔
1827
Plugin.touchStart = 'touchstart.cms.plugin';
1✔
1828
Plugin.touchEnd = 'touchend.cms.plugin';
1✔
1829

1830
/**
1831
 * Updates plugin data in CMS._plugins / CMS._instances or creates new
1832
 * plugin instances if they didn't exist
1833
 *
1834
 * @method _updateRegistry
1835
 * @private
1836
 * @static
1837
 * @param {Object[]} plugins plugins data
1838
 */
1839
Plugin._updateRegistry = function _updateRegistry(plugins) {
1✔
UNCOV
1840
    plugins.forEach(pluginData => {
×
1841
        const pluginContainer = `cms-plugin-${pluginData.plugin_id}`;
×
1842
        const pluginIndex = findIndex(CMS._plugins, ([pluginStr]) => pluginStr === pluginContainer);
×
1843

UNCOV
1844
        if (pluginIndex === -1) {
×
1845
            CMS._plugins.push([pluginContainer, pluginData]);
×
1846
            CMS._instances.push(new Plugin(pluginContainer, pluginData));
×
1847
        } else {
UNCOV
1848
            Plugin.aliasPluginDuplicatesMap[pluginData.plugin_id] = false;
×
UNCOV
1849
            CMS._plugins[pluginIndex] = [pluginContainer, pluginData];
×
UNCOV
1850
            CMS._instances[pluginIndex] = new Plugin(pluginContainer, pluginData);
×
1851
        }
1852
    });
1853
};
1854

1855
/**
1856
 * Hides the opened settings menu. By default looks for any open ones.
1857
 *
1858
 * @method _hideSettingsMenu
1859
 * @static
1860
 * @private
1861
 * @param {jQuery} [navEl] element representing the subnav trigger
1862
 */
1863
Plugin._hideSettingsMenu = function(navEl) {
1✔
1864
    var nav = navEl || $('.cms-submenu-btn.cms-btn-active');
20✔
1865

1866
    if (!nav.length) {
20!
1867
        return;
20✔
1868
    }
1869
    nav.removeClass('cms-btn-active');
×
1870

1871
    // set correct active state
1872
    nav.closest('.cms-draggable').data('active', false);
×
1873
    $('.cms-z-index-9999').removeClass('cms-z-index-9999');
×
1874

1875
    nav.siblings('.cms-submenu-dropdown').hide();
×
UNCOV
1876
    nav.siblings('.cms-quicksearch').hide();
×
1877
    // reset search
1878
    nav.siblings('.cms-quicksearch').find('input').val('').trigger(Plugin.keyUp).blur();
×
1879

1880
    // reset relativity
UNCOV
1881
    $('.cms-dragbar').css('position', '');
×
1882
};
1883

1884
/**
1885
 * Initialises handlers that affect all plugins and don't make sense
1886
 * in context of each own plugin instance, e.g. listening for a click on a document
1887
 * to hide plugin settings menu should only be applied once, and not every time
1888
 * CMS.Plugin is instantiated.
1889
 *
1890
 * @method _initializeGlobalHandlers
1891
 * @static
1892
 * @private
1893
 */
1894
Plugin._initializeGlobalHandlers = function _initializeGlobalHandlers() {
1✔
1895
    var timer;
1896
    var clickCounter = 0;
6✔
1897

1898
    Plugin._updateClipboard();
6✔
1899

1900
    // Structureboard initialized too late
1901
    setTimeout(function() {
6✔
1902
        var pluginData = {};
6✔
1903
        var html = '';
6✔
1904

1905
        if (clipboardDraggable.length) {
6✔
1906
            pluginData = find(
5✔
1907
                CMS._plugins,
1908
                ([desc]) => desc === `cms-plugin-${CMS.API.StructureBoard.getId(clipboardDraggable)}`
10✔
1909
            )[1];
1910
            html = clipboardDraggable.parent().html();
5✔
1911
        }
1912
        if (CMS.API && CMS.API.Clipboard) {
6!
1913
            CMS.API.Clipboard.populate(html, pluginData);
6✔
1914
        }
1915
    }, 0);
1916

1917
    $document
6✔
1918
        .off(Plugin.pointerUp)
1919
        .off(Plugin.keyDown)
1920
        .off(Plugin.keyUp)
1921
        .off(Plugin.click, '.cms-plugin a, a:has(.cms-plugin), a.cms-plugin')
1922
        .on(Plugin.pointerUp, function() {
1923
            // call it as a static method, because otherwise we trigger it the
1924
            // amount of times CMS.Plugin is instantiated,
1925
            // which does not make much sense.
UNCOV
1926
            Plugin._hideSettingsMenu();
×
1927
        })
1928
        .on(Plugin.keyDown, function(e) {
1929
            if (e.keyCode === KEYS.SHIFT) {
26!
1930
                $document.data('expandmode', true);
×
UNCOV
1931
                try {
×
UNCOV
1932
                    $('.cms-plugin:hover').last().trigger('mouseenter');
×
UNCOV
1933
                    $('.cms-dragitem:hover').last().trigger('mouseenter');
×
1934
                } catch (err) {}
1935
            }
1936
        })
1937
        .on(Plugin.keyUp, function(e) {
1938
            if (e.keyCode === KEYS.SHIFT) {
23!
UNCOV
1939
                $document.data('expandmode', false);
×
UNCOV
1940
                try {
×
UNCOV
1941
                    $(':hover').trigger('mouseleave');
×
1942
                } catch (err) {}
1943
            }
1944
        })
1945
        .on(Plugin.click, '.cms-plugin a, a:has(.cms-plugin), a.cms-plugin', function(e) {
UNCOV
1946
            var DOUBLECLICK_DELAY = 300;
×
1947

1948
            // prevents single click from messing up the edit call
1949
            // don't go to the link if there is custom js attached to it
1950
            // or if it's clicked along with shift, ctrl, cmd
1951
            if (e.shiftKey || e.ctrlKey || e.metaKey || e.isDefaultPrevented()) {
×
1952
                return;
×
1953
            }
1954
            e.preventDefault();
×
UNCOV
1955
            if (++clickCounter === 1) {
×
1956
                timer = setTimeout(function() {
×
1957
                    var anchor = $(e.target).closest('a');
×
1958

UNCOV
1959
                    clickCounter = 0;
×
1960
                    window.open(anchor.attr('href'), anchor.attr('target') || '_self');
×
1961
                }, DOUBLECLICK_DELAY);
1962
            } else {
UNCOV
1963
                clearTimeout(timer);
×
UNCOV
1964
                clickCounter = 0;
×
1965
            }
1966
        });
1967

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

UNCOV
1977
        e.stopPropagation();
×
NEW
1978
        const pluginContainer = $(e.target).closest('.cms-plugin:not(.cms-edit-disabled)');
×
1979
        const allOptions = pluginContainer.data('cms');
×
1980

UNCOV
1981
        if (!allOptions || !allOptions.length) {
×
1982
            return;
×
1983
        }
1984

1985
        const options = allOptions[0];
×
1986

1987
        if (e.type === 'touchstart') {
×
1988
            CMS.API.Tooltip._forceTouchOnce();
×
1989
        }
UNCOV
1990
        var name = options.plugin_name;
×
1991
        var id = options.plugin_id;
×
1992
        var type = options.type;
×
1993

1994
        if (type === 'generic') {
×
1995
            return;
×
1996
        }
1997
        var placeholderId = CMS.API.StructureBoard.getId($(`.cms-draggable-${id}`).closest('.cms-dragarea'));
×
1998
        var placeholder = $('.cms-placeholder-' + placeholderId);
×
1999

UNCOV
2000
        if (placeholder.length && placeholder.data('cms')) {
×
2001
            name = placeholder.data('cms').name + ': ' + name;
×
2002
        }
2003

UNCOV
2004
        CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
2005
    });
2006

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

UNCOV
2010
        if (placeholder.hasClass('cms-dragarea-static-expanded') && e.isDefaultPrevented()) {
×
2011
            return;
×
2012
        }
2013

UNCOV
2014
        placeholder.toggleClass('cms-dragarea-static-expanded');
×
2015
    });
2016

2017
    $window.on('blur.cms', () => {
6✔
2018
        $document.data('expandmode', false);
6✔
2019
    });
2020
};
2021

2022
/**
2023
 * @method _isContainingMultiplePlugins
2024
 * @param {jQuery} node to check
2025
 * @static
2026
 * @private
2027
 * @returns {Boolean}
2028
 */
2029
Plugin._isContainingMultiplePlugins = function _isContainingMultiplePlugins(node) {
1✔
2030
    var currentData = node.data('cms');
129✔
2031

2032
    // istanbul ignore if
2033
    if (!currentData) {
129✔
2034
        throw new Error('Provided node is not a cms plugin.');
2035
    }
2036

2037
    var pluginIds = currentData.map(function(pluginData) {
129✔
2038
        return pluginData.plugin_id;
130✔
2039
    });
2040

2041
    if (pluginIds.length > 1) {
129✔
2042
        // another plugin already lives on the same node
2043
        // this only works because the plugins are rendered from
2044
        // the bottom to the top (leaf to root)
2045
        // meaning the deepest plugin is always first
2046
        return true;
1✔
2047
    }
2048

2049
    return false;
128✔
2050
};
2051

2052
/**
2053
 * Shows and immediately fades out a success notification (when
2054
 * plugin was successfully moved.
2055
 *
2056
 * @method _highlightPluginStructure
2057
 * @private
2058
 * @static
2059
 * @param {jQuery} el draggable element
2060
 */
2061
// eslint-disable-next-line no-magic-numbers
2062
Plugin._highlightPluginStructure = function _highlightPluginStructure(
1✔
2063
    el,
2064
    // eslint-disable-next-line no-magic-numbers
2065
    { successTimeout = 200, delay = 1500, seeThrough = false }
×
2066
) {
UNCOV
2067
    const tpl = $(`
×
2068
        <div class="cms-dragitem-success ${seeThrough ? 'cms-plugin-overlay-see-through' : ''}">
×
2069
        </div>
2070
    `);
2071

2072
    el.addClass('cms-draggable-success').append(tpl);
×
2073
    // start animation
2074
    if (successTimeout) {
×
2075
        setTimeout(() => {
×
UNCOV
2076
            tpl.fadeOut(successTimeout, function() {
×
UNCOV
2077
                $(this).remove();
×
UNCOV
2078
                el.removeClass('cms-draggable-success');
×
2079
            });
2080
        }, delay);
2081
    }
2082
    // make sure structurboard gets updated after success
UNCOV
2083
    $(Helpers._getWindow()).trigger('resize.sideframe');
×
2084
};
2085

2086
/**
2087
 * Highlights plugin in content mode
2088
 *
2089
 * @method _highlightPluginContent
2090
 * @private
2091
 * @static
2092
 * @param {String|Number} pluginId
2093
 */
2094
Plugin._highlightPluginContent = function _highlightPluginContent(
1✔
2095
    pluginId,
2096
    // eslint-disable-next-line no-magic-numbers
2097
    { successTimeout = 200, seeThrough = false, delay = 1500, prominent = false } = {}
5✔
2098
) {
2099
    var coordinates = {};
1✔
2100
    var positions = [];
1✔
2101
    var OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO = 0.2;
1✔
2102

2103
    $('.cms-plugin-' + pluginId).each(function() {
1✔
2104
        var el = $(this);
1✔
2105
        var offset = el.offset();
1✔
2106
        var ml = parseInt(el.css('margin-left'), 10);
1✔
2107
        var mr = parseInt(el.css('margin-right'), 10);
1✔
2108
        var mt = parseInt(el.css('margin-top'), 10);
1✔
2109
        var mb = parseInt(el.css('margin-bottom'), 10);
1✔
2110
        var width = el.outerWidth();
1✔
2111
        var height = el.outerHeight();
1✔
2112

2113
        if (width === 0 && height === 0) {
1!
UNCOV
2114
            return;
×
2115
        }
2116

2117
        if (isNaN(ml)) {
1!
2118
            ml = 0;
×
2119
        }
2120
        if (isNaN(mr)) {
1!
2121
            mr = 0;
×
2122
        }
2123
        if (isNaN(mt)) {
1!
2124
            mt = 0;
×
2125
        }
2126
        if (isNaN(mb)) {
1!
UNCOV
2127
            mb = 0;
×
2128
        }
2129

2130
        positions.push({
1✔
2131
            x1: offset.left - ml,
2132
            x2: offset.left + width + mr,
2133
            y1: offset.top - mt,
2134
            y2: offset.top + height + mb
2135
        });
2136
    });
2137

2138
    if (positions.length === 0) {
1!
UNCOV
2139
        return;
×
2140
    }
2141

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

2147
    coordinates.left = Math.min(...positions.map(pos => pos.x1));
1✔
2148
    coordinates.top = Math.min(...positions.map(pos => pos.y1)) - htmlMargin;
1✔
2149
    coordinates.width = Math.max(...positions.map(pos => pos.x2)) - coordinates.left;
1✔
2150
    coordinates.height = Math.max(...positions.map(pos => pos.y2)) - coordinates.top - htmlMargin;
1✔
2151

2152
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2153

2154
    $(
1✔
2155
        `
2156
        <div class="
2157
            cms-plugin-overlay
2158
            cms-dragitem-success
2159
            cms-plugin-overlay-${pluginId}
2160
            ${seeThrough ? 'cms-plugin-overlay-see-through' : ''}
1!
2161
            ${prominent ? 'cms-plugin-overlay-prominent' : ''}
1!
2162
        "
2163
            data-success-timeout="${successTimeout}"
2164
        >
2165
        </div>
2166
    `
2167
    )
2168
        .css(coordinates)
2169
        .css({
2170
            zIndex: 9999
2171
        })
2172
        .appendTo($('body'));
2173

2174
    if (successTimeout) {
1!
2175
        setTimeout(() => {
1✔
2176
            $(`.cms-plugin-overlay-${pluginId}`).fadeOut(successTimeout, function() {
1✔
2177
                $(this).remove();
1✔
2178
            });
2179
        }, delay);
2180
    }
2181
};
2182

2183
Plugin._clickToHighlightHandler = function _clickToHighlightHandler(e) {
1✔
2184
    if (CMS.settings.mode !== 'structure') {
×
2185
        return;
×
2186
    }
2187
    e.preventDefault();
×
UNCOV
2188
    e.stopPropagation();
×
2189
    // FIXME refactor into an object
UNCOV
2190
    CMS.API.StructureBoard._showAndHighlightPlugin(200, true); // eslint-disable-line no-magic-numbers
×
2191
};
2192

2193
Plugin._removeHighlightPluginContent = function(pluginId) {
1✔
UNCOV
2194
    $(`.cms-plugin-overlay-${pluginId}[data-success-timeout=0]`).remove();
×
2195
};
2196

2197
Plugin.aliasPluginDuplicatesMap = {};
1✔
2198
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2199

2200
// istanbul ignore next
2201
Plugin._initializeTree = function _initializeTree() {
2202
    CMS._plugins = uniqWith(CMS._plugins, ([x], [y]) => x === y);
2203
    CMS._instances = CMS._plugins.map(function(args) {
2204
        return new CMS.Plugin(args[0], args[1]);
2205
    });
2206

2207
    // return the cms plugin instances just created
2208
    return CMS._instances;
2209
};
2210

2211
Plugin._updateClipboard = function _updateClipboard() {
1✔
2212
    clipboardDraggable = $('.cms-draggable-from-clipboard:first');
7✔
2213
};
2214

2215
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2216
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2217

2218
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2219

2220
    if (Helpers._isStorageSupported) {
2!
UNCOV
2221
        localStorage.setItem('cms-plugin-usage', JSON.stringify(pluginUsageMap));
×
2222
    }
2223
};
2224

2225
Plugin._removeAddPluginPlaceholder = function removeAddPluginPlaceholder() {
1✔
2226
    // this can't be cached since they are created and destroyed all over the place
2227
    $('.cms-add-plugin-placeholder').remove();
10✔
2228
};
2229

2230
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2231
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2232
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2233
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2234

2235
    CMS._instances.forEach(instance => {
4✔
2236
        if (instance.options.type === 'placeholder') {
5✔
2237
            instance._setupUI(`cms-placeholder-${instance.options.placeholder_id}`);
2✔
2238
            instance._ensureData();
2✔
2239
            instance.ui.container.data('cms', instance.options);
2✔
2240
            instance._setPlaceholder();
2✔
2241
        }
2242
    });
2243

2244
    CMS._instances.forEach(instance => {
4✔
2245
        if (instance.options.type === 'plugin') {
5✔
2246
            instance._setupUI(`cms-plugin-${instance.options.plugin_id}`);
2✔
2247
            instance._ensureData();
2✔
2248
            instance.ui.container.data('cms').push(instance.options);
2✔
2249
            instance._setPluginContentEvents();
2✔
2250
        }
2251
    });
2252

2253
    CMS._plugins.forEach(([type, opts]) => {
4✔
2254
        if (opts.type !== 'placeholder' && opts.type !== 'plugin') {
16✔
2255
            const instance = find(
8✔
2256
                CMS._instances,
2257
                i => i.options.type === opts.type && Number(i.options.plugin_id) === Number(opts.plugin_id)
13✔
2258
            );
2259

2260
            if (instance) {
8✔
2261
                // update
2262
                instance._setupUI(type);
1✔
2263
                instance._ensureData();
1✔
2264
                instance.ui.container.data('cms').push(instance.options);
1✔
2265
                instance._setGeneric();
1✔
2266
            } else {
2267
                // create
2268
                CMS._instances.push(new Plugin(type, opts));
7✔
2269
            }
2270
        }
2271
    });
2272
};
2273

2274
Plugin._getPluginById = function(id) {
1✔
2275
    return find(CMS._instances, ({ options }) => options.type === 'plugin' && Number(options.plugin_id) === Number(id));
20!
2276
};
2277

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

2283
    plugins.forEach((element, index) => {
10✔
2284
        const pluginId = CMS.API.StructureBoard.getId($(element));
20✔
2285
        const instance = Plugin._getPluginById(pluginId);
20✔
2286

2287
        if (!instance) {
20!
2288
            return;
20✔
2289
        }
2290

UNCOV
2291
        instance.options.position = index + 1;
×
2292
    });
2293
};
2294

2295
Plugin._recalculatePluginPositions = function(action, data) {
1✔
2296
    if (action === 'MOVE') {
×
2297
        // le sigh - recalculate all placeholders cause we don't know from where the
2298
        // plugin was moved from
2299
        filter(CMS._instances, ({ options }) => options.type === 'placeholder')
×
2300
            .map(({ options }) => options.placeholder_id)
×
UNCOV
2301
            .forEach(placeholder_id => Plugin._updatePluginPositions(placeholder_id));
×
UNCOV
2302
    } else if (data.placeholder_id) {
×
UNCOV
2303
        Plugin._updatePluginPositions(data.placeholder_id);
×
2304
    }
2305
};
2306

2307
// shorthand for jQuery(document).ready();
2308
$(Plugin._initializeGlobalHandlers);
1✔
2309

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

© 2025 Coveralls, Inc