perf(webui): avoid redundant math layout setup

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-24 20:56:12 +08:00
1 parent 336572de29
commit 24dd740d5b
5 files changed
+118 -15

No files matched your search

+15 -12
View File
@@ -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})` }}>
+41 -3
View File
@@ -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");
});