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'
|
2021-06-16 12:09:45 +00:00
|
|
|
import storage from 'state/storage'
|
2021-06-24 08:18:14 +00:00
|
|
|
import { getCurrentCamera } from '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-05-16 07:09:46 +00:00
|
|
|
|
2021-06-16 12:09:45 +00:00
|
|
|
storage.savePageState(state.data)
|
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])
|
|
|
|
}
|