Skip to content

Your lightweight open-source personal agent.

perf(webui): avoid redundant math layout setup

chengyongru24dd740d5b05
diff --git a/webui/browser/display-math-fixture.tsx b/webui/browser/display-math-fixture.tsx
new file mode 100644
index 000000000..db09675fb
--- /dev/null
+++ b/webui/browser/display-math-fixture.tsx
@@ -0,0 +1,17 @@
+import { useState } from "react";
+
+import { MarkdownText } from "@/components/MarkdownText";
+
+export function DisplayMathFixture() {
+ const [step, setStep] = useState(0);
+ const [streaming, setStreaming] = useState(true);
+ const terms = step === 0 ? "x + y" : Array.from({ length: 24 }, (_, index) => `x_{${index}}`).join(" + ");
+ const tag = step < 2 ? "1" : "1000000";
+ return <main className="mx-auto max-w-3xl p-6">
+ <button onClick={() => setStep((value) => value + 1)}>Advance stream</button>
+ <button onClick={() => setStreaming(false)}>Complete</button>
+ <div data-testid="math-reply"><MarkdownText streaming={streaming} preserveStreamingLayout>
+ {`$$${terms} = 1 \\tag{${tag}}$$`}
+ </MarkdownText></div>
+ </main>;
+}
diff --git a/webui/browser/display-math.spec.ts b/webui/browser/display-math.spec.ts
new file mode 100644
index 000000000..d288a046d
--- /dev/null
+++ b/webui/browser/display-math.spec.ts
@@ -0,0 +1,42 @@
+import { expect, test, type Page } from "@playwright/test";
+
+async function expectFittedFormula(page: Page) {
+ const frame = page.locator(".math-fit");
+ await expect(frame).toHaveCount(1);
+ await expect.poll(async () => frame.evaluate((element) => {
+ const box = element.getBoundingClientRect();
+ const content = element.querySelector<HTMLElement>(".math-fit-content")!.getBoundingClientRect();
+ const tag = element.querySelector<HTMLElement>(".katex-html > .tag")!.getBoundingClientRect();
+ return box.height > 0 && content.width <= box.width + 1
+ && Math.abs(content.height - box.height) <= 1
+ && Math.abs((content.left + content.right) - (box.left + box.right)) <= 2
+ && tag.left >= box.left - 1 && tag.right <= box.right + 1;
+ })).toBe(true);
+}
+
+for (const width of [1280, 390]) {
+ for (const reducedMotion of ["no-preference", "reduce"] as const) {
+ test(`fits tagged streaming math at ${width}px with motion ${reducedMotion}`, async ({ page }) => {
+ const errors: string[] = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ await page.setViewportSize({ width, height: 844 });
+ await page.emulateMedia({ reducedMotion });
+ await page.goto("/browser/fixture.html?case=display-math");
+ await page.evaluate(() => document.fonts.ready);
+ await expectFittedFormula(page);
+ await page.getByRole("button", { name: "Advance stream" }).click();
+ await expectFittedFormula(page);
+ await expect.poll(() => page.locator(".math-fit").getAttribute("data-math-scale").then(Number)).toBeLessThan(1);
+ await page.getByRole("button", { name: "Advance stream" }).click();
+ await expect(page.locator(".katex-html > .tag")).toHaveText("(1000000)");
+ await expectFittedFormula(page);
+ await page.getByRole("button", { name: "Complete", exact: true }).click();
+ await expectFittedFormula(page);
+ await page.setViewportSize({ width: width === 390 ? 1280 : 390, height: 844 });
+ await expectFittedFormula(page);
+ await page.locator(".math-fit-content").evaluate((element) => { element.style.fontSize = "24px"; });
+ await expectFittedFormula(page);
+ expect(errors).toEqual([]);
+ });
+ }
+}
diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx
index 2931b743c..3364a5d01 100644
--- a/webui/browser/fixture.tsx
+++ b/webui/browser/fixture.tsx
@@ -36,6 +36,7 @@ import { QueuedGuidanceFixture } from "./queued-guidance-fixture";
import { WorkspaceAlignmentFixture } from "./workspace-alignment-fixture";
import { ComposerActionFixture } from "./composer-action-fixture";
import { MobileChatLayoutFixture } from "./mobile-chat-layout-fixture";
+import { DisplayMathFixture } from "./display-math-fixture";
const history: UIMessage[] = [
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
@@ -225,6 +226,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>
? <SidebarActivityFixture />
: parameters.get("case") === "chat-failure"
? <ChatFailureFixture parameters={parameters} />
+ : parameters.get("case") === "display-math"
+ ? <DisplayMathFixture />
: parameters.get("case") === "markdown-emphasis"
? <MarkdownEmphasisFixture />
: parameters.get("case") === "typography"
diff --git a/webui/src/components/DisplayMath.tsx b/webui/src/components/DisplayMath.tsx
index 704151738..092f9249b 100644
--- a/webui/src/components/DisplayMath.tsx
+++ b/webui/src/components/DisplayMath.tsx
@@ -1,4 +1,4 @@
-import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import "./DisplayMath.css";
@@ -6,24 +6,27 @@ export function DisplayMath({ children }: { children: ReactNode }) {
const frame = useRef<HTMLSpanElement>(null);
const content = useRef<HTMLSpanElement>(null);
const [layout, setLayout] = useState({ scale: 1, height: 0 });
+ const update = useCallback(() => {
+ if (!frame.current || !content.current) return;
+ const tag = content.current.querySelector<HTMLElement>(".katex-html > .tag");
+ const tagWidth = `${tag?.offsetWidth ?? 0}px`;
+ if (content.current.style.getPropertyValue("--math-tag-width") !== tagWidth) {
+ content.current.style.setProperty("--math-tag-width", tagWidth);
+ }
+ const width = content.current.offsetWidth;
+ const scale = width ? Math.min(1, frame.current.clientWidth / width) : 1;
+ const height = content.current.offsetHeight * scale;
+ setLayout(previous => previous.scale === scale && previous.height === height ? previous : { scale, height });
+ }, []);
useLayoutEffect(() => {
- const update = () => {
- if (!frame.current || !content.current) return;
- const tag = content.current.querySelector<HTMLElement>(".katex-html > .tag");
- content.current.style.setProperty("--math-tag-width", `${tag?.offsetWidth ?? 0}px`);
- const width = content.current.offsetWidth;
- const scale = width ? Math.min(1, frame.current.clientWidth / width) : 1;
- const height = content.current.offsetHeight * scale;
- setLayout(previous => previous.scale === scale && previous.height === height ? previous : { scale, height });
- };
- update();
const observer = new ResizeObserver(update);
observer.observe(frame.current!);
observer.observe(content.current!);
let cancelled = false;
void document.fonts?.ready.then(() => { if (!cancelled) update(); });
return () => { cancelled = true; observer.disconnect(); };
- }, [children]);
+ }, [update]);
+ useLayoutEffect(update, [children, update]);
return <span ref={frame} className="math-fit" style={{ height: layout.height || undefined }}
data-math-scale={layout.scale}>
<span ref={content} className="math-fit-content" style={{ transform: `translateX(-50%) scale(${layout.scale})` }}>
diff --git a/webui/src/tests/display-math.test.tsx b/webui/src/tests/display-math.test.tsx
index 46221e043..11a70d4dd 100644
--- a/webui/src/tests/display-math.test.tsx
+++ b/webui/src/tests/display-math.test.tsx
@@ -6,22 +6,27 @@ let availableWidth: number;
let formulaWidth: number;
let formulaHeight: number;
let resize: () => void;
+let tagWidth: number;
+let observerCreations: number;
beforeEach(() => {
availableWidth = 1000;
formulaWidth = 800;
formulaHeight = 80;
+ tagWidth = 40;
+ observerCreations = 0;
vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(function (this: HTMLElement) {
return this.classList.contains("math-fit") ? availableWidth : 0;
});
vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockImplementation(function (this: HTMLElement) {
+ if (this.classList.contains("tag")) return tagWidth;
return this.classList.contains("math-fit-content") ? formulaWidth : 0;
});
vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(function (this: HTMLElement) {
return this.classList.contains("math-fit-content") ? formulaHeight : 0;
});
vi.stubGlobal("ResizeObserver", class {
- constructor(callback: () => void) { resize = callback; }
+ constructor(callback: () => void) { resize = callback; observerCreations += 1; }
observe() {}
disconnect() {}
});
@@ -32,8 +37,9 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-it("fits a wide formula on resize and restores its size without enlarging it", () => {
+it("fits a wide formula on resize and restores its size without enlarging it", async () => {
const { container } = render(<DisplayMath><span>long equation</span></DisplayMath>);
+ await act(async () => { await document.fonts.ready; });
const frame = container.querySelector<HTMLElement>(".math-fit")!;
const formula = container.querySelector<HTMLElement>(".math-fit-content")!;
expect(frame.style.height).toBe("80px");
@@ -49,11 +55,12 @@ it("fits a wide formula on resize and restores its size without enlarging it", (
expect(formula.style.transform).toContain("scale(1)");
});
-it("recalculates width and occupied height when a streaming formula grows", () => {
+it("recalculates width and occupied height when a streaming formula grows", async () => {
availableWidth = 400;
formulaWidth = 200;
formulaHeight = 40;
const { container, rerender } = render(<DisplayMath><span>initial equation</span></DisplayMath>);
+ await act(async () => { await document.fonts.ready; });
const frame = container.querySelector<HTMLElement>(".math-fit")!;
expect(frame.style.height).toBe("40px");
@@ -64,3 +71,34 @@ it("recalculates width and occupied height when a streaming formula grows", () =
expect(container.querySelector<HTMLElement>(".math-fit-content")!.style.transform).toContain("scale(0.5)");
expect(frame.textContent).toBe("completed equation");
});
+
+it("keeps observation and unchanged tag spacing stable across streaming rerenders", async () => {
+ availableWidth = 400;
+ const setProperty = vi.spyOn(CSSStyleDeclaration.prototype, "setProperty");
+ const equation = (label: string) => <span className="katex-html">
+ <span>{label}</span><span className="tag">(1)</span>
+ </span>;
+ const { container, rerender } = render(<DisplayMath>{equation("initial")}</DisplayMath>);
+ await act(async () => { await document.fonts.ready; });
+ const frame = container.querySelector<HTMLElement>(".math-fit")!;
+ const formula = container.querySelector<HTMLElement>(".math-fit-content")!;
+ const tagWrites = () => setProperty.mock.calls.filter(([name]) => name === "--math-tag-width");
+ expect(formula.style.getPropertyValue("--math-tag-width")).toBe("40px");
+
+ rerender(<DisplayMath>{equation("stream update")}</DisplayMath>);
+ act(() => { resize(); });
+ expect(observerCreations).toBe(1);
+ expect(tagWrites()).toHaveLength(1);
+ expect(formula.style.transform).toContain("scale(0.5)");
+ expect(frame.style.height).toBe("40px");
+ expect(frame.textContent).toBe("stream update(1)");
+
+ tagWidth = 60;
+ formulaWidth = 1000;
+ formulaHeight = 100;
+ rerender(<DisplayMath>{equation("completed")}</DisplayMath>);
+ expect(formula.style.getPropertyValue("--math-tag-width")).toBe("60px");
+ expect(tagWrites()).toHaveLength(2);
+ expect(formula.style.transform).toContain("scale(0.4)");
+ expect(frame.style.height).toBe("40px");
+});