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

markdownDetails.ts

110 lines4.1 KB

1import type { RootContent } from "mdast";
2import { unified } from "unified";
3import remarkParse from "remark-parse";
4import { msg } from "gt-react-native";
5import { m, type MessageResolver } from "../i18n/messages";
6​
7import { decodeHtmlEntities, markdownHtmlTags, splitLeadingBom } from "./markdownDocument";
8​
9export type MarkdownDetailsSegment =
10 | { readonly kind: "markdown"; readonly markdown: string; readonly sourceOffset: number }
11 | {
12 readonly kind: "details";
13 readonly summary: string;
14 readonly body: string;
15 readonly open: boolean;
16 readonly sourceOffset: number;
17 };
18​
19type OpenFold = { start: number; openTagEnd: number; open: boolean };
20​
21const parser = unified().use(remarkParse);
22const DETAILS_TAG = /^<(\/?)details\b/i;
23const ATTRIBUTE =
24 /([^\t\n\f\r <>/][^\t\n\f\r <>/=]*)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"[^"]*"|'[^']*'|[^\t\n\f\r >]+))?/g;
25const SUMMARY = /^\s*<summary\b[^>]*>([\s\S]*?)<\/summary\s*>/i;
26​
27/**
28 * Splits top-level `<details>` blocks out of chat Markdown so they can render as folds.
29 * Tags inside code, or a fold opened inline in a paragraph, stay Markdown. A fold whose
30 * closing tag has not streamed yet runs to the end.
31 */
32export function splitMarkdownDetails(
33 markdown: string,
34 resolve: MessageResolver = m,
35): ReadonlyArray<MarkdownDetailsSegment> {
36 if (!/<details\b/i.test(markdown)) return [{ kind: "markdown", markdown, sourceOffset: 0 }];
37​
38 const [bom] = splitLeadingBom(markdown);
39 const folds: Array<OpenFold & { end: number; closeTagLength: number }> = [];
40 let depth = 0;
41 // Asserted so the scan closure's writes are not narrowed away after the loop.
42 let current = null as OpenFold | null;
43 // A fold opens only at block level; once open, a tag inside a paragraph can close it.
44 const scan = (node: RootContent, inline: boolean) => {
45 if (node.type !== "html") {
46 if (depth > 0 && "children" in node) {
47 for (const child of node.children) scan(child, true);
48 }
49 return;
50 }
51 if (node.position?.start.offset === undefined) return;
52 const nodeStart = bom.length + node.position.start.offset;
53 for (const tag of markdownHtmlTags(node.value)) {
54 const details = DETAILS_TAG.exec(tag[0]);
55 if (!details || (inline && depth === 0)) continue;
56 const start = nodeStart + tag.index;
57 if (details[1] !== "/") {
58 if (depth === 0) {
59 const attributes = tag[0].slice(details[0].length).matchAll(ATTRIBUTE);
60 current = {
61 start,
62 openTagEnd: start + tag[0].length,
63 open: Array.from(attributes).some(
64 (attribute) => attribute[1]!.toLowerCase() === "open",
65 ),
66 };
67 }
68 depth += 1;
69 } else if (depth > 0) {
70 depth -= 1;
71 if (depth === 0 && current) {
72 folds.push({ ...current, end: start + tag[0].length, closeTagLength: tag[0].length });
73 current = null;
74 }
75 }
76 }
77 };
78 for (const node of parser.parse(markdown).children) scan(node, false);
79 if (current) folds.push({ ...current, end: markdown.length, closeTagLength: 0 });
80 if (folds.length === 0) return [{ kind: "markdown", markdown, sourceOffset: 0 }];
81​
82 const segments: MarkdownDetailsSegment[] = [];
83 let cursor = 0;
84 for (const fold of folds) {
85 if (fold.start > cursor) {
86 segments.push({
87 kind: "markdown",
88 markdown: markdown.slice(cursor, fold.start),
89 sourceOffset: cursor,
90 });
91 }
92 let body = markdown.slice(fold.openTagEnd, fold.end - fold.closeTagLength);
93 const summary = SUMMARY.exec(body);
94 if (summary) body = body.slice(summary[0].length);
95 const label = summary ? decodeHtmlEntities(summary[1]!.replace(/<[^>]*>/g, "")).trim() : "";
96 segments.push({
97 kind: "details",
98 summary:
99 label || resolve(msg({ context: "fallback summary of a collapsed section" })`Details`),
100 body,
101 open: fold.open,
102 sourceOffset: fold.start,
103 });
104 cursor = fold.end;
105 }
106 if (cursor < markdown.length) {
107 segments.push({ kind: "markdown", markdown: markdown.slice(cursor), sourceOffset: cursor });
108 }
109 return segments;