forked from django-cms/django-cms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cms.structureboard.js
1641 lines (1372 loc) · 55.9 KB
/
cms.structureboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright https://github.com/divio/django-cms
*/
import $ from 'jquery';
import keyboard from './keyboard';
import Plugin from './cms.plugins';
import { getPlaceholderIds } from './cms.toolbar';
import Clipboard from './cms.clipboard';
import URI from 'urijs';
import { DiffDOM } from 'diff-dom';
import PreventParentScroll from 'prevent-parent-scroll';
import { find, findIndex, once, remove, compact, isEqual, zip, every } from 'lodash';
import ls from 'local-storage';
import './jquery.ui.custom';
import './jquery.ui.touchpunch';
import './jquery.ui.nestedsortable';
import measureScrollbar from './scrollbar';
import preloadImagesFromMarkup from './preload-images';
import { Helpers, KEYS } from './cms.base';
import { showLoader, hideLoader } from './loader';
let dd;
const DOMParser = window.DOMParser; // needed only for testing
const storageKey = 'cms-structure';
let placeholders;
let originalPluginContainer;
const triggerWindowResize = () => {
try {
var evt = document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(evt);
} catch (e) {}
};
const arrayEquals = (a1, a2) => every(zip(a1, a2), ([a, b]) => a === b);
/**
* Handles drag & drop, mode switching and collapsables.
*
* @class StructureBoard
* @namespace CMS
*/
class StructureBoard {
constructor() {
// elements
this._setupUI();
// states
this.click = 'click.cms.structure';
this.keyUpAndDown = 'keyup.cms.structure keydown.cms.structure';
this.pointerUp = 'pointerup.cms';
this.state = false;
this.dragging = false;
this.latestAction = [];
ls.remove(storageKey);
dd = new DiffDOM();
// setup initial stuff
const setup = this._setup();
// istanbul ignore if
if (typeof setup === 'undefined' && CMS.config.mode === 'draft') {
this._preloadOppositeMode();
}
this._setupModeSwitcher();
this._events();
StructureBoard.actualizePlaceholders();
setTimeout(() => this.highlightPluginFromUrl(), 0);
this._listenToExternalUpdates();
}
/**
* Stores all jQuery references within `this.ui`.
*
* @method _setupUI
* @private
*/
_setupUI() {
var container = $('.cms-structure');
var toolbar = $('.cms-toolbar');
this.ui = {
container: container,
content: $('.cms-structure-content'),
doc: $(document),
window: $(window),
html: $('html'),
toolbar: toolbar,
sortables: $('.cms-draggables'), // global scope to include clipboard
plugins: $('.cms-plugin'),
render_model: $('.cms-render-model'),
placeholders: $('.cms-placeholder'),
dragitems: $('.cms-draggable'),
dragareas: $('.cms-dragarea'),
toolbarModeSwitcher: toolbar.find('.cms-toolbar-item-cms-mode-switcher'),
toolbarModeLinks: toolbar.find('.cms-toolbar-item-cms-mode-switcher a')
};
this._preventScroll = new PreventParentScroll(this.ui.content[0]);
}
/**
* Initial setup (and early bail if specific
* elements do not exist).
*
* @method _setup
* @private
* @returns {Boolean|void}
*/
_setup() {
var that = this;
// cancel if there is no structure / content switcher
if (!this.ui.toolbarModeSwitcher.length) {
return false;
}
// setup toolbar mode
if (CMS.config.settings.mode === 'structure') {
that.show({ init: true });
that._loadedStructure = true;
StructureBoard._initializeDragItemsStates();
} else {
// triggering hide here to switch proper classnames on switcher
that.hide(true);
that._loadedContent = true;
}
if (CMS.config.settings.legacy_mode) {
that._loadedStructure = true;
that._loadedContent = true;
}
// check if modes should be visible
if (this.ui.dragareas.not('.cms-clipboard .cms-dragarea').length || this.ui.placeholders.length) {
// eslint-disable-line
this.ui.toolbarModeSwitcher.find('.cms-btn').removeClass('cms-btn-disabled');
}
// add drag & drop functionality
// istanbul ignore next
$('.cms-draggable').one(
'pointerover.cms.drag',
once(() => {
$('.cms-draggable').off('pointerover.cms.drag');
this._drag();
})
);
}
_preloadOppositeMode() {
if (CMS.config.settings.legacy_mode) {
return;
}
const WAIT_BEFORE_PRELOADING = 2000;
$(Helpers._getWindow()).one('load', () => {
setTimeout(() => {
if (this._loadedStructure) {
this._requestMode('content');
} else {
this._requestMode('structure');
}
}, WAIT_BEFORE_PRELOADING);
});
}
_events() {
this.ui.window.on('resize.cms.structureboard', () => {
if (!this._loadedContent) {
return;
}
const width = this.ui.window[0].innerWidth;
const BREAKPOINT = 1024;
if (width > BREAKPOINT && !this.condensed) {
this._makeCondensed();
}
if (width <= BREAKPOINT && this.condensed) {
this._makeFullWidth();
}
});
}
/**
* Sets up events handlers for switching
* structureboard modes.
*
* @method _setupModeSwitcher
* @private
*/
_setupModeSwitcher() {
const modes = this.ui.toolbarModeLinks;
let cmdPressed;
$(Helpers._getWindow())
.on(this.keyUpAndDown, e => {
if (
e.keyCode === KEYS.CMD_LEFT ||
e.keyCode === KEYS.CMD_RIGHT ||
e.keyCode === KEYS.CMD_FIREFOX ||
e.keyCode === KEYS.SHIFT ||
e.keyCode === KEYS.CTRL
) {
cmdPressed = true;
}
if (e.type === 'keyup') {
cmdPressed = false;
}
})
.on('blur', () => {
cmdPressed = false;
});
// show edit mode
modes.on(this.click, e => {
e.preventDefault();
e.stopImmediatePropagation();
if (modes.hasClass('cms-btn-disabled')) {
return;
}
if (cmdPressed && e.type === 'click') {
// control the behaviour when ctrl/cmd is pressed
Helpers._getWindow().open(modes.attr('href'), '_blank');
return;
}
if (CMS.settings.mode === 'edit') {
this.show();
} else {
this.hide();
}
});
// keyboard handling
// only if there is a structure / content switcher
if (
this.ui.toolbarModeSwitcher.length &&
!this.ui.toolbarModeSwitcher.find('.cms-btn').is('.cms-btn-disabled')
) {
keyboard.setContext('cms');
keyboard.bind('space', e => {
e.preventDefault();
this._toggleStructureBoard();
});
keyboard.bind('shift+space', e => {
e.preventDefault();
this._toggleStructureBoard({ useHoveredPlugin: true });
});
}
}
/**
* @method _toggleStructureBoard
* @private
* @param {Object} [options] options
* @param {Boolean} [options.useHoveredPlugin] should the plugin be taken into account
*/
_toggleStructureBoard(options = {}) {
var that = this;
if (options.useHoveredPlugin && CMS.settings.mode !== 'structure') {
that._showAndHighlightPlugin(options.successTimeout).then($.noop, $.noop);
} else if (!options.useHoveredPlugin) {
// eslint-disable-next-line no-lonely-if
if (CMS.settings.mode === 'structure') {
that.hide();
} else if (CMS.settings.mode === 'edit') {
/* istanbul ignore else */ that.show();
}
}
}
/**
* Shows structureboard, scrolls into view and highlights hovered plugin.
* Uses CMS.API.Tooltip because it already handles multiple plugins living on
* the same DOM node.
*
* @method _showAndHighlightPlugin
* @private
* @returns {Promise}
*/
// eslint-disable-next-line no-magic-numbers
_showAndHighlightPlugin(successTimeout = 200, seeThrough = false) {
// cancel show if live modus is active
if (CMS.config.mode === 'live') {
return Promise.resolve(false);
}
if (!CMS.API.Tooltip) {
return Promise.resolve(false);
}
var tooltip = CMS.API.Tooltip.domElem;
var HIGHLIGHT_TIMEOUT = 10;
var DRAGGABLE_HEIGHT = 50; // it's not precisely 50, but it fits
if (!tooltip.is(':visible')) {
return Promise.resolve(false);
}
var pluginId = tooltip.data('plugin_id');
return this.show({ saveState: false }).then(function() {
var draggable = $('.cms-draggable-' + pluginId);
var doc = $(document);
var currentExpandmode = doc.data('expandmode');
// expand necessary parents
doc.data('expandmode', false);
draggable
.parents('.cms-draggable')
.find('> .cms-dragitem-collapsable:not(".cms-dragitem-expanded") > .cms-dragitem-text')
.each((i, el) => $(el).triggerHandler(Plugin.click));
setTimeout(() => doc.data('expandmode', currentExpandmode));
setTimeout(function() {
var offsetParent = draggable.offsetParent();
var position = draggable.position().top + offsetParent.scrollTop();
draggable.offsetParent().scrollTop(position - window.innerHeight / 2 + DRAGGABLE_HEIGHT);
Plugin._highlightPluginStructure(draggable.find('.cms-dragitem:first'), { successTimeout, seeThrough });
}, HIGHLIGHT_TIMEOUT);
});
}
/**
* Shows the structureboard. (Structure mode)
*
* @method show
* @public
* @param {Boolean} init true if this is first initialization
* @returns {Promise}
*/
show({ init = false, saveState = true } = {}) {
// cancel show if live modus is active
if (CMS.config.mode === 'live') {
return Promise.resolve(false);
}
// in order to get consistent positioning
// of the toolbar we have to know if the page
// had the scrollbar and if it had - we adjust
// the toolbar positioning
if (init) {
var width = this.ui.toolbar.width();
var scrollBarWidth = this.ui.window[0].innerWidth - width;
if (!scrollBarWidth && init) {
scrollBarWidth = measureScrollbar();
}
if (scrollBarWidth) {
this.ui.toolbar.css('right', scrollBarWidth);
}
}
// apply new settings
CMS.settings.mode = 'structure';
Helpers.setSettings(CMS.settings);
if (!init && saveState) {
this._saveStateInURL();
}
return this._loadStructure().then(this._showBoard.bind(this, init));
}
_loadStructure() {
// case when structure mode is already loaded
if (CMS.config.settings.mode === 'structure' || this._loadedStructure) {
return Promise.resolve();
}
showLoader();
return this
._requestMode('structure')
.done(contentMarkup => {
this._requeststructure = null;
hideLoader();
CMS.settings.states = Helpers.getSettings().states;
var bodyRegex = /<body[\S\s]*?>([\S\s]*)<\/body>/gi;
var body = $(bodyRegex.exec(contentMarkup)[1]);
var structure = body.find('.cms-structure-content');
var toolbar = body.find('.cms-toolbar');
var scripts = body.filter(function() {
var elem = $(this);
return elem.is('[type="text/cms-template"]'); // cms scripts
});
const pluginIds = this.getIds(body.find('.cms-draggable'));
const pluginDataSource = body.filter('script[data-cms]').toArray()
.map(script => script.textContent || '').join();
const pluginData = StructureBoard._getPluginDataFromMarkup(
pluginDataSource,
pluginIds
);
Plugin._updateRegistry(pluginData.map(([, data]) => data));
CMS.API.Toolbar._refreshMarkup(toolbar);
$('body').append(scripts);
$('.cms-structure-content').html(structure.html());
triggerWindowResize();
StructureBoard._initializeGlobalHandlers();
StructureBoard.actualizePlaceholders();
CMS._instances.forEach(instance => {
if (instance.options.type === 'placeholder') {
instance._setPlaceholder();
}
});
CMS._instances.forEach(instance => {
if (instance.options.type === 'plugin') {
instance._setPluginStructureEvents();
instance._collapsables();
}
});
this.ui.sortables = $('.cms-draggables');
this._drag();
StructureBoard._initializeDragItemsStates();
this._loadedStructure = true;
})
.fail(function() {
window.location.href = new URI(window.location.href)
.addSearch(CMS.config.settings.structure)
.toString();
});
}
_requestMode(mode) {
var url = new URI(window.location.href);
if (mode === 'structure') {
url.addSearch(CMS.config.settings.structure);
} else {
url.addSearch(CMS.settings.edit || 'edit').removeSearch(CMS.config.settings.structure);
}
if (!this[`_request${mode}`]) {
this[`_request${mode}`] = $.ajax({
url: url.toString(),
method: 'GET'
}).then(markup => {
preloadImagesFromMarkup(markup);
return markup;
});
}
return this[`_request${mode}`];
}
_loadContent() {
var that = this;
// case when content mode is already loaded
if (CMS.config.settings.mode === 'edit' || this._loadedContent) {
return Promise.resolve();
}
showLoader();
return that
._requestMode('content')
.done(function(contentMarkup) {
that._requestcontent = null;
hideLoader();
var htmlRegex = /<html([\S\s]*?)>[\S\s]*<\/html>/gi;
var bodyRegex = /<body([\S\s]*?)>([\S\s]*)<\/body>/gi;
var headRegex = /<head[\S\s]*?>([\S\s]*)<\/head>/gi;
var matches = bodyRegex.exec(contentMarkup);
// we don't handle cases where body or html doesn't exist, cause it's highly unlikely
// and will result in way more troubles for cms than this
var bodyAttrs = matches[1];
var body = $(matches[2]);
var head = $(headRegex.exec(contentMarkup)[1]);
var htmlAttrs = htmlRegex.exec(contentMarkup)[1];
var bodyAttributes = $('<div ' + bodyAttrs + '></div>')[0].attributes;
var htmlAttributes = $('<div ' + htmlAttrs + '></div>')[0].attributes;
var newToolbar = body.find('.cms-toolbar');
var toolbar = $('.cms').add('[data-cms]').detach();
var title = head.filter('title');
var bodyElement = $('body');
// istanbul ignore else
if (title) {
document.title = title.text();
}
body = body.filter(function() {
var elem = $(this);
return (
!elem.is('.cms#cms-top') && !elem.is('[data-cms]:not([data-cms-generic])') // toolbar
); // cms scripts
});
body.find('[data-cms]:not([data-cms-generic])').remove(); // cms scripts
[].slice.call(bodyAttributes).forEach(function(attr) {
bodyElement.attr(attr.name, attr.value);
});
[].slice.call(htmlAttributes).forEach(function(attr) {
$('html').attr(attr.name, attr.value);
});
bodyElement.append(body);
$('head').append(head);
bodyElement.prepend(toolbar);
CMS.API.Toolbar._refreshMarkup(newToolbar);
$(window).trigger('resize');
Plugin._refreshPlugins();
const scripts = $('script');
// istanbul ignore next
scripts.on('load', function() {
window.dispatchEvent(new Event('load'));
window.dispatchEvent(new Event('DOMContentLoaded'));
});
const unhandledPlugins = $('body').find('template.cms-plugin');
if (unhandledPlugins.length) {
CMS.API.Messages.open({
message: CMS.config.lang.unhandledPageChange
});
Helpers.reloadBrowser();
}
that._loadedContent = true;
})
.fail(function() {
window.location.href = new URI(window.location.href)
.removeSearch(CMS.config.settings.structure)
.toString();
});
}
_saveStateInURL() {
var url = new URI(window.location.href);
url[CMS.settings.mode === 'structure' ? 'addSearch' : 'removeSearch'](CMS.config.settings.structure);
history.replaceState({}, '', url.toString());
}
/**
* Hides the structureboard. (Content mode)
*
* @method hide
* @param {Boolean} init true if this is first initialization
* @returns {Boolean|void}
*/
hide(init) {
// cancel show if live modus is active
if (CMS.config.mode === 'live') {
return false;
}
// reset toolbar positioning
this.ui.toolbar.css('right', '');
$('html').removeClass('cms-overflow');
// set active item
var modes = this.ui.toolbarModeLinks;
modes.removeClass('cms-btn-active').eq(1).addClass('cms-btn-active');
this.ui.html.removeClass('cms-structure-mode-structure').addClass('cms-structure-mode-content');
CMS.settings.mode = 'edit';
if (!init) {
this._saveStateInURL();
}
// hide canvas
return this._loadContent().then(this._hideBoard.bind(this));
}
/**
* Gets the id of the element.
* relies on cms-{item}-{id} to always be second in a string of classes (!)
*
* @method getId
* @param {jQuery} el element to get id from
* @returns {String}
*/
getId(el) {
// cancel if no element is defined
if (el === undefined || el === null || el.length <= 0) {
return false;
}
var id = null;
var cls = el.attr('class').split(' ')[1];
if (el.hasClass('cms-plugin')) {
id = cls.replace('cms-plugin-', '').trim();
} else if (el.hasClass('cms-draggable')) {
id = cls.replace('cms-draggable-', '').trim();
} else if (el.hasClass('cms-placeholder')) {
id = cls.replace('cms-placeholder-', '').trim();
} else if (el.hasClass('cms-dragbar')) {
id = cls.replace('cms-dragbar-', '').trim();
} else if (el.hasClass('cms-dragarea')) {
id = cls.replace('cms-dragarea-', '').trim();
}
return id;
}
/**
* Gets the ids of the list of elements.
*
* @method getIds
* @param {jQuery} els elements to get id from
* @returns {String[]}
*/
getIds(els) {
var that = this;
var array = [];
els.each(function() {
array.push(that.getId($(this)));
});
return array;
}
/**
* Actually shows the board canvas.
*
* @method _showBoard
* @param {Boolean} init init
* @private
*/
_showBoard(init) {
// set active item
var modes = this.ui.toolbarModeLinks;
modes.removeClass('cms-btn-active').eq(0).addClass('cms-btn-active');
this.ui.html.removeClass('cms-structure-mode-content').addClass('cms-structure-mode-structure');
this.ui.container.show();
hideLoader();
if (!init) {
this._makeCondensed();
}
if (init && !this._loadedContent) {
this._makeFullWidth();
}
this._preventScroll.start();
this.ui.window.trigger('resize');
}
_makeCondensed() {
this.condensed = true;
this.ui.container.addClass('cms-structure-condensed');
var url = new URI(window.location.href);
url.removeSearch('structure');
if (CMS.settings.mode === 'structure') {
history.replaceState({}, '', url.toString());
}
var width = this.ui.toolbar.width();
var scrollBarWidth = this.ui.window[0].innerWidth - width;
if (!scrollBarWidth) {
scrollBarWidth = measureScrollbar();
}
this.ui.html.removeClass('cms-overflow');
if (scrollBarWidth) {
// this.ui.toolbar.css('right', scrollBarWidth);
this.ui.container.css('right', -scrollBarWidth);
}
}
_makeFullWidth() {
this.condensed = false;
this.ui.container.removeClass('cms-structure-condensed');
var url = new URI(window.location.href);
url.addSearch('structure');
if (CMS.settings.mode === 'structure') {
history.replaceState({}, '', url.toString());
this.ui.html.addClass('cms-overflow');
}
this.ui.container.css('right', 0);
}
/**
* Hides the board canvas.
*
* @method _hideBoard
* @private
*/
_hideBoard() {
// hide elements
this.ui.container.hide();
this._preventScroll.stop();
// this is sometimes required for user-side scripts to
// render dynamic elements on the page correctly.
// e.g. you have a parallax script that calculates position
// of elements based on document height. but if the page is
// loaded with structureboard active - the document height
// would be same as screen height, which is likely incorrect,
// so triggering resize on window would force user scripts
// to recalculate whatever is required there
// istanbul ignore catch
triggerWindowResize();
}
/**
* Sets up all the sortables.
*
* @method _drag
* @param {jQuery} [elem=this.ui.sortables] which element to initialize
* @private
*/
_drag(elem = this.ui.sortables) {
var that = this;
elem
.nestedSortable({
items: '> .cms-draggable:not(.cms-draggable-disabled .cms-draggable)',
placeholder: 'cms-droppable',
connectWith: '.cms-draggables:not(.cms-hidden)',
tolerance: 'intersect',
toleranceElement: '> div',
dropOnEmpty: true,
// cloning huge structure is a performance loss compared to cloning just a dragitem
helper: function createHelper(e, item) {
var clone = item.find('> .cms-dragitem').clone();
clone.wrap('<div class="' + item[0].className + '"></div>');
return clone.parent();
},
appendTo: '.cms-structure-content',
// appendTo: '.cms',
cursor: 'move',
cursorAt: { left: -15, top: -15 },
opacity: 1,
zIndex: 9999999,
delay: 100,
tabSize: 15,
// nestedSortable
listType: 'div.cms-draggables',
doNotClear: true,
disableNestingClass: 'cms-draggable-disabled',
errorClass: 'cms-draggable-disallowed',
scrollSpeed: 15,
// eslint-disable-next-line no-magic-numbers
scrollSensitivity: that.ui.window.height() * 0.2,
start: function(e, ui) {
that.ui.content.attr('data-touch-action', 'none');
originalPluginContainer = ui.item.closest('.cms-draggables');
that.dragging = true;
// show empty
StructureBoard.actualizePlaceholders();
// ensure all menus are closed
Plugin._hideSettingsMenu();
// keep in mind that caching cms-draggables query only works
// as long as we don't create them on the fly
that.ui.sortables.each(function() {
var element = $(this);
if (element.children().length === 0) {
element.removeClass('cms-hidden');
}
});
// fixes placeholder height
ui.item.addClass('cms-is-dragging');
ui.helper.addClass('cms-draggable-is-dragging');
if (ui.item.find('> .cms-draggables').children().length) {
ui.helper.addClass('cms-draggable-stack');
}
// attach escape event to cancel dragging
that.ui.doc.on('keyup.cms.interrupt', function(event, cancel) {
if ((event.keyCode === KEYS.ESC && that.dragging) || cancel) {
that.state = false;
$.ui.sortable.prototype._mouseStop();
that.ui.sortables.trigger('mouseup');
}
});
},
beforeStop: function(event, ui) {
that.dragging = false;
ui.item.removeClass('cms-is-dragging cms-draggable-stack');
that.ui.doc.off('keyup.cms.interrupt');
that.ui.content.attr('data-touch-action', 'pan-y');
},
update: function(event, ui) {
// cancel if isAllowed returns false
if (!that.state) {
return false;
}
var newPluginContainer = ui.item.closest('.cms-draggables');
if (originalPluginContainer.is(newPluginContainer)) {
// if we moved inside same container,
// but event is fired on a parent, discard update
if (!newPluginContainer.is(this)) {
return false;
}
} else {
StructureBoard.actualizePluginsCollapsibleStatus(
newPluginContainer.add(originalPluginContainer)
);
}
// we pass the id to the updater which checks within the backend the correct place
var id = that.getId(ui.item);
var plugin = $(`.cms-draggable-${id}`);
var eventData = {
id: id
};
var previousParentPlugin = originalPluginContainer.closest('.cms-draggable');
if (previousParentPlugin.length) {
var previousParentPluginId = that.getId(previousParentPlugin);
eventData.previousParentPluginId = previousParentPluginId;
}
// check if we copy/paste a plugin or not
if (originalPluginContainer.hasClass('cms-clipboard-containers')) {
originalPluginContainer.html(plugin.eq(0).clone(true, true));
Plugin._updateClipboard();
plugin.trigger('cms-paste-plugin-update', [eventData]);
} else {
plugin.trigger('cms-plugins-update', [eventData]);
}
// reset placeholder without entries
that.ui.sortables.each(function() {
var element = $(this);
if (element.children().length === 0) {
element.addClass('cms-hidden');
}
});
StructureBoard.actualizePlaceholders();
},
// eslint-disable-next-line complexity
isAllowed: function(placeholder, placeholderParent, originalItem) {
// cancel if action is executed
if (CMS.API.locked) {
return false;
}
// getting restriction array
var bounds = [];
var immediateParentType;
if (placeholder && placeholder.closest('.cms-clipboard-containers').length) {
return false;
}
// if parent has class disabled, dissalow drop
if (placeholder && placeholder.parent().hasClass('cms-draggable-disabled')) {
return false;
}
var originalItemId = that.getId(originalItem);
// save original state events
var original = $('.cms-draggable-' + originalItemId);
// cancel if item has no settings
if (original.length === 0 || !original.data('cms')) {
return false;
}
var originalItemData = original.data('cms');
var parent_bounds = $.grep(originalItemData.plugin_parent_restriction, function(r) {
// special case when PlaceholderPlugin has a parent restriction named "0"
return r !== '0';
});
var type = originalItemData.plugin_type;
// prepare variables for bound
var holderId = that.getId(placeholder.closest('.cms-dragarea'));
var holder = $('.cms-placeholder-' + holderId);
var plugin;
if (placeholderParent && placeholderParent.length) {
// placeholderParent is always latest, it maybe that
// isAllowed is called _before_ placeholder is moved to a child plugin
plugin = $('.cms-draggable-' + that.getId(placeholderParent.closest('.cms-draggable')));
} else {
plugin = $('.cms-draggable-' + that.getId(placeholder.closest('.cms-draggable')));
}
// now set the correct bounds
// istanbul ignore else
if (holder.length) {
bounds = holder.data('cms').plugin_restriction;
immediateParentType = holder.data('cms').plugin_type;
}
if (plugin.length) {
bounds = plugin.data('cms').plugin_restriction;
immediateParentType = plugin.data('cms').plugin_type;
}
// if restrictions is still empty, proceed
that.state = !(bounds.length && $.inArray(type, bounds) === -1);
// check if we have a parent restriction
if (parent_bounds.length) {
that.state = $.inArray(immediateParentType, parent_bounds) !== -1;
}
return that.state;
}
})
.on('cms-structure-update', StructureBoard.actualizePlaceholders);
}
_dragRefresh() {
this.ui.sortables.each((i, el) => {
const element = $(el);
if (element.data('mjsNestedSortable')) {
return;
}
this._drag(element);
});
}
/**
* @method invalidateState
* @param {String} action - action to handle
* @param {Object} data - data required to handle the object
* @param {Object} opts
* @param {Boolean} [opts.propagate=true] - should we propagate the change to other tabs or not
*/
// eslint-disable-next-line complexity
invalidateState(action, data, { propagate = true } = {}) {
// eslint-disable-next-line default-case
switch (action) {
case 'COPY': {
this.handleCopyPlugin(data);
break;
}
case 'ADD': {
this.handleAddPlugin(data);
break;
}
case 'EDIT': {
this.handleEditPlugin(data);
break;
}
case 'DELETE': {
this.handleDeletePlugin(data);
break;
}
case 'CLEAR_PLACEHOLDER': {
this.handleClearPlaceholder(data);
break;
}
case 'PASTE':