refactor: performance

This commit is contained in:
2026-03-12 21:01:43 +01:00
parent 92fdba7eef
commit 029bab8917
9 changed files with 109 additions and 47 deletions

View File

@@ -17,25 +17,34 @@ export { ViewportDisplayContext }
/**
* Must be rendered inside ReactFlowProvider. Subscribes to viewport once,
* maps zoom to displayMode with hysteresis, and provides it to descendants.
* maps zoom to displayMode with hysteresis. Throttles updates via rAF to avoid
* re-rendering all contextual nodes on every zoom tick.
*/
export function ViewportDisplayProvider({ children }: { children: React.ReactNode }) {
const { zoom } = useViewport()
const [displayMode, setDisplayMode] = useState<ViewportDisplayMode>(() =>
zoom <= CONTEXTUAL_ZOOM_THRESHOLD ? 'compact' : 'full'
)
const lastRef = useRef(displayMode)
const lastModeRef = useRef(displayMode)
const zoomRef = useRef(zoom)
const rafRef = useRef<number | null>(null)
zoomRef.current = zoom
useLayoutEffect(() => {
const low = CONTEXTUAL_ZOOM_THRESHOLD - HYSTERESIS
const high = CONTEXTUAL_ZOOM_THRESHOLD + HYSTERESIS
let next: ViewportDisplayMode = lastRef.current
if (zoom <= low) next = 'compact'
else if (zoom >= high) next = 'full'
if (next !== lastRef.current) {
lastRef.current = next
setDisplayMode(next)
}
if (rafRef.current !== null) return
rafRef.current = requestAnimationFrame(() => {
rafRef.current = null
const z = zoomRef.current
const low = CONTEXTUAL_ZOOM_THRESHOLD - HYSTERESIS
const high = CONTEXTUAL_ZOOM_THRESHOLD + HYSTERESIS
let next: ViewportDisplayMode = lastModeRef.current
if (z <= low) next = 'compact'
else if (z >= high) next = 'full'
if (next !== lastModeRef.current) {
lastModeRef.current = next
setDisplayMode(next)
}
})
}, [zoom])
return (