-
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathuseTrackpadGesture.ts
More file actions
294 lines (256 loc) · 7.59 KB
/
useTrackpadGesture.ts
File metadata and controls
294 lines (256 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { useRef, useState } from "react"
import {
PINCH_THRESHOLD,
TOUCH_MOVE_THRESHOLD,
TOUCH_TIMEOUT,
calculateAccelerationMult,
} from "../utils/math"
interface TrackedTouch {
identifier: number
pageX: number
pageY: number
pageXStart: number
pageYStart: number
timeStamp: number
}
const getTouchDistance = (a: TrackedTouch, b: TrackedTouch): number => {
const dx = a.pageX - b.pageX
const dy = a.pageY - b.pageY
return Math.sqrt(dx * dx + dy * dy)
}
const BUTTON_MAP: Record<number, "left" | "right" | "middle"> = {
1: "left",
2: "right",
3: "middle",
}
export const useTrackpadGesture = (
send: (msg: unknown) => void,
scrollMode: boolean,
sensitivity = 1.5,
invertScroll = false,
axisThreshold = 2.5,
) => {
const [isTracking, setIsTracking] = useState(false)
// Refs for tracking state (avoids re-renders during rapid movement)
const ongoingTouches = useRef<Map<number, TrackedTouch>>(new Map())
const moved = useRef(false)
const startTimeStamp = useRef(0)
const releasedCount = useRef(0)
const dragging = useRef(false)
const draggingTimeout = useRef<NodeJS.Timeout | null>(null)
const lastPinchDist = useRef<number | null>(null)
const pinching = useRef(false)
const processMovement = (sumX: number, sumY: number) => {
const touchCount = ongoingTouches.current.size
if (dragging.current) {
send({
type: "move",
dx: Math.round(sumX * sensitivity * 10) / 10,
dy: Math.round(sumY * sensitivity * 10) / 10,
})
return
}
const invertMult = invertScroll ? -1 : 1
if (!scrollMode && touchCount === 2) {
const touches = Array.from(ongoingTouches.current.values())
const dist = getTouchDistance(touches[0], touches[1])
const delta =
lastPinchDist.current !== null ? dist - lastPinchDist.current : 0
if (pinching.current || Math.abs(delta) > PINCH_THRESHOLD) {
pinching.current = true
lastPinchDist.current = dist
send({ type: "zoom", delta: delta * sensitivity * invertMult })
} else {
lastPinchDist.current = dist
send({
type: "scroll",
dx: -sumX * sensitivity * invertMult,
dy: -sumY * sensitivity * invertMult,
})
}
} else if (scrollMode || touchCount === 2) {
let scrollDx = sumX
let scrollDy = sumY
if (scrollMode) {
const absDx = Math.abs(scrollDx)
const absDy = Math.abs(scrollDy)
if (absDx > absDy * axisThreshold) {
scrollDy = 0
} else if (absDy > absDx * axisThreshold) {
scrollDx = 0
}
}
send({
type: "scroll",
dx: Math.round(-scrollDx * sensitivity * 10 * invertMult) / 10,
dy: Math.round(-scrollDy * sensitivity * 10 * invertMult) / 10,
})
} else if (touchCount === 1) {
send({
type: "move",
dx: Math.round(sumX * sensitivity * 10) / 10,
dy: Math.round(sumY * sensitivity * 10) / 10,
})
}
}
const handleDraggingTimeout = () => {
draggingTimeout.current = null
send({ type: "click", button: "left", press: false })
}
const handleTouchStart = (e: React.TouchEvent) => {
if (ongoingTouches.current.size === 0) {
startTimeStamp.current = e.timeStamp
moved.current = false
}
const touches = e.changedTouches
for (let i = 0; i < touches.length; i++) {
const touch = touches[i]
ongoingTouches.current.set(touch.identifier, {
identifier: touch.identifier,
pageX: touch.pageX,
pageY: touch.pageY,
pageXStart: touch.pageX,
pageYStart: touch.pageY,
timeStamp: e.timeStamp,
})
}
if (ongoingTouches.current.size === 2) {
const touches = Array.from(ongoingTouches.current.values())
lastPinchDist.current = getTouchDistance(touches[0], touches[1])
pinching.current = false
}
setIsTracking(true)
// If we're in dragging timeout, convert to actual drag
if (draggingTimeout.current) {
clearTimeout(draggingTimeout.current)
draggingTimeout.current = null
dragging.current = true
}
}
const handleTouchMove = (e: React.TouchEvent) => {
const touches = e.changedTouches
let sumX = 0
let sumY = 0
let movedTouchesCount = 0
const touchCount = ongoingTouches.current.size
for (let i = 0; i < touches.length; i++) {
const touch = touches[i]
const tracked = ongoingTouches.current.get(touch.identifier)
if (!tracked) continue
movedTouchesCount++
// Check if we've moved enough to consider this a "move" gesture
if (!moved.current) {
const distSq =
(touch.pageX - tracked.pageXStart) ** 2 +
(touch.pageY - tracked.pageYStart) ** 2
const thresholdIndex = Math.min(
touchCount - 1,
TOUCH_MOVE_THRESHOLD.length - 1,
)
const threshold = TOUCH_MOVE_THRESHOLD[thresholdIndex]
const thresholdSq = threshold * threshold
if (
distSq > thresholdSq ||
e.timeStamp - startTimeStamp.current >= TOUCH_TIMEOUT
) {
moved.current = true
}
}
// Calculate delta with acceleration
const dx = touch.pageX - tracked.pageX
const dy = touch.pageY - tracked.pageY
const timeDelta = e.timeStamp - tracked.timeStamp
if (timeDelta > 0) {
const speedX = (Math.abs(dx) / timeDelta) * 1000
const speedY = (Math.abs(dy) / timeDelta) * 1000
sumX += dx * calculateAccelerationMult(speedX)
sumY += dy * calculateAccelerationMult(speedY)
}
// Update tracked position
tracked.pageX = touch.pageX
tracked.pageY = touch.pageY
tracked.timeStamp = e.timeStamp
}
// Normalize movement by number of touches that actually moved to prevent sensitivity doubling
if (moved.current && movedTouchesCount > 0) {
processMovement(sumX / movedTouchesCount, sumY / movedTouchesCount)
}
}
const handleTouchEnd = (e: React.TouchEvent) => {
const touches = e.changedTouches
for (let i = 0; i < touches.length; i++) {
if (ongoingTouches.current.has(touches[i].identifier)) {
ongoingTouches.current.delete(touches[i].identifier)
releasedCount.current += 1
}
}
if (ongoingTouches.current.size < 2) {
lastPinchDist.current = null
pinching.current = false
}
// Mark as moved if too many fingers
if (releasedCount.current > TOUCH_MOVE_THRESHOLD.length) {
moved.current = true
}
// All fingers lifted
if (ongoingTouches.current.size === 0 && releasedCount.current >= 1) {
setIsTracking(false)
// Release drag if active
if (dragging.current) {
dragging.current = false
send({ type: "click", button: "left", press: false })
}
// Handle tap/click if not moved and within timeout
if (
!moved.current &&
e.timeStamp - startTimeStamp.current < TOUCH_TIMEOUT
) {
const button = BUTTON_MAP[releasedCount.current]
if (button) {
send({ type: "click", button, press: true })
// For left click, set up drag timeout
if (button === "left") {
draggingTimeout.current = setTimeout(
handleDraggingTimeout,
TOUCH_TIMEOUT,
)
} else {
send({ type: "click", button, press: false })
}
}
}
releasedCount.current = 0
}
}
const handleTouchCancel = () => {
// Clear all active touches
ongoingTouches.current.clear()
// Reset gesture state
setIsTracking(false)
moved.current = false
releasedCount.current = 0
// Reset pinch state
lastPinchDist.current = null
pinching.current = false
// Clear dragging timeout if exists
if (draggingTimeout.current) {
clearTimeout(draggingTimeout.current)
draggingTimeout.current = null
}
// Release drag if active
if (dragging.current) {
dragging.current = false
}
// 🔥 Safety: ensure no stuck mouse state
send({ type: "click", button: "left", press: false })
}
return {
isTracking,
handlers: {
onTouchStart: handleTouchStart,
onTouchMove: handleTouchMove,
onTouchEnd: handleTouchEnd,
onTouchCancel: handleTouchCancel,
},
}
}