-
Notifications
You must be signed in to change notification settings - Fork 23.2k
/
snippets.editor.js
889 lines (846 loc) · 34.6 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
/** @odoo-modules **/
import { _t } from "@web/core/l10n/translation";
import { Dialog } from "@web/core/dialog/dialog";
import { useChildRef, useService } from "@web/core/utils/hooks";
import { user } from "@web/core/user";
import weSnippetEditor from "@web_editor/js/editor/snippets.editor";
import wSnippetOptions from "@website/js/editor/snippets.options";
import * as OdooEditorLib from "@web_editor/js/editor/odoo-editor/src/utils/utils";
import { Component, onMounted, onWillStart, useEffect, useRef, useState } from "@odoo/owl";
import { throttleForAnimation } from "@web/core/utils/timing";
import { switchTextHighlight } from "@website/js/text_processing";
import { registry } from "@web/core/registry";
const snippetsEditorRegistry = registry.category("snippets_editor");
snippetsEditorRegistry.add("no_parent_editor_snippets", ["s_popup", "o_mega_menu"]);
const getDeepRange = OdooEditorLib.getDeepRange;
const getTraversedNodes = OdooEditorLib.getTraversedNodes;
const FontFamilyPickerUserValueWidget = wSnippetOptions.FontFamilyPickerUserValueWidget;
const ANIMATED_TEXT_SELECTOR = ".o_animated_text";
const HIGHLIGHTED_TEXT_SELECTOR = ".o_text_highlight";
export class WebsiteSnippetsMenu extends weSnippetEditor.SnippetsMenu {
static custom_events = Object.assign({}, weSnippetEditor.SnippetsMenu.custom_events, {
'service_context_get': '_onServiceContextGet',
'get_switchable_related_views': '_onGetSwitchableRelatedViews',
'gmap_api_request': '_onGMapAPIRequest',
'gmap_api_key_request': '_onGMapAPIKeyRequest',
'reload_bundles': '_onReloadBundles',
});
static tabs = Object.assign({}, weSnippetEditor.SnippetsMenu.tabs, {
THEME: 'theme',
});
static optionsTabStructure = [
['theme-colors', _t("Colors")],
['website-settings', _t("Website")],
['theme-paragraph', _t("Paragraph")],
['theme-headings', _t("Headings")],
['theme-button', _t("Button")],
['theme-link', _t("Link")],
['theme-input', _t("Input Fields")],
['theme-advanced', _t("Advanced")],
];
static props = {
...weSnippetEditor.SnippetsMenu.props,
getSwitchableRelatedViews: { type: Function },
};
static template = "website.SnippetsMenu";
/**
* @override
*/
setup() {
super.setup();
this.notification = useService("notification");
this.dialog = useService("dialog");
this.websiteService = useService("website");
this._notActivableElementsSelector += ', .o_mega_menu_toggle';
this.searchInput = useRef("search-input");
onWillStart(async () => {
this.isDesigner = await user.hasGroup("website.group_website_designer");
});
// Displays the button that allows to highlight the animated text if
// there is animated text in the page.
useEffect(
() => {
this.state.hasAnimatedText = !!this.getEditableArea().find('.o_animated_text').length;
},
() => [this.state.isTextAnimated],
);
// Focus the search input depending on the current tab.
useEffect(
(currentTab) => {
if (currentTab === weSnippetEditor.SnippetsMenu.tabs.BLOCKS) {
this.searchInput.el.focus();
} else {
// Clear the search input when switching to another tab.
this.state.search = "";
}
},
() => [this.state.currentTab]
);
}
/**
* @override
*/
async start() {
if (this.$body[0].ownerDocument !== this.ownerDocument) {
this.$body.on('click.snippets_menu', '*', this._onClick);
}
await super.start(...arguments);
this.__onSelectionChange = ev => {
this.state.isTextAnimated = this._getTextOptionState(ANIMATED_TEXT_SELECTOR);
this.state.isTextHighlighted = this._getTextOptionState(HIGHLIGHTED_TEXT_SELECTOR);
};
this.$body[0].ownerDocument.addEventListener('selectionchange', this.__onSelectionChange);
// Even if we prevented the drag via the css, we have to override the
// dragstart event because if one of the image ancestor has a dragstart
// listener, the dragstart handler can be called with the image as
// target. So we didn't prevent the drag with the css but with the
// following handler.
this.__onDragStart = ev => {
if (ev.target.nodeName === "IMG") {
ev.preventDefault();
ev.stopPropagation();
}
};
this.$body[0].addEventListener("dragstart", this.__onDragStart);
this._adaptHighlightOnEdit = throttleForAnimation(switchTextHighlight);
// Used to adjust highlight SVGs when the text is edited.
this.textHighlightObserver = new MutationObserver(mutations => {
// We only update SVGs when the mutation targets text content
// (including all mutations leads to infinite loop since the
// highlight adjustment will also trigger observed mutations).
let isSVGMutation = false;
let isNewContentMutation = false;
const textHighlightEls = new Set();
for (const mutation of mutations) {
for (const addedNode of mutation.addedNodes) {
const addedHighlightNode = addedNode.classlist?.contains("o_text_highlight")
? addedNode
: addedNode.querySelector?.(":scope .o_text_highlight");
if (addedHighlightNode) {
// E.g. When applying the split on a node with text
// highlights, the `oEnter` command will split the node
// and its parents correctly, which leads to duplicated
// highlight items that the observer should also handle.
// The goal here is to adapt these elements too.
textHighlightEls.add(addedHighlightNode);
isNewContentMutation = true;
}
if (addedNode.nodeName === "svg") {
isSVGMutation = true;
}
}
// Get the "text highlight" top element affected by mutations.
const mutationTarget = mutation.target.parentElement?.closest(".o_text_highlight")
|| mutation.target.nodeType === Node.ELEMENT_NODE
&& mutation.target.querySelector(":scope .o_text_highlight");
if (mutationTarget) {
textHighlightEls.add(mutationTarget);
}
}
if (!isSVGMutation || isNewContentMutation) {
for (const targetEl of textHighlightEls) {
this._adaptHighlightOnEdit(targetEl);
}
}
});
this.textHighlightObserver.observe(this.options.editable[0], {
attributes: false,
childList: true,
characterData: true,
subtree: true,
});
}
/**
* @override
*/
get invalidateSnippetCache() {
return this.websiteService.invalidateSnippetCache;
}
set invalidateSnippetCache(value) {
this.websiteService.invalidateSnippetCache = value;
}
/**
* @override
*/
onWillUnmount() {
super.onWillUnmount(...arguments);
this.$body[0].ownerDocument.removeEventListener('selectionchange', this.__onSelectionChange);
this.$body[0].removeEventListener("dragstart", this.__onDragStart);
this.$body[0].classList.remove('o_animated_text_highlighted');
clearTimeout(this._hideBackendNavbarTimeout);
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* @override
*/
async cleanForSave() {
this.textHighlightObserver.disconnect();
const getFromEditable = selector => this.options.editable[0].querySelectorAll(selector);
// Clean unstyled translations
return super.cleanForSave(...arguments).then(() => {
for (const el of getFromEditable('.o_translation_without_style')) {
el.classList.remove('o_translation_without_style');
if (el.dataset.oeTranslationSaveSha) {
el.dataset.oeTranslationInitialSha = el.dataset.oeTranslationSaveSha;
delete el.dataset.oeTranslationSaveSha;
}
}
// Adapt translation values for `select` > `options`s and remove all
// temporary `.o_translation_select` elements.
for (const optionsEl of getFromEditable('.o_translation_select')) {
const selectEl = optionsEl.nextElementSibling;
const translatedOptions = optionsEl.children;
const selectOptions = selectEl.tagName === 'SELECT' ? [...selectEl.options] : [];
if (selectOptions.length === translatedOptions.length) {
selectOptions.map((option, i) => {
option.text = translatedOptions[i].textContent;
});
}
optionsEl.remove();
}
});
}
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @override
*/
_computeSnippetTemplates(html) {
const $html = $(html);
const toFind = $html.find("we-fontfamilypicker[data-variable]").toArray();
const fontVariables = toFind.map((el) => el.dataset.variable);
FontFamilyPickerUserValueWidget.prototype.fontVariables = fontVariables;
<<<<<<< HEAD
return super._computeSnippetTemplates(html);
}
||||||| parent of 99155729d624 (temp)
return this._super(...arguments);
},
/**
* @override
*/
_patchForComputeSnippetTemplates($html) {
this._super(...arguments);
// TODO adapt in master: as a stable fix we corrected the behavior of
// the logo button that led to an error when switching from Text to
// Logo. Remove me in master.
const logoViewName = 'website.option_header_brand_logo';
const logoButtonEl = $html.find(`[data-customize-website-views="${logoViewName}"]`)[0];
if (logoButtonEl) {
logoButtonEl.dataset.customizeWebsiteViews = `|website.option_header_brand_name|${logoViewName}`;
logoButtonEl.dataset.resetViewArch = "true";
}
const brandSelectorEl = $html.find('[data-name="option_header_brand_none"]')[0]
?.closest("[data-selector]");
if (brandSelectorEl) {
brandSelectorEl.dataset.selector = brandSelectorEl.dataset.selector
.replace('.navbar-brand.logo', '.navbar-brand');
}
// TODO adapt in master: as a stable imp we added a preview for the
// "Effect" option of the "On Hover" animation option.
const hoverEffectSelectEl = $html.find('[data-set-img-shape-hover-effect]')[0];
delete hoverEffectSelectEl.dataset.noPreview;
// TODO remove in master: as a stable fix we exclude the form fields
// from the grid cell's Padding (Y, X) option.
const gridColumnsEl = $html.find('[data-js="GridColumns"]')[0];
if (gridColumnsEl) {
gridColumnsEl.dataset.selector = ".row:not(.s_col_no_resize) > div";
}
// Remove the input-border-width-sm and input-border-width-lg from the input-border-width
['input-border-width-sm', 'input-border-width-lg'].forEach(variable => {
const element = $html.find(
`[data-selector='theme-input'] we-input[data-customize-website-variable][data-variable='${variable}']`
)[0];
element.remove();
});
},
=======
return this._super(...arguments);
},
/**
* @override
*/
_patchForComputeSnippetTemplates($html) {
this._super(...arguments);
// TODO adapt in master: as a stable fix we corrected the behavior of
// the logo button that led to an error when switching from Text to
// Logo. Remove me in master.
const logoViewName = 'website.option_header_brand_logo';
const logoButtonEl = $html.find(`[data-customize-website-views="${logoViewName}"]`)[0];
if (logoButtonEl) {
logoButtonEl.dataset.customizeWebsiteViews = `|website.option_header_brand_name|${logoViewName}`;
logoButtonEl.dataset.resetViewArch = "true";
}
const brandSelectorEl = $html.find('[data-name="option_header_brand_none"]')[0]
?.closest("[data-selector]");
if (brandSelectorEl) {
brandSelectorEl.dataset.selector = brandSelectorEl.dataset.selector
.replace('.navbar-brand.logo', '.navbar-brand');
}
// TODO adapt in master: as a stable imp we added a preview for the
// "Effect" option of the "On Hover" animation option.
const hoverEffectSelectEl = $html.find('[data-set-img-shape-hover-effect]')[0];
delete hoverEffectSelectEl.dataset.noPreview;
// TODO remove in master: as a stable fix we exclude the form fields
// from the grid cell's Padding (Y, X) option.
const gridColumnsEl = $html.find('[data-js="GridColumns"]')[0];
if (gridColumnsEl) {
gridColumnsEl.dataset.selector = ".row:not(.s_col_no_resize) > div";
}
// Remove the input-border-width-sm and input-border-width-lg from the input-border-width
['input-border-width-sm', 'input-border-width-lg'].forEach(variable => {
const element = $html.find(
`[data-selector='theme-input'] we-input[data-customize-website-variable][data-variable='${variable}']`
)[0];
element.remove();
});
// TODO remove in master: should be simply replaced by a
// `data-text-selector` attribute to mark text options.
const AnimationOptionEl = $html.find('[data-js="WebsiteAnimate"]')[0];
const HighlightOptionEl = $html.find('[data-js="TextHighlight"]')[0];
if (AnimationOptionEl) {
AnimationOptionEl.dataset.textSelector = ".o_animated_text";
}
if (HighlightOptionEl) {
HighlightOptionEl.dataset.textSelector = HighlightOptionEl.dataset.selector;
}
},
>>>>>>> 99155729d624 (temp)
/**
* Depending of the demand, reconfigure they gmap key or configure it
* if not already defined.
*
* @private
* @param {boolean} [alwaysReconfigure=false]
* @param {boolean} [configureIfNecessary=false]
*/
async _configureGMapAPI({alwaysReconfigure, configureIfNecessary}) {
if (!alwaysReconfigure && !configureIfNecessary) {
// TODO should review, parameters are weird... only one necessary?
return false;
}
const apiKey = await new Promise(resolve => {
this.websiteService.websiteRootInstance.trigger_up("gmap_api_key_request", {
onSuccess: key => resolve(key),
});
});
const apiKeyValidation = apiKey ? await this._validateGMapAPIKey(apiKey) : {
isValid: false,
message: undefined,
};
if (!alwaysReconfigure && configureIfNecessary && apiKey && apiKeyValidation.isValid) {
return false;
}
const websiteId = this.websiteService.currentWebsite.id;
function applyError(message) {
const $apiKeyInput = this.find('#api_key_input');
const $apiKeyHelp = this.find('#api_key_help');
$apiKeyInput.addClass('is-invalid');
$apiKeyHelp.empty().text(message);
}
const GoogleMapAPIKeyDialog = class extends Component {
static template = "website.s_google_map_modal";
static components = { Dialog };
static props = {
onMounted: Function,
close: Function,
confirm: Function
};
setup() {
this.modalRef = useChildRef();
this.state = useState({ apiKey: apiKey });
this.apiKeyInput = useRef("apiKeyInput");
onMounted(() => this.props.onMounted(this.modalRef));
}
onClickSave() {
this.props.confirm(this.modalRef, this.state.apiKey);
}
};
return new Promise(resolve => {
let invalidated = false;
this.dialog.add(GoogleMapAPIKeyDialog, {
onMounted: (modalRef) => {
if (!apiKeyValidation.isValid && apiKeyValidation.message) {
applyError.call($(modalRef.el), apiKeyValidation.message);
}
},
confirm: async (modalRef, valueAPIKey) => {
if (!valueAPIKey) {
applyError.call($(modalRef.el), _t("Enter an API Key"));
return;
}
const $button = $(modalRef.el).find("button");
$button.prop('disabled', true);
const res = await this._validateGMapAPIKey(valueAPIKey);
if (res.isValid) {
await this.orm.write("website", [websiteId], {google_maps_api_key: valueAPIKey});
invalidated = true;
return true;
} else {
applyError.call($(modalRef.el), res.message);
}
$button.prop("disabled", false);
}
}, {
onClose: () => resolve(invalidated),
});
});
}
/**
* @private
*/
async _validateGMapAPIKey(key) {
try {
const response = await fetch(`https://maps.googleapis.com/maps/api/staticmap?center=belgium&size=10x10&key=${encodeURIComponent(key)}`);
const isValid = (response.status === 200);
return {
isValid: isValid,
message: !isValid &&
_t("Invalid API Key. The following error was returned by Google:") + " " + (await response.text()),
};
} catch {
return {
isValid: false,
message: _t("Check your connection and try again"),
};
}
}
/**
* @override
*/
_getDragAndDropOptions(options = {}) {
// TODO: This is currently not in use by Odoo's D&D
// There is currently no way in Odoo D&D to offset the edge scrolling.
// When there is, this code should be adapted.
const finalOptions = super._getDragAndDropOptions(...arguments);
if (!options.offsetElements || !options.offsetElements.$top) {
const $header = $('#top');
if ($header.length) {
finalOptions.offsetElements = finalOptions.offsetElements || {};
finalOptions.offsetElements.$top = $header;
}
}
return finalOptions;
}
/**
* @private
* @param {OdooEvent} ev
* @param {string} gmapRequestEventName
*/
async _handleGMapRequest(ev, gmapRequestEventName) {
ev.stopPropagation();
const reconfigured = await this._configureGMapAPI({
alwaysReconfigure: ev.data.reconfigure,
configureIfNecessary: ev.data.configureIfNecessary,
});
this.websiteService.websiteRootInstance.trigger_up(gmapRequestEventName, {
refetch: reconfigured,
editableMode: true,
onSuccess: key => ev.data.onSuccess(key),
});
}
/**
* Returns the text option element wrapping the selection if it exists.
*
* @private
* @param {String} selector
* @return {Element|false}
*/
_getSelectedTextElement(selector) {
const editable = this.options.wysiwyg.$editable[0];
const textOptionNode = getTraversedNodes(editable).find(n => n.parentElement.closest(selector));
return textOptionNode ? textOptionNode.parentElement.closest(selector) : false;
}
/**
* @private
* @return {Selection|null}
*/
_getSelection() {
return this.options.wysiwyg.odooEditor.document.getSelection();
}
/**
* @override
*/
_addToolbar() {
super._addToolbar(...arguments);
this.state.animatedTextHighlighted = this.$body[0].classList.contains("o_animated_text_highlighted");
this.state.isTextAnimated = this._getTextOptionState(ANIMATED_TEXT_SELECTOR);
this.state.isTextHighlighted = this._getTextOptionState(HIGHLIGHTED_TEXT_SELECTOR);
// As the toolbar displays css variable that are customizable by users,
// we have the recompute the font size selector values.
this.options.wysiwyg.odooEditor.computeFontSizeSelectorValues();
}
/**
* @override
*/
_checkEditorToolbarVisibility(e) {
super._checkEditorToolbarVisibility(...arguments);
// Close the option's dropdowns manually on outside click if any open.
this._toolbarWrapperEl.querySelectorAll(".dropdown-toggle.show").forEach(toggleEl => {
Dropdown.getOrCreateInstance(toggleEl).hide();
});
}
/**
* Returns true if the selected text matches the selector.
*
* @private
*/
_getTextOptionState(textSelector) {
if (!this._isValidSelection(this._getSelection())) {
return;
}
return !!this._getSelectedTextElement(textSelector);
}
/**
* @private
* @param {Node} node
* @return {Boolean}
*/
_isValidSelection(sel) {
return sel.rangeCount && [...this.getEditableArea()].some(el => el.contains(sel.anchorNode));
}
/**
* @override
*/
_isMobile() {
return this.websiteService.context.isMobile;
}
/**
* This callback type is used to identify the function used to apply some
* actions on the activated text snippet.
*
* @callback TextOptionCallback
* @param {jQuery} $snippet The selected text element on which the option
* should be applied.
*/
/**
* Used to handle "text options" button click according to whether the
* selected text has the option activated or not.
*
* @private
* @param {string} classSelector
* @param {Array<String>} optionClassList
* @param {TextOptionCallback} textOptionsPostActivate callback to trigger
* actions when the text snippet is activated.
* @returns {boolean} true if the option was applied, false if it was
* removed or could not be applied.
*/
_handleTextOptions(classSelector, optionClassList, textOptionsPostActivate = () => {}) {
const sel = this._getSelection();
if (!this._isValidSelection(sel)) {
return false;
}
const editable = this.options.wysiwyg.$editable[0];
const range = getDeepRange(editable, {splitText: true, select: true, correctTripleClick: true});
// Check if the text has already the current option activated.
let selectedTextEl = this._getSelectedTextElement(classSelector);
if (selectedTextEl) {
const restoreCursor = OdooEditorLib.preserveCursor(this.$body[0].ownerDocument);
// Unwrap the selected text content and disable the option.
const selectedTextParent = selectedTextEl.parentNode;
while (selectedTextEl.firstChild) {
const child = selectedTextEl.firstChild;
// When the text highlight option is activated, the text wrapper
// may contain SVG elements. They should be removed too...
if (child.nodeType === Node.ELEMENT_NODE && child.className.includes("o_text_highlight_item")) {
child.after(...[...child.childNodes].filter((node) => node.tagName !== "svg"));
child.remove();
}
selectedTextParent.insertBefore(selectedTextEl.firstChild, selectedTextEl);
}
selectedTextParent.removeChild(selectedTextEl);
// Update the option's UI.
this.options.wysiwyg.odooEditor.historyResetLatestComputedSelection();
this.options.wysiwyg.odooEditor.historyStep(true);
restoreCursor();
<<<<<<< HEAD
return false;
||||||| parent of 99155729d624 (temp)
=======
if (this.options.enableTranslation) {
$(selectedTextParent).trigger("content_changed");
}
>>>>>>> 99155729d624 (temp)
} else {
if (sel.getRangeAt(0).collapsed) {
return;
}
selectedTextEl = document.createElement("span");
selectedTextEl.classList.add(...optionClassList);
let $snippet = null;
try {
range.surroundContents(selectedTextEl);
$snippet = $(selectedTextEl);
} catch {
// This try catch is needed because 'surroundContents' may
// fail when the range has partially selected a non-Text node.
if (range.commonAncestorContainer.textContent === range.toString()) {
const $commonAncestor = $(range.commonAncestorContainer);
$commonAncestor.wrapInner(selectedTextEl);
$snippet = $commonAncestor.find(classSelector);
}
}
if ($snippet) {
$snippet[0].normalize();
this._activateSnippet($snippet, false).then(() => {
textOptionsPostActivate($snippet);
});
this.options.wysiwyg.odooEditor.historyStep();
return true;
} else {
this.notification.add(
_t("Cannot apply this option on current text selection. Try clearing the format and try again."),
{ type: 'danger', sticky: true }
);
}
return false;
}
}
/**
* @private
* @param {string} textSelector;
*/
_getOptionTextClass(textSelector) {
return textSelector.slice(1);
}
/**
* The goal here is to disable parents editors for snippets that should not
* display their parents options.
*
* @override
*/
_allowParentsEditors($snippet) {
return super._allowParentsEditors(...arguments) && !snippetsEditorRegistry.get("no_parent_editor_snippets")
.some(snippetClass => $snippet[0].classList.contains(snippetClass));
}
/**
* @override
*/
_insertDropzone($hook) {
var $hookParent = $hook.parent();
var $dropzone = super._insertDropzone(...arguments);
$dropzone.attr('data-editor-message-default', $hookParent.attr('data-editor-message-default'));
$dropzone.attr('data-editor-message', $hookParent.attr('data-editor-message'));
$dropzone.attr('data-editor-sub-message', $hookParent.attr('data-editor-sub-message'));
return $dropzone;
}
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* @private
* @param {OdooEvent} ev
*/
_onGMapAPIRequest(ev) {
this._handleGMapRequest(ev, 'gmap_api_request');
}
/**
* @private
* @param {OdooEvent} ev
*/
_onGMapAPIKeyRequest(ev) {
this._handleGMapRequest(ev, 'gmap_api_key_request');
}
/**
* @private
*/
_onThemeTabClick(ev) {
this._enableFakeOptionsTab(WebsiteSnippetsMenu.tabs.THEME);
}
/**
* @override
*/
_onOptionsTabClick(ev) {
if (!ev.currentTarget.classList.contains('active')) {
this._activateSnippet(false);
this._mutex.exec(async () => {
const switchableViews = await this.props.getSwitchableRelatedViews();
if (switchableViews.length) {
// These do not need to be awaited as we're in teh context
// of the mutex.
this._activateSnippet(this.$body.find('#wrapwrap > main'));
return;
}
let $pageOptionsTarget = $();
let i = 0;
const pageOptions = this.templateOptions.filter(template => template.data.pageOptions);
while (!$pageOptionsTarget.length && i < pageOptions.length) {
$pageOptionsTarget = pageOptions[i].selector.all();
i++;
}
if ($pageOptionsTarget.length) {
this._activateSnippet($pageOptionsTarget);
} else {
this._activateEmptyOptionsTab();
}
});
}
}
/**
* @private
* @param {Event} ev
*/
_onAnimateTextClick(ev) {
const active = this._handleTextOptions(ANIMATED_TEXT_SELECTOR, [
this._getOptionTextClass(ANIMATED_TEXT_SELECTOR),
"o_animate",
"o_animate_preview",
"o_anim_fade_in",
]);
this.state.isTextAnimated = active;
}
/**
* @private
*/
_onHighlightAnimatedTextClick(ev) {
const highlighted = this.$body[0].classList.toggle('o_animated_text_highlighted');
this.state.animatedTextHighlighted = highlighted;
$(ev.target).toggleClass('fa-eye fa-eye-slash').toggleClass('text-success');
}
/**
* @private
*/
_onTextHighlightClick() {
// To be able to open the highlights grid immediately, we need to
// prevent the `_onClick()` handler from closing the widget (using
// the `_closeWidgets()` method) right after opening it.
this._closeWidgets();
const active = this._handleTextOptions(
HIGHLIGHTED_TEXT_SELECTOR,
[
this._getOptionTextClass(HIGHLIGHTED_TEXT_SELECTOR),
"o_text_highlight_underline"
],
($snippet) => {
// TODO should be reviewed
$snippet.data("snippet-editor")?.trigger_up("option_update", {
optionName: "TextHighlight",
name: "new_text_highlight",
});
}
);
this.state.isTextHighlighted = active;
}
/**
* On reload bundles, when it's from the theme tab, destroy any
* snippetEditor as they might hold outdated style values. (e.g. color palettes).
* We do not destroy the Theme tab editors as they should have the correct
* values with their compute widget states.
* NOTE: This is a bit janky, _computeWidgetState should modify the
* option's widget to reflect the style accordingly. But since
* color_palette widget is independent of the UserValueWidget, it's hard to
* modify its style using the options events.
*
* @private
*/
_onReloadBundles(ev) {
const excludeSelector = this.constructor.optionsTabStructure.map(element => element[0]).join(', ');
const oldSuccess = ev.data.onSuccess;
ev.data.onSuccess = (...args) => {
// Update the panel so that color previews reflect the ones used by the
// edited content.
this.props.setCSSVariables(this.el);
oldSuccess(...args);
};
for (const editor of this.snippetEditors) {
if (!editor.$target[0].matches(excludeSelector)) {
if (this._currentTab === this.tabs.THEME) {
this._mutex.exec(() => {
editor.destroy();
});
} else {
this._mutex.exec(async () => {
await editor.updateOptionsUI(true);
});
}
}
}
}
/**
* Notifies the website service that mobile preview is toggled.
* This will toggle the iframe between mobile and desktop view.
*
* @private
*/
_toggleMobilePreview() {
this.websiteService.context.isMobile = !this.websiteService.context.isMobile;
}
/**
* Used by legacy widgets to fetch the state of the mobile preview.
*
* @private
* @param {CustomEvent} ev
*/
_onServiceContextGet(ev) {
ev.data.callback({
isMobile: this.websiteService.context.isMobile,
});
}
/**
* Returns the list of views that can be toggled on the current page.
*
* @param {CustomEvent} ev
*/
_onGetSwitchableRelatedViews(ev) {
this.props.getSwitchableRelatedViews().then(ev.data.onSuccess);
}
}
weSnippetEditor.SnippetEditor.include({
layoutElementsSelector: [
weSnippetEditor.SnippetEditor.prototype.layoutElementsSelector,
'.s_parallax_bg',
'.o_bg_video_container',
].join(','),
/**
* @override
*/
getName() {
if (this.$target[0].closest('[data-oe-field=logo]')) {
return _t("Logo");
}
return this._super(...arguments);
},
/**
* @override
* @returns {Promise}
*/
async updateOptionsUIVisibility() {
await this._super(...arguments);
// TODO improve this: some website text options (like text animations,
// text highlights...) are moved to the toolbar, which leads to an empty
// "options section". The goal of this override is to hide options
// sections with no option elements.
if (!this.$optionsSection[0].querySelector(":scope > we-customizeblock-option")) {
this.$optionsSection[0].classList.add("d-none");
}
},
/**
* Changes some behaviors before the drag and drop.
*
* @private
* @override
* @returns {Function} a function that restores what was changed when the
* drag and drop is over.
*/
_prepareDrag() {
const restore = this._super(...arguments);
// Remove the footer scroll effect if it has one (because the footer
// dropzone flickers otherwise when it is in grid mode).
const wrapwrapEl = this.$body[0].ownerDocument.defaultView.document.body.querySelector('#wrapwrap');
const hasFooterScrollEffect = wrapwrapEl && wrapwrapEl.classList.contains('o_footer_effect_enable');
if (hasFooterScrollEffect) {
wrapwrapEl.classList.remove('o_footer_effect_enable');
return () => {
wrapwrapEl.classList.add('o_footer_effect_enable');
restore();
};
}
return restore;
},
});
export default {
SnippetsMenu: WebsiteSnippetsMenu,
};