Open History to see the last commit
1import type { Nodes } from "mdast";
2import { describe, expect, it } from "vite-plus/test";
3
4import { mathKind } from "./markdownMath.ts";
5import { markdownMathRanges, parseMarkdownWithMath } from "./markdownMath.ts";
6
7const parse = parseMarkdownWithMath;
8
9function collect(node: Nodes, out: Nodes[] = []): Nodes[] {
10 out.push(node);
11 if ("children" in node) for (const child of node.children) collect(child, out);
12 return out;
13}
14
15/** Formulas as `[kind, tex]`, in document order. */
16function formulas(markdown: string) {
17 return collect(parse(markdown)).flatMap((node) => {
18 if (node.type === "math") return [["display", node.value]];
19 if (node.type !== "inlineMath") return [];
20 const className = node.data?.hProperties?.className;
21 return [[mathKind(Array.isArray(className) ? className.join(" ") : undefined), node.value]];
22 });
23}
24
25function text(markdown: string) {
26 return collect(parse(markdown))
27 .flatMap((node) => (node.type === "text" ? [node.value] : []))
28 .join("");
29}
30
31describe("chat math parsing", () => {
32 it("keeps GFM autolink destinations intact while restoring literal dollars", () => {
33 const source = "Query www.example.com/?$select=id and $x$.";
34 const link = collect(parse(source)).find((node) => node.type === "link");
35 expect(link).toMatchObject({ url: "http://www.example.com/?$select=id" });
36 expect(formulas(source)).toEqual([["inline", "x"]]);
37 });
38
39 it.each(["", "", ""])(
40 "preserves decoded private-use reference %s",
41 (reference) => {
42 const source = `${reference} [${reference}](https://example.com/?q=${reference}) $x$`;
43 const nodes = collect(parse(source));
44 expect(
45 nodes
46 .filter((node) => node.type === "text")
47 .map((node) => node.value)
48 .join(""),
49 ).toBe("\uE000 \uE000 ");
50 expect(nodes.find((node) => node.type === "link")).toMatchObject({
51 url: "https://example.com/?q=\uE000",
52 });
53 expect(formulas(source)).toEqual([["inline", "x"]]);
54 },
55 );
56
57 it.each(["\\(x\\)", "$x$", "$$x$$"])("preserves indented code containing %s", (formula) => {
58 const source = ` ${formula}`;
59 expect(collect(parse(source)).find((node) => node.type === "code")).toMatchObject({
60 value: formula,
61 });
62 expect(markdownMathRanges(source)).toEqual([]);
63 });
64
65 it("parses formulas without reserving private-use characters", () => {
66 const characters = Array.from({ length: 6400 }, (_, index) =>
67 String.fromCharCode(0xe000 + index),
68 ).join("");
69 const source = "$x$ " + characters;
70 expect(formulas(source)).toEqual([["inline", "x"]]);
71 expect(text(source)).toBe(" " + characters);
72 });
73
74 it("only exposes closed explicit math fences to editors and native rendering", () => {
75 expect(markdownMathRanges("```math\nx^2")).toEqual([]);
76 expect(markdownMathRanges("```math\nx^2\n```")[0]?.tex).toBe("x^2");
77 expect(markdownMathRanges("> ```math\n> x^2\n> ```")[0]?.tex).toBe("x^2");
78 });
79 it("reads the four delimiters models emit", () => {
80 expect(formulas("Inline $x^2$ and \\(y_1\\), display $$a+b$$ and \\[c\\].")).toEqual([
81 ["inline", "x^2"],
82 ["inline", "y_1"],
83 ["display", "a+b"],
84 ["display", "c"],
85 ]);
86 });
87
88 it("reads display blocks on their own lines", () => {
89 expect(formulas("$$\n\\frac{a}{b}\n$$")).toEqual([["display", "\\frac{a}{b}"]]);
90 expect(
91 formulas("Where\n\\[\n\\begin{aligned} a &= b \\\\ c &= d \\end{aligned}\n\\]\nholds."),
92 ).toEqual([["display", "\\begin{aligned} a &= b \\\\ c &= d \\end{aligned}"]]);
93 });
94
95 it.each([" is the first formula.", ", followed by prose.", " \tthen more text."])(
96 "keeps text after a same-line formula separate from later display math: %s",
97 (trailing) => {
98 const source = `$$a$$${trailing}\nSome prose.\n$$\nb\n$$`;
99 const nodes = collect(parse(source));
100 expect(
101 nodes.filter((node) => node.type === "inlineMath" || node.type === "math"),
102 ).toMatchObject([
103 { type: "inlineMath", value: "a" },
104 { type: "math", value: "b" },
105 ]);
106 expect(text(source)).toContain(`${trailing}\nSome prose.`);
107 expect(markdownMathRanges(source).map((formula) => formula.source)).toEqual([
108 "$$a$$",
109 "$$\nb\n$$",
110 ]);
111 },
112 );
113
114 it("keeps block syntax inside display blocks as TeX", () => {
115 expect(formulas("\\[\nx\n- y\n# z\n\\]\nafter")).toEqual([["display", "x\n- y\n# z"]]);
116 expect(formulas("> $$\n> x\n> $$")).toEqual([["display", "x"]]);
117 // Same-line content is not a fence; it stays one formula.
118 expect(formulas("$$x^2\n+y^2$$")).toEqual([["display", "x^2\n+y^2"]]);
119 expect(text("$$E=mc^2")).toBe("$$E=mc^2");
120 });
121
122 it("keeps prices, shell variables, and skill tokens as prose", () => {
123 for (const prose of [
124 "It costs $5 and $10.",
125 "Budget $5-$10 per seat, or $20,000-$30,000 a year.",
126 "Plans are $5/$10 monthly.",
127 "Run $browser then $deploy on it.",
128 "Set $HOME before running.",
129 ]) {
130 expect(formulas(prose), prose).toEqual([]);
131 expect(text(prose), prose).toBe(prose);
132 }
133 });
134
135 it("keeps prices as prose when math follows on the same line", () => {
136 for (const price of ["$5-$10", "$5 and $10", "$5/$10", "$20,000-$30,000"]) {
137 const source = `Price ${price} stays literal. The formula is $x_i$ and $5$.`;
138 expect(formulas(source)).toEqual([
139 ["inline", "x_i"],
140 ["inline", "5"],
141 ]);
142 expect(text(source)).toBe(`Price ${price} stays literal. The formula is and .`);
143 }
144 });
145
146 it("leaves code, escapes, links, and citations alone", () => {
147 for (const [markdown, rendered] of [
148 ["Use `$x$` in code.", "Use in code."],
149 ["It costs $5 and $10, and `$HOME` stays code.", "It costs $5 and $10, and stays code."],
150 ["Export $PATH, then `$HOME`.", "Export $PATH, then ."],
151 ["\\(a `\\)` b", "(a b"],
152 [
153 "Set $TOKEN, then open [users](https://graph.microsoft.com/v1.0/users?$select=id).",
154 "Set $TOKEN, then open users.",
155 ],
156 [
157 "Set $TOKEN, then open <https://graph.microsoft.com/v1.0/users?$select=id>.",
158 "Set $TOKEN, then open https://graph.microsoft.com/v1.0/users?$select=id.",
159 ],
160 ["```\n$x$ \\(y\\)\n```", ""],
161 ["Escaped \\$x\\$ stays.", "Escaped $x$ stays."],
162 ["Escaped \\\\(x\\\\) stays.", "Escaped \\(x\\) stays."],
163 ["See [docs](https://example.com/\\(a\\)) here.", "See docs here."],
164 ["As shown in \\[1\\] and \\[2, 3\\].", "As shown in [1] and [2, 3]."],
165 ] as const) {
166 expect(formulas(markdown), markdown).toEqual([]);
167 expect(text(markdown), markdown).toBe(rendered);
168 }
169 });
170
171 it("starts a formula right after an escaped dollar", () => {
172 expect(formulas("Pay \\$$x$ now.")).toEqual([["inline", "x"]]);
173 });
174
175 it.each([
176 ["$a`$HOME`", "$HOME"],
177 ["\\(a`\\)`", "\\)"],
178 ["\\(a\\alpha`\\)`", "\\)"],
179 ["text \\[a`\\]`", "\\]"],
180 ])("preserves an adjacent code span in %s", (source, code) => {
181 expect(formulas(source)).toEqual([]);
182 expect(collect(parse(source)).find((node) => node.type === "inlineCode")).toMatchObject({
183 value: code,
184 });
185 });
186
187 it.each([1, 2])("respects %i backslashes before a display fence", (count) => {
188 const prefix = "a+" + "\\".repeat(count);
189 for (const opening of ["$$", "$$\n"]) {
190 const source = `${opening}${prefix}$$\nb\n$$`;
191 expect(formulas(source)).toEqual([["display", count % 2 === 1 ? `${prefix}$$\nb` : prefix]]);
192 expect(markdownMathRanges(source)[0]?.source).toBe(
193 count % 2 === 1 ? source : `${opening}${prefix}$$`,
194 );
195 }
196 });
197
198 it("keeps TeX escapes inside formulas", () => {
199 expect(formulas("Cost $a\\$b$ and \\(\\left(x\\right)\\).")).toEqual([
200 ["inline", "a\\$b"],
201 ["inline", "\\left(x\\right)"],
202 ]);
203 });
204
205 it("keeps source offsets of the original message", () => {
206 const markdown = "- [ ] check \\(x\\)\n- [x] then $y$";
207 const offsets = collect(parse(markdown)).flatMap((node) =>
208 node.type === "inlineMath" || node.type === "listItem"
209 ? [[node.type, node.position?.start.offset]]
210 : [],
211 );
212 expect(offsets).toEqual([
213 ["listItem", 0],
214 ["inlineMath", markdown.indexOf("\\(")],
215 ["listItem", markdown.indexOf("- [x]")],
216 ["inlineMath", markdown.indexOf("$y$")],
217 ]);
218 });
219
220 it.each(["\n", "\r\n", "\r"])("keeps authored lines and UTF-16 offsets with %j", (eol) => {
221 const source = `😀 \\(x${eol}+y\\)${eol}${eol}- [ ] check $z$`;
222 const nodes = collect(parse(source));
223 const formula = nodes.find(
224 (node) => node.type === "inlineMath" && node.value === "x" + eol + "+y",
225 );
226 expect(formula?.position?.start).toEqual({ line: 1, column: 4, offset: 3 });
227 expect(formula?.position?.end).toEqual({
228 line: 2,
229 column: 5,
230 offset: source.indexOf(eol + eol),
231 });
232 expect(nodes.find((node) => node.type === "listItem")?.position?.start).toEqual({
233 line: 4,
234 column: 1,
235 offset: source.indexOf("- [ ]"),
236 });
237 });
238
239 it("shows unfinished formulas as text while a response streams", () => {
240 const message = "Energy \\(E = mc^2\\) and $$\\sum_i x_i$$ done.";
241 for (let end = 0; end <= message.length; end++) {
242 expect(() => parse(message.slice(0, end))).not.toThrow();
243 }
244 expect(text("Energy \\(E = mc")).toBe("Energy (E = mc");
245 expect(formulas("$$\nx^2")).toEqual([]);
246 expect(formulas("\\[\nx^2\n- y")).toEqual([]);
247 expect(formulas(message)).toEqual([
248 ["inline", "E = mc^2"],
249 ["display", "\\sum_i x_i"],
250 ]);
251 });
252});
253
254describe("math in GFM tables", () => {
255 it("renders math in link labels while retaining dollars in their destinations", () => {
256 const row = "| [norm $|x|$](https://example.com/$path) | y$ |";
257 for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
258 const tree = parse(source);
259 const table = tree.children[0];
260 expect(table?.type).toBe("table");
261 if (table?.type !== "table") throw new Error("Missing table");
262 expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
263 expect(markdownMathRanges(source, tree).map((range) => range.tex)).toEqual(["|x|"]);
264 expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
265 url: "https://example.com/$path",
266 });
267 }
268 });
269
270 it.each(["[a](https://example.com/$x)", "`$x`", '<span title="$x">a</span>'])(
271 "preserves table separators after literal dollars in %s",
272 (literal) => {
273 const row = `| ${literal} | y$ |`;
274 for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
275 const tree = parse(source);
276 const table = tree.children[0];
277 expect(table?.type).toBe("table");
278 if (table?.type !== "table") throw new Error("Missing table");
279 expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
280 expect(markdownMathRanges(source, tree)).toEqual([]);
281 if (literal.startsWith("[a](https://example.com/$x)")) {
282 expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
283 url: "https://example.com/$x",
284 });
285 }
286 }
287 },
288 );
289
290 it("retains multiline math after a prose pipe outside tables", () => {
291 const source = "a | b: \\(x\n+y\\)";
292 expect(formulas(source)).toEqual([["inline", "x\n+y"]]);
293 expect(markdownMathRanges(source)).toEqual([
294 expect.objectContaining({ source: "\\(x\n+y\\)", inTable: false }),
295 ]);
296 });
297 it.each(["\\(", "\\["])("keeps table rows intact when %s closes in a later row", (opener) => {
298 const closer = opener === "\\(" ? "\\)" : "\\]";
299 const source = `| Name | Value |\n| --- | --- |\n| first | ${opener}x |\n| second | y${closer} |\n| valid | $|z|$ |`;
300 const tree = parseMarkdownWithMath(source);
301 const table = tree.children[0];
302 expect(table?.type).toBe("table");
303 if (table?.type !== "table") throw new Error("Missing table");
304 expect(table.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2]);
305 expect(
306 collect(tree)
307 .filter((node) => node.type === "text")
308 .map((node) => node.value),
309 ).toEqual([
310 "Name",
311 "Value",
312 "first",
313 opener.slice(1) + "x",
314 "second",
315 "y" + closer.slice(1),
316 "valid",
317 ]);
318 expect(markdownMathRanges(source)).toEqual([
319 expect.objectContaining({ source: "$|z|$", tex: "|z|" }),
320 ]);
321 expect(JSON.stringify(tree)).not.toMatch(/[\uE000-\uF8FF]/);
322 });
323 it.each(["\\(\\frac{1}{|x|}\\)", "$$|x|$$", "$|x|$"])(
324 "keeps pipes inside %s in one cell and preserves source offsets",
325 (formula) => {
326 const source = `| Name | Value |\n| --- | --- |\n| x | ${formula} |\n\n- [ ] next`;
327 const tree = parseMarkdownWithMath(source);
328 const table = tree.children[0];
329 expect(table?.type).toBe("table");
330 if (table?.type !== "table") throw new Error("Missing table");
331 expect(table.children.map((row) => row.children.length)).toEqual([2, 2]);
332 expect(markdownMathRanges(source)).toEqual([
333 expect.objectContaining({ source: formula, start: source.indexOf(formula) }),
334 ]);
335 const checkbox = collect(tree).find((node) => node.type === "listItem");
336 expect(checkbox?.position?.start.offset).toBe(source.indexOf("- [ ]"));
337 },
338 );
339
340 it("preserves TeX pipe commands inside and outside tables", () => {
341 const source = "| Formula |\n| --- |\n| \\(\\|x\\|\\) |\n\n\\(\\|x\\|\\)";
342 expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual([
343 "\\|x\\|",
344 "\\|x\\|",
345 ]);
346 });
347
348 it("leaves code, URLs, incomplete math, and private-use text unchanged", () => {
349 const source =
350 "| Value | Other |\n| --- | --- |\n| `\\(a\\|b\\)` | \\(x|y\\) |\n\n\uE000\n\n[link](https://example.com/$x|y$)\n\nUnclosed \\(x|y";
351 const tree = parseMarkdownWithMath(source);
352 expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual(["x|y"]);
353 expect(JSON.stringify(tree)).toContain("https://example.com/$x|y$");
354 expect(collect(tree).find((node) => node.type === "inlineCode")).toMatchObject({
355 value: "\\(a|b\\)",
356 });
357 expect(JSON.stringify(tree)).toContain("\uE000");
358 });
359
360 it("keeps a display equation's equality line out of Markdown headings", () => {
361 const source = "\\[\na\n=\nb\n\\]";
362 expect(parseMarkdownWithMath(source).children).toEqual([
363 expect.objectContaining({ type: "math", value: "a\n=\nb" }),
364 ]);
365 });
366});