-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditor.jsx
More file actions
1049 lines (969 loc) · 34.1 KB
/
Copy pathEditor.jsx
File metadata and controls
1049 lines (969 loc) · 34.1 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
import { useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react'
import { useTranslation } from 'react-i18next'
import { Editor as MilkdownEditor, rootCtx, defaultValueCtx, commandsCtx, serializerCtx, editorViewCtx } from '@milkdown/kit/core'
import { commonmark, headingSchema, blockquoteSchema, hrSchema, bulletListSchema, orderedListSchema, codeBlockSchema, insertImageCommand } from '@milkdown/kit/preset/commonmark'
import { clearTextInCurrentBlockCommand, setBlockTypeCommand, wrapInBlockTypeCommand, addBlockTypeCommand } from '@milkdown/kit/preset/commonmark'
import { gfm } from '@milkdown/kit/preset/gfm'
import { listener, listenerCtx } from '@milkdown/kit/plugin/listener'
import { clipboard } from '@milkdown/kit/plugin/clipboard'
import { history } from '@milkdown/kit/plugin/history'
import { slashFactory, SlashProvider } from '@milkdown/kit/plugin/slash'
import { TextSelection, Plugin, PluginKey } from '@milkdown/kit/prose/state'
import { $prose } from '@milkdown/kit/utils'
import api from '../../api/client'
import { wikilink } from './wikilink'
import { mention } from './mention'
import { math, mathBlockSchema } from './math'
import { tableTooltip } from './tableTooltip'
import { tablePasteExpand } from './tablePasteExpand'
import { isStrayPostCompositionEnter, NO_COMPOSITION } from './imeGuard'
const SLASH_ITEM_DEFS = [
{ id: 'h1', icon: 'H1' },
{ id: 'h2', icon: 'H2' },
{ id: 'h3', icon: 'H3' },
{ id: 'bullet', icon: '\u2022' },
{ id: 'ordered', icon: '1.' },
{ id: 'quote', icon: '\u275D' },
{ id: 'code', icon: '</>' },
{ id: 'hr', icon: '\u2014' },
{ id: 'callout-info', icon: '\u2139' },
{ id: 'callout-warning', icon: '\u26A0' },
{ id: 'callout-tip', icon: '\u2713' },
{ id: 'callout-danger', icon: '\u2715' },
{ id: 'mermaid', icon: '\u25C7' },
{ id: 'math', icon: '\u03A3' },
{ id: 'drawio', icon: '\u25A1' },
{ id: 'media', icon: '\u{1F5BC}' },
]
function buildSlashItems(t) {
return SLASH_ITEM_DEFS.map((d) => ({
id: d.id,
icon: d.icon,
label: t(`slash.items.${d.id}.label`),
desc: t(`slash.items.${d.id}.desc`),
}))
}
function executeSlashCommand(ctx, id, view, drawioHandlerRef, mediaHandlerRef) {
const commands = ctx.get(commandsCtx)
commands.call(clearTextInCurrentBlockCommand.key)
if (id.startsWith('callout-')) {
const type = id.replace('callout-', '')
if (view) {
const { state, dispatch } = view
const { from } = state.selection
const text = `\n:::${type}\n\n:::\n`
dispatch(state.tr.insertText(text, from))
}
return
}
if (id === 'mermaid' && view) {
const { state, dispatch } = view
const { from } = state.selection
const text = '\n```mermaid\ngraph TD\n A[Start] --> B[End]\n```\n'
dispatch(state.tr.insertText(text, from))
return
}
if (id === 'math' && view) {
const { state, dispatch } = view
const mathType = mathBlockSchema.type(ctx)
const node = mathType.create({ value: 'E = mc^2' })
dispatch(state.tr.replaceSelectionWith(node))
return
}
if (id === 'drawio') {
if (drawioHandlerRef?.current) drawioHandlerRef.current()
return
}
if (id === 'media') {
if (mediaHandlerRef?.current) mediaHandlerRef.current()
return
}
switch (id) {
case 'h1':
commands.call(setBlockTypeCommand.key, { nodeType: headingSchema.type(ctx), attrs: { level: 1 } })
break
case 'h2':
commands.call(setBlockTypeCommand.key, { nodeType: headingSchema.type(ctx), attrs: { level: 2 } })
break
case 'h3':
commands.call(setBlockTypeCommand.key, { nodeType: headingSchema.type(ctx), attrs: { level: 3 } })
break
case 'bullet':
commands.call(wrapInBlockTypeCommand.key, { nodeType: bulletListSchema.type(ctx) })
break
case 'ordered':
commands.call(wrapInBlockTypeCommand.key, { nodeType: orderedListSchema.type(ctx) })
break
case 'quote':
commands.call(wrapInBlockTypeCommand.key, { nodeType: blockquoteSchema.type(ctx) })
break
case 'code':
commands.call(setBlockTypeCommand.key, { nodeType: codeBlockSchema.type(ctx) })
break
case 'hr':
commands.call(addBlockTypeCommand.key, { nodeType: hrSchema.type(ctx) })
break
}
}
class SlashMenuView {
constructor(ctx, view, drawioHandlerRef, editorViewRef, mediaHandlerRef, items) {
this.ctx = ctx
this.view = view
this.drawioHandlerRef = drawioHandlerRef
this.mediaHandlerRef = mediaHandlerRef
this.editorViewRef = editorViewRef
this.items = items
editorViewRef.current = view
this.selectedIndex = 0
this.filteredItems = [...items]
this.isVisible = false
this.content = document.createElement('div')
this.content.className = 'slash-menu'
this.content.style.position = 'fixed'
this.content.style.zIndex = '100'
this.content.dataset.show = 'false'
this.renderItems()
this.provider = new SlashProvider({
content: this.content,
debounce: 50,
shouldShow: (view) => {
if (view.composing) return false
const currentText = this.provider.getContent(
view,
(node) => ['paragraph', 'heading'].includes(node.type.name)
)
if (currentText == null) return false
const { selection } = view.state
if (!(selection instanceof TextSelection)) return false
const { $head } = selection
if ($head.parentOffset !== $head.parent.content.size) return false
if (!currentText.startsWith('/')) return false
const filter = currentText.slice(1).toLowerCase()
this.filteredItems = this.items.filter(
(item) => item.label.toLowerCase().includes(filter) || item.id.includes(filter)
)
this.selectedIndex = 0
this.renderItems()
return this.filteredItems.length > 0
},
offset: 10,
})
this.provider.onShow = () => { this.isVisible = true }
this.provider.onHide = () => { this.isVisible = false }
this.update(view)
}
handleKey(event) {
if (!this.isVisible) return false
if (event.isComposing || event.keyCode === 229) return false
if (event.key === 'ArrowDown') {
event.preventDefault()
this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredItems.length - 1)
this.updateActiveItem()
return true
} else if (event.key === 'ArrowUp') {
event.preventDefault()
this.selectedIndex = Math.max(this.selectedIndex - 1, 0)
this.updateActiveItem()
return true
} else if (event.key === 'Enter') {
event.preventDefault()
const item = this.filteredItems[this.selectedIndex]
if (item) {
executeSlashCommand(this.ctx, item.id, this.view, this.drawioHandlerRef, this.mediaHandlerRef)
this.provider.hide()
}
return true
} else if (event.key === 'Escape') {
event.preventDefault()
this.provider.hide()
return true
}
return false
}
renderItems() {
this.content.innerHTML = ''
this.filteredItems.forEach((item, i) => {
const el = document.createElement('div')
el.className = 'slash-menu-item' + (i === this.selectedIndex ? ' active' : '')
el.innerHTML = `
<span class="slash-menu-icon">${item.icon}</span>
<div>
<div class="slash-menu-label">${item.label}</div>
<div class="slash-menu-desc">${item.desc}</div>
</div>
`
el.addEventListener('mouseenter', () => {
this.selectedIndex = i
this.updateActiveItem()
})
el.addEventListener('mousedown', (e) => {
e.preventDefault()
e.stopPropagation()
executeSlashCommand(this.ctx, item.id, this.view, this.drawioHandlerRef, this.mediaHandlerRef)
this.provider.hide()
})
this.content.appendChild(el)
})
}
updateActiveItem() {
const items = this.content.querySelectorAll('.slash-menu-item')
items.forEach((el, i) => {
el.classList.toggle('active', i === this.selectedIndex)
})
// Scroll selected item into view
items[this.selectedIndex]?.scrollIntoView({ block: 'nearest' })
}
update(view) {
this.view = view
this.editorViewRef.current = view
// Don't query or mutate menu state mid-IME — coordsAtPos / DOM writes
// triggered here can drop in-flight composition characters on Windows.
if (view.composing) return
this.provider.update(view)
}
destroy() {
this.provider.destroy()
this.content.remove()
}
}
// ── Wikilink [[ autocomplete ──
class WikilinkMenu {
constructor(emptyLabel) {
this.emptyLabel = emptyLabel
this.el = document.createElement('div')
this.el.className = 'wikilink-menu'
this.el.style.display = 'none'
document.body.appendChild(this.el)
this.pages = []
this.filtered = []
this.selectedIndex = 0
this.active = false
this.triggerPos = null // doc position where [[ starts
this._lastQuery = null
this._lastPagesCount = -1 // -1 forces a render on first show()
// Cache pages list
this.loadPages()
}
async loadPages() {
try {
const res = await api.get('/pages')
this.pages = (res.data.pages || res.data || []).map((p) => ({
slug: p.slug,
title: p.title,
}))
} catch { /* ignore */ }
}
show(view, from, query) {
if (this.active && this.triggerPos === from && this._lastQuery === query
&& this._lastPagesCount === this.pages.length) {
// Re-position only — query and page list unchanged, no need to re-render
const coords = view.coordsAtPos(view.state.selection.head)
this.el.style.left = coords.left + 'px'
this.el.style.top = (coords.bottom + 4) + 'px'
return
}
this._lastQuery = query
this._lastPagesCount = this.pages.length
this.active = true
this.triggerPos = from
this.filter(query)
// Position near cursor
const coords = view.coordsAtPos(view.state.selection.head)
this.el.style.position = 'fixed'
this.el.style.left = coords.left + 'px'
this.el.style.top = (coords.bottom + 4) + 'px'
this.el.style.display = ''
this.el.style.zIndex = '200'
}
hide() {
this.active = false
this.el.style.display = 'none'
this.triggerPos = null
this._lastQuery = null
this._lastPagesCount = -1
}
filter(query) {
const q = query.toLowerCase()
this.filtered = this.pages.filter(
(p) => p.title.toLowerCase().includes(q) || p.slug.toLowerCase().includes(q)
).slice(0, 8)
this.selectedIndex = 0
this.render()
}
render() {
this.el.innerHTML = ''
if (this.filtered.length === 0) {
const empty = document.createElement('div')
empty.className = 'wikilink-menu-empty'
empty.textContent = this.emptyLabel
this.el.appendChild(empty)
return
}
this.filtered.forEach((page, i) => {
const item = document.createElement('div')
item.className = 'wikilink-menu-item' + (i === this.selectedIndex ? ' active' : '')
item.innerHTML = `
<span class="wikilink-menu-title">${page.title}</span>
<span class="wikilink-menu-slug">/${page.slug}</span>
`
item.addEventListener('mouseenter', () => {
this.selectedIndex = i
this.render()
})
item.addEventListener('mousedown', (e) => {
e.preventDefault()
this.select(page)
})
this.el.appendChild(item)
})
}
select(page) {
if (!this._view || this.triggerPos == null) return
const { state, dispatch } = this._view
const to = state.selection.head
const nodeType = state.schema.nodes.wikilink
if (!nodeType) {
// Schema not registered yet — fall back to plain text so typing still works.
const text = `[[${page.slug}|${page.title}]]`
dispatch(state.tr.replaceWith(this.triggerPos, to, state.schema.text(text)))
} else {
const node = nodeType.create({
slug: page.slug,
display: page.title,
transclusion: false,
})
dispatch(state.tr.replaceWith(this.triggerPos, to, node))
}
this.hide()
}
handleKeyDown(view, event) {
if (!this.active) return false
if (event.isComposing || event.keyCode === 229) return false
if (event.key === 'ArrowDown') {
event.preventDefault()
this.selectedIndex = Math.min(this.selectedIndex + 1, this.filtered.length - 1)
this.render()
return true
}
if (event.key === 'ArrowUp') {
event.preventDefault()
this.selectedIndex = Math.max(this.selectedIndex - 1, 0)
this.render()
return true
}
if (event.key === 'Enter' || event.key === 'Tab') {
event.preventDefault()
const page = this.filtered[this.selectedIndex]
if (page) this.select(page)
return true
}
if (event.key === 'Escape') {
event.preventDefault()
this.hide()
return true
}
return false
}
destroy() {
this.el.remove()
}
}
const wikilinkPluginKey = new PluginKey('wikilink-autocomplete')
// ── Mention `@` / `@@` autocomplete ──
class MentionMenu {
constructor({ pageSlug, emptyLabel }) {
this.pageSlug = pageSlug
this.emptyLabel = emptyLabel
this.el = document.createElement('div')
this.el.className = 'wikilink-menu mention-menu'
this.el.style.display = 'none'
document.body.appendChild(this.el)
this.users = []
this.groups = []
this.combined = []
this.selectedIndex = 0
this.active = false
this.triggerPos = null
this.isGroup = false
this.lastQuery = null
this._fetchSeq = 0
}
async fetchCandidates(query, isGroup) {
const seq = ++this._fetchSeq
try {
let users = []
let groups = []
// Without a page context we can't ACL-filter; fall back to the
// generic user-search endpoint (already restricted to authenticated
// users) so the editor still surfaces candidates while editing a
// brand-new page. The actual notification still re-checks ACL.
if (this.pageSlug) {
const res = await api.get('/users/mentionable', {
params: { page_slug: this.pageSlug, q: query },
})
users = res.data.users || []
groups = res.data.groups || []
} else {
const res = await api.get('/users/search', { params: { q: query, limit: 10 } })
users = (res.data || []).map((u) => ({
username: u.username,
display_name: u.display_name || '',
}))
}
// Drop out-of-order responses so a slow earlier request can't paint
// stale rows over a fresher one.
if (seq !== this._fetchSeq) return
this.users = users
this.groups = groups
this.combined = isGroup
? groups.map((g) => ({ kind: 'group', name: g.name, sub: g.description }))
: [
...users.map((u) => ({ kind: 'user', name: u.username, sub: u.display_name })),
]
this.selectedIndex = 0
this.render()
} catch {
// ignore — autocomplete is best-effort
}
}
show(view, triggerPos, query, isGroup) {
this.active = true
this.triggerPos = triggerPos
this.isGroup = isGroup
this.lastQuery = query
const coords = view.coordsAtPos(view.state.selection.head)
this.el.style.position = 'fixed'
this.el.style.left = coords.left + 'px'
this.el.style.top = (coords.bottom + 4) + 'px'
this.el.style.display = ''
this.el.style.zIndex = '200'
this.fetchCandidates(query, isGroup)
}
hide() {
this.active = false
this.el.style.display = 'none'
this.triggerPos = null
this.lastQuery = null
}
render() {
this.el.innerHTML = ''
if (this.combined.length === 0) {
const empty = document.createElement('div')
empty.className = 'wikilink-menu-empty'
empty.textContent = this.emptyLabel
this.el.appendChild(empty)
return
}
this.combined.forEach((item, i) => {
const row = document.createElement('div')
row.className = 'wikilink-menu-item' + (i === this.selectedIndex ? ' active' : '')
const sigil = item.kind === 'group' ? '@@' : '@'
const escName = item.name.replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' }[c]))
const escSub = (item.sub || '').replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' }[c]))
row.innerHTML = `
<span class="wikilink-menu-title">${sigil}${escName}</span>
<span class="wikilink-menu-slug">${escSub}</span>
`
row.addEventListener('mouseenter', () => {
this.selectedIndex = i
this.render()
})
row.addEventListener('mousedown', (e) => {
e.preventDefault()
this.select(item)
})
this.el.appendChild(row)
})
}
select(item) {
if (!this._view || this.triggerPos == null) return
const { state, dispatch } = this._view
const to = state.selection.head
const nodeType = state.schema.nodes.mention
if (!nodeType) {
const sigil = item.kind === 'group' ? '@@' : '@'
const text = `${sigil}${item.name} `
dispatch(state.tr.replaceWith(this.triggerPos, to, state.schema.text(text)))
} else {
const node = nodeType.create({
name: item.name,
group: item.kind === 'group',
})
// Insert the node + a trailing space so the user can keep typing
// without the next keystroke being absorbed into the atom node.
const tr = state.tr.replaceWith(this.triggerPos, to, node)
tr.insertText(' ', tr.mapping.map(to))
dispatch(tr)
}
this.hide()
}
handleKeyDown(view, event) {
if (!this.active) return false
if (event.isComposing || event.keyCode === 229) return false
if (event.key === 'ArrowDown') {
event.preventDefault()
this.selectedIndex = Math.min(this.selectedIndex + 1, this.combined.length - 1)
this.render()
return true
}
if (event.key === 'ArrowUp') {
event.preventDefault()
this.selectedIndex = Math.max(this.selectedIndex - 1, 0)
this.render()
return true
}
if (event.key === 'Enter' || event.key === 'Tab') {
if (this.combined.length === 0) return false
event.preventDefault()
const item = this.combined[this.selectedIndex]
if (item) this.select(item)
return true
}
if (event.key === 'Escape') {
event.preventDefault()
this.hide()
return true
}
return false
}
destroy() {
this.el.remove()
}
}
const mentionPluginKey = new PluginKey('mention-autocomplete')
const Editor = forwardRef(function Editor({ defaultValue = '', onChange, onDrawioOpen, onMediaPickerOpen, onTabOut, pageSlug = null }, ref) {
const { t } = useTranslation()
const editorRef = useRef(null)
const containerRef = useRef(null)
const onChangeRef = useRef(onChange)
const drawioHandlerRef = useRef(onDrawioOpen)
const mediaHandlerRef = useRef(onMediaPickerOpen)
const onTabOutRef = useRef(onTabOut)
const editorViewRef = useRef(null)
// Source ("plain Markdown") mode is a textarea-based fallback. The Milkdown
// contenteditable mishandles IME composition on Windows (committing a Zhuyin
// selection with Enter can revert to the raw phonetic buffer and drop the
// last keystrokes); a native <textarea> has none of that. The preference is
// persisted so affected users set it once.
const SOURCE_MODE_KEY = 'editor.sourceMode'
const [sourceMode, setSourceMode] = useState(
() => typeof localStorage !== 'undefined' && localStorage.getItem(SOURCE_MODE_KEY) === '1'
)
const sourceRef = useRef(null)
// Latest markdown, kept current in both modes so we can seed the other mode
// when the user toggles.
const markdownRef = useRef(defaultValue)
const [sourceText, setSourceText] = useState(defaultValue)
// The slash menu and wikilink menu both render plain DOM (not React),
// so they cannot read t() from context. Snapshot translated strings into
// refs before the editor's init effect runs.
const slashItemsRef = useRef(null)
const wikilinkEmptyRef = useRef('')
const mentionEmptyRef = useRef('')
const tableTooltipLabelsRef = useRef(null)
const pageSlugRef = useRef(pageSlug)
useEffect(() => { pageSlugRef.current = pageSlug }, [pageSlug])
useEffect(() => {
slashItemsRef.current = buildSlashItems(t)
wikilinkEmptyRef.current = t('slash.wikilinkEmpty')
mentionEmptyRef.current = t('mention.empty', 'No matches')
tableTooltipLabelsRef.current = {
addRowAbove: t('tableTooltip.addRowAbove'),
addRowBelow: t('tableTooltip.addRowBelow'),
addColLeft: t('tableTooltip.addColLeft'),
addColRight: t('tableTooltip.addColRight'),
deleteRow: t('tableTooltip.deleteRow'),
deleteCol: t('tableTooltip.deleteCol'),
deleteTable: t('tableTooltip.deleteTable'),
}
}, [t])
useEffect(() => {
onChangeRef.current = onChange
})
useEffect(() => {
drawioHandlerRef.current = onDrawioOpen || null
}, [onDrawioOpen])
useEffect(() => {
mediaHandlerRef.current = onMediaPickerOpen || null
}, [onMediaPickerOpen])
useEffect(() => {
onTabOutRef.current = onTabOut || null
}, [onTabOut])
useImperativeHandle(ref, () => ({
insertText(text) {
const view = editorViewRef.current
if (!view) {
// Source mode: splice at the textarea caret.
const ta = sourceRef.current
if (!ta) return
const start = ta.selectionStart ?? ta.value.length
const end = ta.selectionEnd ?? start
const next = ta.value.slice(0, start) + text + ta.value.slice(end)
markdownRef.current = next
setSourceText(next)
onChangeRef.current?.(next)
requestAnimationFrame(() => {
const el = sourceRef.current
if (!el) return
const caret = start + text.length
el.focus()
el.setSelectionRange(caret, caret)
})
return
}
const { state, dispatch } = view
const pos = state.selection.from
dispatch(state.tr.insertText(text, pos))
},
focus() {
const view = editorViewRef.current
if (!view) {
sourceRef.current?.focus()
return
}
view.focus()
},
getMarkdown() {
const editor = editorRef.current
// Source mode (or before init): the textarea text is the source of truth.
if (!editor) return markdownRef.current
let md = null
editor.action((ctx) => {
const view = ctx.get(editorViewCtx)
md = ctx.get(serializerCtx)(view.state.doc)
})
markdownRef.current = md
return md
},
}), [])
useEffect(() => {
// Source mode renders a plain textarea instead — no Milkdown to build.
if (sourceMode) return
if (!containerRef.current) return
let cancelled = false
const slash = slashFactory('slash-menu')
// Create wikilink plugin per editor instance to avoid stale DOM references
const wikilinkMenu = new WikilinkMenu(wikilinkEmptyRef.current)
const wikilinkPlugin = $prose(() => {
return new Plugin({
key: wikilinkPluginKey,
props: {
handleKeyDown(view, event) {
return wikilinkMenu.handleKeyDown(view, event)
},
},
view(editorView) {
wikilinkMenu._view = editorView
return {
update(view) {
wikilinkMenu._view = view
// Bail during IME composition: coordsAtPos + DOM writes from
// show()/hide() can disturb the active composition on Windows,
// making characters disappear and the cursor jump.
if (view.composing) return
const { state } = view
const { selection } = state
if (!(selection instanceof TextSelection)) {
wikilinkMenu.hide()
return
}
const { $head } = selection
const textBefore = $head.parent.textContent.slice(0, $head.parentOffset)
const lastOpen = textBefore.lastIndexOf('[[')
if (lastOpen === -1) {
wikilinkMenu.hide()
return
}
const afterOpen = textBefore.slice(lastOpen + 2)
if (afterOpen.includes(']]')) {
wikilinkMenu.hide()
return
}
const query = afterOpen.split('|')[0]
const blockStart = $head.pos - $head.parentOffset
const triggerPos = blockStart + lastOpen
wikilinkMenu.show(view, triggerPos, query)
},
destroy() {
wikilinkMenu.destroy()
},
}
},
})
})
const mentionMenu = new MentionMenu({
pageSlug: pageSlugRef.current,
emptyLabel: mentionEmptyRef.current,
})
const mentionPlugin = $prose(() => {
return new Plugin({
key: mentionPluginKey,
props: {
handleKeyDown(view, event) {
return mentionMenu.handleKeyDown(view, event)
},
},
view(editorView) {
mentionMenu._view = editorView
return {
update(view) {
mentionMenu._view = view
if (view.composing) return
const { state } = view
const { selection } = state
if (!(selection instanceof TextSelection)) {
mentionMenu.hide()
return
}
const { $head } = selection
const textBefore = $head.parent.textContent.slice(0, $head.parentOffset)
// Find the latest `@` (or `@@`) start that is followed only by
// mention-name chars up to the cursor. Stop on whitespace or
// anything outside `[A-Za-z0-9_-@]` so a previous mention on
// the same line doesn't keep the menu open forever.
let i = textBefore.length - 1
while (i >= 0 && /[A-Za-z0-9_-]/.test(textBefore[i])) i--
if (i < 0 || textBefore[i] !== '@') {
mentionMenu.hide()
return
}
// Name must start with alphanum (matches the renderer/server
// regex). `@-bob` typed mid-word is junk, hide rather than
// surface a mention that won't ever resolve.
const firstNameChar = textBefore[i + 1]
if (firstNameChar !== undefined && !/[A-Za-z0-9]/.test(firstNameChar)) {
mentionMenu.hide()
return
}
let triggerStart = i
let isGroup = false
if (i > 0 && textBefore[i - 1] === '@') {
triggerStart = i - 1
isGroup = true
}
// Boundary check: char before `@` (or `@@`) must not be word/@//.
if (triggerStart > 0) {
const prev = textBefore[triggerStart - 1]
if (/[A-Za-z0-9_@/]/.test(prev)) {
mentionMenu.hide()
return
}
}
const query = textBefore.slice(i + 1)
const blockStart = $head.pos - $head.parentOffset
const triggerPos = blockStart + triggerStart
if (mentionMenu.active && mentionMenu.triggerPos === triggerPos && mentionMenu.lastQuery === query) {
return // already showing this exact state
}
mentionMenu.show(view, triggerPos, query, isGroup)
},
destroy() {
mentionMenu.destroy()
},
}
},
})
})
const tabOutPlugin = $prose(() => {
return new Plugin({
props: {
handleKeyDown(view, event) {
if (event.key !== 'Tab' || event.shiftKey) return false
if (event.isComposing || event.keyCode === 229) return false
if (!onTabOutRef.current) return false
const { $from } = view.state.selection
for (let depth = $from.depth; depth >= 0; depth--) {
const name = $from.node(depth).type.name
if (['list_item', 'bullet_list', 'ordered_list', 'code_block', 'table'].includes(name)) {
return false
}
}
event.preventDefault()
onTabOutRef.current()
return true
},
},
})
})
// On Windows, the Enter that confirms an IME selection can surface as a
// stray keydown fired right after compositionend (isComposing already
// false), which ProseMirror's default Enter handler would turn into a
// spurious block split. Suppress only that stray Enter — scoped to a
// short window after compositionend — and never an Enter that is still
// part of an active composition (see imeGuard.js for the rationale).
const compositionGuardPlugin = $prose(() => {
let lastCompositionEndAt = NO_COMPOSITION
return new Plugin({
props: {
handleDOMEvents: {
compositionend(_view, _event) {
lastCompositionEndAt = performance.now()
return false
},
},
handleKeyDown(_view, event) {
if (isStrayPostCompositionEnter(event, lastCompositionEndAt, performance.now())) {
event.preventDefault()
return true
}
return false
},
},
})
})
const init = async () => {
const editor = await MilkdownEditor.make()
.config((ctx) => {
ctx.set(rootCtx, containerRef.current)
// Seed from the live markdown (so toggling back from source mode keeps
// edits), falling back to the initial prop on first mount.
ctx.set(defaultValueCtx, markdownRef.current ?? defaultValue)
ctx.get(listenerCtx).markdownUpdated((_ctx, markdown) => {
// Skip parent state updates while IME composition is active —
// the React re-render they trigger can interrupt composition on
// Windows. ProseMirror dispatches a final transaction at
// compositionend, which fires the listener again with the
// committed text, so no input is lost.
if (editorViewRef.current?.composing) return
markdownRef.current = markdown
onChangeRef.current?.(markdown)
})
let slashMenuView = null
ctx.set(slash.key, {
view: (editorView) => {
slashMenuView = new SlashMenuView(ctx, editorView, drawioHandlerRef, editorViewRef, mediaHandlerRef, slashItemsRef.current)
return slashMenuView
},
props: {
handleKeyDown(view, event) {
return slashMenuView?.handleKey(event) ?? false
},
},
})
})
.use(tablePasteExpand)
.use(commonmark)
.use(gfm)
.use(math)
.use(listener)
.use(clipboard)
.use(history)
.use(slash)
.use(wikilink)
.use(wikilinkPlugin)
.use(mention)
.use(mentionPlugin)
.use(tabOutPlugin)
.use(compositionGuardPlugin)
.use(tableTooltip(tableTooltipLabelsRef.current))
.create()
// StrictMode: if cleanup ran while we were awaiting, destroy immediately
if (cancelled) {
editor.destroy()
return
}
editorRef.current = editor
}
init()
return () => {
cancelled = true
if (editorRef.current) {
editorRef.current.destroy()
editorRef.current = null
}
editorViewRef.current = null
// Clear leftover DOM from any editor
if (containerRef.current) {
containerRef.current.innerHTML = ''
}
}
}, [sourceMode])
// Image paste handler
useEffect(() => {
if (sourceMode) return
const container = containerRef.current
if (!container) return
const handlePaste = async (e) => {
const items = e.clipboardData?.items
if (!items) return
for (const item of items) {
if (item.type.startsWith('image/')) {
e.preventDefault()
const file = item.getAsFile()
if (!file) continue
const formData = new FormData()
formData.append('file', file)
try {
const res = await api.post('/media/upload', formData)
const url = res.data.url
const editor = editorRef.current
if (editor) {
editor.action((ctx) => {
const commands = ctx.get(commandsCtx)
commands.call(insertImageCommand.key, { src: url, alt: 'image' })
})
}
} catch (err) {
console.error('Image upload failed:', err)
}
}
}
}
container.addEventListener('paste', handlePaste)
return () => container.removeEventListener('paste', handlePaste)
}, [sourceMode])
const handleSourceChange = (e) => {
const v = e.target.value
markdownRef.current = v
setSourceText(v)
onChangeRef.current?.(v)
}
const toggleSourceMode = () => {
const goingToSource = !sourceMode