-
Notifications
You must be signed in to change notification settings - Fork 24.6k
/
wysiwyg.js
3712 lines (3560 loc) · 161 KB
/
wysiwyg.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 { session } from "@web/session";
import { user } from "@web/core/user";
import { MediaDialog } from "@web_editor/components/media_dialog/media_dialog";
import { VideoSelector } from "@web_editor/components/media_dialog/video_selector";
import { browser } from "@web/core/browser/browser";
import { useService } from "@web/core/utils/hooks";
import customColors from "@web_editor/js/editor/custom_colors";
import { localization } from "@web/core/l10n/localization";
import * as OdooEditorLib from "@web_editor/js/editor/odoo-editor/src/OdooEditor";
import { Toolbar } from "@web_editor/js/editor/toolbar";
import { LinkPopoverWidget } from '@web_editor/js/wysiwyg/widgets/link_popover_widget';
import { AltDialog } from '@web_editor/js/wysiwyg/widgets/alt_dialog';
import { ChatGPTPromptDialog } from '@web_editor/js/wysiwyg/widgets/chatgpt_prompt_dialog';
import { ChatGPTAlternativesDialog } from '@web_editor/js/wysiwyg/widgets/chatgpt_alternatives_dialog';
import { ChatGPTTranslateDialog } from "@web_editor/js/wysiwyg/widgets/chatgpt_translate_dialog";
import { ImageCrop } from '@web_editor/js/wysiwyg/widgets/image_crop';
import * as wysiwygUtils from "@web_editor/js/common/wysiwyg_utils";
import weUtils from "@web_editor/js/common/utils";
import { isIconElement, isSelectionInSelectors, peek } from '@web_editor/js/editor/odoo-editor/src/utils/utils';
import { PeerToPeer, RequestError } from "@web_editor/js/wysiwyg/PeerToPeer";
import { rpc } from "@web/core/network/rpc";
import { uniqueId } from "@web/core/utils/functions";
import { groupBy } from "@web/core/utils/arrays";
import { debounce } from "@web/core/utils/timing";
import { registry } from "@web/core/registry";
import { FileViewer } from "@web/core/file_viewer/file_viewer";
import { isMobileOS } from "@web/core/browser/feature_detection";
import { Deferred, Mutex } from "@web/core/utils/concurrency";
import { AlertDialog, ConfirmationDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
import { _t } from "@web/core/l10n/translation";
import { ConflictDialog } from "./conflict_dialog";
import { getOrCreateLink } from "./widgets/link";
import { shouldUnlink } from '@web_editor/js/wysiwyg/widgets/link_tools';
import { LinkDialog } from "./widgets/link_dialog";
import {
Component,
EventBus,
useRef,
useState,
onWillStart,
onMounted,
onWillDestroy,
onWillUpdateProps,
markup,
status,
} from "@odoo/owl";
import { isCSSColor } from '@web/core/utils/colors';
import { EmojiPicker } from '@web/core/emoji_picker/emoji_picker';
import { Tooltip } from "@web/core/tooltip/tooltip";
const OdooEditor = OdooEditorLib.OdooEditor;
const getDeepRange = OdooEditorLib.getDeepRange;
const getInSelection = OdooEditorLib.getInSelection;
const isProtected = OdooEditorLib.isProtected;
const rgbToHex = OdooEditorLib.rgbToHex;
const preserveCursor = OdooEditorLib.preserveCursor;
const closestElement = OdooEditorLib.closestElement;
const setSelection = OdooEditorLib.setSelection;
const endPos = OdooEditorLib.endPos;
const hasValidSelection = OdooEditorLib.hasValidSelection;
const parseHTML = OdooEditorLib.parseHTML;
const closestBlock = OdooEditorLib.closestBlock;
const getRangePosition = OdooEditorLib.getRangePosition;
const childNodeIndex = OdooEditorLib.childNodeIndex;
const fillEmpty = OdooEditorLib.fillEmpty;
const isVisible = OdooEditorLib.isVisible;
const getDeepestPosition = OdooEditorLib.getDeepestPosition;
const paragraphRelatedElements = OdooEditorLib.paragraphRelatedElements;
function getJqueryFromDocument(doc) {
if (doc.defaultView && doc.defaultView.$) {
return doc.defaultView.$;
} else {
const _jquery = window.$;
return (...args) => {
if (args.length <= 2 && typeof args[0] === "string") {
return _jquery(args[0], args[1] || doc);
} else {
return _jquery(...args)
}
}
}
}
var id = 0;
const basicMediaSelector = 'img, .fa, .o_image, .media_iframe_video';
// (see isImageSupportedForStyle).
const mediaSelector = basicMediaSelector.split(',').map(s => `${s}:not([data-oe-xpath])`).join(',');
// Time to consider a user offline in ms. This fixes the problem of the
// navigator closing rtc connection when the mac laptop screen is closed.
const CONSIDER_OFFLINE_TIME = 1000;
// Check wether the computer could be offline. This fixes the problem of the
// navigator closing rtc connection when the mac laptop screen is closed.
// This case happens on Mac OS on every browser when the user close it's laptop
// screen. At first, the os/navigator closes all rtc connection, and after some
// times, the os/navigator internet goes offline without triggering an
// offline/online event.
// However, if the laptop screen is open and the connection is properly remove
// (e.g. disconnect wifi), the event is properly triggered.
const CHECK_OFFLINE_TIME = 1000;
const PTP_CLIENT_DISCONNECTED_STATES = [
'failed',
'closed',
'disconnected',
];
// Time in ms to wait when trying to aggregate snapshots from other peers and
// potentially recover from a missing step before trying to apply those
// snapshots or recover from the server.
const PTP_MAX_RECOVERY_TIME = 500;
const REQUEST_ERROR = Symbol('REQUEST_ERROR');
// this is a local cache for ice server descriptions
let ICE_SERVERS = null;
let fileViewerId = 0;
export class Wysiwyg extends Component {
static template = 'web_editor.Wysiwyg';
static components = { MediaDialog, VideoSelector, Toolbar, ImageCrop };
static props = {
options: Object,
startWysiwyg: { type: Function, optional: true },
editingValue: { type: String, optional: true },
};
elRef = useRef("el");
toolbarRef = useRef("toolbar");
imageCropRef = useRef("imageCrop");
colorPalettesProps = {
text: useState({
resetTabCount: 0,
}),
background: useState({
resetTabCount: 0,
}),
}
imageCropProps = useState({
showCount: 0,
media: undefined,
mimetype: undefined,
});
state = useState({
linkToolProps: false,
showToolbar: true,
toolbarProps: {},
showSnippetsMenu: false,
snippetsMenuFolded: false,
});
setup() {
this.orm = useService('orm');
this.getColorPickerTemplateService = useService('get_color_picker_template');
this.notification = useService("notification");
this.popover = useService("popover");
this.busService = this.env.services.bus_service;
this.user = user;
this.snippetsMenuContainer = useRef("snippets-menu-container");
this.mutex = new Mutex();
this.snippetsMenuBus = new EventBus();
const getColorPickedHandler = (colorType) => {
return (params) => {
if (this.hadNonCollapsedSelectionBeforeColorpicker) {
this.odooEditor.historyResetLatestComputedSelection(true);
}
// Unstash the mutations now that the color is picked.
this.odooEditor.historyUnstash();
this._processAndApplyColor(colorType, params.color);
// Deselect tables so the applied color can be seen
// without using `!important` (otherwise the selection
// hides it).
if (this.odooEditor.deselectTable() && hasValidSelection(this.odooEditor.editable)) {
this.odooEditor.document.getSelection().collapseToStart();
}
this._updateEditorUI(this.lastMediaClicked && { target: this.lastMediaClicked });
};
}
const getColorHoverHandler = (colorType) => {
return (props) => {
if (this.hadNonCollapsedSelectionBeforeColorpicker) {
this.odooEditor.historyResetLatestComputedSelection(true);
}
this.odooEditor.historyPauseSteps();
try {
this._processAndApplyColor(colorType, props.color, true);
this.odooEditor._computeHistorySelection();
} finally {
this.odooEditor.historyUnpauseSteps();
}
}
};
const colorPaletteCommonOptions = {
excluded: ['transparent_grayscale'],
document: this.props.options.document,
selectedTab: 'theme-colors',
withGradients: true,
onColorLeave: () => {
// We need to prevent rollback in case the seclection is in unremovable
this.odooEditor.withoutRollback(() => this.odooEditor.historyRevertCurrentStep());
// Compute the selection to ensure it's preserved between
// selectionchange events in case this gets triggered multiple
// times quickly.
this.odooEditor._computeHistorySelection();
},
onInputEnter: (ev) => {
const pickergroup = ev.target.closest('.colorpicker-group');
$(pickergroup.querySelector('.dropdown-toggle')).dropdown('hide');
},
getTemplate: this.getColorpickerTemplate.bind(this),
getEditableCustomColors: () => {
if (!this.$editable) {
return [];
}
return [...this.$editable[0].querySelectorAll('[style*="color"]')].map(el => {
return [el.style.color, el.style.backgroundColor];
}).flat();
},
};
onWillStart(() => {
this.init();
Object.assign(this.colorPalettesProps.text, colorPaletteCommonOptions, {
document: this.options.document,
onColorPicked: getColorPickedHandler('text'),
onCustomColorPicked: getColorPickedHandler('text'),
onColorHover: getColorHoverHandler('text'),
onColorpaletteTabChange: this.getColorPaletteTabChangeHandler('text').bind(this),
});
Object.assign(this.colorPalettesProps.background, colorPaletteCommonOptions, {
document: this.options.document,
onColorPicked: getColorPickedHandler('background'),
onCustomColorPicked: getColorPickedHandler('background'),
onColorHover: getColorHoverHandler('background'),
onColorpaletteTabChange: this.getColorPaletteTabChangeHandler('background').bind(this),
});
this._setToolbarProps();
});
onMounted(async () => {
this.el = this.elRef.el
this.$el = $(this.elRef.el);
this._renderElement();
if (this.props.startWysiwyg) {
await this.props.startWysiwyg(this);
} else {
await this.startEdition();
}
});
onWillDestroy(() => {
this.destroy();
});
onWillUpdateProps((newProps) => {
this.options = this._getEditorOptions(newProps.options);
this._setToolbarProps();
const lastValue = String(this.props.options.value || '');
const lastRecordInfo = this.props.options.recordInfo;
const lastCollaborationChannel = this.props.options.collaborationChannel;
const newValue = String(newProps.options.value || '');
const newRecordInfo = newProps.options.recordInfo;
const newCollaborationChannel = newProps.options.collaborationChannel;
const isDifferentRecord =
JSON.stringify(lastRecordInfo) !== JSON.stringify(newRecordInfo) ||
JSON.stringify(lastCollaborationChannel) !== JSON.stringify(newCollaborationChannel);
const isDiscardedRecord = !isDifferentRecord && newProps.options.record && !newProps.options.record.dirty;
if (
(
stripHistoryIds(newValue) !== stripHistoryIds(newProps.editingValue) &&
stripHistoryIds(lastValue) !== stripHistoryIds(newValue)
) ||
isDifferentRecord
)
{
if (isDifferentRecord || isDiscardedRecord) {
this.resetEditor(newValue, newProps.options);
} else {
this.setValue(newValue);
}
this.env.onWysiwygReset && this.env.onWysiwygReset();
}
});
}
defaultOptions = {
lang: 'odoo',
colors: customColors,
recordInfo: {context: {}},
document: document,
allowCommandVideo: true,
allowCommandImage: true,
allowCommandLink: true,
insertParagraphAfterColumns: true,
onHistoryResetFromSteps: () => {},
autostart: true,
dropImageAsAttachment: true,
editorPlugins: [],
useResponsiveFontSizes: true,
showResponsiveFontSizesBadges: false,
showExtendedTextStylesOptions: false,
getCSSVariableValue: weUtils.getCSSVariableValue,
convertNumericToUnit: weUtils.convertNumericToUnit,
};
init() {
this.id = ++id;
this.options = this._getEditorOptions(this.props.options);
this.saving_mutex = new Mutex();
// Keeps track of color palettes per event name.
this.colorpickers = {};
this._onDocumentMousedown = this._onDocumentMousedown.bind(this);
this._onBlur = this._onBlur.bind(this);
this._onScroll = this._onScroll.bind(this);
this.customizableLinksSelector = 'a'
+ ':not([data-bs-toggle="tab"])'
+ ':not([data-bs-toggle="collapse"])'
+ ':not([data-bs-toggle="dropdown"])'
+ ':not(.dropdown-item)';
// navigator.onLine is sometimes a false positive, this._isOnline use
// more heuristics to bypass the limitation.
this._isOnline = true;
this._signalOnline = this._signalOnline.bind(this);
this.tooltipTimeouts = [];
Wysiwyg.activeWysiwygs.add(this);
this._joinPeerToPeer = this._joinPeerToPeer.bind(this);
}
/**
*
* @override
*/
async start() {
// If this widget is started from the OWL legacy component, at the time
// of start, the $el is not in the document yet. Some instruction in the
// start rely on the $el being in the document at that time, including
// code for the collaboration (for adding cursors) or the iframe loading
// in mass_mailing.
if (this.options.autostart) {
return this.startEdition();
}
}
async startEdition() {
const self = this;
const options = this.options;
this.$editable ??= this.$el;
if (options.value) {
this.$editable.html(options.value);
}
this._isDocumentStale = false;
// Each time a reset of the document is triggered, it is assigned a
// unique identifier. Since resetting the editor involves asynchronous
// requests, it is possible that subsequent resets are triggered before
// the previous one is complete. This property identifies the latest
// reset and can be compared against to cancel the processing of late
// responses from previous resets.
this._lastCollaborationResetId = 0;
// This ID correspond to the peer that initiated the document and set
// the initial oid for all nodes in the tree. It is not the same as
// document that had a step id at some point. If a step comes from a
// different history, we should not apply it.
this._historyShareId = Math.floor(Math.random() * Math.pow(2,52)).toString();
// The ID is the latest step ID that the server knows through
// `data-last-history-steps`. We cannot save to the server if we do not
// have that ID in our history ids as it means that our version is
// stale.
this._serverLastStepId = options.value && this._getLastHistoryStepId(options.value);
this.$editable.data('wysiwyg', this);
this.$editable.data('oe-model', options.recordInfo.res_model);
this.$editable.data('oe-id', options.recordInfo.res_id);
document.addEventListener('mousedown', this._onDocumentMousedown, true);
this._bindOnBlur();
this.toolbarEl = this.toolbarRef.el.firstChild;
this.imageCropEL = this.imageCropRef.el.firstChild;
options.document.body.append(this.imageCropEL);
const powerboxOptions = this._getPowerboxOptions();
let editorCollaborationOptions;
if (this._isCollaborationEnabled(options)) {
this._currentClientId = this._generateClientId();
editorCollaborationOptions = this.setupCollaboration(options.collaborationChannel);
if (this.options.collaborativeTrigger === 'start') {
this._joinPeerToPeer();
} else if (this.options.collaborativeTrigger === 'focus') {
// Wait until editor is focused to join the peer to peer network.
this.$editable[0].addEventListener('focus', this._joinPeerToPeer);
}
}
const getYoutubeVideoElement = async (url) => {
const { embed_url: src } = await this._serviceRpc(
'/web_editor/video_url/data',
{ video_url: url },
);
const [savedVideo] = VideoSelector.createElements([{src}]);
savedVideo.classList.add(...VideoSelector.mediaSpecificClasses);
return savedVideo;
};
weUtils.setEditableDocument(this.options.document);
const _getContentEditableAreas = this.options.getContentEditableAreas;
this.odooEditor = new OdooEditor(this.$editable[0], Object.assign({
_t: _t,
toolbar: this.toolbarEl,
document: this.options.document,
autohideToolbar: !!this.options.autohideToolbar,
isRootEditable: this.options.isRootEditable,
onPostSanitize: this._onPostSanitize.bind(this),
placeholder: this.options.placeholder,
powerboxFilters: this.options.powerboxFilters || [],
showEmptyElementHint: this.options.showEmptyElementHint,
controlHistoryFromDocument: this.options.controlHistoryFromDocument,
initialHistoryId: this._serverLastStepId,
// TODO other places in this file call this.options.getContentEditableAreas
// without the extension here. It does not seem to be a problem (it
// was like that before o_editor_banner elements were considered
// here), but we might want to review that.
getContentEditableAreas: (...args) => {
const areaEls = _getContentEditableAreas?.(...args) || [];
const bannerEls = this.$editable[0].querySelectorAll('.o_editor_banner > div');
return [...areaEls, ...bannerEls];
},
getReadOnlyAreas: this.options.getReadOnlyAreas,
getUnremovableElements: this.options.getUnremovableElements,
defaultLinkAttributes: this.options.userGeneratedContent ? {rel: 'ugc' } : {},
allowCommandVideo: this.options.allowCommandVideo,
allowInlineAtRoot: this.options.allowInlineAtRoot,
getYoutubeVideoElement: getYoutubeVideoElement,
getContextFromParentRect: options.getContextFromParentRect,
getScrollContainerRect: () => {
if (!this.scrollContainer || !this.scrollContainer.getBoundingClientRect) {
this.scrollContainer = document.querySelector('.o_action_manager') || document.body;
}
return this.scrollContainer.getBoundingClientRect();
},
getPowerboxElement: () => {
const selection = (this.options.document || document).getSelection();
if (selection.isCollapsed && selection.rangeCount) {
const [deepestNode] = getDeepestPosition(selection.anchorNode, selection.anchorOffset);
const elementSelectors = [
'LI:not([t-field])',
'DIV:not([t-field]):not(.o_not_editable)',
...paragraphRelatedElements.map(tag => `${tag}:not([t-field])`),
];
const baseNode = closestElement(deepestNode, elementSelectors.join(', '));
const fieldContainer = closestElement(deepestNode, '[data-oe-field]');
if (!baseNode ||
(
fieldContainer &&
!(
fieldContainer.getAttribute('data-oe-field') === 'arch' ||
fieldContainer.getAttribute('data-oe-type') === 'html'
)
)) {
return false;
}
return baseNode;
}
},
isHintBlacklisted: node => {
return (node.classList && node.classList.contains('nav-item')) || (
node.hasAttribute && (
node.hasAttribute('data-target') ||
node.hasAttribute('data-oe-model')
)
);
},
filterMutationRecords: (records) => {
return records.filter((record) => {
if (record.type === 'attributes'
&& record.attributeName === 'aria-describedby') {
const value = (record.oldValue || record.target.getAttribute(record.attributeName));
if (value && ['popover', 'tooltip'].some(type => value.startsWith(type))) {
// E.g. prevents to consider the mutation due to
// the 'o_edit_menu_popover' popover being shown.
return false;
}
}
return !(
// TODO should probably not check o_header_standard
// here, since it is a website class ?
(record.target.classList && record.target.classList.contains('o_header_standard')) ||
(record.type === 'attributes' && record.attributeName === 'data-last-history-steps')
);
});
},
preHistoryUndo: () => {
this.destroyLinkTools();
},
beforeAnyCommand: this._beforeAnyCommand.bind(this),
commands: powerboxOptions.commands,
categories: powerboxOptions.categories,
plugins: options.editorPlugins,
direction: options.direction || localization.direction || 'ltr',
collaborationClientAvatarUrl: this._getCollaborationClientAvatarUrl(),
renderingClasses: ["o_dirty", "o_transform_removal", "oe_edited_link", "o_menu_loading", "o_draggable", "o_link_in_selection"],
dropImageAsAttachment: options.dropImageAsAttachment,
foldSnippets: !!options.foldSnippets,
useResponsiveFontSizes: options.useResponsiveFontSizes,
showResponsiveFontSizesBadges: options.showResponsiveFontSizesBadges,
showExtendedTextStylesOptions: options.showExtendedTextStylesOptions,
getCSSVariableValue: options.getCSSVariableValue,
convertNumericToUnit: options.convertNumericToUnit,
autoActivateContentEditable: this.options.autoActivateContentEditable,
}, editorCollaborationOptions));
this.odooEditor.addEventListener('contentChanged', function () {
self.$editable.trigger('content_changed');
});
document.addEventListener("mousemove", this._signalOnline, true);
document.addEventListener("keydown", this._signalOnline, true);
document.addEventListener("keyup", this._signalOnline, true);
if (this.odooEditor.document !== document) {
this.odooEditor.document.addEventListener("mousemove", this._signalOnline, true);
this.odooEditor.document.addEventListener("keydown", this._signalOnline, true);
this.odooEditor.document.addEventListener("keyup", this._signalOnline, true);
}
this._initialValue = this.getValue();
// TODO this code should be reviewed. Previously, it searched for the
// wrapwrap and added some scroll handler if found... we are now
// continuing to search for it, but it is not clear why. As the wrapwrap
// will be removed, this code will not stay for too long anyway.
if ($('wrapwrap').length) {
this.multiSelectionTarget = $().getScrollingTarget(this.odooEditor.document);
this.multiSelectionTarget.addEventListener('scroll', this.odooEditor.multiselectionRefresh, { passive: true });
}
this.$editable.on('click', '[data-oe-field][data-oe-sanitize-prevent-edition]', () => {
this.env.services.dialog.add(AlertDialog, {
body: _t("Someone with escalated rights previously modified this area, you are therefore not able to modify it yourself."),
});
});
for (const field of this.$editable[0].querySelectorAll('[data-oe-type="text"], [data-oe-type="char"]')) {
if (!isVisible(field)) {
fillEmpty(field);
}
}
this._observeOdooFieldChanges();
this.$editable.on(
'mousedown touchstart',
'[data-oe-field]',
function () {
self.odooEditor.observerUnactive();
const $field = $(this);
if (($field.data('oe-type') === "datetime" || $field.data('oe-type') === "date")) {
let selector = '[data-oe-id="' + $field.data('oe-id') + '"]';
selector += '[data-oe-field="' + $field.data('oe-field') + '"]';
selector += '[data-oe-model="' + $field.data('oe-model') + '"]';
const $linkedFieldNodes = self.$editable.find(selector).addBack(selector);
$linkedFieldNodes.addClass('o_editable_date_field_linked');
if (!$field.hasClass('o_editable_date_field_format_changed')) {
$linkedFieldNodes.text($field.data('oe-original-with-format'));
$linkedFieldNodes.addClass('o_editable_date_field_format_changed');
$linkedFieldNodes.filter('.oe_hide_on_date_edit').addClass('d-none');
setTimeout(() => {
// we might hide the clicked date, focus the one
// supposed to be editable
Wysiwyg.setRange($linkedFieldNodes.filter(':not(.oe_hide_on_date_edit)')[0]);
}, 0);
}
}
if ($field.attr('contenteditable') !== 'false') {
if ($field.data('oe-type') === "monetary") {
$field.attr('contenteditable', false);
const $currencyValue = $field.find('.oe_currency_value');
$currencyValue.attr('contenteditable', true);
$currencyValue.one('mouseup touchend', (e) => {
$currencyValue.selectContent();
});
}
if ($field.data('oe-type') === "image") {
$field.attr('contenteditable', false);
$field.find('img').attr('contenteditable', $field.data('oe-readonly') !== 1);
}
if ($field.is('[data-oe-many2one-id]')) {
$field.attr('contenteditable', false);
}
}
self.odooEditor.observerActive();
}
);
this.$editable.on('click', '.o_image, .media_iframe_video', e => e.preventDefault());
let closeBannerEmojiPicker;
this.$editable.on('click', '.o_editor_banner_icon', event => {
if (closeBannerEmojiPicker) {
closeBannerEmojiPicker();
}
closeBannerEmojiPicker = this.popover.add(event.target, EmojiPicker, {
onSelect: emoji => {
event.target.innerText = emoji;
}
}, { position: 'bottom' });
});
this.showTooltip = true;
this.$editable.on('dblclick', mediaSelector, ev => {
const targetEl = ev.currentTarget;
let isEditable =
// TODO that first check is probably useless/wrong: checking if
// the media itself has editable content should not be relevant.
// In fact the content of all media should be marked as non
// editable anyway.
targetEl.isContentEditable ||
// For a media to be editable, the base case is to be in a
// container whose content is editable.
(targetEl.parentElement && targetEl.parentElement.isContentEditable);
if (!isEditable && targetEl.classList.contains('o_editable_media')) {
isEditable = weUtils.shouldEditableMediaBeEditable(targetEl);
}
if (isEditable) {
this.showTooltip = false;
if (!isProtected(this.odooEditor.document.getSelection().anchorNode)) {
if (this.options.onDblClickEditableMedia && targetEl.nodeName === 'IMG' && targetEl.src) {
this.options.onDblClickEditableMedia(ev);
} else {
this._onDblClickEditableMedia(ev);
}
}
}
});
if (options.snippets) {
this.snippetsMenuComponent = await this.getSnippetsMenuClass(options);
await this._insertSnippetMenu();
$(this.odooEditor.document.body).addClass('editor_enable');
this._onBeforeUnload = (event) => {
if (this.isDirty()) {
event.returnValue = _t('This document is not saved!');
}
};
window.addEventListener('beforeunload', this._onBeforeUnload);
}
if (this.options.getContentEditableAreas) {
$(this.options.getContentEditableAreas(this.odooEditor)).find('*').off('mousedown mouseup click');
}
// The toolbar must be configured after the snippetMenu is loaded
// because if snippetMenu is loaded in an iframe, binding of the color
// buttons must use the jquery loaded in that iframe.
this._configureToolbar(options);
$(this.odooEditor.editable).on('mouseup', this._updateEditorUI.bind(this));
$(this.odooEditor.editable).on('keydown', this._updateEditorUI.bind(this));
$(this.odooEditor.editable).on('keydown', this._handleShortcuts.bind(this));
// Ensure the Toolbar always have the correct layout in note.
this._updateEditorUI();
this.$editable.on('click.Wysiwyg', (ev) => {
const $target = $(ev.target).closest('a');
// Keep popover open if clicked inside it, but not on a button
if ($(ev.target).parents('.o_edit_menu_popover').length && !$target.length) {
ev.preventDefault();
}
if ($target.is(this.customizableLinksSelector)
&& $target.is('a')
&& $target[0].isContentEditable
&& !$target.attr('data-oe-model')
&& !$target.find('> [data-oe-model]').length
&& !$target[0].closest('.o_extra_menu_items')
&& $target[0].isContentEditable) {
if (ev.ctrlKey || ev.metaKey) {
window.open($target[0].href, '_blank');
}
this.linkPopover = $target.data('popover-widget-initialized');
if (!this.linkPopover) {
// TODO this code is ugly maybe the mutex should be in the
// editor root widget / the popover should not depend on
// editor panel (like originally intended but...) / ...
(async () => {
let container;
if (this.state.showSnippetsMenu) {
// Await for the editor panel to be fully updated
// as some buttons of the link popover we create
// here relies on clicking in that editor panel...
await this.mutex.exec(() => null);
container = this.options.document.getElementById('oe_manipulators');
}
this.linkPopover = LinkPopoverWidget.createFor({
target: $target[0],
wysiwyg: this,
container,
notify: (message, params) => {
this.notification.add(message, { type: params.type });
},
});;
$target.data('popover-widget-initialized', this.linkPopover);
})();
}
// Setting the focus on the closest contenteditable element
// resets the selection inside that element if no selection
// exists.
$target.closest('[contenteditable=true]').focus();
if ($target.closest('#wrapwrap').length && this.state.showSnippetsMenu) {
this.toggleLinkTools({
forceOpen: true,
link: $target[0],
shouldFocusUrl: ev.detail !== 1,
});
}
}
});
this._onSelectionChange = this._onSelectionChange.bind(this);
this.odooEditor.document.addEventListener('selectionchange', this._onSelectionChange);
if (!this.state.showSnippetsMenu) {
this.setCSSVariables(this.toolbarEl);
}
this.odooEditor.addEventListener('preObserverActive', () => {
// The onPostSanitize will be called right after the
// editor sanitization (to be right before the historyStep).
// If any `.o_not_editable` is created while the observer is
// unactive, now is the time to call `onPostSanitize` before the
// editor could register a mutation.
this._onPostSanitize(this.odooEditor.editable);
});
if (this.options.autohideToolbar) {
if (this.odooEditor.isMobile) {
this.odooEditor.editable.before(this.toolbarEl);
} else {
document.body.append(this.toolbarEl);
}
}
}
setupCollaboration(collaborationChannel) {
const modelName = collaborationChannel.collaborationModelName;
const fieldName = collaborationChannel.collaborationFieldName;
const resId = collaborationChannel.collaborationResId;
const channelName = `editor_collaboration:${modelName}:${fieldName}:${resId}`;
if (
!(modelName && fieldName && resId) ||
Wysiwyg.activeCollaborationChannelNames.has(channelName)
) {
return;
}
this._collaborationChannelName = channelName;
this._historyStepsBuffer = [];
Wysiwyg.activeCollaborationChannelNames.add(channelName);
const collaborationBusListener = (payload) => {
if (
payload.model_name === modelName &&
payload.field_name === fieldName &&
payload.res_id === resId
) {
if (payload.notificationName === 'html_field_write') {
this._onServerLastIdUpdate(payload.notificationPayload.last_step_id);
} else if (this._ptpJoined) {
this._peerToPeerLoading.then(() => this.ptp.handleNotification(payload));
}
}
}
this.busService.subscribe('editor_collaboration', collaborationBusListener);
this.busService.addChannel(this._collaborationChannelName);
this._collaborationStopBus = () => {
Wysiwyg.activeCollaborationChannelNames.delete(this._collaborationChannelName);
this.busService.unsubscribe('editor_collaboration', collaborationBusListener);
this.busService.deleteChannel(this._collaborationChannelName);
}
this._startCollaborationTime = new Date().getTime();
this._checkConnectionChange = () => {
if (!this.ptp) {
return;
}
if (!navigator.onLine) {
this._signalOffline();
} else {
this._signalOnline();
}
};
window.addEventListener('online', this._checkConnectionChange);
window.addEventListener('offline', this._checkConnectionChange);
this._collaborationInterval = setInterval(async () => {
if (this._offlineTimeout || this.preSavePromise || !this.ptp) {
return;
}
const clientsInfos = Object.values(this.ptp.clientsInfos);
const couldBeDisconnected =
Boolean(clientsInfos.length) &&
clientsInfos.every((x) => PTP_CLIENT_DISCONNECTED_STATES.includes(x.peerConnection && x.peerConnection.connectionState));
if (couldBeDisconnected) {
this._offlineTimeout = setTimeout(() => {
this._signalOffline();
}, CONSIDER_OFFLINE_TIME);
}
}, CHECK_OFFLINE_TIME);
this._peerToPeerLoading = new Promise(async (resolve) => {
if (!ICE_SERVERS) {
ICE_SERVERS = await this._serviceRpc('/web_editor/get_ice_servers');
}
let iceServers = ICE_SERVERS;
if (!iceServers.length) {
iceServers = [
{
urls: [
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
],
}
];
}
this._iceServers = iceServers;
this.ptp = this._getNewPtp();
resolve();
});
const editorCollaborationOptions = {
collaborationClientId: this._currentClientId,
onHistoryStep: (historyStep) => {
if (!this.ptp) return;
this.ptp.notifyAllClients('oe_history_step', historyStep, { transport: 'rtc' });
},
onCollaborativeSelectionChange: debounce((collaborativeSelection) => {
if (!this.ptp) return;
this.ptp.notifyAllClients('oe_history_set_selection', collaborativeSelection, { transport: 'rtc' });
}, 50),
onHistoryMissingParentSteps: async ({ step, fromStepId }) => {
if (!this.ptp) return;
const missingSteps = await this.requestClient(
step.clientId,
'get_missing_steps', {
fromStepId: fromStepId,
toStepId: step.id
},
{ transport: 'rtc' }
);
if (missingSteps === REQUEST_ERROR) return;
this._processMissingSteps(Array.isArray(missingSteps) ? missingSteps.concat(step) : missingSteps);
},
};
if (this.options.postProcessExternalSteps) {
editorCollaborationOptions.postProcessExternalSteps = this.options.postProcessExternalSteps;
}
return editorCollaborationOptions;
}
setupToolbar(toolbarEl) {
this.toolbarEl = toolbarEl;
this.odooEditor.setupToolbar(toolbarEl);
this._configureToolbar(this.options)
this._updateEditorUI();
}
/**
* @override
*/
destroy() {
// Sometimes, the component is started and destroyed so quickly that
// external calls to `wysiwyg.getColorPickerTemplateService()` fail by
// the time it's done, even though `wysiwyg` was properly instantiated.
// As it's not needed once the component is destroyed, we return null.
this.getColorPickerTemplateService = () => null;
Wysiwyg.activeWysiwygs.delete(this);
this._stopPeerToPeer();
document.removeEventListener("mousemove", this._signalOnline, true);
document.removeEventListener("keydown", this._signalOnline, true);
document.removeEventListener("keyup", this._signalOnline, true);
this._collaborationStopBus && this._collaborationStopBus();
if (this.odooEditor) {
this.odooEditor.document.removeEventListener("mousemove", this._signalOnline, true);
this.odooEditor.document.removeEventListener("keydown", this._signalOnline, true);
this.odooEditor.document.removeEventListener("keyup", this._signalOnline, true);
this.odooEditor.document.removeEventListener('selectionchange', this._onSelectionChange);
this.odooEditor.destroy();
}
// If peer to peer is initializing, wait for properly closing it.
if (this._peerToPeerLoading) {
this._peerToPeerLoading.then(()=> {
this._stopPeerToPeer();
this._collaborationStopBus && this._collaborationStopBus();
});
}
clearInterval(this._collaborationInterval);
this.$editable && this.$editable.off('blur', this._onBlur);
document.removeEventListener('mousedown', this._onDocumentMousedown, true);
const $body = $(document.body);
$body.off('mousemove', this.resizerMousemove);
$body.off('mouseup', this.resizerMouseup);
this.multiSelectionTarget?.removeEventListener('scroll', this.odooEditor.multiselectionRefresh, { passive: true });
this.$editable?.off('.Wysiwyg');
this.toolbarEl?.remove();
this.imageCropEL?.remove();
if (this.linkPopover) {
this.linkPopover.hide();
}
if (this._checkConnectionChange) {
window.removeEventListener('online', this._checkConnectionChange);
window.removeEventListener('offline', this._checkConnectionChange);
}
window.removeEventListener('beforeunload', this._onBeforeUnload);
for (const timeout of this.tooltipTimeouts) {
clearTimeout(timeout);
}
document.removeEventListener('scroll', this._onScroll, true);
}
/**
* @override
*/
_renderElement() {
this.$editable = this.options.editable || $('<div class="note-editable">');
// We add the field's name as id so default_focus will target it if
// needed. For that to work, it has to already be editable but note that
// the editor is at this point not yet instantiated.
if (typeof this.options.fieldId !== 'undefined' && !this.options.inIframe) {
this.$editable.attr('id', this.options.fieldId);
this.$editable.attr('contenteditable', true);
}
if (this.options.height) {
this.$editable.height(this.options.height);
}
if (this.options.minHeight) {
this.$editable.css('min-height', this.options.minHeight);
}
if (this.options.maxHeight && this.options.maxHeight > 10) {
this.$editable.css('max-height', this.options.maxHeight);
}
if (this.options.resizable && !isMobileOS()) {
const $wrapper = $('<div class="o_wysiwyg_wrapper odoo-editor">');
$wrapper.append(this.$editable);
this.$resizer = $(`<div class="o_wysiwyg_resizer">
<div class="o_wysiwyg_resizer_hook"></div>
<div class="o_wysiwyg_resizer_hook"></div>
<div class="o_wysiwyg_resizer_hook"></div>
</div>`);
$wrapper.append(this.$resizer);
this._replaceElement($wrapper);
const minHeight = this.options.minHeight || 100;
this.$editable.height(this.options.height || minHeight);
// resizer hooks
let startOffsetTop;
let startHeight;
const $body = $(document.body);
const resizerMousedown = (e) => {
e.preventDefault();
e.stopPropagation();
$body.on('mousemove', this.resizerMousemove);
$body.on('mouseup', this.resizerMouseup);
startHeight = this.$editable.height();
startOffsetTop = e.pageY;
};
this.resizerMousemove = (e) => {
const offsetTop = e.pageY - startOffsetTop;
let height = startHeight + offsetTop;
if (height < minHeight) {
height = minHeight;
}
this.$editable.height(height);
};
this.resizerMouseup = () => {
$body.off('mousemove', this.resizerMousemove);
$body.off('mouseup', this.resizerMouseup);
};
this.$resizer.on('mousedown', resizerMousedown);
} else {
if (!this.options.sideAttach) {
this._replaceElement(this.$editable);
}