forked from SimpleMachines/SMF
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.sceditor.smf.js
1869 lines (1617 loc) · 49.5 KB
/
jquery.sceditor.smf.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
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2024 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 3.0 Alpha 2
*/
(sceditor => {
sceditor.plugins.smf = function ()
{
let editor;
let opts;
let line;
const appendEmoticon = (code, {newrow, url, tooltip}) => {
if (newrow)
line.appendChild(document.createElement('br'));
const i = document.createElement("img");
i.src = opts.emoticonsRoot + url;
i.alt = code;
i.title = tooltip;
i.addEventListener('click', function (e)
{
if (editor.inSourceMode())
editor.insertText(' ' + this.alt + ' ');
else
editor.wysiwygEditorInsertHtml(' <img src="' + this.src + '" data-sceditor-emoticon="' + this.alt + '"> ');
e.preventDefault();
});
line.appendChild(i);
};
const createPopup = el => {
const t = document.createElement("div");
const cover = document.createElement('div');
const root = document.createElement('div');
const hide = () => {
cover.classList.remove('show');
document.removeEventListener('keydown', esc);
};
var esc = ({keyCode}) => {
if (keyCode === 27)
hide();
};
const a = document.createElement('button');
root.appendChild(a);
cover.appendChild(root);
document.body.appendChild(cover);
root.id = 'popup-container';
cover.id = 'popup';
a.id = 'close';
cover.addEventListener('click', ({target}) => {
if (target.id === 'popup')
hide();
});
a.addEventListener('click', hide);
document.addEventListener('keydown', esc);
root.appendChild(el);
root.appendChild(a);
cover.classList.add('show');
editor.hidePopup = hide;
};
const ev = ({children, nextSibling}, col, row) => {
for (let i = 1; i <= 144; i++)
children[i - 1].className = Math.ceil(i / 12) <= col && (i % 12 || 12) <= row ? 'active' : '';
nextSibling.textContent = col + 'x' + row;
};
const tbl = callback => {
const content = document.createElement('div');
content.className = 'sceditor-insert-table';
const div = document.createElement('div');
div.className = 'sceditor-insert-table-grid';
div.addEventListener('mouseleave', ev.bind(null, div, 0, 0));
const div2 = document.createElement('div');
div2.className = 'largetext';
div2.textContent = '0x0';
for (let i = 1; i <= 144; i++)
{
const row = i % 12 || 12;
const col = Math.ceil(i / 12);
const span = document.createElement('span');
span.className = 'windowbg';
span.addEventListener('mouseenter', ev.bind(null, div, col, row));
span.addEventListener('click', function (col, row) {
callback(col, row);
editor.hidePopup();
editor.focus();
}.bind(null, col, row));
div.appendChild(span);
}
content.append(div, div2);
createPopup(content);
};
this.init = function ()
{
editor = this;
opts = editor.opts;
if (opts.emoticonsEnabled)
{
const emoticons = opts.emoticons;
content = opts.smileyContainer;
if (emoticons.dropdown && content)
{
line = document.createElement('div');
sceditor.utils.each(emoticons.dropdown, appendEmoticon);
content.appendChild(line);
}
if (emoticons.more)
{
const moreButton = document.createElement('button');
moreButton.type = 'button';
moreButton.className = 'button';
moreButton.textContent = editor._('More');
moreButton.addEventListener('click', e => {
line = document.createElement('div');
sceditor.utils.each(emoticons.more, appendEmoticon);
createPopup(line);
e.preventDefault();
});
content.appendChild(moreButton);
}
content.className = 'sceditor-insertemoticon';
}
editor.commands.table = {
state(parents, firstBlock) {
return firstBlock && firstBlock.closest('table') ? 1 : 0;
},
exec() {
tbl((cols, rows) => {
editor.wysiwygEditorInsertHtml(
'<table><tr><td>',
'</td>'+ Array(cols).join('<td><br></td>') + Array(rows).join('</tr><tr>' + Array(cols+1).join('<td><br></td>')) + '</tr></table>'
);
});
},
txtExec() {
tbl((cols, rows) => {
editor.insertText(
'[table]\n[tr]\n[td]',
'[/td]'+ Array(cols).join('\n[td][/td]') + Array(rows).join('\n[/tr]\n[tr]' + Array(cols+1).join('\n[td][/td]')) + '\n[/tr]\n[/table]'
);
});
},
};
const fn = editor.createDropDown;
this.createDropDown = function (menuItem, name, content) {
fn(menuItem, name, content);
document.body.appendChild(document.querySelector('.sceditor-dropdown'));
};
editor.insertQuoteFast = messageid =>
{
getXMLDocument(
smf_prepareScriptUrl(smf_scripturl) + 'action=quotefast;quote=' + messageid + ';xml',
XMLDoc =>
{
var text = '';
for (var i = 0, n = XMLDoc.getElementsByTagName('quote')[0].childNodes.length; i < n; i++)
text += XMLDoc.getElementsByTagName('quote')[0].childNodes[i].nodeValue;
editor.insert(text);
// Manually move cursor to after the quote.
var
rangeHelper = editor.getRangeHelper(),
parent = rangeHelper.parentNode();
if (parent && parent.nodeName === 'BLOCKQUOTE')
{
var range = rangeHelper.selectedRange();
range.setStartAfter(parent);
rangeHelper.selectRange(range);
}
ajax_indicator(false);
}
);
};
editor.addStyleshet = path =>
{
const iframe = editor.getContentAreaContainer();
const el = iframe.contentDocument.createElement('link');
el.type = 'text/css';
el.href = path;
iframe.contentDocument.head.appendChild(el);
};
};
let buttons = {};
this.signalReady = function ()
{
for (const group of this.opts.toolbarContainer.children[0].children) {
for (const button of group.children) {
const cmd = button.dataset.sceditorCommand;
buttons[cmd] = button;
// Create a pseudo linebreak.
if (this.opts.toolbar.includes(cmd + '||')) {
button.parentNode.after(document.createElement('div'));
}
// Add icon to custom buttons.
if (this.opts.customTextualCommands[cmd]) {
button.firstChild.style.backgroundImage = 'url(' + smf_default_theme_url + '/images/bbc/' + this.opts.customTextualCommands[cmd].image + '.png)';
}
// Add arrowhead to buttons.
if (this.opts.commandsWithDropdown[cmd]) {
button.classList.add('with-dropdown');
}
// This button uses text without an icon.
if (this.opts.textOnlyCommands[cmd]) {
button.classList.add('text');
}
// Show text alongside the icon on this button.
if (this.opts.commandsWithText[cmd]) {
button.classList.add('text-icon');
}
}
}
// Copy variables from variants into ifrane.
const iframe = editor.getContentAreaContainer();
const el = iframe.contentDocument.createElement('style');
el.type = 'text/css';
for (const sheet of document.styleSheets) {
if (sheet.href?.includes('/index_') || sheet.href?.includes('/variables')) {
for (const rule of sheet.cssRules) {
el.innerHTML += rule.cssText;
}
} else if (sheet.href?.includes('/minified_')) {
for (const rule of sheet.cssRules) {
if (rule.selectorText == ':root') {
el.innerHTML += rule.cssText;
}
}
}
}
iframe.contentDocument.head.appendChild(el);
// Override these functions in order to convince SCEditor not to
// delete tabs. Supporting Markdown means we need to keep them.
const getSourceVal = editor.getSourceEditorValue;
const setSourceVal = editor.setSourceEditorValue;
const sourceEditor = editor.getContentAreaContainer().nextSibling;
editor.getSourceEditorValue = function (filter) {
if (filter !== false) {
sourceEditor.value = sourceEditor.value.replaceAll(/\t/, '[tab]');
}
return getSourceVal(filter);
};
editor.setSourceEditorValue = function (value) {
setSourceVal(value.replaceAll(/\[tab\]/, '\t'));
};
};
};
const setCustomTextualCommands = cmds => {
for (let c in cmds) {
const cmd = cmds[c];
const obj = {
tooltip: cmd.description || c
};
if (!sceditor.commands[c] && cmd.before) {
obj.exec = function() {
this.insertText(cmd.before, cmd.after || '');
};
obj.txtExec = [cmd.before, cmd.after || ''];
}
sceditor.command.set(c, obj);
}
};
// Our custom autolinker plugin.
sceditor.plugins.autolinker = function () {
if (typeof autolinker_regexes === 'undefined') {
return;
}
const testOnKeyDown = [
'Enter',
'ArrowLeft',
'ArrowRight',
'ArrowUp',
'ArrowDown',
'End',
'Home',
'PageDown',
'PageUp',
];
// Detects and links plain text URLs when the user presses certain keys down.
this.signalKeydownEvent = function (e) {
if (this.inSourceMode() || !testOnKeyDown.includes(e.key)) {
return;
}
const rangeHelper = this.getRangeHelper();
const range = rangeHelper.selectedRange();
// Are we in a link or a span that was specifically set not to autolink?
if (
range.endContainer.parentNode.closest('a')
|| range.endContainer.parentNode.closest('span.nolink')
) {
return;
}
// Only do this when the caret is at the end of a string of non-space characters.
if (range.endContainer.textContent.substring(range.endOffset).match(/^\S/)) {
return;
}
// We want to search from the start of the current text node to the caret position.
let str = range.endContainer.textContent.substring(0, range.endOffset);
let found = false;
for (const [name, regex] of autolinker_regexes.entries()) {
if (!name.startsWith('keypress_')) {
continue;
}
// Ensure the search always starts from the beginning.
regex.lastIndex = 0;
// Append a space so that the keyup regex will match.
const url = regex.exec(str + " ");
if (url !== null) {
found = true;
insertAutolink(this, str, url, regex, name, rangeHelper);
break;
}
}
if (!found) {
removeAutolink(rangeHelper, range.startOffset);
}
};
// Detects and links plain text URLs when user releases a key.
this.signalKeyupEvent = function (e) {
if (this.inSourceMode()) {
return;
}
const rangeHelper = this.getRangeHelper();
const range = rangeHelper.selectedRange();
// Are we in a span that was specifically set not to autolink?
if (range.endContainer.parentNode.closest('span.nolink')) {
return;
}
// We want to search from the start of the current text node to the caret position.
let str = range.endContainer.textContent.substring(0, range.endOffset);
let found = false;
if (!testOnKeyDown.includes(e.key)) {
for (const [name, regex] of autolinker_regexes.entries()) {
if (!name.startsWith('keypress_')) {
continue;
}
// Ensure the search always starts from the beginning.
regex.lastIndex = 0;
const url = regex.exec(str);
if (url !== null) {
found = true;
insertAutolink(this, str, url, regex, name, rangeHelper);
// Put the caret back where it was originally.
rangeHelper.selectRange(range);
break;
}
}
}
};
// Used when editing an existing link or an "nolink" span.
this.signalInputEvent = function (e) {
if (this.inSourceMode() && ['insertText', 'insertLineBreak', 'insertParagraph'].includes(e.inputType)) {
const caretPos = this.sourceEditorCaret().start;
const val = this.val();
const valBefore = val.substring(0, caretPos);
const valAfter = val.substring(caretPos);
for (const [name, regex] of autolinker_regexes.entries()) {
if (!name.startsWith('keypress_')) {
continue;
}
// Ensure the search always starts from the beginning.
regex.lastIndex = 0;
let found = false;
let url = regex.exec(valBefore);
if (url !== null) {
// Wrap in BBC tags.
this.sourceEditorCaret({start: url.index, end: regex.lastIndex});
const bbc_tag = name.endsWith('email') ? 'email' : url[0].startsWith(smf_scripturl) ? 'iurl' : 'url';
const tag_param = name.endsWith('naked_domain') ? '="//' + url[0] + '"' : '';
this.insert('[' + bbc_tag + tag_param + ']', '[/' + bbc_tag + ']');
// Bump the caret along by the length of the inserted tags.
this.sourceEditorCaret({start: caretPos + bbc_tag.length * 2 + tag_param.length + 5, end: caretPos + bbc_tag.length * 2 + tag_param.length + 5});
// Don't try any more regular expressions.
break;
}
}
return;
}
const rangeHelper = this.getRangeHelper();
const range = rangeHelper.selectedRange();
const parent = rangeHelper.parentNode();
const container = parent.parentNode;
const containerParent = container.parentNode;
// Adding text immediately after an existing link.
if (
e.inputType === 'insertText'
&& parent.nodeType === Node.TEXT_NODE
&& parent.textContent === e.data
&& parent.previousSibling
&& parent.previousSibling.nodeType === Node.ELEMENT_NODE
&& parent.previousSibling.nodeName === 'A'
&& parent.previousSibling.href.replace(/\/$/, '').replace(/^mailto:/, '').startsWith(parent.previousSibling.textContent.replace(/\/$/, '').replace(/^mailto:/, ''))
) {
// Turn the link back into plain text.
parent.previousSibling.replaceWith(parent.previousSibling.textContent);
containerParent.normalize();
// Put the caret back where it was originally.
rangeHelper.selectRange(range);
}
// Inside an existing link.
if (
container.nodeType === Node.ELEMENT_NODE
&& container.nodeName === 'A'
) {
containerParent.normalize();
const str = container.textContent;
// Pressed backspace inside a link.
if (e.inputType === 'deleteContentBackward') {
const caretPos = range.startOffset;
// Turn the link back into plain text.
const strBefore = document.createTextNode(str.substring(0, caretPos));
const strAfter = document.createTextNode(str.substring(caretPos));
containerParent.insertBefore(strBefore, container);
containerParent.replaceChild(strAfter, container);
containerParent.normalize();
// Put the caret back where it was originally.
rangeHelper.selectRange(range);
return;
}
// Any other edits.
for (const [name, regex] of autolinker_regexes.entries()) {
if (name.startsWith('keypress_') || name.startsWith('paste_')) {
continue;
}
// Ensure the search always starts from the beginning.
regex.lastIndex = 0;
// If text content is a URL, update the href.
if (regex.test(str)) {
container.href = (name === 'email' ? 'mailto:' : '') + str;
break;
}
}
return;
}
// Inside a span that was specifically set not to autolink.
if (
container.nodeType === Node.ELEMENT_NODE
&& container.nodeName === 'SPAN'
&& container.classList.contains('nolink')
) {
const caretPos = range.startOffset;
containerParent.normalize();
const str = container.textContent;
let url = null;
for (const [name, regex] of autolinker_regexes.entries()) {
if (name.startsWith('keypress_') || name.startsWith('paste_')) {
continue;
}
// Ensure the search always starts from the beginning.
regex.lastIndex = 0;
url = regex.exec(str);
if (url !== null) {
break;
}
}
// If the nolink span no longer contains a URL, remove the span.
if (url === null) {
const strBefore = document.createTextNode(str.substring(0, caretPos));
const strAfter = document.createTextNode(str.substring(caretPos));
containerParent.insertBefore(strBefore, container);
containerParent.replaceChild(strAfter, container);
containerParent.normalize();
// Put the caret back where it was originally.
rangeHelper.selectRange(range);
return;
}
// Move any trailing spaces out of the nolink span.
const trailing = str.match(/\s+$/);
if (trailing !== null && str.replace(/\s+$/, '') === url[0]) {
const newText = document.createTextNode(trailing[0]);
const newSpan = document.createElement('span');
newSpan.classList.add('nolink')
newSpan.textContent = url[0];
containerParent.insertBefore(newSpan, container);
containerParent.insertBefore(newText, container);
containerParent.removeChild(container);
containerParent.normalize();
// Put the caret back where it was originally.
rangeHelper.selectRange(range);
}
}
};
// Autolink URLs that are pasted into the editor.
this.signalPasteRaw = function (data) {
if (!data.html && data.text) {
data.html = data.text;
}
for (const [name, regex] of autolinker_regexes.entries()) {
if (!name.startsWith('paste_')) {
continue;
}
const url = regex.exec(data.html);
if (url !== null) {
const bbc_tag = name === 'paste_email' ? 'email' : (url[0].startsWith(smf_scripturl) ? 'iurl' : 'url');
data.html = data.html.replace(regex, '<a data-type="' + bbc_tag + '" href="' + (bbc_tag === 'email' ? 'mailto:' : '') + url[0] + '">' + url[0] + '</a>');
break;
}
}
};
// Helper for this.signalKeydownEvent and this.signalKeyupEvent.
function insertAutolink(editor, str, url, regex, regex_name, rangeHelper) {
// Trim off trailing brackets and quotes that aren't part of balanced pairs.
let found_trailing_bracket_quote = false;
do {
for (const [opener, closer] of autolinker_balanced_pairs.entries()) {
found_trailing_bracket_quote = url[0].endsWith(opener) || url[0].endsWith(closer);
if (url[0].endsWith(opener)) {
url[0] = url[0].slice(0, -1);
regex.lastIndex--;
break;
}
if (url[0].endsWith(closer)) {
let allowed_closers = 0;
for (const char of url[0]) {
if (char === opener) {
allowed_closers++;
} else if (char === closer) {
allowed_closers--;
}
}
if (allowed_closers < 0) {
url[0] = url[0].slice(0, -1);
regex.lastIndex--;
} else {
found_trailing_bracket_quote = false;
}
break;
}
}
} while (found_trailing_bracket_quote);
// Which BBC do we want to use?
const bbc_tag = regex_name.endsWith('email') ? 'email' : (url[0].startsWith(smf_scripturl) ? 'iurl' : 'url');
// Set start of selection to the start of the URL.
rangeHelper.selectOuterText(str.length - url.index, 0);
// Set end of selection to the end of the URL.
let selectedRange = rangeHelper.selectedRange();
selectedRange.setEnd(rangeHelper.parentNode(), selectedRange.endOffset - (str.length - url.index - url[0].length));
// Prepend '//' to naked domains.
if (regex_name.endsWith('naked_domain')) {
url[0] = '//' + url[0];
}
// Wrap the URL in BBC tags.
editor.insert('[' + bbc_tag + '="' + url[0] + '"]', '[/' + bbc_tag + ']');
}
// Helper for this.signalKeydownEvent.
function removeAutolink(rangeHelper, caretPos) {
const container = rangeHelper.parentNode().parentNode;
if (
container.nodeType === Node.ELEMENT_NODE
&& container.nodeName === 'A'
&& container.href.replace(/\/$/, '').replace(/^mailto:/, '') === container.textContent.replace(/\/$/, '')
) {
const url = container.textContent;
const containerParent = container.parentNode;
if (caretPos === url.length) {
container.replaceWith(url);
containerParent.normalize();
rangeHelper.selectOuterText(0, caretPos);
let selectedRange = rangeHelper.selectedRange();
selectedRange.setStart(rangeHelper.parentNode(), selectedRange.endOffset);
}
}
}
};
const createFn = sceditor.create;
sceditor.create = (textarea, options, bbcContainer, smileyContainer) => {
setCustomTextualCommands(options.customTextualCommands);
options.original = textarea;
if (typeof oQuickModify !== "undefined") {
oQuickModify.opt.sceOptions = options;
}
if (typeof bbcContainer === 'string')
options.toolbarContainer = document.getElementById(bbcContainer);
if (typeof smileyContainer === 'string')
options.smileyContainer = document.getElementById(smileyContainer);
if (bbcContainer === true || !options.toolbarContainer) {
options.toolbarContainer = document.createElement("div");
textarea.before(options.toolbarContainer);
} else {
options.toolbar = '';
}
if (smileyContainer === true || !options.smileyContainer) {
options.smileyContainer = document.createElement("div");
textarea.before(options.smileyContainer);
} else {
options.emoticons = {};
}
textarea.value = textarea.value.replaceAll(/\t/, '[tab]');
// Call the original create function
createFn(textarea, options);
textarea.value = textarea.value.replaceAll(/\[tab\]/, '\t');
};
})(sceditor);
sceditor.command.set(
'pre', {
txtExec: ["[pre]", "[/pre]"],
exec: function () {
this.wysiwygEditorInsertHtml('<pre>', '</pre>');
}
}
).set(
'link', {
exec(caller) {
const editor = this;
editor.commands.link._dropDown(editor, caller, (url, text) => {
if (!editor.getRangeHelper().selectedHtml() || text) {
text = text || url;
editor.wysiwygEditorInsertHtml(
'<a data-type="url" href="' +
sceditor.escapeEntities(url) + '">' +
sceditor.escapeEntities(text, true) + '</a>'
);
} else {
editor.wysiwygEditorInsertHtml(
'<a data-type="url" href="' +
sceditor.escapeEntities(url) + '">', '</a>'
);
}
});
}
}
).set(
'unlink', {
state() {
if (this.inSourceMode()) {
return 0;
}
const rangeHelper = this.getRangeHelper();
const container = rangeHelper.parentNode().parentNode;
if (container.nodeType === Node.ELEMENT_NODE && container.nodeName === 'SPAN' && container.classList.contains('nolink')) {
return 1;
}
if (container.nodeType !== Node.ELEMENT_NODE || container.nodeName !== 'A') {
return -1;
}
return 0;
},
exec() {
const rangeHelper = this.getRangeHelper();
const container = rangeHelper.parentNode().parentNode;
if (
container.nodeType === Node.ELEMENT_NODE
&& container.nodeName === 'A'
) {
const containerParent = container.parentNode;
const caretPos = rangeHelper.selectedRange().startOffset;
const url = container.textContent;
container.replaceWith(url);
containerParent.normalize();
rangeHelper.selectOuterText(0, url.length);
this.insert('[nolink]', '[/nolink]');
} else if (
container.nodeType === Node.ELEMENT_NODE
&& container.nodeName === 'SPAN'
&& container.classList.contains('nolink')
) {
const containerParent = container.parentNode;
const caretPos = rangeHelper.selectedRange().startOffset;
const url = container.textContent;
container.replaceWith(url);
containerParent.normalize();
const bbc_tag = autolinker_regexes.get('email').test(url) ? 'email' : (url.startsWith(smf_scripturl) ? 'iurl' : 'url');
rangeHelper.selectOuterText(0, url.length);
if (autolinker_regexes.get('naked_domain').test(url)) {
this.insert('[' + bbc_tag + '="//' + url + '"]', '[/' + bbc_tag + ']');
} else {
this.insert('[' + bbc_tag + ']', '[/' + bbc_tag + ']');
}
}
},
txtExec() {
let caretPos = this.sourceEditorCaret().start;
const val = this.val();
const valBefore = val.substring(0, caretPos);
const valAfter = val.substring(caretPos);
const urlBbcBefore = new RegExp('\\[(i?url|email)([^\\]]*)\\]([^\\[\\]\\s]*)$', 'i');
const urlBbcAfter = new RegExp('^([^\\[\\]\\s]*)\\[\\/(i?url|email)\\]', 'i');
const nolinkBbcBefore = new RegExp('\\[nolink\\]([^\\[]|\\[(?!/?nolink))*$', 'im');
const nolinkBbcAfter = new RegExp('^([^\\]]|(?<!nolink)\\])*\\[\\/nolink\\]', 'im');
if (valBefore.match(nolinkBbcBefore) && valAfter.match(nolinkBbcAfter)) {
const before = nolinkBbcBefore.exec(valBefore);
const after = nolinkBbcAfter.exec(valAfter);
const beforePos = caretPos - before[0].length;
let possibleUrl = before[0] + after[0];
possibleUrl = possibleUrl.substring(8, possibleUrl.length - 9);
for (const [name, regex] of autolinker_regexes.entries()) {
if (name.startsWith('keypress_') || name.startsWith('paste_')) {
continue;
}
// Ensure the search always starts from the beginning.
regex.lastIndex = 0;
let found = false;
let url = regex.exec(possibleUrl);
if (url !== null) {
this.val(val.replace(before[0] + after[0], url[0]));
this.sourceEditorCaret({start: caretPos - before[0].length, end: caretPos - before[0].length + url[0].length});
const bbc_tag = name.endsWith('email') ? 'email' : possibleUrl.startsWith(smf_scripturl) ? 'iurl' : 'url';
if (name.endsWith('naked_domain')) {
this.insert('[' + bbc_tag + '="//' + url[0] + '"]', '[/' + bbc_tag + ']');
} else {
this.insert('[' + bbc_tag + ']', '[/' + bbc_tag + ']');
}
break;
}
}
} else if (valBefore.match(urlBbcBefore) && valAfter.match(urlBbcAfter)) {
const before = urlBbcBefore.exec(valBefore);
caretPos = caretPos - (before[1].length + before[2].length - 6);
this.val(valBefore.replace(urlBbcBefore, '[nolink]$3') + valAfter.replace(urlBbcAfter, '$1[/nolink]'));
this.sourceEditorCaret({start: caretPos, end: caretPos});
} else {
for (const [name, regex] of autolinker_regexes.entries()) {
if (name.startsWith('keypress_') || name.startsWith('paste_')) {
continue;
}
// Ensure the search always starts from the beginning.
regex.lastIndex = 0;
let found = false;
let url = regex.exec(val);
while (url !== null) {
if (regex.lastIndex < caretPos) {
url = regex.exec(val);
} else if (url.index > caretPos) {
break;
} else {
found = true;
break;
}
}
if (found) {
// Wrap in nolink tags.
this.sourceEditorCaret({start: url.index, end: regex.lastIndex});
this.insert('[nolink]', '[/nolink]');
// Bump the caret along by the length of the opening tag.
this.sourceEditorCaret({start: caretPos + 8, end: caretPos + 8});
// Don't try any more regular expressions.
break;
}
}
}
},
}
).set(
'bulletlist', {
txtExec(caller, selected) {
if (selected)
this.insertText(
'[list]\n[li]' +
selected.split(/\r?\n/).join('[/li]\n[li]') +
'[/li]\n[/list]'
);
else
this.insertText('[list]\n[li]', '[/li]\n[li][/li]\n[/list]');
}
}
).set(
'orderedlist', {
txtExec(caller, selected) {
if (selected)
this.insertText(
'[list type=decimal]\n[li]' +
selected.split(/\r?\n/).join('[/li]\n[li]') +
'[/li]\n[/list]'
);
else
this.insertText('[list type=decimal]\n[li]', '[/li]\n[li][/li]\n[/list]');
}
}
).set(
'floatleft', {
txtExec: ["[float=left max=45%]", "[/float]"],
exec: function () {
this.wysiwygEditorInsertHtml('<div class="floatleft">', '</div>');
}
}
).set(
'floatright', {
txtExec: ["[float=right max=45%]", "[/float]"],
exec: function () {
this.wysiwygEditorInsertHtml('<div class="floatright">', '</div>');
}
}
);
sceditor.command.set(
'heading', {
_dropDown: function (editor, caller, callback) {
var content = document.createElement('div');
for (var i = 1; i <= 6; i++) {
let opt = document.createElement('a');
opt.href = '#',
opt.dataset.tag = 'h' + i;
opt.innerText = 'H' + i;
opt.style.display = 'block';
opt.classList.add('bbc_h' + i);
content.appendChild(opt);
}
if (!editor.sourceMode()) {
let opt = document.createElement('a');
opt.href = '#',
opt.dataset.tag = '';
opt.innerText = "\u2014";
opt.style.display = 'block';
content.appendChild(opt);
}
for (const elem of content.querySelectorAll("a")) {
elem.addEventListener("click", function (e) {
callback(elem.dataset.tag);
editor.closeDropDown(true);
e.preventDefault();
});
}
editor.createDropDown(caller, 'item-picker', content);
},
state: function (parent, firstBlock) {
return sceditor.dom.closest(this.currentNode(), 'h1, h2, h3, h4, h5, h6') ? 1 : 0;
},
txtExec: function (caller) {
var editor = this;
editor.commands.heading._dropDown(editor, caller, function (tag) {
editor.insert('[' + tag + ']', '[/' + tag + ']');
});
},
exec: function (caller) {
var editor = this;
editor.commands.heading._dropDown(editor, caller, function (tag) {
const rangeHelper = editor.getRangeHelper();
const container = rangeHelper.parentNode().parentNode.closest('h1, h2, h3, h4, h5, h6');