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

markdownMath.test.ts

464 lines17.9 KB

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