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

divio / django-cms / #29287

10 Jan 2025 08:55PM UTC coverage: 76.168% (-1.4%) from 77.576%
#29287

push

travis-ci

web-flow
Merge 16bd3c1ee into ec268c7b2

1053 of 1568 branches covered (67.16%)

16 of 28 new or added lines in 2 files covered. (57.14%)

405 existing lines in 6 files now uncovered.

2528 of 3319 relevant lines covered (76.17%)

26.8 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

111
    /**
112
     * Caches some jQuery references and sets up structure for
113
     * further initialisation.
114
     *
115
     * @method _setupUI
116
     * @private
117
     * @param {String} container `cms-plugin-${id}`
118
     */
119
    _setupUI: function setupUI(container) {
120
        var wrapper = $(`.${container}`);
179✔
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/)) {
179✔
126
            // so it's possible that multiple plugins (more often generics) are rendered
127
            // in different places. e.g. page menu in the header and in the footer
128
            // so first, we find all the template tags, then put them in a structure like this:
129
            // [[start, end], [start, end]...]
130
            //
131
            // in case of plugins it means that it's aliased plugin or a plugin in a duplicated
132
            // static placeholder (for whatever reason)
133
            var contentWrappers = wrapper.toArray().reduce((wrappers, elem, index) => {
136✔
134
                if (index === 0) {
274✔
135
                    wrappers[0].push(elem);
136✔
136
                    return wrappers;
136✔
137
                }
138

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

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

148
                return wrappers;
138✔
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
136✔
154
                .map(items => {
155
                    var templateStart = $(items[0]);
137✔
156
                    var className = templateStart.attr('class').replace('cms-plugin-start', '');
137✔
157

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

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

162
                    itemContents.each((index, el) => {
137✔
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*$/)) {
158✔
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() {
137✔
174
                        return this.nodeType !== Node.TEXT_NODE && this.nodeType !== Node.COMMENT_NODE;
158✔
175
                    });
176

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

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

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

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

196
        this.ui = this.ui || {};
179✔
197
        this.ui.container = contents;
179✔
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()) {
130!
248
            this._setPluginStructureEvents();
130✔
249
        }
250
        if (isContentReady()) {
130!
251
            this._setPluginContentEvents();
130✔
252
        }
253
    },
254

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

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

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

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

268
        // adds listener for all plugin updates
269
        this.ui.draggable.off('cms-plugins-update').on('cms-plugins-update', function(e, eventData) {
130✔
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) {
130✔
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(() => {
130✔
302
            this.ui.dragitem
130✔
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);
130✔
330

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

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

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

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

UNCOV
346
        if (!disabled.length) {
×
UNCOV
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);
130✔
357

358
        this.ui.container
130✔
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();
×
UNCOV
368
                $('.cms-dragitem-success').remove();
×
UNCOV
369
                $('.cms-draggable-success').removeClass('cms-draggable-success');
×
UNCOV
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();
×
UNCOV
378
                if (this.ui.draggable && this.ui.draggable.length) {
×
UNCOV
379
                    this.ui.draggable.find('.cms-dragitem-success').remove();
×
UNCOV
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)) {
130✔
386
            $document
129✔
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✔
UNCOV
408
            e.preventDefault();
×
UNCOV
409
            e.stopPropagation();
×
UNCOV
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;
×
UNCOV
421
                var id = that.options.plugin_id;
×
422

UNCOV
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]');
151✔
440
        var pasteItem = pasteButton.parent();
151✔
441

442
        if (!clipboardDraggable.length) {
151✔
443
            pasteItem.addClass('cms-submenu-item-disabled');
86✔
444
            pasteItem.find('a').attr('tabindex', '-1').attr('aria-disabled', 'true');
86✔
445
            pasteItem.find('.cms-submenu-item-paste-tooltip-empty').css('display', 'block');
86✔
446
            return false;
86✔
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 {
UNCOV
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 {Boolean} showAddForm if false, will NOT show the add form
494
     * @param {Number} position (optional) position of the plugin
495
     */
496
    // eslint-disable-next-line max-params
497
    addPlugin: function(type, name, parent, showAddForm = true, position) {
2✔
498
        var params = {
4✔
499
            placeholder_id: this.options.placeholder_id,
500
            plugin_type: type,
501
            cms_path: path,
502
            plugin_language: CMS.config.request.language,
503
            plugin_position: position || this._getPluginAddPosition()
8✔
504
        };
505

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

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

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

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

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

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

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

559
        if (maybeChildren.length) {
×
UNCOV
560
            const lastChild = maybeChildren.last();
×
561

UNCOV
562
            const lastChildInstance = Plugin._getPluginById(this._getId(lastChild));
×
563

564
            return lastChildInstance.options.position + 1;
×
565
        }
566

UNCOV
567
        return this.options.position + 1;
×
568
    },
569

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

586
        this.modal = modal;
3✔
587

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

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

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

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

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

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

674
        $.ajax(request);
8✔
675
    },
676

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

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

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

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

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

739
        const clipboardDraggableClone = clipboardDraggable.clone(true, true);
5✔
740

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

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

768
        // set correct options
769
        var options = opts || this.options;
11✔
770

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

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

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

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

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

UNCOV
797
            Plugin._updatePluginPositions(placeholder_id);
×
UNCOV
798
            Plugin._updatePluginPositions(options.placeholder_id);
×
799
        }
800

801
        var position = this.options.position;
10✔
802

803
        data.target_position = position;
10✔
804

805
        showLoader();
10✔
806

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

817
                // enable actions again
818
                CMS.API.locked = false;
4✔
819
                hideLoader();
4✔
820
            },
821
            error: function(jqXHR) {
822
                CMS.API.locked = false;
4✔
823
                var msg = CMS.config.lang.error;
4✔
824

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

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

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

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

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

880
        this.modal = modal;
2✔
881

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

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

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

913
        if (mustCleanup) {
2✔
914
            this.cleanup();
1✔
915
        }
916

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1114
            plugins = nav.siblings('.cms-plugin-picker');
×
1115

UNCOV
1116
            that._setupQuickSearch(plugins);
×
1117
        });
1118

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

UNCOV
1131
                Plugin._hideSettingsMenu();
×
1132

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

NEW
1136
                if (selectionNeeded) {
×
NEW
1137
                    initModal();
×
1138

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

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

NEW
1162
                    that.addPlugin(pluginType, el.text(), parentId, showAddForm);
×
1163
                }
1164
            });
1165

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

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

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

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

1189
        let ref = plugins.find('.cms-quicksearch');
×
1190

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

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

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

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

UNCOV
1214
        return plugins;
×
1215
    },
1216

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

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

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

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

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

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

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

1276
        return resultElements;
33✔
1277
    },
1278

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

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

1297
            that._filterPluginsList(pluginsPicker, input);
×
1298
        }, FILTER_DEBOUNCE_TIMER);
1299

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

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

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

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

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

1355
        var nav;
1356
        var that = this;
13✔
1357

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

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

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

1368
        Plugin._hideSettingsMenu(nav);
13✔
1369

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

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

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

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

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

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

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

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

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

1494
        // set visible states
1495
        dropdown.show();
×
1496

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

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

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

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

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

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

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

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

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

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

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

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

1565
        mostRecentItems.hide();
4✔
1566
    },
1567

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

UNCOV
1582
        var settings = CMS.settings;
×
1583

1584
        settings.states = settings.states || [];
×
1585

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

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

1599
            if ($document.data('expandmode')) {
×
UNCOV
1600
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
1601
                if (!items.length) {
×
1602
                    return false;
×
1603
                }
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
        } else {
UNCOV
1613
            settings.states.push(id);
×
UNCOV
1614
            el
×
1615
                .addClass('cms-dragitem-expanded')
1616
                .parent()
1617
                .find('> .cms-collapsable-container')
1618
                .removeClass('cms-hidden');
1619

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

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

1635
        this._updatePlaceholderCollapseState();
×
1636

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

1640
        // save settings
UNCOV
1641
        Helpers.setSettings(settings);
×
1642
    },
1643

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1743
        el.addClass('cms-dragbar-title-expanded');
×
1744

1745
        var settings = CMS.settings;
×
1746

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

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

1763
        items.each(function() {
×
1764
            var item = $(this);
×
1765

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

UNCOV
1771
        el.removeClass('cms-dragbar-title-expanded');
×
1772

1773
        var settings = CMS.settings;
×
1774

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

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

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

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

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

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

1825
        var id = this.options.plugin_parent;
6✔
1826
        var data;
1827

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

1831
            if (!data) {
6✔
1832
                break;
1✔
1833
            }
1834

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

1842
        return breadcrumbs;
6✔
1843
    }
1844
});
1845

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

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

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

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

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

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

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

1907
    // reset relativity
UNCOV
1908
    $('.cms-dragbar').css('position', '');
×
1909
};
1910

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

1925
    Plugin._updateClipboard();
6✔
1926

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

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

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

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

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

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

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

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

2012
        const options = allOptions[0];
×
2013

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

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

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

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

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

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

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

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

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

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

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

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

2076
    return false;
129✔
2077
};
2078

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

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

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

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

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

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

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

2165
    if (positions.length === 0) {
1!
UNCOV
2166
        return;
×
2167
    }
2168

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

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

2179
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2180

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

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

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

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

2224
Plugin.aliasPluginDuplicatesMap = {};
1✔
2225
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2226

2227
// istanbul ignore next
2228
Plugin._initializeTree = function _initializeTree() {
2229
    CMS._plugins = uniqWith(CMS._plugins, ([x], [y]) => x === y);
2230
    CMS._instances = CMS._plugins.map(function(args) {
2231
        return new CMS.Plugin(args[0], args[1]);
2232
    });
2233

2234
    // return the cms plugin instances just created
2235
    return CMS._instances;
2236
};
2237

2238
Plugin._updateClipboard = function _updateClipboard() {
1✔
2239
    clipboardDraggable = $('.cms-draggable-from-clipboard:first');
7✔
2240
};
2241

2242
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2243
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2244

2245
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2246

2247
    if (Helpers._isStorageSupported) {
2!
UNCOV
2248
        localStorage.setItem('cms-plugin-usage', JSON.stringify(pluginUsageMap));
×
2249
    }
2250
};
2251

2252
Plugin._removeAddPluginPlaceholder = function removeAddPluginPlaceholder() {
1✔
2253
    // this can't be cached since they are created and destroyed all over the place
2254
    $('.cms-add-plugin-placeholder').remove();
10✔
2255
};
2256

2257
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2258
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2259
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2260
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2261

2262
    CMS._instances.forEach(instance => {
4✔
2263
        if (instance.options.type === 'placeholder') {
5✔
2264
            instance._setupUI(`cms-placeholder-${instance.options.placeholder_id}`);
2✔
2265
            instance._ensureData();
2✔
2266
            instance.ui.container.data('cms', instance.options);
2✔
2267
            instance._setPlaceholder();
2✔
2268
        }
2269
    });
2270

2271
    CMS._instances.forEach(instance => {
4✔
2272
        if (instance.options.type === 'plugin') {
5✔
2273
            instance._setupUI(`cms-plugin-${instance.options.plugin_id}`);
2✔
2274
            instance._ensureData();
2✔
2275
            instance.ui.container.data('cms').push(instance.options);
2✔
2276
            instance._setPluginContentEvents();
2✔
2277
        }
2278
    });
2279

2280
    CMS._plugins.forEach(([type, opts]) => {
4✔
2281
        if (opts.type !== 'placeholder' && opts.type !== 'plugin') {
16✔
2282
            const instance = find(
8✔
2283
                CMS._instances,
2284
                i => i.options.type === opts.type && Number(i.options.plugin_id) === Number(opts.plugin_id)
13✔
2285
            );
2286

2287
            if (instance) {
8✔
2288
                // update
2289
                instance._setupUI(type);
1✔
2290
                instance._ensureData();
1✔
2291
                instance.ui.container.data('cms').push(instance.options);
1✔
2292
                instance._setGeneric();
1✔
2293
            } else {
2294
                // create
2295
                CMS._instances.push(new Plugin(type, opts));
7✔
2296
            }
2297
        }
2298
    });
2299
};
2300

2301
Plugin._getPluginById = function(id) {
1✔
2302
    return find(CMS._instances, ({ options }) => options.type === 'plugin' && Number(options.plugin_id) === Number(id));
20!
2303
};
2304

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

2310
    plugins.forEach((element, index) => {
10✔
2311
        const pluginId = CMS.API.StructureBoard.getId($(element));
20✔
2312
        const instance = Plugin._getPluginById(pluginId);
20✔
2313

2314
        if (!instance) {
20!
2315
            return;
20✔
2316
        }
2317

UNCOV
2318
        instance.options.position = index + 1;
×
2319
    });
2320
};
2321

2322
Plugin._recalculatePluginPositions = function(action, data) {
1✔
2323
    if (action === 'MOVE') {
×
2324
        // le sigh - recalculate all placeholders cause we don't know from where the
2325
        // plugin was moved from
2326
        filter(CMS._instances, ({ options }) => options.type === 'placeholder')
×
2327
            .map(({ options }) => options.placeholder_id)
×
UNCOV
2328
            .forEach(placeholder_id => Plugin._updatePluginPositions(placeholder_id));
×
UNCOV
2329
    } else if (data.placeholder_id) {
×
UNCOV
2330
        Plugin._updatePluginPositions(data.placeholder_id);
×
2331
    }
2332
};
2333

2334
// shorthand for jQuery(document).ready();
2335
$(Plugin._initializeGlobalHandlers);
1✔
2336

2337
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