-
-
Notifications
You must be signed in to change notification settings - Fork 980
/
GestureDetector.tsx
651 lines (575 loc) · 20 KB
/
GestureDetector.tsx
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
import React, { useEffect, useRef } from 'react';
import {
GestureType,
HandlerCallbacks,
BaseGesture,
GestureRef,
CALLBACK_TYPE,
} from './gesture';
import { Reanimated, SharedValue } from './reanimatedWrapper';
import { registerHandler, unregisterHandler } from '../handlersRegistry';
import RNGestureHandlerModule from '../../RNGestureHandlerModule';
import {
baseGestureHandlerWithMonitorProps,
filterConfig,
findNodeHandle,
GestureTouchEvent,
GestureUpdateEvent,
GestureStateChangeEvent,
HandlerStateChangeEvent,
scheduleFlushOperations,
} from '../gestureHandlerCommon';
import {
GestureStateManager,
GestureStateManagerType,
} from './gestureStateManager';
import { flingGestureHandlerProps } from '../FlingGestureHandler';
import { forceTouchGestureHandlerProps } from '../ForceTouchGestureHandler';
import { longPressGestureHandlerProps } from '../LongPressGestureHandler';
import {
panGestureHandlerProps,
panGestureHandlerCustomNativeProps,
} from '../PanGestureHandler';
import { tapGestureHandlerProps } from '../TapGestureHandler';
import { State } from '../../State';
import { TouchEventType } from '../../TouchEventType';
import { ComposedGesture } from './gestureComposition';
import { ActionType } from '../../ActionType';
import { isFabric, tagMessage } from '../../utils';
import { getShadowNodeFromRef } from '../../getShadowNodeFromRef';
import { Platform } from 'react-native';
import type RNGestureHandlerModuleWeb from '../../RNGestureHandlerModule.web';
import { onGestureHandlerEvent } from './eventReceiver';
declare const global: {
isFormsStackingContext: (node: unknown) => boolean | null; // JSI function
};
const ALLOWED_PROPS = [
...baseGestureHandlerWithMonitorProps,
...tapGestureHandlerProps,
...panGestureHandlerProps,
...panGestureHandlerCustomNativeProps,
...longPressGestureHandlerProps,
...forceTouchGestureHandlerProps,
...flingGestureHandlerProps,
];
export type GestureConfigReference = {
config: GestureType[];
animatedEventHandler: unknown;
animatedHandlers: SharedValue<
HandlerCallbacks<Record<string, unknown>>[] | null
> | null;
firstExecution: boolean;
useReanimatedHook: boolean;
};
function convertToHandlerTag(ref: GestureRef): number {
if (typeof ref === 'number') {
return ref;
} else if (ref instanceof BaseGesture) {
return ref.handlerTag;
} else {
// @ts-ignore in this case it should be a ref either to gesture object or
// a gesture handler component, in both cases handlerTag property exists
return ref.current?.handlerTag ?? -1;
}
}
function extractValidHandlerTags(interactionGroup: GestureRef[] | undefined) {
return (
interactionGroup?.map(convertToHandlerTag)?.filter((tag) => tag > 0) ?? []
);
}
function dropHandlers(preparedGesture: GestureConfigReference) {
for (const handler of preparedGesture.config) {
RNGestureHandlerModule.dropGestureHandler(handler.handlerTag);
unregisterHandler(handler.handlerTag, handler.config.testId);
}
scheduleFlushOperations();
}
function checkGestureCallbacksForWorklets(gesture: GestureType) {
// if a gesture is explicitly marked to run on the JS thread there is no need to check
// if callbacks are worklets as the user is aware they will be ran on the JS thread
if (gesture.config.runOnJS) {
return;
}
const areSomeNotWorklets = gesture.handlers.isWorklet.includes(false);
const areSomeWorklets = gesture.handlers.isWorklet.includes(true);
// if some of the callbacks are worklets and some are not, and the gesture is not
// explicitly marked with `.runOnJS(true)` show an error
if (areSomeNotWorklets && areSomeWorklets) {
console.error(
tagMessage(
`Some of the callbacks in the gesture are worklets and some are not. Either make sure that all calbacks are marked as 'worklet' if you wish to run them on the UI thread or use '.runOnJS(true)' modifier on the gesture explicitly to run all callbacks on the JS thread.`
)
);
}
}
interface WebEventHandler {
onGestureHandlerEvent: (event: HandlerStateChangeEvent<unknown>) => void;
}
interface AttachHandlersConfig {
preparedGesture: GestureConfigReference;
gestureConfig: ComposedGesture | GestureType | undefined;
gesture: GestureType[];
viewTag: number;
webEventHandlersRef: React.RefObject<WebEventHandler>;
}
function attachHandlers({
preparedGesture,
gestureConfig,
gesture,
viewTag,
webEventHandlersRef,
}: AttachHandlersConfig) {
if (!preparedGesture.firstExecution) {
gestureConfig?.initialize();
} else {
preparedGesture.firstExecution = false;
}
// use setImmediate to extract handlerTags, because all refs should be initialized
// when it's ran
setImmediate(() => {
gestureConfig?.prepare();
});
for (const handler of gesture) {
checkGestureCallbacksForWorklets(handler);
RNGestureHandlerModule.createGestureHandler(
handler.handlerName,
handler.handlerTag,
filterConfig(handler.config, ALLOWED_PROPS)
);
registerHandler(handler.handlerTag, handler, handler.config.testId);
}
// use setImmediate to extract handlerTags, because all refs should be initialized
// when it's ran
setImmediate(() => {
for (const handler of gesture) {
let requireToFail: number[] = [];
if (handler.config.requireToFail) {
requireToFail = extractValidHandlerTags(handler.config.requireToFail);
}
let simultaneousWith: number[] = [];
if (handler.config.simultaneousWith) {
simultaneousWith = extractValidHandlerTags(
handler.config.simultaneousWith
);
}
RNGestureHandlerModule.updateGestureHandler(
handler.handlerTag,
filterConfig(handler.config, ALLOWED_PROPS, {
simultaneousHandlers: simultaneousWith,
waitFor: requireToFail,
})
);
}
scheduleFlushOperations();
});
preparedGesture.config = gesture;
for (const gesture of preparedGesture.config) {
const actionType = gesture.shouldUseReanimated
? ActionType.REANIMATED_WORKLET
: ActionType.JS_FUNCTION_NEW_API;
if (Platform.OS === 'web') {
(RNGestureHandlerModule.attachGestureHandler as typeof RNGestureHandlerModuleWeb.attachGestureHandler)(
gesture.handlerTag,
viewTag,
ActionType.JS_FUNCTION_OLD_API, // ignored on web
webEventHandlersRef
);
} else {
RNGestureHandlerModule.attachGestureHandler(
gesture.handlerTag,
viewTag,
actionType
);
}
}
if (preparedGesture.animatedHandlers) {
const isAnimatedGesture = (g: GestureType) => g.shouldUseReanimated;
preparedGesture.animatedHandlers.value = (gesture
.filter(isAnimatedGesture)
.map((g) => g.handlers) as unknown) as HandlerCallbacks<
Record<string, unknown>
>[];
}
}
function updateHandlers(
preparedGesture: GestureConfigReference,
gestureConfig: ComposedGesture | GestureType | undefined,
gesture: GestureType[]
) {
gestureConfig?.prepare();
for (let i = 0; i < gesture.length; i++) {
const handler = preparedGesture.config[i];
checkGestureCallbacksForWorklets(handler);
// only update handlerTag when it's actually different, it may be the same
// if gesture config object is wrapped with useMemo
if (gesture[i].handlerTag !== handler.handlerTag) {
gesture[i].handlerTag = handler.handlerTag;
gesture[i].handlers.handlerTag = handler.handlerTag;
}
}
// use setImmediate to extract handlerTags, because when it's ran, all refs should be updated
// and handlerTags in BaseGesture references should be updated in the loop above (we need to wait
// in case of external relations)
setImmediate(() => {
for (let i = 0; i < gesture.length; i++) {
const handler = preparedGesture.config[i];
handler.config = gesture[i].config;
handler.handlers = gesture[i].handlers;
const requireToFail = extractValidHandlerTags(
handler.config.requireToFail
);
const simultaneousWith = extractValidHandlerTags(
handler.config.simultaneousWith
);
RNGestureHandlerModule.updateGestureHandler(
handler.handlerTag,
filterConfig(handler.config, ALLOWED_PROPS, {
simultaneousHandlers: simultaneousWith,
waitFor: requireToFail,
})
);
registerHandler(handler.handlerTag, handler, handler.config.testId);
}
if (preparedGesture.animatedHandlers) {
const previousHandlersValue =
preparedGesture.animatedHandlers.value ?? [];
const newHandlersValue = (preparedGesture.config
.filter((g) => g.shouldUseReanimated) // ignore gestures that shouldn't run on UI
.map((g) => g.handlers) as unknown) as HandlerCallbacks<
Record<string, unknown>
>[];
// if amount of gesture configs changes, we need to update the callbacks in shared value
let shouldUpdateSharedValue =
previousHandlersValue.length !== newHandlersValue.length;
if (!shouldUpdateSharedValue) {
// if the amount is the same, we need to check if any of the configs inside has changed
for (let i = 0; i < newHandlersValue.length; i++) {
if (
// we can use the `gestureId` prop as it's unique for every config instance
newHandlersValue[i].gestureId !== previousHandlersValue[i].gestureId
) {
shouldUpdateSharedValue = true;
break;
}
}
}
if (shouldUpdateSharedValue) {
preparedGesture.animatedHandlers.value = newHandlersValue;
}
}
scheduleFlushOperations();
});
}
function needsToReattach(
preparedGesture: GestureConfigReference,
gesture: GestureType[]
) {
if (gesture.length !== preparedGesture.config.length) {
return true;
}
for (let i = 0; i < gesture.length; i++) {
if (
gesture[i].handlerName !== preparedGesture.config[i].handlerName ||
gesture[i].shouldUseReanimated !==
preparedGesture.config[i].shouldUseReanimated
) {
return true;
}
}
return false;
}
function useAnimatedGesture(
preparedGesture: GestureConfigReference,
needsRebuild: boolean
) {
if (!Reanimated) {
return;
}
function isStateChangeEvent(
event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent
): event is GestureStateChangeEvent {
'worklet';
// @ts-ignore Yes, the oldState prop is missing on GestureTouchEvent, that's the point
return event.oldState != null;
}
function isTouchEvent(
event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent
): event is GestureTouchEvent {
'worklet';
return event.eventType != null;
}
function getHandler(
type: CALLBACK_TYPE,
gesture: HandlerCallbacks<Record<string, unknown>>
) {
'worklet';
switch (type) {
case CALLBACK_TYPE.BEGAN:
return gesture.onBegin;
case CALLBACK_TYPE.START:
return gesture.onStart;
case CALLBACK_TYPE.UPDATE:
return gesture.onUpdate;
case CALLBACK_TYPE.CHANGE:
return gesture.onChange;
case CALLBACK_TYPE.END:
return gesture.onEnd;
case CALLBACK_TYPE.FINALIZE:
return gesture.onFinalize;
case CALLBACK_TYPE.TOUCHES_DOWN:
return gesture.onTouchesDown;
case CALLBACK_TYPE.TOUCHES_MOVE:
return gesture.onTouchesMove;
case CALLBACK_TYPE.TOUCHES_UP:
return gesture.onTouchesUp;
case CALLBACK_TYPE.TOUCHES_CANCELLED:
return gesture.onTouchesCancelled;
}
}
function touchEventTypeToCallbackType(
eventType: TouchEventType
): CALLBACK_TYPE {
'worklet';
switch (eventType) {
case TouchEventType.TOUCHES_DOWN:
return CALLBACK_TYPE.TOUCHES_DOWN;
case TouchEventType.TOUCHES_MOVE:
return CALLBACK_TYPE.TOUCHES_MOVE;
case TouchEventType.TOUCHES_UP:
return CALLBACK_TYPE.TOUCHES_UP;
case TouchEventType.TOUCHES_CANCELLED:
return CALLBACK_TYPE.TOUCHES_CANCELLED;
}
return CALLBACK_TYPE.UNDEFINED;
}
function runWorklet(
type: CALLBACK_TYPE,
gesture: HandlerCallbacks<Record<string, unknown>>,
event: GestureStateChangeEvent | GestureUpdateEvent | GestureTouchEvent,
...args: any[]
) {
'worklet';
const handler = getHandler(type, gesture);
if (gesture.isWorklet[type]) {
// @ts-ignore Logic below makes sure the correct event is send to the
// correct handler.
handler?.(event, ...args);
} else if (handler) {
console.warn(tagMessage('Animated gesture callback must be a worklet'));
}
}
// Hooks are called conditionally, but the condition is whether the
// react-native-reanimated is installed, which shouldn't change while running
// eslint-disable-next-line react-hooks/rules-of-hooks
const sharedHandlersCallbacks = Reanimated.useSharedValue<
HandlerCallbacks<Record<string, unknown>>[] | null
>(null);
// eslint-disable-next-line react-hooks/rules-of-hooks
const lastUpdateEvent = Reanimated.useSharedValue<
(GestureUpdateEvent | undefined)[]
>([]);
// not every gesture needs a state controller, init them lazily
const stateControllers: GestureStateManagerType[] = [];
const callback = (
event: GestureStateChangeEvent | GestureUpdateEvent | GestureTouchEvent
) => {
'worklet';
const currentCallback = sharedHandlersCallbacks.value;
if (!currentCallback) {
return;
}
for (let i = 0; i < currentCallback.length; i++) {
const gesture = currentCallback[i];
if (event.handlerTag === gesture.handlerTag) {
if (isStateChangeEvent(event)) {
if (
event.oldState === State.UNDETERMINED &&
event.state === State.BEGAN
) {
runWorklet(CALLBACK_TYPE.BEGAN, gesture, event);
} else if (
(event.oldState === State.BEGAN ||
event.oldState === State.UNDETERMINED) &&
event.state === State.ACTIVE
) {
runWorklet(CALLBACK_TYPE.START, gesture, event);
lastUpdateEvent.value[gesture.handlerTag] = undefined;
} else if (
event.oldState !== event.state &&
event.state === State.END
) {
if (event.oldState === State.ACTIVE) {
runWorklet(CALLBACK_TYPE.END, gesture, event, true);
}
runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, true);
} else if (
(event.state === State.FAILED || event.state === State.CANCELLED) &&
event.state !== event.oldState
) {
if (event.oldState === State.ACTIVE) {
runWorklet(CALLBACK_TYPE.END, gesture, event, false);
}
runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, false);
}
} else if (isTouchEvent(event)) {
if (!stateControllers[i]) {
stateControllers[i] = GestureStateManager.create(event.handlerTag);
}
if (event.eventType !== TouchEventType.UNDETERMINED) {
runWorklet(
touchEventTypeToCallbackType(event.eventType),
gesture,
event,
stateControllers[i]
);
}
} else {
runWorklet(CALLBACK_TYPE.UPDATE, gesture, event);
if (gesture.onChange && gesture.changeEventCalculator) {
runWorklet(
CALLBACK_TYPE.CHANGE,
gesture,
gesture.changeEventCalculator?.(
event,
lastUpdateEvent.value[gesture.handlerTag]
)
);
lastUpdateEvent.value[gesture.handlerTag] = event;
}
}
}
}
};
// eslint-disable-next-line react-hooks/rules-of-hooks
const event = Reanimated.useEvent(
callback,
['onGestureHandlerStateChange', 'onGestureHandlerEvent'],
needsRebuild
);
preparedGesture.animatedEventHandler = event;
preparedGesture.animatedHandlers = sharedHandlersCallbacks;
}
interface GestureDetectorProps {
gesture?: ComposedGesture | GestureType;
children?: React.ReactNode;
}
export const GestureDetector = (props: GestureDetectorProps) => {
const gestureConfig = props.gesture;
const gesture = gestureConfig?.toGestureArray?.() ?? [];
const useReanimatedHook = gesture.some((g) => g.shouldUseReanimated);
const viewRef = useRef(null);
const firstRenderRef = useRef(true);
const webEventHandlersRef = useRef<WebEventHandler>({
onGestureHandlerEvent: (e: HandlerStateChangeEvent<unknown>) => {
onGestureHandlerEvent(e.nativeEvent);
},
});
const preparedGesture = React.useRef<GestureConfigReference>({
config: gesture,
animatedEventHandler: null,
animatedHandlers: null,
firstExecution: true,
useReanimatedHook: useReanimatedHook,
}).current;
if (useReanimatedHook !== preparedGesture.useReanimatedHook) {
throw new Error(
tagMessage(
'You cannot change the thread the callbacks are ran on while the app is running'
)
);
}
// Reanimated event should be rebuilt only when gestures are reattached, otherwise
// config update will be enough as all necessary items are stored in shared values anyway
const needsToRebuildReanimatedEvent =
preparedGesture.firstExecution || needsToReattach(preparedGesture, gesture);
if (preparedGesture.firstExecution) {
gestureConfig?.initialize?.();
}
if (useReanimatedHook) {
// Whether animatedGesture or gesture is used shouldn't change while the app is running
// eslint-disable-next-line react-hooks/rules-of-hooks
useAnimatedGesture(preparedGesture, needsToRebuildReanimatedEvent);
}
useEffect(() => {
firstRenderRef.current = true;
const viewTag = findNodeHandle(viewRef.current) as number;
attachHandlers({
preparedGesture,
gestureConfig,
gesture,
viewTag,
webEventHandlersRef,
});
return () => {
dropHandlers(preparedGesture);
};
}, []);
useEffect(() => {
if (!firstRenderRef.current) {
const viewTag = findNodeHandle(viewRef.current) as number;
if (needsToReattach(preparedGesture, gesture)) {
dropHandlers(preparedGesture);
attachHandlers({
preparedGesture,
gestureConfig,
gesture,
viewTag,
webEventHandlersRef,
});
} else {
updateHandlers(preparedGesture, gestureConfig, gesture);
}
} else {
firstRenderRef.current = false;
}
}, [props]);
const refFunction = (ref: unknown) => {
if (ref !== null) {
//@ts-ignore Just setting the ref
viewRef.current = ref;
if (isFabric()) {
const node = getShadowNodeFromRef(ref);
if (global.isFormsStackingContext(node) === false) {
console.error(
tagMessage(
'GestureDetector has received a child that may get view-flattened. ' +
'\nTo prevent it from misbehaving you need to wrap the child with a `<View collapsable={false}>`.'
)
);
}
}
}
};
if (useReanimatedHook) {
return (
<AnimatedWrap
ref={refFunction}
onGestureHandlerEvent={preparedGesture.animatedEventHandler}>
{props.children}
</AnimatedWrap>
);
} else {
return <Wrap ref={refFunction}>{props.children}</Wrap>;
}
};
class Wrap extends React.Component<{
onGestureHandlerEvent?: unknown;
// implicit `children` prop has been removed in @types/react^18.0.0
children?: React.ReactNode;
}> {
render() {
// I don't think that fighting with types over such a simple function is worth it
// The only thing it does is add 'collapsable: false' to the child component
// to make sure it is in the native view hierarchy so the detector can find
// correct viewTag to attach to.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const child: any = React.Children.only(this.props.children);
return React.cloneElement(
child,
{ collapsable: false },
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
child.props.children
);
}
}
const AnimatedWrap = Reanimated?.default?.createAnimatedComponent(Wrap) ?? Wrap;