Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

usePanZoom.ts

405 lines13.1 KB

1import { useCallback, useEffect, useRef } from "react"
2import type { RefObject } from "react"
3​
4interface PanZoomOptions {
5 onPan: (deltaX: number, deltaY: number) => void
6 onZoom: (newZoom: number, focalX?: number, focalY?: number) => void
7}
8​
9interface TouchPoint {
10 id: number
11 x: number
12 y: number
14​
15/**
16 * Calculate distance between two touch points
17 */
18function getTouchDistance(t1: TouchPoint, t2: TouchPoint): number {
19 const dx = t2.x - t1.x
20 const dy = t2.y - t1.y
21 return Math.sqrt(dx * dx + dy * dy)
23​
24/**
25 * Calculate center point between two touch points
26 */
27function getTouchCenter(t1: TouchPoint, t2: TouchPoint): { x: number; y: number } {
28 return {
29 x: (t1.x + t2.x) / 2,
30 y: (t1.y + t2.y) / 2,
31 }
33​
34// Double-tap detection constants
35const DOUBLE_TAP_DELAY = 300 // ms
36const DOUBLE_TAP_DISTANCE = 30 // px
37const DOUBLE_TAP_ZOOM_FACTOR = 2 // zoom in by 2x on double-tap
38​
39// Momentum scrolling constants (physics-based)
40const MOMENTUM_DECELERATION = 0.008 // px/ms² - how fast velocity decreases
41const MOMENTUM_MIN_VELOCITY = 0.05 // px/ms - minimum velocity to continue
42​
43/**
44 * Hook to handle pan and zoom interactions on an element.
45 * Supports mouse drag for panning, mouse wheel for zooming,
46 * and touch gestures (single touch pan, pinch to zoom, double-tap to zoom).
47 */
48export function usePanZoom(containerRef: RefObject<HTMLElement | null>, options: PanZoomOptions) {
49 const { onPan, onZoom } = options
50​
51 // Store callbacks in refs to avoid re-render cascades during momentum animation
52 const onPanRef = useRef(onPan)
53 const onZoomRef = useRef(onZoom)
54 onPanRef.current = onPan
55 onZoomRef.current = onZoom
56​
57 const isPanning = useRef(false)
58 const lastPos = useRef({ x: 0, y: 0 })
59 const currentZoom = useRef(1)
60​
61 // Touch state
62 const activeTouches = useRef<Map<number, TouchPoint>>(new Map())
63 const lastPinchDistance = useRef<number | null>(null)
64 const lastPinchCenter = useRef<{ x: number; y: number } | null>(null)
65​
66 // Double-tap detection
67 const lastTapTime = useRef(0)
68 const lastTapPos = useRef({ x: 0, y: 0 })
69​
70 // Momentum scrolling state - track previous and current for velocity calc
71 const prevMoveTime = useRef(0)
72 const prevMovePos = useRef({ x: 0, y: 0 })
73 const currMoveTime = useRef(0)
74 const currMovePos = useRef({ x: 0, y: 0 })
75 const momentumAnimationId = useRef<number | null>(null)
76 const velocity = useRef({ x: 0, y: 0 }) // px/ms
77 const lastFrameTime = useRef(0)
78​
79 // Setter for external zoom sync
80 const setCurrentZoom = useCallback((zoom: number) => {
81 currentZoom.current = zoom
82 }, [])
83​
84 // Stop momentum animation
85 const stopMomentum = useCallback(() => {
86 if (momentumAnimationId.current !== null) {
87 cancelAnimationFrame(momentumAnimationId.current)
88 momentumAnimationId.current = null
89 }
90 velocity.current = { x: 0, y: 0 }
91 }, [])
92​
93 // Start momentum animation using physics-based deceleration
94 const startMomentum = useCallback(() => {
95 lastFrameTime.current = 0
96​
97 const animate = (currentTime: number) => {
98 // First frame: use 16ms, subsequent frames: use actual delta
99 const deltaTime = lastFrameTime.current === 0 ? 16 : currentTime - lastFrameTime.current
100 lastFrameTime.current = currentTime
101​
102 const vx = velocity.current.x
103 const vy = velocity.current.y
104 const speed = Math.sqrt(vx * vx + vy * vy)
105​
106 // Check if velocity is below threshold
107 if (speed < MOMENTUM_MIN_VELOCITY) {
108 momentumAnimationId.current = null
109 return
110 }
111​
112 // Calculate displacement for this frame: v * dt
113 const dx = vx * deltaTime
114 const dy = vy * deltaTime
115​
116 onPanRef.current(dx, dy)
117​
118 // Apply deceleration: reduce velocity magnitude
119 // v_new = v - (deceleration * dt) in the direction of motion
120 const decelAmount = MOMENTUM_DECELERATION * deltaTime
121 if (speed > decelAmount) {
122 const ratio = (speed - decelAmount) / speed
123 velocity.current.x *= ratio
124 velocity.current.y *= ratio
125 } else {
126 velocity.current = { x: 0, y: 0 }
127 }
128​
129 // Continue animation
130 momentumAnimationId.current = requestAnimationFrame(animate)
131 }
132​
133 momentumAnimationId.current = requestAnimationFrame(animate)
134 }, [])
135​
136 const handleMouseDown = useCallback((e: MouseEvent) => {
137 if (e.button === 0) {
138 // Left mouse button
139 isPanning.current = true
140 lastPos.current = { x: e.clientX, y: e.clientY }
141 }
142 }, [])
143​
144 const handleMouseMove = useCallback((e: MouseEvent) => {
145 if (isPanning.current) {
146 const deltaX = e.clientX - lastPos.current.x
147 const deltaY = e.clientY - lastPos.current.y
148 lastPos.current = { x: e.clientX, y: e.clientY }
149 onPanRef.current(deltaX, deltaY)
150 }
151 }, [])
152​
153 const handleMouseUp = useCallback(() => {
154 isPanning.current = false
155 }, [])
156​
157 const handleWheel = useCallback(
158 (e: WheelEvent) => {
159 e.preventDefault()
160​
161 const container = containerRef.current
162 if (!container) return
163​
164 const rect = container.getBoundingClientRect()
165 const focalX = e.clientX - rect.left
166 const focalY = e.clientY - rect.top
167​
168 // Calculate zoom factor based on wheel delta
169 const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1
170 const newZoom = currentZoom.current * zoomFactor
171 currentZoom.current = newZoom
172​
173 onZoomRef.current(newZoom, focalX, focalY)
174 },
175 [containerRef],
176 )
177​
178 // Touch event handlers
179 const handleTouchStart = useCallback(
180 (e: TouchEvent) => {
181 e.preventDefault()
182​
183 // Stop any ongoing momentum animation
184 stopMomentum()
185​
186 const container = containerRef.current
187 if (!container) return
188​
189 const rect = container.getBoundingClientRect()
190​
191 // Track all new touches
192 for (const touch of Array.from(e.changedTouches)) {
193 activeTouches.current.set(touch.identifier, {
194 id: touch.identifier,
195 x: touch.clientX - rect.left,
196 y: touch.clientY - rect.top,
197 })
198 }
199​
200 const touchCount = activeTouches.current.size
201​
202 if (touchCount === 1) {
203 // Single touch - check for double-tap
204 const now = Date.now()
205 const touches = Array.from(activeTouches.current.values())
206 const touch = touches[0]
207​
208 const timeDiff = now - lastTapTime.current
209 const dx = touch.x - lastTapPos.current.x
210 const dy = touch.y - lastTapPos.current.y
211 const distance = Math.sqrt(dx * dx + dy * dy)
212​
213 if (timeDiff < DOUBLE_TAP_DELAY && distance < DOUBLE_TAP_DISTANCE) {
214 // Double-tap detected - zoom in
215 const newZoom = currentZoom.current * DOUBLE_TAP_ZOOM_FACTOR
216 currentZoom.current = newZoom
217 onZoomRef.current(newZoom, touch.x, touch.y)
218 lastTapTime.current = 0 // Reset to prevent triple-tap
219 } else {
220 lastTapTime.current = now
221 lastTapPos.current = { x: touch.x, y: touch.y }
222 }
223​
224 // Set up for panning and momentum tracking
225 lastPos.current = { x: touch.x, y: touch.y }
226 prevMovePos.current = { x: touch.x, y: touch.y }
227 prevMoveTime.current = now
228 currMovePos.current = { x: touch.x, y: touch.y }
229 currMoveTime.current = now
230 } else if (touchCount === 2) {
231 // Two touches - initialize pinch
232 const touches = Array.from(activeTouches.current.values())
233 lastPinchDistance.current = getTouchDistance(touches[0], touches[1])
234 lastPinchCenter.current = getTouchCenter(touches[0], touches[1])
235 }
236 },
237 [containerRef, stopMomentum],
238 )
239​
240 const handleTouchMove = useCallback(
241 (e: TouchEvent) => {
242 e.preventDefault()
243​
244 const container = containerRef.current
245 if (!container) return
246​
247 const rect = container.getBoundingClientRect()
248​
249 // Update touch positions
250 for (const touch of Array.from(e.changedTouches)) {
251 if (activeTouches.current.has(touch.identifier)) {
252 activeTouches.current.set(touch.identifier, {
253 id: touch.identifier,
254 x: touch.clientX - rect.left,
255 y: touch.clientY - rect.top,
256 })
257 }
258 }
259​
260 const touchCount = activeTouches.current.size
261​
262 if (touchCount === 1) {
263 // Single touch - pan
264 const touches = Array.from(activeTouches.current.values())
265 const touch = touches[0]
266 const deltaX = touch.x - lastPos.current.x
267 const deltaY = touch.y - lastPos.current.y
268​
269 // Track for momentum calculation - shift current to previous, then update current
270 prevMoveTime.current = currMoveTime.current
271 prevMovePos.current = { ...currMovePos.current }
272 currMoveTime.current = performance.now()
273 currMovePos.current = { x: touch.x, y: touch.y }
274​
275 lastPos.current = { x: touch.x, y: touch.y }
276 onPanRef.current(deltaX, deltaY)
277 } else if (touchCount === 2) {
278 // Two touches - pinch to zoom and pan
279 const touches = Array.from(activeTouches.current.values())
280 const currentDistance = getTouchDistance(touches[0], touches[1])
281 const currentCenter = getTouchCenter(touches[0], touches[1])
282​
283 if (lastPinchDistance.current !== null && lastPinchCenter.current !== null) {
284 // Calculate zoom
285 const scale = currentDistance / lastPinchDistance.current
286 const newZoom = currentZoom.current * scale
287 currentZoom.current = newZoom
288 onZoomRef.current(newZoom, currentCenter.x, currentCenter.y)
289​
290 // Also pan while pinching
291 const deltaX = currentCenter.x - lastPinchCenter.current.x
292 const deltaY = currentCenter.y - lastPinchCenter.current.y
293 onPanRef.current(deltaX, deltaY)
294 }
295​
296 lastPinchDistance.current = currentDistance
297 lastPinchCenter.current = currentCenter
298 }
299 },
300 [containerRef],
301 )
302​
303 const handleTouchEnd = useCallback(
304 (e: TouchEvent) => {
305 const wasOneFinger = activeTouches.current.size === 1
306​
307 // Remove ended touches
308 for (const touch of Array.from(e.changedTouches)) {
309 activeTouches.current.delete(touch.identifier)
310 }
311​
312 // Reset pinch state when fewer than 2 touches
313 if (activeTouches.current.size < 2) {
314 lastPinchDistance.current = null
315 lastPinchCenter.current = null
316 }
317​
318 // Start momentum if releasing from single-finger pan
319 if (wasOneFinger && activeTouches.current.size === 0) {
320 // Calculate velocity from the last two tracked positions
321 const dt = currMoveTime.current - prevMoveTime.current
322 const dx = currMovePos.current.x - prevMovePos.current.x
323 const dy = currMovePos.current.y - prevMovePos.current.y
324​
325 if (dt > 0 && dt < 200) {
326 // Calculate velocity in px/ms
327 const vx = dx / dt
328 const vy = dy / dt
329 const speed = Math.sqrt(vx * vx + vy * vy)
330​
331 if (speed > MOMENTUM_MIN_VELOCITY) {
332 velocity.current = { x: vx, y: vy }
333 startMomentum()
334 }
335 }
336 }
337​
338 // Update last position if still have one touch
339 if (activeTouches.current.size === 1) {
340 const touches = Array.from(activeTouches.current.values())
341 const now = performance.now()
342 lastPos.current = { x: touches[0].x, y: touches[0].y }
343 prevMovePos.current = { x: touches[0].x, y: touches[0].y }
344 prevMoveTime.current = now
345 currMovePos.current = { x: touches[0].x, y: touches[0].y }
346 currMoveTime.current = now
347 }
348 },
349 [containerRef, startMomentum],
350 )
351​
352 const handleTouchCancel = useCallback(() => {
353 // Clear all touches on cancel
354 activeTouches.current.clear()
355 lastPinchDistance.current = null
356 lastPinchCenter.current = null
357 stopMomentum()
358 }, [stopMomentum])
359​
360 useEffect(() => {
361 const container = containerRef.current
362 if (!container) return
363​
364 // Mouse events
365 container.addEventListener(`mousedown`, handleMouseDown)
366 window.addEventListener(`mousemove`, handleMouseMove)
367 window.addEventListener(`mouseup`, handleMouseUp)
368 container.addEventListener(`wheel`, handleWheel, { passive: false })
369​
370 // Touch events
371 container.addEventListener(`touchstart`, handleTouchStart, {
372 passive: false,
373 })
374 container.addEventListener(`touchmove`, handleTouchMove, { passive: false })
375 container.addEventListener(`touchend`, handleTouchEnd)
376 container.addEventListener(`touchcancel`, handleTouchCancel)
377​
378 return () => {
379 container.removeEventListener(`mousedown`, handleMouseDown)
380 window.removeEventListener(`mousemove`, handleMouseMove)
381 window.removeEventListener(`mouseup`, handleMouseUp)
382 container.removeEventListener(`wheel`, handleWheel)
383 container.removeEventListener(`touchstart`, handleTouchStart)
384 container.removeEventListener(`touchmove`, handleTouchMove)
385 container.removeEventListener(`touchend`, handleTouchEnd)
386 container.removeEventListener(`touchcancel`, handleTouchCancel)
387 // Stop momentum on cleanup
388 if (momentumAnimationId.current !== null) {
389 cancelAnimationFrame(momentumAnimationId.current)
390 }
391 }
392 }, [
393 containerRef,
394 handleMouseDown,
395 handleMouseMove,
396 handleMouseUp,
397 handleWheel,
398 handleTouchStart,
399 handleTouchMove,
400 handleTouchEnd,
401 handleTouchCancel,
402 ])
403​
404 return { setCurrentZoom }