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