/
editor.js
3376 lines (2961 loc) · 113 KB
/
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
/* eslint-disable no-useless-escape */
/* eslint-disable no-restricted-syntax */
/* eslint-disable consistent-return */
import { Environment as env } from '../../utils/environment';
import { debounce } from '../../utils/debounced-resize';
import * as debug from '../../utils/debug';
import { warnAboutDeprecation } from '../../utils/deprecated';
import { utils } from '../../utils/utils';
import { FontPickerStyle } from '../fontpicker/fontpicker';
import { Locale } from '../locale/locale';
import { ToolbarFlexItem } from '../toolbar-flex/toolbar-flex.item';
import { xssUtils } from '../../utils/xss';
import { DOM } from '../../utils/dom';
import { theme } from '../theme/theme';
// jQuery Components
import '../colorpicker/colorpicker.jquery';
import '../fontpicker/fontpicker.jquery';
import '../toolbar/toolbar.jquery';
import '../toolbar-flex/toolbar-flex.jquery';
import '../tooltip/tooltip.jquery';
const COMPONENT_NAME = 'editor';
const EDITOR_PARENT_ELEMENTS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'code'];
/**
* The Editor Component displays and edits markdown.
*
* @class Editor
* @param {string} element The component element.
* @param {string} [settings] The component settings.
* @param {string} [settings.buttons =
* { editor: [ 'header1', 'header2', 'separator', 'bold', 'italic', 'underline', 'strikethrough',
* 'separator', 'foreColor', 'backColor', 'separator', 'justifyLeft', 'justifyCenter', 'justifyRight', 'separator', 'quote', 'orderedlist',
* 'unorderedlist', 'separator', 'anchor', 'separator', 'image', 'separator', 'source' ], source: [ 'visual' ] }]
* An array with all the visible buttons in it.
* @param {string} [settings.excludeButtons = { editor: ['backColor'], source: [] }] An array with all the buttons in it to excloude
* @param {string} [settings.firstHeader = 'h3'] Allows you to set if the first header inserted is a h3 or h4 element.
* You should set this to match the structure of the parent page for accessibility
* @param {boolean} [settings.secondHeader = 'h4'] Allows you to set if the second header inserted is a h3 or
* h4 element. You should set this to match the structure of the parent page for accessibility
* @param {string} [settings.placeholder] If set to some text this will be shown as placeholder text in the editor.
* @param {string} [settings.pasteAsPlainText = false] If true, when you paste into the editor the element will be unformatted to plain text.
* @param {string} [settings.anchor = { url: 'http://www.example.com', class: 'hyperlink', target: 'NewWindow', isClickable: false, showIsClickable: false }] An object with settings related to controlling link behavior when inserted example: `{url: 'http://www.example.com', class: 'hyperlink', target: 'NewWindow', isClickable: false, showIsClickable: false},` the url is the default url to display. Class should normally stay hyperlink and represents the styling class. target can be 'NewWindow' or 'SameWindow', isClickable make the links appear clickable in the editor, showIsClickable will show a checkbox to allow the user to make clickable links in the link popup.
* @param {string} [settings.image = { url: 'https://imgplaceholder.com/250x250/2578A9/ffffff/fa-image' }] Info object to populate the image dialog defaulting to ` {url: 'http://lorempixel.com/output/cats-q-c-300-200-3.jpg'}`
* @param {function} [settings.onLinkClick = null] Call back for clicking on links to control link behavior.
* @param {function} [settings.showHtmlView = false] If set to true, editor should be displayed in HTML view initialy.
* @param {function} [settings.preview = false] If set to true, editor should be displayed in preview mode with noneditable content.
* @param {string} [settings.paragraphSeparator = 'p'] Only can use 'p'|'br'|'div', If set to anything else will not run `defaultParagraphSeparator` execCommand.
* @param {boolean} [settings.useFlexToolbar = false] if set to true, renders the toolbar as flex toolbar.
* @param {boolean} [settings.useSourceFormatter = false] true will format the html content in source mode.
* @param {boolean} [settings.formatterTabsize = 4] number of spaces can use for indentation.
* @param {boolean} [settings.rows = null] Number of rows that will be shown in each part of the editor. Set like textarea rows attributes to adjust the height of the editor without css. Example: `{ editor: 10, source: 20 }`
* @param {array|object} [settings.attributes = null] Add extra attributes like id's to the chart elements. For example `attributes: { name: 'id', value: 'my-unique-id' }`
*/
const EDITOR_DEFAULTS = {
buttons: {
editor: [
'fontPicker',
'separator', 'bold', 'italic', 'underline', 'strikethrough',
'separator', 'foreColor', 'backColor',
'separator', 'justifyLeft', 'justifyCenter', 'justifyRight',
'separator', 'quote', 'orderedlist', 'unorderedlist',
'separator', 'anchor',
'separator', 'image',
'separator', 'clearFormatting',
'separator', 'generative',
'separator', 'source'
],
source: [
'fontPicker',
'separator', 'bold', 'italic', 'underline', 'strikethrough',
'separator', 'foreColor', 'backColor',
'separator', 'justifyLeft', 'justifyCenter', 'justifyRight',
'separator', 'quote', 'orderedlist', 'unorderedlist',
'separator', 'anchor',
'separator', 'image',
'separator', 'clearFormatting',
'separator', 'generative',
'separator', 'visual',
]
},
excludeButtons: {
editor: ['backColor', 'generative'],
source: ['backColor', 'generative']
},
rows: {
editor: null,
source: null
},
delay: 200,
placeholder: null,
pasteAsPlainText: false,
// anchor > target: 'SameWindow'|'NewWindow'| any string value
anchor: {
url: 'http://www.example.com',
class: 'hyperlink',
target: 'NewWindow',
isClickable: false,
showIsClickable: false
},
image: {
url: '/images/placeholder-80x80.png'
},
onLinkClick: null,
showHtmlView: false,
preview: false,
paragraphSeparator: 'p',
useFlexToolbar: true,
useSourceFormatter: false,
formatterTabsize: 4,
fontpickerSettings: {
popupmenuSettings: {
showArrow: false,
offset: {
y: 0
}
}
},
attributes: null
};
function Editor(element, settings) {
this.settings = utils.mergeSettings(element, settings, EDITOR_DEFAULTS);
if (settings?.buttons) {
this.settings.buttons = settings.buttons;
}
if (settings?.excludeButtons) {
this.settings.excludeButtons = settings.excludeButtons;
}
this.element = $(element);
debug.logTimeStart(COMPONENT_NAME);
this.init();
debug.logTimeEnd(COMPONENT_NAME);
}
// Editor Methods
Editor.prototype = {
/**
* @returns {Toolbar|ToolbarFlex} a reference to the Editor's Toolbar API
*/
get toolbarAPI() {
let api;
if (this.toolbar && this.toolbar.length) {
api = this.toolbar.data(this.settings.useFlexToolbar ? 'toolbar-flex' : 'toolbar');
}
return api;
},
init() {
this.id = `${utils.uniqueId(this.element, 'editor')}-id`;
this.container = this.element.parent('.field, .field-short').addClass('editor-container');
this.label = this.element.prevAll('.label').first();
// Preview mode
if (!this.previewRendered && (this.element.hasClass('is-preview') || this.settings.preview)) {
this.container[0].classList.add('is-preview');
this.element[0].classList.remove('is-disabled', 'is-readonly', 'is-preview');
this.element[0].setAttribute('contenteditable', false);
this.element[0].removeAttribute('aria-multiline');
this.element[0].removeAttribute('role');
return;
}
const s = this.settings;
s.anchor = $.extend({}, EDITOR_DEFAULTS.anchor, s.anchor);
s.image = $.extend({}, EDITOR_DEFAULTS.image, s.image);
s.anchor.defaultUrl = s.anchor.url;
s.anchor.defaultClass = s.anchor.class;
s.anchor.defaultTargetText = s.anchor.target;
s.anchor.defaultIsClickable = s.anchor.isClickable;
s.anchor.targets = s.anchor.targets || {
SameWindow: '',
NewWindow: '_blank'
};
$.each(this.settings.anchor.targets, (key, val) => {
if ((this.settings.anchor.defaultTargetText).toLowerCase() === (key).toLowerCase()) {
this.settings.anchor.target = val;
this.settings.anchor.defaultTarget = val;
}
});
// Convert legacy header settings into Fontpicker settings
if (this.settings.firstHeader || this.settings.secondHeader) {
if (!Array.isArray(this.settings.fontpickerSettings.styles)) {
this.settings.fontpickerSettings.styles = [];
}
if (!this.settings.fontpickerSettings.styles.length) {
this.settings.fontpickerSettings.styles.push(new FontPickerStyle('legacyDefault', 'Default'));
}
if (this.settings.firstHeader) {
warnAboutDeprecation('`fontpickerSettings.styles` setting', '`firstHeader` setting', 'Editor Component');
this.settings.fontpickerSettings.styles.push(new FontPickerStyle('legacyHeader1', 'Header 1', this.settings.firstHeader));
delete this.settings.firstHeader;
}
if (this.settings.secondHeader) {
warnAboutDeprecation('`fontpickerSettings.styles` setting', '`secondHeader` setting', 'Editor Component');
this.settings.fontpickerSettings.styles.push(new FontPickerStyle('legacyHeader2', 'Header 2', this.settings.secondHeader));
delete this.settings.secondHeader;
}
}
if (s.buttons && s.buttons.editor) {
let foundOldSettings = false;
const styles = [new FontPickerStyle('default', 'Default', 'p')];
const headers = s.buttons.editor.filter(el => el.substr(0, 6) === 'header');
for (let i = 0; i < headers.length; i++) {
const hLevel = headers[i].substr(6, 1);
foundOldSettings = true;
styles.push(new FontPickerStyle(`header${hLevel}`, `Header ${hLevel}`, `h${hLevel}`));
}
if (s.buttons.editor[0] === 'separator') {
s.buttons.editor.splice(0, 1);
}
if (foundOldSettings) {
s.buttons.editor = s.buttons.editor.filter(el => el.substr(0, 6) !== 'header');
s.fontpickerSettings = { styles };
}
if (foundOldSettings) {
s.buttons.editor = ['fontPicker'].concat(s.buttons.editor);
}
}
if (!s.anchor.defaultTarget) {
if (s.anchor.target && $.trim(s.anchor.target).length) {
s.anchor.defaultTarget = s.anchor.target;
} else {
s.anchor.defaultTargetText = Locale.translate('SameWindow');
s.anchor.defaultTarget = s.anchor.targets[s.anchor.defaultTargetText];
}
}
this.setup();
// Set default paragraph separator
if (typeof s.paragraphSeparator === 'string' && /^(p|br|div)$/.test(s.paragraphSeparator)) {
document.execCommand('defaultParagraphSeparator', false, s.paragraphSeparator);
}
if (this.element.hasClass('is-readonly')) {
this.readonly();
}
if (this.settings.showHtmlView) {
this.toggleSource();
}
this.setRowsHeight();
return this;
},
setup() {
this.isActive = true;
this.modals = {};
this.initElements()
.bindSelect()
.bindPaste()
.setPlaceholders()
.bindWindowActions()
.setupKeyboardEvents()
.onPasteTriggered();
},
initElements() {
// Make it an editor
this.element.attr({
contentEditable: true,
'aria-multiline': true,
role: 'textbox',
'aria-labelledby': this.container.find('.label').length ? this.container.find('.label')[0].id : 'no-id'
});
// Bind functionality for Pre elements. We dont use this yet but could if we
// want to edit code blocks.
this.element.attr('data-editor', true);
// Build the textarea that will be used as source view and for content serialization
this.initTextarea();
this.bindParagraphCreation().bindTab();
this.createToolbar()
.bindButtons()
.bindModals()
.bindAnchorPreview();
return this;
},
// Returns true if the source view is currently active.
sourceViewActive() {
return this.element.hasClass('source-view-active');
},
// Bind Events for the place holder
setPlaceholders() {
if (!this.settings.placeholder) {
return this;
}
this.element.attr('placeholder', this.settings.placeholder);
return this;
},
// Returns the currently visible element - either the main editor window,
// or the source-view textarea
getCurrentElement() {
return this.sourceViewActive() ? this.textarea : this.element;
},
bindSelection(selectionTimer) {
clearTimeout(selectionTimer);
selectionTimer = setTimeout(() => {
this.checkSelection();
}, this.settings.delay);
},
bindSelect() {
const selectionTimer = '';
const currentElement = this.getCurrentElement();
currentElement.on('mouseup.editor', () => {
this.bindSelection(selectionTimer);
});
return this;
},
bindParagraphCreation() {
const selectionTimer = '';
const currentElement = this.getCurrentElement();
currentElement.on('keyup.editor', (e) => {
let node = this.getSelectionStart();
const tagName = node.tagName.toLowerCase();
if (node && node.getAttribute('data-editor') && node.children.length === 0) {
document.execCommand('formatBlock', false, 'p');
}
if (e.which === 13) {
node = this.getSelectionStart();
if (tagName === 'blockquote') {
return;
}
if (tagName !== 'li' && !this.isListItemChild(node)) {
if (!e.shiftKey) {
document.execCommand('formatBlock', false, 'p');
}
if (tagName === 'a') {
document.execCommand('unlink', false, null);
}
}
}
this.bindSelection(selectionTimer);
});
return this;
},
bindTab() {
const currentElement = this.getCurrentElement();
currentElement.on('keydown.editor', (e) => {
if (e.which === 9) {
// Override tab only for pre nodes
const selectionStart = this.getSelectionStart();
if (!selectionStart || !selectionStart.tagName) {
return;
}
const tag = selectionStart.tagName.toLowerCase();
if (tag === 'pre') {
e.preventDefault();
document.execCommand('insertHtml', null, ' ');
}
// Tab to indent list structures!
if (tag === 'li') {
e.preventDefault();
// If Shift is down, outdent, otherwise indent
document.execCommand((e.shiftKey ? 'outdent' : 'indent'), e);
}
}
if (e.which === 8) {
const text = this.element.text().toString().trim().replace(/\s/g, '');
if (window.getSelection().toString().trim().replace(/\s/g, '') === text) {
this.element.html('');
}
}
});
return this;
},
// Set excluded buttons
setExcludedButtons() {
const excludeButtons = (elements, toExclude) => {
let separatorIndex = -1;
let numOfExcluded = 0;
return elements.filter((x, i) => {
let r = true;
// Exclude matching buttons but keep separator/s
if (toExclude.indexOf(x) > -1 && x !== 'separator') {
numOfExcluded++;
r = false;
} else if (x === 'separator' && ((i - numOfExcluded - 1) === separatorIndex)) {
// Exclude extra separator/s
numOfExcluded = 0;
r = false;
}
if (x === 'separator') {
separatorIndex = i;
}
return r;
});
};
// Run only if it needs (excludeButtons)
const setButtons = () => {
const s = this.settings;
const btns = s.buttons;
const exBtns = s.excludeButtons;
if (this.sourceViewActive()) {
return (exBtns && exBtns.source && exBtns.source.length) ?
excludeButtons(btns.source, exBtns.source) : btns.source;
}
return (exBtns && exBtns.editor && exBtns.editor.length) ?
excludeButtons(btns.editor, exBtns.editor) : btns.editor;
};
return setButtons();
},
/**
* @private
* @returns {this} component instance
*/
createToolbar() {
if (this.toolbar) {
return this;
}
const toolbarCssClasses = [
this.settings.useFlexToolbar ? 'flex-toolbar' : 'toolbar',
'editor-toolbar',
'formatter-toolbar'
].join(' ');
let sectionCss = '';
let moreButtonHTML = '';
if (this.settings.useFlexToolbar) {
sectionCss = 'toolbar-section ';
moreButtonHTML = `<div class="toolbar-section more">
<button class="btn-actions btn-editor">
<svg class="icon" focusable="false" aria-hidden="true" role="presentation">
<use href="#icon-more"></use>
</svg>
</button>
</div>`;
}
const btns = this.setExcludedButtons();
let buttonsHTML = '';
for (let i = 0, l = btns.length; i < l; i += 1) {
let btn = this.buttonTemplate(btns[i]);
if (btn && this.element.hasClass('source-view-active') && btns[i] !== 'visual') {
btn = btn.replace('type="button"', 'type="button" disabled');
}
if (btn) {
buttonsHTML += btn;
}
}
// Add automation attributes to each buttons
let btnAttributes = '';
if (this.settings.attributes) {
btnAttributes = this.getAutomationAttributes('-editor-toolbar');
btnAttributes = JSON.stringify(btnAttributes);
btnAttributes = ` data-options='{"attributes": ${btnAttributes}}'`;
}
const toolbar = `<div class="${toolbarCssClasses}" data-init="false" id="editor-toolbar-${this.id}"${btnAttributes}>
<div class="${sectionCss}buttonset">
${buttonsHTML}
</div>
${moreButtonHTML}
</div>`;
if (this.element.parent().find('.icon-dirty').length) {
this.toolbar = $(toolbar).insertBefore(this.element.parent().find('.icon-dirty'));
} else {
this.toolbar = $(toolbar).insertBefore(this.sourceViewActive() ?
this.element.prev() : this.element);
}
// Invoke Fontpicker, if applicable
const fpElement = this.toolbar.find('[data-action="fontStyle"]').first();
if (fpElement && fpElement.length) {
// Set suffix for fontpicker automation attributes
if (this.settings.attributes) {
const fpAttributes = this.getAutomationAttributes('-editor-fontpicker');
if (typeof this.settings.fontpickerSettings.popupmenuSettings === 'object') {
this.settings.fontpickerSettings.popupmenuSettings.attributes = fpAttributes;
} else if (!this.settings.fontpickerSettings.popupmenuSettings) {
this.settings.fontpickerSettings.popupmenuSettings = { attributes: fpAttributes };
}
}
fpElement.fontpicker(this.settings.fontpickerSettings);
this.fontPickerElem = fpElement;
this.fontPickerElem.tooltip({
placementOpts: {
x: 40
}
});
}
// Invoke Colorpicker, if applicable
const cpElements = this.toolbar.find('[data-action="foreColor"], [data-action="backColor"]');
cpElements.colorpicker({
placeIn: 'editor',
popupmenuSettings: {
offset: {
y: 0
},
showArrow: false
}
});
$('.trigger', cpElements).off('click.colorpicker');
// Invoke the (Flex?) Toolbar
this.toolbar[this.settings.useFlexToolbar ? 'toolbarflex' : 'toolbar']({
moreMenuSettings: {
offset: {
y: 0
},
showArrow: false
}
});
// Invoke Tooltips
this.toolbar.find('button[title]').tooltip();
// Adjust color picker alignment, for opened by toolbar overflowed items
cpElements.on('beforeopen.editor', (e, menu) => {
const toolbarApi = this.toolbar.data('toolbar') || this.toolbar.data('toolbar-flex');
if (toolbarApi) {
toolbarApi.overflowedItems.forEach((item) => {
if (item.type === 'colorpicker' && menu) {
menu.parent('.popupmenu-wrapper')
.off('afterplace.editor') // if reached more then once
.one('afterplace.editor', (evt, args) => {
if (typeof args.width === 'undefined') {
const containerW = args.container?.outerWidth() || -1;
const elementW = args.element?.outerWidth() || -1;
const left = (containerW - elementW) / 2;
if (left > -1) {
args.element.css('left', `${left}px`);
}
}
});
}
});
}
});
return this;
},
/**
* Get append suffix with automation attributes
* @private
* @param {string} suffix to use
* @returns {object|array} attributes with suffix
*/
getAutomationAttributes(suffix) {
const s = this.settings;
let attributes = s.attributes;
if (s.attributes && typeof suffix === 'string' && suffix !== '') {
if (Array.isArray(s.attributes)) {
attributes = [];
s.attributes.forEach((item) => {
const value = typeof item.value === 'function' ? item.value(this) : item.value;
attributes.push({ name: item.name, value: (value + suffix) });
});
} else {
const value = typeof s.attributes.value === 'function' ? s.attributes.value(this) : s.attributes.value;
attributes = { name: s.attributes.name, value: (value + suffix) };
}
}
return attributes;
},
/**
* Switch between source and editing toolbar.
* @returns {void}
*/
switchToolbars() {
this.destroyToolbar();
// Rebind everything to the new element
this.setupTextareaEvents();
this.createToolbar();
this.bindButtons().bindModals().bindAnchorPreview();
this.bindSelect().bindPaste().setupKeyboardEvents();
this.toolbar.find('button').button();
},
initTextarea() {
const self = this;
if (this.textarea && !this.settings.showHtmlView) {
return this;
}
this.textarea = this.createTextarea();
// fill the text area with any content that may already exist within the editor DIV
this.textarea.text(xssUtils.sanitizeHTML(this.element.html().toString()));
self.container.on('input.editor keyup.editor', '.editor', debounce((e) => {
/// The last savedSelection was always replaced on this section so we need to disabled this event when CTRL+H was used.
if (e.keyCode !== 72 && !e.ctrlKey && $('.modal.is-visible').length < 1) {
this.textarea.text(xssUtils.sanitizeHTML(this.element.html().toString()));
this.resetEmptyEditor(e);
this.element.trigger('change');
}
}, 400));
$('html').on(`themechanged.${COMPONENT_NAME}`, () => {
this.setRowsHeight();
if (!(this.sourceView.hasClass('hidden'))) {
this.adjustSourceLineNumbers();
}
});
this.setupTextareaEvents();
return this.textarea;
},
/**
* Set or reset the `rows` setting height
* @private
*/
setRowsHeight() {
const isNew = theme.currentTheme.id && (theme.currentTheme.id.indexOf('uplift') > -1 || theme.currentTheme.id.indexOf('new') > -1);
if (this.settings?.rows?.editor) {
this.element.height(Number(this.settings?.rows?.editor) * (isNew ? 26 : 22.2));
}
if (this.settings?.rows?.source) {
this.element.parent().find('.editor-source').height((Number(this.settings?.rows?.source) * (isNew ? 26 : 26)) + 15);
}
},
/**
* Clean up the editor content on change.
* @private
*/
resetEmptyEditor() {
this.savedSelection = this.saveSelection();
const sep = this.settings.paragraphSeparator === 'p' ? 'p' : 'div';
let html = this.element.html().toString().trim();
// Cleanout browser specific logic to level things
html = this.element.html().toString().trim();
if (html === '<br>' || html === `<${sep}><br></${sep}>`) {
this.element.html('');
}
this.element.contents().filter(function () {
return this.nodeType === 3 && this.textContent.trim() !== '';
}).wrap(`<${sep}></${sep}>`);
html = this.element.html().toString().trim();
this.textarea.html(xssUtils.sanitizeHTML(html));
const newSelection = this.saveSelection();
const isNumber = n => typeof n === 'number';
const isPresent = obj => obj && obj[0] &&
isNumber(obj[0].startOffset) && isNumber(obj[0].endOffset);
const getOffset = obj => (isPresent(obj) ?
{ start: obj[0].startOffset, end: obj[0].endOffset } : null);
const offset = { old: getOffset(this.savedSelection), new: getOffset(newSelection) };
if (!((offset.old !== null && offset.new !== null) &&
(offset.old.start === offset.new.start) && (offset.old.end === offset.new.end))) {
this.restoreSelection(this.savedSelection);
}
},
/**
* Remove whitespace between tags.
* @private
*/
removeWhiteSpace() {
const html = this.element.html().toString().trim();
const count = (str) => {
const re = />\s+</g;
return ((str || '').match(re) || []).length;
};
// Remove Whitepsace after tags
if (count(html) > 0) {
this.element.html(html.replace(/>\s+</g, '><'));
}
},
/**
* Add support for `ol` types
* @private
* @returns {void}
*/
orderedListTypeStyling() {
const currentElement = this.getCurrentElement();
const editor = this.element;
const types = {
loweralpha: 'a',
upperalpha: 'A',
lowerroman: 'i',
upperroman: 'I'
};
const orderedListTag = currentElement.find('ol');
switch (orderedListTag.attr('type')) {
case types.loweralpha:
editor.addClass('type-l-alpha');
editor.removeClass('type-u-alpha');
break;
case types.upperalpha:
editor.addClass('type-u-alpha');
editor.removeClass('type-l-alpha');
break;
case types.lowerroman:
editor.addClass('type-l-roman');
editor.removeClass('type-u-roman');
break;
case types.upperroman:
editor.addClass('type-u-roman');
editor.removeClass('type-l-roman');
break;
default:
break;
}
},
/**
* Do creation and setup on the editor.
* @private
* @returns {object} The proto object for chaining.
*/
createTextarea() {
this.sourceView = $('<div></div>').attr({
class: 'editor-source editable hidden',
id: `editor-source-${this.id}`
}).insertBefore(this.element);
$('<ul></ul>').addClass('line-numbers').appendTo(this.sourceView);
const textareaContainer = $('<div class="text-container"></div>').appendTo(this.sourceView);
const newTextareaID = `source-textarea-${($('[id^="source-textarea-"]').length + 1)}`;
const labelContents = `${this.element.prev('.label').addClass('audible').text()} - HTML Source View`;
$(`<label class="audible" for="${newTextareaID}">${labelContents}</label>`).appendTo(textareaContainer);
const textarea = $(`<textarea id="${newTextareaID}" data-options="{ characterCounter: false }" class="editable"></textarea>`).appendTo(textareaContainer);
return textarea;
},
/**
* Trigger the click event on the buttons.
* @param {object} e the event data
* @param {object} btn the button types to trigger
*/
triggerClick(e, btn) {
$(`button[data-action="${btn}"]`, this.toolbar).trigger('click.editor');
},
/**
* Set up keyboard handling.
* @private
* @returns {object} The proto object for chaining.
*/
setupKeyboardEvents() {
const currentElement = this.getCurrentElement();
const keys = {
b: 66, // {Ctrl + B} bold
e: 69, // {Ctrl + E} justifyCenter
h: 72, // {Ctrl + H} anchor
i: 73, // {Ctrl + I} italic --------with SHIFT: {Ctrl + Shift + I} image
l: 76, // {Ctrl + L} justifyLeft
bl: 55, // {Ctrl + Shift + 7} bullet list
n: 56, // {Ctrl + Shift + 8} numbered list
q: 81, // {Ctrl + Q} blockquotes
r: 82, // {Ctrl + R} justifyRight
u: 85, // {Ctrl + U} underline
h3: 51, // {Ctrl + 3} h3
h4: 52, // {Ctrl + 4} h4
space: 32, // {Ctrl + Space} Clear Formatting
sv: 192, // {Ctrl + ~} toggle source -or- visualview
g: 71 // {Ctrl + G} toggle for gen AI Button
};
currentElement.on('keydown.editor', (e) => {
e = e || window.event;
if (e.which) {
keys.charCode = e.which;
} else if (e.keyCode) {
keys.charCode = e.keyCode;
} else {
keys.charCode = false;
}
switch (e.ctrlKey && keys.charCode) {
case keys.h3:
this.triggerClick(e, `append-${this.settings.firstHeader}`);
break;
case keys.h4:
this.triggerClick(e, `append-${this.settings.secondHeader}`);
break;
case keys.b:
this.triggerClick(e, 'bold');
e.preventDefault();
break;
case keys.e:
this.triggerClick(e, 'justifyCenter');
break;
case keys.h:
this.triggerClick(e, 'anchor');
e.preventDefault();
break;
case keys.i:
this.triggerClick(e, e.shiftKey ? 'image' : 'italic');
if (!e.shiftKey) {
e.preventDefault();
}
break;
case keys.bl:
if (e.shiftKey) {
this.triggerClick(e, 'insertunorderedlist');
}
e.preventDefault();
break;
case keys.l:
if (!e.shiftKey) {
this.triggerClick(e, 'justifyLeft');
}
e.preventDefault();
break;
case keys.n:
if (e.shiftKey) {
this.triggerClick(e, 'insertorderedlist');
}
break;
case keys.q:
this.triggerClick(e, 'append-blockquote');
break;
case keys.r:
this.triggerClick(e, 'justifyRight');
break;
case keys.u:
this.triggerClick(e, 'underline');
e.preventDefault();
break;
case keys.space:
this.triggerClick(e, 'clearFormatting');
break;
case keys.g:
this.triggerClick(e, 'generative');
break;
case keys.sv:
this.triggerClick(e, currentElement === this.element ? 'source' : 'visual');
break;
default:
break;
}
});
// Open link in new windows/tab, if clicked with command-key(for mac) or ctrl-key(for windows)
this.element.on('mousedown.editor', 'a', function (e) {
const href = $(this).attr('href');
if (env.browser.name !== 'firefox' && (env.os.name === 'mac' && (e.metaKey || e.ctrlKey))) {
window.open(href, '_blank');
e.preventDefault();
}
});
this.element.on('updated.editor', () => {
this.updated();
});
return this;
},
setupTextareaEvents() {
// Adjust line numbers on input
this.textarea.off('.editor').on('input.editor keyup.editor', () => {
if (!(this.sourceView.hasClass('hidden'))) {
this.adjustSourceLineNumbers();
}
}).on('focus.editor', () => {
this.sourceView.addClass('is-focused');
}).on('blur.editor', (e) => {
this.sourceView.removeClass('is-focused');
this.element.empty().html(xssUtils.sanitizeHTML(this.textarea.val()));
if (this.element.data('validate')) {
this.element.data('validate').validate(this.element, true, e);
}
});
return this;
},
/**
* Set the heights and adjust the line number feature.
* @private
* @returns {void}
*/
adjustSourceLineNumbers() {
const container = this.textarea.parent();
const lineHeight = parseInt(getComputedStyle(this.textarea[0]).lineHeight, 10);
const YPadding = (this.textarea.innerHeight() - this.textarea.height());
this.textarea[0].style.height = '';
const scrollHeight = this.textarea[0].scrollHeight;
const lineNumberCount = Math.floor((scrollHeight - YPadding) / lineHeight);
const numberList = this.sourceView.find('.line-numbers');
const lastIdx = numberList.find('li').length;
let list = '';
let i = 0;
if (!this.lineNumbers || lineNumberCount !== this.lineNumbers) {
if (!this.lineNumbers) {
// Build the list of line numbers from scratch
this.lineNumbers = lineNumberCount;
while (i < this.lineNumbers) {
list += `<li role="presentation"><span>${(i + 1)}</span></li>`;
i++;
}
numberList.append(list);
} else if (this.lineNumbers < lineNumberCount) {
// Add extra line numbers to the bottom
while (i < (lineNumberCount - this.lineNumbers)) {
list += `<li role="presentation"><span>${(lastIdx + i + 1)}</span></li>`;
i++;
}
numberList.append(list);
} else if (this.lineNumbers > lineNumberCount) {
// Remove extra line numbers from the bottom
i = this.lineNumbers - lineNumberCount;
numberList.find('li').slice(-(i)).remove();
}
this.lineNumbers = lineNumberCount;
}
container[0].style.width = `calc(100% - ${(numberList.outerWidth() + 2)}px)`;
if (scrollHeight !== this.textarea[0].scrollHeight) {
this.adjustSourceLineNumbers();
return;
}
this.textarea[0].style.height = `${numberList[0].scrollHeight - 13}px`;
},
wrapTextInTags(insertedText, selectedText, action) {
let tags;
let finalText;
switch (action) {
case 'bold':
tags = ['<b>', '</b>'];
break;
case 'italic':
tags = ['<i>', '</i>'];
break;
case 'underline':
tags = ['<u>', '</u>'];
break;
case 'strikethrough':
tags = ['<strike>', '</strike>'];
break;
case 'append-blockquote':
tags = ['<blockquote>', '</blockquote>'];
break;
default: