tldraw/hooks/useCamera.ts

35 lines
932 B
TypeScript
Raw Normal View History

2021-06-21 21:35:28 +00:00
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
2021-06-03 12:06:39 +00:00
import React, { useEffect } from 'react'
import state from 'state'
import storage from 'state/storage'
2021-06-29 12:00:59 +00:00
import tld from 'utils/tld'
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-29 12:00:59 +00:00
let prev = tld.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-29 12:00:59 +00:00
const { point, zoom } = tld.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]})`
)
storage.savePageState(state.data)
2021-05-09 13:04:42 +00:00
2021-06-29 12:00:59 +00:00
prev = tld.getCurrentCamera(state.data)
2021-06-03 12:06:39 +00:00
}
2021-05-09 13:04:42 +00:00
})
}, [state])
}