-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathMarkdownManager.ts
More file actions
1616 lines (1402 loc) · 55.8 KB
/
Copy pathMarkdownManager.ts
File metadata and controls
1616 lines (1402 loc) · 55.8 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 {
type AnyExtension,
type ExtendableConfig,
type JSONContent,
type MarkdownExtensionSpec,
type MarkdownLexerConfiguration,
type MarkdownParseHelpers,
type MarkdownParseResult,
type MarkdownRendererHelpers,
type MarkdownToken,
type MarkdownTokenizer,
type RenderContext,
attrsEqual,
callOrReturn,
decodeHtmlEntities,
encodeHtmlEntities,
flattenExtensions,
generateJSON,
getExtensionField,
getSchema,
marksEqual,
sortExtensions,
} from '@tiptap/core'
import { type Lexer, type Token, type TokenizerExtension, type TokenizerThis, marked } from 'marked'
import {
closeMarksBeforeNode,
findMarksToClose,
findMarksToCloseAtEnd,
findMarksToOpen,
isTaskItem,
reopenMarksAfterNode,
wrapInMarkdownBlock,
} from './utils.js'
import { htmlContainsUnrecognizedTag } from './utils/htmlTagDetection.js'
export class MarkdownManager {
private markedInstance: typeof marked
private activeParseLexer: Lexer | null = null
private registry: Map<string, MarkdownExtensionSpec[]>
private nodeTypeRegistry: Map<string, MarkdownExtensionSpec[]>
/**
* Order in which extensions were registered. Used to resolve mark nesting
* deterministically when several marks open on the same text node.
*
* The flattened extensions passed to the manager are pre-sorted by Tiptap's
* extension priority (descending), which is also the order ProseMirror uses
* to assign mark ranks. Recording that index here lets the serializer place
* higher-priority / lower-rank marks (e.g. link with priority 1000) on the
* outside without inspecting any rendered markdown output.
*/
private extensionRanks: Map<string, number> = new Map()
private indentStyle: 'space' | 'tab'
private indentSize: number
private baseExtensions: AnyExtension[] = []
private extensions: AnyExtension[] = []
/** Set of extension names whose `code` spec property is truthy (nodes and marks). */
private codeTypes: Set<string> = new Set()
/** Lazy cache of tag names declared by the registered schema's parseDOM rules. */
private schemaParseDomTagsCache: Set<string> | null = null
/**
* Create a MarkdownManager.
* @param options.marked Optional marked instance to use (injected).
* @param options.markedOptions Optional options to pass to marked.setOptions
* @param options.indentation Indentation settings (style and size).
* @param options.extensions An array of Tiptap extensions to register for markdown parsing and rendering.
*/
constructor(options?: {
marked?: typeof marked
markedOptions?: Parameters<typeof marked.setOptions>[0]
indentation?: { style?: 'space' | 'tab'; size?: number }
extensions: AnyExtension[]
}) {
this.markedInstance = options?.marked ?? marked
this.indentStyle = options?.indentation?.style ?? 'space'
this.indentSize = options?.indentation?.size ?? 2
this.baseExtensions = options?.extensions || []
if (options?.markedOptions && typeof this.markedInstance.setOptions === 'function') {
this.markedInstance.setOptions(options.markedOptions)
}
this.registry = new Map()
this.nodeTypeRegistry = new Map()
// If extensions were provided, register them now. Sort by Tiptap priority
// first (matching how the editor builds its schema) so the registration
// index lines up with ProseMirror's mark rank — this is what the
// serializer relies on to nest higher-priority marks like link outermost.
if (options?.extensions) {
this.baseExtensions = options.extensions
const flattened = sortExtensions(flattenExtensions(options.extensions))
flattened.forEach(ext => this.registerExtension(ext))
}
}
/** Returns the underlying marked instance. */
get instance(): typeof marked {
return this.markedInstance
}
/** Returns the correct indentCharacter (space or tab) */
get indentCharacter(): string {
return this.indentStyle === 'space' ? ' ' : '\t'
}
/** Returns the correct indentString repeated X times */
get indentString(): string {
return this.indentCharacter.repeat(this.indentSize)
}
/** Helper to quickly check whether a marked instance is available. */
hasMarked(): boolean {
return !!this.markedInstance
}
/**
* Register a Tiptap extension (Node/Mark/Extension). This will read
* `markdownName`, `parseMarkdown`, `renderMarkdown` and `priority` from the
* extension config (using the same resolution used across the codebase).
*/
registerExtension(extension: AnyExtension): void {
// Keep track of all extensions for HTML parsing
this.extensions.push(extension)
// Track extensions that declare `code: true` so we can skip HTML entity
// encoding inside code contexts without hardcoding specific type names.
const isCode = callOrReturn(getExtensionField(extension, 'code'))
const name = extension.name
if (isCode) {
this.codeTypes.add(name)
}
if (!this.extensionRanks.has(name)) {
this.extensionRanks.set(name, this.extensionRanks.size)
}
const tokenName =
(getExtensionField(
extension,
'markdownTokenName',
) as ExtendableConfig['markdownTokenName']) || name
const parseMarkdown = getExtensionField(extension, 'parseMarkdown') as
| ExtendableConfig['parseMarkdown']
| undefined
const renderMarkdown = getExtensionField(extension, 'renderMarkdown') as
| ExtendableConfig['renderMarkdown']
| undefined
const tokenizer = getExtensionField(extension, 'markdownTokenizer') as
| ExtendableConfig['markdownTokenizer']
| undefined
// Read the `markdown` object from the extension config. This allows
// extensions to provide `markdown: { name?, parseName?, renderName?, parse?, render?, match? }`.
const markdownCfg = (getExtensionField(extension, 'markdownOptions') ??
null) as ExtendableConfig['markdownOptions']
const isIndenting = markdownCfg?.indentsContent ?? false
const htmlReopen = markdownCfg?.htmlReopen
const spec: MarkdownExtensionSpec = {
tokenName,
nodeName: name,
parseMarkdown,
renderMarkdown,
isIndenting,
htmlReopen,
tokenizer,
}
// Add to parse registry using parseName
if (tokenName && parseMarkdown) {
const parseExisting = this.registry.get(tokenName) || []
parseExisting.push(spec)
this.registry.set(tokenName, parseExisting)
}
// Add to render registry using renderName (node type)
if (renderMarkdown) {
const renderExisting = this.nodeTypeRegistry.get(name) || []
renderExisting.push(spec)
this.nodeTypeRegistry.set(name, renderExisting)
}
// Register custom tokenizer with marked.js
if (tokenizer && this.hasMarked()) {
this.registerTokenizer(tokenizer)
}
}
private createLexer(): Lexer {
// Pass the instance's defaults so the lexer keeps its `use()`-registered tokenizers.
return new this.markedInstance.Lexer(this.markedInstance.defaults)
}
private createTokenizerHelpers(lexer: Lexer): MarkdownLexerConfiguration {
return {
inlineTokens: (src: string) => lexer.inlineTokens(src),
blockTokens: (src: string) => lexer.blockTokens(src),
}
}
private tokenizeInline(src: string): MarkdownToken[] {
return (this.activeParseLexer ?? this.createLexer()).inlineTokens(src) as MarkdownToken[]
}
/**
* Register a custom tokenizer with marked.js for parsing non-standard markdown syntax.
*/
private registerTokenizer(tokenizer: MarkdownTokenizer): void {
if (!this.hasMarked()) {
return
}
const { name, start, level = 'inline', tokenize } = tokenizer
const createTokenizerHelpers = this.createTokenizerHelpers.bind(this)
const createLexer = this.createLexer.bind(this)
let startCb: (src: string) => number
if (!start) {
startCb = (src: string) => {
// For other tokenizers, try to find a match and return its position
const result = tokenize(src, [], this.createTokenizerHelpers(this.createLexer()))
if (result && result.raw) {
const index = src.indexOf(result.raw)
return index
}
return -1
}
} else {
startCb = typeof start === 'function' ? start : (src: string) => src.indexOf(start)
}
// Create marked.js extension with proper types
const markedExtension: TokenizerExtension = {
name,
level,
start: startCb,
tokenizer(this: TokenizerThis, src, tokens) {
const helper = this.lexer
? createTokenizerHelpers(this.lexer)
: createTokenizerHelpers(createLexer())
const result = tokenize(src, tokens, helper)
if (result && result.type) {
return {
...result,
type: result.type || name,
raw: result.raw || '',
tokens: (result.tokens || []) as Token[],
}
}
return undefined
},
childTokens: [],
}
// Register with marked.js - use extensions array to control priority
this.markedInstance.use({
extensions: [markedExtension],
})
}
/** Get registered handlers for a token type and try each until one succeeds. */
private getHandlersForToken(type: string): MarkdownExtensionSpec[] {
try {
return this.registry.get(type) || []
} catch {
return []
}
}
/** Get the first handler for a token type (for backwards compatibility). */
private getHandlerForToken(type: string): MarkdownExtensionSpec | undefined {
// First try the markdown token registry (for parsing)
const markdownHandlers = this.getHandlersForToken(type)
if (markdownHandlers.length > 0) {
return markdownHandlers[0]
}
// Then try the node type registry (for rendering)
const nodeTypeHandlers = this.getHandlersForNodeType(type)
return nodeTypeHandlers.length > 0 ? nodeTypeHandlers[0] : undefined
}
/** Get registered handlers for a node type (for rendering). */
private getHandlersForNodeType(type: string): MarkdownExtensionSpec[] {
try {
return this.nodeTypeRegistry.get(type) || []
} catch {
return []
}
}
/**
* Serialize a ProseMirror-like JSON document (or node array) to a Markdown string
* using registered renderers and fallback renderers.
*/
serialize(docOrContent: JSONContent): string {
if (!docOrContent) {
return ''
}
const result = this.renderNodes(docOrContent, docOrContent)
// Return empty string if result is only whitespace entities or non-breaking spaces
return this.isEmptyOutput(result) ? '' : result
}
/**
* Check if the markdown output represents an empty document.
* Empty documents may contain only entities or non-breaking space characters
* which are used by the Paragraph extension to preserve blank lines.
*/
private isEmptyOutput(markdown: string): boolean {
if (!markdown || markdown.trim() === '') {
return true
}
// Check if the output is only entities or non-breaking space characters
const cleanedOutput = markdown
.replace(/ /g, '')
.replace(/\u00A0/g, '')
.trim()
return cleanedOutput === ''
}
/**
* Parse markdown string into Tiptap JSON document using registered extension handlers.
*/
parse(markdown: string): JSONContent {
if (!this.hasMarked()) {
throw new Error('No marked instance available for parsing')
}
const previousParseLexer = this.activeParseLexer
const parseLexer = this.createLexer()
this.activeParseLexer = parseLexer
try {
// Use a parse-scoped lexer so follow-up inline tokenization can reuse
// the same configured lexer state without sharing it across parses.
const tokens = parseLexer.lex(markdown) as MarkdownToken[]
// Convert tokens to Tiptap JSON
const content = this.parseTokens(tokens, true)
// A `doc` node requires at least one block child (`block+`), so an empty
// `content` array produces an invalid document that makes `setContent`
// throw `RangeError: Invalid content for node doc: <>`. This happens for
// input that yields no renderable blocks — whitespace-only markdown, or
// markdown whose only token has no registered handler (e.g. an indented
// code block when no code-block extension is present, as with a line of
// leading whitespace followed by text). Fall back to a single empty
// paragraph, matching how an empty markdown string is represented.
return {
type: 'doc',
content: content.length > 0 ? content : [{ type: 'paragraph' }],
}
} finally {
this.activeParseLexer = previousParseLexer
}
}
/**
* Convert an array of marked tokens into Tiptap JSON nodes using registered extension handlers.
*/
private parseTokens(
tokens: MarkdownToken[],
parseImplicitEmptyParagraphs = false,
): JSONContent[] {
const nonSpaceTokenIndexes = tokens.reduce<number[]>((indexes, token, index) => {
if (token.type !== 'space') {
indexes.push(index)
}
return indexes
}, [])
let previousNonSpaceTokenIndex = -1
let nextNonSpaceTokenPointer = 0
return tokens.flatMap((token, index) => {
while (
nextNonSpaceTokenPointer < nonSpaceTokenIndexes.length &&
nonSpaceTokenIndexes[nextNonSpaceTokenPointer] < index
) {
previousNonSpaceTokenIndex = nonSpaceTokenIndexes[nextNonSpaceTokenPointer]
nextNonSpaceTokenPointer += 1
}
if (parseImplicitEmptyParagraphs && token.type === 'space') {
const nextNonSpaceTokenIndex = nonSpaceTokenIndexes[nextNonSpaceTokenPointer] ?? -1
return this.createImplicitEmptyParagraphsFromSpace(
token,
previousNonSpaceTokenIndex,
nextNonSpaceTokenIndex,
)
}
const parsed = this.parseToken(token, parseImplicitEmptyParagraphs)
if (parsed === null) {
return []
}
return Array.isArray(parsed) ? parsed : [parsed]
})
}
private createImplicitEmptyParagraphsFromSpace(
token: MarkdownToken,
previousNonSpaceTokenIndex: number,
nextNonSpaceTokenIndex: number,
): JSONContent[] {
const separatorCount = this.countParagraphSeparators(token.raw || '')
if (separatorCount === 0) {
return []
}
const isBoundarySpace = previousNonSpaceTokenIndex === -1 || nextNonSpaceTokenIndex === -1
const emptyParagraphCount = Math.max(separatorCount - (isBoundarySpace ? 0 : 1), 0)
return Array.from({ length: emptyParagraphCount }, () => ({ type: 'paragraph', content: [] }))
}
private countParagraphSeparators(raw: string): number {
return (raw.replace(/\r\n/g, '\n').match(/\n\n/g) || []).length
}
/**
* Parse a single token into Tiptap JSON using the appropriate registered handler.
*/
private parseToken(
token: MarkdownToken,
parseImplicitEmptyParagraphs = false,
): JSONContent | JSONContent[] | null {
if (!token.type) {
return null
}
// Special handling for 'list' tokens that may contain mixed bullet/task items
if (token.type === 'list') {
return this.parseListToken(token)
}
const handlers = this.getHandlersForToken(token.type)
const helpers = this.createParseHelpers()
// Try each handler until one returns a valid result
const result = handlers.find(handler => {
if (!handler.parseMarkdown) {
return false
}
const parseResult = handler.parseMarkdown(token, helpers)
const normalized = this.normalizeParseResult(parseResult)
// Check if this handler returned a valid result (not null/empty array)
if (normalized && (!Array.isArray(normalized) || normalized.length > 0)) {
// Store result for return
this.lastParseResult = normalized
return true
}
return false
})
// If a handler worked, return its result
if (result && this.lastParseResult) {
const toReturn = this.lastParseResult
this.lastParseResult = null // Clean up
return toReturn
}
// If no handler worked, try fallback parsing
return this.parseFallbackToken(token, parseImplicitEmptyParagraphs)
}
private lastParseResult: JSONContent | JSONContent[] | null = null
/**
* Parse a list token, handling mixed bullet and task list items by splitting them into separate lists.
* This ensures that consecutive task items and bullet items are grouped and parsed as separate list nodes.
*
* @param token The list token to parse
* @returns Array of parsed list nodes, or null if parsing fails
*/
private parseListToken(token: MarkdownToken): JSONContent | JSONContent[] | null {
if (!token.items || token.items.length === 0) {
// No items, parse normally
return this.parseTokenWithHandlers(token)
}
const hasTask = token.items.some(item => isTaskItem(item).isTask)
const hasNonTask = token.items.some(item => !isTaskItem(item).isTask)
if (!hasTask || !hasNonTask || this.getHandlersForToken('taskList').length === 0) {
// Not mixed or no taskList extension, parse normally
return this.parseTokenWithHandlers(token)
}
// Mixed list with taskList extension available: split into separate lists
type TaskListItemToken = MarkdownToken & {
type: 'taskItem'
checked?: boolean
indentLevel?: number
}
const groups: { type: 'list' | 'taskList'; items: (MarkdownToken | TaskListItemToken)[] }[] = []
let currentGroup: (MarkdownToken | TaskListItemToken)[] = []
let currentType: 'list' | 'taskList' | null = null
for (let i = 0; i < token.items.length; i += 1) {
const item = token.items[i]
const { isTask, checked, indentLevel } = isTaskItem(item)
let processedItem = item
if (isTask) {
// Transform list_item into taskItem token
const raw = item.raw || item.text || ''
// Split raw content by lines to separate main content from nested
const lines = raw.split('\n')
// Extract main content from the first line
const firstLineMatch = lines[0].match(/^\s*[-+*]\s+\[([ xX])\]\s+(.*)$/)
const mainContent = firstLineMatch ? firstLineMatch[2] : ''
// Parse nested content from remaining lines
let nestedTokens: MarkdownToken[] = []
if (lines.length > 1) {
// Join all lines after the first
const nestedRaw = lines.slice(1).join('\n')
// Only parse if there's actual content
if (nestedRaw.trim()) {
// Find minimum indentation of non-empty lines
const nestedLines = lines.slice(1)
const nonEmptyLines = nestedLines.filter(line => line.trim())
if (nonEmptyLines.length > 0) {
const minIndent = Math.min(
...nonEmptyLines.map(line => line.length - line.trimStart().length),
)
// Remove common indentation while preserving structure
const trimmedLines = nestedLines.map(line => {
if (!line.trim()) {
return '' // Keep empty lines
}
return line.slice(minIndent)
})
const nestedContent = trimmedLines.join('\n').trim()
// Use the lexer to parse nested content
if (nestedContent) {
// Use the full lexer pipeline to ensure inline tokens are populated
nestedTokens = this.markedInstance.lexer(`${nestedContent}\n`)
}
}
}
}
processedItem = {
type: 'taskItem',
raw: '',
mainContent,
indentLevel,
checked: checked ?? false,
text: mainContent,
tokens: this.tokenizeInline(mainContent),
nestedTokens,
}
}
const itemType: 'list' | 'taskList' = isTask ? 'taskList' : 'list'
if (currentType !== itemType) {
if (currentGroup.length > 0) {
groups.push({ type: currentType!, items: currentGroup })
}
currentGroup = [processedItem]
currentType = itemType
} else {
currentGroup.push(processedItem)
}
}
if (currentGroup.length > 0) {
groups.push({ type: currentType!, items: currentGroup })
}
// Parse each group as a separate token
const results: JSONContent[] = []
for (let i = 0; i < groups.length; i += 1) {
const group = groups[i]
const subToken = { ...token, type: group.type, items: group.items }
const parsed = this.parseToken(subToken)
if (parsed) {
if (Array.isArray(parsed)) {
results.push(...parsed)
} else {
results.push(parsed)
}
}
}
return results.length > 0 ? results : null
}
/**
* Parse a token using registered handlers (extracted for reuse).
*/
private parseTokenWithHandlers(token: MarkdownToken): JSONContent | JSONContent[] | null {
if (!token.type) {
return null
}
const handlers = this.getHandlersForToken(token.type)
const helpers = this.createParseHelpers()
// Try each handler until one returns a valid result
const result = handlers.find(handler => {
if (!handler.parseMarkdown) {
return false
}
const parseResult = handler.parseMarkdown(token, helpers)
const normalized = this.normalizeParseResult(parseResult)
// Check if this handler returned a valid result (not null/empty array)
if (normalized && (!Array.isArray(normalized) || normalized.length > 0)) {
// Store result for return
this.lastParseResult = normalized
return true
}
return false
})
// If a handler worked, return its result
if (result && this.lastParseResult) {
const toReturn = this.lastParseResult
this.lastParseResult = null // Clean up
return toReturn
}
// If no handler worked, try fallback parsing
return this.parseFallbackToken(token)
}
/**
* Creates helper functions for parsing markdown tokens.
* @returns An object containing helper functions for parsing.
*/
private createParseHelpers(): MarkdownParseHelpers {
return {
parseInline: (tokens: MarkdownToken[]) => this.parseInlineTokens(tokens),
tokenizeInline: (src: string) => this.tokenizeInline(src),
parseChildren: (tokens: MarkdownToken[]) => this.parseTokens(tokens),
parseBlockChildren: (tokens: MarkdownToken[]) => this.parseTokens(tokens, true),
createTextNode: (text: string, marks?: Array<{ type: string; attrs?: any }>) => {
const node = {
type: 'text',
text,
marks: marks || undefined,
}
return node
},
createNode: (type: string, attrs?: any, content?: JSONContent[]) => {
const node = {
type,
attrs: attrs || undefined,
content: content || undefined,
}
if (!attrs || Object.keys(attrs).length === 0) {
delete node.attrs
}
return node
},
applyMark: (markType: string, content: JSONContent[], attrs?: any) => ({
mark: markType,
content,
attrs: attrs && Object.keys(attrs).length > 0 ? attrs : undefined,
}),
}
}
/**
* Escape special regex characters in a string.
*/
private escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
/**
* Parse inline tokens (bold, italic, links, etc.) into text nodes with marks.
* This is the complex part that handles mark nesting and boundaries.
*/
private parseInlineTokens(tokens: MarkdownToken[]): JSONContent[] {
const result: JSONContent[] = []
// Process tokens sequentially using an index so we can lookahead and
// merge split inline HTML fragments like: text / <em> / inner / </em> / text
for (let i = 0; i < tokens.length; i += 1) {
const token = tokens[i]
if (token.type === 'text') {
// Create text node – decode HTML entities so that e.g. `<` displays as `<` in the editor
result.push({
type: 'text',
text: decodeHtmlEntities(token.text || ''),
})
} else if (token.type === 'escape') {
// Backslash-escaped character: produce a text node with the escaped character
result.push({
type: 'text',
text: token.text || '',
})
} else if (token.type === 'html') {
// Handle possible split inline HTML by attempting to detect an
// opening tag and searching forward for a matching closing tag.
const raw = (token.raw ?? token.text ?? '').toString()
// Quick checks for opening vs. closing tag
const isClosing = /^<\/[\s]*[\w-]+/i.test(raw)
const openMatch = raw.match(/^<[\s]*([\w-]+)(\s|>|\/|$)/i)
// oxlint-disable-next-line prefer-string-starts-ends-with
if (!isClosing && openMatch && !/\/>$/.test(raw)) {
// Try to find the corresponding closing html token for this tag
const tagName = openMatch[1]
const escapedTagName = this.escapeRegex(tagName)
const closingRegex = new RegExp(`^<\\/\\s*${escapedTagName}\\b`, 'i')
let foundIndex = -1
// Collect intermediate raw parts to reconstruct full HTML fragment
const parts: string[] = [raw]
for (let j = i + 1; j < tokens.length; j += 1) {
const t = tokens[j]
const tRaw = (t.raw ?? t.text ?? '').toString()
parts.push(tRaw)
if (t.type === 'html' && closingRegex.test(tRaw)) {
foundIndex = j
break
}
}
if (foundIndex !== -1) {
// Merge opening + inner + closing into one html fragment and parse
const mergedRaw = parts.join('')
const mergedToken = {
type: 'html',
raw: mergedRaw,
text: mergedRaw,
block: false,
} as unknown as MarkdownToken
const parsed = this.parseHTMLToken(mergedToken)
if (parsed) {
const normalized = this.normalizeParseResult(parsed as any)
if (Array.isArray(normalized)) {
result.push(...normalized)
} else if (normalized) {
result.push(normalized)
}
}
// Advance i to the closing token
i = foundIndex
continue
}
}
// Fallback: single html token parse
const parsedSingle = this.parseHTMLToken(token)
if (parsedSingle) {
const normalized = this.normalizeParseResult(parsedSingle as any)
if (Array.isArray(normalized)) {
result.push(...normalized)
} else if (normalized) {
result.push(normalized)
}
}
} else if (token.type) {
// Handle inline marks (bold, italic, etc.)
const markHandler = this.getHandlerForToken(token.type)
if (markHandler && markHandler.parseMarkdown) {
const helpers = this.createParseHelpers()
const parsed = markHandler.parseMarkdown(token, helpers)
if (this.isMarkResult(parsed)) {
// This is a mark result - apply the mark to the content
const markedContent = this.applyMarkToContent(parsed.mark, parsed.content, parsed.attrs)
result.push(...markedContent)
} else {
// Regular inline node
const normalized = this.normalizeParseResult(parsed)
if (Array.isArray(normalized)) {
result.push(...normalized)
} else if (normalized) {
result.push(normalized)
}
}
} else if (token.tokens) {
// Fallback: try to parse children if they exist
result.push(...this.parseInlineTokens(token.tokens))
}
}
}
// Merge adjacent text nodes with the same marks. The marked tokenizer may
// produce adjacent inline tokens (e.g. escape + text + escape) that each
// become separate text nodes. Merging them keeps the output compact and
// consistent with ProseMirror's expectation that contiguous styled text
// lives in a single text node.
for (let i = result.length - 1; i > 0; i -= 1) {
const current = result[i]
const previous = result[i - 1]
if (current.type === 'text' && previous.type === 'text') {
const currentMarks = current.marks || []
const previousMarks = previous.marks || []
if (marksEqual(currentMarks, previousMarks)) {
previous.text = (previous.text || '') + (current.text || '')
result.splice(i, 1)
}
}
}
return result
}
/**
* Apply a mark to content nodes.
*/
private applyMarkToContent(markType: string, content: JSONContent[], attrs?: any): JSONContent[] {
return content.map(node => {
if (node.type === 'text') {
// Add the mark to existing marks or create new marks array
const existingMarks = node.marks || []
const newMark = attrs ? { type: markType, attrs } : { type: markType }
return {
...node,
marks: [...existingMarks, newMark],
}
}
// For non-text nodes, recursively apply to content
return {
...node,
content: node.content ? this.applyMarkToContent(markType, node.content, attrs) : undefined,
}
})
} /**
* Check if a parse result represents a mark to be applied.
*/
private isMarkResult(
result: any,
): result is { mark: string; content: JSONContent[]; attrs?: any } {
return result && typeof result === 'object' && 'mark' in result
}
/**
* Normalize parse results to ensure they're valid JSONContent.
*/
private normalizeParseResult(result: MarkdownParseResult): JSONContent | JSONContent[] | null {
if (!result) {
return null
}
if (this.isMarkResult(result)) {
// This shouldn't happen at the top level, but handle it gracefully
return result.content
}
return result as JSONContent | JSONContent[]
}
/**
* Fallback parsing for common tokens when no specific handler is registered.
*/
private parseFallbackToken(
token: MarkdownToken,
parseImplicitEmptyParagraphs = false,
): JSONContent | JSONContent[] | null {
switch (token.type) {
case 'paragraph':
return {
type: 'paragraph',
content: token.tokens ? this.parseInlineTokens(token.tokens) : [],
}
case 'heading':
return {
type: 'heading',
attrs: { level: token.depth || 1 },
content: token.tokens ? this.parseInlineTokens(token.tokens) : [],
}
case 'text':
return {
type: 'text',
text: decodeHtmlEntities(token.text || ''),
}
case 'html':
// Parse HTML using extensions' parseHTML methods
return this.parseHTMLToken(token)
// handle Marked escape tokens as literal text (e.g. backslash-escaped characters)
case 'escape':
return {
type: 'text',
text: token.text || '',
}
case 'space':
return null
default:
// Unknown token type - try to parse children if they exist
if (token.tokens) {
return this.parseTokens(token.tokens, parseImplicitEmptyParagraphs)
}
return null
}
}
/**
* Parse an HTML token from marked into JSONContent using the registered
* extensions' `parseHTML` rules. Falls back to literal text when the HTML
* has nothing for the schema to keep.
*
* @param token Marked HTML token (block or inline).
* @example
* parseHTMLToken({ type: 'html', raw: '<em>hi</em>', block: false })
* // → text node with an italic mark
*/
private parseHTMLToken(token: MarkdownToken): JSONContent | JSONContent[] | null {
const html = token.text || token.raw || ''
if (!html.trim()) {
return null
}
// If the HTML would parse to nothing meaningful, keep the original
// characters as literal text instead of dropping them.
if (this.isUnrecognizedHtml(html)) {
return this.htmlAsLiteralText(html, !!token.block)
}
// generateJSON requires window.DOMParser – treat recognized HTML as literal on the server
if (typeof window === 'undefined' || typeof window.DOMParser === 'undefined') {
return this.htmlAsLiteralText(html, !!token.block)
}
// Use generateJSON to parse the HTML using extensions' parseHTML rules
try {
const parsed = generateJSON(html, this.baseExtensions)
// If the result is a doc node, extract its content
if (parsed.type === 'doc' && parsed.content) {
// For block-level HTML, return the content array
if (token.block) {
return parsed.content
}
// For inline HTML, we need to flatten the content appropriately
// If there's only one paragraph with content, unwrap it
if (
parsed.content.length === 1 &&
parsed.content[0].type === 'paragraph' &&
parsed.content[0].content
) {
return parsed.content[0].content
}
return parsed.content
}
return parsed as JSONContent
} catch (error) {
throw new Error(`Failed to parse HTML in markdown: ${error}`)
}
}
/**
* Returns true when the HTML contains a tag that is neither a standard
* HTML/SVG element nor declared in a registered extension's parseDOM rules.
*
* Recognized but empty elements such as `<em></em>` or `<span></span>`,
* and hyphenated custom elements like `<my-mention>`, are not considered
* unrecognized.