You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

useZoomEvents.ts 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { useRef } from 'react'
  2. import state from 'state'
  3. import inputs from 'state/inputs'
  4. import vec from 'utils/vec'
  5. import { useGesture } from 'react-use-gesture'
  6. import { fastPanUpdate, fastPinchCamera, fastZoomUpdate } from 'state/hacks'
  7. /**
  8. * Capture zoom gestures (pinches, wheels and pans) and send to the state.
  9. * @param ref
  10. * @returns
  11. */
  12. export default function useZoomEvents() {
  13. const rPinchDa = useRef<number[] | undefined>(undefined)
  14. const rPinchPoint = useRef<number[] | undefined>(undefined)
  15. useGesture(
  16. {
  17. onWheel: ({ event, delta }) => {
  18. if (event.ctrlKey) {
  19. const { point } = inputs.wheel(event as WheelEvent)
  20. fastZoomUpdate(point, delta[1])
  21. return
  22. }
  23. if (state.isInAny('pointing', 'drawing')) {
  24. fastPanUpdate(delta)
  25. return
  26. }
  27. state.send('PANNED_CAMERA', {
  28. delta,
  29. ...inputs.wheel(event as WheelEvent),
  30. })
  31. },
  32. onPinch: ({ pinching, da, origin }) => {
  33. if (!pinching) {
  34. state.send('STOPPED_PINCHING')
  35. rPinchDa.current = undefined
  36. rPinchPoint.current = undefined
  37. return
  38. }
  39. if (rPinchPoint.current === undefined) {
  40. state.send('STARTED_PINCHING')
  41. rPinchDa.current = da
  42. rPinchPoint.current = origin
  43. }
  44. const [distanceDelta] = vec.sub(rPinchDa.current, da)
  45. fastPinchCamera(
  46. origin,
  47. vec.sub(rPinchPoint.current, origin),
  48. distanceDelta
  49. )
  50. rPinchDa.current = da
  51. rPinchPoint.current = origin
  52. },
  53. },
  54. {
  55. domTarget: document.body,
  56. eventOptions: { passive: false },
  57. }
  58. )
  59. }