Skip to content

Commit 67c87bc

Browse files
test(web): cover percent repair with a unit test instead of a browser test
Moves escapeLiteralPercents into MathTypeset.logic.ts so its cases run as a millisecond unit test, and drops the browser test rows that re-checked the same string logic through the DOM. AI-assisted; verified with the tests and tools listed above. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e09f9aa commit 67c87bc

4 files changed

Lines changed: 71 additions & 81 deletions

File tree

Lines changed: 1 addition & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { expect, it, vi } from "vite-plus/test";
1+
import { expect, it } from "vite-plus/test";
22
import { userEvent } from "vite-plus/test/browser";
33

44
import { render } from "../../../test/render";
@@ -34,43 +34,3 @@ it("keeps keyboard scrolling available as a streamed equation outgrows its viewp
3434
await userEvent.keyboard("{Tab}");
3535
await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus();
3636
});
37-
38-
it("typesets equations whose labels have an unescaped percent", async () => {
39-
// The reported multiline equation, line breaks included.
40-
const issue =
41-
"R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}";
42-
const typeset = [
43-
issue,
44-
"\\text{100%% yield}",
45-
"\\begin{aligned}x\\\\%\\end{aligned}",
46-
"\\begin{aligned}\nx &= 1 % +999\n\\\\ y &= \\text{2%}\n\\end{aligned}",
47-
"\\verb|50%|+\n\\text{2%}",
48-
"x % note\n+ 1",
49-
];
50-
const raw = ["\\frac{1", "\\text{50 % off}", "\\verb|50%+\\text{2%}"];
51-
const equations = (tex: string[]) => tex.map((t) => <MarkdownMath key={t} tex={t} display />);
52-
await using screen = await render(<>{equations(typeset)}</>);
53-
const rendered = () => [...screen.container.querySelectorAll("[data-markdown-math]")];
54-
const visibleText = (index: number) =>
55-
rendered()[index]?.querySelector(".katex-html")?.textContent?.replaceAll("\u00a0", " ");
56-
await vi.waitFor(() => {
57-
for (const equation of rendered()) expect(equation.querySelector(".katex")).not.toBeNull();
58-
});
59-
expect(visibleText(0)).toContain("3.18% dividend yield");
60-
expect(visibleText(0)).toContain("9.18%");
61-
expect(rendered()[0]?.getAttribute("data-markdown-copy")).toBe(`\\[\n${issue}\n\\]\n\n`);
62-
expect(visibleText(1)).toContain("100%% yield");
63-
expect(visibleText(3)).toContain("2%");
64-
expect(visibleText(3)).not.toContain("999");
65-
expect(visibleText(4)).toContain("50%");
66-
expect(visibleText(4)).toContain("2%");
67-
expect(visibleText(5)).not.toContain("note");
68-
69-
// KaTeX has loaded, so these render their final result in this commit.
70-
await screen.rerender(<>{equations([...typeset, ...raw])}</>);
71-
raw.forEach((tex, offset) => {
72-
const equation = rendered()[typeset.length + offset];
73-
expect(equation?.querySelector(".katex")).toBeNull();
74-
expect(equation?.textContent).toBe(`\\[\n${tex}\n\\]`);
75-
});
76-
});
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import katex from "katex";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { escapeLiteralPercents } from "./MathTypeset.logic";
5+
6+
describe("escapeLiteralPercents", () => {
7+
it.each([
8+
["\\text{3.18% yield}", "\\text{3.18\\% yield}"],
9+
["\\text{100%% yield}", "\\text{100\\%\\% yield}"],
10+
["6\\% + 2\\%", "6\\% + 2\\%"],
11+
["x\\\\%", "x\\\\\\%"],
12+
["x % note\n+ 1", "x % note\n+ 1"],
13+
["% note\n\\text{2%}", "% note\n\\text{2\\%}"],
14+
["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"],
15+
["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"],
16+
["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"],
17+
["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"],
18+
])("repairs %j", (tex, expected) => {
19+
expect(escapeLiteralPercents(tex)).toBe(expected);
20+
});
21+
22+
it("lets the reported multiline equation typeset", () => {
23+
const tex =
24+
"R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}";
25+
expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow();
26+
expect(() =>
27+
katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }),
28+
).not.toThrow();
29+
});
30+
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Escapes each `%` written right after other text, as in `\text{3.18% yield}`.
3+
* A `%` at a line start or after whitespace stays a comment. Skips escapes and
4+
* `\verb` like KaTeX's lexer, in one linear pass.
5+
*/
6+
export function escapeLiteralPercents(tex: string): string {
7+
let repaired = "";
8+
let copied = 0;
9+
let index = 0;
10+
while (index < tex.length) {
11+
const char = tex[index];
12+
if (char === "\\") {
13+
if (tex.startsWith("\\verb", index)) {
14+
const starred = tex[index + 5] === "*";
15+
const delimiter = tex[index + (starred ? 6 : 5)];
16+
if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) {
17+
const bodyStart = index + (starred ? 7 : 6);
18+
let close = bodyStart;
19+
while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++;
20+
// KaTeX rejects a \verb that does not close on its own line.
21+
if (tex[close] !== delimiter) return tex;
22+
index = close + 1;
23+
continue;
24+
}
25+
}
26+
// A control symbol such as `\%` or `\\` is two characters.
27+
index += 2;
28+
} else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) {
29+
repaired += `${tex.slice(copied, index)}\\%`;
30+
copied = ++index;
31+
} else if (char === "%") {
32+
const newline = tex.indexOf("\n", index);
33+
index = newline === -1 ? tex.length : newline + 1;
34+
} else {
35+
index++;
36+
}
37+
}
38+
return copied === 0 ? tex : repaired + tex.slice(copied);
39+
}

‎apps/web/src/components/chat/MathTypeset.tsx‎

Lines changed: 1 addition & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -3,51 +3,12 @@ import "katex/dist/katex.min.css";
33
import type { ReactNode } from "react";
44

55
import { LRUCache } from "../../lib/lruCache";
6+
import { escapeLiteralPercents } from "./MathTypeset.logic";
67

78
// Virtualized threads remount messages while scrolling; cached markup keeps
89
// that from typesetting the same formulas again. "" records a parse error.
910
const typesetCache = new LRUCache<string>(1000, 4 * 1024 * 1024);
1011

11-
/**
12-
* Escapes each `%` written right after other text, as in `\text{3.18% yield}`.
13-
* A `%` at a line start or after whitespace stays a comment. Skips escapes and
14-
* `\verb` like KaTeX's lexer, in one linear pass.
15-
*/
16-
function escapeLiteralPercents(tex: string): string {
17-
let repaired = "";
18-
let copied = 0;
19-
let index = 0;
20-
while (index < tex.length) {
21-
const char = tex[index];
22-
if (char === "\\") {
23-
if (tex.startsWith("\\verb", index)) {
24-
const starred = tex[index + 5] === "*";
25-
const delimiter = tex[index + (starred ? 6 : 5)];
26-
if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) {
27-
const bodyStart = index + (starred ? 7 : 6);
28-
let close = bodyStart;
29-
while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++;
30-
// KaTeX rejects a \verb that does not close on its own line.
31-
if (tex[close] !== delimiter) return tex;
32-
index = close + 1;
33-
continue;
34-
}
35-
}
36-
// A control symbol such as `\%` or `\\` is two characters.
37-
index += 2;
38-
} else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) {
39-
repaired += `${tex.slice(copied, index)}\\%`;
40-
copied = ++index;
41-
} else if (char === "%") {
42-
const newline = tex.indexOf("\n", index);
43-
index = newline === -1 ? tex.length : newline + 1;
44-
} else {
45-
index++;
46-
}
47-
}
48-
return copied === 0 ? tex : repaired + tex.slice(copied);
49-
}
50-
5112
function typeset(tex: string, display: boolean): string {
5213
const key = `${display ? "display" : "inline"}:${tex}`;
5314
const cached = typesetCache.get(key);

0 commit comments

Comments
 (0)