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

divio / django-cms / #29274

09 Jan 2025 01:23PM UTC coverage: 76.134%. Remained the same
#29274

push

travis-ci

web-flow
Merge 70639f549 into ec268c7b2

1046 of 1559 branches covered (67.09%)

0 of 10 new or added lines in 1 file covered. (0.0%)

168 existing lines in 1 file now uncovered.

2517 of 3306 relevant lines covered (76.13%)

26.85 hits per line

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

58.82
/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;
×
341
        var disabled = $(e.currentTarget).closest('.cms-drag-disabled');
×
342

343
        e.preventDefault();
×
344
        e.stopPropagation();
×
345

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

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

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

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

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

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

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

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

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

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

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

456
        var bounds = this.options.plugin_restriction;
20✔
457

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

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

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

483
        return true;
5✔
484
    },
485

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

505
        if (parent) {
3✔
506
            params.plugin_parent = parent;
1✔
507
        }
508
        var url = this.options.urls.add_plugin + '?' + $.param(params);
3✔
509
        var modal = new Modal({
3✔
510
            onClose: this.options.onClose || false,
5✔
511
            redirectOnClose: this.options.redirectOnClose || false
5✔
512
        });
513

514
        modal.open({
3✔
515
            url: url,
516
            title: name
517
        });
518

519
        this.modal = modal;
3✔
520

521
        Helpers.removeEventListener('modal-closed.add-plugin');
3✔
522
        Helpers.addEventListener('modal-closed.add-plugin', (e, { instance }) => {
3✔
523
            if (instance !== modal) {
1!
524
                return;
×
525
            }
526
            Plugin._removeAddPluginPlaceholder();
1✔
527
        });
528
    },
529

530
    _getPluginAddPosition: function() {
531
        if (this.options.type === 'placeholder') {
×
532
            return $(`.cms-dragarea-${this.options.placeholder_id} .cms-draggable`).length + 1;
×
533
        }
534

535
        // assume plugin now
536
        // would prefer to get the information from the tree, but the problem is that the flat data
537
        // isn't sorted by position
538
        const maybeChildren = this.ui.draggable.find('.cms-draggable');
×
539

540
        if (maybeChildren.length) {
×
541
            const lastChild = maybeChildren.last();
×
542

543
            const lastChildInstance = Plugin._getPluginById(this._getId(lastChild));
×
544

545
            return lastChildInstance.options.position + 1;
×
546
        }
547

548
        return this.options.position + 1;
×
549
    },
550

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

567
        this.modal = modal;
3✔
568

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

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

604
        // set correct options (don't mutate them)
605
        var options = $.extend({}, opts || this.options);
8✔
606
        var sourceLanguage = source_language;
8✔
607
        let copyingFromLanguage = false;
8✔
608

609
        if (sourceLanguage) {
8✔
610
            copyingFromLanguage = true;
1✔
611
            options.target = options.placeholder_id;
1✔
612
            options.plugin_id = '';
1✔
613
            options.parent = '';
1✔
614
        } else {
615
            sourceLanguage = CMS.config.request.language;
7✔
616
        }
617

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

647
                // trigger error
648
                CMS.API.Messages.open({
3✔
649
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
4✔
650
                    error: true
651
                });
652
            }
653
        };
654

655
        $.ajax(request);
8✔
656
    },
657

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

672
        var that = this;
8✔
673
        var data = {
8✔
674
            placeholder_id: CMS.config.clipboard.id,
675
            plugin_id: this.options.plugin_id,
676
            plugin_parent: '',
677
            target_language: CMS.config.request.language,
678
            csrfmiddlewaretoken: CMS.config.csrf
679
        };
680

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

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

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

720
        const clipboardDraggableClone = clipboardDraggable.clone(true, true);
5✔
721

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

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

749
        // set correct options
750
        var options = opts || this.options;
11✔
751

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

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

757
        // cancel here if we have no placeholder id
758
        if (placeholder_id === false) {
11✔
759
            return false;
1✔
760
        }
761
        var pluginParentElement = dragitem.parent().closest('.cms-draggable');
10✔
762
        var plugin_parent = this._getId(pluginParentElement);
10✔
763

764
        // gather the data for ajax request
765
        var data = {
10✔
766
            plugin_id: options.plugin_id,
767
            plugin_parent: plugin_parent || '',
20✔
768
            target_language: CMS.config.request.language,
769
            csrfmiddlewaretoken: CMS.config.csrf,
770
            move_a_copy: options.move_a_copy
771
        };
772

773
        if (Number(placeholder_id) === Number(options.placeholder_id)) {
10!
774
            Plugin._updatePluginPositions(options.placeholder_id);
10✔
775
        } else {
776
            data.placeholder_id = placeholder_id;
×
777

778
            Plugin._updatePluginPositions(placeholder_id);
×
779
            Plugin._updatePluginPositions(options.placeholder_id);
×
780
        }
781

782
        var position = this.options.position;
10✔
783

784
        data.target_position = position;
10✔
785

786
        showLoader();
10✔
787

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

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

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

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

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

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

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

861
        this.modal = modal;
2✔
862

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

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

887
        // close the plugin modal if it was open
888
        if (this.modal) {
2!
889
            this.modal.close();
×
890
            // unsubscribe to all the modal events
891
            this.modal.off();
×
892
        }
893

894
        if (mustCleanup) {
2✔
895
            this.cleanup();
1✔
896
        }
897

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

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

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

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

937
        this.ui.dropdown = nav.siblings('.cms-submenu-dropdown-settings');
152✔
938
        var dropdown = this.ui.dropdown;
152✔
939

940
        nav
152✔
941
            .off(Plugin.pointerUp)
942
            .on(Plugin.pointerUp, function(e) {
943
                e.preventDefault();
×
944
                e.stopPropagation();
×
945
                var trigger = $(this);
×
946

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

962
        dropdown
152✔
963
            .off(Plugin.mouseEvents)
964
            .on(Plugin.mouseEvents, function(e) {
965
                e.stopPropagation();
×
966
            })
967
            .off(Plugin.touchStart)
968
            .on(Plugin.touchStart, function(e) {
969
                // required for scrolling on mobile
970
                e.stopPropagation();
×
971
            });
972

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

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

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

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

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

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

UNCOV
1049
            modal = new Modal({
×
1050
                minWidth: 400,
1051
                minHeight: 400
1052
            });
1053

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

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

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

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

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

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

UNCOV
1095
            plugins = nav.siblings('.cms-plugin-picker');
×
1096

UNCOV
1097
            that._setupQuickSearch(plugins);
×
1098
        });
1099

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

UNCOV
1112
                Plugin._hideSettingsMenu();
×
1113

NEW
1114
                possibleChildClasses = that._getPossibleChildClasses();
×
NEW
1115
                var selectionNeeded = possibleChildClasses.filter(':not(.cms-submenu-item-title)').length !== 1;
×
1116

NEW
1117
                if (selectionNeeded) {
×
NEW
1118
                    initModal();
×
1119

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

NEW
1129
                    modal.open({
×
1130
                        title: that.options.addPluginHelpTitle,
1131
                        html: pluginsCopy,
1132
                        width: 530,
1133
                        height: 400
1134
                    });
1135
                } else {
1136
                    // only one plugin available, no need to show the modal
1137
                    // instead directly add the single plugin
NEW
1138
                    const el = possibleChildClasses.find('a');  // only one result
×
NEW
1139
                    const pluginType = el.attr('href').replace('#', '');
×
NEW
1140
                    const parentId = that._getId(nav.closest('.cms-draggable'));
×
1141

NEW
1142
                    that.addPlugin(pluginType, el.text(), parentId);
×
1143
                }
1144
            });
1145

1146
        // prevent propagation
1147
        nav.on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
65✔
UNCOV
1148
            e.stopPropagation();
×
1149
        });
1150

1151
        nav
65✔
1152
            .siblings('.cms-quicksearch, .cms-submenu-dropdown')
1153
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
1154
                e.stopPropagation();
×
1155
            });
1156
    },
1157

1158
    _updateWithMostUsedPlugins: function _updateWithMostUsedPlugins(plugins) {
UNCOV
1159
        const items = plugins.find('.cms-submenu-item');
×
1160
        // eslint-disable-next-line no-unused-vars
1161
        const mostUsedPlugins = toPairs(pluginUsageMap).sort(([x, a], [y, b]) => a - b).reverse();
×
UNCOV
1162
        const MAX_MOST_USED_PLUGINS = 5;
×
UNCOV
1163
        let count = 0;
×
1164

UNCOV
1165
        if (items.filter(':not(.cms-submenu-item-title)').length <= MAX_MOST_USED_PLUGINS) {
×
UNCOV
1166
            return plugins;
×
1167
        }
1168

UNCOV
1169
        let ref = plugins.find('.cms-quicksearch');
×
1170

UNCOV
1171
        mostUsedPlugins.forEach(([name]) => {
×
1172
            if (count === MAX_MOST_USED_PLUGINS) {
×
UNCOV
1173
                return;
×
1174
            }
1175
            const item = items.find(`[href=${name}]`);
×
1176

UNCOV
1177
            if (item.length) {
×
1178
                const clone = item.closest('.cms-submenu-item').clone(true, true);
×
1179

UNCOV
1180
                ref.after(clone);
×
UNCOV
1181
                ref = clone;
×
1182
                count += 1;
×
1183
            }
1184
        });
1185

1186
        if (count) {
×
UNCOV
1187
            plugins.find('.cms-quicksearch').after(
×
1188
                $(`<div class="cms-submenu-item cms-submenu-item-title" data-cms-most-used>
1189
                    <span>${CMS.config.lang.mostUsed}</span>
1190
                </div>`)
1191
            );
1192
        }
1193

1194
        return plugins;
×
1195
    },
1196

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

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

1232
        if (childRestrictions && childRestrictions.length) {
33✔
1233
            resultElements = resultElements.filter(function() {
29✔
1234
                var item = $(this);
4,727✔
1235

1236
                return (
4,727✔
1237
                    item.hasClass('cms-submenu-item-title') ||
9,106✔
1238
                    childRestrictions.indexOf(item.find('a').attr('href')) !== -1
1239
                );
1240
            });
1241

1242
            resultElements = resultElements.filter(function(index) {
29✔
1243
                var item = $(this);
411✔
1244

1245
                return (
411✔
1246
                    !item.hasClass('cms-submenu-item-title') ||
1,182✔
1247
                    (item.hasClass('cms-submenu-item-title') &&
1248
                        (!resultElements.eq(index + 1).hasClass('cms-submenu-item-title') &&
1249
                            resultElements.eq(index + 1).length))
1250
                );
1251
            });
1252
        }
1253

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

1256
        return resultElements;
33✔
1257
    },
1258

1259
    /**
1260
     * Sets up event handlers for quicksearching in the plugin picker.
1261
     *
1262
     * @method _setupQuickSearch
1263
     * @private
1264
     * @param {jQuery} plugins plugins picker element
1265
     */
1266
    _setupQuickSearch: function _setupQuickSearch(plugins) {
UNCOV
1267
        var that = this;
×
UNCOV
1268
        var FILTER_DEBOUNCE_TIMER = 100;
×
UNCOV
1269
        var FILTER_PICK_DEBOUNCE_TIMER = 110;
×
1270

UNCOV
1271
        var handler = debounce(function() {
×
UNCOV
1272
            var input = $(this);
×
1273
            // have to always find the pluginsPicker in the handler
1274
            // because of how we move things into/out of the modal
UNCOV
1275
            var pluginsPicker = input.closest('.cms-plugin-picker');
×
1276

UNCOV
1277
            that._filterPluginsList(pluginsPicker, input);
×
1278
        }, FILTER_DEBOUNCE_TIMER);
1279

1280
        plugins.find('> .cms-quicksearch').find('input').on(Plugin.keyUp, handler).on(
×
1281
            Plugin.keyUp,
1282
            debounce(function(e) {
1283
                var input;
1284
                var pluginsPicker;
1285

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

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

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

1323
    /**
1324
     * Handler for the "action" items
1325
     *
1326
     * @method _delegate
1327
     * @param {$.Event} e event
1328
     * @private
1329
     */
1330
    // eslint-disable-next-line complexity
1331
    _delegate: function _delegate(e) {
1332
        e.preventDefault();
13✔
1333
        e.stopPropagation();
13✔
1334

1335
        var nav;
1336
        var that = this;
13✔
1337

1338
        if (e.data && e.data.nav) {
13!
UNCOV
1339
            nav = e.data.nav;
×
1340
        }
1341

1342
        // show loader and make sure scroll doesn't jump
1343
        showLoader();
13✔
1344

1345
        var items = '.cms-submenu-edit, .cms-submenu-item a';
13✔
1346
        var el = $(e.target).closest(items);
13✔
1347

1348
        Plugin._hideSettingsMenu(nav);
13✔
1349

1350
        // set switch for subnav entries
1351
        switch (el.attr('data-rel')) {
13!
1352
            // eslint-disable-next-line no-case-declarations
1353
            case 'add':
1354
                const pluginType = el.attr('href').replace('#', '');
2✔
1355

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

1414
    /**
1415
     * Sets up keyboard traversing of plugin picker.
1416
     *
1417
     * @method _setupKeyboardTraversing
1418
     * @private
1419
     */
1420
    _setupKeyboardTraversing: function _setupKeyboardTraversing() {
1421
        var dropdown = $('.cms-modal-markup .cms-plugin-picker');
3✔
1422
        const keyDownTraverseEvent = this._getNamepacedEvent(Plugin.keyDown, 'traverse');
3✔
1423

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

1434
            // bind arrow down and tab keys
1435
            if (e.keyCode === KEYS.DOWN || (e.keyCode === KEYS.TAB && !e.shiftKey)) {
1436
                e.preventDefault();
1437
                if (index >= 0 && index < anchors.length - 1) {
1438
                    anchors.eq(index + 1).focus();
1439
                } else {
1440
                    anchors.eq(0).focus();
1441
                }
1442
            }
1443

1444
            // bind arrow up and shift+tab keys
1445
            if (e.keyCode === KEYS.UP || (e.keyCode === KEYS.TAB && e.shiftKey)) {
1446
                e.preventDefault();
1447
                if (anchors.is(':focus')) {
1448
                    anchors.eq(index - 1).focus();
1449
                } else {
1450
                    anchors.eq(anchors.length).focus();
1451
                }
1452
            }
1453
        });
1454
    },
1455

1456
    /**
1457
     * Opens the settings menu for a plugin.
1458
     *
1459
     * @method _showSettingsMenu
1460
     * @private
1461
     * @param {jQuery} nav trigger element
1462
     */
1463
    _showSettingsMenu: function(nav) {
UNCOV
1464
        this._checkIfPasteAllowed();
×
1465

UNCOV
1466
        var dropdown = this.ui.dropdown;
×
UNCOV
1467
        var parents = nav.parentsUntil('.cms-dragarea').last();
×
UNCOV
1468
        var MIN_SCREEN_MARGIN = 10;
×
1469

UNCOV
1470
        nav.addClass('cms-btn-active');
×
UNCOV
1471
        parents.addClass('cms-z-index-9999');
×
1472

1473
        // set visible states
UNCOV
1474
        dropdown.show();
×
1475

1476
        // calculate dropdown positioning
1477
        if (
×
1478
            $window.height() + $window.scrollTop() - nav.offset().top - dropdown.height() <= MIN_SCREEN_MARGIN &&
×
1479
            nav.offset().top - dropdown.height() >= 0
1480
        ) {
1481
            dropdown.removeClass('cms-submenu-dropdown-top').addClass('cms-submenu-dropdown-bottom');
×
1482
        } else {
1483
            dropdown.removeClass('cms-submenu-dropdown-bottom').addClass('cms-submenu-dropdown-top');
×
1484
        }
1485
    },
1486

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

1501
        // cancel if query is zero
1502
        if (query === '') {
5✔
1503
            items.add(titles).show();
1✔
1504
            return false;
1✔
1505
        }
1506

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

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

1511
        var itemsToFilter = items.toArray().map(function(el) {
4✔
1512
            var element = $(el);
72✔
1513

1514
            return {
72✔
1515
                value: element.text(),
1516
                element: element
1517
            };
1518
        });
1519

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

1522
        items.hide();
4✔
1523
        filteredItems.forEach(function(item) {
4✔
1524
            item.element.show();
3✔
1525
        });
1526

1527
        // check if a title is matching
1528
        titles.filter(':visible').each(function(index, item) {
4✔
1529
            titles.hide();
1✔
1530
            $(item).nextUntil('.cms-submenu-item-title').show();
1✔
1531
        });
1532

1533
        // always display title of a category
1534
        items.filter(':visible').each(function(index, titleItem) {
4✔
1535
            var item = $(titleItem);
16✔
1536

1537
            if (item.prev().hasClass('cms-submenu-item-title')) {
16✔
1538
                item.prev().show();
2✔
1539
            } else {
1540
                item.prevUntil('.cms-submenu-item-title').last().prev().show();
14✔
1541
            }
1542
        });
1543

1544
        mostRecentItems.hide();
4✔
1545
    },
1546

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

UNCOV
1561
        var settings = CMS.settings;
×
1562

UNCOV
1563
        settings.states = settings.states || [];
×
1564

UNCOV
1565
        if (!draggable || !draggable.length) {
×
UNCOV
1566
            return;
×
1567
        }
1568

1569
        // collapsable function and save states
1570
        if (el.hasClass('cms-dragitem-expanded')) {
×
1571
            settings.states.splice($.inArray(id, settings.states), 1);
×
UNCOV
1572
            el
×
1573
                .removeClass('cms-dragitem-expanded')
1574
                .parent()
1575
                .find('> .cms-collapsable-container')
1576
                .addClass('cms-hidden');
1577

1578
            if ($document.data('expandmode')) {
×
1579
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
UNCOV
1580
                if (!items.length) {
×
UNCOV
1581
                    return false;
×
1582
                }
1583
                items.each(function() {
×
1584
                    var item = $(this);
×
1585

UNCOV
1586
                    if (item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1587
                        that._toggleCollapsable(item);
×
1588
                    }
1589
                });
1590
            }
1591
        } else {
1592
            settings.states.push(id);
×
1593
            el
×
1594
                .addClass('cms-dragitem-expanded')
1595
                .parent()
1596
                .find('> .cms-collapsable-container')
1597
                .removeClass('cms-hidden');
1598

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

UNCOV
1607
                    if (!item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1608
                        that._toggleCollapsable(item);
×
1609
                    }
1610
                });
1611
            }
1612
        }
1613

1614
        this._updatePlaceholderCollapseState();
×
1615

1616
        // make sure structurboard gets updated after expanding
1617
        $document.trigger('resize.sideframe');
×
1618

1619
        // save settings
1620
        Helpers.setSettings(settings);
×
1621
    },
1622

1623
    _updatePlaceholderCollapseState() {
UNCOV
1624
        if (this.options.type !== 'plugin' || !this.options.placeholder_id) {
×
UNCOV
1625
            return;
×
1626
        }
1627

UNCOV
1628
        const pluginsOfCurrentPlaceholder = CMS._plugins
×
UNCOV
1629
            .filter(([, o]) => o.placeholder_id === this.options.placeholder_id && o.type === 'plugin')
×
1630
            .map(([, o]) => o.plugin_id);
×
1631

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

1643
        if (areAllRemainingPluginsLeafs) {
×
1644
            // meaning that all plugins in current placeholder are expanded
1645
            el.addClass('cms-dragbar-title-expanded');
×
1646

1647
            settings.dragbars = settings.dragbars || [];
×
1648
            settings.dragbars.push(this.options.placeholder_id);
×
1649
        } else {
1650
            el.removeClass('cms-dragbar-title-expanded');
×
1651

UNCOV
1652
            settings.dragbars = settings.dragbars || [];
×
1653
            settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1654
        }
1655
    },
1656

1657
    /**
1658
     * Sets up collabspable event handlers.
1659
     *
1660
     * @method _collapsables
1661
     * @private
1662
     * @returns {Boolean|void}
1663
     */
1664
    _collapsables: function() {
1665
        // one time setup
1666
        var that = this;
152✔
1667

1668
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
152✔
1669
        // cancel here if its not a draggable
1670
        if (!this.ui.draggable.length) {
152✔
1671
            return false;
38✔
1672
        }
1673

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

1676
        // check which button should be shown for collapsemenu
1677
        var els = this.ui.draggable.find('.cms-dragitem-collapsable');
114✔
1678
        var open = els.filter('.cms-dragitem-expanded');
114✔
1679

1680
        if (els.length === open.length && els.length + open.length !== 0) {
114!
UNCOV
1681
            this.ui.draggable.find('.cms-dragbar-title').addClass('cms-dragbar-title-expanded');
×
1682
        }
1683

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

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

1710
        // cancel if there are no items
UNCOV
1711
        if (!items.length) {
×
UNCOV
1712
            return false;
×
1713
        }
UNCOV
1714
        items.each(function() {
×
UNCOV
1715
            var item = $(this);
×
1716

UNCOV
1717
            if (!item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1718
                that._toggleCollapsable(item);
×
1719
            }
1720
        });
1721

UNCOV
1722
        el.addClass('cms-dragbar-title-expanded');
×
1723

1724
        var settings = CMS.settings;
×
1725

UNCOV
1726
        settings.dragbars = settings.dragbars || [];
×
1727
        settings.dragbars.push(this.options.placeholder_id);
×
1728
        Helpers.setSettings(settings);
×
1729
    },
1730

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

UNCOV
1742
        items.each(function() {
×
UNCOV
1743
            var item = $(this);
×
1744

UNCOV
1745
            if (item.hasClass('cms-dragitem-expanded')) {
×
UNCOV
1746
                that._toggleCollapsable(item);
×
1747
            }
1748
        });
1749

UNCOV
1750
        el.removeClass('cms-dragbar-title-expanded');
×
1751

1752
        var settings = CMS.settings;
×
1753

UNCOV
1754
        settings.dragbars = settings.dragbars || [];
×
1755
        settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1756
        Helpers.setSettings(settings);
×
1757
    },
1758

1759
    /**
1760
     * Gets the id of the element, uses CMS.StructureBoard instance.
1761
     *
1762
     * @method _getId
1763
     * @private
1764
     * @param {jQuery} el element to get id from
1765
     * @returns {String}
1766
     */
1767
    _getId: function(el) {
1768
        return CMS.API.StructureBoard.getId(el);
36✔
1769
    },
1770

1771
    /**
1772
     * Gets the ids of the list of elements, uses CMS.StructureBoard instance.
1773
     *
1774
     * @method _getIds
1775
     * @private
1776
     * @param {jQuery} els elements to get id from
1777
     * @returns {String[]}
1778
     */
1779
    _getIds: function(els) {
UNCOV
1780
        return CMS.API.StructureBoard.getIds(els);
×
1781
    },
1782

1783
    /**
1784
     * Traverses the registry to find plugin parents
1785
     *
1786
     * @method _getPluginBreadcrumbs
1787
     * @returns {Object[]} array of breadcrumbs in `{ url, title }` format
1788
     * @private
1789
     */
1790
    _getPluginBreadcrumbs: function _getPluginBreadcrumbs() {
1791
        var breadcrumbs = [];
6✔
1792

1793
        breadcrumbs.unshift({
6✔
1794
            title: this.options.plugin_name,
1795
            url: this.options.urls.edit_plugin
1796
        });
1797

1798
        var findParentPlugin = function(id) {
6✔
1799
            return $.grep(CMS._plugins || [], function(pluginOptions) {
6✔
1800
                return pluginOptions[0] === 'cms-plugin-' + id;
10✔
1801
            })[0];
1802
        };
1803

1804
        var id = this.options.plugin_parent;
6✔
1805
        var data;
1806

1807
        while (id && id !== 'None') {
6✔
1808
            data = findParentPlugin(id);
6✔
1809

1810
            if (!data) {
6✔
1811
                break;
1✔
1812
            }
1813

1814
            breadcrumbs.unshift({
5✔
1815
                title: data[1].plugin_name,
1816
                url: data[1].urls.edit_plugin
1817
            });
1818
            id = data[1].plugin_parent;
5✔
1819
        }
1820

1821
        return breadcrumbs;
6✔
1822
    }
1823
});
1824

1825
Plugin.click = 'click.cms.plugin';
1✔
1826
Plugin.pointerUp = 'pointerup.cms.plugin';
1✔
1827
Plugin.pointerDown = 'pointerdown.cms.plugin';
1✔
1828
Plugin.pointerOverAndOut = 'pointerover.cms.plugin pointerout.cms.plugin';
1✔
1829
Plugin.doubleClick = 'dblclick.cms.plugin';
1✔
1830
Plugin.keyUp = 'keyup.cms.plugin';
1✔
1831
Plugin.keyDown = 'keydown.cms.plugin';
1✔
1832
Plugin.mouseEvents = 'mousedown.cms.plugin mousemove.cms.plugin mouseup.cms.plugin';
1✔
1833
Plugin.touchStart = 'touchstart.cms.plugin';
1✔
1834
Plugin.touchEnd = 'touchend.cms.plugin';
1✔
1835

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

UNCOV
1850
        if (pluginIndex === -1) {
×
UNCOV
1851
            CMS._plugins.push([pluginContainer, pluginData]);
×
UNCOV
1852
            CMS._instances.push(new Plugin(pluginContainer, pluginData));
×
1853
        } else {
UNCOV
1854
            Plugin.aliasPluginDuplicatesMap[pluginData.plugin_id] = false;
×
UNCOV
1855
            CMS._plugins[pluginIndex] = [pluginContainer, pluginData];
×
UNCOV
1856
            CMS._instances[pluginIndex] = new Plugin(pluginContainer, pluginData);
×
1857
        }
1858
    });
1859
};
1860

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

1872
    if (!nav.length) {
20!
1873
        return;
20✔
1874
    }
UNCOV
1875
    nav.removeClass('cms-btn-active');
×
1876

1877
    // set correct active state
UNCOV
1878
    nav.closest('.cms-draggable').data('active', false);
×
UNCOV
1879
    $('.cms-z-index-9999').removeClass('cms-z-index-9999');
×
1880

UNCOV
1881
    nav.siblings('.cms-submenu-dropdown').hide();
×
UNCOV
1882
    nav.siblings('.cms-quicksearch').hide();
×
1883
    // reset search
UNCOV
1884
    nav.siblings('.cms-quicksearch').find('input').val('').trigger(Plugin.keyUp).blur();
×
1885

1886
    // reset relativity
UNCOV
1887
    $('.cms-dragbar').css('position', '');
×
1888
};
1889

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

1904
    Plugin._updateClipboard();
6✔
1905

1906
    // Structureboard initialized too late
1907
    setTimeout(function() {
6✔
1908
        var pluginData = {};
6✔
1909
        var html = '';
6✔
1910

1911
        if (clipboardDraggable.length) {
6✔
1912
            pluginData = find(
5✔
1913
                CMS._plugins,
1914
                ([desc]) => desc === `cms-plugin-${CMS.API.StructureBoard.getId(clipboardDraggable)}`
10✔
1915
            )[1];
1916
            html = clipboardDraggable.parent().html();
5✔
1917
        }
1918
        if (CMS.API && CMS.API.Clipboard) {
6!
1919
            CMS.API.Clipboard.populate(html, pluginData);
6✔
1920
        }
1921
    }, 0);
1922

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

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

1965
                    clickCounter = 0;
×
UNCOV
1966
                    window.open(anchor.attr('href'), anchor.attr('target') || '_self');
×
1967
                }, DOUBLECLICK_DELAY);
1968
            } else {
UNCOV
1969
                clearTimeout(timer);
×
1970
                clickCounter = 0;
×
1971
            }
1972
        });
1973

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

1983
        e.stopPropagation();
×
UNCOV
1984
        const pluginContainer = $(e.target).closest('.cms-plugin');
×
UNCOV
1985
        const allOptions = pluginContainer.data('cms');
×
1986

UNCOV
1987
        if (!allOptions || !allOptions.length) {
×
UNCOV
1988
            return;
×
1989
        }
1990

UNCOV
1991
        const options = allOptions[0];
×
1992

UNCOV
1993
        if (e.type === 'touchstart') {
×
UNCOV
1994
            CMS.API.Tooltip._forceTouchOnce();
×
1995
        }
1996
        var name = options.plugin_name;
×
1997
        var id = options.plugin_id;
×
1998
        var type = options.type;
×
1999

2000
        if (type === 'generic') {
×
2001
            return;
×
2002
        }
UNCOV
2003
        var placeholderId = CMS.API.StructureBoard.getId($(`.cms-draggable-${id}`).closest('.cms-dragarea'));
×
2004
        var placeholder = $('.cms-placeholder-' + placeholderId);
×
2005

2006
        if (placeholder.length && placeholder.data('cms')) {
×
2007
            name = placeholder.data('cms').name + ': ' + name;
×
2008
        }
2009

2010
        CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
2011
    });
2012

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

2016
        if (placeholder.hasClass('cms-dragarea-static-expanded') && e.isDefaultPrevented()) {
×
2017
            return;
×
2018
        }
2019

2020
        placeholder.toggleClass('cms-dragarea-static-expanded');
×
2021
    });
2022

2023
    $window.on('blur.cms', () => {
6✔
2024
        $document.data('expandmode', false);
6✔
2025
    });
2026
};
2027

2028
/**
2029
 * @method _isContainingMultiplePlugins
2030
 * @param {jQuery} node to check
2031
 * @static
2032
 * @private
2033
 * @returns {Boolean}
2034
 */
2035
Plugin._isContainingMultiplePlugins = function _isContainingMultiplePlugins(node) {
1✔
2036
    var currentData = node.data('cms');
129✔
2037

2038
    // istanbul ignore if
2039
    if (!currentData) {
129✔
2040
        throw new Error('Provided node is not a cms plugin.');
2041
    }
2042

2043
    var pluginIds = currentData.map(function(pluginData) {
129✔
2044
        return pluginData.plugin_id;
130✔
2045
    });
2046

2047
    if (pluginIds.length > 1) {
129✔
2048
        // another plugin already lives on the same node
2049
        // this only works because the plugins are rendered from
2050
        // the bottom to the top (leaf to root)
2051
        // meaning the deepest plugin is always first
2052
        return true;
1✔
2053
    }
2054

2055
    return false;
128✔
2056
};
2057

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

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

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

2109
    $('.cms-plugin-' + pluginId).each(function() {
1✔
2110
        var el = $(this);
1✔
2111
        var offset = el.offset();
1✔
2112
        var ml = parseInt(el.css('margin-left'), 10);
1✔
2113
        var mr = parseInt(el.css('margin-right'), 10);
1✔
2114
        var mt = parseInt(el.css('margin-top'), 10);
1✔
2115
        var mb = parseInt(el.css('margin-bottom'), 10);
1✔
2116
        var width = el.outerWidth();
1✔
2117
        var height = el.outerHeight();
1✔
2118

2119
        if (width === 0 && height === 0) {
1!
UNCOV
2120
            return;
×
2121
        }
2122

2123
        if (isNaN(ml)) {
1!
UNCOV
2124
            ml = 0;
×
2125
        }
2126
        if (isNaN(mr)) {
1!
UNCOV
2127
            mr = 0;
×
2128
        }
2129
        if (isNaN(mt)) {
1!
UNCOV
2130
            mt = 0;
×
2131
        }
2132
        if (isNaN(mb)) {
1!
2133
            mb = 0;
×
2134
        }
2135

2136
        positions.push({
1✔
2137
            x1: offset.left - ml,
2138
            x2: offset.left + width + mr,
2139
            y1: offset.top - mt,
2140
            y2: offset.top + height + mb
2141
        });
2142
    });
2143

2144
    if (positions.length === 0) {
1!
UNCOV
2145
        return;
×
2146
    }
2147

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

2153
    coordinates.left = Math.min(...positions.map(pos => pos.x1));
1✔
2154
    coordinates.top = Math.min(...positions.map(pos => pos.y1)) - htmlMargin;
1✔
2155
    coordinates.width = Math.max(...positions.map(pos => pos.x2)) - coordinates.left;
1✔
2156
    coordinates.height = Math.max(...positions.map(pos => pos.y2)) - coordinates.top - htmlMargin;
1✔
2157

2158
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2159

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

2180
    if (successTimeout) {
1!
2181
        setTimeout(() => {
1✔
2182
            $(`.cms-plugin-overlay-${pluginId}`).fadeOut(successTimeout, function() {
1✔
2183
                $(this).remove();
1✔
2184
            });
2185
        }, delay);
2186
    }
2187
};
2188

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

2199
Plugin._removeHighlightPluginContent = function(pluginId) {
1✔
UNCOV
2200
    $(`.cms-plugin-overlay-${pluginId}[data-success-timeout=0]`).remove();
×
2201
};
2202

2203
Plugin.aliasPluginDuplicatesMap = {};
1✔
2204
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2205

2206
// istanbul ignore next
2207
Plugin._initializeTree = function _initializeTree() {
2208
    CMS._plugins = uniqWith(CMS._plugins, ([x], [y]) => x === y);
2209
    CMS._instances = CMS._plugins.map(function(args) {
2210
        return new CMS.Plugin(args[0], args[1]);
2211
    });
2212

2213
    // return the cms plugin instances just created
2214
    return CMS._instances;
2215
};
2216

2217
Plugin._updateClipboard = function _updateClipboard() {
1✔
2218
    clipboardDraggable = $('.cms-draggable-from-clipboard:first');
7✔
2219
};
2220

2221
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2222
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2223

2224
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2225

2226
    if (Helpers._isStorageSupported) {
2!
UNCOV
2227
        localStorage.setItem('cms-plugin-usage', JSON.stringify(pluginUsageMap));
×
2228
    }
2229
};
2230

2231
Plugin._removeAddPluginPlaceholder = function removeAddPluginPlaceholder() {
1✔
2232
    // this can't be cached since they are created and destroyed all over the place
2233
    $('.cms-add-plugin-placeholder').remove();
10✔
2234
};
2235

2236
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2237
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2238
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2239
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2240

2241
    CMS._instances.forEach(instance => {
4✔
2242
        if (instance.options.type === 'placeholder') {
5✔
2243
            instance._setupUI(`cms-placeholder-${instance.options.placeholder_id}`);
2✔
2244
            instance._ensureData();
2✔
2245
            instance.ui.container.data('cms', instance.options);
2✔
2246
            instance._setPlaceholder();
2✔
2247
        }
2248
    });
2249

2250
    CMS._instances.forEach(instance => {
4✔
2251
        if (instance.options.type === 'plugin') {
5✔
2252
            instance._setupUI(`cms-plugin-${instance.options.plugin_id}`);
2✔
2253
            instance._ensureData();
2✔
2254
            instance.ui.container.data('cms').push(instance.options);
2✔
2255
            instance._setPluginContentEvents();
2✔
2256
        }
2257
    });
2258

2259
    CMS._plugins.forEach(([type, opts]) => {
4✔
2260
        if (opts.type !== 'placeholder' && opts.type !== 'plugin') {
16✔
2261
            const instance = find(
8✔
2262
                CMS._instances,
2263
                i => i.options.type === opts.type && Number(i.options.plugin_id) === Number(opts.plugin_id)
13✔
2264
            );
2265

2266
            if (instance) {
8✔
2267
                // update
2268
                instance._setupUI(type);
1✔
2269
                instance._ensureData();
1✔
2270
                instance.ui.container.data('cms').push(instance.options);
1✔
2271
                instance._setGeneric();
1✔
2272
            } else {
2273
                // create
2274
                CMS._instances.push(new Plugin(type, opts));
7✔
2275
            }
2276
        }
2277
    });
2278
};
2279

2280
Plugin._getPluginById = function(id) {
1✔
2281
    return find(CMS._instances, ({ options }) => options.type === 'plugin' && Number(options.plugin_id) === Number(id));
20!
2282
};
2283

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

2289
    plugins.forEach((element, index) => {
10✔
2290
        const pluginId = CMS.API.StructureBoard.getId($(element));
20✔
2291
        const instance = Plugin._getPluginById(pluginId);
20✔
2292

2293
        if (!instance) {
20!
2294
            return;
20✔
2295
        }
2296

UNCOV
2297
        instance.options.position = index + 1;
×
2298
    });
2299
};
2300

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

2313
// shorthand for jQuery(document).ready();
2314
$(Plugin._initializeGlobalHandlers);
1✔
2315

2316
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