@blocknote/core 0.50.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/blocknote.cjs +1 -1
  2. package/dist/blocknote.js +4 -4
  3. package/dist/{blocks-UU7EM-QM.js → blocks-D0lMxErU.js} +397 -368
  4. package/dist/blocks-D0lMxErU.js.map +1 -0
  5. package/dist/blocks-KyMOxPT3.cjs +11 -0
  6. package/dist/blocks-KyMOxPT3.cjs.map +1 -0
  7. package/dist/blocks.cjs +1 -1
  8. package/dist/blocks.js +2 -2
  9. package/dist/{extensions-CkLT--Nc.js → extensions-CQFfm5f5.js} +619 -353
  10. package/dist/extensions-CQFfm5f5.js.map +1 -0
  11. package/dist/extensions-Cuw3zOdC.cjs +52 -0
  12. package/dist/extensions-Cuw3zOdC.cjs.map +1 -0
  13. package/dist/extensions.cjs +1 -1
  14. package/dist/extensions.js +3 -3
  15. package/dist/locales.cjs +1 -1
  16. package/dist/locales.cjs.map +1 -1
  17. package/dist/locales.js +1 -1
  18. package/dist/locales.js.map +1 -1
  19. package/dist/{src-SVFpMAWE.js → src-DK_8q1j5.js} +1070 -564
  20. package/dist/src-DK_8q1j5.js.map +1 -0
  21. package/dist/src-_83jmA7A.cjs +21 -0
  22. package/dist/src-_83jmA7A.cjs.map +1 -0
  23. package/dist/style.css +1 -1
  24. package/dist/webpack-stats.json +1 -1
  25. package/dist/yjs.cjs +1 -1
  26. package/dist/yjs.js +8 -8
  27. package/package.json +1 -13
  28. package/src/api/blockManipulation/commands/insertBlocks/__snapshots__/insertBlocks.test.ts.snap +7 -7
  29. package/src/api/blockManipulation/commands/insertBlocks/insertBlocks.ts +5 -3
  30. package/src/api/blockManipulation/commands/mergeBlocks/__snapshots__/mergeBlocks.test.ts.snap +5 -5
  31. package/src/api/blockManipulation/commands/moveBlocks/__snapshots__/moveBlocks.test.ts.snap +2550 -291
  32. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.test.ts +83 -2
  33. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.ts +103 -42
  34. package/src/api/blockManipulation/commands/nestBlock/__snapshots__/nestBlock.test.ts.snap +0 -143
  35. package/src/api/blockManipulation/commands/replaceBlocks/__snapshots__/replaceBlocks.test.ts.snap +12 -12
  36. package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.ts +5 -3
  37. package/src/api/blockManipulation/commands/splitBlock/__snapshots__/splitBlock.test.ts.snap +6 -6
  38. package/src/api/blockManipulation/commands/updateBlock/__snapshots__/updateBlock.test.ts.snap +22 -22
  39. package/src/api/blockManipulation/commands/updateBlock/updateBlock.ts +12 -8
  40. package/src/api/blockManipulation/setupTestEnv.ts +1 -1
  41. package/src/api/clipboard/fromClipboard/handleVSCodePaste.ts +2 -6
  42. package/src/api/clipboard/fromClipboard/pasteExtension.ts +7 -2
  43. package/src/api/exporters/markdown/htmlToMarkdown.ts +813 -0
  44. package/src/api/exporters/markdown/markdownExporter.ts +2 -21
  45. package/src/api/nodeConversions/blockToNode.ts +3 -2
  46. package/src/api/parsers/html/util/__snapshots__/nestedLists.test.ts.snap +122 -107
  47. package/src/api/parsers/html/util/nestedLists.test.ts +1 -12
  48. package/src/api/parsers/markdown/markdownToHtml.ts +1194 -0
  49. package/src/api/parsers/markdown/parseMarkdown.ts +2 -101
  50. package/src/blocks/Audio/block.ts +1 -4
  51. package/src/blocks/Code/block.test.ts +258 -0
  52. package/src/blocks/File/block.ts +1 -4
  53. package/src/blocks/File/helpers/render/createFileBlockWrapper.ts +7 -2
  54. package/src/blocks/Image/block.ts +9 -6
  55. package/src/blocks/ListItem/BulletListItem/block.ts +7 -4
  56. package/src/blocks/ListItem/NumberedListItem/IndexingPlugin.ts +3 -4
  57. package/src/blocks/Video/block.ts +4 -5
  58. package/src/blocks/Video/parseVideoElement.ts +2 -1
  59. package/src/editor/Block.css +8 -0
  60. package/src/editor/BlockNoteEditor.test.ts +10 -4
  61. package/src/editor/BlockNoteEditor.ts +30 -13
  62. package/src/editor/managers/BlockManager.ts +10 -6
  63. package/src/editor/managers/ExtensionManager/index.ts +80 -25
  64. package/src/editor/performance.test.ts +2 -2
  65. package/src/editor/transformPasted.test.ts +295 -0
  66. package/src/editor/transformPasted.ts +77 -0
  67. package/src/extensions/Collaboration/__snapshots__/fork-yjs-snap-editor-forked.json +1 -12
  68. package/src/extensions/Collaboration/__snapshots__/fork-yjs-snap-editor.json +0 -11
  69. package/src/extensions/Collaboration/__snapshots__/fork-yjs-snap-forked.html +1 -1
  70. package/src/extensions/Collaboration/__snapshots__/fork-yjs-snap.html +1 -1
  71. package/src/extensions/SideMenu/dragging.ts +7 -10
  72. package/src/extensions/SuggestionMenu/getDefaultSlashMenuItems.ts +21 -0
  73. package/src/extensions/TrailingNode/TrailingNode.ts +124 -65
  74. package/src/i18n/locales/fr.ts +1 -1
  75. package/types/src/api/blockManipulation/commands/moveBlocks/moveBlocks.d.ts +13 -2
  76. package/types/src/api/clipboard/fromClipboard/handleVSCodePaste.d.ts +1 -1
  77. package/types/src/api/exporters/markdown/htmlToMarkdown.d.ts +11 -0
  78. package/types/src/api/parsers/markdown/markdownToHtml.d.ts +5 -0
  79. package/types/src/blocks/Code/block.test.d.ts +1 -0
  80. package/types/src/blocks/Video/block.d.ts +2 -0
  81. package/types/src/blocks/Video/parseVideoElement.d.ts +1 -0
  82. package/types/src/editor/BlockNoteEditor.d.ts +20 -6
  83. package/types/src/editor/managers/BlockManager.d.ts +8 -4
  84. package/types/src/editor/transformPasted.test.d.ts +1 -0
  85. package/types/src/extensions/TrailingNode/TrailingNode.d.ts +8 -3
  86. package/dist/blocks-BFnTypT-.cjs +0 -11
  87. package/dist/blocks-BFnTypT-.cjs.map +0 -1
  88. package/dist/blocks-UU7EM-QM.js.map +0 -1
  89. package/dist/extensions-CYsFi5Is.cjs +0 -2
  90. package/dist/extensions-CYsFi5Is.cjs.map +0 -1
  91. package/dist/extensions-CkLT--Nc.js.map +0 -1
  92. package/dist/src-DsJ6yzs9.cjs +0 -5
  93. package/dist/src-DsJ6yzs9.cjs.map +0 -1
  94. package/dist/src-SVFpMAWE.js.map +0 -1
  95. package/src/api/exporters/markdown/util/addSpacesToCheckboxesRehypePlugin.ts +0 -42
  96. package/src/api/exporters/markdown/util/convertVideoToMarkdownRehypePlugin.ts +0 -19
  97. package/src/api/exporters/markdown/util/removeUnderlinesRehypePlugin.ts +0 -39
  98. package/types/src/api/exporters/markdown/util/addSpacesToCheckboxesRehypePlugin.d.ts +0 -7
  99. package/types/src/api/exporters/markdown/util/convertVideoToMarkdownRehypePlugin.d.ts +0 -2
  100. package/types/src/api/exporters/markdown/util/removeUnderlinesRehypePlugin.d.ts +0 -6
@@ -0,0 +1,1194 @@
1
+ import { isVideoUrl } from "../../../util/string.js";
2
+
3
+ /**
4
+ * Custom markdown-to-HTML converter for BlockNote.
5
+ * Replaces the unified/remark/rehype pipeline with a direct, minimal implementation
6
+ * that handles exactly the markdown features BlockNote needs.
7
+ */
8
+
9
+ // ─── HTML Escaping ───────────────────────────────────────────────────────────
10
+
11
+ function escapeHtml(str: string): string {
12
+ return str
13
+ .replace(/&/g, "&")
14
+ .replace(/</g, "&lt;")
15
+ .replace(/>/g, "&gt;")
16
+ .replace(/"/g, "&quot;");
17
+ }
18
+
19
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
20
+
21
+ function isAlphanumeric(char: string | undefined): boolean {
22
+ if (!char) {
23
+ return false;
24
+ }
25
+ return /\w/.test(char);
26
+ }
27
+
28
+ /**
29
+ * Returns true when an underscore delimiter at position `i` is "intraword",
30
+ * meaning the characters on both sides are alphanumeric (e.g. `snake_case`).
31
+ * In that case the underscore should NOT be treated as emphasis per CommonMark.
32
+ */
33
+ function isIntraword(text: string, i: number, delimLen: number): boolean {
34
+ const before = i > 0 ? text[i - 1] : undefined;
35
+ const after =
36
+ i + delimLen < text.length ? text[i + delimLen] : undefined;
37
+ return isAlphanumeric(before) && isAlphanumeric(after);
38
+ }
39
+
40
+ // ─── Inline Parser ───────────────────────────────────────────────────────────
41
+
42
+ type InlineTokenizer = (
43
+ text: string,
44
+ i: number
45
+ ) => { html: string; end: number } | null;
46
+
47
+ function tryBackslashEscape(
48
+ text: string,
49
+ i: number
50
+ ): { html: string; end: number } | null {
51
+ if (text[i] !== "\\" || i + 1 >= text.length) {return null;}
52
+ const next = text[i + 1];
53
+ // Hard line break: backslash at end of line
54
+ if (next === "\n") {
55
+ return { html: "<br>\n", end: i + 2 };
56
+ }
57
+ // Escapable characters
58
+ if ("\\`*_{}[]()#+-.!~|>".includes(next)) {
59
+ return { html: escapeHtml(next), end: i + 2 };
60
+ }
61
+ return null;
62
+ }
63
+
64
+ function tryInlineCode(
65
+ text: string,
66
+ i: number
67
+ ): { html: string; end: number } | null {
68
+ if (text[i] !== "`") {return null;}
69
+ return parseInlineCode(text, i);
70
+ }
71
+
72
+ function tryImage(
73
+ text: string,
74
+ i: number
75
+ ): { html: string; end: number } | null {
76
+ if (text[i] !== "!" || text[i + 1] !== "[") {return null;}
77
+ return parseImage(text, i);
78
+ }
79
+
80
+ function tryLink(
81
+ text: string,
82
+ i: number
83
+ ): { html: string; end: number } | null {
84
+ if (text[i] !== "[") {return null;}
85
+ return parseLink(text, i);
86
+ }
87
+
88
+ function tryStrikethrough(
89
+ text: string,
90
+ i: number
91
+ ): { html: string; end: number } | null {
92
+ if (text[i] !== "~" || text[i + 1] !== "~") {return null;}
93
+ return parseDelimited(text, i, "~~", "<del>", "</del>");
94
+ }
95
+
96
+ function tryBoldItalic(
97
+ text: string,
98
+ i: number
99
+ ): { html: string; end: number } | null {
100
+ if (
101
+ (text[i] === "*" && text[i + 1] === "*" && text[i + 2] === "*") ||
102
+ (text[i] === "_" &&
103
+ text[i + 1] === "_" &&
104
+ text[i + 2] === "_" &&
105
+ !isIntraword(text, i, 3))
106
+ ) {
107
+ const delimiter = text.substring(i, i + 3);
108
+ return parseDelimited(text, i, delimiter, "<strong><em>", "</em></strong>");
109
+ }
110
+ return null;
111
+ }
112
+
113
+ function tryBold(
114
+ text: string,
115
+ i: number
116
+ ): { html: string; end: number } | null {
117
+ if (
118
+ (text[i] === "*" && text[i + 1] === "*") ||
119
+ (text[i] === "_" && text[i + 1] === "_" && !isIntraword(text, i, 2))
120
+ ) {
121
+ const delimiter = text.substring(i, i + 2);
122
+ return parseDelimited(text, i, delimiter, "<strong>", "</strong>");
123
+ }
124
+ return null;
125
+ }
126
+
127
+ function tryItalic(
128
+ text: string,
129
+ i: number
130
+ ): { html: string; end: number } | null {
131
+ if (text[i] === "*" || (text[i] === "_" && !isIntraword(text, i, 1))) {
132
+ return parseDelimited(text, i, text[i], "<em>", "</em>");
133
+ }
134
+ return null;
135
+ }
136
+
137
+ function trySoftBreak(
138
+ text: string,
139
+ i: number
140
+ ): { html: string; end: number } | null {
141
+ if (text[i] === "\n") {
142
+ return { html: "<br>\n", end: i + 1 };
143
+ }
144
+ return null;
145
+ }
146
+
147
+ // Inline raw HTML: pass through tags, comments, CDATA, processing
148
+ // instructions, and declarations verbatim so authors can mix HTML into
149
+ // markdown (e.g. `text <em>foo</em> more`). Anything that doesn't match
150
+ // these shapes falls through and gets HTML-escaped as plain text.
151
+ const INLINE_HTML_TAG_RE =
152
+ /^<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s+[a-zA-Z_:][a-zA-Z0-9_.:-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?>/;
153
+ const HTML_COMMENT_RE = /^<!--[\s\S]*?-->/;
154
+ const HTML_CDATA_RE = /^<!\[CDATA\[[\s\S]*?\]\]>/;
155
+ const HTML_PI_RE = /^<\?[\s\S]*?\?>/;
156
+ const HTML_DECL_RE = /^<![A-Za-z][\s\S]*?>/;
157
+
158
+ function tryInlineHtml(
159
+ text: string,
160
+ i: number
161
+ ): { html: string; end: number } | null {
162
+ if (text[i] !== "<") {return null;}
163
+ const rest = text.substring(i);
164
+ for (const re of [
165
+ HTML_COMMENT_RE,
166
+ HTML_CDATA_RE,
167
+ HTML_PI_RE,
168
+ HTML_DECL_RE,
169
+ INLINE_HTML_TAG_RE,
170
+ ]) {
171
+ const m = rest.match(re);
172
+ if (m) {
173
+ return { html: m[0], end: i + m[0].length };
174
+ }
175
+ }
176
+ return null;
177
+ }
178
+
179
+ /** Characters that can start an inline syntax token. */
180
+ const SPECIAL_CHARS = new Set("\\`![~*_\n<");
181
+
182
+ /**
183
+ * Ordered array of inline tokenizers, tried in priority order.
184
+ * The first match wins.
185
+ */
186
+ const inlineTokenizers: InlineTokenizer[] = [
187
+ tryBackslashEscape,
188
+ tryInlineCode,
189
+ tryImage,
190
+ tryLink,
191
+ tryStrikethrough,
192
+ tryBoldItalic, // *** / ___
193
+ tryBold, // ** / __
194
+ tryItalic, // * / _
195
+ tryInlineHtml,
196
+ trySoftBreak,
197
+ ];
198
+
199
+ /**
200
+ * Parse inline markdown syntax and return HTML.
201
+ * Handles: bold, italic, bold+italic, strikethrough, inline code,
202
+ * links, images (with video detection), hard line breaks, backslash escapes.
203
+ */
204
+ function parseInline(text: string): string {
205
+ let result = "";
206
+ let i = 0;
207
+
208
+ while (i < text.length) {
209
+ // Hard line break: 2+ trailing spaces immediately before a newline.
210
+ // (The other hard-break form, backslash + newline, is handled by
211
+ // tryBackslashEscape.) Strip the trailing spaces from the accumulated
212
+ // result before emitting the <br>.
213
+ if (
214
+ text[i] === "\n" &&
215
+ i >= 2 &&
216
+ text[i - 1] === " " &&
217
+ text[i - 2] === " "
218
+ ) {
219
+ result = result.replace(/ +$/, "");
220
+ result += "<br>\n";
221
+ i++;
222
+ continue;
223
+ }
224
+
225
+ // Try each tokenizer in priority order
226
+ let matched = false;
227
+ if (SPECIAL_CHARS.has(text[i])) {
228
+ for (const tokenizer of inlineTokenizers) {
229
+ const r = tokenizer(text, i);
230
+ if (r) {
231
+ result += r.html;
232
+ i = r.end;
233
+ matched = true;
234
+ break;
235
+ }
236
+ }
237
+ }
238
+
239
+ if (!matched) {
240
+ // Batch consecutive plain-text characters and escape once
241
+ const runStart = i;
242
+ i++;
243
+ while (i < text.length && !SPECIAL_CHARS.has(text[i])) {
244
+ i++;
245
+ }
246
+ result += escapeHtml(text.substring(runStart, i));
247
+ }
248
+ }
249
+
250
+ return result;
251
+ }
252
+
253
+ function parseInlineCode(
254
+ text: string,
255
+ start: number
256
+ ): { html: string; end: number } | null {
257
+ // Count opening backticks
258
+ let openCount = 0;
259
+ let i = start;
260
+ while (i < text.length && text[i] === "`") {
261
+ openCount++;
262
+ i++;
263
+ }
264
+
265
+ // Find matching closing backticks
266
+ let j = i;
267
+ while (j < text.length) {
268
+ if (text[j] === "`") {
269
+ let closeCount = 0;
270
+ const closeStart = j;
271
+ while (j < text.length && text[j] === "`") {
272
+ closeCount++;
273
+ j++;
274
+ }
275
+ if (closeCount === openCount) {
276
+ let code = text.substring(i, closeStart);
277
+ // Per CommonMark: line endings inside a code span are converted to
278
+ // single spaces, then if the result starts AND ends with a space and
279
+ // is not all-spaces, one leading + trailing space is stripped (so
280
+ // `` ` `foo` ` `` is `<code>`foo`</code>`).
281
+ code = code.replace(/\n/g, " ");
282
+ if (
283
+ code.length >= 2 &&
284
+ code[0] === " " &&
285
+ code[code.length - 1] === " " &&
286
+ /[^ ]/.test(code)
287
+ ) {
288
+ code = code.substring(1, code.length - 1);
289
+ }
290
+ return {
291
+ html: `<code>${escapeHtml(code)}</code>`,
292
+ end: j,
293
+ };
294
+ }
295
+ } else {
296
+ j++;
297
+ }
298
+ }
299
+ return null;
300
+ }
301
+
302
+ function parseImage(
303
+ text: string,
304
+ start: number
305
+ ): { html: string; end: number } | null {
306
+ // ![alt](url) or ![alt](url "title")
307
+ // Use balanced bracket matching to handle nested/escaped brackets in alt text
308
+ const altEnd = findClosingBracket(text, start + 1);
309
+ if (altEnd === -1) {return null;}
310
+ const altStart = start + 2; // after ![
311
+
312
+ if (text[altEnd + 1] !== "(") {return null;}
313
+
314
+ const urlStart = altEnd + 2;
315
+ const parenEnd = findClosingParen(text, urlStart - 1);
316
+ if (parenEnd === -1) {return null;}
317
+
318
+ const alt = text.substring(altStart, altEnd);
319
+ const { url, title } = parseDestinationAndTitle(
320
+ text.substring(urlStart, parenEnd),
321
+ );
322
+
323
+ if (isVideoUrl(url)) {
324
+ // Use the alt text as the video's display name (falling back to the
325
+ // title) so a video link written with the standard `![name](url)` form
326
+ // round-trips into BlockNote's video block. Captioned videos go through
327
+ // raw `<figure>` HTML instead, see htmlToMarkdown.serializeMediaFigure.
328
+ const name = alt || title;
329
+ return {
330
+ html: `<video src="${escapeHtml(url)}"${name ? ` data-name="${escapeHtml(name)}"` : ""} data-url="${escapeHtml(url)}" controls></video>`,
331
+ end: parenEnd + 1,
332
+ };
333
+ }
334
+
335
+ const titleAttr =
336
+ title !== undefined ? ` title="${escapeHtml(title)}"` : "";
337
+ return {
338
+ html: `<img src="${escapeHtml(url)}" alt="${escapeHtml(alt)}"${titleAttr}>`,
339
+ end: parenEnd + 1,
340
+ };
341
+ }
342
+
343
+ function parseLink(
344
+ text: string,
345
+ start: number
346
+ ): { html: string; end: number } | null {
347
+ // [text](url)
348
+ const textStart = start + 1;
349
+ const textEnd = findClosingBracket(text, start);
350
+ if (textEnd === -1) {return null;}
351
+
352
+ if (text[textEnd + 1] !== "(") {return null;}
353
+
354
+ const urlStart = textEnd + 2;
355
+ const parenEnd = findClosingParen(text, textEnd + 1);
356
+ if (parenEnd === -1) {return null;}
357
+
358
+ const linkText = text.substring(textStart, textEnd);
359
+ const { url, title } = parseDestinationAndTitle(
360
+ text.substring(urlStart, parenEnd),
361
+ );
362
+
363
+ const titleAttr =
364
+ title !== undefined ? ` title="${escapeHtml(title)}"` : "";
365
+ return {
366
+ html: `<a href="${escapeHtml(url)}"${titleAttr}>${parseInline(linkText)}</a>`,
367
+ end: parenEnd + 1,
368
+ };
369
+ }
370
+
371
+ function findClosingBracket(text: string, openPos: number): number {
372
+ let depth = 0;
373
+ for (let i = openPos; i < text.length; i++) {
374
+ if (text[i] === "\\" && i + 1 < text.length) {
375
+ i++; // skip escaped
376
+ continue;
377
+ }
378
+ if (text[i] === "[") {depth++;}
379
+ if (text[i] === "]") {
380
+ depth--;
381
+ if (depth === 0) {return i;}
382
+ }
383
+ }
384
+ return -1;
385
+ }
386
+
387
+ function findClosingParen(text: string, openPos: number): number {
388
+ let depth = 0;
389
+ for (let i = openPos; i < text.length; i++) {
390
+ if (text[i] === "\\" && i + 1 < text.length) {
391
+ i++;
392
+ continue;
393
+ }
394
+ if (text[i] === "(") {depth++;}
395
+ if (text[i] === ")") {
396
+ depth--;
397
+ if (depth === 0) {return i;}
398
+ }
399
+ }
400
+ return -1;
401
+ }
402
+
403
+ /**
404
+ * Parse the inside of `(...)` from a link/image (the URL and optional title).
405
+ * Handles three URL forms:
406
+ * - bare: `/uri` or `/uri "title"`
407
+ * - angle-bracket: `<url>` or `<url> "title"` (brackets are stripped)
408
+ * And three title-quote forms: `"..."`, `'...'`, `(...)`.
409
+ */
410
+ function parseDestinationAndTitle(raw: string): {
411
+ url: string;
412
+ title?: string;
413
+ } {
414
+ raw = raw.trim();
415
+ let url: string;
416
+ let rest: string;
417
+
418
+ if (raw.startsWith("<")) {
419
+ const close = raw.indexOf(">");
420
+ if (close === -1) {
421
+ // Unmatched `<` — treat the whole thing as the URL minus the `<`.
422
+ url = raw.substring(1);
423
+ rest = "";
424
+ } else {
425
+ url = raw.substring(1, close);
426
+ rest = raw.substring(close + 1).trim();
427
+ }
428
+ } else {
429
+ // Split at first unescaped whitespace.
430
+ let split = raw.length;
431
+ for (let i = 0; i < raw.length; i++) {
432
+ if (raw[i] === "\\" && i + 1 < raw.length) {
433
+ i++;
434
+ continue;
435
+ }
436
+ if (raw[i] === " " || raw[i] === "\t" || raw[i] === "\n") {
437
+ split = i;
438
+ break;
439
+ }
440
+ }
441
+ url = raw.substring(0, split);
442
+ rest = raw.substring(split).trim();
443
+ }
444
+
445
+ let title: string | undefined;
446
+ if (rest.length > 0) {
447
+ const titleMatch = rest.match(/^"([^"]*)"$|^'([^']*)'$|^\(([^)]*)\)$/);
448
+ if (titleMatch) {
449
+ title = titleMatch[1] ?? titleMatch[2] ?? titleMatch[3];
450
+ }
451
+ }
452
+
453
+ return { url, title };
454
+ }
455
+
456
+ function parseDelimited(
457
+ text: string,
458
+ start: number,
459
+ delimiter: string,
460
+ openTag: string,
461
+ closeTag: string
462
+ ): { html: string; end: number } | null {
463
+ const len = delimiter.length;
464
+ const afterOpen = start + len;
465
+
466
+ if (afterOpen >= text.length) {return null;}
467
+
468
+ // Opening delimiter must not be followed by whitespace
469
+ if (text[afterOpen] === " " || text[afterOpen] === "\t") {return null;}
470
+
471
+ // Find closing delimiter
472
+ let j = afterOpen;
473
+ while (j < text.length) {
474
+ // Skip escaped characters
475
+ if (text[j] === "\\" && j + 1 < text.length) {
476
+ j += 2;
477
+ continue;
478
+ }
479
+
480
+ if (text.substring(j, j + len) === delimiter) {
481
+ // Closing delimiter must not be preceded by whitespace
482
+ if (text[j - 1] === " " || text[j - 1] === "\t") {
483
+ j++;
484
+ continue;
485
+ }
486
+
487
+ // For single-char delimiters, don't accept closer if it's part of a
488
+ // multi-char run (e.g., don't treat the * in ** as italic closer)
489
+ if (
490
+ len === 1 &&
491
+ ((j > 0 && text[j - 1] === delimiter[0] && !(j >= 2 && text[j - 2] === "\\")) ||
492
+ (j + len < text.length && text[j + len] === delimiter[0]))
493
+ ) {
494
+ j++;
495
+ continue;
496
+ }
497
+
498
+ const inner = text.substring(afterOpen, j);
499
+ if (inner.length === 0) {
500
+ j++;
501
+ continue;
502
+ }
503
+
504
+ return {
505
+ html: openTag + parseInline(inner) + closeTag,
506
+ end: j + len,
507
+ };
508
+ }
509
+ j++;
510
+ }
511
+
512
+ return null;
513
+ }
514
+
515
+ // ─── Block-Level Types ───────────────────────────────────────────────────────
516
+
517
+ interface BlockToken {
518
+ type: string;
519
+ }
520
+
521
+ interface HeadingToken extends BlockToken {
522
+ type: "heading";
523
+ level: number;
524
+ content: string;
525
+ }
526
+
527
+ interface ParagraphToken extends BlockToken {
528
+ type: "paragraph";
529
+ content: string;
530
+ }
531
+
532
+ interface CodeBlockToken extends BlockToken {
533
+ type: "codeBlock";
534
+ language: string;
535
+ code: string;
536
+ }
537
+
538
+ interface BlockquoteToken extends BlockToken {
539
+ type: "blockquote";
540
+ content: string;
541
+ }
542
+
543
+ interface HorizontalRuleToken extends BlockToken {
544
+ type: "hr";
545
+ }
546
+
547
+ interface ListItemToken extends BlockToken {
548
+ type: "listItem";
549
+ listType: "bullet" | "ordered" | "task";
550
+ indent: number;
551
+ content: string;
552
+ start?: number; // for ordered lists
553
+ checked?: boolean; // for task lists
554
+ childContent?: string; // recursively parsed content within this item
555
+ }
556
+
557
+ interface TableToken extends BlockToken {
558
+ type: "table";
559
+ headers: string[];
560
+ rows: string[][];
561
+ alignments: ("left" | "center" | "right" | null)[];
562
+ }
563
+
564
+ interface RawHtmlToken extends BlockToken {
565
+ type: "rawHtml";
566
+ content: string;
567
+ }
568
+
569
+ type Token =
570
+ | HeadingToken
571
+ | ParagraphToken
572
+ | CodeBlockToken
573
+ | BlockquoteToken
574
+ | HorizontalRuleToken
575
+ | ListItemToken
576
+ | TableToken
577
+ | RawHtmlToken;
578
+
579
+ /**
580
+ * HTML block-level tag names (from the CommonMark type-6 list, plus `audio`
581
+ * which BlockNote serializes as raw HTML since markdown has no shorthand
582
+ * for it). When a line starts with `<` followed by one of these tag names,
583
+ * the run of non-blank lines is emitted verbatim as raw HTML rather than
584
+ * wrapped in a paragraph.
585
+ */
586
+ const HTML_BLOCK_TAGS = new Set([
587
+ "address", "article", "aside", "audio", "base", "basefont", "blockquote",
588
+ "body", "caption", "center", "col", "colgroup", "dd", "details", "dialog",
589
+ "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer",
590
+ "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head",
591
+ "header", "hr", "html", "iframe", "legend", "li", "link", "main", "menu",
592
+ "menuitem", "nav", "noframes", "ol", "optgroup", "option", "p", "param",
593
+ "section", "source", "summary", "table", "tbody", "td", "tfoot", "th",
594
+ "thead", "title", "tr", "track", "ul",
595
+ ]);
596
+
597
+ function isHtmlBlockStart(line: string): boolean {
598
+ // <!-- ..., <?..., <![CDATA[..., <!DOCTYPE, etc.
599
+ if (/^ {0,3}<(!--|\?|![A-Za-z]|!\[CDATA\[)/.test(line)) {
600
+ return true;
601
+ }
602
+ const m = line.match(/^ {0,3}<\/?([a-zA-Z][a-zA-Z0-9-]*)(?:\s|\/?>|$)/);
603
+ if (!m) {return false;}
604
+ return HTML_BLOCK_TAGS.has(m[1].toLowerCase());
605
+ }
606
+
607
+ // ─── Block-Level Tokenizer ──────────────────────────────────────────────────
608
+
609
+ function tokenize(markdown: string): Token[] {
610
+ const lines = markdown.split("\n");
611
+ const tokens: Token[] = [];
612
+ let i = 0;
613
+ let prevLineWasBlank = true; // treat start of document as after blank
614
+
615
+ while (i < lines.length) {
616
+ const line = lines[i];
617
+
618
+ // Blank line — skip
619
+ if (line.trim() === "") {
620
+ prevLineWasBlank = true;
621
+ i++;
622
+ continue;
623
+ }
624
+
625
+ // Fenced code block (0-3 leading spaces allowed per CommonMark)
626
+ const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
627
+ if (fenceMatch) {
628
+ const fence = fenceMatch[1];
629
+ const fenceChar = fence[0];
630
+ const fenceLen = fence.length;
631
+ const language = fenceMatch[2].trim();
632
+ const codeLines: string[] = [];
633
+ i++;
634
+ while (i < lines.length) {
635
+ const closingMatch = lines[i].match(
636
+ new RegExp(`^ {0,3}${fenceChar}{${fenceLen},}\\s*$`)
637
+ );
638
+ if (closingMatch) {
639
+ i++;
640
+ break;
641
+ }
642
+ codeLines.push(lines[i]);
643
+ i++;
644
+ }
645
+ tokens.push({
646
+ type: "codeBlock",
647
+ language: language || "",
648
+ code: codeLines.join("\n"),
649
+ });
650
+ prevLineWasBlank = false;
651
+ continue;
652
+ }
653
+
654
+ // ATX Heading.
655
+ // - Closing `#` sequence requires a preceding space (so `### foo###`
656
+ // keeps the trailing #s as text, while `### foo ###` strips them).
657
+ // - Trailing whitespace is always stripped from the heading content.
658
+ const headingMatch = line.match(/^(#{1,6})\s+(.+?)(?:\s+#+\s*|\s*)$/);
659
+ if (headingMatch) {
660
+ tokens.push({
661
+ type: "heading",
662
+ level: headingMatch[1].length,
663
+ content: headingMatch[2],
664
+ });
665
+ prevLineWasBlank = false;
666
+ i++;
667
+ continue;
668
+ }
669
+
670
+ // Horizontal rule: ---, ***, ___ (3+ chars, optionally with spaces)
671
+ if (/^(\s{0,3})([-*_])\s*(\2\s*){2,}$/.test(line)) {
672
+ // Setext H2: --- immediately after a paragraph (no blank line between)
673
+ const prevToken = tokens[tokens.length - 1];
674
+ if (
675
+ !prevLineWasBlank &&
676
+ line.trim().match(/^-+$/) &&
677
+ prevToken &&
678
+ prevToken.type === "paragraph"
679
+ ) {
680
+ const para = prevToken as ParagraphToken;
681
+ tokens[tokens.length - 1] = {
682
+ type: "heading",
683
+ level: 2,
684
+ content: para.content,
685
+ };
686
+ prevLineWasBlank = false;
687
+ i++;
688
+ continue;
689
+ }
690
+ tokens.push({ type: "hr" });
691
+ prevLineWasBlank = false;
692
+ i++;
693
+ continue;
694
+ }
695
+
696
+ // Setext heading detection: check if next line is === or ---
697
+ if (i + 1 < lines.length) {
698
+ const nextLine = lines[i + 1];
699
+ if (/^={1,}\s*$/.test(nextLine) && line.trim().length > 0) {
700
+ tokens.push({
701
+ type: "heading",
702
+ level: 1,
703
+ content: line.trim(),
704
+ });
705
+ prevLineWasBlank = false;
706
+ i += 2;
707
+ continue;
708
+ }
709
+ // Setext H2 --- handled in HR section above
710
+ }
711
+
712
+ // Table: detect by looking for separator row
713
+ const tableResult = tryParseTable(lines, i);
714
+ if (tableResult) {
715
+ tokens.push(tableResult.token);
716
+ i = tableResult.nextLine;
717
+ prevLineWasBlank = false;
718
+ continue;
719
+ }
720
+
721
+ // Blockquote
722
+ if (/^\s{0,3}>/.test(line)) {
723
+ const quoteLines: string[] = [];
724
+ while (i < lines.length && /^\s{0,3}>/.test(lines[i])) {
725
+ // Remove the > prefix
726
+ quoteLines.push(lines[i].replace(/^\s{0,3}>\s?/, ""));
727
+ i++;
728
+ }
729
+ // Lazy continuation: collect non-blank lines that don't start a new
730
+ // block-level element (per CommonMark spec)
731
+ while (i < lines.length) {
732
+ const cur = lines[i];
733
+ if (cur.trim() === "") {break;}
734
+ // Stop on block-level markers
735
+ if (/^\s{0,3}>/.test(cur)) {break;} // new blockquote
736
+ if (/^(#{1,6})\s/.test(cur)) {break;} // heading
737
+ if (/^(`{3,}|~{3,})/.test(cur)) {break;} // code fence
738
+ if (/^(\s{0,3})([-*_])\s*(\2\s*){2,}$/.test(cur)) {break;} // hr
739
+ if (/^\s*([-*+]|\d+[.)])\s+/.test(cur)) {break;} // list item
740
+ if (/^\s*\|(.+\|)+\s*$/.test(cur)) {break;} // table
741
+ quoteLines.push(cur);
742
+ i++;
743
+ }
744
+ tokens.push({
745
+ type: "blockquote",
746
+ content: quoteLines.join("\n"),
747
+ });
748
+ prevLineWasBlank = false;
749
+ continue;
750
+ }
751
+
752
+ // List item (bullet, ordered, or task)
753
+ const listItemMatch = line.match(
754
+ /^(\s*)([-*+]|\d+[.)])(\s+)(\[[ xX]\] )?(.*)$/
755
+ );
756
+ if (listItemMatch) {
757
+ const indent = listItemMatch[1].length;
758
+ const marker = listItemMatch[2];
759
+ const markerSpaces = listItemMatch[3];
760
+ const checkbox = listItemMatch[4];
761
+ const firstLineContent = listItemMatch[5];
762
+
763
+ let listType: "bullet" | "ordered" | "task";
764
+ let start: number | undefined;
765
+ let checked: boolean | undefined;
766
+
767
+ if (checkbox) {
768
+ listType = "task";
769
+ checked = checkbox.trim() !== "[ ]";
770
+ } else if (/^\d+[.)]$/.test(marker)) {
771
+ listType = "ordered";
772
+ start = parseInt(marker, 10);
773
+ } else {
774
+ listType = "bullet";
775
+ }
776
+
777
+ // Content indent = column where content actually starts
778
+ const contentIndent =
779
+ indent +
780
+ marker.length +
781
+ markerSpaces.length +
782
+ (checkbox ? checkbox.length : 0);
783
+
784
+ // Minimum indent for child content: anything indented past the marker
785
+ // (sub-lists can start at indent > marker position)
786
+ const minChildIndent = indent + 1;
787
+
788
+ // Helper to check if a line belongs to this list item
789
+ const belongsToItem = (lineStr: string): boolean => {
790
+ if (lineStr.trim() === "") {return true;} // blank lines checked separately
791
+ const lineInd = lineStr.match(/^\s*/)![0].length;
792
+ // Lines at contentIndent are continuation text
793
+ if (lineInd >= contentIndent) {return true;}
794
+ // Lines between marker and content column that start a sub-list
795
+ if (
796
+ lineInd >= minChildIndent &&
797
+ lineStr.match(/^\s*([-*+]|\d+[.)])\s+/)
798
+ ) {
799
+ return true;
800
+ }
801
+ return false;
802
+ }
803
+
804
+ // Consume ALL subsequent lines that belong to this list item
805
+ i++;
806
+ const subLines: string[] = [];
807
+ while (i < lines.length) {
808
+ const cur = lines[i];
809
+
810
+ if (cur.trim() === "") {
811
+ // Blank line: include if followed by content that belongs to this item
812
+ let lookAhead = i + 1;
813
+ while (lookAhead < lines.length && lines[lookAhead].trim() === "") {
814
+ lookAhead++;
815
+ }
816
+ if (lookAhead < lines.length && belongsToItem(lines[lookAhead])) {
817
+ subLines.push("");
818
+ i++;
819
+ continue;
820
+ }
821
+ break;
822
+ }
823
+
824
+ if (!belongsToItem(cur)) {break;}
825
+
826
+ // Strip indent: for lines at contentIndent+, strip contentIndent chars;
827
+ // for sub-list lines between minChildIndent and contentIndent, strip minChildIndent
828
+ const lineIndent = cur.match(/^\s*/)![0].length;
829
+ if (lineIndent >= contentIndent) {
830
+ subLines.push(cur.substring(contentIndent));
831
+ } else {
832
+ // Sub-list item between minChildIndent and contentIndent
833
+ subLines.push(cur.substring(minChildIndent));
834
+ }
835
+ i++;
836
+ }
837
+
838
+ // Build the list item token
839
+ // If there are sub-lines, they become child content (recursively tokenized)
840
+ // Don't trim — preserve relative indentation of sub-lines
841
+ const childContent = subLines.join("\n").replace(/^\n+|\n+$/g, "");
842
+ tokens.push({
843
+ type: "listItem",
844
+ listType,
845
+ indent,
846
+ content: firstLineContent.trim(),
847
+ start,
848
+ checked,
849
+ childContent: childContent || undefined,
850
+ });
851
+ prevLineWasBlank = false;
852
+ continue;
853
+ }
854
+
855
+ // Block-level raw HTML: a line starting with `<tag>` (block-level tag),
856
+ // `<!-- ... -->`, `<?...?>`, `<!DOCTYPE ...>`, or `<![CDATA[...]]>`.
857
+ // Lines are emitted verbatim until the next blank line.
858
+ if (isHtmlBlockStart(line)) {
859
+ const htmlLines: string[] = [];
860
+ while (i < lines.length && lines[i].trim() !== "") {
861
+ htmlLines.push(lines[i]);
862
+ i++;
863
+ }
864
+ tokens.push({
865
+ type: "rawHtml",
866
+ content: htmlLines.join("\n"),
867
+ });
868
+ prevLineWasBlank = false;
869
+ continue;
870
+ }
871
+
872
+ // Paragraph (default)
873
+ const paraLines: string[] = [line];
874
+ i++;
875
+ while (i < lines.length) {
876
+ const nextLine = lines[i];
877
+ // Stop paragraph on blank line
878
+ if (nextLine.trim() === "") {break;}
879
+ // Stop on block-level element
880
+ if (/^(#{1,6})\s/.test(nextLine)) {break;}
881
+ if (/^(`{3,}|~{3,})/.test(nextLine)) {break;}
882
+ if (/^\s{0,3}>/.test(nextLine)) {break;}
883
+ if (/^(\s{0,3})([-*_])\s*(\2\s*){2,}$/.test(nextLine)) {break;}
884
+ if (/^\s*([-*+]|\d+[.)])\s+/.test(nextLine)) {break;}
885
+ if (/^\s*\|(.+\|)+\s*$/.test(nextLine)) {break;}
886
+ if (isHtmlBlockStart(nextLine)) {break;}
887
+ // Check if next-next line is setext marker
888
+ if (
889
+ i + 1 < lines.length &&
890
+ /^[=-]+\s*$/.test(lines[i + 1]) &&
891
+ nextLine.trim().length > 0
892
+ ) {
893
+ break;
894
+ }
895
+ paraLines.push(nextLine);
896
+ i++;
897
+ }
898
+ // CommonMark allows up to 3 leading spaces of indent on paragraph lines.
899
+ // Also strip trailing whitespace from the final line so a trailing
900
+ // hard-break sequence (` \n` at end of paragraph) doesn't leak as
901
+ // literal trailing spaces in the rendered output.
902
+ tokens.push({
903
+ type: "paragraph",
904
+ content: paraLines
905
+ .map((l) => l.replace(/^ {1,3}/, ""))
906
+ .join("\n")
907
+ .replace(/[ \t]+$/, ""),
908
+ });
909
+ prevLineWasBlank = false;
910
+ }
911
+
912
+ return tokens;
913
+ }
914
+
915
+ function tryParseTable(
916
+ lines: string[],
917
+ start: number
918
+ ): { token: TableToken; nextLine: number } | null {
919
+ // A table needs at least a header row and a separator row
920
+ if (start + 1 >= lines.length) {return null;}
921
+
922
+ const headerLine = lines[start];
923
+ const separatorLine = lines[start + 1];
924
+
925
+ // Check separator line format: | --- | --- | or --- | --- (outer pipes optional)
926
+ // Must contain at least one pipe and only dashes, colons, pipes, and whitespace
927
+ if (
928
+ !separatorLine.includes("|") ||
929
+ !/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(separatorLine)
930
+ ) {return null;}
931
+
932
+ // Check header line has at least one pipe (required to distinguish from plain text)
933
+ if (!headerLine.includes("|")) {return null;}
934
+
935
+ const headers = parsePipeCells(headerLine);
936
+ const alignments = parseAlignments(separatorLine);
937
+
938
+ const rows: string[][] = [];
939
+ let i = start + 2;
940
+ while (i < lines.length) {
941
+ const line = lines[i];
942
+ if (!line.includes("|")) {break;}
943
+ rows.push(parsePipeCells(line));
944
+ i++;
945
+ }
946
+
947
+ return {
948
+ token: {
949
+ type: "table",
950
+ headers,
951
+ rows,
952
+ alignments,
953
+ },
954
+ nextLine: i,
955
+ };
956
+ }
957
+
958
+ function parsePipeCells(line: string): string[] {
959
+ // Trim leading/trailing pipes and split
960
+ const trimmed = line.trim();
961
+ const withoutOuterPipes = trimmed.startsWith("|")
962
+ ? trimmed.substring(1)
963
+ : trimmed;
964
+ const content = withoutOuterPipes.endsWith("|")
965
+ ? withoutOuterPipes.substring(0, withoutOuterPipes.length - 1)
966
+ : withoutOuterPipes;
967
+
968
+ // Split by pipes, handling escaped pipes
969
+ const cells: string[] = [];
970
+ let current = "";
971
+ for (let i = 0; i < content.length; i++) {
972
+ if (content[i] === "\\" && i + 1 < content.length && content[i + 1] === "|") {
973
+ current += "|";
974
+ i++;
975
+ } else if (content[i] === "|") {
976
+ cells.push(current.trim());
977
+ current = "";
978
+ } else {
979
+ current += content[i];
980
+ }
981
+ }
982
+ cells.push(current.trim());
983
+
984
+ return cells;
985
+ }
986
+
987
+ function parseAlignments(
988
+ separatorLine: string
989
+ ): ("left" | "center" | "right" | null)[] {
990
+ const cells = parsePipeCells(separatorLine);
991
+ return cells.map((cell) => {
992
+ const trimmed = cell.trim();
993
+ const left = trimmed.startsWith(":");
994
+ const right = trimmed.endsWith(":");
995
+ if (left && right) {return "center";}
996
+ if (right) {return "right";}
997
+ if (left) {return "left";}
998
+ return null;
999
+ });
1000
+ }
1001
+
1002
+ // ─── HTML Emitter ────────────────────────────────────────────────────────────
1003
+
1004
+ function tokensToHtml(tokens: Token[]): string {
1005
+ let html = "";
1006
+ let i = 0;
1007
+
1008
+ while (i < tokens.length) {
1009
+ const token = tokens[i];
1010
+
1011
+ switch (token.type) {
1012
+ case "heading": {
1013
+ const t = token as HeadingToken;
1014
+ html += `<h${t.level}>${parseInline(t.content)}</h${t.level}>`;
1015
+ i++;
1016
+ break;
1017
+ }
1018
+
1019
+ case "paragraph": {
1020
+ const t = token as ParagraphToken;
1021
+ html += `<p>${parseInline(t.content)}</p>`;
1022
+ i++;
1023
+ break;
1024
+ }
1025
+
1026
+ case "codeBlock": {
1027
+ const t = token as CodeBlockToken;
1028
+ const langAttr = t.language
1029
+ ? ` data-language="${escapeHtml(t.language)}"`
1030
+ : "";
1031
+ html += `<pre><code${langAttr}>${escapeHtml(t.code)}</code></pre>`;
1032
+ i++;
1033
+ break;
1034
+ }
1035
+
1036
+ case "blockquote": {
1037
+ const t = token as BlockquoteToken;
1038
+ // Recursively parse blockquote content as markdown
1039
+ const innerTokens = tokenize(t.content);
1040
+ const innerHtml = tokensToHtml(innerTokens);
1041
+ html += `<blockquote>${innerHtml}</blockquote>`;
1042
+ i++;
1043
+ break;
1044
+ }
1045
+
1046
+ case "hr":
1047
+ html += `<hr>`;
1048
+ i++;
1049
+ break;
1050
+
1051
+ case "listItem": {
1052
+ // Collect consecutive list items and build nested list structure
1053
+ const listHtml = emitListItems(tokens, i);
1054
+ html += listHtml.html;
1055
+ i = listHtml.nextIndex;
1056
+ break;
1057
+ }
1058
+
1059
+ case "table": {
1060
+ const t = token as TableToken;
1061
+ html += emitTable(t);
1062
+ i++;
1063
+ break;
1064
+ }
1065
+
1066
+ case "rawHtml": {
1067
+ const t = token as RawHtmlToken;
1068
+ html += t.content;
1069
+ i++;
1070
+ break;
1071
+ }
1072
+
1073
+ default:
1074
+ i++;
1075
+ }
1076
+ }
1077
+
1078
+ return html;
1079
+ }
1080
+
1081
+ function emitListItems(
1082
+ tokens: Token[],
1083
+ startIdx: number
1084
+ ): { html: string; nextIndex: number } {
1085
+ let html = "";
1086
+ let i = startIdx;
1087
+ let currentListType: "bullet" | "ordered" | null = null;
1088
+
1089
+ while (i < tokens.length && tokens[i].type === "listItem") {
1090
+ const item = tokens[i] as ListItemToken;
1091
+ const effectiveType = getEffectiveListType(item.listType);
1092
+
1093
+ // Check if we need to switch list type
1094
+ if (currentListType !== null && currentListType !== effectiveType) {
1095
+ // Close current list, open new one
1096
+ html += `</${currentListType === "ordered" ? "ol" : "ul"}>`;
1097
+ currentListType = null;
1098
+ }
1099
+
1100
+ // Open list if needed
1101
+ if (currentListType === null) {
1102
+ if (effectiveType === "ordered") {
1103
+ const startAttr =
1104
+ item.start !== undefined && item.start !== 1
1105
+ ? ` start="${item.start}"`
1106
+ : "";
1107
+ html += `<ol${startAttr}>`;
1108
+ } else {
1109
+ html += `<ul>`;
1110
+ }
1111
+ currentListType = effectiveType;
1112
+ }
1113
+
1114
+ // Emit list item
1115
+ if (item.listType === "task") {
1116
+ const checkedAttr = item.checked ? " checked" : "";
1117
+ html += `<li><input type="checkbox" disabled${checkedAttr}><p>${parseInline(item.content)}</p>`;
1118
+ } else {
1119
+ html += `<li><p>${parseInline(item.content)}</p>`;
1120
+ }
1121
+
1122
+ // Render child content (nested items, continuation paragraphs, etc.)
1123
+ if (item.childContent) {
1124
+ const childTokens = tokenize(item.childContent);
1125
+ html += tokensToHtml(childTokens);
1126
+ }
1127
+
1128
+ html += `</li>`;
1129
+ i++;
1130
+ }
1131
+
1132
+ // Close the list
1133
+ if (currentListType !== null) {
1134
+ html += `</${currentListType === "ordered" ? "ol" : "ul"}>`;
1135
+ }
1136
+
1137
+ return { html, nextIndex: i };
1138
+ }
1139
+
1140
+ function getEffectiveListType(
1141
+ listType: "bullet" | "ordered" | "task"
1142
+ ): "bullet" | "ordered" {
1143
+ return listType === "ordered" ? "ordered" : "bullet";
1144
+ }
1145
+
1146
+ function emitTable(table: TableToken): string {
1147
+ let html = "<table>";
1148
+
1149
+ // BlockNote tables have no required header row, but the markdown table
1150
+ // syntax does. When we serialize a headerless BlockNote table to markdown
1151
+ // we emit an empty header row; on re-parse, treat that empty header as
1152
+ // "no header" so the round-trip is stable (issue #739).
1153
+ const headerIsEmpty = table.headers.every((h) => h.trim() === "");
1154
+ const colCount = table.headers.length;
1155
+
1156
+ if (!headerIsEmpty) {
1157
+ html += "<thead><tr>";
1158
+ for (let c = 0; c < colCount; c++) {
1159
+ const align = table.alignments[c];
1160
+ const alignAttr = align ? ` align="${align}"` : "";
1161
+ html += `<th${alignAttr}>${parseInline(table.headers[c])}</th>`;
1162
+ }
1163
+ html += "</tr></thead>";
1164
+ }
1165
+
1166
+ if (table.rows.length > 0) {
1167
+ html += "<tbody>";
1168
+ for (const row of table.rows) {
1169
+ html += "<tr>";
1170
+ for (let c = 0; c < colCount; c++) {
1171
+ const cell = c < row.length ? row[c] : "";
1172
+ const align = table.alignments[c];
1173
+ const alignAttr = align ? ` align="${align}"` : "";
1174
+ html += `<td${alignAttr}>${parseInline(cell)}</td>`;
1175
+ }
1176
+ html += "</tr>";
1177
+ }
1178
+ html += "</tbody>";
1179
+ }
1180
+
1181
+ html += "</table>";
1182
+ return html;
1183
+ }
1184
+
1185
+ // ─── Public API ──────────────────────────────────────────────────────────────
1186
+
1187
+ /**
1188
+ * Convert a markdown string to an HTML string.
1189
+ * This is a direct replacement for the unified/remark/rehype pipeline.
1190
+ */
1191
+ export function markdownToHtml(markdown: string): string {
1192
+ const tokens = tokenize(markdown);
1193
+ return tokensToHtml(tokens);
1194
+ }