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

divio / django-cms / #27529

pending completion
#27529

push

travis-ci

web-flow
Merge 8238619f8 into 1c208a8cb

1046 of 1539 branches covered (67.97%)

29 of 29 new or added lines in 2 files covered. (100.0%)

2525 of 3281 relevant lines covered (76.96%)

32.87 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

111
    /**
112
     * Caches some jQuery references and sets up structure for
113
     * further initialisation.
114
     *
115
     * @method _setupUI
116
     * @private
117
     * @param {String} container `cms-plugin-${id}`
118
     */
119
    _setupUI: function setupUI(container) {
120
        var wrapper = $(`.${container}`);
178✔
121
        var contents;
122

123
        // have to check for cms-plugin, there can be a case when there are multiple
124
        // static placeholders or plugins rendered twice, there could be multiple wrappers on same page
125
        if (wrapper.length > 1 && container.match(/cms-plugin/)) {
178✔
126
            // so it's possible that multiple plugins (more often generics) are rendered
127
            // in different places. e.g. page menu in the header and in the footer
128
            // so first, we find all the template tags, then put them in a structure like this:
129
            // [[start, end], [start, end]...]
130
            //
131
            // in case of plugins it means that it's aliased plugin or a plugin in a duplicated
132
            // static placeholder (for whatever reason)
133
            var contentWrappers = wrapper.toArray().reduce((wrappers, elem, index) => {
135✔
134
                if (index === 0) {
272✔
135
                    wrappers[0].push(elem);
135✔
136
                    return wrappers;
135✔
137
                }
138

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

339
    _dblClickToEditHandler: function _dblClickToEditHandler(e) {
340
        var that = this;
×
341

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

345
        that.editPlugin(
×
346
            Helpers.updateUrlWithPath(that.options.urls.edit_plugin),
347
            that.options.plugin_name,
348
            that._getPluginBreadcrumbs()
349
        );
350
    },
351

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

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

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

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

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

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

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

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

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

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

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

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

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

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

480
        return true;
5✔
481
    },
482

483
    /**
484
     * Calls api to create a plugin and then proceeds to edit it.
485
     *
486
     * @method addPlugin
487
     * @param {String} type type of the plugin, e.g "Bootstrap3ColumnCMSPlugin"
488
     * @param {String} name name of the plugin, e.g. "Column"
489
     * @param {String} parent id of a parent plugin
490
     */
491
    addPlugin: function(type, name, parent) {
492
        var params = {
3✔
493
            placeholder_id: this.options.placeholder_id,
494
            plugin_type: type,
495
            cms_path: path,
496
            plugin_language: CMS.config.request.language,
497
            plugin_position: this._getPluginAddPosition()
498
        };
499

500
        if (parent) {
3✔
501
            params.plugin_parent = parent;
1✔
502
        }
503
        var url = this.options.urls.add_plugin + '?' + $.param(params);
3✔
504
        var modal = new Modal({
3✔
505
            onClose: this.options.onClose || false,
5✔
506
            redirectOnClose: this.options.redirectOnClose || false
5✔
507
        });
508

509
        modal.open({
3✔
510
            url: url,
511
            title: name
512
        });
513

514
        this.modal = modal;
3✔
515

516
        Helpers.removeEventListener('modal-closed.add-plugin');
3✔
517
        Helpers.addEventListener('modal-closed.add-plugin', (e, { instance }) => {
3✔
518
            if (instance !== modal) {
1!
519
                return;
×
520
            }
521
            Plugin._removeAddPluginPlaceholder();
1✔
522
        });
523
    },
524

525
    _getPluginAddPosition: function() {
526
        if (this.options.type === 'placeholder') {
×
527
            return $(`.cms-dragarea-${this.options.placeholder_id} .cms-draggable`).length + 1;
×
528
        }
529

530
        // assume plugin now
531
        // would prefer to get the information from the tree, but the problem is that the flat data
532
        // isn't sorted by position
533
        const maybeChildren = this.ui.draggable.find('.cms-draggable');
×
534

535
        if (maybeChildren.length) {
×
536
            const lastChild = maybeChildren.last();
×
537

538
            const lastChildInstance = Plugin._getPluginById(this._getId(lastChild));
×
539

540
            return lastChildInstance.options.position + 1;
×
541
        }
542

543
        return this.options.position + 1;
×
544
    },
545

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

562
        this.modal = modal;
3✔
563

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

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

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

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

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

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

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

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

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

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

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

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

715
        const clipboardDraggableClone = clipboardDraggable.clone(true, true);
5✔
716

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

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

744
        // set correct options
745
        var options = opts || this.options;
11✔
746

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

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

752
        // cancel here if we have no placeholder id
753
        if (placeholder_id === false) {
11✔
754
            return false;
1✔
755
        }
756
        var pluginParentElement = dragitem.parent().closest('.cms-draggable');
10✔
757
        var plugin_parent = this._getId(pluginParentElement);
10✔
758

759
        // gather the data for ajax request
760
        var data = {
10✔
761
            plugin_id: options.plugin_id,
762
            plugin_parent: plugin_parent || '',
20✔
763
            target_language: CMS.config.request.language,
764
            csrfmiddlewaretoken: CMS.config.csrf,
765
            move_a_copy: options.move_a_copy
766
        };
767

768
        if (Number(placeholder_id) === Number(options.placeholder_id)) {
10!
769
            Plugin._updatePluginPositions(options.placeholder_id);
10✔
770
        } else {
771
            data.placeholder_id = placeholder_id;
×
772

773
            Plugin._updatePluginPositions(placeholder_id);
×
774
            Plugin._updatePluginPositions(options.placeholder_id);
×
775
        }
776

777
        var position = this.options.position;
10✔
778

779
        data.target_position = position;
10✔
780

781
        showLoader();
10✔
782

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

793
                // enable actions again
794
                CMS.API.locked = false;
4✔
795
                hideLoader();
4✔
796
            },
797
            error: function(jqXHR) {
798
                CMS.API.locked = false;
4✔
799
                var msg = CMS.config.lang.error;
4✔
800

801
                // trigger error
802
                CMS.API.Messages.open({
4✔
803
                    message: msg + jqXHR.responseText || jqXHR.status + ' ' + jqXHR.statusText,
5✔
804
                    error: true
805
                });
806
                hideLoader();
4✔
807
            }
808
        });
809
    },
810

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

824
        // set new setting on instance and plugin data
825
        this.options = settings;
×
826
        if (plugin.length) {
×
827
            var index = plugin.data('cms').findIndex(function(pluginData) {
×
828
                return pluginData.plugin_id === settings.plugin_id;
×
829
            });
830

831
            plugin.each(function() {
×
832
                $(this).data('cms')[index] = settings;
×
833
            });
834
        }
835
        if (draggable.length) {
×
836
            draggable.data('cms', settings);
×
837
        }
838
    },
839

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

856
        this.modal = modal;
2✔
857

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

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

882
        // close the plugin modal if it was open
883
        if (this.modal) {
2!
884
            this.modal.close();
×
885
            // unsubscribe to all the modal events
886
            this.modal.off();
×
887
        }
888

889
        if (mustCleanup) {
2✔
890
            this.cleanup();
1✔
891
        }
892

893
        // remove event bound to global elements like document or window
894
        $document.off(`.${this.uid}`);
2✔
895
        $window.off(`.${this.uid}`);
2✔
896
    },
897

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

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

922
    /**
923
     * _setSettingsMenu sets up event handlers for settings menu.
924
     *
925
     * @method _setSettingsMenu
926
     * @private
927
     * @param {jQuery} nav
928
     */
929
    _setSettingsMenu: function _setSettingsMenu(nav) {
930
        var that = this;
152✔
931

932
        this.ui.dropdown = nav.siblings('.cms-submenu-dropdown-settings');
152✔
933
        var dropdown = this.ui.dropdown;
152✔
934

935
        nav
152✔
936
            .off(Plugin.pointerUp)
937
            .on(Plugin.pointerUp, function(e) {
938
                e.preventDefault();
×
939
                e.stopPropagation();
×
940
                var trigger = $(this);
×
941

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

957
        dropdown
152✔
958
            .off(Plugin.mouseEvents)
959
            .on(Plugin.mouseEvents, function(e) {
960
                e.stopPropagation();
×
961
            })
962
            .off(Plugin.touchStart)
963
            .on(Plugin.touchStart, function(e) {
964
                // required for scrolling on mobile
965
                e.stopPropagation();
×
966
            });
967

968
        that._setupActions(nav);
152✔
969
        // prevent propagation
970
        nav
152✔
971
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '))
972
            .on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
973
                e.stopPropagation();
×
974
            });
975

976
        nav
152✔
977
            .siblings('.cms-quicksearch, .cms-submenu-dropdown-settings')
978
            .off([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '))
979
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
980
                e.stopPropagation();
×
981
            });
982
    },
983

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

1007
        if (!isInViewport) {
3✔
1008
            scrollable.animate(
2✔
1009
                {
1010
                    scrollTop: elPosition + offset + elHeight + scrollTop - scrollHeight
1011
                },
1012
                duration
1013
            );
1014
        }
1015
    },
1016

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

1035
        var initModal = once(function initModal() {
65✔
1036
            var placeholder = $(
×
1037
                '<div class="cms-add-plugin-placeholder">' + CMS.config.lang.addPluginPlaceholder + '</div>'
1038
            );
1039
            var dragItem = nav.closest('.cms-dragitem');
×
1040
            var isPlaceholder = !dragItem.length;
×
1041
            var childrenList;
1042

1043
            modal = new Modal({
×
1044
                minWidth: 400,
1045
                minHeight: 400
1046
            });
1047

1048
            if (isPlaceholder) {
×
1049
                childrenList = nav.closest('.cms-dragarea').find('> .cms-draggables');
×
1050
            } else {
1051
                childrenList = nav.closest('.cms-draggable').find('> .cms-draggables');
×
1052
            }
1053

1054
            Helpers.addEventListener('modal-loaded', (e, { instance }) => {
×
1055
                if (instance !== modal) {
×
1056
                    return;
×
1057
                }
1058

1059
                that._setupKeyboardTraversing();
×
1060
                if (childrenList.hasClass('cms-hidden') && !isPlaceholder) {
×
1061
                    that._toggleCollapsable(dragItem);
×
1062
                }
1063
                Plugin._removeAddPluginPlaceholder();
×
1064
                placeholder.appendTo(childrenList);
×
1065
                that._scrollToElement(placeholder);
×
1066
            });
1067

1068
            Helpers.addEventListener('modal-closed', (e, { instance }) => {
×
1069
                if (instance !== modal) {
×
1070
                    return;
×
1071
                }
1072
                Plugin._removeAddPluginPlaceholder();
×
1073
            });
1074

1075
            Helpers.addEventListener('modal-shown', (e, { instance }) => {
×
1076
                if (modal !== instance) {
×
1077
                    return;
×
1078
                }
1079
                var dropdown = $('.cms-modal-markup .cms-plugin-picker');
×
1080

1081
                if (!isTouching) {
×
1082
                    // only focus the field if using mouse
1083
                    // otherwise keyboard pops up
1084
                    dropdown.find('input').trigger('focus');
×
1085
                }
1086
                isTouching = false;
×
1087
            });
1088

1089
            plugins = nav.siblings('.cms-plugin-picker');
×
1090

1091
            that._setupQuickSearch(plugins);
×
1092
        });
1093

1094
        nav
65✔
1095
            .on(Plugin.touchStart, function(e) {
1096
                isTouching = true;
×
1097
                // required on some touch devices so
1098
                // ui touch punch is not triggering mousemove
1099
                // which in turn results in pep triggering pointercancel
1100
                e.stopPropagation();
×
1101
            })
1102
            .on(Plugin.pointerUp, function(e) {
1103
                e.preventDefault();
×
1104
                e.stopPropagation();
×
1105

1106
                Plugin._hideSettingsMenu();
×
1107

1108
                initModal();
×
1109

1110
                // since we don't know exact plugin parent (because dragndrop)
1111
                // we need to know the parent id by the time we open "add plugin" dialog
1112
                var pluginsCopy = that._updateWithMostUsedPlugins(
×
1113
                    plugins
1114
                        .clone(true, true)
1115
                        .data('parentId', that._getId(nav.closest('.cms-draggable')))
1116
                        .append(that._getPossibleChildClasses())
1117
                );
1118

1119
                modal.open({
×
1120
                    title: that.options.addPluginHelpTitle,
1121
                    html: pluginsCopy,
1122
                    width: 530,
1123
                    height: 400
1124
                });
1125
            });
1126

1127
        // prevent propagation
1128
        nav.on([Plugin.pointerUp, Plugin.pointerDown, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
65✔
1129
            e.stopPropagation();
×
1130
        });
1131

1132
        nav
65✔
1133
            .siblings('.cms-quicksearch, .cms-submenu-dropdown')
1134
            .on([Plugin.pointerUp, Plugin.click, Plugin.doubleClick].join(' '), function(e) {
1135
                e.stopPropagation();
×
1136
            });
1137
    },
1138

1139
    _updateWithMostUsedPlugins: function _updateWithMostUsedPlugins(plugins) {
1140
        const items = plugins.find('.cms-submenu-item');
×
1141
        // eslint-disable-next-line no-unused-vars
1142
        const mostUsedPlugins = toPairs(pluginUsageMap).sort(([x, a], [y, b]) => a - b).reverse();
×
1143
        const MAX_MOST_USED_PLUGINS = 5;
×
1144
        let count = 0;
×
1145

1146
        if (items.filter(':not(.cms-submenu-item-title)').length <= MAX_MOST_USED_PLUGINS) {
×
1147
            return plugins;
×
1148
        }
1149

1150
        let ref = plugins.find('.cms-quicksearch');
×
1151

1152
        mostUsedPlugins.forEach(([name]) => {
×
1153
            if (count === MAX_MOST_USED_PLUGINS) {
×
1154
                return;
×
1155
            }
1156
            const item = items.find(`[href=${name}]`);
×
1157

1158
            if (item.length) {
×
1159
                const clone = item.closest('.cms-submenu-item').clone(true, true);
×
1160

1161
                ref.after(clone);
×
1162
                ref = clone;
×
1163
                count += 1;
×
1164
            }
1165
        });
1166

1167
        if (count) {
×
1168
            plugins.find('.cms-quicksearch').after(
×
1169
                $(`<div class="cms-submenu-item cms-submenu-item-title" data-cms-most-used>
1170
                    <span>${CMS.config.lang.mostUsed}</span>
1171
                </div>`)
1172
            );
1173
        }
1174

1175
        return plugins;
×
1176
    },
1177

1178
    /**
1179
     * Returns a specific plugin namespaced event postfixing the plugin uid to it
1180
     * in order to properly manage it via jQuery $.on and $.off
1181
     *
1182
     * @method _getNamepacedEvent
1183
     * @private
1184
     * @param {String} base - plugin event type
1185
     * @param {String} additionalNS - additional namespace (like '.traverse' for example)
1186
     * @returns {String} a specific plugin event
1187
     *
1188
     * @example
1189
     *
1190
     * plugin._getNamepacedEvent(Plugin.click); // 'click.cms.plugin.42'
1191
     * plugin._getNamepacedEvent(Plugin.keyDown, '.traverse'); // 'keydown.cms.plugin.traverse.42'
1192
     */
1193
    _getNamepacedEvent(base, additionalNS = '') {
132✔
1194
        return `${base}${additionalNS ? '.'.concat(additionalNS) : ''}.${this.uid}`;
143✔
1195
    },
1196

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

1213
        if (childRestrictions && childRestrictions.length) {
33✔
1214
            resultElements = resultElements.filter(function() {
29✔
1215
                var item = $(this);
4,727✔
1216

1217
                return (
4,727✔
1218
                    item.hasClass('cms-submenu-item-title') ||
9,106✔
1219
                    childRestrictions.indexOf(item.find('a').attr('href')) !== -1
1220
                );
1221
            });
1222

1223
            resultElements = resultElements.filter(function(index) {
29✔
1224
                var item = $(this);
411✔
1225

1226
                return (
411✔
1227
                    !item.hasClass('cms-submenu-item-title') ||
1,182✔
1228
                    (item.hasClass('cms-submenu-item-title') &&
1229
                        (!resultElements.eq(index + 1).hasClass('cms-submenu-item-title') &&
1230
                            resultElements.eq(index + 1).length))
1231
                );
1232
            });
1233
        }
1234

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

1237
        return resultElements;
33✔
1238
    },
1239

1240
    /**
1241
     * Sets up event handlers for quicksearching in the plugin picker.
1242
     *
1243
     * @method _setupQuickSearch
1244
     * @private
1245
     * @param {jQuery} plugins plugins picker element
1246
     */
1247
    _setupQuickSearch: function _setupQuickSearch(plugins) {
1248
        var that = this;
×
1249
        var FILTER_DEBOUNCE_TIMER = 100;
×
1250
        var FILTER_PICK_DEBOUNCE_TIMER = 110;
×
1251

1252
        var handler = debounce(function() {
×
1253
            var input = $(this);
×
1254
            // have to always find the pluginsPicker in the handler
1255
            // because of how we move things into/out of the modal
1256
            var pluginsPicker = input.closest('.cms-plugin-picker');
×
1257

1258
            that._filterPluginsList(pluginsPicker, input);
×
1259
        }, FILTER_DEBOUNCE_TIMER);
1260

1261
        plugins.find('> .cms-quicksearch').find('input').on(Plugin.keyUp, handler).on(
×
1262
            Plugin.keyUp,
1263
            debounce(function(e) {
1264
                var input;
1265
                var pluginsPicker;
1266

1267
                if (e.keyCode === KEYS.ENTER) {
×
1268
                    input = $(this);
×
1269
                    pluginsPicker = input.closest('.cms-plugin-picker');
×
1270
                    pluginsPicker
×
1271
                        .find('.cms-submenu-item')
1272
                        .not('.cms-submenu-item-title')
1273
                        .filter(':visible')
1274
                        .first()
1275
                        .find('> a')
1276
                        .focus()
1277
                        .trigger('click');
1278
                }
1279
            }, FILTER_PICK_DEBOUNCE_TIMER)
1280
        );
1281
    },
1282

1283
    /**
1284
     * Sets up click handlers for various plugin/placeholder items.
1285
     * Items can be anywhere in the plugin dragitem, not only in dropdown.
1286
     *
1287
     * @method _setupActions
1288
     * @private
1289
     * @param {jQuery} nav dropdown trigger with the items
1290
     */
1291
    _setupActions: function _setupActions(nav) {
1292
        var items = '.cms-submenu-edit, .cms-submenu-item a';
162✔
1293
        var parent = nav.parent();
162✔
1294

1295
        parent.find('.cms-submenu-edit').off(Plugin.touchStart).on(Plugin.touchStart, function(e) {
162✔
1296
            // required on some touch devices so
1297
            // ui touch punch is not triggering mousemove
1298
            // which in turn results in pep triggering pointercancel
1299
            e.stopPropagation();
1✔
1300
        });
1301
        parent.find(items).off(Plugin.click).on(Plugin.click, nav, e => this._delegate(e));
162✔
1302
    },
1303

1304
    /**
1305
     * Handler for the "action" items
1306
     *
1307
     * @method _delegate
1308
     * @param {$.Event} e event
1309
     * @private
1310
     */
1311
    // eslint-disable-next-line complexity
1312
    _delegate: function _delegate(e) {
1313
        e.preventDefault();
13✔
1314
        e.stopPropagation();
13✔
1315

1316
        var nav;
1317
        var that = this;
13✔
1318

1319
        if (e.data && e.data.nav) {
13!
1320
            nav = e.data.nav;
×
1321
        }
1322

1323
        // show loader and make sure scroll doesn't jump
1324
        showLoader();
13✔
1325

1326
        var items = '.cms-submenu-edit, .cms-submenu-item a';
13✔
1327
        var el = $(e.target).closest(items);
13✔
1328

1329
        Plugin._hideSettingsMenu(nav);
13✔
1330

1331
        // set switch for subnav entries
1332
        switch (el.attr('data-rel')) {
13!
1333
            // eslint-disable-next-line no-case-declarations
1334
            case 'add':
1335
                const pluginType = el.attr('href').replace('#', '');
2✔
1336

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

1395
    /**
1396
     * Sets up keyboard traversing of plugin picker.
1397
     *
1398
     * @method _setupKeyboardTraversing
1399
     * @private
1400
     */
1401
    _setupKeyboardTraversing: function _setupKeyboardTraversing() {
1402
        var dropdown = $('.cms-modal-markup .cms-plugin-picker');
3✔
1403
        const keyDownTraverseEvent = this._getNamepacedEvent(Plugin.keyDown, 'traverse');
3✔
1404

1405
        if (!dropdown.length) {
3✔
1406
            return;
1✔
1407
        }
1408
        // add key events
1409
        $document.off(keyDownTraverseEvent);
2✔
1410
        // istanbul ignore next: not really possible to reproduce focus state in unit tests
1411
        $document.on(keyDownTraverseEvent, function(e) {
1412
            var anchors = dropdown.find('.cms-submenu-item:visible a');
1413
            var index = anchors.index(anchors.filter(':focus'));
1414

1415
            // bind arrow down and tab keys
1416
            if (e.keyCode === KEYS.DOWN || (e.keyCode === KEYS.TAB && !e.shiftKey)) {
1417
                e.preventDefault();
1418
                if (index >= 0 && index < anchors.length - 1) {
1419
                    anchors.eq(index + 1).focus();
1420
                } else {
1421
                    anchors.eq(0).focus();
1422
                }
1423
            }
1424

1425
            // bind arrow up and shift+tab keys
1426
            if (e.keyCode === KEYS.UP || (e.keyCode === KEYS.TAB && e.shiftKey)) {
1427
                e.preventDefault();
1428
                if (anchors.is(':focus')) {
1429
                    anchors.eq(index - 1).focus();
1430
                } else {
1431
                    anchors.eq(anchors.length).focus();
1432
                }
1433
            }
1434
        });
1435
    },
1436

1437
    /**
1438
     * Opens the settings menu for a plugin.
1439
     *
1440
     * @method _showSettingsMenu
1441
     * @private
1442
     * @param {jQuery} nav trigger element
1443
     */
1444
    _showSettingsMenu: function(nav) {
1445
        this._checkIfPasteAllowed();
×
1446

1447
        var dropdown = this.ui.dropdown;
×
1448
        var parents = nav.parentsUntil('.cms-dragarea').last();
×
1449
        var MIN_SCREEN_MARGIN = 10;
×
1450

1451
        nav.addClass('cms-btn-active');
×
1452
        parents.addClass('cms-z-index-9999');
×
1453

1454
        // set visible states
1455
        dropdown.show();
×
1456

1457
        // calculate dropdown positioning
1458
        if (
×
1459
            $window.height() + $window.scrollTop() - nav.offset().top - dropdown.height() <= MIN_SCREEN_MARGIN &&
×
1460
            nav.offset().top - dropdown.height() >= 0
1461
        ) {
1462
            dropdown.removeClass('cms-submenu-dropdown-top').addClass('cms-submenu-dropdown-bottom');
×
1463
        } else {
1464
            dropdown.removeClass('cms-submenu-dropdown-bottom').addClass('cms-submenu-dropdown-top');
×
1465
        }
1466
    },
1467

1468
    /**
1469
     * Filters given plugins list by a query.
1470
     *
1471
     * @method _filterPluginsList
1472
     * @private
1473
     * @param {jQuery} list plugins picker element
1474
     * @param {jQuery} input input, which value to filter plugins with
1475
     * @returns {Boolean|void}
1476
     */
1477
    _filterPluginsList: function _filterPluginsList(list, input) {
1478
        var items = list.find('.cms-submenu-item');
5✔
1479
        var titles = list.find('.cms-submenu-item-title');
5✔
1480
        var query = input.val();
5✔
1481

1482
        // cancel if query is zero
1483
        if (query === '') {
5✔
1484
            items.add(titles).show();
1✔
1485
            return false;
1✔
1486
        }
1487

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

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

1492
        var itemsToFilter = items.toArray().map(function(el) {
4✔
1493
            var element = $(el);
72✔
1494

1495
            return {
72✔
1496
                value: element.text(),
1497
                element: element
1498
            };
1499
        });
1500

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

1503
        items.hide();
4✔
1504
        filteredItems.forEach(function(item) {
4✔
1505
            item.element.show();
3✔
1506
        });
1507

1508
        // check if a title is matching
1509
        titles.filter(':visible').each(function(index, item) {
4✔
1510
            titles.hide();
1✔
1511
            $(item).nextUntil('.cms-submenu-item-title').show();
1✔
1512
        });
1513

1514
        // always display title of a category
1515
        items.filter(':visible').each(function(index, titleItem) {
4✔
1516
            var item = $(titleItem);
16✔
1517

1518
            if (item.prev().hasClass('cms-submenu-item-title')) {
16✔
1519
                item.prev().show();
2✔
1520
            } else {
1521
                item.prevUntil('.cms-submenu-item-title').last().prev().show();
14✔
1522
            }
1523
        });
1524

1525
        mostRecentItems.hide();
4✔
1526
    },
1527

1528
    /**
1529
     * Toggles collapsable item.
1530
     *
1531
     * @method _toggleCollapsable
1532
     * @private
1533
     * @param {jQuery} el element to toggle
1534
     * @returns {Boolean|void}
1535
     */
1536
    _toggleCollapsable: function toggleCollapsable(el) {
1537
        var that = this;
×
1538
        var id = that._getId(el.parent());
×
1539
        var draggable = el.closest('.cms-draggable');
×
1540
        var items;
1541

1542
        var settings = CMS.settings;
×
1543

1544
        settings.states = settings.states || [];
×
1545

1546
        if (!draggable || !draggable.length) {
×
1547
            return;
×
1548
        }
1549

1550
        // collapsable function and save states
1551
        if (el.hasClass('cms-dragitem-expanded')) {
×
1552
            settings.states.splice($.inArray(id, settings.states), 1);
×
1553
            el
×
1554
                .removeClass('cms-dragitem-expanded')
1555
                .parent()
1556
                .find('> .cms-collapsable-container')
1557
                .addClass('cms-hidden');
1558

1559
            if ($document.data('expandmode')) {
×
1560
                items = draggable.find('.cms-draggable').find('.cms-dragitem-collapsable');
×
1561
                if (!items.length) {
×
1562
                    return false;
×
1563
                }
1564
                items.each(function() {
×
1565
                    var item = $(this);
×
1566

1567
                    if (item.hasClass('cms-dragitem-expanded')) {
×
1568
                        that._toggleCollapsable(item);
×
1569
                    }
1570
                });
1571
            }
1572
        } else {
1573
            settings.states.push(id);
×
1574
            el
×
1575
                .addClass('cms-dragitem-expanded')
1576
                .parent()
1577
                .find('> .cms-collapsable-container')
1578
                .removeClass('cms-hidden');
1579

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

1588
                    if (!item.hasClass('cms-dragitem-expanded')) {
×
1589
                        that._toggleCollapsable(item);
×
1590
                    }
1591
                });
1592
            }
1593
        }
1594

1595
        this._updatePlaceholderCollapseState();
×
1596

1597
        // make sure structurboard gets updated after expanding
1598
        $document.trigger('resize.sideframe');
×
1599

1600
        // save settings
1601
        Helpers.setSettings(settings);
×
1602
    },
1603

1604
    _updatePlaceholderCollapseState() {
1605
        if (this.options.type !== 'plugin' || !this.options.placeholder_id) {
×
1606
            return;
×
1607
        }
1608

1609
        const pluginsOfCurrentPlaceholder = CMS._plugins
×
1610
            .filter(([, o]) => o.placeholder_id === this.options.placeholder_id && o.type === 'plugin')
×
1611
            .map(([, o]) => o.plugin_id);
×
1612

1613
        const openedPlugins = CMS.settings.states;
×
1614
        const closedPlugins = difference(pluginsOfCurrentPlaceholder, openedPlugins);
×
1615
        const areAllRemainingPluginsLeafs = every(closedPlugins, id => {
×
1616
            return !find(
×
1617
                CMS._plugins,
1618
                ([, o]) => o.placeholder_id === this.options.placeholder_id && o.plugin_parent === id
×
1619
            );
1620
        });
1621
        const el = $(`.cms-dragarea-${this.options.placeholder_id} .cms-dragbar-title`);
×
1622
        var settings = CMS.settings;
×
1623

1624
        if (areAllRemainingPluginsLeafs) {
×
1625
            // meaning that all plugins in current placeholder are expanded
1626
            el.addClass('cms-dragbar-title-expanded');
×
1627

1628
            settings.dragbars = settings.dragbars || [];
×
1629
            settings.dragbars.push(this.options.placeholder_id);
×
1630
        } else {
1631
            el.removeClass('cms-dragbar-title-expanded');
×
1632

1633
            settings.dragbars = settings.dragbars || [];
×
1634
            settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1635
        }
1636
    },
1637

1638
    /**
1639
     * Sets up collabspable event handlers.
1640
     *
1641
     * @method _collapsables
1642
     * @private
1643
     * @returns {Boolean|void}
1644
     */
1645
    _collapsables: function() {
1646
        // one time setup
1647
        var that = this;
152✔
1648

1649
        this.ui.draggable = $('.cms-draggable-' + this.options.plugin_id);
152✔
1650
        // cancel here if its not a draggable
1651
        if (!this.ui.draggable.length) {
152✔
1652
            return false;
38✔
1653
        }
1654

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

1657
        // check which button should be shown for collapsemenu
1658
        var els = this.ui.draggable.find('.cms-dragitem-collapsable');
114✔
1659
        var open = els.filter('.cms-dragitem-expanded');
114✔
1660

1661
        if (els.length === open.length && els.length + open.length !== 0) {
114!
1662
            this.ui.draggable.find('.cms-dragbar-title').addClass('cms-dragbar-title-expanded');
×
1663
        }
1664

1665
        // attach events to draggable
1666
        // debounce here required because on some devices click is not triggered,
1667
        // so we consolidate latest click and touch event to run the collapse only once
1668
        dragitem.find('> .cms-dragitem-text').on(
114✔
1669
            Plugin.touchEnd + ' ' + Plugin.click,
1670
            debounce(function() {
1671
                if (!dragitem.hasClass('cms-dragitem-collapsable')) {
×
1672
                    return;
×
1673
                }
1674
                that._toggleCollapsable(dragitem);
×
1675
            }, 0)
1676
        );
1677
    },
1678

1679
    /**
1680
     * Expands all the collapsables in the given placeholder.
1681
     *
1682
     * @method _expandAll
1683
     * @private
1684
     * @param {jQuery} el trigger element that is a child of a placeholder
1685
     * @returns {Boolean|void}
1686
     */
1687
    _expandAll: function(el) {
1688
        var that = this;
×
1689
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1690

1691
        // cancel if there are no items
1692
        if (!items.length) {
×
1693
            return false;
×
1694
        }
1695
        items.each(function() {
×
1696
            var item = $(this);
×
1697

1698
            if (!item.hasClass('cms-dragitem-expanded')) {
×
1699
                that._toggleCollapsable(item);
×
1700
            }
1701
        });
1702

1703
        el.addClass('cms-dragbar-title-expanded');
×
1704

1705
        var settings = CMS.settings;
×
1706

1707
        settings.dragbars = settings.dragbars || [];
×
1708
        settings.dragbars.push(this.options.placeholder_id);
×
1709
        Helpers.setSettings(settings);
×
1710
    },
1711

1712
    /**
1713
     * Collapses all the collapsables in the given placeholder.
1714
     *
1715
     * @method _collapseAll
1716
     * @private
1717
     * @param {jQuery} el trigger element that is a child of a placeholder
1718
     */
1719
    _collapseAll: function(el) {
1720
        var that = this;
×
1721
        var items = el.closest('.cms-dragarea').find('.cms-dragitem-collapsable');
×
1722

1723
        items.each(function() {
×
1724
            var item = $(this);
×
1725

1726
            if (item.hasClass('cms-dragitem-expanded')) {
×
1727
                that._toggleCollapsable(item);
×
1728
            }
1729
        });
1730

1731
        el.removeClass('cms-dragbar-title-expanded');
×
1732

1733
        var settings = CMS.settings;
×
1734

1735
        settings.dragbars = settings.dragbars || [];
×
1736
        settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1737
        Helpers.setSettings(settings);
×
1738
    },
1739

1740
    /**
1741
     * Gets the id of the element, uses CMS.StructureBoard instance.
1742
     *
1743
     * @method _getId
1744
     * @private
1745
     * @param {jQuery} el element to get id from
1746
     * @returns {String}
1747
     */
1748
    _getId: function(el) {
1749
        return CMS.API.StructureBoard.getId(el);
36✔
1750
    },
1751

1752
    /**
1753
     * Gets the ids of the list of elements, uses CMS.StructureBoard instance.
1754
     *
1755
     * @method _getIds
1756
     * @private
1757
     * @param {jQuery} els elements to get id from
1758
     * @returns {String[]}
1759
     */
1760
    _getIds: function(els) {
1761
        return CMS.API.StructureBoard.getIds(els);
×
1762
    },
1763

1764
    /**
1765
     * Traverses the registry to find plugin parents
1766
     *
1767
     * @method _getPluginBreadcrumbs
1768
     * @returns {Object[]} array of breadcrumbs in `{ url, title }` format
1769
     * @private
1770
     */
1771
    _getPluginBreadcrumbs: function _getPluginBreadcrumbs() {
1772
        var breadcrumbs = [];
6✔
1773

1774
        breadcrumbs.unshift({
6✔
1775
            title: this.options.plugin_name,
1776
            url: this.options.urls.edit_plugin
1777
        });
1778

1779
        var findParentPlugin = function(id) {
6✔
1780
            return $.grep(CMS._plugins || [], function(pluginOptions) {
6✔
1781
                return pluginOptions[0] === 'cms-plugin-' + id;
10✔
1782
            })[0];
1783
        };
1784

1785
        var id = this.options.plugin_parent;
6✔
1786
        var data;
1787

1788
        while (id && id !== 'None') {
6✔
1789
            data = findParentPlugin(id);
6✔
1790

1791
            if (!data) {
6✔
1792
                break;
1✔
1793
            }
1794

1795
            breadcrumbs.unshift({
5✔
1796
                title: data[1].plugin_name,
1797
                url: data[1].urls.edit_plugin
1798
            });
1799
            id = data[1].plugin_parent;
5✔
1800
        }
1801

1802
        return breadcrumbs;
6✔
1803
    }
1804
});
1805

1806
Plugin.click = 'click.cms.plugin';
1✔
1807
Plugin.pointerUp = 'pointerup.cms.plugin';
1✔
1808
Plugin.pointerDown = 'pointerdown.cms.plugin';
1✔
1809
Plugin.pointerOverAndOut = 'pointerover.cms.plugin pointerout.cms.plugin';
1✔
1810
Plugin.doubleClick = 'dblclick.cms.plugin';
1✔
1811
Plugin.keyUp = 'keyup.cms.plugin';
1✔
1812
Plugin.keyDown = 'keydown.cms.plugin';
1✔
1813
Plugin.mouseEvents = 'mousedown.cms.plugin mousemove.cms.plugin mouseup.cms.plugin';
1✔
1814
Plugin.touchStart = 'touchstart.cms.plugin';
1✔
1815
Plugin.touchEnd = 'touchend.cms.plugin';
1✔
1816

1817
/**
1818
 * Updates plugin data in CMS._plugins / CMS._instances or creates new
1819
 * plugin instances if they didn't exist
1820
 *
1821
 * @method _updateRegistry
1822
 * @private
1823
 * @static
1824
 * @param {Object[]} plugins plugins data
1825
 */
1826
Plugin._updateRegistry = function _updateRegistry(plugins) {
1✔
1827
    plugins.forEach(pluginData => {
×
1828
        const pluginContainer = `cms-plugin-${pluginData.plugin_id}`;
×
1829
        const pluginIndex = findIndex(CMS._plugins, ([pluginStr]) => pluginStr === pluginContainer);
×
1830

1831
        if (pluginIndex === -1) {
×
1832
            CMS._plugins.push([pluginContainer, pluginData]);
×
1833
            CMS._instances.push(new Plugin(pluginContainer, pluginData));
×
1834
        } else {
1835
            Plugin.aliasPluginDuplicatesMap[pluginData.plugin_id] = false;
×
1836
            CMS._plugins[pluginIndex] = [pluginContainer, pluginData];
×
1837
            CMS._instances[pluginIndex] = new Plugin(pluginContainer, pluginData);
×
1838
        }
1839
    });
1840
};
1841

1842
/**
1843
 * Hides the opened settings menu. By default looks for any open ones.
1844
 *
1845
 * @method _hideSettingsMenu
1846
 * @static
1847
 * @private
1848
 * @param {jQuery} [navEl] element representing the subnav trigger
1849
 */
1850
Plugin._hideSettingsMenu = function(navEl) {
1✔
1851
    var nav = navEl || $('.cms-submenu-btn.cms-btn-active');
20✔
1852

1853
    if (!nav.length) {
20!
1854
        return;
20✔
1855
    }
1856
    nav.removeClass('cms-btn-active');
×
1857

1858
    // set correct active state
1859
    nav.closest('.cms-draggable').data('active', false);
×
1860
    $('.cms-z-index-9999').removeClass('cms-z-index-9999');
×
1861

1862
    nav.siblings('.cms-submenu-dropdown').hide();
×
1863
    nav.siblings('.cms-quicksearch').hide();
×
1864
    // reset search
1865
    nav.siblings('.cms-quicksearch').find('input').val('').trigger(Plugin.keyUp).blur();
×
1866

1867
    // reset relativity
1868
    $('.cms-dragbar').css('position', '');
×
1869
};
1870

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

1885
    Plugin._updateClipboard();
6✔
1886

1887
    // Structureboard initialized too late
1888
    setTimeout(function() {
6✔
1889
        var pluginData = {};
6✔
1890
        var html = '';
6✔
1891

1892
        if (clipboardDraggable.length) {
6✔
1893
            pluginData = find(
5✔
1894
                CMS._plugins,
1895
                ([desc]) => desc === `cms-plugin-${CMS.API.StructureBoard.getId(clipboardDraggable)}`
10✔
1896
            )[1];
1897
            html = clipboardDraggable.parent().html();
5✔
1898
        }
1899
        if (CMS.API && CMS.API.Clipboard) {
6!
1900
            CMS.API.Clipboard.populate(html, pluginData);
6✔
1901
        }
1902
    }, 0);
1903

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

1935
            // prevents single click from messing up the edit call
1936
            // don't go to the link if there is custom js attached to it
1937
            // or if it's clicked along with shift, ctrl, cmd
1938
            if (e.shiftKey || e.ctrlKey || e.metaKey || e.isDefaultPrevented()) {
×
1939
                return;
×
1940
            }
1941
            e.preventDefault();
×
1942
            if (++clickCounter === 1) {
×
1943
                timer = setTimeout(function() {
×
1944
                    var anchor = $(e.target).closest('a');
×
1945

1946
                    clickCounter = 0;
×
1947
                    window.open(anchor.attr('href'), anchor.attr('target') || '_self');
×
1948
                }, DOUBLECLICK_DELAY);
1949
            } else {
1950
                clearTimeout(timer);
×
1951
                clickCounter = 0;
×
1952
            }
1953
        });
1954

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

1964
        e.stopPropagation();
×
1965
        const pluginContainer = $(e.target).closest('.cms-plugin');
×
1966
        const allOptions = pluginContainer.data('cms');
×
1967

1968
        if (!allOptions || !allOptions.length) {
×
1969
            return;
×
1970
        }
1971

1972
        const options = allOptions[0];
×
1973

1974
        if (e.type === 'touchstart') {
×
1975
            CMS.API.Tooltip._forceTouchOnce();
×
1976
        }
1977
        var name = options.plugin_name;
×
1978
        var id = options.plugin_id;
×
1979
        var type = options.type;
×
1980

1981
        if (type === 'generic') {
×
1982
            return;
×
1983
        }
1984
        var placeholderId = CMS.API.StructureBoard.getId($(`.cms-draggable-${id}`).closest('.cms-dragarea'));
×
1985
        var placeholder = $('.cms-placeholder-' + placeholderId);
×
1986

1987
        if (placeholder.length && placeholder.data('cms')) {
×
1988
            name = placeholder.data('cms').name + ': ' + name;
×
1989
        }
1990

1991
        CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
1992
    });
1993

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

1997
        if (placeholder.hasClass('cms-dragarea-static-expanded') && e.isDefaultPrevented()) {
×
1998
            return;
×
1999
        }
2000

2001
        placeholder.toggleClass('cms-dragarea-static-expanded');
×
2002
    });
2003

2004
    $window.on('blur.cms', () => {
6✔
2005
        $document.data('expandmode', false);
6✔
2006
    });
2007
};
2008

2009
/**
2010
 * @method _isContainingMultiplePlugins
2011
 * @param {jQuery} node to check
2012
 * @static
2013
 * @private
2014
 * @returns {Boolean}
2015
 */
2016
Plugin._isContainingMultiplePlugins = function _isContainingMultiplePlugins(node) {
1✔
2017
    var currentData = node.data('cms');
129✔
2018

2019
    // istanbul ignore if
2020
    if (!currentData) {
129✔
2021
        throw new Error('Provided node is not a cms plugin.');
2022
    }
2023

2024
    var pluginIds = currentData.map(function(pluginData) {
129✔
2025
        return pluginData.plugin_id;
130✔
2026
    });
2027

2028
    if (pluginIds.length > 1) {
129✔
2029
        // another plugin already lives on the same node
2030
        // this only works because the plugins are rendered from
2031
        // the bottom to the top (leaf to root)
2032
        // meaning the deepest plugin is always first
2033
        return true;
1✔
2034
    }
2035

2036
    return false;
128✔
2037
};
2038

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

2059
    el.addClass('cms-draggable-success').append(tpl);
×
2060
    // start animation
2061
    if (successTimeout) {
×
2062
        setTimeout(() => {
×
2063
            tpl.fadeOut(successTimeout, function() {
×
2064
                $(this).remove();
×
2065
                el.removeClass('cms-draggable-success');
×
2066
            });
2067
        }, delay);
2068
    }
2069
    // make sure structurboard gets updated after success
2070
    $(Helpers._getWindow()).trigger('resize.sideframe');
×
2071
};
2072

2073
/**
2074
 * Highlights plugin in content mode
2075
 *
2076
 * @method _highlightPluginContent
2077
 * @private
2078
 * @static
2079
 * @param {String|Number} pluginId
2080
 */
2081
Plugin._highlightPluginContent = function _highlightPluginContent(
1✔
2082
    pluginId,
2083
    // eslint-disable-next-line no-magic-numbers
2084
    { successTimeout = 200, seeThrough = false, delay = 1500, prominent = false } = {}
5✔
2085
) {
2086
    var coordinates = {};
1✔
2087
    var positions = [];
1✔
2088
    var OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO = 0.2;
1✔
2089

2090
    $('.cms-plugin-' + pluginId).each(function() {
1✔
2091
        var el = $(this);
1✔
2092
        var offset = el.offset();
1✔
2093
        var ml = parseInt(el.css('margin-left'), 10);
1✔
2094
        var mr = parseInt(el.css('margin-right'), 10);
1✔
2095
        var mt = parseInt(el.css('margin-top'), 10);
1✔
2096
        var mb = parseInt(el.css('margin-bottom'), 10);
1✔
2097
        var width = el.outerWidth();
1✔
2098
        var height = el.outerHeight();
1✔
2099

2100
        if (width === 0 && height === 0) {
1!
2101
            return;
×
2102
        }
2103

2104
        if (isNaN(ml)) {
1!
2105
            ml = 0;
×
2106
        }
2107
        if (isNaN(mr)) {
1!
2108
            mr = 0;
×
2109
        }
2110
        if (isNaN(mt)) {
1!
2111
            mt = 0;
×
2112
        }
2113
        if (isNaN(mb)) {
1!
2114
            mb = 0;
×
2115
        }
2116

2117
        positions.push({
1✔
2118
            x1: offset.left - ml,
2119
            x2: offset.left + width + mr,
2120
            y1: offset.top - mt,
2121
            y2: offset.top + height + mb
2122
        });
2123
    });
2124

2125
    if (positions.length === 0) {
1!
2126
        return;
×
2127
    }
2128

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

2134
    coordinates.left = Math.min(...positions.map(pos => pos.x1));
1✔
2135
    coordinates.top = Math.min(...positions.map(pos => pos.y1)) - htmlMargin;
1✔
2136
    coordinates.width = Math.max(...positions.map(pos => pos.x2)) - coordinates.left;
1✔
2137
    coordinates.height = Math.max(...positions.map(pos => pos.y2)) - coordinates.top - htmlMargin;
1✔
2138

2139
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2140

2141
    $(
1✔
2142
        `
2143
        <div class="
2144
            cms-plugin-overlay
2145
            cms-dragitem-success
2146
            cms-plugin-overlay-${pluginId}
2147
            ${seeThrough ? 'cms-plugin-overlay-see-through' : ''}
1!
2148
            ${prominent ? 'cms-plugin-overlay-prominent' : ''}
1!
2149
        "
2150
            data-success-timeout="${successTimeout}"
2151
        >
2152
        </div>
2153
    `
2154
    )
2155
        .css(coordinates)
2156
        .css({
2157
            zIndex: 9999
2158
        })
2159
        .appendTo($('body'));
2160

2161
    if (successTimeout) {
1!
2162
        setTimeout(() => {
1✔
2163
            $(`.cms-plugin-overlay-${pluginId}`).fadeOut(successTimeout, function() {
1✔
2164
                $(this).remove();
1✔
2165
            });
2166
        }, delay);
2167
    }
2168
};
2169

2170
Plugin._clickToHighlightHandler = function _clickToHighlightHandler(e) {
1✔
2171
    if (CMS.settings.mode !== 'structure') {
×
2172
        return;
×
2173
    }
2174
    e.preventDefault();
×
2175
    e.stopPropagation();
×
2176
    // FIXME refactor into an object
2177
    CMS.API.StructureBoard._showAndHighlightPlugin(200, true); // eslint-disable-line no-magic-numbers
×
2178
};
2179

2180
Plugin._removeHighlightPluginContent = function(pluginId) {
1✔
2181
    $(`.cms-plugin-overlay-${pluginId}[data-success-timeout=0]`).remove();
×
2182
};
2183

2184
Plugin.aliasPluginDuplicatesMap = {};
1✔
2185
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2186

2187
// istanbul ignore next
2188
Plugin._initializeTree = function _initializeTree() {
2189
    CMS._plugins = uniqWith(CMS._plugins, ([x], [y]) => x === y);
2190
    CMS._instances = CMS._plugins.map(function(args) {
2191
        return new CMS.Plugin(args[0], args[1]);
2192
    });
2193

2194
    // return the cms plugin instances just created
2195
    return CMS._instances;
2196
};
2197

2198
Plugin._updateClipboard = function _updateClipboard() {
1✔
2199
    clipboardDraggable = $('.cms-draggable-from-clipboard:first');
7✔
2200
};
2201

2202
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2203
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2204

2205
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2206

2207
    if (Helpers._isStorageSupported) {
2!
2208
        localStorage.setItem('cms-plugin-usage', JSON.stringify(pluginUsageMap));
×
2209
    }
2210
};
2211

2212
Plugin._removeAddPluginPlaceholder = function removeAddPluginPlaceholder() {
1✔
2213
    // this can't be cached since they are created and destroyed all over the place
2214
    $('.cms-add-plugin-placeholder').remove();
10✔
2215
};
2216

2217
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2218
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2219
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2220
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2221

2222
    CMS._instances.forEach(instance => {
4✔
2223
        if (instance.options.type === 'placeholder') {
5✔
2224
            instance._setupUI(`cms-placeholder-${instance.options.placeholder_id}`);
2✔
2225
            instance._ensureData();
2✔
2226
            instance.ui.container.data('cms', instance.options);
2✔
2227
            instance._setPlaceholder();
2✔
2228
        }
2229
    });
2230

2231
    CMS._instances.forEach(instance => {
4✔
2232
        if (instance.options.type === 'plugin') {
5✔
2233
            instance._setupUI(`cms-plugin-${instance.options.plugin_id}`);
2✔
2234
            instance._ensureData();
2✔
2235
            instance.ui.container.data('cms').push(instance.options);
2✔
2236
            instance._setPluginContentEvents();
2✔
2237
        }
2238
    });
2239

2240
    CMS._plugins.forEach(([type, opts]) => {
4✔
2241
        if (opts.type !== 'placeholder' && opts.type !== 'plugin') {
16✔
2242
            const instance = find(
8✔
2243
                CMS._instances,
2244
                i => i.options.type === opts.type && Number(i.options.plugin_id) === Number(opts.plugin_id)
13✔
2245
            );
2246

2247
            if (instance) {
8✔
2248
                // update
2249
                instance._setupUI(type);
1✔
2250
                instance._ensureData();
1✔
2251
                instance.ui.container.data('cms').push(instance.options);
1✔
2252
                instance._setGeneric();
1✔
2253
            } else {
2254
                // create
2255
                CMS._instances.push(new Plugin(type, opts));
7✔
2256
            }
2257
        }
2258
    });
2259
};
2260

2261
Plugin._getPluginById = function(id) {
1✔
2262
    return find(CMS._instances, ({ options }) => options.type === 'plugin' && Number(options.plugin_id) === Number(id));
20!
2263
};
2264

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

2270
    plugins.forEach((element, index) => {
10✔
2271
        const pluginId = CMS.API.StructureBoard.getId($(element));
20✔
2272
        const instance = Plugin._getPluginById(pluginId);
20✔
2273

2274
        if (!instance) {
20!
2275
            return;
20✔
2276
        }
2277

2278
        instance.options.position = index + 1;
×
2279
    });
2280
};
2281

2282
Plugin._recalculatePluginPositions = function(action, data) {
1✔
2283
    if (action === 'MOVE') {
×
2284
        // le sigh - recalculate all placeholders cause we don't know from where the
2285
        // plugin was moved from
2286
        filter(CMS._instances, ({ options }) => options.type === 'placeholder')
×
2287
            .map(({ options }) => options.placeholder_id)
×
2288
            .forEach(placeholder_id => Plugin._updatePluginPositions(placeholder_id));
×
2289
    } else if (data.placeholder_id) {
×
2290
        Plugin._updatePluginPositions(data.placeholder_id);
×
2291
    }
2292
};
2293

2294
// shorthand for jQuery(document).ready();
2295
$(Plugin._initializeGlobalHandlers);
1✔
2296

2297
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