-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
1779 lines (1571 loc) · 67.6 KB
/
Copy pathcontentScript.js
File metadata and controls
1779 lines (1571 loc) · 67.6 KB
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
(function () {
const DEFAULTS = {
convertOnPaste: false,
autoFormat: true,
gfm: true,
theme: 'default',
shortcut: 'Ctrl+Shift+M',
codeShortcut: 'Ctrl+E',
disableDefault: false
};
const SELECTOR = 'div[aria-label="Message Body"][contenteditable="true"]';
const BLOCKQUOTE_INLINE_STYLE = 'border-left:4px solid #ccc;padding-left:24px !important;color:#555;margin:0.5em 0;background:none;';
const PRE_WRAPPER_STYLE = 'background-color:#f7f6f3;border-radius:3px;padding:12px 16px;margin:1em 0;overflow-x:auto;max-width:100%;';
const PRE_CODE_STYLE = 'font-family:SFMono-Regular,Consolas,"Liberation Mono",Menlo,monospace;font-size:0.85em;white-space:pre-wrap;word-break:break-word;overflow-wrap:anywhere;color:#333;margin:0;padding:0;display:block;';
const INLINE_CODE_STYLE = 'background-color:#f2f2f2;color:#d73a49;padding:2px 4px;border-radius:3px;font-family:monospace;';
const CALLOUT_INLINE_STYLE = 'display:inline-block;max-width:100%;box-sizing:border-box;background-color:#f2f2f2;padding:10px 14px;border-radius:4px;margin:8px 0;overflow-wrap:anywhere;word-break:break-word;';
const TABLE_INLINE_STYLE = 'border-collapse:collapse;border-spacing:0;margin:0.5em 0;max-width:100%;';
const TABLE_CELL_INLINE_STYLE = 'border:1px solid #ccc;padding:6px 10px;text-align:left;min-width:80px;overflow-wrap:anywhere;word-break:break-word;';
const TABLE_HEADER_INLINE_STYLE = `${TABLE_CELL_INLINE_STYLE}background-color:#f8f9fa;font-weight:bold;`;
const SLASH_COMMANDS = [
{ id: 'quote', label: 'Quote', description: 'Insert a quoted block', aliases: ['blockquote'] },
{ id: 'note', label: 'Note', description: 'Insert a gray callout for important information', aliases: ['callout'] },
{ id: 'h1', label: 'H1', description: 'Insert a large heading', aliases: ['title', 'heading1'] },
{ id: 'h2', label: 'H2', description: 'Insert a section heading', aliases: ['heading', 'heading2'] },
{ id: 'h3', label: 'H3', description: 'Insert a smaller heading', aliases: ['subheading', 'heading3'] },
{ id: 'bullets', label: 'Bulleted list', description: 'Insert a bullet list', aliases: ['bullet', 'unordered', 'ul'] },
{ id: 'numbered', label: 'Numbered list', description: 'Insert a numbered list', aliases: ['number', 'ordered', 'ol'] },
{ id: 'code', label: 'Code block', description: 'Insert a multiline code block', aliases: ['codeblock', 'pre'] },
{ id: 'table', label: 'Table', description: 'Insert an editable 2-column table', aliases: ['grid'] },
{ id: 'divider', label: 'Divider', description: 'Insert a horizontal rule', aliases: ['horizontal', 'rule', 'hr'] }
];
let slashMenuState = null;
let tableToolbarState = null;
const AUTO_FORMATS = [
{ reg: /(\*\*|__)(.+?)\1$/, cmd: 'bold' },
{ reg: /(\*|_)(.+?)\1$/, cmd: 'italic' },
{ reg: /~~(.+?)~~$/, cmd: 'strikeThrough' },
{ reg: /`(.+?)`$/, cmd: 'code' },
{ reg: /:([a-zA-Z0-9_\+\-]+):$/, cmd: 'emoji' }
];
function getActiveEditable() {
const active = document.activeElement;
if (active && active.matches && active.matches(SELECTOR)) return active;
// Fallback based on text selection
const sel = window.getSelection();
if (sel && sel.rangeCount) {
let node = sel.getRangeAt(0).commonAncestorContainer;
while (node && node !== document.body) {
if (node.nodeType === Node.ELEMENT_NODE && node.matches(SELECTOR)) return node;
node = node.parentNode;
}
}
// Absolute fallback: first editor on page
return document.querySelector(SELECTOR);
}
function convertLinksToReadable(text) {
return text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ($2)');
}
function escapeHtml(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function isSafeLinkUrl(url) {
const normalized = String(url || '').trim().replace(/[\u0000-\u0020\u007F]+/g, '');
const scheme = normalized.match(/^([a-z][a-z0-9+.-]*):/i);
return !scheme || ['http', 'https', 'mailto'].includes(scheme[1].toLowerCase());
}
function createMarkedOptions(markedLib, gfm) {
const options = { gfm };
if (!markedLib || typeof markedLib.Renderer !== 'function') return options;
const renderer = new markedLib.Renderer();
renderer.html = (html) => {
const raw = typeof html === 'string' ? html : (html && html.text) || '';
return escapeHtml(raw);
};
renderer.link = function (linkOrHref, title, text) {
const isToken = linkOrHref && typeof linkOrHref === 'object';
const href = isToken ? linkOrHref.href : linkOrHref;
const linkTitle = isToken ? linkOrHref.title : title;
const label = isToken
? (linkOrHref.tokens && this.parser
? this.parser.parseInline(linkOrHref.tokens)
: escapeHtml(linkOrHref.text || href || ''))
: (text || escapeHtml(href || ''));
if (!isSafeLinkUrl(href)) return label;
const titleAttribute = linkTitle ? ` title="${escapeHtml(linkTitle)}"` : '';
return `<a href="${escapeHtml(href)}"${titleAttribute}>${label}</a>`;
};
options.renderer = renderer;
return options;
}
function applyTheme(theme) {
const id = 'md-theme-style';
let style = document.getElementById(id);
if (!style) {
style = document.createElement('style');
style.id = id;
document.documentElement.appendChild(style);
}
const sel = 'div[aria-label="Message Body"][contenteditable="true"]';
const base = `
${sel} > div:not([style]), ${sel} > p:not([style]) { margin: 0 !important; padding: 0 !important; }
`;
const themes = {
default: `
${sel} h1 { font-size: 1.4em !important; font-weight: bold !important; margin: 0.6em 0 !important; }
${sel} h2 { font-size: 1.2em !important; font-weight: bold !important; margin: 0.5em 0 !important; }
${sel} h3 { font-size: 1.1em !important; font-weight: bold !important; margin: 0.4em 0 !important; }
${sel} table[data-md-table="1"] { border-collapse: collapse !important; border-spacing: 0 !important; margin: 0.5em 0 !important; }
${sel} table[data-md-table="1"] th, ${sel} table[data-md-table="1"] td { border: 1px solid #ccc !important; padding: 6px 10px !important; text-align: left !important; }
${sel} table[data-md-table="1"] th { background-color: #f8f9fa !important; font-weight: bold !important; }
`,
bold: `
${sel} h1 { font-size: 1.4em !important; font-weight: bold !important; text-transform: uppercase !important; margin: 0.6em 0 !important; }
${sel} h2 { font-size: 1.2em !important; font-weight: bold !important; text-transform: uppercase !important; margin: 0.5em 0 !important; }
${sel} h3 { font-size: 1.1em !important; font-weight: bold !important; text-transform: uppercase !important; margin: 0.4em 0 !important; }
${sel} table[data-md-table="1"] { border-collapse: collapse !important; border-spacing: 0 !important; margin: 0.5em 0 !important; }
${sel} table[data-md-table="1"] th, ${sel} table[data-md-table="1"] td { border: 1px solid #ccc !important; padding: 6px 10px !important; text-align: left !important; }
${sel} table[data-md-table="1"] th { background-color: #f8f9fa !important; font-weight: bold !important; text-transform: uppercase !important; }
`
};
// Map 'strong' to 'bold' if user had it saved previously
let activeTheme = theme === 'strong' ? 'bold' : theme;
style.textContent = base + (themes[activeTheme] || themes.default);
}
function ensureSlashMenuStyles() {
if (document.getElementById('md-slash-menu-style')) return;
const style = document.createElement('style');
style.id = 'md-slash-menu-style';
style.textContent = `
[data-md-slash-menu="1"] {
position: fixed;
z-index: 2147483647;
width: 260px;
max-height: 240px;
overflow-y: auto;
padding: 4px;
background: #fff;
border: 1px solid #dadce0;
border-radius: 8px;
box-shadow: 0 8px 24px rgba(60, 64, 67, 0.24);
box-sizing: border-box;
font-family: Arial, sans-serif;
}
[data-md-slash-command] {
display: block;
width: 100%;
padding: 8px 10px;
color: #202124;
background: transparent;
border: 0;
border-radius: 5px;
box-sizing: border-box;
cursor: pointer;
text-align: left;
}
[data-md-slash-command][aria-selected="true"],
[data-md-slash-command]:hover {
background: #e8f0fe;
}
[data-md-slash-command][aria-selected="true"] {
color: #174ea6;
box-shadow: inset 3px 0 #1a73e8;
}
[data-md-slash-command] strong {
display: block;
font-size: 14px;
line-height: 20px;
}
[data-md-slash-command] span {
display: block;
color: #5f6368;
font-size: 12px;
line-height: 18px;
}
`;
document.documentElement.appendChild(style);
}
function closeSlashCommandMenu(body) {
if (!slashMenuState || (body && slashMenuState.body !== body)) return;
if (slashMenuState.menu.parentNode) {
slashMenuState.menu.parentNode.removeChild(slashMenuState.menu);
}
slashMenuState = null;
}
function ensureTableToolbarStyles() {
if (document.getElementById('md-table-toolbar-style')) return;
const style = document.createElement('style');
style.id = 'md-table-toolbar-style';
style.textContent = `
[data-md-table-toolbar="1"] {
position: fixed;
z-index: 2147483647;
display: flex;
gap: 4px;
padding: 4px;
background: #fff;
border: 1px solid #dadce0;
border-radius: 7px;
box-shadow: 0 4px 12px rgba(60, 64, 67, 0.24);
box-sizing: border-box;
font-family: Arial, sans-serif;
}
[data-md-table-action] {
padding: 5px 8px;
color: #3c4043;
background: transparent;
border: 0;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
line-height: 18px;
white-space: nowrap;
}
[data-md-table-action]:hover,
[data-md-table-action]:focus {
color: #174ea6;
background: #e8f0fe;
outline: none;
}
`;
document.documentElement.appendChild(style);
}
function closeTableToolbar() {
if (!tableToolbarState) return;
if (tableToolbarState.toolbar.parentNode) tableToolbarState.toolbar.remove();
tableToolbarState = null;
}
function positionTableToolbar(state) {
const tableRect = state.table.getBoundingClientRect();
const toolbarRect = state.toolbar.getBoundingClientRect();
const maxLeft = Math.max(8, window.innerWidth - toolbarRect.width - 8);
const maxTop = Math.max(8, window.innerHeight - toolbarRect.height - 8);
const above = tableRect.top - toolbarRect.height - 6;
let left = Math.max(8, Math.min(tableRect.right - toolbarRect.width, maxLeft));
let top;
if (above >= 8) {
top = above;
} else if (tableRect.right + toolbarRect.width + 6 <= window.innerWidth - 8) {
left = tableRect.right + 6;
top = tableRect.top;
} else if (tableRect.left - toolbarRect.width - 6 >= 8) {
left = tableRect.left - toolbarRect.width - 6;
top = tableRect.top;
} else {
top = tableRect.bottom + 6;
}
state.toolbar.style.left = `${left}px`;
state.toolbar.style.top = `${Math.max(8, Math.min(top, maxTop))}px`;
}
function placeCaretAfterTable(table, editor) {
let trailingLine = table.nextElementSibling;
if (!trailingLine || trailingLine.tagName !== 'DIV') {
trailingLine = document.createElement('div');
trailingLine.innerHTML = '<br>';
table.parentNode.insertBefore(trailingLine, table.nextSibling);
}
table.remove();
editor.focus();
const selection = window.getSelection();
const range = document.createRange();
range.setStart(trailingLine, 0);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
function applySelectedTableAction(action) {
if (!tableToolbarState) return;
const { cell, table, editor } = tableToolbarState;
if (!cell.isConnected || !table.isConnected || !editor.isConnected) {
closeTableToolbar();
return;
}
const row = cell.parentElement;
const rowIndex = Array.from(table.rows).indexOf(row);
const columnIndex = Array.from(row.cells).indexOf(cell);
if (action === 'add-row') {
const newRow = document.createElement('tr');
const columnCount = table.rows[0] ? table.rows[0].cells.length : row.cells.length;
for (let currentColumnIndex = 0; currentColumnIndex < columnCount; currentColumnIndex += 1) {
const newCell = document.createElement('td');
newCell.setAttribute('style', TABLE_CELL_INLINE_STYLE);
newCell.appendChild(document.createElement('br'));
newRow.appendChild(newCell);
}
row.parentNode.insertBefore(newRow, row.nextSibling);
placeCaretInTableCell(newRow.cells[Math.min(columnIndex, newRow.cells.length - 1)]);
updateTableToolbar();
} else if (action === 'add-column') {
let targetCell = null;
Array.from(table.rows).forEach((tableRow, currentRowIndex) => {
const isHeaderRow = tableRow.cells[0] && tableRow.cells[0].tagName === 'TH';
const newCell = document.createElement(isHeaderRow ? 'th' : 'td');
newCell.setAttribute(
'style',
isHeaderRow ? TABLE_HEADER_INLINE_STYLE : TABLE_CELL_INLINE_STYLE
);
newCell.appendChild(document.createElement('br'));
const nextCell = tableRow.cells[columnIndex + 1];
tableRow.insertBefore(newCell, nextCell || null);
if (currentRowIndex === rowIndex) targetCell = newCell;
});
placeCaretInTableCell(targetCell);
updateTableToolbar();
} else if (action === 'row') {
if (table.rows.length <= 1) {
closeTableToolbar();
placeCaretAfterTable(table, editor);
} else {
row.remove();
const targetRow = table.rows[Math.min(rowIndex, table.rows.length - 1)];
placeCaretInTableCell(targetRow.cells[Math.min(columnIndex, targetRow.cells.length - 1)]);
updateTableToolbar();
}
} else if (action === 'column') {
const columnCount = table.rows[0] ? table.rows[0].cells.length : 0;
if (columnCount <= 1) {
closeTableToolbar();
placeCaretAfterTable(table, editor);
} else {
Array.from(table.rows).forEach(tableRow => {
if (tableRow.cells[columnIndex]) tableRow.deleteCell(columnIndex);
});
const targetRow = table.rows[Math.min(rowIndex, table.rows.length - 1)];
placeCaretInTableCell(targetRow.cells[Math.min(columnIndex, targetRow.cells.length - 1)]);
updateTableToolbar();
}
}
editor.dispatchEvent(new window.Event('input', { bubbles: true }));
}
function updateTableToolbar() {
const cell = getSelectedTableCell();
const table = cell && cell.closest('table[data-md-table="1"]');
const editor = table && table.closest(SELECTOR);
if (!cell || !table || !editor) {
closeTableToolbar();
return;
}
ensureTableToolbarStyles();
let toolbar = tableToolbarState && tableToolbarState.toolbar;
if (!toolbar) {
toolbar = document.createElement('div');
toolbar.setAttribute('data-md-table-toolbar', '1');
toolbar.setAttribute('role', 'toolbar');
toolbar.setAttribute('aria-label', 'Table actions');
toolbar.innerHTML = [
'<button type="button" data-md-table-action="add-row">Add row</button>',
'<button type="button" data-md-table-action="add-column">Add column</button>',
'<button type="button" data-md-table-action="row">Delete row</button>',
'<button type="button" data-md-table-action="column">Delete column</button>'
].join('');
toolbar.addEventListener('mousedown', event => event.preventDefault());
toolbar.addEventListener('click', event => {
const button = event.target.closest('[data-md-table-action]');
if (button) applySelectedTableAction(button.getAttribute('data-md-table-action'));
});
document.body.appendChild(toolbar);
}
tableToolbarState = { toolbar, cell, table, editor };
positionTableToolbar(tableToolbarState);
}
function getSlashCommandContext(body) {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0 || !selection.isCollapsed) return null;
const caretRange = selection.getRangeAt(0);
if (!body.contains(caretRange.startContainer)) return null;
let block = caretRange.startContainer;
if (block.nodeType === Node.TEXT_NODE) block = block.parentNode;
while (block && block !== body && block.parentNode !== body) {
block = block.parentNode;
}
if (!block) return null;
const commandRange = document.createRange();
if (block === body && caretRange.startContainer.nodeType === Node.TEXT_NODE) {
commandRange.setStart(caretRange.startContainer, 0);
} else {
commandRange.setStart(block, 0);
}
commandRange.setEnd(caretRange.startContainer, caretRange.startOffset);
const prefix = commandRange.toString().replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
const match = prefix.match(/^\/([a-z0-9-]*)$/i);
if (!match) return null;
return {
body,
block,
commandRange: commandRange.cloneRange(),
caretRange: caretRange.cloneRange(),
query: match[1].toLowerCase()
};
}
function positionSlashCommandMenu(state) {
const caretRect = state.context.caretRange.getBoundingClientRect();
const editorRect = state.body.getBoundingClientRect();
const left = caretRect.left || editorRect.left || 8;
const anchorTop = caretRect.top || editorRect.top || 8;
const anchorBottom = caretRect.bottom || editorRect.top + 24 || 24;
const maxLeft = Math.max(8, window.innerWidth - state.menu.offsetWidth - 8);
const below = anchorBottom + 6;
const above = Math.max(8, anchorTop - state.menu.offsetHeight - 6);
const top = below + state.menu.offsetHeight <= window.innerHeight - 8 ? below : above;
state.menu.style.left = `${Math.max(8, Math.min(left, maxLeft))}px`;
state.menu.style.top = `${Math.max(8, top)}px`;
}
function setSlashMenuSelection(index) {
if (!slashMenuState || slashMenuState.commands.length === 0) return;
const count = slashMenuState.commands.length;
slashMenuState.selectedIndex = (index + count) % count;
const items = slashMenuState.menu.querySelectorAll('[data-md-slash-command]');
let selectedItem = null;
items.forEach((item, itemIndex) => {
const isSelected = itemIndex === slashMenuState.selectedIndex;
item.setAttribute('aria-selected', itemIndex === slashMenuState.selectedIndex ? 'true' : 'false');
if (isSelected) selectedItem = item;
});
if (!selectedItem) return;
slashMenuState.menu.setAttribute('aria-activedescendant', selectedItem.id);
const visibleTop = slashMenuState.menu.scrollTop;
const visibleBottom = visibleTop + slashMenuState.menu.clientHeight;
const itemTop = selectedItem.offsetTop;
const itemBottom = itemTop + selectedItem.offsetHeight;
if (itemTop < visibleTop) {
slashMenuState.menu.scrollTop = itemTop;
} else if (itemBottom > visibleBottom) {
slashMenuState.menu.scrollTop = itemBottom - slashMenuState.menu.clientHeight;
}
}
function renderSlashCommandMenu(state) {
state.menu.replaceChildren();
state.commands.forEach((command, index) => {
const item = document.createElement('button');
item.type = 'button';
item.id = `md-slash-option-${command.id}`;
item.setAttribute('role', 'option');
item.setAttribute('data-md-slash-command', command.id);
item.setAttribute('aria-selected', index === state.selectedIndex ? 'true' : 'false');
const label = document.createElement('strong');
label.textContent = command.label;
const description = document.createElement('span');
description.textContent = command.description;
item.append(label, description);
state.menu.appendChild(item);
});
const selectedItem = state.menu.querySelector('[aria-selected="true"]');
if (selectedItem) {
state.menu.setAttribute('aria-activedescendant', selectedItem.id);
}
}
function createEmptySlashBlock(tagName) {
const node = document.createElement(tagName);
node.appendChild(document.createElement('br'));
return { node, caretTarget: node, caretOffset: 0 };
}
function createSlashCommandBlock(commandId) {
if (commandId === 'quote') {
const quote = document.createElement('div');
quote.setAttribute('style', BLOCKQUOTE_INLINE_STYLE);
quote.setAttribute('data-md-quote', '1');
const space = document.createTextNode('\u00A0');
quote.appendChild(space);
return { node: quote, caretTarget: space, caretOffset: 1 };
}
if (commandId === 'note') {
const callout = document.createElement('div');
callout.className = 'md-callout';
callout.setAttribute('style', CALLOUT_INLINE_STYLE);
callout.textContent = 'Important info';
return {
node: callout,
caretTarget: callout.firstChild,
caretOffset: callout.textContent.length
};
}
if (commandId === 'bullets' || commandId === 'numbered') {
const list = document.createElement(commandId === 'bullets' ? 'ul' : 'ol');
const item = document.createElement('li');
item.appendChild(document.createElement('br'));
list.appendChild(item);
return { node: list, caretTarget: item, caretOffset: 0 };
}
if (commandId === 'code') {
const wrapper = document.createElement('div');
wrapper.setAttribute('data-md-code', '1');
wrapper.setAttribute('style', PRE_WRAPPER_STYLE);
const pre = document.createElement('pre');
pre.setAttribute('style', PRE_CODE_STYLE);
pre.appendChild(document.createElement('br'));
wrapper.appendChild(pre);
return { node: wrapper, caretTarget: pre, caretOffset: 0 };
}
if (commandId === 'table') {
const table = document.createElement('table');
table.setAttribute('data-md-table', '1');
table.setAttribute('style', TABLE_INLINE_STYLE);
const body = document.createElement('tbody');
table.appendChild(body);
let firstHeader = null;
for (let rowIndex = 0; rowIndex < 3; rowIndex += 1) {
const row = document.createElement('tr');
for (let columnIndex = 0; columnIndex < 2; columnIndex += 1) {
const cell = document.createElement(rowIndex === 0 ? 'th' : 'td');
cell.setAttribute(
'style',
rowIndex === 0 ? TABLE_HEADER_INLINE_STYLE : TABLE_CELL_INLINE_STYLE
);
cell.appendChild(document.createElement('br'));
if (!firstHeader) firstHeader = cell;
row.appendChild(cell);
}
body.appendChild(row);
}
return { node: table, caretTarget: firstHeader, caretOffset: 0 };
}
if (commandId === 'divider') {
return { node: document.createElement('hr'), focusTrailingLine: true };
}
return null;
}
function applySlashHeadingCommand(commandId, context) {
closeSlashCommandMenu();
const range = context.commandRange.cloneRange();
range.deleteContents();
range.collapse(true);
const selection = window.getSelection();
context.body.focus();
const marker = document.createElement('span');
marker.setAttribute('data-md-empty-anchor', '1');
marker.textContent = '\u200B';
range.insertNode(marker);
const markerRange = document.createRange();
markerRange.setStart(marker.firstChild, marker.textContent.length);
markerRange.collapse(true);
selection.removeAllRanges();
selection.addRange(markerRange);
document.execCommand('formatBlock', false, commandId.toUpperCase());
let heading = marker.closest(commandId);
marker.remove();
if (heading && !heading.hasChildNodes()) heading.appendChild(document.createElement('br'));
if (heading && heading !== context.body) {
const trailingLine = document.createElement('div');
trailingLine.innerHTML = '<br>';
heading.parentNode.insertBefore(trailingLine, heading.nextSibling);
const headingRange = document.createRange();
headingRange.setStart(heading, 0);
headingRange.collapse(true);
selection.removeAllRanges();
selection.addRange(headingRange);
}
context.body.dispatchEvent(new Event('input', { bubbles: true }));
}
function applySlashCommand(commandId) {
if (!slashMenuState) return;
const state = slashMenuState;
const context = state.context;
if (/^h[1-3]$/.test(commandId)) {
applySlashHeadingCommand(commandId, context);
return;
}
const commandBlock = createSlashCommandBlock(commandId);
if (!commandBlock || !context.body.contains(context.commandRange.commonAncestorContainer)) {
closeSlashCommandMenu();
return;
}
const commandNode = commandBlock.node;
closeSlashCommandMenu();
const range = context.commandRange.cloneRange();
range.deleteContents();
const reusableBlock = context.block !== context.body &&
context.block.parentNode &&
context.body.contains(context.block) &&
context.block.textContent.replace(/[\u200B\u200C\u200D\uFEFF]/g, '').trim() === '';
if (reusableBlock) {
context.block.parentNode.replaceChild(commandNode, context.block);
} else {
range.insertNode(commandNode);
}
const trailingLine = document.createElement('div');
trailingLine.innerHTML = '<br>';
commandNode.parentNode.insertBefore(trailingLine, commandNode.nextSibling);
const selection = window.getSelection();
const nextRange = document.createRange();
if (commandBlock.focusTrailingLine) {
nextRange.setStart(trailingLine, 0);
} else if (commandBlock.caretTarget) {
nextRange.setStart(commandBlock.caretTarget, commandBlock.caretOffset || 0);
} else {
nextRange.selectNodeContents(commandNode);
nextRange.collapse(false);
}
nextRange.collapse(true);
context.body.focus();
selection.removeAllRanges();
selection.addRange(nextRange);
context.body.dispatchEvent(new Event('input', { bubbles: true }));
}
function updateSlashCommandMenu(body) {
const context = getSlashCommandContext(body);
if (!context) {
closeSlashCommandMenu(body);
return;
}
const commands = SLASH_COMMANDS
.map((command, originalIndex) => {
const label = command.label.toLowerCase();
const aliases = command.aliases || [];
let score = -1;
if (context.query === '') score = originalIndex;
else if (command.id === context.query) score = 0;
else if (label === context.query) score = 1;
else if (aliases.includes(context.query)) score = 2;
else if (command.id.startsWith(context.query)) score = 3;
else if (label.startsWith(context.query)) score = 4;
else if (aliases.some(alias => alias.startsWith(context.query))) score = 5;
return { command, originalIndex, score };
})
.filter(result => result.score >= 0)
.sort((a, b) => a.score - b.score || a.originalIndex - b.originalIndex)
.map(result => result.command);
if (commands.length === 0) {
closeSlashCommandMenu(body);
return;
}
ensureSlashMenuStyles();
let menu = slashMenuState && slashMenuState.body === body
? slashMenuState.menu
: null;
if (!menu) {
closeSlashCommandMenu();
menu = document.createElement('div');
menu.setAttribute('data-md-slash-menu', '1');
menu.setAttribute('role', 'listbox');
menu.setAttribute('aria-label', 'Markdown commands');
menu.addEventListener('mousedown', (event) => event.preventDefault());
menu.addEventListener('click', (event) => {
const item = event.target.closest('[data-md-slash-command]');
if (item) applySlashCommand(item.getAttribute('data-md-slash-command'));
});
document.body.appendChild(menu);
}
slashMenuState = {
body,
menu,
context,
commands,
selectedIndex: 0
};
renderSlashCommandMenu(slashMenuState);
positionSlashCommandMenu(slashMenuState);
}
function handleSlashCommandKeydown(event, body) {
if (!slashMenuState || slashMenuState.body !== body) return false;
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
event.stopPropagation();
const direction = event.key === 'ArrowDown' ? 1 : -1;
setSlashMenuSelection(slashMenuState.selectedIndex + direction);
return true;
}
if (event.key === 'Enter' || event.key === 'Tab') {
event.preventDefault();
event.stopPropagation();
const selected = slashMenuState.commands[slashMenuState.selectedIndex];
if (selected) applySlashCommand(selected.id);
return true;
}
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
closeSlashCommandMenu(body);
return true;
}
return false;
}
function deletePrecise(container, offset, count) {
const sel = window.getSelection();
if (!sel) return;
const r = document.createRange();
const startOffset = Math.max(0, offset - count);
r.setStart(container, startOffset);
r.setEnd(container, offset);
r.deleteContents();
// Ensure cursor is collapsed at the point of deletion
r.collapse(true);
sel.removeAllRanges();
sel.addRange(r);
}
function isCursorAtBlockStart(range, block) {
try {
const testRange = document.createRange();
testRange.setStart(block, 0);
testRange.setEnd(range.startContainer, range.startOffset);
return testRange.toString().length === 0;
} catch (e) {
return false;
}
}
function hasTextAfterCursorInBlock(range, body) {
let block = range.startContainer;
if (block.nodeType === Node.TEXT_NODE) block = block.parentNode;
while (block && block !== body && !block.matches('div, p, h1, h2, h3, h4, h5, h6, li, blockquote, pre, [data-md-code]')) {
block = block.parentNode;
}
if (!block || block === body) {
return range.startContainer.nodeType === Node.TEXT_NODE &&
range.startOffset < range.startContainer.textContent.length;
}
try {
const afterRange = document.createRange();
afterRange.setStart(range.startContainer, range.startOffset);
afterRange.setEnd(block, block.childNodes.length);
return afterRange.toString().length > 0;
} catch (e) {
return false;
}
}
function replaceBlockWithDiv(block) {
const isPreBlock = block.tagName === 'PRE';
const isCodeWrapper = !!(block.getAttribute && block.getAttribute('data-md-code'));
const div = document.createElement('div');
if (isPreBlock || isCodeWrapper) {
// For code wrappers, unwrap the inner <pre> content
const source = isCodeWrapper ? (block.querySelector('pre') || block) : block;
source.querySelectorAll('[style]').forEach(el => el.removeAttribute('style'));
while (source.firstChild) div.appendChild(source.firstChild);
} else {
while (block.firstChild) div.appendChild(block.firstChild);
}
if (!div.hasChildNodes()) div.innerHTML = '<br>';
block.parentNode.replaceChild(div, block);
const s = window.getSelection();
if (isPreBlock || isCodeWrapper) {
const contentRange = document.createRange();
contentRange.selectNodeContents(div);
s.removeAllRanges();
s.addRange(contentRange);
document.execCommand('removeFormat');
}
const newRange = document.createRange();
newRange.setStart(div, 0);
newRange.collapse(true);
s.removeAllRanges();
s.addRange(newRange);
div.dispatchEvent(new InputEvent('input', { bubbles: true, cancelable: false }));
}
function insertCodeBlock(body) {
// Outer <div> provides background-color (Gmail strips background-color from <pre>).
// Inner <pre> handles whitespace preservation and native Enter behaviour.
const wrapperStyle = PRE_WRAPPER_STYLE;
const preStyle = PRE_CODE_STYLE;
const html = `<div data-md-code="1" style="${wrapperStyle}"><pre style="${preStyle}"><br></pre></div><div>\u200B<br></div>`;
document.execCommand('insertHTML', false, html);
// Place cursor inside the <pre> block
const sel = window.getSelection();
const wrappers = body.querySelectorAll('[data-md-code] pre');
if (wrappers.length) {
const pre = wrappers[wrappers.length - 1];
const newRange = document.createRange();
newRange.setStart(pre, 0);
newRange.collapse(true);
sel.removeAllRanges();
sel.addRange(newRange);
}
}
function handleCodeBlockMacro(e, container, offset, textBefore, body) {
e.preventDefault();
setTimeout(() => {
const s = window.getSelection();
if (!s || !s.rangeCount) return;
const r = s.getRangeAt(0);
let curCont = r.startContainer;
let curOff = r.startOffset;
if (curCont.nodeType !== Node.TEXT_NODE) {
if (curOff > 0 && curCont.childNodes[curOff - 1] && curCont.childNodes[curOff - 1].nodeType === Node.TEXT_NODE) {
curCont = curCont.childNodes[curOff - 1];
curOff = curCont.textContent.length;
}
}
if (curCont.nodeType === Node.TEXT_NODE) {
const curText = curCont.textContent.slice(0, curOff);
// Clean out any pending OS/IME string of backticks (like OSX smart composition)
if (/^[\s\u200B\u200C\u200D\uFEFF]*`+$/.test(curText)) {
deletePrecise(curCont, curOff, curText.length);
} else {
try { deletePrecise(container, offset, textBefore.length); } catch (err) { }
}
} else {
try { deletePrecise(container, offset, textBefore.length); } catch (err) { }
}
insertCodeBlock(body);
}, 10);
}
function insertLineAfterHR(body) {
const hrs = body.querySelectorAll('hr');
if (!hrs.length) return;
const hr = hrs[hrs.length - 1];
const emptyDiv = document.createElement('div');
emptyDiv.innerHTML = '<br>';
hr.parentNode.insertBefore(emptyDiv, hr.nextSibling);
const newRange = document.createRange();
newRange.setStart(emptyDiv, 0);
newRange.collapse(true);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(newRange);
}
function splitBlockAtCursor(body) {
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0) return;
const range = sel.getRangeAt(0);
let block = range.startContainer;
if (block.nodeType === Node.TEXT_NODE) block = block.parentNode;
while (block && block !== body && !block.matches('div, p, h1, h2, h3, h4, h5, h6, li, blockquote, pre, [data-md-code]')) {
block = block.parentNode;
}
if (block && block !== body) {
const testRange = document.createRange();
testRange.setStart(block, 0);
testRange.setEnd(range.startContainer, range.startOffset);
const beforeFragment = testRange.cloneContents();
if (beforeFragment.querySelector('br') || beforeFragment.textContent.trim().length > 0) {
const afterRange = document.createRange();
afterRange.setStart(range.startContainer, range.startOffset);
afterRange.setEnd(block, block.childNodes.length);
const afterContent = afterRange.extractContents();
let lastNode = block.lastChild;
while (lastNode && lastNode.nodeType === Node.TEXT_NODE && lastNode.textContent === '') {
const prev = lastNode.previousSibling;
block.removeChild(lastNode);
lastNode = prev;
}
if (lastNode && lastNode.nodeName === 'BR') {
block.removeChild(lastNode);
}
const newBlock = document.createElement('div');
newBlock.appendChild(afterContent);
if (!newBlock.hasChildNodes()) newBlock.innerHTML = '<br>';
block.parentNode.insertBefore(newBlock, block.nextSibling);
const newSelRange = document.createRange();
newSelRange.setStart(newBlock, 0);
newSelRange.collapse(true);
sel.removeAllRanges();
sel.addRange(newSelRange);
}
}
}
function convertCurrentBlockToList(body, ordered) {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return false;
const range = selection.getRangeAt(0);
let block = range.startContainer;
if (block.nodeType === Node.TEXT_NODE) block = block.parentNode;
while (block && block !== body && !block.matches('div, p')) {
block = block.parentNode;
}
const list = document.createElement(ordered ? 'ol' : 'ul');
const item = document.createElement('li');
list.appendChild(item);
if (block && block !== body) {
while (block.firstChild) item.appendChild(block.firstChild);
block.parentNode.replaceChild(list, block);
} else if (range.startContainer.nodeType === Node.TEXT_NODE &&
range.startContainer.parentNode === body) {
const textNode = range.startContainer;
item.appendChild(textNode.cloneNode(true));
body.replaceChild(list, textNode);
} else {
const referenceNode = body.childNodes[range.startOffset] || null;
body.insertBefore(list, referenceNode);
}
if (!item.hasChildNodes() ||
(item.childNodes.length === 1 && item.firstChild.nodeType === Node.TEXT_NODE && item.textContent === '')) {
item.replaceChildren(document.createElement('br'));
}
const itemRange = document.createRange();
if (item.firstChild && item.firstChild.nodeType === Node.TEXT_NODE) {
itemRange.setStart(item.firstChild, 0);
} else {
itemRange.setStart(item, 0);
}
itemRange.collapse(true);
selection.removeAllRanges();
selection.addRange(itemRange);