Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownStreamBlocks.ts

60 lines2.4 KB

1// Definitions, footnotes, raw HTML, container directives and display math can tie blocks together.
2const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m;
3const FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})/;
4// After a blank line these still continue the previous block: a list item or indented content.
5const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/;
6// Claude insight fences render as one callout, so they stay in one block until the closing rule.
7const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
8const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u;
9​
10/**
11 * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it
12 * would inside the whole text. Returns null when the text uses syntax that spans blocks.
13 */
14export function splitMarkdownBlocks(text: string): string[] | null {
15 if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null;
16 const blocks: string[] = [];
17 let blockStart = 0;
18 let lineStart = 0;
19 let fence: string | null = null;
20 let fenceIndent = 0;
21 let afterBlankLine = false;
22 let insightIndent: string | null = null;
23 for (const line of text.split("\n")) {
24 const opener = FENCE_PATTERN.exec(line)?.[1];
25 if (fence !== null) {
26 // A line left of an indented fence may end the list item holding it, which isn't tracked.
27 if (/\S/.test(line.slice(0, fenceIndent))) break;
28 if (
29 opener &&
30 opener[0] === fence[0] &&
31 opener.length >= fence.length &&
32 line.trim() === opener
33 ) {
34 fence = null;
35 }
36 } else if (insightIndent !== null && INSIGHT_CLOSE_PATTERN.exec(line)?.[1] === insightIndent) {
37 insightIndent = null;
38 afterBlankLine = false;
39 } else if (line.trim() === "") {
40 afterBlankLine = true;
41 } else {
42 if (
43 afterBlankLine &&
44 insightIndent === null &&
45 lineStart > blockStart &&
46 !CONTINUATION_PATTERN.test(line)
47 ) {
48 blocks.push(text.slice(blockStart, lineStart));
49 blockStart = lineStart;
50 }
51 afterBlankLine = false;
52 if (insightIndent === null) insightIndent = INSIGHT_OPEN_PATTERN.exec(line)?.[1] ?? null;
53 fence = opener ?? null;
54 if (opener) fenceIndent = line.indexOf(opener);
55 }
56 lineStart += line.length + 1;
57 }
58 blocks.push(text.slice(blockStart));
59 return blocks;