-
Notifications
You must be signed in to change notification settings - Fork 23.2k
/
snippets.editor.js
4860 lines (4580 loc) · 200 KB
/
snippets.editor.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
/** @odoo-module **/
import { clamp } from "@web/core/utils/numbers";
import { ConfirmationDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
import { useService, useBus } from "@web/core/utils/hooks";
import dom from "@web/legacy/js/core/dom";
import Widget from "@web/legacy/js/core/widget";
import { useDragAndDrop } from "@web_editor/js/editor/drag_and_drop";
import options from "@web_editor/js/editor/snippets.options";
import weUtils from "@web_editor/js/common/utils";
import * as gridUtils from "@web_editor/js/common/grid_layout_utils";
import { escape } from "@web/core/utils/strings";
import { closestElement, isUnremovable } from "@web_editor/js/editor/odoo-editor/src/utils/utils";
import { debounce, throttleForAnimation } from "@web/core/utils/timing";
import { uniqueId } from "@web/core/utils/functions";
import { sortBy, unique } from "@web/core/utils/arrays";
import { browser } from "@web/core/browser/browser";
import { Toolbar } from "@web_editor/js/editor/toolbar";
import {
Component,
EventBus,
markup,
onMounted,
onWillStart,
onWillUnmount,
useEffect,
useRef,
useState,
} from "@odoo/owl";
import { LinkTools } from '@web_editor/js/wysiwyg/widgets/link_tools';
import { touching, closest, addLoadingEffect as addButtonLoadingEffect } from "@web/core/utils/ui";
import { _t } from "@web/core/l10n/translation";
import { renderToElement } from "@web/core/utils/render";
import { RPCError } from "@web/core/network/rpc";
import { ColumnLayoutMixin } from "@web_editor/js/common/column_layout_mixin";
import { Tooltip as OdooTooltip } from "@web/core/tooltip/tooltip";
let cacheSnippetTemplate = {};
var globalSelector = {
closest: () => $(),
all: () => $(),
is: () => false,
};
/**
* Management of the overlay and option list for a snippet.
*/
var SnippetEditor = Widget.extend({
template: 'web_editor.snippet_overlay',
events: {
'click .oe_snippet_remove': '_onRemoveClick',
'wheel': '_onMouseWheel',
'click .o_send_back': '_onSendBackClick',
'click .o_bring_front': '_onBringFrontClick',
},
custom_events: {
'option_update': '_onOptionUpdate',
'user_value_widget_request': '_onUserValueWidgetRequest',
'snippet_option_visibility_update': '_onSnippetOptionVisibilityUpdate',
},
layoutElementsSelector: [
'.o_we_shape',
'.o_we_bg_filter',
].join(','),
/**
* @constructor
* @param {Widget} parent
* @param {Element} target
* @param {Object} templateOptions
* @param {jQuery} $editable
* @param {Object} options
*/
init: function (parent, target, templateOptions, $editable, options) {
this._super.apply(this, arguments);
this.options = options;
// This is possible to have a snippet editor not inside an editable area
// (data-no-check="true") and it is possible to not have editable areas
// at all (restricted editor), in that case we just suppose this is the
// body so related code can still be executed without crash (as we still
// need to instantiate instances of editors even if nothing is really
// editable (data-no-check="true" / navigation options / ...)).
// TODO this should probably be reviewed in master: do we need a
// reference to the editable area? There should be workarounds.
this.$editable = $editable && $editable.length ? $editable : $(document.body);
this.ownerDocument = this.$editable[0].ownerDocument;
this.$body = $(this.ownerDocument.body);
this.$target = $(target);
this.$target.data('snippet-editor', this);
this.templateOptions = templateOptions;
this.isTargetParentEditable = false;
this.isTargetMovable = false;
this.$scrollingElement = $().getScrollingElement(this.$editable[0].ownerDocument);
if (!this.$scrollingElement[0]) {
this.$scrollingElement = $(this.ownerDocument).find('.o_editable');
}
this.displayOverlayOptions = false;
this._$toolbarContainer = $();
this.__isStarted = new Promise(resolve => {
this.__isStartedResolveFunc = resolve;
});
},
/**
* @override
*/
start: function () {
var defs = [this._super.apply(this, arguments)];
// Initialize the associated options (see snippets.options.js)
defs.push(this._initializeOptions());
var $customize = this._customize$Elements[this._customize$Elements.length - 1];
this.isTargetParentEditable = this.$target.parent().is(':o_editable');
this.isTargetMovable = this.isTargetParentEditable && this.isTargetMovable && !this.$target.hasClass('oe_unmovable');
this.isTargetRemovable = this.isTargetParentEditable && !this.$target.parent().is('[data-oe-type="image"]') && !isUnremovable(this.$target[0]);
this.displayOverlayOptions = this.displayOverlayOptions || this.isTargetMovable || !this.isTargetParentEditable;
// Initialize move/clone/remove buttons
if (this.isTargetMovable) {
this.dropped = false;
this.draggableComponent = this._initDragAndDrop(".o_move_handle", ".oe_overlay", this.el);
if (!this.$target[0].matches("section")) {
// Allow the user to drag the image itself to move the target.
// Note that the o_draggable class will be added by the
// _initDragAndDrop function. So adding it here is probably
// useless. To check. The fact that that class is added in any
// case should probably reviewed in master anyway (TODO).
this.$target[0].classList.add("o_draggable");
this.draggableComponentImgs = this._initDragAndDrop("img", ".o_draggable", this.$target[0]);
}
} else {
this.$('.o_overlay_move_options').addClass('d-none');
const cloneButtonEl = $customize[0].querySelector(".oe_snippet_clone");
cloneButtonEl.classList.toggle("d-none", !this.forceDuplicateButton);
}
if (!this.isTargetRemovable) {
this.$el.add($customize).find('.oe_snippet_remove').addClass('d-none');
}
var _animationsCount = 0;
this.postAnimationCover = throttleForAnimation(() => {
this.trigger_up('cover_update', {
overlayVisible: true,
});
});
this.$target.on('transitionstart.snippet_editor, animationstart.snippet_editor', () => {
// We cannot rely on the fact each transition/animation start will
// trigger a transition/animation end as the element may be removed
// from the DOM before or it could simply be an infinite animation.
//
// By simplicity, for each start, we add a delayed operation that
// will decrease the animation counter after a fixed duration and
// do the post animation cover if none is registered anymore.
_animationsCount++;
setTimeout(() => {
if (!--_animationsCount) {
this.postAnimationCover();
}
}, 500); // This delay have to be huge enough to take care of long
// animations which will not trigger an animation end event
// but if it is too small for some, this is the job of the
// animation creator to manually ask for a re-cover
});
// On top of what is explained above, do the post animation cover for
// each detected transition/animation end so that the user does not see
// a flickering when not needed.
this.$target.on('transitionend.snippet_editor, animationend.snippet_editor', this.postAnimationCover);
return Promise.all(defs).then(() => {
this.__isStartedResolveFunc(this);
});
},
/**
* @override
*/
destroy: function () {
// Before actually destroying a snippet editor, notify the parent
// about it so that it can update its list of alived snippet editors.
this.trigger_up('snippet_editor_destroyed');
this.draggableComponent && this.draggableComponent.destroy();
this.draggableComponentImgs?.destroy();
if (this.$optionsSection) {
this.$optionsSection.remove();
}
if (this.postAnimationCover) {
this.postAnimationCover.cancel();
}
this._super(...arguments);
this.$target.removeData('snippet-editor');
this.$target.off('.snippet_editor');
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Checks whether the snippet options are shown or not.
*
* @returns {boolean}
*/
areOptionsShown: function () {
const lastIndex = this._customize$Elements.length - 1;
return !!this._customize$Elements[lastIndex].parent().length;
},
/**
* Notifies all the associated snippet options that the snippet has just
* been dropped in the page.
*
* @param {HTMLElement} targetEl the snippet dropped in the page
*/
async buildSnippet(targetEl) {
for (var i in this.styles) {
await this.styles[i].onBuilt({
isCurrent: targetEl === this.$target[0],
});
}
await this.toggleTargetVisibility(true, true);
},
/**
* Notifies all the associated snippet options that the template which
* contains the snippet is about to be saved.
*/
cleanForSave: async function () {
if (this.isDestroyed()) {
return;
}
await this.toggleTargetVisibility(!this.$target.hasClass('o_snippet_invisible')
&& !this.$target.hasClass('o_snippet_mobile_invisible')
&& !this.$target.hasClass('o_snippet_desktop_invisible'));
const proms = Object.values(this.styles).map((option) => {
return option.cleanForSave();
});
await Promise.all(proms);
await this.cleanUI();
},
/**
* Notifies all the associated snippet options that the snippet UI needs to
* be cleaned.
*/
async cleanUI() {
const proms = Object.values(this.styles).map((option) => {
return option.cleanUI();
});
await Promise.all(proms);
},
/**
* Closes all widgets of all options.
*/
closeWidgets: function () {
if (!this.styles || !this.areOptionsShown()) {
return;
}
Object.keys(this.styles).forEach(key => {
this.styles[key].closeWidgets();
});
},
/**
* Makes the editor overlay cover the associated snippet.
*/
cover: function () {
if (!this.isShown() || !this.$target.length) {
return;
}
const $modal = this.$target.find('.modal:visible');
const $target = $modal.length ? $modal : this.$target;
const targetEl = $target[0];
// Check first if the target is still visible, otherwise we have to
// hide it. When covering all element after scroll for instance it may
// have been hidden (part of an affixed header for example) or it may
// be outside of the viewport (the whole header during an effect for
// example).
const rect = targetEl.getBoundingClientRect();
// TODO: At that point, targetEl.ownerDocument.defaultView should not be
// null. However, there is a non-deterministic race condition that can
// result in the document being unloaded from the iframe before the handlers
// of the snippets menu are removed, thus triggering a traceback if the
// optional chaining operator is removed. This can be reproduced
// non-deterministically on runbot by running the edit_menus tour.
const vpWidth = targetEl.ownerDocument.defaultView?.innerWidth || document.documentElement.clientWidth;
const vpHeight = targetEl.ownerDocument.defaultView?.innerHeight || document.documentElement.clientHeight;
const isInViewport = (
rect.bottom > -0.1 &&
rect.right > -0.1 &&
(vpHeight - rect.top) > -0.1 &&
(vpWidth - rect.left) > -0.1
);
const hasSize = ( // :visible not enough for images
Math.abs(rect.bottom - rect.top) > 0.01 &&
Math.abs(rect.right - rect.left) > 0.01
);
if (!isInViewport || !hasSize || !this.$target.is(`:visible`)) {
this.toggleOverlayVisibility(false);
return;
}
const transform = window.getComputedStyle(targetEl).getPropertyValue('transform');
const transformOrigin = window.getComputedStyle(targetEl).getPropertyValue('transform-origin');
targetEl.classList.add('o_transform_removal');
// Now cover the element
const offset = $target.offset();
// The manipulator is supposed to follow the scroll of the content
// naturally without any JS recomputation.
const manipulatorOffset = this.$el.parent().offset();
offset.top -= manipulatorOffset.top;
offset.left -= manipulatorOffset.left;
this.$el.css({
width: $target.outerWidth(),
height: $target.outerHeight(),
left: offset.left,
top: offset.top,
transform,
'transform-origin': transformOrigin,
});
this.$('.o_handles').css('height', $target.outerHeight());
targetEl.classList.remove('o_transform_removal');
const editableOffsetTop = this.$editable.offset().top - manipulatorOffset.top;
this.$el.toggleClass('o_top_cover', offset.top - editableOffsetTop < 25);
// If the element covered by the overlay has a scrollbar, we remove its
// right border as it interferes with proper scrolling. (e.g. modal)
const handleEReadonlyEl = this.$el[0].querySelector('.o_handle.e.readonly');
if (handleEReadonlyEl) {
handleEReadonlyEl.style.width = $(targetEl).hasScrollableContent() ? 0 : '';
}
},
/**
* DOMElements have a default name which appears in the overlay when they
* are being edited. This method retrieves this name; it can be defined
* directly in the DOM thanks to the `data-name` attribute.
*/
getName: function () {
if (this.$target.data('name') !== undefined) {
return this.$target.data('name');
}
if (this.$target.is('img')) {
return _t("Image");
}
if (this.$target.is('.fa')) {
return _t("Icon");
}
if (this.$target.is('.media_iframe_video')) {
return _t("Video");
}
if (this.$target.parent('.row').length) {
return _t("Column");
}
if (this.$target.is('#wrapwrap > main')) {
return _t("Page Options");
}
if (this.$target[0].matches(".btn")) {
return _t("Button");
}
return _t("Block");
},
/**
* @return {boolean}
*/
isShown: function () {
return this.$el && this.$el.parent().length && this.$el.hasClass('oe_active');
},
/**
* @returns {boolean}
*/
isSticky: function () {
return this.$el && this.$el.hasClass('o_we_overlay_sticky');
},
/**
* @returns {boolean}
*/
isTargetVisible: function () {
return (this.$target[0].dataset.invisible !== '1');
},
/**
* Removes the associated snippet from the DOM and destroys the associated
* editor (itself).
*
* @param {boolean} [shouldRecordUndo=true]
* @returns {Promise}
*/
removeSnippet: async function (shouldRecordUndo = true) {
this.options.wysiwyg.odooEditor.unbreakableStepUnactive();
this.toggleOverlay(false);
await this.toggleOptions(false);
// If it is an invisible element, we must close it before deleting it
// (e.g. modal).
await this.toggleTargetVisibility(!this.$target.hasClass('o_snippet_invisible'));
this.trigger_up('will_remove_snippet', {$target: this.$target});
// Call the onRemove of all internal options
await new Promise(resolve => {
this.trigger_up('call_for_each_child_snippet', {
$snippet: this.$target,
callback: async function (editor, $snippet) {
for (var i in editor.styles) {
await editor.styles[i].onRemove();
}
},
onSuccess: resolve,
});
});
// TODO this should probably be awaited but this is not possible right
// now as removeSnippet can be called in a locked editor mutex context
// and would thus produce a deadlock. Also, this awaited
// 'activate_snippet' call would allow to remove the 'toggleOverlay' and
// 'toggleOptions' calls at the start of this function.
// TODO also to be checked: this not being awaited, the DOM is removed
// first, destroying the related editors and not calling onBlur... to
// check if this has always been like this or not and this should be
// unit tested.
let parent = this.$target[0].parentElement;
let nextSibling = this.$target[0].nextElementSibling;
while (nextSibling && nextSibling.matches('.o_snippet_invisible')) {
nextSibling = nextSibling.nextElementSibling;
}
let previousSibling = this.$target[0].previousElementSibling;
while (previousSibling && previousSibling.matches('.o_snippet_invisible')) {
previousSibling = previousSibling.previousElementSibling;
}
if ($(parent).is('.o_editable:not(body)')) {
// If we target the editable, we want to reset the selection to the
// body. If the editable has options, we do not want to show them.
parent = $(parent).closest('body');
}
const activateSnippetProm = new Promise(resolve => {
this.trigger_up('activate_snippet', {
$snippet: $(previousSibling || nextSibling || parent),
onSuccess: resolve,
});
});
// Actually remove the snippet and its option UI.
var $parent = this.$target.parent();
this.$target.find('*').addBack().each((index, el) => {
const tooltip = Tooltip.getInstance(el);
if (tooltip) {
tooltip.dispose();
}
});
this.$target.remove();
this.$el.remove();
// Resize the grid to have the correct row count.
// Must be done here and not in a dedicated onRemove method because
// onRemove is called before actually removing the element and it
// should be the case in order to resize the grid.
if (this.$target[0].classList.contains('o_grid_item')) {
gridUtils._resizeGrid($parent[0]);
}
var node = $parent[0];
if (node && node.firstChild) {
if (!node.firstChild.tagName && node.firstChild.textContent === ' ') {
node.removeChild(node.firstChild);
}
}
// Potentially remove ancestors (like when removing the last column of a
// snippet).
if ($parent.closest(':data("snippet-editor")').length) {
const isEmptyAndRemovable = ($el, editor) => {
editor = editor || $el.data('snippet-editor');
const isEmpty = $el.text().trim() === ''
&& $el.children().toArray().every(el => {
// Consider layout-only elements (like bg-shapes) as empty
return el.matches(this.layoutElementsSelector);
});
return isEmpty && !$el.hasClass('oe_structure')
&& !$el.parent().hasClass('carousel-item')
&& (!editor || editor.isTargetParentEditable)
&& !isUnremovable($el[0]);
};
var editor = $parent.data('snippet-editor');
while (!editor) {
var $nextParent = $parent.parent();
if (isEmptyAndRemovable($parent)) {
$parent.remove();
}
$parent = $nextParent;
editor = $parent.data('snippet-editor');
}
if (isEmptyAndRemovable($parent, editor)) {
// TODO maybe this should be part of the actual Promise being
// returned by the function ?
setTimeout(() => editor.removeSnippet());
}
}
// Clean editor if they are image or table in deleted content
this.$body.find('.note-control-selection').hide();
this.$body.find('.o_table_handler').remove();
this.trigger_up('snippet_removed');
// FIXME that whole Promise should be awaited before the DOM removal etc
// as explained above where it is defined. However, it is critical to at
// least await it before destroying the snippet editor instance
// otherwise the logic of activateSnippet gets messed up.
// FIXME should not this call _destroyEditor ?
activateSnippetProm.then(() => this.destroy());
$parent.trigger('content_changed');
// TODO Page content changed, some elements may need to be adapted
// according to it. While waiting for a better way to handle that this
// window trigger will handle most cases.
$(window).trigger('resize');
if (shouldRecordUndo) {
this.options.wysiwyg.odooEditor.historyStep();
}
},
/**
* Displays/Hides the editor overlay.
*
* @param {boolean} show
* @param {boolean} [previewMode=false]
*/
toggleOverlay: function (show, previewMode) {
if (!this.$el) {
return;
}
if (previewMode) {
// In preview mode, the sticky classes are left untouched, we only
// add/remove the preview class when toggling/untoggling
this.$el.toggleClass('o_we_overlay_preview', show);
} else {
// In non preview mode, the preview class is always removed, and the
// sticky class is added/removed when toggling/untoggling
this.$el.removeClass('o_we_overlay_preview');
this.$el.toggleClass('o_we_overlay_sticky', show);
if (!this.displayOverlayOptions) {
this.$el.find('.o_overlay_options_wrap').addClass('o_we_hidden_overlay_options');
}
}
// Show/hide overlay in preview mode or not
this.$el.toggleClass('oe_active', show);
this.cover();
this.toggleOverlayVisibility(show);
},
/**
* Updates the UI of the editor (+ parent) options and call onFocus/onBlur
* if necessary. The UI jquery elements to display are returned, it is up
* to the caller to actually display them or not.
*
* @param {boolean} show
* @returns {Promise<jQuery[]>}
*/
async toggleOptions(show) {
if (!this.$el) {
return [];
}
if (this.areOptionsShown() === show) {
return null;
}
// All onFocus before all ui updates as the onFocus of an option might
// affect another option (like updating the $target)
const editorUIsToUpdate = [];
const focusOrBlur = show
? async (editor, options) => {
for (const opt of options) {
await opt.onFocus();
}
editorUIsToUpdate.push(editor);
}
: async (editor, options) => {
for (const opt of options) {
await opt.onBlur();
}
};
for (const $el of this._customize$Elements) {
const editor = $el.data('editor');
const styles = sortBy(Object.values(editor.styles || {}), "__order");
await focusOrBlur(editor, styles);
}
await Promise.all(editorUIsToUpdate.map(editor => editor.updateOptionsUI()));
await Promise.all(editorUIsToUpdate.map(editor => editor.updateOptionsUIVisibility()));
// As the 'd-none' class is added to option sections that have no visible
// options with 'updateOptionsUIVisibility', if no option section is
// visible, we prevent the activation of the options.
// Special case: For now, we only allow activating text options in
// translate mode (with no parent editors). These text options have a
// special way to be displayed in the editor: We add the options in the
// toolbar `onFocus()` and set them back `onBlur()`. Which means the
// options section will be empty and get a `d-none` class, while
// actually it has visible options (they are just added in the toolbar
// DOM). We need to take them into consideration to display options in
// translate mode correctly.
const optionsSectionVisible = editorUIsToUpdate.some(editor =>
!editor.$optionsSection[0].classList.contains("d-none") ||
Object.keys(editor.styles).some(key =>
editor.styles[key].el.closest(".oe-toolbar")
)
);
if (editorUIsToUpdate.length > 0 && !optionsSectionVisible) {
return null;
}
return this._customize$Elements;
},
/**
* @param {boolean} [show]
* @param {boolean} [ignoreDeviceVisibility]
* @returns {Promise<boolean>}
*/
toggleTargetVisibility: async function (show, ignoreDeviceVisibility) {
show = this._toggleVisibilityStatus(show, ignoreDeviceVisibility);
var styles = Object.values(this.styles);
const proms = sortBy(styles, "__order").map((style) => {
return show ? style.onTargetShow() : style.onTargetHide();
});
await Promise.all(proms);
return show;
},
/**
* @param {boolean} [show=false]
*/
toggleOverlayVisibility: function (show) {
if (this.$el && !this.scrollingTimeout) {
this.$el.toggleClass('o_overlay_hidden', (!show || this.$target[0].matches('.o_animating:not(.o_animate_on_scroll)')) && this.isShown());
}
},
/**
* Updates the UI of all the options according to the status of their
* associated editable DOM. This does not take care of options *visibility*.
* For that @see updateOptionsUIVisibility, which should called when the UI
* is up-to-date thanks to the function here, as the visibility depends on
* the UI's status.
*
* @param {boolean} [assetsChanged=false]
* @returns {Promise}
*/
async updateOptionsUI(assetsChanged) {
const proms = Object.values(this.styles).map(opt => {
return opt.updateUI({noVisibility: true, assetsChanged: assetsChanged});
});
return Promise.all(proms);
},
/**
* Updates the visibility of the UI of all the options according to the
* status of their associated dependencies and related editable DOM status.
*
* @returns {Promise}
*/
async updateOptionsUIVisibility() {
const proms = Object.values(this.styles).map(opt => {
return opt.updateUIVisibility();
});
await Promise.all(proms);
// Hide the snippetEditor if none of its options are visible
// This cannot be done using the visibility of the options' UI
// because some options can be located in the overlay.
const $visibleOptions = this.$optionsSection.find('we-top-button-group, we-customizeblock-option')
.children(':not(.d-none)');
this.$optionsSection.toggleClass('d-none', !$visibleOptions.length);
},
/**
* Clones the current snippet.
*
* @param {boolean} recordUndo
*/
clone: async function (recordUndo) {
this.trigger_up('snippet_will_be_cloned', {$target: this.$target});
await new Promise(resolve => {
this.trigger_up("clean_ui_request", {
targetEl: this.$target[0],
onSuccess: resolve,
});
});
var $clone = this.$target.clone(false);
this.$target.after($clone);
if (recordUndo) {
this.options.wysiwyg.odooEditor.historyStep(true);
}
await new Promise(resolve => {
this.trigger_up('call_for_each_child_snippet', {
$snippet: $clone,
callback: function (editor, $snippet) {
for (var i in editor.styles) {
editor.styles[i].onClone({
isCurrent: ($snippet.is($clone)),
});
}
},
onSuccess: resolve,
});
});
this.trigger_up('snippet_cloned', {$target: $clone, $origin: this.$target});
$clone.trigger('content_changed');
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Instantiates the snippet's options.
*
* @private
*/
_initializeOptions: function () {
this._customize$Elements = [];
this.styles = {};
this.selectorSiblings = [];
this.selectorChildren = [];
this.selectorLockWithin = new Set();
const selectorExcludeAncestor = new Set();
var $element = this.$target.parent();
while ($element.length) {
var parentEditor = $element.data('snippet-editor');
if (parentEditor) {
this._customize$Elements = this._customize$Elements
.concat(parentEditor._customize$Elements);
break;
}
$element = $element.parent();
}
var $optionsSection = $(renderToElement('web_editor.customize_block_options_section', {
name: this.getName(),
})).data('editor', this);
const $optionsSectionBtnGroup = $optionsSection.find('we-top-button-group');
$optionsSectionBtnGroup.contents().each((i, node) => {
if (node.nodeType === Node.TEXT_NODE) {
node.parentNode.removeChild(node);
}
});
this.$optionsSection = $optionsSection;
$optionsSection.on('mouseenter', this._onOptionsSectionMouseEnter.bind(this));
$optionsSection.on('mouseleave', this._onOptionsSectionMouseLeave.bind(this));
$optionsSection.on('click', 'we-title > span', this._onOptionsSectionClick.bind(this));
$optionsSection.on('click', '.oe_snippet_clone', this._onCloneClick.bind(this));
$optionsSection.on('click', '.oe_snippet_remove', this._onRemoveClick.bind(this));
this._customize$Elements.push($optionsSection);
// TODO get rid of this when possible (made as a fix to support old
// theme options)
this.$el.data('$optionsSection', $optionsSection);
var i = 0;
var defs = this.templateOptions.map((val) => {
if (!val.selector.is(this.$target)) {
return;
}
if (val.data.string) {
$optionsSection[0].querySelector('we-title > span').textContent = val.data.string;
}
if (val['drop-near']) {
this.selectorSiblings.push(val['drop-near']);
}
if (val['drop-in']) {
this.selectorChildren.push(val['drop-in']);
}
if (val['drop-lock-within']) {
this.selectorLockWithin.add(val['drop-lock-within']);
}
if (val['drop-exclude-ancestor']) {
selectorExcludeAncestor.add(val['drop-exclude-ancestor']);
}
var optionName = val.option;
var option = new (options.registry[optionName] || options.Class)(
this,
val.$el.children(),
val.base_target ? this.$target.find(val.base_target).eq(0) : this.$target,
this.$el,
Object.assign({
optionName: optionName,
snippetName: this.getName(),
}, val.data),
this.options
);
var key = optionName || uniqueId("option");
if (this.styles[key]) {
// If two snippet options use the same option name (and so use
// the same JS option), store the subsequent ones with a unique
// ID (TODO improve)
key = uniqueId(key);
}
this.styles[key] = option;
option.__order = i++;
if (option.forceNoDeleteButton) {
this.$el.add($optionsSection).find('.oe_snippet_remove').addClass('d-none');
this.$el.add($optionsSection).find('.oe_snippet_clone').addClass('d-none');
}
if (option.displayOverlayOptions) {
this.displayOverlayOptions = true;
}
if (option.forceDuplicateButton) {
this.forceDuplicateButton = true;
}
return option.appendTo(document.createDocumentFragment());
});
if (selectorExcludeAncestor.size) {
// Prevents dropping an element into another one.
// (E.g. ToC inside another ToC)
const excludedAncestorSelector = [...selectorExcludeAncestor].join(", ");
this.excludeAncestors = (i, el) => !el.closest(excludedAncestorSelector);
}
this.isTargetMovable = (this.selectorSiblings.length > 0 || this.selectorChildren.length > 0);
this.$el.find('[data-bs-toggle="dropdown"]').dropdown();
return Promise.all(defs).then(async () => {
const options = sortBy(Object.values(this.styles), "__order");
const firstOptions = [];
options.forEach(option => {
if (option.isTopOption) {
if (option.isTopFirstOption) {
firstOptions.push(option);
} else {
$optionsSectionBtnGroup.prepend(option.$el);
}
} else {
$optionsSection.append(option.$el);
}
});
firstOptions.forEach(option => {
$optionsSectionBtnGroup.prepend(option.$el);
});
$optionsSection.toggleClass('d-none', options.length === 0);
});
},
/**
* Initialize drag and drop handlers.
*
* @private
* @param {String} handle css selector for grabble element
* @param {String} elementsSelector selector for elements that will be dragged.
* @param {HTMLElement} element element to listen for drag events.
* @returns {Object} the drag state.
*/
_initDragAndDrop(handle, elementsSelector, element) {
const modalAncestorEl = this.$target[0].closest('.modal');
const $scrollable = modalAncestorEl && $(modalAncestorEl)
|| (this.options.$scrollable)
|| (this.$scrollingElement.length && this.$scrollingElement)
|| $().getScrollingElement(this.ownerDocument);
const dragAndDropOptions = {
ref: { el: element },
elements: elementsSelector,
handle: handle,
scrollingElement: $scrollable[0],
enable: () => !!this.$el.find('.o_move_handle:visible').length || this.dragStarted,
helper: () => {
const cloneEl = this.$el[0].cloneNode(true);
cloneEl.style.width = "24px";
cloneEl.style.height = "24px";
cloneEl.style.border = "0";
this.$el[0].ownerDocument.body.appendChild(cloneEl);
cloneEl.classList.remove("d-none");
cloneEl.classList.remove("o_dragged");
return cloneEl;
},
onDragStart: (args) => {
this.dragStarted = true;
const targetRect = this.$target[0].getBoundingClientRect();
// Bound the Y mouse position to the element height minus one
// grid row, to be able to drag from the bottom in a grid.
const gridRowSize = gridUtils.rowSize;
const boundedYMousePosition = Math.min(args.y, targetRect.bottom - gridRowSize);
this.mousePositionYOnElement = boundedYMousePosition - targetRect.y;
this.mousePositionXOnElement = args.x - targetRect.x;
this._onDragAndDropStart(args);
},
onDragEnd: (...args) => {
if (!this.dragStarted) {
return false;
}
this.dragStarted = false;
// Delay our stop handler so that some wysiwyg handlers
// which occur on mouseup (and are themself delayed) are
// executed first (this prevents the library to crash
// because our stop handler may change the DOM).
setTimeout(() => {
this._onDragAndDropStop(...args);
}, 0);
},
onDrag: this._onDragMove.bind(this),
dropzoneOver: this.dropzoneOver.bind(this),
dropzoneOut: this.dropzoneOut.bind(this),
dropzones: () => this.$dropZones?.toArray() || [],
};
const finalOptions = this.options.getDragAndDropOptions(dragAndDropOptions);
return useDragAndDrop(finalOptions);
},
/**
* @private
* @param {boolean} [show]
* @param {boolean} [ignoreDeviceVisibility]
* @returns {boolean}
*/
_toggleVisibilityStatus: function (show, ignoreDeviceVisibility) {
if (ignoreDeviceVisibility) {
if (this.$target[0].matches(".o_snippet_mobile_invisible, .o_snippet_desktop_invisible")) {
const isMobilePreview = weUtils.isMobileView(this.$target[0]);
const isMobileHidden = this.$target[0].classList.contains("o_snippet_mobile_invisible");
if (isMobilePreview === isMobileHidden) {
// Preview mode and hidden type are the same.
show = false;
}
}
}
if (show === undefined) {
show = !this.isTargetVisible();
}
if (show) {
delete this.$target[0].dataset.invisible;
} else {
this.$target[0].dataset.invisible = '1';
}
return show;
},
/**
* Returns false if the element matches a snippet block that cannot be
* dropped in a sanitized HTML field or a string representing a specific
* reason. Returns true if no such issue exists.
*
* @param {Element} el
* @return {boolean|str} str indicates a specific type of forbidden sanitization
*/
_canBeSanitizedUnless(el) {
let result = true;
for (const snippetEl of [el, ...el.querySelectorAll('[data-snippet]')]) {
this.trigger_up('find_snippet_template', {
snippet: snippetEl,
callback: function (snippet) {
const forbidSanitize = snippet.data.oeForbidSanitize;
if (forbidSanitize) {
result = forbidSanitize === 'form' ? 'form' : false;
}
},
});
// If some element in the block is already fully non-sanitizable,
// the whole block cannot be sanitized.
if (!result) {
break;
}
}
return result;
},
/**
* Called when an "over" dropzone event happens after an other "over"
* without an "out" between them. It escapes the previous dropzone.
*
* @private
* @param {Object} self
* the same `self` variable as when we are in `_onDragAndDropStart`
* @param {Element} currentDropzoneEl
* the dropzone over which we are currently dragging
*/
_outPreviousDropzone(self, currentDropzoneEl) {
const previousDropzoneEl = this;
const rowEl = previousDropzoneEl.parentNode;
if (rowEl.classList.contains('o_grid_mode')) {
self.dragState.gridMode = false;
const fromGridToGrid = currentDropzoneEl.classList.contains('oe_grid_zone');
if (fromGridToGrid) {
// If we went from a grid dropzone to an other grid one.
rowEl.style.removeProperty('position');
} else {
// If we went from a grid dropzone to a normal one.
gridUtils._gridCleanUp(rowEl, self.$target[0]);
self.$target[0].style.removeProperty('z-index');
}
// Removing the drag helper and the background grid and
// resizing the grid and the dropzone.
self.dragState.dragHelperEl.remove();
self.dragState.backgroundGridEl.remove();
self.options.wysiwyg.odooEditor.observerActive('dragAndDropMoveSnippet');
gridUtils._resizeGrid(rowEl);
self.options.wysiwyg.odooEditor.observerUnactive('dragAndDropMoveSnippet');
const rowCount = parseInt(rowEl.dataset.rowCount);
previousDropzoneEl.style.gridRowEnd = Math.max(rowCount + 1, 1);