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([1, 2, 3, 4])("respects %i backslashes before a display fence", (count) => {
191 const prefix = "a+" + "\\".repeat(count);
192 for (const opening of ["$$", "$$\n"]) {
193 const source = `${opening}${prefix}$$\nb\n$$`;
194 expect(formulas(source)).toEqual([["display", count % 2 === 1 ? `${prefix}$$\nb` : prefix]]);
195 expect(markdownMathRanges(source)[0]?.source).toBe(
196 count % 2 === 1 ? source : `${opening}${prefix}$$`,
197 );
198 }
199 });
200
201 it("keeps TeX escapes inside formulas", () => {
202 expect(formulas("Cost $a\\$b$ and \\(\\left(x\\right)\\).")).toEqual([
203 ["inline", "a\\$b"],
204 ["inline", "\\left(x\\right)"],
205 ]);
206 });
207
208 it("keeps source offsets of the original message", () => {
209 const markdown = "- [ ] check \\(x\\)\n- [x] then $y$";
210 const offsets = collect(parse(markdown)).flatMap((node) =>
211 node.type === "inlineMath" || node.type === "listItem"
212 ? [[node.type, node.position?.start.offset]]
213 : [],
214 );
215 expect(offsets).toEqual([
216 ["listItem", 0],
217 ["inlineMath", markdown.indexOf("\\(")],
218 ["listItem", markdown.indexOf("- [x]")],
219 ["inlineMath", markdown.indexOf("$y$")],
220 ]);
221 });
222
223 it.each(["\n", "\r\n", "\r"])("keeps authored lines and UTF-16 offsets with %j", (eol) => {
224 const source = `😀 \\(x${eol}+y\\)${eol}${eol}- [ ] check $z$`;
225 const nodes = collect(parse(source));
226 const formula = nodes.find(
227 (node) => node.type === "inlineMath" && node.value === "x" + eol + "+y",
228 );
229 expect(formula?.position?.start).toEqual({ line: 1, column: 4, offset: 3 });
230 expect(formula?.position?.end).toEqual({
231 line: 2,
232 column: 5,
233 offset: source.indexOf(eol + eol),
234 });
235 expect(nodes.find((node) => node.type === "listItem")?.position?.start).toEqual({
236 line: 4,
237 column: 1,
238 offset: source.indexOf("- [ ]"),
239 });
240 });
241
242 it("shows unfinished formulas as text while a response streams", () => {
243 const message = "Energy \\(E = mc^2\\) and $$\\sum_i x_i$$ done.";
244 for (let end = 0; end <= message.length; end++) {
245 expect(() => parse(message.slice(0, end))).not.toThrow();
246 }
247 expect(text("Energy \\(E = mc")).toBe("Energy (E = mc");
248 expect(formulas("$$\nx^2")).toEqual([]);
249 expect(formulas("\\[\nx^2\n- y")).toEqual([]);
250 expect(formulas(message)).toEqual([
251 ["inline", "E = mc^2"],
252 ["display", "\\sum_i x_i"],
253 ]);
254 });
255});
256
257describe("math in GFM tables", () => {
258 it("renders math in link labels while retaining dollars in their destinations", () => {
259 const row = "| [norm $|x|$](https://example.com/$path) | y$ |";
260 for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
261 const tree = parse(source);
262 const table = tree.children[0];
263 expect(table?.type).toBe("table");
264 if (table?.type !== "table") throw new Error("Missing table");
265 expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
266 expect(markdownMathRanges(source, tree).map((range) => range.tex)).toEqual(["|x|"]);
267 expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
268 url: "https://example.com/$path",
269 });
270 }
271 });
272
273 it.each([
274 "[a](https://example.com/$x)",
275 '[a](https://example.com "title $x")',
276 "<https://example.com/$x>",
277 "`$x`",
278 '<span title="$x">a</span>',
279 ])("preserves table separators after literal dollars in %s", (literal) => {
280 const row = `| ${literal} | y$ |`;
281 for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
282 const tree = parse(source);
283 const table = tree.children[0];
284 expect(table?.type).toBe("table");
285 if (table?.type !== "table") throw new Error("Missing table");
286 expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
287 expect(markdownMathRanges(source, tree)).toEqual([]);
288 if (literal.startsWith("[a](https://example.com/$x)")) {
289 expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
290 url: "https://example.com/$x",
291 });
292 }
293 }
294 });
295
296 it("retains multiline math after a prose pipe outside tables", () => {
297 const source = "a | b: \\(x\n+y\\)";
298 expect(formulas(source)).toEqual([["inline", "x\n+y"]]);
299 expect(markdownMathRanges(source)).toEqual([
300 expect.objectContaining({ source: "\\(x\n+y\\)", inTable: false }),
301 ]);
302 });
303 it.each(["\\(", "\\["])("keeps table rows intact when %s closes in a later row", (opener) => {
304 const closer = opener === "\\(" ? "\\)" : "\\]";
305 const source = `| Name | Value |\n| --- | --- |\n| first | ${opener}x |\n| second | y${closer} |\n| valid | $|z|$ |`;
306 const tree = parseMarkdownWithMath(source);
307 const table = tree.children[0];
308 expect(table?.type).toBe("table");
309 if (table?.type !== "table") throw new Error("Missing table");
310 expect(table.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2]);
311 expect(
312 collect(tree)
313 .filter((node) => node.type === "text")
314 .map((node) => node.value),
315 ).toEqual([
316 "Name",
317 "Value",
318 "first",
319 opener.slice(1) + "x",
320 "second",
321 "y" + closer.slice(1),
322 "valid",
323 ]);
324 expect(markdownMathRanges(source)).toEqual([
325 expect.objectContaining({ source: "$|z|$", tex: "|z|" }),
326 ]);
327 expect(JSON.stringify(tree)).not.toMatch(/[\uE000-\uF8FF]/);
328 });
329 it.each(["\\(\\frac{1}{|x|}\\)", "$$|x|$$", "$|x|$", "\\[|x|\\]"])(
330 "keeps pipes inside %s in one cell and preserves source offsets",
331 (formula) => {
332 const source = `| Name | Value |\n| --- | --- |\n| x | ${formula} |\n\n- [ ] next`;
333 const tree = parseMarkdownWithMath(source);
334 const table = tree.children[0];
335 expect(table?.type).toBe("table");
336 if (table?.type !== "table") throw new Error("Missing table");
337 expect(table.children.map((row) => row.children.length)).toEqual([2, 2]);
338 expect(markdownMathRanges(source)).toEqual([
339 expect.objectContaining({ source: formula, start: source.indexOf(formula) }),
340 ]);
341 const checkbox = collect(tree).find((node) => node.type === "listItem");
342 expect(checkbox?.position?.start.offset).toBe(source.indexOf("- [ ]"));
343 },
344 );
345
346 it("preserves TeX pipe commands inside and outside tables", () => {
347 const source = "| Formula |\n| --- |\n| \\(\\|x\\|\\) |\n\n\\(\\|x\\|\\)";
348 expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual([
349 "\\|x\\|",
350 "\\|x\\|",
351 ]);
352 });
353
354 it("leaves code, URLs, incomplete math, and private-use text unchanged", () => {
355 const source =
356 "| Value | Other |\n| --- | --- |\n| `\\(a\\|b\\)` | \\(x|y\\) |\n\n\uE000\n\n[link](https://example.com/$x|y$)\n\nUnclosed \\(x|y";
357 const tree = parseMarkdownWithMath(source);
358 expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual(["x|y"]);
359 expect(JSON.stringify(tree)).toContain("https://example.com/$x|y$");
360 expect(collect(tree).find((node) => node.type === "inlineCode")).toMatchObject({
361 value: "\\(a|b\\)",
362 });
363 expect(JSON.stringify(tree)).toContain("\uE000");
364 });
365
366 it("keeps a display equation's equality line out of Markdown headings", () => {
367 const source = "\\[\na\n=\nb\n\\]";
368 expect(parseMarkdownWithMath(source).children).toEqual([
369 expect.objectContaining({ type: "math", value: "a\n=\nb" }),
370 ]);
371 });
372});