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

divio / django-cms / #29514

06 Aug 2021 01:37PM UTC coverage: 77.798%. Remained the same
#29514

push

travis-ci

web-flow
Update ---bug-report.md

2551 of 3279 relevant lines covered (77.8%)

34.13 hits per line

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

60.69
/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 {
11
    includes,
12
    toPairs,
13
    isNaN,
14
    debounce,
15
    findIndex,
16
    find,
17
    every,
18
    uniqWith,
19
    once,
20
    difference,
21
    isEqual
22
} from 'lodash';
23

24
import Class from 'classjs';
25
import { Helpers, KEYS, $window, $document, uid } from './cms.base';
26
import { showLoader, hideLoader } from './loader';
27
import { filter as fuzzyFilter } from 'fuzzaldrin';
28

29
var clipboardDraggable;
30
var path = window.location.pathname + window.location.search;
1✔
31

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

34
const isStructureReady = () =>
1✔
35
    CMS.config.settings.mode === 'structure' ||
×
36
    CMS.config.settings.legacy_mode ||
37
    CMS.API.StructureBoard._loadedStructure;
38
const isContentReady = () =>
1✔
39
    CMS.config.settings.mode !== 'structure' ||
×
40
    CMS.config.settings.legacy_mode ||
41
    CMS.API.StructureBoard._loadedContent;
42

43
/**
44
 * Class for handling Plugins / Placeholders or Generics.
45
 * Handles adding / moving / copying / pasting / menus etc
46
 * in structureboard.
47
 *
48
 * @class Plugin
49
 * @namespace CMS
50
 * @uses CMS.API.Helpers
51
 */
52
var Plugin = new Class({
1✔
53
    implement: [Helpers],
54

55
    options: {
56
        type: '', // bar, plugin or generic
57
        placeholder_id: null,
58
        plugin_type: '',
59
        plugin_id: null,
60
        plugin_parent: null,
61
        plugin_order: null,
62
        plugin_restriction: [],
63
        plugin_parent_restriction: [],
64
        urls: {
65
            add_plugin: '',
66
            edit_plugin: '',
67
            move_plugin: '',
68
            copy_plugin: '',
69
            delete_plugin: ''
70
        }
71
    },
72

73
    // these properties will be filled later
74
    modal: null,
75

76
    initialize: function initialize(container, options) {
77
        this.options = $.extend(true, {}, this.options, options);
184✔
78

79
        // create an unique for this component to use it internally
80
        this.uid = uid();
184✔
81

82
        this._setupUI(container);
184✔
83
        this._ensureData();
184✔
84

85
        if (this.options.type === 'plugin' && Plugin.aliasPluginDuplicatesMap[this.options.plugin_id]) {
184✔
86
            return;
1✔
87
        }
88
        if (this.options.type === 'placeholder' && Plugin.staticPlaceholderDuplicatesMap[this.options.placeholder_id]) {
183✔
89
            return;
1✔
90
        }
91

92
        // determine type of plugin
93
        switch (this.options.type) {
182✔
94
            case 'placeholder': // handler for placeholder bars
95
                Plugin.staticPlaceholderDuplicatesMap[this.options.placeholder_id] = true;
24✔
96
                this.ui.container.data('cms', this.options);
24✔
97
                this._setPlaceholder();
24✔
98
                if (isStructureReady()) {
24✔
99
                    this._collapsables();
24✔
100
                }
101
                break;
24✔
102
            case 'plugin': // handler for all plugins
103
                this.ui.container.data('cms').push(this.options);
133✔
104
                Plugin.aliasPluginDuplicatesMap[this.options.plugin_id] = true;
133✔
105
                this._setPlugin();
133✔
106
                if (isStructureReady()) {
133✔
107
                    this._collapsables();
133✔
108
                }
109
                break;
133✔
110
            default:
111
                // handler for static content
112
                this.ui.container.data('cms').push(this.options);
25✔
113
                this._setGeneric();
25✔
114
        }
115
    },
116

117
    _ensureData: function _ensureData() {
118
        // bind data element to the container (mutating!)
119
        if (!this.ui.container.data('cms')) {
184✔
120
            this.ui.container.data('cms', []);
179✔
121
        }
122
    },
123

124
    /**
125
     * Caches some jQuery references and sets up structure for
126
     * further initialisation.
127
     *
128
     * @method _setupUI
129
     * @private
130
     * @param {String} container `cms-plugin-${id}`
131
     */
132
    _setupUI: function setupUI(container) {
133
        var wrapper = $(`.${container}`);
184✔
134
        var contents;
135

136
        // have to check for cms-plugin, there can be a case when there are multiple
137
        // static placeholders or plugins rendered twice, there could be multiple wrappers on same page
138
        if (wrapper.length > 1 && container.match(/cms-plugin/)) {
184✔
139
            // so it's possible that multiple plugins (more often generics) are rendered
140
            // in different places. e.g. page menu in the header and in the footer
141
            // so first, we find all the template tags, then put them in a structure like this:
142
            // [[start, end], [start, end]...]
143
            //
144
            // in case of plugins it means that it's aliased plugin or a plugin in a duplicated
145
            // static placeholder (for whatever reason)
146
            var contentWrappers = wrapper.toArray().reduce((wrappers, elem, index) => {
140✔
147
                if (index === 0) {
282✔
148
                    wrappers[0].push(elem);
140✔
149
                    return wrappers;
140✔
150
                }
151

152
                var lastWrapper = wrappers[wrappers.length - 1];
142✔
153
                var lastItemInWrapper = lastWrapper[lastWrapper.length - 1];
142✔
154

155
                if ($(lastItemInWrapper).is('.cms-plugin-end')) {
142✔
156
                    wrappers.push([elem]);
1✔
157
                } else {
158
                    lastWrapper.push(elem);
141✔
159
                }
160

161
                return wrappers;
142✔
162
            }, [[]]);
163

164
            // then we map that structure into an array of jquery collections
165
            // from which we filter out empty ones
166
            contents = contentWrappers
140✔
167
                .map(items => {
168
                    var templateStart = $(items[0]);
141✔
169
                    var className = templateStart.attr('class').replace('cms-plugin-start', '');
141✔
170

171
                    var itemContents = $(nextUntil(templateStart[0], container));
141✔
172

173
                    $(items).filter('template').remove();
141✔
174

175
                    itemContents.each((index, el) => {
141✔
176
                        // Due to the way browsers interact with plugins and external code, the .data()
177
                        // method cannot be used on <object> (unless it's a Flash plugin), <applet> or <embed> elements,
178
                        // so we have to wrap them
179
                        if (includes(['OBJECT', 'EMBED', 'APPLET'], el.nodeName)) {
164✔
180
                            const element = $(el);
1✔
181

182
                            element.wrap('<cms-plugin class="cms-plugin-object-node"></cms-plugin>');
1✔
183
                            itemContents[index] = element.parent()[0];
1✔
184
                        }
185

186
                        // if it's a non-space top-level text node - wrap it in `cms-plugin`
187
                        if (el.nodeType === Node.TEXT_NODE && !el.textContent.match(/^\s*$/)) {
164✔
188
                            const element = $(el);
10✔
189

190
                            element.wrap('<cms-plugin class="cms-plugin-text-node"></cms-plugin>');
10✔
191
                            itemContents[index] = element.parent()[0];
10✔
192
                        }
193
                    });
194

195
                    // otherwise we don't really need text nodes or comment nodes or empty text nodes
196
                    itemContents = itemContents.filter(function() {
141✔
197
                        return this.nodeType !== Node.TEXT_NODE && this.nodeType !== Node.COMMENT_NODE;
164✔
198
                    });
199

200
                    itemContents.addClass(`cms-plugin ${className}`);
141✔
201

202
                    return itemContents;
141✔
203
                })
204
                .filter(v => v.length);
141✔
205

206
            if (contents.length) {
140✔
207
                // and then reduce it to one big collection
208
                contents = contents.reduce((collection, items) => collection.add(items), $());
141✔
209
            }
210
        } else {
211
            contents = wrapper;
44✔
212
        }
213

214
        // in clipboard can be non-existent
215
        if (!contents.length) {
184✔
216
            contents = $('<div></div>');
11✔
217
        }
218

219
        this.ui = this.ui || {};
184✔
220
        this.ui.container = contents;
184✔
221
    },
222

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

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

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

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

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

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

260
        this._checkIfPasteAllowed();
24✔
261
    },
262

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

278
    _setPluginStructureEvents: function _setPluginStructureEvents() {
279
        var that = this;
133✔
280

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

287
        this.ui.draggable.data('cms', this.options);
133✔
288

289
        this.ui.dragitem.on(Plugin.doubleClick, this._dblClickToEditHandler.bind(this));
133✔
290

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

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

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

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

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

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

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

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

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

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

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

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

362
    _dblClickToEditHandler: function _dblClickToEditHandler(e) {
363
        var that = this;
×
364

365
        e.preventDefault();
×
366
        e.stopPropagation();
×
367

368
        that.editPlugin(
×
369
            Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
370
            that.options.plugin_name,
371
            that._getPluginBreadcrumbs()
372
        );
373
    },
374

375
    _setPluginContentEvents: function _setPluginContentEvents() {
376
        const pluginDoubleClickEvent = this._getNamepacedEvent(Plugin.doubleClick);
133✔
377

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

405
        if (!Plugin._isContainingMultiplePlugins(this.ui.container)) {
133✔
406
            $document
132✔
407
                .off(pluginDoubleClickEvent, `.cms-plugin-${this.options.plugin_id}`)
408
                .on(
409
                    pluginDoubleClickEvent,
410
                    `.cms-plugin-${this.options.plugin_id}`,
411
                    this._dblClickToEditHandler.bind(this)
412
                );
413
        }
414
    },
415

416
    /**
417
     * Sets up behaviours and ui for generics.
418
     * Generics do not show up in structure board.
419
     *
420
     * @method _setGeneric
421
     * @private
422
     */
423
    _setGeneric: function() {
424
        var that = this;
25✔
425

426
        // adds double click to edit
427
        this.ui.container.off(Plugin.doubleClick).on(Plugin.doubleClick, function(e) {
25✔
428
            e.preventDefault();
×
429
            e.stopPropagation();
×
430
            that.editPlugin(Helpers.updateUrlWithPath(that.options.urls.edit_plugin), that.options.plugin_name, []);
×
431
        });
432

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

443
                CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
444
            });
445
    },
446

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

462
        if (!clipboardDraggable.length) {
155✔
463
            pasteItem.addClass('cms-submenu-item-disabled');
89✔
464
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
89✔
465
            pasteItem.find('.cms-submenu-item-paste-tooltip-empty').css('display', 'block');
89✔
466
            return false;
89✔
467
        }
468

469
        if (this.ui.draggable && this.ui.draggable.hasClass('cms-draggable-disabled')) {
66✔
470
            pasteItem.addClass('cms-submenu-item-disabled');
46✔
471
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
46✔
472
            pasteItem.find('.cms-submenu-item-paste-tooltip-disabled').css('display', 'block');
46✔
473
            return false;
46✔
474
        }
475

476
        var bounds = this.options.plugin_restriction;
20✔
477

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

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

500
        pasteItem.find('a').removeAttr('tabindex').removeAttr('aria-disabled');
5✔
501
        pasteItem.removeClass('cms-submenu-item-disabled');
5✔
502

503
        return true;
5✔
504
    },
505

506
    /**
507
     * Calls api to create a plugin and then proceeds to edit it.
508
     *
509
     * @method addPlugin
510
     * @param {String} type type of the plugin, e.g "Bootstrap3ColumnCMSPlugin"
511
     * @param {String} name name of the plugin, e.g. "Column"
512
     * @param {String} parent id of a parent plugin
513
     */
514
    addPlugin: function(type, name, parent) {
515
        var params = {
3✔
516
            placeholder_id: this.options.placeholder_id,
517
            plugin_type: type,
518
            cms_path: path,
519
            plugin_language: CMS.config.request.language
520
        };
521

522
        if (parent) {
3✔
523
            params.plugin_parent = parent;
1✔
524
        }
525
        var url = this.options.urls.add_plugin + '?' + $.param(params);
3✔
526
        var modal = new Modal({
3✔
527
            onClose: this.options.onClose || false,
528
            redirectOnClose: this.options.redirectOnClose || false
529
        });
530

531
        modal.open({
3✔
532
            url: url,
533
            title: name
534
        });
535

536
        this.modal = modal;
3✔
537

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

547
    /**
548
     * Opens the modal for editing a plugin.
549
     *
550
     * @method editPlugin
551
     * @param {String} url editing url
552
     * @param {String} name Name of the plugin, e.g. "Column"
553
     * @param {Object[]} breadcrumb array of objects representing a breadcrumb,
554
     *     each item is `{ title: 'string': url: 'string' }`
555
     */
556
    editPlugin: function(url, name, breadcrumb) {
557
        // trigger modal window
558
        var modal = new Modal({
3✔
559
            onClose: this.options.onClose || false,
560
            redirectOnClose: this.options.redirectOnClose || false
561
        });
562

563
        this.modal = modal;
3✔
564

565
        Helpers.removeEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin');
3✔
566
        Helpers.addEventListener('modal-closed.edit-plugin modal-loaded.edit-plugin', (e, { instance }) => {
3✔
567
            if (instance === modal) {
1✔
568
                // cannot be cached
569
                Plugin._removeAddPluginPlaceholder();
1✔
570
            }
571
        });
572
        modal.open({
3✔
573
            url: url,
574
            title: name,
575
            breadcrumbs: breadcrumb,
576
            width: 850
577
        });
578
    },
579

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

600
        // set correct options (don't mutate them)
601
        var options = $.extend({}, opts || this.options);
8✔
602
        var sourceLanguage = source_language;
8✔
603
        let copyingFromLanguage = false;
8✔
604

605
        if (sourceLanguage) {
8✔
606
            copyingFromLanguage = true;
1✔
607
            options.target = options.placeholder_id;
1✔
608
            options.plugin_id = '';
1✔
609
            options.parent = '';
1✔
610
        } else {
611
            sourceLanguage = CMS.config.request.language;
7✔
612
        }
613

614
        var data = {
8✔
615
            source_placeholder_id: options.placeholder_id,
616
            source_plugin_id: options.plugin_id || '',
617
            source_language: sourceLanguage,
618
            target_plugin_id: options.parent || '',
619
            target_placeholder_id: options.target || CMS.config.clipboard.id,
620
            csrfmiddlewaretoken: CMS.config.csrf,
621
            target_language: CMS.config.request.language
622
        };
623
        var request = {
8✔
624
            type: 'POST',
625
            url: Helpers.updateUrlWithPath(options.urls.copy_plugin),
626
            data: data,
627
            success: function(response) {
628
                CMS.API.Messages.open({
2✔
629
                    message: CMS.config.lang.success
630
                });
631
                if (copyingFromLanguage) {
2✔
632
                    CMS.API.StructureBoard.invalidateState('PASTE', $.extend({}, data, response));
×
633
                } else {
634
                    CMS.API.StructureBoard.invalidateState('COPY', response);
2✔
635
                }
636
                CMS.API.locked = false;
2✔
637
                hideLoader();
2✔
638
            },
639
            error: function(jqXHR) {
640
                CMS.API.locked = false;
3✔
641
                var msg = CMS.config.lang.error;
3✔
642

643
                // trigger error
644
                CMS.API.Messages.open({
3✔
645
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
646
                    error: true
647
                });
648
            }
649
        };
650

651
        $.ajax(request);
8✔
652
    },
653

654
    /**
655
     * Essentially clears clipboard and moves plugin to a clipboard
656
     * placholder through `movePlugin`.
657
     *
658
     * @method cutPlugin
659
     * @returns {Boolean|void}
660
     */
661
    cutPlugin: function() {
662
        // if cut is once triggered, prevent additional actions
663
        if (CMS.API.locked) {
9✔
664
            return false;
1✔
665
        }
666
        CMS.API.locked = true;
8✔
667

668
        var that = this;
8✔
669
        var data = {
8✔
670
            placeholder_id: CMS.config.clipboard.id,
671
            plugin_id: this.options.plugin_id,
672
            plugin_parent: '',
673
            plugin_order: [this.options.plugin_id],
674
            target_language: CMS.config.request.language,
675
            csrfmiddlewaretoken: CMS.config.csrf
676
        };
677

678
        // move plugin
679
        $.ajax({
8✔
680
            type: 'POST',
681
            url: Helpers.updateUrlWithPath(that.options.urls.move_plugin),
682
            data: data,
683
            success: function(response) {
684
                CMS.API.locked = false;
4✔
685
                CMS.API.Messages.open({
4✔
686
                    message: CMS.config.lang.success
687
                });
688
                CMS.API.StructureBoard.invalidateState('CUT', $.extend({}, data, response));
4✔
689
                hideLoader();
4✔
690
            },
691
            error: function(jqXHR) {
692
                CMS.API.locked = false;
3✔
693
                var msg = CMS.config.lang.error;
3✔
694

695
                // trigger error
696
                CMS.API.Messages.open({
3✔
697
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
698
                    error: true
699
                });
700
                hideLoader();
3✔
701
            }
702
        });
703
    },
704

705
    /**
706
     * Method is called when you click on the paste button on the plugin.
707
     * Uses existing solution of `copyPlugin(options)`
708
     *
709
     * @method pastePlugin
710
     */
711
    pastePlugin: function() {
712
        var id = this._getId(clipboardDraggable);
5✔
713
        var eventData = {
5✔
714
            id: id
715
        };
716

717
        const clipboardDraggableClone = clipboardDraggable.clone(true, true);
5✔
718

719
        clipboardDraggableClone.appendTo(this.ui.draggables);
5✔
720
        if (this.options.plugin_id) {
5✔
721
            StructureBoard.actualizePluginCollapseStatus(this.options.plugin_id);
4✔
722
        }
723
        this.ui.draggables.trigger('cms-structure-update', [eventData]);
5✔
724
        clipboardDraggableClone.trigger('cms-paste-plugin-update', [eventData]);
5✔
725
    },
726

727
    /**
728
     * Moves plugin by querying the API and then updates some UI parts
729
     * to reflect that the page has changed.
730
     *
731
     * @method movePlugin
732
     * @param {Object} [opts=this.options]
733
     * @param {String} [opts.placeholder_id]
734
     * @param {String} [opts.plugin_id]
735
     * @param {String} [opts.plugin_parent]
736
     * @param {Boolean} [opts.move_a_copy]
737
     * @returns {Boolean|void}
738
     */
739
    movePlugin: function(opts) {
740
        // cancel request if already in progress
741
        if (CMS.API.locked) {
13✔
742
            return false;
1✔
743
        }
744
        CMS.API.locked = true;
12✔
745

746
        // set correct options
747
        var options = opts || this.options;
12✔
748

749
        var dragitem = $(`.cms-draggable-${options.plugin_id}:last`);
12✔
750

751
        // SAVING POSITION
752
        var placeholder_id = this._getId(dragitem.parents('.cms-draggables').last().prevAll('.cms-dragbar').first());
12✔
753

754
        var plugin_parent = this._getId(dragitem.parent().closest('.cms-draggable'));
12✔
755
        var plugin_order = this._getIds(dragitem.siblings('.cms-draggable').andSelf());
12✔
756

757
        if (options.move_a_copy) {
12✔
758
            plugin_order = plugin_order.map(function(pluginId) {
1✔
759
                var id = pluginId;
3✔
760

761
                // correct way would be to check if it's actually a
762
                // pasted plugin and only then replace the id with copy token
763
                // otherwise if we would copy from the same placeholder we would get
764
                // two copy tokens instead of original and a copy.
765
                // it's ok so far, as long as we copy only from clipboard
766
                if (id === options.plugin_id) {
3✔
767
                    id = '__COPY__';
1✔
768
                }
769
                return id;
3✔
770
            });
771
        }
772

773
        // cancel here if we have no placeholder id
774
        if (placeholder_id === false) {
12✔
775
            return false;
1✔
776
        }
777

778
        // gather the data for ajax request
779
        var data = {
11✔
780
            placeholder_id: placeholder_id,
781
            plugin_id: options.plugin_id,
782
            plugin_parent: plugin_parent || '',
783
            target_language: CMS.config.request.language,
784
            plugin_order: plugin_order,
785
            csrfmiddlewaretoken: CMS.config.csrf,
786
            move_a_copy: options.move_a_copy
787
        };
788

789
        showLoader();
11✔
790

791
        $.ajax({
11✔
792
            type: 'POST',
793
            url: Helpers.updateUrlWithPath(options.urls.move_plugin),
794
            data: data,
795
            success: function(response) {
796
                CMS.API.StructureBoard.invalidateState(
4✔
797
                    data.move_a_copy ? 'PASTE' : 'MOVE',
798
                    $.extend({}, data, response)
799
                );
800

801
                // enable actions again
802
                CMS.API.locked = false;
4✔
803
                hideLoader();
4✔
804
            },
805
            error: function(jqXHR) {
806
                CMS.API.locked = false;
4✔
807
                var msg = CMS.config.lang.error;
4✔
808

809
                // trigger error
810
                CMS.API.Messages.open({
4✔
811
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
812
                    error: true
813
                });
814
                hideLoader();
4✔
815
            }
816
        });
817
    },
818

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

832
        // set new setting on instance and plugin data
833
        this.options = settings;
×
834
        if (plugin.length) {
×
835
            var index = plugin.data('cms').findIndex(function(pluginData) {
×
836
                return pluginData.plugin_id === settings.plugin_id;
×
837
            });
838

839
            plugin.each(function() {
×
840
                $(this).data('cms')[index] = settings;
×
841
            });
842
        }
843
        if (draggable.length) {
×
844
            draggable.data('cms', settings);
×
845
        }
846
    },
847

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

864
        this.modal = modal;
2✔
865

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

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

890
        // close the plugin modal if it was open
891
        if (this.modal) {
2✔
892
            this.modal.close();
×
893
            // unsubscribe to all the modal events
894
            this.modal.off();
×
895
        }
896

897
        if (mustCleanup) {
2✔
898
            this.cleanup();
1✔
899
        }
900

901
        // remove event bound to global elements like document or window
902
        $document.off(`.${this.uid}`);
2✔
903
        $window.off(`.${this.uid}`);
2✔
904
    },
905

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

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

930
    /**
931
     * _setSettingsMenu sets up event handlers for settings menu.
932
     *
933
     * @method _setSettingsMenu
934
     * @private
935
     * @param {jQuery} nav
936
     */
937
    _setSettingsMenu: function _setSettingsMenu(nav) {
938
        var that = this;
157✔
939

940
        this.ui.dropdown = nav.siblings('.cms-submenu-dropdown-settings');
157✔
941
        var dropdown = this.ui.dropdown;
157✔
942

943
        nav
157✔
944
            .off(Plugin.pointerUp)
945
            .on(Plugin.pointerUp, function(e) {
946
                e.preventDefault();
×
947
                e.stopPropagation();
×
948
                var trigger = $(this);
×
949

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

965
        dropdown
157✔
966
            .off(Plugin.mouseEvents)
967
            .on(Plugin.mouseEvents, function(e) {
968
                e.stopPropagation();
×
969
            })
970
            .off(Plugin.touchStart)
971
            .on(Plugin.touchStart, function(e) {
972
                // required for scrolling on mobile
973
                e.stopPropagation();
×
974
            });
975

976
        that._setupActions(nav);
157✔
977
        // prevent propagation
978
        nav
157✔
979
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '))
980
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
981
                e.stopPropagation();
×
982
            });
983

984
        nav
157✔
985
            .siblings('.cms-quicksearch, .cms-submenu-dropdown-settings')
986
            .off([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '))
987
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
988
                e.stopPropagation();
×
989
            });
990
    },
991

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

1015
        if (!isInViewport) {
3✔
1016
            scrollable.animate(
2✔
1017
                {
1018
                    scrollTop: elPosition + offset + elHeight + scrollTop - scrollHeight
1019
                },
1020
                duration
1021
            );
1022
        }
1023
    },
1024

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

1043
        var initModal = once(function initModal() {
68✔
1044
            var placeholder = $(
×
1045
                '<div class="cms-add-plugin-placeholder">' + CMS.config.lang.addPluginPlaceholder + '</div>'
1046
            );
1047
            var dragItem = nav.closest('.cms-dragitem');
×
1048
            var isPlaceholder = !dragItem.length;
×
1049
            var childrenList;
1050

1051
            modal = new Modal({
×
1052
                minWidth: 400,
1053
                minHeight: 400
1054
            });
1055

1056
            if (isPlaceholder) {
×
1057
                childrenList = nav.closest('.cms-dragarea').find('> .cms-draggables');
×
1058
            } else {
1059
                childrenList = nav.closest('.cms-draggable').find('> .cms-draggables');
×
1060
            }
1061

1062
            Helpers.addEventListener('modal-loaded', (e, { instance }) => {
×
1063
                if (instance !== modal) {
×
1064
                    return;
×
1065
                }
1066

1067
                that._setupKeyboardTraversing();
×
1068
                if (childrenList.hasClass('cms-hidden') && !isPlaceholder) {
×
1069
                    that._toggleCollapsable(dragItem);
×
1070
                }
1071
                Plugin._removeAddPluginPlaceholder();
×
1072
                placeholder.appendTo(childrenList);
×
1073
                that._scrollToElement(placeholder);
×
1074
            });
1075

1076
            Helpers.addEventListener('modal-closed', (e, { instance }) => {
×
1077
                if (instance !== modal) {
×
1078
                    return;
×
1079
                }
1080
                Plugin._removeAddPluginPlaceholder();
×
1081
            });
1082

1083
            Helpers.addEventListener('modal-shown', (e, { instance }) => {
×
1084
                if (modal !== instance) {
×
1085
                    return;
×
1086
                }
1087
                var dropdown = $('.cms-modal-markup .cms-plugin-picker');
×
1088

1089
                if (!isTouching) {
×
1090
                    // only focus the field if using mouse
1091
                    // otherwise keyboard pops up
1092
                    dropdown.find('input').trigger('focus');
×
1093
                }
1094
                isTouching = false;
×
1095
            });
1096

1097
            plugins = nav.siblings('.cms-plugin-picker');
×
1098

1099
            that._setupQuickSearch(plugins);
×
1100
        });
1101

1102
        nav
68✔
1103
            .on(Plugin.touchStart, function(e) {
1104
                isTouching = true;
×
1105
                // required on some touch devices so
1106
                // ui touch punch is not triggering mousemove
1107
                // which in turn results in pep triggering pointercancel
1108
                e.stopPropagation();
×
1109
            })
1110
            .on(Plugin.pointerUp, function(e) {
1111
                e.preventDefault();
×
1112
                e.stopPropagation();
×
1113

1114
                Plugin._hideSettingsMenu();
×
1115

1116
                initModal();
×
1117

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

1127
                modal.open({
×
1128
                    title: that.options.addPluginHelpTitle,
1129
                    html: pluginsCopy,
1130
                    width: 530,
1131
                    height: 400
1132
                });
1133
            });
1134

1135
        // prevent propagation
1136
        nav.on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
68✔
1137
            e.stopPropagation();
×
1138
        });
1139

1140
        nav
68✔
1141
            .siblings('.cms-quicksearch, .cms-submenu-dropdown')
1142
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
1143
                e.stopPropagation();
×
1144
            });
1145
    },
1146

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

1154
        if (items.filter(':not(.cms-submenu-item-title)').length <= MAX_MOST_USED_PLUGINS) {
×
1155
            return plugins;
×
1156
        }
1157

1158
        let ref = plugins.find('.cms-quicksearch');
×
1159

1160
        mostUsedPlugins.forEach(([name]) => {
×
1161
            if (count === MAX_MOST_USED_PLUGINS) {
×
1162
                return;
×
1163
            }
1164
            const item = items.find(`[href=${name}]`);
×
1165

1166
            if (item.length) {
×
1167
                const clone = item.closest('.cms-submenu-item').clone(true, true);
×
1168

1169
                ref.after(clone);
×
1170
                ref = clone;
×
1171
                count += 1;
×
1172
            }
1173
        });
1174

1175
        if (count) {
×
1176
            plugins.find('.cms-quicksearch').after(
×
1177
                $(`<div class="cms-submenu-item cms-submenu-item-title" data-cms-most-used>
1178
                    <span>${CMS.config.lang.mostUsed}</span>
1179
                </div>`)
1180
            );
1181
        }
1182

1183
        return plugins;
×
1184
    },
1185

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

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

1221
        if (childRestrictions && childRestrictions.length) {
33✔
1222
            resultElements = resultElements.filter(function() {
29✔
1223
                var item = $(this);
4,727✔
1224

1225
                return (
4,727✔
1226
                    item.hasClass('cms-submenu-item-title') ||
1227
                    childRestrictions.indexOf(item.find('a').attr('href')) !== -1
1228
                );
1229
            });
1230

1231
            resultElements = resultElements.filter(function(index) {
29✔
1232
                var item = $(this);
411✔
1233

1234
                return (
411✔
1235
                    !item.hasClass('cms-submenu-item-title') ||
1236
                    (item.hasClass('cms-submenu-item-title') &&
1237
                        (!resultElements.eq(index + 1).hasClass('cms-submenu-item-title') &&
1238
                            resultElements.eq(index + 1).length))
1239
                );
1240
            });
1241
        }
1242

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

1245
        return resultElements;
33✔
1246
    },
1247

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

1260
        var handler = debounce(function() {
×
1261
            var input = $(this);
×
1262
            // have to always find the pluginsPicker in the handler
1263
            // because of how we move things into/out of the modal
1264
            var pluginsPicker = input.closest('.cms-plugin-picker');
×
1265

1266
            that._filterPluginsList(pluginsPicker, input);
×
1267
        }, FILTER_DEBOUNCE_TIMER);
1268

1269
        plugins.find('> .cms-quicksearch').find('input').on(Plugin.keyUp, handler).on(
×
1270
            Plugin.keyUp,
1271
            debounce(function(e) {
1272
                var input;
1273
                var pluginsPicker;
1274

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

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

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

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

1324
        var nav;
1325
        var that = this;
13✔
1326

1327
        if (e.data && e.data.nav) {
13✔
1328
            nav = e.data.nav;
×
1329
        }
1330

1331
        // show loader and make sure scroll doesn't jump
1332
        showLoader();
13✔
1333

1334
        var items = '.cms-submenu-edit, .cms-submenu-item a';
13✔
1335
        var el = $(e.target).closest(items);
13✔
1336

1337
        Plugin._hideSettingsMenu(nav);
13✔
1338

1339
        // set switch for subnav entries
1340
        switch (el.attr('data-rel')) {
13✔
1341
            // eslint-disable-next-line no-case-declarations
1342
            case 'add':
1343
                const pluginType = el.attr('href').replace('#', '');
2✔
1344

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

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

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

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

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

1445
    /**
1446
     * Opens the settings menu for a plugin.
1447
     *
1448
     * @method _showSettingsMenu
1449
     * @private
1450
     * @param {jQuery} nav trigger element
1451
     */
1452
    _showSettingsMenu: function(nav) {
1453
        this._checkIfPasteAllowed();
×
1454

1455
        var dropdown = this.ui.dropdown;
×
1456
        var parents = nav.parentsUntil('.cms-dragarea').last();
×
1457
        var MIN_SCREEN_MARGIN = 10;
×
1458

1459
        nav.addClass('cms-btn-active');
×
1460
        parents.addClass('cms-z-index-9999');
×
1461

1462
        // set visible states
1463
        dropdown.show();
×
1464

1465
        // calculate dropdown positioning
1466
        if (
×
1467
            $window.height() + $window.scrollTop() - nav.offset().top - dropdown.height() <= MIN_SCREEN_MARGIN &&
1468
            nav.offset().top - dropdown.height() >= 0
1469
        ) {
1470
            dropdown.removeClass('cms-submenu-dropdown-top').addClass('cms-submenu-dropdown-bottom');
×
1471
        } else {
1472
            dropdown.removeClass('cms-submenu-dropdown-bottom').addClass('cms-submenu-dropdown-top');
×
1473
        }
1474
    },
1475

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

1490
        // cancel if query is zero
1491
        if (query === '') {
5✔
1492
            items.add(titles).show();
1✔
1493
            return false;
1✔
1494
        }
1495

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

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

1500
        var itemsToFilter = items.toArray().map(function(el) {
4✔
1501
            var element = $(el);
72✔
1502

1503
            return {
72✔
1504
                value: element.text(),
1505
                element: element
1506
            };
1507
        });
1508

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

1511
        items.hide();
4✔
1512
        filteredItems.forEach(function(item) {
4✔
1513
            item.element.show();
3✔
1514
        });
1515

1516
        // check if a title is matching
1517
        titles.filter(':visible').each(function(index, item) {
4✔
1518
            titles.hide();
1✔
1519
            $(item).nextUntil('.cms-submenu-item-title').show();
1✔
1520
        });
1521

1522
        // always display title of a category
1523
        items.filter(':visible').each(function(index, titleItem) {
4✔
1524
            var item = $(titleItem);
16✔
1525

1526
            if (item.prev().hasClass('cms-submenu-item-title')) {
16✔
1527
                item.prev().show();
2✔
1528
            } else {
1529
                item.prevUntil('.cms-submenu-item-title').last().prev().show();
14✔
1530
            }
1531
        });
1532

1533
        mostRecentItems.hide();
4✔
1534
    },
1535

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

1550
        var settings = CMS.settings;
×
1551

1552
        settings.states = settings.states || [];
×
1553

1554
        if (!draggable || !draggable.length) {
×
1555
            return;
×
1556
        }
1557

1558
        // collapsable function and save states
1559
        if (el.hasClass('cms-dragitem-expanded')) {
×
1560
            settings.states.splice($.inArray(id, settings.states), 1);
×
1561
            el
×
1562
                .removeClass('cms-dragitem-expanded')
1563
                .parent()
1564
                .find('> .cms-collapsable-container')
1565
                .addClass('cms-hidden');
1566

1567
            if ($document.data('expandmode')) {
×
1568
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
1569
                if (!items.length) {
×
1570
                    return false;
×
1571
                }
1572
                items.each(function() {
×
1573
                    var item = $(this);
×
1574

1575
                    if (item.hasClass('cms-dragitem-expanded')) {
×
1576
                        that._toggleCollapsable(item);
×
1577
                    }
1578
                });
1579
            }
1580
        } else {
1581
            settings.states.push(id);
×
1582
            el
×
1583
                .addClass('cms-dragitem-expanded')
1584
                .parent()
1585
                .find('> .cms-collapsable-container')
1586
                .removeClass('cms-hidden');
1587

1588
            if ($document.data('expandmode')) {
×
1589
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
1590
                if (!items.length) {
×
1591
                    return false;
×
1592
                }
1593
                items.each(function() {
×
1594
                    var item = $(this);
×
1595

1596
                    if (!item.hasClass('cms-dragitem-expanded')) {
×
1597
                        that._toggleCollapsable(item);
×
1598
                    }
1599
                });
1600
            }
1601
        }
1602

1603
        this._updatePlaceholderCollapseState();
×
1604

1605
        // make sure structurboard gets updated after expanding
1606
        $document.trigger('resize.sideframe');
×
1607

1608
        // save settings
1609
        Helpers.setSettings(settings);
×
1610
    },
1611

1612
    _updatePlaceholderCollapseState() {
1613
        if (this.options.type !== 'plugin' || !this.options.placeholder_id) {
×
1614
            return;
×
1615
        }
1616

1617
        const pluginsOfCurrentPlaceholder = CMS._plugins
×
1618
            .filter(([, o]) => o.placeholder_id === this.options.placeholder_id && o.type === 'plugin')
×
1619
            .map(([, o]) => o.plugin_id);
×
1620

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

1632
        if (areAllRemainingPluginsLeafs) {
×
1633
            // meaning that all plugins in current placeholder are expanded
1634
            el.addClass('cms-dragbar-title-expanded');
×
1635

1636
            settings.dragbars = settings.dragbars || [];
×
1637
            settings.dragbars.push(this.options.placeholder_id);
×
1638
        } else {
1639
            el.removeClass('cms-dragbar-title-expanded');
×
1640

1641
            settings.dragbars = settings.dragbars || [];
×
1642
            settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1643
        }
1644
    },
1645

1646
    /**
1647
     * Sets up collabspable event handlers.
1648
     *
1649
     * @method _collapsables
1650
     * @private
1651
     * @returns {Boolean|void}
1652
     */
1653
    _collapsables: function() {
1654
        // one time setup
1655
        var that = this;
157✔
1656

1657
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
157✔
1658
        // cancel here if its not a draggable
1659
        if (!this.ui.draggable.length) {
157✔
1660
            return false;
40✔
1661
        }
1662

1663
        var dragitem = this.ui.draggable.find('> .cms-dragitem');
117✔
1664

1665
        // check which button should be shown for collapsemenu
1666
        var els = this.ui.draggable.find('.cms-dragitem-collapsable');
117✔
1667
        var open = els.filter('.cms-dragitem-expanded');
117✔
1668

1669
        if (els.length === open.length && els.length + open.length !== 0) {
117✔
1670
            this.ui.draggable.find('.cms-dragbar-title').addClass('cms-dragbar-title-expanded');
×
1671
        }
1672

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

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

1699
        // cancel if there are no items
1700
        if (!items.length) {
×
1701
            return false;
×
1702
        }
1703
        items.each(function() {
×
1704
            var item = $(this);
×
1705

1706
            if (!item.hasClass('cms-dragitem-expanded')) {
×
1707
                that._toggleCollapsable(item);
×
1708
            }
1709
        });
1710

1711
        el.addClass('cms-dragbar-title-expanded');
×
1712

1713
        var settings = CMS.settings;
×
1714

1715
        settings.dragbars = settings.dragbars || [];
×
1716
        settings.dragbars.push(this.options.placeholder_id);
×
1717
        Helpers.setSettings(settings);
×
1718
    },
1719

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

1731
        items.each(function() {
×
1732
            var item = $(this);
×
1733

1734
            if (item.hasClass('cms-dragitem-expanded')) {
×
1735
                that._toggleCollapsable(item);
×
1736
            }
1737
        });
1738

1739
        el.removeClass('cms-dragbar-title-expanded');
×
1740

1741
        var settings = CMS.settings;
×
1742

1743
        settings.dragbars = settings.dragbars || [];
×
1744
        settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1745
        Helpers.setSettings(settings);
×
1746
    },
1747

1748
    /**
1749
     * Gets the id of the element, uses CMS.StructureBoard instance.
1750
     *
1751
     * @method _getId
1752
     * @private
1753
     * @param {jQuery} el element to get id from
1754
     * @returns {String}
1755
     */
1756
    _getId: function(el) {
1757
        return CMS.API.StructureBoard.getId(el);
39✔
1758
    },
1759

1760
    /**
1761
     * Gets the ids of the list of elements, uses CMS.StructureBoard instance.
1762
     *
1763
     * @method _getIds
1764
     * @private
1765
     * @param {jQuery} els elements to get id from
1766
     * @returns {String[]}
1767
     */
1768
    _getIds: function(els) {
1769
        return CMS.API.StructureBoard.getIds(els);
12✔
1770
    },
1771

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

1782
        breadcrumbs.unshift({
6✔
1783
            title: this.options.plugin_name,
1784
            url: this.options.urls.edit_plugin
1785
        });
1786

1787
        var findParentPlugin = function(id) {
6✔
1788
            return $.grep(CMS._plugins || [], function(pluginOptions) {
6✔
1789
                return pluginOptions[0] === 'cms-plugin-' + id;
10✔
1790
            })[0];
1791
        };
1792

1793
        var id = this.options.plugin_parent;
6✔
1794
        var data;
1795

1796
        while (id && id !== 'None') {
6✔
1797
            data = findParentPlugin(id);
6✔
1798

1799
            if (!data) {
6✔
1800
                break;
1✔
1801
            }
1802

1803
            breadcrumbs.unshift({
5✔
1804
                title: data[1].plugin_name,
1805
                url: data[1].urls.edit_plugin
1806
            });
1807
            id = data[1].plugin_parent;
5✔
1808
        }
1809

1810
        return breadcrumbs;
6✔
1811
    }
1812
});
1813

1814
Plugin.click = 'click.cms.plugin';
1✔
1815
Plugin.pointerUp = 'pointerup.cms.plugin';
1✔
1816
Plugin.pointerDown = 'pointerdown.cms.plugin';
1✔
1817
Plugin.pointerOverAndOut = 'pointerover.cms.plugin pointerout.cms.plugin';
1✔
1818
Plugin.doubleClick = 'dblclick.cms.plugin';
1✔
1819
Plugin.keyUp = 'keyup.cms.plugin';
1✔
1820
Plugin.keyDown = 'keydown.cms.plugin';
1✔
1821
Plugin.mouseEvents = 'mousedown.cms.plugin mousemove.cms.plugin mouseup.cms.plugin';
1✔
1822
Plugin.touchStart = 'touchstart.cms.plugin';
1✔
1823
Plugin.touchEnd = 'touchend.cms.plugin';
1✔
1824

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

1839
        if (pluginIndex === -1) {
×
1840
            CMS._plugins.push([pluginContainer, pluginData]);
×
1841
            CMS._instances.push(new Plugin(pluginContainer, pluginData));
×
1842
        } else {
1843
            Plugin.aliasPluginDuplicatesMap[pluginData.plugin_id] = false;
×
1844
            CMS._plugins[pluginIndex] = [pluginContainer, pluginData];
×
1845
            CMS._instances[pluginIndex] = new Plugin(pluginContainer, pluginData);
×
1846
        }
1847
    });
1848
};
1849

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

1861
    if (!nav.length) {
20✔
1862
        return;
20✔
1863
    }
1864
    nav.removeClass('cms-btn-active');
×
1865

1866
    // set correct active state
1867
    nav.closest('.cms-draggable').data('active', false);
×
1868
    $('.cms-z-index-9999').removeClass('cms-z-index-9999');
×
1869

1870
    nav.siblings('.cms-submenu-dropdown').hide();
×
1871
    nav.siblings('.cms-quicksearch').hide();
×
1872
    // reset search
1873
    nav.siblings('.cms-quicksearch').find('input').val('').trigger(Plugin.keyUp).blur();
×
1874

1875
    // reset relativity
1876
    $('.cms-dragbar').css('position', '');
×
1877
};
1878

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

1893
    Plugin._updateClipboard();
6✔
1894

1895
    // Structureboard initialized too late
1896
    setTimeout(function() {
6✔
1897
        var pluginData = {};
6✔
1898
        var html = '';
6✔
1899

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

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

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

1954
                    clickCounter = 0;
×
1955
                    window.open(anchor.attr('href'), anchor.attr('target') || '_self');
×
1956
                }, DOUBLECLICK_DELAY);
1957
            } else {
1958
                clearTimeout(timer);
×
1959
                clickCounter = 0;
×
1960
            }
1961
        });
1962

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

1972
        e.stopPropagation();
×
1973
        const pluginContainer = $(e.target).closest('.cms-plugin');
×
1974
        const allOptions = pluginContainer.data('cms');
×
1975

1976
        if (!allOptions || !allOptions.length) {
×
1977
            return;
×
1978
        }
1979

1980
        const options = allOptions[0];
×
1981

1982
        if (e.type === 'touchstart') {
×
1983
            CMS.API.Tooltip._forceTouchOnce();
×
1984
        }
1985
        var name = options.plugin_name;
×
1986
        var id = options.plugin_id;
×
1987
        var type = options.type;
×
1988

1989
        if (type === 'generic') {
×
1990
            return;
×
1991
        }
1992
        var placeholderId = CMS.API.StructureBoard.getId($(`.cms-draggable-${id}`).closest('.cms-dragarea'));
×
1993
        var placeholder = $('.cms-placeholder-' + placeholderId);
×
1994

1995
        if (placeholder.length && placeholder.data('cms')) {
×
1996
            name = placeholder.data('cms').name + ': ' + name;
×
1997
        }
1998

1999
        CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
2000
    });
2001

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

2005
        if (placeholder.hasClass('cms-dragarea-static-expanded') && e.isDefaultPrevented()) {
×
2006
            return;
×
2007
        }
2008

2009
        placeholder.toggleClass('cms-dragarea-static-expanded');
×
2010
    });
2011

2012
    $window.on('blur.cms', () => {
6✔
2013
        $document.data('expandmode', false);
6✔
2014
    });
2015
};
2016

2017
/**
2018
 * @method _isContainingMultiplePlugins
2019
 * @param {jQuery} node to check
2020
 * @static
2021
 * @private
2022
 * @returns {Boolean}
2023
 */
2024
Plugin._isContainingMultiplePlugins = function _isContainingMultiplePlugins(node) {
1✔
2025
    var currentData = node.data('cms');
133✔
2026

2027
    // istanbul ignore if
2028
    if (!currentData) {
133✔
2029
        throw new Error('Provided node is not a cms plugin.');
2030
    }
2031

2032
    var pluginIds = currentData.map(function(pluginData) {
133✔
2033
        return pluginData.plugin_id;
134✔
2034
    });
2035

2036
    if (pluginIds.length > 1) {
133✔
2037
        // another plugin already lives on the same node
2038
        // this only works because the plugins are rendered from
2039
        // the bottom to the top (leaf to root)
2040
        // meaning the deepest plugin is always first
2041
        return true;
1✔
2042
    }
2043

2044
    return false;
132✔
2045
};
2046

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

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

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

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

2108
        if (width === 0 && height === 0) {
1✔
2109
            return;
×
2110
        }
2111

2112
        if (isNaN(ml)) {
1✔
2113
            ml = 0;
×
2114
        }
2115
        if (isNaN(mr)) {
1✔
2116
            mr = 0;
×
2117
        }
2118
        if (isNaN(mt)) {
1✔
2119
            mt = 0;
×
2120
        }
2121
        if (isNaN(mb)) {
1✔
2122
            mb = 0;
×
2123
        }
2124

2125
        positions.push({
1✔
2126
            x1: offset.left - ml,
2127
            x2: offset.left + width + mr,
2128
            y1: offset.top - mt,
2129
            y2: offset.top + height + mb
2130
        });
2131
    });
2132

2133
    if (positions.length === 0) {
1✔
2134
        return;
×
2135
    }
2136

2137
    // turns out that offset calculation will be off by toolbar height if
2138
    // position is set to "relative" on html element.
2139
    var html = $('html');
1✔
2140
    var htmlMargin = html.css('position') === 'relative' ? parseInt($('html').css('margin-top'), 10) : 0;
1✔
2141

2142
    coordinates.left = Math.min(...positions.map(pos => pos.x1));
1✔
2143
    coordinates.top = Math.min(...positions.map(pos => pos.y1)) - htmlMargin;
1✔
2144
    coordinates.width = Math.max(...positions.map(pos => pos.x2)) - coordinates.left;
1✔
2145
    coordinates.height = Math.max(...positions.map(pos => pos.y2)) - coordinates.top - htmlMargin;
1✔
2146

2147
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2148

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

2169
    if (successTimeout) {
1✔
2170
        setTimeout(() => {
1✔
2171
            $(`.cms-plugin-overlay-${pluginId}`).fadeOut(successTimeout, function() {
1✔
2172
                $(this).remove();
1✔
2173
            });
2174
        }, delay);
2175
    }
2176
};
2177

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

2188
Plugin._removeHighlightPluginContent = function(pluginId) {
1✔
2189
    $(`.cms-plugin-overlay-${pluginId}[data-success-timeout=0]`).remove();
×
2190
};
2191

2192
Plugin.aliasPluginDuplicatesMap = {};
1✔
2193
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2194

2195
// istanbul ignore next
2196
Plugin._initializeTree = function _initializeTree() {
2197
    CMS._plugins = uniqWith(CMS._plugins, ([x], [y]) => x === y);
2198
    CMS._instances = CMS._plugins.map(function(args) {
2199
        return new CMS.Plugin(args[0], args[1]);
2200
    });
2201

2202
    // return the cms plugin instances just created
2203
    return CMS._instances;
2204
};
2205

2206
Plugin._updateClipboard = function _updateClipboard() {
1✔
2207
    clipboardDraggable = $('.cms-draggable-from-clipboard:first');
7✔
2208
};
2209

2210
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2211
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2212

2213
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2214

2215
    if (Helpers._isStorageSupported) {
2✔
2216
        localStorage.setItem('cms-plugin-usage', JSON.stringify(pluginUsageMap));
×
2217
    }
2218
};
2219

2220
Plugin._removeAddPluginPlaceholder = function removeAddPluginPlaceholder() {
1✔
2221
    // this can't be cached since they are created and destroyed all over the place
2222
    $('.cms-add-plugin-placeholder').remove();
10✔
2223
};
2224

2225
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2226
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2227
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2228
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2229

2230
    CMS._instances.forEach(instance => {
4✔
2231
        if (instance.options.type === 'placeholder') {
5✔
2232
            instance._setupUI(`cms-placeholder-${instance.options.placeholder_id}`);
2✔
2233
            instance._ensureData();
2✔
2234
            instance.ui.container.data('cms', instance.options);
2✔
2235
            instance._setPlaceholder();
2✔
2236
        }
2237
    });
2238

2239
    CMS._instances.forEach(instance => {
4✔
2240
        if (instance.options.type === 'plugin') {
5✔
2241
            instance._setupUI(`cms-plugin-${instance.options.plugin_id}`);
2✔
2242
            instance._ensureData();
2✔
2243
            instance.ui.container.data('cms').push(instance.options);
2✔
2244
            instance._setPluginContentEvents();
2✔
2245
        }
2246
    });
2247

2248
    CMS._plugins.forEach(([type, opts]) => {
4✔
2249
        if (opts.type !== 'placeholder' && opts.type !== 'plugin') {
16✔
2250
            const instance = find(
8✔
2251
                CMS._instances,
2252
                i => i.options.type === opts.type && Number(i.options.plugin_id) === Number(opts.plugin_id)
13✔
2253
            );
2254

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

2269
// shorthand for jQuery(document).ready();
2270
$(Plugin._initializeGlobalHandlers);
1✔
2271

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

© 2026 Coveralls, Inc