-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathindex.ts
More file actions
421 lines (377 loc) · 11.4 KB
/
index.ts
File metadata and controls
421 lines (377 loc) · 11.4 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/* global document */
import * as React from "react";
import {
AttachTouch,
SwipeDirections,
DOWN,
SwipeEventData,
HandledEvents,
LEFT,
RIGHT,
Setter,
ConfigurationOptions,
SwipeableDirectionCallbacks,
SwipeableHandlers,
SwipeableProps,
SwipeablePropsWithDefaultOptions,
SwipeableState,
SwipeCallback,
TapCallback,
UP,
Vector2,
} from "./types";
export {
LEFT,
RIGHT,
UP,
DOWN,
SwipeDirections,
SwipeEventData,
SwipeableDirectionCallbacks,
SwipeCallback,
TapCallback,
SwipeableHandlers,
SwipeableProps,
Vector2,
};
const defaultProps = {
delta: 10,
preventScrollOnSwipe: false,
rotationAngle: 0,
trackMouse: false,
trackTouch: true,
swipeDuration: Infinity,
touchEventOptions: { passive: true },
} satisfies ConfigurationOptions;
const initialState: SwipeableState = {
first: true,
initial: [0, 0],
start: 0,
swiping: false,
xy: [0, 0],
};
const mouseMove = "mousemove";
const mouseUp = "mouseup";
const touchEnd = "touchend";
const touchMove = "touchmove";
const touchStart = "touchstart";
function getDirection(
absX: number,
absY: number,
deltaX: number,
deltaY: number
): SwipeDirections {
if (absX > absY) {
if (deltaX > 0) {
return RIGHT;
}
return LEFT;
} else if (deltaY > 0) {
return DOWN;
}
return UP;
}
function rotateXYByAngle(pos: Vector2, angle: number): Vector2 {
if (angle === 0) return pos;
const angleInRadians = (Math.PI / 180) * angle;
const x =
pos[0] * Math.cos(angleInRadians) + pos[1] * Math.sin(angleInRadians);
const y =
pos[1] * Math.cos(angleInRadians) - pos[0] * Math.sin(angleInRadians);
return [x, y];
}
function getHandlers(
set: Setter,
handlerProps: { trackMouse: boolean | undefined }
): [
{
ref: (element: HTMLElement | null) => void;
onMouseDown?: (event: React.MouseEvent) => void;
},
AttachTouch
] {
const onStart = (event: HandledEvents) => {
const isTouch = "touches" in event;
// if more than a single touch don't track, for now...
if (isTouch && event.touches.length > 1) return;
set((state, props) => {
// setup mouse listeners on document to track swipe since swipe can leave container
if (props.trackMouse && !isTouch) {
document.addEventListener(mouseMove, onMove);
document.addEventListener(mouseUp, onUp);
}
const { clientX, clientY } = isTouch ? event.touches[0] : event;
const xy = rotateXYByAngle([clientX, clientY], props.rotationAngle);
props.onTouchStartOrOnMouseDown &&
props.onTouchStartOrOnMouseDown({ event });
return {
...state,
...initialState,
initial: xy.slice() as Vector2,
xy,
start: event.timeStamp || 0,
};
});
};
const onMove = (event: HandledEvents) => {
set((state, props) => {
const isTouch = "touches" in event;
// Discount a swipe if additional touches are present after
// a swipe has started.
if (isTouch && event.touches.length > 1) {
return state;
}
// if swipe has exceeded duration stop tracking
if (event.timeStamp - state.start > props.swipeDuration) {
return state.swiping ? { ...state, swiping: false } : state;
}
const { clientX, clientY } = isTouch ? event.touches[0] : event;
const [x, y] = rotateXYByAngle([clientX, clientY], props.rotationAngle);
const deltaX = x - state.xy[0];
const deltaY = y - state.xy[1];
const absX = Math.abs(deltaX);
const absY = Math.abs(deltaY);
const time = (event.timeStamp || 0) - state.start;
const velocity = Math.sqrt(absX * absX + absY * absY) / (time || 1);
const vxvy: Vector2 = [deltaX / (time || 1), deltaY / (time || 1)];
const dir = getDirection(absX, absY, deltaX, deltaY);
// if swipe is under delta and we have not started to track a swipe: skip update
const delta =
typeof props.delta === "number"
? props.delta
: props.delta[dir.toLowerCase() as Lowercase<SwipeDirections>] ||
defaultProps.delta;
if (absX < delta && absY < delta && !state.swiping) return state;
const eventData = {
absX,
absY,
deltaX,
deltaY,
dir,
event,
first: state.first,
initial: state.initial,
velocity,
vxvy,
};
// call onSwipeStart if present and is first swipe event
eventData.first && props.onSwipeStart && props.onSwipeStart(eventData);
// call onSwiping if present
props.onSwiping && props.onSwiping(eventData);
// track if a swipe is cancelable (handler for swiping or swiped(dir) exists)
// so we can call preventDefault if needed
let cancelablePageSwipe = false;
if (
props.onSwiping ||
props.onSwiped ||
props[`onSwiped${dir}` as keyof SwipeableDirectionCallbacks]
) {
cancelablePageSwipe = true;
}
if (
cancelablePageSwipe &&
props.preventScrollOnSwipe &&
props.trackTouch &&
event.cancelable
) {
event.preventDefault();
}
return {
...state,
// first is now always false
first: false,
eventData,
swiping: true,
};
});
};
const onEnd = (event: HandledEvents) => {
set((state, props) => {
let eventData: SwipeEventData | undefined;
if (state.swiping && state.eventData) {
// if swipe is less than duration fire swiped callbacks
if (event.timeStamp - state.start < props.swipeDuration) {
eventData = { ...state.eventData, event };
props.onSwiped && props.onSwiped(eventData);
const onSwipedDir =
props[
`onSwiped${eventData.dir}` as keyof SwipeableDirectionCallbacks
];
onSwipedDir && onSwipedDir(eventData);
}
} else {
props.onTap && props.onTap({ event });
}
props.onTouchEndOrOnMouseUp && props.onTouchEndOrOnMouseUp({ event });
return { ...state, ...initialState, eventData };
});
};
const cleanUpMouse = () => {
// safe to just call removeEventListener
document.removeEventListener(mouseMove, onMove);
document.removeEventListener(mouseUp, onUp);
};
const onUp = (e: HandledEvents) => {
cleanUpMouse();
onEnd(e);
};
/**
* The value of passive on touchMove depends on `preventScrollOnSwipe`:
* - true => { passive: false }
* - false => { passive: true } // Default
*
* NOTE: When preventScrollOnSwipe is true, we attempt to call preventDefault to prevent scroll.
*
* props.touchEventOptions can also be set for all touch event listeners,
* but for `touchmove` specifically when `preventScrollOnSwipe` it will
* supersede and force passive to false.
*
*/
const attachTouch: AttachTouch = (el, props) => {
let cleanup = () => {};
if (el && el.addEventListener) {
const baseOptions = {
...defaultProps.touchEventOptions,
...props.touchEventOptions,
};
// attach touch event listeners and handlers
const tls: [
typeof touchStart | typeof touchMove | typeof touchEnd,
(e: HandledEvents) => void,
{ passive: boolean }
][] = [
[touchStart, onStart, baseOptions],
// preventScrollOnSwipe option supersedes touchEventOptions.passive
[
touchMove,
onMove,
{
...baseOptions,
...(props.preventScrollOnSwipe ? { passive: false } : {}),
},
],
[touchEnd, onEnd, baseOptions],
];
tls.forEach(([e, h, o]) => {
el.addEventListener(e, h, o)
});
// return properly scoped cleanup method for removing listeners, options not required
cleanup = () => tls.forEach(([e, h]) => {
el.removeEventListener(e, h)
});
}
return cleanup;
};
const onRef = (el: HTMLElement | null) => {
// "inline" ref functions are called twice on render, once with null then again with DOM element
// ignore null here
if (el === null) return;
set((state, props) => {
// if the same DOM el as previous just return state
if (state.el === el) return state;
const addState: { cleanUpTouch?: () => void } = {};
// if new DOM el clean up old DOM and reset cleanUpTouch
if (state.el && state.el !== el && state.cleanUpTouch) {
state.cleanUpTouch();
addState.cleanUpTouch = void 0;
}
// only attach if we want to track touch
if (props.trackTouch && el) {
addState.cleanUpTouch = attachTouch(el, props);
}
// store event attached DOM el for comparison, clean up, and re-attachment
return { ...state, el, ...addState };
});
};
// set ref callback to attach touch event listeners
const output: { ref: typeof onRef; onMouseDown?: typeof onStart } = {
ref: onRef,
};
// if track mouse attach mouse down listener
if (handlerProps.trackMouse) {
output.onMouseDown = onStart;
}
return [output, attachTouch];
}
function updateTransientState(
state: SwipeableState,
props: SwipeablePropsWithDefaultOptions,
previousProps: SwipeablePropsWithDefaultOptions,
attachTouch: AttachTouch
) {
// if trackTouch is off or there is no el, then remove handlers if necessary and exit
if (!props.trackTouch || !state.el) {
if (state.cleanUpTouch) {
state.cleanUpTouch();
}
return {
...state,
cleanUpTouch: undefined,
};
}
// trackTouch is on, so if there are no handlers attached, attach them and exit
if (!state.cleanUpTouch) {
return {
...state,
cleanUpTouch: attachTouch(state.el, props),
};
}
// trackTouch is on and handlers are already attached, so if preventScrollOnSwipe changes value,
// remove and reattach handlers (this is required to update the passive option when attaching
// the handlers)
if (
props.preventScrollOnSwipe !== previousProps.preventScrollOnSwipe ||
props.touchEventOptions.passive !== previousProps.touchEventOptions.passive
) {
state.cleanUpTouch();
return {
...state,
cleanUpTouch: attachTouch(state.el, props),
};
}
return state;
}
export function useSwipeable(options: SwipeableProps): SwipeableHandlers {
const { trackMouse } = options;
const transientState = React.useRef({ ...initialState });
const transientProps = React.useRef<SwipeablePropsWithDefaultOptions>({
...defaultProps,
});
// track previous rendered props
const previousProps = React.useRef<SwipeablePropsWithDefaultOptions>({
...transientProps.current,
});
previousProps.current = { ...transientProps.current };
// update current render props & defaults
transientProps.current = {
...defaultProps,
...options,
};
// Force defaults for config properties
let defaultKey: keyof ConfigurationOptions;
for (defaultKey in defaultProps) {
if (transientProps.current[defaultKey] === void 0) {
(transientProps.current[defaultKey] as any) = defaultProps[defaultKey];
}
}
const [handlers, attachTouch] = React.useMemo(
() =>
getHandlers(
(stateSetter) => {
transientState.current = stateSetter(
transientState.current,
transientProps.current
);
},
{ trackMouse }
),
[trackMouse]
);
transientState.current = updateTransientState(
transientState.current,
transientProps.current,
previousProps.current,
attachTouch
);
return handlers;
}