tldraw/hooks/useCamera.ts

36 lines
903 B
TypeScript
Raw Normal View History

2021-06-03 12:06:39 +00:00
import React, { useEffect } from 'react'
import state from 'state'
import { getCurrentCamera } from 'utils/utils'
2021-05-09 13:04:42 +00:00
/**
* When the state's camera changes, update the transform of
* the SVG group to reflect the correct zoom and pan.
* @param ref
*/
2021-05-09 21:22:25 +00:00
export default function useCamera(ref: React.MutableRefObject<SVGGElement>) {
2021-05-09 13:04:42 +00:00
useEffect(() => {
2021-06-03 12:06:39 +00:00
let prev = getCurrentCamera(state.data)
2021-05-09 13:04:42 +00:00
2021-06-03 12:06:39 +00:00
return state.onUpdate(() => {
2021-05-09 13:04:42 +00:00
const g = ref.current
if (!g) return
2021-06-03 12:06:39 +00:00
const { point, zoom } = getCurrentCamera(state.data)
2021-05-09 13:04:42 +00:00
2021-06-03 12:06:39 +00:00
if (point !== prev.point || zoom !== prev.zoom) {
2021-05-09 13:04:42 +00:00
g.setAttribute(
2021-06-03 12:06:39 +00:00
'transform',
2021-05-09 13:04:42 +00:00
`scale(${zoom}) translate(${point[0]} ${point[1]})`
)
2021-06-03 12:06:39 +00:00
localStorage.setItem(
'code_slate_camera',
JSON.stringify({ point, zoom })
)
2021-05-09 13:04:42 +00:00
2021-06-03 12:06:39 +00:00
prev = getCurrentCamera(state.data)
}
2021-05-09 13:04:42 +00:00
})
}, [state])
}