refactor: performance
This commit is contained in:
@@ -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 (
|
||||
|
||||
Reference in New Issue
Block a user