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

markdownMath.test.ts

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