Skip to content
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React, { RefObject, useCallback, useRef, useState } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import HostGestureDetector from '../HostGestureDetector';
import {
VirtualChildren,
VirtualChild,
GestureHandlerEvent,
DetectorCallbacks,
} from '../../types';
import { DetectorContext } from './useDetectorContext';
import { DetectorContext, DetectorContextValue } from './useDetectorContext';
import { Reanimated } from '../../../handlers/gestures/reanimatedWrapper';
import { configureRelations, ensureNativeDetectorComponent } from '../utils';
import { isComposedGesture } from '../../hooks/utils/relationUtils';
Expand All @@ -21,61 +21,57 @@ export function InterceptingGestureDetector<THandlerData, TConfig>({
gesture,
children,
}: InterceptingGestureDetectorProps<THandlerData, TConfig>) {
const [virtualChildren, setVirtualChildren] = useState<VirtualChildren[]>([]);

const virtualMethods = useRef<
Map<number, RefObject<DetectorCallbacks<unknown>>>
>(new Map());

const [shouldUseReanimated, setShouldUseReanimated] = useState(
gesture ? gesture.config.shouldUseReanimatedDetector : false
const [virtualChildren, setVirtualChildren] = useState<VirtualChild[]>([]);

const shouldUseReanimatedDetector = useMemo(
() =>
virtualChildren.reduce(
(acc, child) => acc || child.forReanimated,
gesture?.config.shouldUseReanimatedDetector ?? false
),
[virtualChildren, gesture]
);
const [dispatchesAnimatedEvents, setDispatchesAnimatedEvents] = useState(
gesture ? gesture.config.dispatchesAnimatedEvents : false

const dispatchesAnimatedEvents = useMemo(
() =>
virtualChildren.reduce(
(acc, child) => acc || child.forAnimated,
gesture?.config.dispatchesAnimatedEvents ?? false
),
[virtualChildren, gesture]
);

const NativeDetectorComponent = dispatchesAnimatedEvents
? AnimatedNativeDetector
: shouldUseReanimated
: shouldUseReanimatedDetector
? ReanimatedNativeDetector
: HostGestureDetector;
Comment on lines 44 to 48
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we throw an error when both shouldUseReanimatedDetector and dispatchesAnimatedEvents are true?


const register = useCallback(
(
child: VirtualChildren,
methods: RefObject<DetectorCallbacks<unknown>>,
forReanimated: boolean | undefined,
forAnimated: boolean | undefined
) => {
setShouldUseReanimated(!!forReanimated);
setDispatchesAnimatedEvents(!!forAnimated);

setVirtualChildren((prev) => {
const index = prev.findIndex((c) => c.viewTag === child.viewTag);
if (index !== -1) {
const updated = [...prev];
updated[index] = child;
return updated;
}

return [...prev, child];
});

child.handlerTags.forEach((tag) => {
virtualMethods.current.set(tag, methods);
});
},
[]
);
const register = useCallback((child: VirtualChild) => {
setVirtualChildren((prev) => {
const index = prev.findIndex((c) => c.viewTag === child.viewTag);
if (index !== -1) {
const updated = [...prev];
updated[index] = child;
return updated;
}

const unregister = useCallback((childTag: number, handlerTags: number[]) => {
handlerTags.forEach((tag) => {
virtualMethods.current.delete(tag);
return [...prev, child];
});
}, []);

const unregister = useCallback((childTag: number) => {
setVirtualChildren((prev) => prev.filter((c) => c.viewTag !== childTag));
}, []);

const contextValue: DetectorContextValue = useMemo(
() => ({
register,
unregister,
}),
[register, unregister]
);

// It might happen only with ReanimatedNativeDetector
if (!NativeDetectorComponent) {
throw new Error(
Expand All @@ -85,20 +81,23 @@ export function InterceptingGestureDetector<THandlerData, TConfig>({
);
}

const handleGestureEvent = (key: keyof DetectorCallbacks<THandlerData>) => {
return (e: GestureHandlerEvent<THandlerData>) => {
if (gesture?.detectorCallbacks[key]) {
gesture.detectorCallbacks[key](e);
}

virtualMethods.current.forEach((ref) => {
const method = ref.current?.[key];
if (method) {
method(e);
const createGestureEventHandler = useCallback(
(key: keyof DetectorCallbacks<THandlerData>) => {
return (e: GestureHandlerEvent<THandlerData>) => {
if (gesture?.detectorCallbacks[key]) {
gesture.detectorCallbacks[key](e);
}
});
};
};

virtualChildren.forEach((child) => {
const method = child.methods[key];
if (method) {
method(e);
}
});
};
},
[gesture, virtualChildren]
);

const getHandlers = useCallback(
(key: keyof DetectorCallbacks<unknown>) => {
Expand All @@ -112,8 +111,8 @@ export function InterceptingGestureDetector<THandlerData, TConfig>({
);
}

virtualMethods.current.forEach((ref) => {
const handler = ref.current?.[key];
virtualChildren.forEach((child) => {
const handler = child.methods[key];
if (handler) {
handlers.push(
handler as (e: GestureHandlerEvent<THandlerData>) => void
Expand All @@ -126,14 +125,28 @@ export function InterceptingGestureDetector<THandlerData, TConfig>({
[virtualChildren, gesture?.detectorCallbacks]
);

const reanimatedUpdateEvents = useMemo(
() => getHandlers('onReanimatedUpdateEvent'),
[getHandlers]
);
const reanimatedEventHandler = Reanimated?.useComposedEventHandler(
getHandlers('onReanimatedUpdateEvent')
reanimatedUpdateEvents
);

const reanimatedStateChangeEvents = useMemo(
() => getHandlers('onReanimatedStateChange'),
[getHandlers]
);
const reanimatedStateChangeHandler = Reanimated?.useComposedEventHandler(
getHandlers('onReanimatedStateChange')
reanimatedStateChangeEvents
);

const reanimatedTouchEvents = useMemo(
() => getHandlers('onReanimatedTouchEvent'),
[getHandlers]
);
const reanimatedTouchEventHandler = Reanimated?.useComposedEventHandler(
getHandlers('onReanimatedTouchEvent')
reanimatedTouchEvents
);

ensureNativeDetectorComponent(NativeDetectorComponent);
Expand All @@ -142,42 +155,48 @@ export function InterceptingGestureDetector<THandlerData, TConfig>({
configureRelations(gesture);
}

const handlerTags = useMemo(() => {
if (gesture) {
return isComposedGesture(gesture) ? gesture.tags : [gesture.tag];
}
return [];
}, [gesture]);

return (
<DetectorContext value={{ register, unregister }}>
<DetectorContext value={contextValue}>
<NativeDetectorComponent
// @ts-ignore This is a type mismatch between RNGH types and RN Codegen types
onGestureHandlerStateChange={handleGestureEvent(
'onGestureHandlerStateChange'
onGestureHandlerStateChange={useMemo(
() => createGestureEventHandler('onGestureHandlerStateChange'),
[createGestureEventHandler]
)}
// @ts-ignore This is a type mismatch between RNGH types and RN Codegen types
onGestureHandlerEvent={handleGestureEvent('onGestureHandlerEvent')}
onGestureHandlerEvent={useMemo(
() => createGestureEventHandler('onGestureHandlerEvent'),
[createGestureEventHandler]
)}
// @ts-ignore This is a type mismatch between RNGH types and RN Codegen types
onGestureHandlerAnimatedEvent={
gesture?.detectorCallbacks.onGestureHandlerAnimatedEvent
}
Comment on lines 179 to 181
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the new approach with useMemo( () => createGestureEventHandler allow us to allow support for AnimatedEvents?

// @ts-ignore This is a type mismatch between RNGH types and RN Codegen types
onGestureHandlerTouchEvent={handleGestureEvent(
'onGestureHandlerTouchEvent'
onGestureHandlerTouchEvent={useMemo(
() => createGestureEventHandler('onGestureHandlerTouchEvent'),
[createGestureEventHandler]
)}
// @ts-ignore This is a type mismatch between RNGH types and RN Codegen types
onGestureHandlerReanimatedStateChange={
shouldUseReanimated ? reanimatedStateChangeHandler : undefined
shouldUseReanimatedDetector ? reanimatedStateChangeHandler : undefined
}
// @ts-ignore This is a type mismatch between RNGH types and RN Codegen types
onGestureHandlerReanimatedEvent={
shouldUseReanimated ? reanimatedEventHandler : undefined
shouldUseReanimatedDetector ? reanimatedEventHandler : undefined
}
// @ts-ignore This is a type mismatch between RNGH types and RN Codegen types
onGestureHandlerReanimatedTouchEvent={
shouldUseReanimated ? reanimatedTouchEventHandler : undefined
}
handlerTags={
gesture
? isComposedGesture(gesture)
? gesture.tags
: [gesture.tag]
: []
shouldUseReanimatedDetector ? reanimatedTouchEventHandler : undefined
}
handlerTags={handlerTags}
style={nativeDetectorStyles.detector}
virtualChildren={virtualChildren}
moduleId={globalThis._RNGH_MODULE_ID}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { RefObject, useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Wrap } from '../../../handlers/gestures/GestureDetector/Wrap';
import { findNodeHandle, Platform } from 'react-native';
import { useDetectorContext } from './useDetectorContext';
import { isComposedGesture } from '../../hooks/utils/relationUtils';
import { NativeDetectorProps } from '../common';
import { configureRelations } from '../utils';
import { tagMessage } from '../../../utils';
import { DetectorCallbacks } from '../../types';
import { DetectorCallbacks, VirtualChild } from '../../types';

export function VirtualDetector<THandlerData, TConfig>(
props: NativeDetectorProps<THandlerData, TConfig>
) {
function useRequiredDetectorContext() {
const context = useDetectorContext();
if (!context) {
throw new Error(
Expand All @@ -19,43 +17,36 @@ export function VirtualDetector<THandlerData, TConfig>(
)
);
}
const { register, unregister } = context;
return context;
}

export function VirtualDetector<THandlerData, TConfig>(
props: NativeDetectorProps<THandlerData, TConfig>
) {
// Don't memoize virtual detectors to be able to listen to changes in children
// TODO: replace with MutationObserver when it rolls out in React Native
'use no memo';

const { register, unregister } = useRequiredDetectorContext();

const viewRef = useRef(null);
const [viewTag, setViewTag] = useState<number>(-1);

const virtualMethods = useRef(props.gesture.detectorCallbacks);

const handleRef = useCallback(
(node: any) => {
viewRef.current = node;
if (!node) {
return;
if (node) {
const tag: number = Platform.OS === 'web' ? node : findNodeHandle(node);
setViewTag(tag ?? -1);
} else {
setViewTag(-1);
}

const tag = Platform.OS === 'web' ? node : findNodeHandle(node);

if (tag != null) {
setViewTag(tag);
}

return () => {
if (tag != null) {
const handlerTags = isComposedGesture(props.gesture)
? props.gesture.tags
: [props.gesture.tag];

unregister(tag, handlerTags);
}
};
},
// Invalid dependency array to change the function when children change
// eslint-disable-next-line react-hooks/exhaustive-deps
[props.children]
);

useEffect(() => {
virtualMethods.current = props.gesture.detectorCallbacks;
}, [props.gesture.detectorCallbacks]);

useEffect(() => {
if (viewTag === -1) {
return;
Expand All @@ -65,24 +56,20 @@ export function VirtualDetector<THandlerData, TConfig>(
? props.gesture.tags
: [props.gesture.tag];

const virtualProps = {
const virtualChild: VirtualChild = {
viewTag,
handlerTags,
methods: props.gesture.detectorCallbacks as DetectorCallbacks<unknown>,
forReanimated: !!props.gesture.config.shouldUseReanimatedDetector,
forAnimated: !!props.gesture.config.dispatchesAnimatedEvents,
// used by HostGestureDetector on web
viewRef: Platform.OS === 'web' ? viewRef : undefined,
};

if (Platform.OS === 'web') {
Object.assign(virtualProps, { viewRef });
}

register(
virtualProps,
virtualMethods as RefObject<DetectorCallbacks<unknown>>,
props.gesture.config.shouldUseReanimatedDetector,
props.gesture.config.dispatchesAnimatedEvents
);
register(virtualChild);

return () => {
unregister(viewTag, handlerTags);
unregister(viewTag);
};
}, [viewTag, props.gesture, register, unregister]);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import { createContext, RefObject, use } from 'react';
import { DetectorCallbacks, VirtualChildren } from '../../types';
import { createContext, use } from 'react';
import { VirtualChild } from '../../types';

type DetectorContextType = {
register: (
child: VirtualChildren,
methods: RefObject<DetectorCallbacks<unknown>>,
forReanimated: boolean | undefined,
forAnimated: boolean | undefined
) => void;
unregister: (child: number, handlerTags: number[]) => void;
export type DetectorContextValue = {
register: (child: VirtualChild) => void;
unregister: (child: number) => void;
};

export const DetectorContext = createContext<DetectorContextType | null>(null);
export const DetectorContext = createContext<DetectorContextValue | null>(null);

export function useDetectorContext() {
const ctx = use(DetectorContext);
Expand Down
Loading
Loading