|
| 1 | +import { useDebouncedCallback, useSyncedRef } from '@react-hookz/web'; |
| 2 | +import { useFrame, useThree } from '@react-three/fiber'; |
| 3 | +import { useLayoutEffect } from 'react'; |
| 4 | +import { useStore } from 'zustand'; |
| 5 | + |
| 6 | +import { useVisCanvasContext } from '../vis/shared/VisCanvasProvider'; |
| 7 | +import { useMoveCameraTo } from './hooks'; |
| 8 | +import { useKeepZoomStore } from './keep-zoom-store'; |
| 9 | + |
| 10 | +interface Props { |
| 11 | + visKey: string; |
| 12 | +} |
| 13 | + |
| 14 | +function KeepZoom(props: Props) { |
| 15 | + const { visKey } = props; |
| 16 | + const { abscissaConfig, ordinateConfig } = useVisCanvasContext(); |
| 17 | + const keyRef = useSyncedRef( |
| 18 | + `${visKey}_${abscissaConfig.visDomain.toString()}_${ordinateConfig.visDomain.toString()}`, |
| 19 | + ); |
| 20 | + |
| 21 | + const store = useKeepZoomStore(); |
| 22 | + const setState = useStore(store, (state) => state.setState); |
| 23 | + const setStateDebounced = useDebouncedCallback(setState, [setState], 100); |
| 24 | + |
| 25 | + const camera = useThree((state) => state.camera); |
| 26 | + const moveCameraToRef = useSyncedRef(useMoveCameraTo()); |
| 27 | + |
| 28 | + /* Restore camera position and scale on mount if current key matches persisted key from store. |
| 29 | + * Synced refs are to ensure that the effect runs only on mount and not when the axis domains change. */ |
| 30 | + useLayoutEffect(() => { |
| 31 | + const { key, scale, position } = store.getState(); // non-reactive state to avoid render loop |
| 32 | + |
| 33 | + if (keyRef.current === key) { |
| 34 | + camera.scale.copy(scale); |
| 35 | + moveCameraToRef.current(position); |
| 36 | + } |
| 37 | + }, [keyRef, moveCameraToRef, camera, store]); |
| 38 | + |
| 39 | + // Save camera position and scale on change |
| 40 | + useFrame(() => { |
| 41 | + setStateDebounced(keyRef.current, camera.position, camera.scale); |
| 42 | + }); |
| 43 | + |
| 44 | + return null; |
| 45 | +} |
| 46 | + |
| 47 | +export default KeepZoom; |
0 commit comments