perf(webui): avoid redundant math layout setup
This commit is contained in:
1 parent
336572de29
commit
24dd740d5b
5 files changed
+118
-15
No files matched your search
@@ -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})` }}>
|
||||
|
||||
Reference in new issue
Block a user