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

divio / django-cms / #29104

04 Oct 2024 06:09AM UTC coverage: 76.296% (-0.7%) from 76.981%
#29104

push

travis-ci

web-flow
Merge 9967bee9e into 1f864af6f

1044 of 1555 branches covered (67.14%)

2517 of 3299 relevant lines covered (76.3%)

26.91 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

483
        return true;
5✔
484
    },
485

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

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

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

517
        this.modal = modal;
3✔
518

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

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

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

538
        if (maybeChildren.length) {
×
539
            const lastChild = maybeChildren.last();
×
540

541
            const lastChildInstance = Plugin._getPluginById(this._getId(lastChild));
×
542

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

546
        return this.options.position + 1;
×
547
    },
548

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

565
        this.modal = modal;
3✔
566

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

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

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

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

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

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

653
        $.ajax(request);
8✔
654
    },
655

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

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

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

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

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

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

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

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

747
        // set correct options
748
        var options = opts || this.options;
11✔
749

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

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

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

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

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

776
            Plugin._updatePluginPositions(placeholder_id);
×
777
            Plugin._updatePluginPositions(options.placeholder_id);
×
778
        }
779

780
        var position = this.options.position;
10✔
781

782
        data.target_position = position;
10✔
783

784
        showLoader();
10✔
785

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

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

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

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

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

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

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

859
        this.modal = modal;
2✔
860

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

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

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

892
        if (mustCleanup) {
2✔
893
            this.cleanup();
1✔
894
        }
895

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1046
            modal = new Modal({
×
1047
                minWidth: 400,
1048
                minHeight: 400
1049
            });
1050

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

1057
            Helpers.addEventListener('modal-loaded', (e, { instance }) => {
×
1058
                if (instance !== modal) {
×
1059
                    return;
×
1060
                }
1061

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

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

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

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

1092
            plugins = nav.siblings('.cms-plugin-picker');
×
1093

1094
            that._setupQuickSearch(plugins);
×
1095
        });
1096

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

1109
                Plugin._hideSettingsMenu();
×
1110

1111
                initModal();
×
1112

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

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

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

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

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

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

1153
        let ref = plugins.find('.cms-quicksearch');
×
1154

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

1161
            if (item.length) {
×
1162
                const clone = item.closest('.cms-submenu-item').clone(true, true);
×
1163

1164
                ref.after(clone);
×
1165
                ref = clone;
×
1166
                count += 1;
×
1167
            }
1168
        });
1169

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

1178
        return plugins;
×
1179
    },
1180

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

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

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

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

1226
            resultElements = resultElements.filter(function(index) {
29✔
1227
                var item = $(this);
411✔
1228

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

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

1240
        return resultElements;
33✔
1241
    },
1242

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

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

1261
            that._filterPluginsList(pluginsPicker, input);
×
1262
        }, FILTER_DEBOUNCE_TIMER);
1263

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

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

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

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

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

1319
        var nav;
1320
        var that = this;
13✔
1321

1322
        if (e.data && e.data.nav) {
13!
1323
            nav = e.data.nav;
×
1324
        }
1325

1326
        // show loader and make sure scroll doesn't jump
1327
        showLoader();
13✔
1328

1329
        var items = '.cms-submenu-edit, .cms-submenu-item a';
13✔
1330
        var el = $(e.target).closest(items);
13✔
1331

1332
        Plugin._hideSettingsMenu(nav);
13✔
1333

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

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

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

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

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

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

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

1450
        var dropdown = this.ui.dropdown;
×
1451
        var parents = nav.parentsUntil('.cms-dragarea').last();
×
1452
        var MIN_SCREEN_MARGIN = 10;
×
1453

1454
        nav.addClass('cms-btn-active');
×
1455
        parents.addClass('cms-z-index-9999');
×
1456

1457
        // set visible states
1458
        dropdown.show();
×
1459

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

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

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

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

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

1495
        var itemsToFilter = items.toArray().map(function(el) {
4✔
1496
            var element = $(el);
72✔
1497

1498
            return {
72✔
1499
                value: element.text(),
1500
                element: element
1501
            };
1502
        });
1503

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

1506
        items.hide();
4✔
1507
        filteredItems.forEach(function(item) {
4✔
1508
            item.element.show();
3✔
1509
        });
1510

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

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

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

1528
        mostRecentItems.hide();
4✔
1529
    },
1530

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

1545
        var settings = CMS.settings;
×
1546

1547
        settings.states = settings.states || [];
×
1548

1549
        if (!draggable || !draggable.length) {
×
1550
            return;
×
1551
        }
1552

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

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

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

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

1591
                    if (!item.hasClass('cms-dragitem-expanded')) {
×
1592
                        that._toggleCollapsable(item);
×
1593
                    }
1594
                });
1595
            }
1596
        }
1597

1598
        this._updatePlaceholderCollapseState();
×
1599

1600
        // make sure structurboard gets updated after expanding
1601
        $document.trigger('resize.sideframe');
×
1602

1603
        // save settings
1604
        Helpers.setSettings(settings);
×
1605
    },
1606

1607
    _updatePlaceholderCollapseState() {
1608
        if (this.options.type !== 'plugin' || !this.options.placeholder_id) {
×
1609
            return;
×
1610
        }
1611

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

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

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

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

1636
            settings.dragbars = settings.dragbars || [];
×
1637
            settings.dragbars.splice($.inArray(this.options.placeholder_id, settings.states), 1);
×
1638
        }
1639
    },
1640

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

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

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

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

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

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

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

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

1701
            if (!item.hasClass('cms-dragitem-expanded')) {
×
1702
                that._toggleCollapsable(item);
×
1703
            }
1704
        });
1705

1706
        el.addClass('cms-dragbar-title-expanded');
×
1707

1708
        var settings = CMS.settings;
×
1709

1710
        settings.dragbars = settings.dragbars || [];
×
1711
        settings.dragbars.push(this.options.placeholder_id);
×
1712
        Helpers.setSettings(settings);
×
1713
    },
1714

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

1726
        items.each(function() {
×
1727
            var item = $(this);
×
1728

1729
            if (item.hasClass('cms-dragitem-expanded')) {
×
1730
                that._toggleCollapsable(item);
×
1731
            }
1732
        });
1733

1734
        el.removeClass('cms-dragbar-title-expanded');
×
1735

1736
        var settings = CMS.settings;
×
1737

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

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

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

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

1777
        breadcrumbs.unshift({
6✔
1778
            title: this.options.plugin_name,
1779
            url: this.options.urls.edit_plugin
1780
        });
1781

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

1788
        var id = this.options.plugin_parent;
6✔
1789
        var data;
1790

1791
        while (id && id !== 'None') {
6✔
1792
            data = findParentPlugin(id);
6✔
1793

1794
            if (!data) {
6✔
1795
                break;
1✔
1796
            }
1797

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

1805
        return breadcrumbs;
6✔
1806
    }
1807
});
1808

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

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

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

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

1856
    if (!nav.length) {
20!
1857
        return;
20✔
1858
    }
1859
    nav.removeClass('cms-btn-active');
×
1860

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

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

1870
    // reset relativity
1871
    $('.cms-dragbar').css('position', '');
×
1872
};
1873

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

1888
    Plugin._updateClipboard();
6✔
1889

1890
    // Structureboard initialized too late
1891
    setTimeout(function() {
6✔
1892
        var pluginData = {};
6✔
1893
        var html = '';
6✔
1894

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

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

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

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

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

1967
        e.stopPropagation();
×
1968
        const pluginContainer = $(e.target).closest('.cms-plugin');
×
1969
        const allOptions = pluginContainer.data('cms');
×
1970

1971
        if (!allOptions || !allOptions.length) {
×
1972
            return;
×
1973
        }
1974

1975
        const options = allOptions[0];
×
1976

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

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

1990
        if (placeholder.length && placeholder.data('cms')) {
×
1991
            name = placeholder.data('cms').name + ': ' + name;
×
1992
        }
1993

1994
        CMS.API.Tooltip.displayToggle(e.type === 'pointerover' || e.type === 'touchstart', e, name, id);
×
1995
    });
1996

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

2000
        if (placeholder.hasClass('cms-dragarea-static-expanded') && e.isDefaultPrevented()) {
×
2001
            return;
×
2002
        }
2003

2004
        placeholder.toggleClass('cms-dragarea-static-expanded');
×
2005
    });
2006

2007
    $window.on('blur.cms', () => {
6✔
2008
        $document.data('expandmode', false);
6✔
2009
    });
2010
};
2011

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

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

2027
    var pluginIds = currentData.map(function(pluginData) {
129✔
2028
        return pluginData.plugin_id;
130✔
2029
    });
2030

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

2039
    return false;
128✔
2040
};
2041

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

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

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

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

2103
        if (width === 0 && height === 0) {
1!
2104
            return;
×
2105
        }
2106

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

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

2128
    if (positions.length === 0) {
1!
2129
        return;
×
2130
    }
2131

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

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

2142
    $window.scrollTop(coordinates.top - $window.height() * OVERLAY_POSITION_TO_WINDOW_HEIGHT_RATIO);
1✔
2143

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

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

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

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

2187
Plugin.aliasPluginDuplicatesMap = {};
1✔
2188
Plugin.staticPlaceholderDuplicatesMap = {};
1✔
2189

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

2197
    // return the cms plugin instances just created
2198
    return CMS._instances;
2199
};
2200

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

2205
Plugin._updateUsageCount = function _updateUsageCount(pluginType) {
1✔
2206
    var currentValue = pluginUsageMap[pluginType] || 0;
2✔
2207

2208
    pluginUsageMap[pluginType] = currentValue + 1;
2✔
2209

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

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

2220
Plugin._refreshPlugins = function refreshPlugins() {
1✔
2221
    Plugin.aliasPluginDuplicatesMap = {};
4✔
2222
    Plugin.staticPlaceholderDuplicatesMap = {};
4✔
2223
    CMS._plugins = uniqWith(CMS._plugins, isEqual);
4✔
2224

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

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

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

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

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

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

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

2277
        if (!instance) {
20!
2278
            return;
20✔
2279
        }
2280

2281
        instance.options.position = index + 1;
×
2282
    });
2283
};
2284

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

2297
// shorthand for jQuery(document).ready();
2298
$(Plugin._initializeGlobalHandlers);
1✔
2299

2300
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