-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathvaadin-rich-text-editor.js
1126 lines (991 loc) · 34.2 KB
/
vaadin-rich-text-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
/**
* @license
* Copyright (c) 2000 - 2022 Vaadin Ltd.
*
* This program is available under Vaadin Commercial License and Service Terms.
*
*
* See https://vaadin.com/commercial-license-and-service-terms for the full
* license.
*/
import '@vaadin/button/src/vaadin-button.js';
import '@vaadin/confirm-dialog/src/vaadin-confirm-dialog.js';
import '@vaadin/text-field/src/vaadin-text-field.js';
import '@vaadin/tooltip/src/vaadin-tooltip.js';
import '../vendor/vaadin-quill.js';
import './vaadin-rich-text-editor-toolbar-styles.js';
import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
import { timeOut } from '@vaadin/component-base/src/async.js';
import { isFirefox } from '@vaadin/component-base/src/browser-utils.js';
import { Debouncer } from '@vaadin/component-base/src/debounce.js';
import { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';
import { registerStyles, ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
import { richTextEditorStyles } from './vaadin-rich-text-editor-styles.js';
registerStyles('vaadin-rich-text-editor', richTextEditorStyles, { moduleId: 'vaadin-rich-text-editor-styles' });
const Quill = window.Quill;
const HANDLERS = [
'bold',
'italic',
'underline',
'strike',
'header',
'script',
'list',
'align',
'blockquote',
'code-block',
];
const SOURCE = {
API: 'api',
USER: 'user',
SILENT: 'silent',
};
const STATE = {
DEFAULT: 0,
FOCUSED: 1,
CLICKED: 2,
};
const TAB_KEY = 9;
/**
* `<vaadin-rich-text-editor>` is a Web Component for rich text editing.
* It provides a set of toolbar controls to apply formatting on the content,
* which is stored and can be accessed as HTML5 or JSON string.
*
* ```
* <vaadin-rich-text-editor></vaadin-rich-text-editor>
* ```
*
* Vaadin Rich Text Editor focuses on the structure, not the styling of content.
* Therefore, the semantic HTML5 tags such as <h1>, <strong> and <ul> are used,
* and CSS usage is limited to most common cases, like horizontal text alignment.
*
* ### Styling
*
* The following state attributes are available for styling:
*
* Attribute | Description | Part name
* -------------|-------------|------------
* `disabled` | Set to a disabled text editor | :host
* `readonly` | Set to a readonly text editor | :host
* `on` | Set to a toolbar button applied to the selected text | toolbar-button
*
* The following shadow DOM parts are available for styling:
*
* Part name | Description
* -------------------------------------|----------------
* `content` | The content wrapper
* `toolbar` | The toolbar wrapper
* `toolbar-group` | The group for toolbar controls
* `toolbar-group-history` | The group for histroy controls
* `toolbar-group-emphasis` | The group for emphasis controls
* `toolbar-group-heading` | The group for heading controls
* `toolbar-group-glyph-transformation` | The group for glyph transformation controls
* `toolbar-group-group-list` | The group for group list controls
* `toolbar-group-alignment` | The group for alignment controls
* `toolbar-group-rich-text` | The group for rich text controls
* `toolbar-group-block` | The group for preformatted block controls
* `toolbar-group-format` | The group for format controls
* `toolbar-button` | The toolbar button (applies to all buttons)
* `toolbar-button-undo` | The "undo" button
* `toolbar-button-redo` | The "redo" button
* `toolbar-button-bold` | The "bold" button
* `toolbar-button-italic` | The "italic" button
* `toolbar-button-underline` | The "underline" button
* `toolbar-button-strike` | The "strike-through" button
* `toolbar-button-h1` | The "header 1" button
* `toolbar-button-h2` | The "header 2" button
* `toolbar-button-h3` | The "header 3" button
* `toolbar-button-subscript` | The "subscript" button
* `toolbar-button-superscript` | The "superscript" button
* `toolbar-button-list-ordered` | The "ordered list" button
* `toolbar-button-list-bullet` | The "bullet list" button
* `toolbar-button-align-left` | The "left align" button
* `toolbar-button-align-center` | The "center align" button
* `toolbar-button-align-right` | The "right align" button
* `toolbar-button-image` | The "image" button
* `toolbar-button-link` | The "link" button
* `toolbar-button-blockquote` | The "blockquote" button
* `toolbar-button-code-block` | The "code block" button
* `toolbar-button-clean` | The "clean formatting" button
*
* See [Styling Components](https://vaadin.com/docs/latest/styling/custom-theme/styling-components) documentation.
*
* @fires {Event} change - Fired when the user commits a value change.
* @fires {CustomEvent} html-value-changed - Fired when the `htmlValue` property changes.
* @fires {CustomEvent} value-changed - Fired when the `value` property changes.
*
* @extends HTMLElement
* @mixes ElementMixin
* @mixes ThemableMixin
*/
class RichTextEditor extends ElementMixin(ThemableMixin(PolymerElement)) {
static get template() {
return html`
<style>
:host {
display: flex;
flex-direction: column;
box-sizing: border-box;
}
:host([hidden]) {
display: none !important;
}
.announcer {
position: fixed;
clip: rect(0, 0, 0, 0);
}
input[type='file'] {
display: none;
}
.vaadin-rich-text-editor-container {
display: flex;
flex-direction: column;
min-height: inherit;
max-height: inherit;
flex: auto;
}
</style>
<div class="vaadin-rich-text-editor-container">
<!-- Create toolbar container -->
<div part="toolbar" role="toolbar">
<span part="toolbar-group toolbar-group-history">
<!-- Undo and Redo -->
<button id="btn-undo" type="button" part="toolbar-button toolbar-button-undo" on-click="_undo"></button>
<vaadin-tooltip for="btn-undo" text="[[i18n.undo]]"></vaadin-tooltip>
<button id="btn-redo" type="button" part="toolbar-button toolbar-button-redo" on-click="_redo"></button>
<vaadin-tooltip for="btn-redo" text="[[i18n.redo]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-emphasis">
<!-- Bold -->
<button id="btn-bold" class="ql-bold" part="toolbar-button toolbar-button-bold"></button>
<vaadin-tooltip for="btn-bold" text="[[i18n.bold]]"></vaadin-tooltip>
<!-- Italic -->
<button id="btn-italic" class="ql-italic" part="toolbar-button toolbar-button-italic"></button>
<vaadin-tooltip for="btn-italic" text="[[i18n.italic]]"></vaadin-tooltip>
<!-- Underline -->
<button id="btn-underline" class="ql-underline" part="toolbar-button toolbar-button-underline"></button>
<vaadin-tooltip for="btn-underline" text="[[i18n.underline]]"></vaadin-tooltip>
<!-- Strike -->
<button id="btn-strike" class="ql-strike" part="toolbar-button toolbar-button-strike"></button>
<vaadin-tooltip for="btn-strike" text="[[i18n.strike]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-heading">
<!-- Header buttons -->
<button
id="btn-h1"
type="button"
class="ql-header"
value="1"
part="toolbar-button toolbar-button-h1"
></button>
<vaadin-tooltip for="btn-h1" text="[[i18n.h1]]"></vaadin-tooltip>
<button
id="btn-h2"
type="button"
class="ql-header"
value="2"
part="toolbar-button toolbar-button-h2"
></button>
<vaadin-tooltip for="btn-h2" text="[[i18n.h2]]"></vaadin-tooltip>
<button
id="btn-h3"
type="button"
class="ql-header"
value="3"
part="toolbar-button toolbar-button-h3"
></button>
<vaadin-tooltip for="btn-h3" text="[[i18n.h3]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-glyph-transformation">
<!-- Subscript and superscript -->
<button
id="btn-subscript"
class="ql-script"
value="sub"
part="toolbar-button toolbar-button-subscript"
></button>
<vaadin-tooltip for="btn-subscript" text="[[i18n.subscript]]"></vaadin-tooltip>
<button
id="btn-superscript"
class="ql-script"
value="super"
part="toolbar-button toolbar-button-superscript"
></button>
<vaadin-tooltip for="btn-superscript" text="[[i18n.superscript]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-list">
<!-- List buttons -->
<button
id="btn-ol"
type="button"
class="ql-list"
value="ordered"
part="toolbar-button toolbar-button-list-ordered"
></button>
<vaadin-tooltip for="btn-ol" text="[[i18n.listOrdered]]"></vaadin-tooltip>
<button
id="btn-ul"
type="button"
class="ql-list"
value="bullet"
part="toolbar-button toolbar-button-list-bullet"
></button>
<vaadin-tooltip for="btn-ul" text="[[i18n.listBullet]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-alignment">
<!-- Align buttons -->
<button
id="btn-left"
type="button"
class="ql-align"
value=""
part="toolbar-button toolbar-button-align-left"
></button>
<vaadin-tooltip for="btn-left" text="[[i18n.alignLeft]]"></vaadin-tooltip>
<button
id="btn-center"
type="button"
class="ql-align"
value="center"
part="toolbar-button toolbar-button-align-center"
></button>
<vaadin-tooltip for="btn-center" text="[[i18n.alignCenter]]"></vaadin-tooltip>
<button
id="btn-right"
type="button"
class="ql-align"
value="right"
part="toolbar-button toolbar-button-align-right"
></button>
<vaadin-tooltip for="btn-right" text="[[i18n.alignRight]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-rich-text">
<!-- Image -->
<button
id="btn-image"
type="button"
part="toolbar-button toolbar-button-image"
on-touchend="_onImageTouchEnd"
on-click="_onImageClick"
></button>
<vaadin-tooltip for="btn-image" text="[[i18n.image]]"></vaadin-tooltip>
<!-- Link -->
<button
id="btn-link"
type="button"
part="toolbar-button toolbar-button-link"
on-click="_onLinkClick"
></button>
<vaadin-tooltip for="btn-link" text="[[i18n.link]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-block">
<!-- Blockquote -->
<button
id="btn-blockquote"
type="button"
class="ql-blockquote"
part="toolbar-button toolbar-button-blockquote"
></button>
<vaadin-tooltip for="btn-blockquote" text="[[i18n.blockquote]]"></vaadin-tooltip>
<!-- Code block -->
<button
id="btn-code"
type="button"
class="ql-code-block"
part="toolbar-button toolbar-button-code-block"
></button>
<vaadin-tooltip for="btn-code" text="[[i18n.codeBlock]]"></vaadin-tooltip>
</span>
<span part="toolbar-group toolbar-group-format">
<!-- Clean -->
<button id="btn-clean" type="button" class="ql-clean" part="toolbar-button toolbar-button-clean"></button>
<vaadin-tooltip for="btn-clean" text="[[i18n.clean]]"></vaadin-tooltip>
</span>
<input
id="fileInput"
type="file"
accept="image/png, image/gif, image/jpeg, image/bmp, image/x-icon"
on-change="_uploadImage"
/>
</div>
<div part="content"></div>
<div class="announcer" aria-live="polite"></div>
</div>
<vaadin-confirm-dialog id="linkDialog" opened="{{_linkEditing}}" header="[[i18n.linkDialogTitle]]">
<vaadin-text-field
id="linkUrl"
value="{{_linkUrl}}"
style="width: 100%;"
on-keydown="_onLinkKeydown"
></vaadin-text-field>
<vaadin-button id="confirmLink" slot="confirm-button" theme="primary" on-click="_onLinkEditConfirm">
[[i18n.ok]]
</vaadin-button>
<vaadin-button
id="removeLink"
slot="reject-button"
theme="error"
on-click="_onLinkEditRemove"
hidden$="[[!_linkRange]]"
>
[[i18n.remove]]
</vaadin-button>
<vaadin-button id="cancelLink" slot="cancel-button" on-click="_onLinkEditCancel">
[[i18n.cancel]]
</vaadin-button>
</vaadin-confirm-dialog>
`;
}
static get is() {
return 'vaadin-rich-text-editor';
}
static get cvdlName() {
return 'vaadin-rich-text-editor';
}
static get properties() {
return {
/**
* Value is a list of the operations which describe change to the document.
* Each of those operations describe the change at the current index.
* They can be an `insert`, `delete` or `retain`. The format is as follows:
*
* ```js
* [
* { insert: 'Hello World' },
* { insert: '!', attributes: { bold: true }}
* ]
* ```
*
* See also https://github.com/quilljs/delta for detailed documentation.
* @type {string}
*/
value: {
type: String,
notify: true,
value: '',
},
/**
* HTML representation of the rich text editor content.
*/
htmlValue: {
type: String,
notify: true,
readOnly: true,
},
/**
* When true, the user can not modify, nor copy the editor content.
* @type {boolean}
*/
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* When true, the user can not modify the editor content, but can copy it.
* @type {boolean}
*/
readonly: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* An object used to localize this component. The properties are used
* e.g. as the tooltips for the editor toolbar buttons.
*
* @type {!RichTextEditorI18n}
* @default {English/US}
*/
i18n: {
type: Object,
value: () => {
return {
undo: 'undo',
redo: 'redo',
bold: 'bold',
italic: 'italic',
underline: 'underline',
strike: 'strike',
h1: 'h1',
h2: 'h2',
h3: 'h3',
subscript: 'subscript',
superscript: 'superscript',
listOrdered: 'list ordered',
listBullet: 'list bullet',
alignLeft: 'align left',
alignCenter: 'align center',
alignRight: 'align right',
image: 'image',
link: 'link',
blockquote: 'blockquote',
codeBlock: 'code block',
clean: 'clean',
linkDialogTitle: 'Link address',
ok: 'OK',
cancel: 'Cancel',
remove: 'Remove',
};
},
},
/** @private */
_editor: {
type: Object,
},
/**
* Stores old value
* @private
*/
__oldValue: String,
/** @private */
__lastCommittedChange: {
type: String,
value: '',
},
/** @private */
_linkEditing: {
type: Boolean,
},
/** @private */
_linkRange: {
type: Object,
value: null,
},
/** @private */
_linkIndex: {
type: Number,
value: null,
},
/** @private */
_linkUrl: {
type: String,
value: '',
},
};
}
static get observers() {
return ['_valueChanged(value, _editor)', '_disabledChanged(disabled, readonly, _editor)'];
}
/**
* @param {string} prop
* @param {?string} oldVal
* @param {?string} newVal
* @protected
*/
attributeChangedCallback(prop, oldVal, newVal) {
super.attributeChangedCallback(prop, oldVal, newVal);
if (prop === 'dir') {
this.__dir = newVal;
this.__setDirection(newVal);
}
}
/** @protected */
disconnectedCallback() {
super.disconnectedCallback();
this._editor.emitter.removeAllListeners();
this._editor.emitter.listeners = {};
}
/** @private */
__setDirection(dir) {
// Needed for proper `ql-align` class to be set and activate the toolbar align button
const alignAttributor = Quill.import('attributors/class/align');
alignAttributor.whitelist = [dir === 'rtl' ? 'left' : 'right', 'center', 'justify'];
Quill.register(alignAttributor, true);
const alignGroup = this._toolbar.querySelector('[part~="toolbar-group-alignment"]');
if (dir === 'rtl') {
alignGroup.querySelector('[part~="toolbar-button-align-left"]').value = 'left';
alignGroup.querySelector('[part~="toolbar-button-align-right"]').value = '';
} else {
alignGroup.querySelector('[part~="toolbar-button-align-left"]').value = '';
alignGroup.querySelector('[part~="toolbar-button-align-right"]').value = 'right';
}
this._editor.getModule('toolbar').update(this._editor.getSelection());
}
/** @protected */
connectedCallback() {
super.connectedCallback();
const editor = this.shadowRoot.querySelector('[part="content"]');
this._editor = new Quill(editor, {
modules: {
toolbar: this._toolbarConfig,
},
});
this.__patchToolbar();
this.__patchKeyboard();
/* c8 ignore next 3 */
if (isFirefox) {
this.__patchFirefoxFocus();
}
const editorContent = editor.querySelector('.ql-editor');
editorContent.setAttribute('role', 'textbox');
editorContent.setAttribute('aria-multiline', 'true');
this._editor.on('text-change', () => {
const timeout = 200;
this.__debounceSetValue = Debouncer.debounce(this.__debounceSetValue, timeOut.after(timeout), () => {
this.value = JSON.stringify(this._editor.getContents().ops);
});
});
editorContent.addEventListener('focusout', () => {
if (this._toolbarState === STATE.FOCUSED) {
this._cleanToolbarState();
} else {
this.__emitChangeEvent();
}
});
editorContent.addEventListener('focus', () => {
// Format changed, but no value changed happened
if (this._toolbarState === STATE.CLICKED) {
this._cleanToolbarState();
}
});
this._editor.on('selection-change', this.__announceFormatting.bind(this));
}
/** @protected */
ready() {
super.ready();
this._toolbarConfig = this._prepareToolbar();
this._toolbar = this._toolbarConfig.container;
this._addToolbarListeners();
this.$.linkDialog.$.dialog.$.overlay.addEventListener('vaadin-overlay-open', () => {
this.$.linkUrl.focus();
});
}
/** @private */
_prepareToolbar() {
const clean = Quill.imports['modules/toolbar'].DEFAULTS.handlers.clean;
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
const toolbar = {
container: this.shadowRoot.querySelector('[part="toolbar"]'),
handlers: {
clean() {
self._markToolbarClicked();
clean.call(this);
},
},
};
HANDLERS.forEach((handler) => {
toolbar.handlers[handler] = (value) => {
this._markToolbarClicked();
this._editor.format(handler, value, SOURCE.USER);
};
});
return toolbar;
}
/** @private */
_addToolbarListeners() {
const buttons = this._toolbarButtons;
const toolbar = this._toolbar;
// Disable tabbing to all buttons but the first one
buttons.forEach((button, index) => index > 0 && button.setAttribute('tabindex', '-1'));
toolbar.addEventListener('keydown', (e) => {
// Use roving tab-index for the toolbar buttons
if ([37, 39].indexOf(e.keyCode) > -1) {
e.preventDefault();
let index = buttons.indexOf(e.target);
buttons[index].setAttribute('tabindex', '-1');
let step;
if (e.keyCode === 39) {
step = 1;
} else if (e.keyCode === 37) {
step = -1;
}
index = (buttons.length + index + step) % buttons.length;
buttons[index].removeAttribute('tabindex');
buttons[index].focus();
}
// Esc and Tab focuses the content
if (e.keyCode === 27 || (e.keyCode === TAB_KEY && !e.shiftKey)) {
e.preventDefault();
this._editor.focus();
}
});
// Mousedown happens before editor focusout
toolbar.addEventListener('mousedown', (e) => {
if (buttons.indexOf(e.composedPath()[0]) > -1) {
this._markToolbarFocused();
}
});
}
/** @private */
_markToolbarClicked() {
this._toolbarState = STATE.CLICKED;
}
/** @private */
_markToolbarFocused() {
this._toolbarState = STATE.FOCUSED;
}
/** @private */
_cleanToolbarState() {
this._toolbarState = STATE.DEFAULT;
}
/** @private */
__createFakeFocusTarget() {
const isRTL = document.documentElement.getAttribute('dir') === 'rtl';
const elem = document.createElement('textarea');
// Reset box model
elem.style.border = '0';
elem.style.padding = '0';
elem.style.margin = '0';
// Move element out of screen horizontally
elem.style.position = 'absolute';
elem.style[isRTL ? 'right' : 'left'] = '-9999px';
// Move element to the same position vertically
const yPosition = window.pageYOffset || document.documentElement.scrollTop;
elem.style.top = `${yPosition}px`;
return elem;
}
/** @private */
__patchFirefoxFocus() {
// In Firefox 63+ with native Shadow DOM, when moving focus out of
// contenteditable and back again within same shadow root, cursor
// disappears. See https://bugzilla.mozilla.org/show_bug.cgi?id=1496769
const editorContent = this.shadowRoot.querySelector('.ql-editor');
let isFake = false;
const focusFake = () => {
isFake = true;
this.__fakeTarget = this.__createFakeFocusTarget();
document.body.appendChild(this.__fakeTarget);
// Let the focus step out of shadow root!
this.__fakeTarget.focus();
return new Promise((resolve) => {
setTimeout(resolve);
});
};
const focusBack = (offsetNode, offset) => {
this._editor.focus();
if (offsetNode) {
this._editor.selection.setNativeRange(offsetNode, offset);
}
document.body.removeChild(this.__fakeTarget);
delete this.__fakeTarget;
isFake = false;
};
editorContent.addEventListener('mousedown', (e) => {
if (!this._editor.hasFocus()) {
const { x, y } = e;
const { offset, offsetNode } = document.caretPositionFromPoint(x, y);
focusFake().then(() => {
focusBack(offsetNode, offset);
});
}
});
editorContent.addEventListener('focusin', () => {
if (isFake === false) {
focusFake().then(() => focusBack());
}
});
}
/** @private */
__patchToolbar() {
const toolbar = this._editor.getModule('toolbar');
const update = toolbar.update;
// Add custom link button to toggle state attribute
toolbar.controls.push(['link', this.shadowRoot.querySelector('[part~="toolbar-button-link"]')]);
toolbar.update = function (range) {
update.call(toolbar, range);
toolbar.controls.forEach((pair) => {
const input = pair[1];
if (input.classList.contains('ql-active')) {
input.setAttribute('on', '');
} else {
input.removeAttribute('on');
}
});
};
}
/** @private */
__patchKeyboard() {
const focusToolbar = () => {
this._markToolbarFocused();
this._toolbar.querySelector('button:not([tabindex])').focus();
};
const keyboard = this._editor.getModule('keyboard');
const bindings = keyboard.bindings[TAB_KEY];
// Exclude Quill shift-tab bindings, except for code block,
// as some of those are breaking when on a newline in the list
// https://github.com/vaadin/vaadin-rich-text-editor/issues/67
const originalBindings = bindings.filter((b) => !b.shiftKey || (b.format && b.format['code-block']));
const moveFocusBinding = { key: TAB_KEY, shiftKey: true, handler: focusToolbar };
keyboard.bindings[TAB_KEY] = [...originalBindings, moveFocusBinding];
// Alt-f10 focuses a toolbar button
keyboard.addBinding({ key: 121, altKey: true, handler: focusToolbar });
}
/** @private */
__emitChangeEvent() {
let lastCommittedChange = this.__lastCommittedChange;
if (this.__debounceSetValue && this.__debounceSetValue.isActive()) {
lastCommittedChange = this.value;
this.__debounceSetValue.flush();
}
if (lastCommittedChange !== this.value) {
this.dispatchEvent(new CustomEvent('change', { bubbles: true, cancelable: false }));
this.__lastCommittedChange = this.value;
}
}
/** @private */
_onLinkClick() {
const range = this._editor.getSelection();
if (range) {
const LinkBlot = Quill.imports['formats/link'];
const [link, offset] = this._editor.scroll.descendant(LinkBlot, range.index);
if (link != null) {
// Existing link
this._linkRange = { index: range.index - offset, length: link.length() };
this._linkUrl = LinkBlot.formats(link.domNode);
} else if (range.length === 0) {
this._linkIndex = range.index;
}
this._linkEditing = true;
}
}
/** @private */
_applyLink(link) {
if (link) {
this._markToolbarClicked();
this._editor.format('link', link, SOURCE.USER);
this._editor.getModule('toolbar').update(this._editor.selection.savedRange);
}
this._closeLinkDialog();
}
/** @private */
_insertLink(link, position) {
if (link) {
this._markToolbarClicked();
this._editor.insertText(position, link, { link });
this._editor.setSelection(position, link.length);
}
this._closeLinkDialog();
}
/** @private */
_updateLink(link, range) {
this._markToolbarClicked();
this._editor.formatText(range, 'link', link, SOURCE.USER);
this._closeLinkDialog();
}
/** @private */
_removeLink() {
this._markToolbarClicked();
if (this._linkRange != null) {
this._editor.formatText(this._linkRange, { link: false, color: false }, SOURCE.USER);
}
this._closeLinkDialog();
}
/** @private */
_closeLinkDialog() {
this._linkEditing = false;
this._linkUrl = '';
this._linkIndex = null;
this._linkRange = null;
}
/** @private */
_onLinkEditConfirm() {
if (this._linkIndex != null) {
this._insertLink(this._linkUrl, this._linkIndex);
} else if (this._linkRange) {
this._updateLink(this._linkUrl, this._linkRange);
} else {
this._applyLink(this._linkUrl);
}
}
/** @private */
_onLinkEditCancel() {
this._closeLinkDialog();
this._editor.focus();
}
/** @private */
_onLinkEditRemove() {
this._removeLink();
this._closeLinkDialog();
}
/** @private */
_onLinkKeydown(e) {
if (e.keyCode === 13) {
e.preventDefault();
e.stopPropagation();
this.$.confirmLink.click();
}
}
/** @private */
__updateHtmlValue() {
const editor = this.shadowRoot.querySelector('.ql-editor');
let content = editor.innerHTML;
// Remove Quill classes, e.g. ql-syntax, except for align
content = content.replace(/\s*ql-(?!align)[\w-]*\s*/g, '');
// Remove meta spans, e.g. cursor which are empty after Quill classes removed
content = content.replace(/<\/?span[^>]*>/gu, '');
// Replace Quill align classes with inline styles
[this.__dir === 'rtl' ? 'left' : 'right', 'center', 'justify'].forEach((align) => {
content = content.replace(
new RegExp(` class=[\\\\]?"\\s?ql-align-${align}[\\\\]?"`, 'g'),
` style="text-align: ${align}"`,
);
});
content = content.replace(/ class=""/g, '');
this._setHtmlValue(content);
}
/**
* Sets content represented by HTML snippet into the editor.
* The snippet is interpreted by [Quill's Clipboard matchers](https://quilljs.com/docs/modules/clipboard/#matchers),
* which may not produce the exactly input HTML.
*
* **NOTE:** Improper handling of HTML can lead to cross site scripting (XSS) and failure to sanitize
* properly is both notoriously error-prone and a leading cause of web vulnerabilities.
* This method is aptly named to ensure the developer has taken the necessary precautions.
* @param {string} htmlValue
*/
dangerouslySetHtmlValue(htmlValue) {
const deltaFromHtml = this._editor.clipboard.convert(htmlValue);
this._editor.setContents(deltaFromHtml, SOURCE.API);
}
/** @private */
__announceFormatting() {
const timeout = 200;
const announcer = this.shadowRoot.querySelector('.announcer');
announcer.textContent = '';
this.__debounceAnnounceFormatting = Debouncer.debounce(
this.__debounceAnnounceFormatting,
timeOut.after(timeout),
() => {
const formatting = Array.from(this.shadowRoot.querySelectorAll('[part="toolbar"] .ql-active'))
.map((button) => {
const tooltip = this.shadowRoot.querySelector(`[for="${button.id}"]`);
return tooltip.text;
})
.join(', ');
announcer.textContent = formatting;
},
);
}
/** @private */
get _toolbarButtons() {
return Array.from(this.shadowRoot.querySelectorAll('[part="toolbar"] button')).filter((btn) => {
return btn.clientHeight > 0;
});
}
/** @private */
_clear() {
this._editor.deleteText(0, this._editor.getLength(), SOURCE.SILENT);
this.__updateHtmlValue();
}
/** @private */
_undo(e) {
e.preventDefault();
this._editor.history.undo();
this._editor.focus();
}
/** @private */
_redo(e) {
e.preventDefault();
this._editor.history.redo();
this._editor.focus();