import { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from "react"; import "./DisplayMath.css"; export function DisplayMath({ children }: { children: ReactNode }) { const frame = useRef(null); const content = useRef(null); const [layout, setLayout] = useState({ scale: 1, height: 0 }); const update = useCallback(() => { if (!frame.current || !content.current) return; const tag = content.current.querySelector(".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 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(); }; }, [update]); useLayoutEffect(update, [children, update]); return {children} ; }