react-native-gesture-handler#TapGestureHandler TypeScript Examples
The following examples show how to use
react-native-gesture-handler#TapGestureHandler.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlphabetScroller.tsx From jellyfin-audio-player with MIT License | 6 votes |
AlphabetScroller: React.FC<Props> = ({ onSelect }) => {
const [ height, setHeight ] = useState(0);
const [ index, setIndex ] = useState<number>();
// Handler for setting the correct height for a single alphabet item
const handleLayout = useCallback((event: LayoutChangeEvent) => {
setHeight(event.nativeEvent.layout.height);
}, []);
// Handler for passing on a new index when it is tapped or swiped
const handleGestureEvent = useCallback((event: PanGestureHandlerGestureEvent | TapGestureHandlerGestureEvent) => {
const newIndex = Math.floor(event.nativeEvent.y / height);
if (newIndex !== index) {
setIndex(newIndex);
onSelect(newIndex);
}
}, [height, index, onSelect]);
return (
<Container>
<TapGestureHandler onHandlerStateChange={handleGestureEvent}>
<PanGestureHandler onGestureEvent={handleGestureEvent}>
<View>
{ALPHABET_LETTERS.split('').map((l, i) => (
<View
key={l}
onLayout={i === 0 ? handleLayout : undefined}
>
<Letter>{l}</Letter>
</View>
))}
</View>
</PanGestureHandler>
</TapGestureHandler>
</Container>
);
}
Example #2
Source File: index.tsx From react-native-scroll-bottom-sheet with MIT License | 5 votes |
/**
* Gesture Handler references
*/
private masterDrawer = React.createRef<TapGestureHandler>();
Example #3
Source File: StickyItemFlatList.tsx From react-native-sticky-item with MIT License | 4 votes |
StickyItemFlatList = forwardRef( <T extends {}>(props: StickyItemFlatListProps<T>, ref: Ref<FlatList<T>>) => { const { initialScrollIndex = 0, decelerationRate = DEFAULT_DECELERATION_RATE, itemWidth, itemHeight, separatorSize = DEFAULT_SEPARATOR_SIZE, borderRadius = DEFAULT_BORDER_RADIUS, stickyItemActiveOpacity = DEFAULT_STICKY_ITEM_ACTIVE_OPACITY, stickyItemWidth, stickyItemHeight, stickyItemBackgroundColors, stickyItemContent, onStickyItemPress, isRTL = DEFAULT_IS_RTL, ItemSeparatorComponent = Separator, ...rest } = props; // refs const flatListRef = useRef<FlatList<T>>(null); const tapRef = useRef<TapGestureHandler>(null); //#region variables const itemWidthWithSeparator = useMemo( () => itemWidth + separatorSize, [itemWidth, separatorSize] ); const separatorProps = useMemo( () => ({ size: separatorSize, }), [separatorSize] ); //#endregion //#region styles const contentContainerStyle = useMemo( () => [ rest.contentContainerStyle, { paddingLeft: itemWidth + separatorSize * 2, paddingRight: separatorSize, }, ], [rest.contentContainerStyle, itemWidth, separatorSize] ); //#endregion //#region methods const getHitSlop = useCallback( isMinimized => { const verticalPosition = isMinimized ? -((itemHeight - stickyItemHeight) / 2) : 0; const startPosition = isMinimized ? 0 : -separatorSize; const endPosition = isMinimized ? -(SCREEN_WIDTH - stickyItemWidth) : -(SCREEN_WIDTH - separatorSize - itemWidth); return { top: verticalPosition, right: isRTL ? startPosition : endPosition, left: isRTL ? endPosition : startPosition, bottom: verticalPosition, }; }, [ itemWidth, itemHeight, stickyItemWidth, stickyItemHeight, separatorSize, isRTL, ] ); const getItemLayout = useCallback( (_, index) => { return { length: itemWidthWithSeparator, // sticky item + previous items width offset: itemWidthWithSeparator + itemWidthWithSeparator * index, index, }; }, [itemWidthWithSeparator] ); //#endregion //#region gesture const x = useValue(0); const tapState = useValue(State.UNDETERMINED); const tapGestures = useGestureHandler({ state: tapState }); const onScroll = event([ { nativeEvent: { contentOffset: { x, }, }, }, ]); const onScrollEnd = event([ { nativeEvent: { contentOffset: { x, }, }, }, ]); //#endregion //#region effects //@ts-ignore useImperativeHandle(ref, () => flatListRef.current!.getNode()); useCode( () => cond(eq(tapState, State.END), [ call([tapState], () => { if (onStickyItemPress) { onStickyItemPress(); } }), set(tapState, State.UNDETERMINED), ]), [tapState] ); useCode( () => onChange( x, call([x], args => { if (tapRef.current) { const isMinimized = args[0] > 0; // @ts-ignore tapRef.current.setNativeProps({ hitSlop: getHitSlop(isMinimized), }); } }) ), [ x, itemWidth, itemHeight, stickyItemWidth, stickyItemWidth, separatorSize, ] ); useEffect(() => { /** * @DEV * to fix stick item position with fast refresh */ x.setValue(0); if (tapRef.current) { // @ts-ignore tapRef.current.setNativeProps({ hitSlop: getHitSlop(initialScrollIndex !== 0), }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [getHitSlop]); //#endregion // render const renderSeparator = useCallback(() => { if (typeof ItemSeparatorComponent === 'function') { // @ts-ignore return ItemSeparatorComponent(separatorProps); } else { // @ts-ignore return <ItemSeparatorComponent size={separatorProps.size} />; } }, [ItemSeparatorComponent, separatorProps]); return ( <TapGestureHandler ref={tapRef} waitFor={flatListRef} shouldCancelWhenOutside={true} {...tapGestures} > <Animated.View> <AnimatedFlatList {...rest} ref={flatListRef} initialScrollIndex={initialScrollIndex} inverted={isRTL} ItemSeparatorComponent={renderSeparator} contentContainerStyle={contentContainerStyle} horizontal={true} showsHorizontalScrollIndicator={false} scrollEventThrottle={1} pagingEnabled={true} decelerationRate={decelerationRate} snapToAlignment={'start'} snapToInterval={itemWidth + separatorSize} onScroll={onScroll} onScrollAnimationEnd={onScrollEnd} getItemLayout={getItemLayout} /> <StickyItem x={x} tapState={tapState} itemWidth={itemWidth} itemHeight={itemHeight} separatorSize={separatorSize} borderRadius={borderRadius} stickyItemActiveOpacity={stickyItemActiveOpacity} stickyItemWidth={stickyItemWidth} stickyItemHeight={stickyItemHeight} stickyItemBackgroundColors={stickyItemBackgroundColors} stickyItemContent={stickyItemContent} isRTL={isRTL} /> </Animated.View> </TapGestureHandler> ); } )
Example #4
Source File: index.tsx From react-native-bottomsheet-reanimated with MIT License | 4 votes |
Index = forwardRef(
(
{
isBackDropDismissByPress,
initialPosition = { y: 0 },
onChangeSnap,
onChangeKeyboardAwareSnap,
snapPoints,
bottomSheerColor = '#FFFFFF',
backDropColor = '#000000',
isRoundBorderWithTipHeader = false,
tipHeaderRadius = 12,
header,
body,
isBackDrop = false,
isModal,
dragEnabled = true,
isAnimatedYFromParent,
animatedValueY,
containerStyle,
bodyContainerStyle = {},
tipStyle,
headerStyle,
bodyStyle,
onClose,
bounce = 0.5,
keyboardAware = false,
keyboardAwareExtraSnapHeight = 0,
keyboardAwareDrag = false,
overDrag = true,
}: BottomSheetProps,
ref
) => {
const [keyboardHeight] = useKeyboard(keyboardAware);
const [headerHeight, setHeaderHeight] = useState(0);
const [currentSnap, setCurrentSnap] = useState(initialPosition);
const currentNomalizeSnap = useMemo(() => normalize(currentSnap), [
currentSnap,
]);
const normalizeSnap = useMemo(() => getNormalizeSnaps(snapPoints), [
snapPoints,
]);
const [_deltaY] = useState(new Animated.Value(Screen.height));
const bottomPanel = useRef<any>();
const _snapPoints = useMemo(() => getSnapPoints(normalizeSnap), [
normalizeSnap,
]);
const boundaries = useMemo(
() =>
overDrag
? { top: isModal ? 0 : -300, bounce: bounce }
: getOverDragBoundries(normalizeSnap),
[overDrag, isModal, bounce, normalizeSnap]
);
const _initialPosition = useMemo(
() => getInitialPosition(initialPosition),
[initialPosition]
);
const isDismissWithPress = isBackDropDismissByPress
? isBackDropDismissByPress
: false;
const [
isBottomSheetDismissed,
setIsBottomSheetDismissed,
] = useState<boolean>(initialPosition === 0 || initialPosition === '0%');
const onDrawerSnap = (snap: any) => {
const index = snap.nativeEvent.index;
const value = snapPoints[index];
setCurrentSnap(value); //
if (value === 0 || value === '0%') {
setIsBottomSheetDismissed(true);
onClose && onClose();
} else {
setIsBottomSheetDismissed(false);
}
onChangeSnap && onChangeSnap({ index, value });
};
const dismissBottomSheet = () => {
let index = snapPoints.findIndex(
(x: number | string) => x === 0 || x === '0%'
);
if (index !== -1) {
bottomPanel.current.snapTo({ index });
onClose && onClose();
}
Keyboard.dismiss();
};
const snapTo = (index: number) => {
if (snapPoints.findIndex((x) => x === 0 || x === '0%') !== -1) {
Keyboard.dismiss();
}
bottomPanel.current.snapTo({ index });
const value = snapPoints[index];
onChangeSnap && onChangeSnap({ index, value });
};
useImperativeHandle(ref, () => ({
snapTo,
dismissBottomSheet,
}));
useEffect(() => {
if (keyboardAware) {
const currentSnapHeight = normalize(currentSnap);
if (keyboardHeight) {
const newSnapHeight = currentSnapHeight + keyboardHeight;
if (newSnapHeight > Screen.height) {
bottomPanel.current.snapToPosition({
x: 0,
y: 0 - keyboardAwareExtraSnapHeight,
});
onChangeKeyboardAwareSnap &&
onChangeKeyboardAwareSnap({
previousSnap: currentSnapHeight,
nextSnap: 0,
keyboardHeight,
});
} else {
bottomPanel.current.snapToPosition({
x: 0,
y: Screen.height - newSnapHeight - keyboardAwareExtraSnapHeight,
});
onChangeKeyboardAwareSnap &&
onChangeKeyboardAwareSnap({
previousSnap: currentSnapHeight,
nextSnap: newSnapHeight,
keyboardHeight,
});
}
} else {
bottomPanel.current.snapToPosition({
x: 0,
y: Screen.height - currentSnapHeight,
});
}
}
}, [keyboardHeight]);
const dragHandler = () => {
if (dragEnabled) {
if (!keyboardAwareDrag && keyboardHeight > 0) {
return false;
} else {
return true;
}
}
return false;
};
return (
<View style={styles.panelContainer} pointerEvents={'box-none'}>
{/* Backdrop */}
{isBackDrop && (
<Animated.View
pointerEvents={!isBottomSheetDismissed ? 'auto' : 'box-none'}
style={[
styles.panelContainer,
{
backgroundColor: backDropColor,
opacity: isAnimatedYFromParent
? animatedValueY.interpolate({
inputRange: [0, Screen.height - 100],
outputRange: [1, 0],
extrapolateRight: Extrapolate.CLAMP,
})
: _deltaY.interpolate({
inputRange: [0, Screen.height - 100],
outputRange: [1, 0],
extrapolateRight: Extrapolate.CLAMP,
}),
},
]}
/>
)}
<Interactable.View
dragEnabled={isModal ? false : dragHandler()}
verticalOnly={true}
ref={bottomPanel}
snapPoints={_snapPoints}
initialPosition={_initialPosition}
boundaries={boundaries}
animatedValueY={isAnimatedYFromParent ? animatedValueY : _deltaY}
onSnap={onDrawerSnap}
>
{!isModal && isDismissWithPress && !isBottomSheetDismissed && (
<TapGestureHandler
enabled={isBackDrop}
onActivated={dismissBottomSheet}
>
<View
style={{
height: Screen.height,
marginTop: -Screen.height,
}}
/>
</TapGestureHandler>
)}
<View
style={[
isModal ? styles.modal : styles.panel,
{ backgroundColor: bottomSheerColor },
isRoundBorderWithTipHeader
? [
{
backgroundColor: '#FFFFFF',
shadowColor: '#000000',
shadowOffset: { width: 0, height: 0 },
shadowRadius: 5,
shadowOpacity: 0.4,
},
{
borderTopLeftRadius: tipHeaderRadius,
borderTopRightRadius: tipHeaderRadius,
},
]
: {},
containerStyle,
]}
>
<View
style={[
isModal ? styles.modal : styles.panel,
bodyContainerStyle,
]}
>
{!isModal && isRoundBorderWithTipHeader && (
<View style={[styles.panelHandle, tipStyle]} />
)}
{!isModal && (
<View
style={[styles.panelHeader, headerStyle]}
onLayout={(e) => setHeaderHeight(e.nativeEvent.layout.height)}
>
{header}
</View>
)}
<View style={bodyStyle}>
{React.cloneElement(body, {
style: {
...body?.props?.style,
height: currentNomalizeSnap - headerHeight + OFFSET,
},
})}
</View>
</View>
</View>
</Interactable.View>
</View>
);
}
)
Example #5
Source File: index.tsx From react-native-scroll-bottom-sheet with MIT License | 4 votes |
render() {
const {
renderHandle,
snapPoints,
initialSnapIndex,
componentType,
onSettle,
animatedPosition,
containerStyle,
...rest
} = this.props;
const AnimatedScrollableComponent = this.scrollComponent;
const normalisedSnapPoints = this.getNormalisedSnapPoints();
const initialSnap = normalisedSnapPoints[initialSnapIndex];
const Content = (
<Animated.View
style={[
StyleSheet.absoluteFillObject,
containerStyle,
// @ts-ignore
{
transform: [{ translateY: this.translateY }],
},
]}
>
<PanGestureHandler
ref={this.drawerHandleRef}
shouldCancelWhenOutside={false}
simultaneousHandlers={this.masterDrawer}
onGestureEvent={this.onHandleGestureEvent}
onHandlerStateChange={this.onHandleGestureEvent}
>
<Animated.View>{renderHandle()}</Animated.View>
</PanGestureHandler>
<PanGestureHandler
ref={this.drawerContentRef}
simultaneousHandlers={[this.scrollComponentRef, this.masterDrawer]}
shouldCancelWhenOutside={false}
onGestureEvent={this.onDrawerGestureEvent}
onHandlerStateChange={this.onDrawerGestureEvent}
>
<Animated.View style={styles.container}>
<NativeViewGestureHandler
ref={this.scrollComponentRef}
waitFor={this.masterDrawer}
simultaneousHandlers={this.drawerContentRef}
>
<AnimatedScrollableComponent
overScrollMode="never"
bounces={false}
{...rest}
ref={this.props.innerRef}
// @ts-ignore
decelerationRate={this.decelerationRate}
onScrollBeginDrag={this.onScrollBeginDrag}
scrollEventThrottle={1}
contentContainerStyle={[
rest.contentContainerStyle,
{ paddingBottom: this.getNormalisedSnapPoints()[0] },
]}
/>
</NativeViewGestureHandler>
</Animated.View>
</PanGestureHandler>
{this.props.animatedPosition && (
<Animated.Code
exec={onChange(
this.position,
set(this.props.animatedPosition, this.position)
)}
/>
)}
<Animated.Code
exec={onChange(
this.dragY,
cond(not(eq(this.dragY, 0)), set(this.prevDragY, this.dragY))
)}
/>
<Animated.Code
exec={onChange(
this.didGestureFinish,
cond(this.didGestureFinish, [
this.didScrollUpAndPullDown,
this.setTranslationY,
set(
this.tempDestSnapPoint,
add(normalisedSnapPoints[0], this.extraOffset)
),
set(this.nextSnapIndex, 0),
set(this.destSnapPoint, this.calculateNextSnapPoint()),
cond(
and(
greaterThan(this.dragY, this.lastStartScrollY),
this.isAndroid,
not(this.dragWithHandle)
),
call([], () => {
// This prevents the scroll glide from happening on Android when pulling down with inertia.
// It's not perfect, but does the job for now
const { method, args } = imperativeScrollOptions[
this.props.componentType
];
// @ts-ignore
const node = this.props.innerRef.current?.getNode();
if (
node &&
node[method] &&
((this.props.componentType === 'FlatList' &&
(this.props?.data?.length || 0) > 0) ||
(this.props.componentType === 'SectionList' &&
this.props.sections.length > 0) ||
this.props.componentType === 'ScrollView')
) {
node[method](args);
}
})
),
set(this.dragY, 0),
set(this.velocityY, 0),
set(
this.lastSnap,
sub(
this.destSnapPoint,
cond(
eq(this.scrollUpAndPullDown, 1),
this.lastStartScrollY,
0
)
)
),
call([this.lastSnap], ([value]) => {
// This is the TapGHandler trick
// @ts-ignore
this.masterDrawer?.current?.setNativeProps({
maxDeltaY: value - this.getNormalisedSnapPoints()[0],
});
}),
set(
this.decelerationRate,
cond(
eq(this.isAndroid, 1),
cond(
eq(this.lastSnap, normalisedSnapPoints[0]),
ANDROID_NORMAL_DECELERATION_RATE,
0
),
IOS_NORMAL_DECELERATION_RATE
)
),
])
)}
/>
<Animated.Code
exec={onChange(this.isManuallySetValue, [
cond(
this.isManuallySetValue,
[
set(this.destSnapPoint, this.manualYOffset),
set(this.animationFinished, 0),
set(this.lastSnap, this.manualYOffset),
call([this.lastSnap], ([value]) => {
// This is the TapGHandler trick
// @ts-ignore
this.masterDrawer?.current?.setNativeProps({
maxDeltaY: value - this.getNormalisedSnapPoints()[0],
});
}),
],
[set(this.nextSnapIndex, 0)]
),
])}
/>
</Animated.View>
);
// On Android, having an intermediary view with pointerEvents="box-none", breaks the
// waitFor logic
if (Platform.OS === 'android') {
return (
<TapGestureHandler
maxDurationMs={100000}
ref={this.masterDrawer}
maxDeltaY={initialSnap - this.getNormalisedSnapPoints()[0]}
shouldCancelWhenOutside={false}
>
{Content}
</TapGestureHandler>
);
}
// On iOS, We need to wrap the content on a view with PointerEvents box-none
// So that we can start scrolling automatically when reaching the top without
// Stopping the gesture
return (
<TapGestureHandler
maxDurationMs={100000}
ref={this.masterDrawer}
maxDeltaY={initialSnap - this.getNormalisedSnapPoints()[0]}
>
<View style={StyleSheet.absoluteFillObject} pointerEvents="box-none">
{Content}
</View>
</TapGestureHandler>
);
}
Example #6
Source File: ImageTransformer.tsx From react-native-gallery-toolkit with MIT License | 4 votes |
ImageTransformer = React.memo<ImageTransformerProps>(
({
outerGestureHandlerRefs = [],
source,
width,
height,
onStateChange = workletNoop,
renderImage,
windowDimensions = Dimensions.get('window'),
isActive,
outerGestureHandlerActive,
style,
onTap = workletNoop,
onDoubleTap = workletNoop,
onInteraction = workletNoop,
DOUBLE_TAP_SCALE = 3,
MAX_SCALE = 3,
MIN_SCALE = 0.7,
OVER_SCALE = 0.5,
timingConfig = defaultTimingConfig,
springConfig = defaultSpringConfig,
enabled = true,
ImageComponent = Image,
}) => {
// fixGestureHandler();
assertWorklet(onStateChange);
assertWorklet(onTap);
assertWorklet(onDoubleTap);
assertWorklet(onInteraction);
if (typeof source === 'undefined') {
throw new Error(
'ImageTransformer: either source or uri should be passed to display an image',
);
}
const imageSource = useMemo(
() =>
typeof source === 'string'
? {
uri: source,
}
: source,
[source],
);
const interactionsEnabled = useSharedValue(false);
const setInteractionsEnabled = useCallback((value: boolean) => {
interactionsEnabled.value = value;
}, []);
const onLoadImageSuccess = useCallback(() => {
setInteractionsEnabled(true);
}, []);
// HACK ALERT
// we disable pinch handler in order to trigger onFinish
// in case user releases one finger
const [pinchEnabled, setPinchEnabledState] = useState(true);
useEffect(() => {
if (!pinchEnabled) {
setPinchEnabledState(true);
}
}, [pinchEnabled]);
const disablePinch = useCallback(() => {
setPinchEnabledState(false);
}, []);
// HACK ALERT END
const pinchRef = useRef(null);
const panRef = useRef(null);
const tapRef = useRef(null);
const doubleTapRef = useRef(null);
const panState = useSharedValue<State>(State.UNDETERMINED);
const pinchState = useSharedValue<State>(State.UNDETERMINED);
const scale = useSharedValue(1);
const scaleOffset = useSharedValue(1);
const translation = vectors.useSharedVector(0, 0);
const panVelocity = vectors.useSharedVector(0, 0);
const scaleTranslation = vectors.useSharedVector(0, 0);
const offset = vectors.useSharedVector(0, 0);
const canvas = useMemo(
() =>
vectors.create(
windowDimensions.width,
windowDimensions.height,
),
[windowDimensions.width, windowDimensions.height],
);
const targetWidth = windowDimensions.width;
const scaleFactor = width / targetWidth;
const targetHeight = height / scaleFactor;
const image = useMemo(
() => vectors.create(targetWidth, targetHeight),
[targetHeight, targetWidth],
);
const canPanVertically = useDerivedValue(() => {
return windowDimensions.height < targetHeight * scale.value;
}, []);
const resetSharedState = useWorkletCallback(
(animated?: boolean) => {
'worklet';
if (animated) {
scale.value = withTiming(1, timingConfig);
scaleOffset.value = 1;
vectors.set(offset, () => withTiming(0, timingConfig));
} else {
scale.value = 1;
scaleOffset.value = 1;
vectors.set(translation, 0);
vectors.set(scaleTranslation, 0);
vectors.set(offset, 0);
}
},
[timingConfig],
);
const maybeRunOnEnd = useWorkletCallback(() => {
'worklet';
const target = vectors.create(0, 0);
const fixedScale = clamp(MIN_SCALE, scale.value, MAX_SCALE);
const scaledImage = image.y * fixedScale;
const rightBoundary = (canvas.x / 2) * (fixedScale - 1);
let topBoundary = 0;
if (canvas.y < scaledImage) {
topBoundary = Math.abs(scaledImage - canvas.y) / 2;
}
const maxVector = vectors.create(rightBoundary, topBoundary);
const minVector = vectors.invert(maxVector);
if (!canPanVertically.value) {
offset.y.value = withSpring(target.y, springConfig);
}
// we should handle this only if pan or pinch handlers has been used already
if (
(checkIsNotUsed(panState) || checkIsNotUsed(pinchState)) &&
pinchState.value !== State.CANCELLED
) {
return;
}
if (
vectors.eq(offset, 0) &&
vectors.eq(translation, 0) &&
vectors.eq(scaleTranslation, 0) &&
scale.value === 1
) {
// we don't need to run any animations
return;
}
if (scale.value <= 1) {
// just center it
vectors.set(offset, () => withTiming(0, timingConfig));
return;
}
vectors.set(
target,
vectors.clamp(offset, minVector, maxVector),
);
const deceleration = 0.9915;
const isInBoundaryX = target.x === offset.x.value;
const isInBoundaryY = target.y === offset.y.value;
if (isInBoundaryX) {
if (
Math.abs(panVelocity.x.value) > 0 &&
scale.value <= MAX_SCALE
) {
offset.x.value = withDecay({
velocity: panVelocity.x.value,
clamp: [minVector.x, maxVector.x],
deceleration,
});
}
} else {
offset.x.value = withSpring(target.x, springConfig);
}
if (isInBoundaryY) {
if (
Math.abs(panVelocity.y.value) > 0 &&
scale.value <= MAX_SCALE &&
offset.y.value !== minVector.y &&
offset.y.value !== maxVector.y
) {
offset.y.value = withDecay({
velocity: panVelocity.y.value,
clamp: [minVector.y, maxVector.y],
deceleration,
});
}
} else {
offset.y.value = withSpring(target.y, springConfig);
}
}, [
MIN_SCALE,
MAX_SCALE,
image,
canvas,
springConfig,
timingConfig,
]);
const onPanEvent = useAnimatedGestureHandler<
PanGestureHandlerGestureEvent,
{
panOffset: vectors.Vector<number>;
pan: vectors.Vector<number>;
}
>({
onInit: (_, ctx) => {
ctx.panOffset = vectors.create(0, 0);
},
shouldHandleEvent: () => {
return (
scale.value > 1 &&
(typeof outerGestureHandlerActive !== 'undefined'
? !outerGestureHandlerActive.value
: true) &&
interactionsEnabled.value
);
},
beforeEach: (evt, ctx) => {
ctx.pan = vectors.create(evt.translationX, evt.translationY);
const velocity = vectors.create(evt.velocityX, evt.velocityY);
vectors.set(panVelocity, velocity);
},
onStart: (_, ctx) => {
cancelAnimation(offset.x);
cancelAnimation(offset.y);
ctx.panOffset = vectors.create(0, 0);
onInteraction('pan');
},
onActive: (evt, ctx) => {
panState.value = evt.state;
if (scale.value > 1) {
if (evt.numberOfPointers > 1) {
// store pan offset during the pan with two fingers (during the pinch)
vectors.set(ctx.panOffset, ctx.pan);
} else {
// subtract the offset and assign fixed pan
const nextTranslate = vectors.add(
ctx.pan,
vectors.invert(ctx.panOffset),
);
translation.x.value = nextTranslate.x;
if (canPanVertically.value) {
translation.y.value = nextTranslate.y;
}
}
}
},
onEnd: (evt, ctx) => {
panState.value = evt.state;
vectors.set(ctx.panOffset, 0);
vectors.set(offset, vectors.add(offset, translation));
vectors.set(translation, 0);
maybeRunOnEnd();
vectors.set(panVelocity, 0);
},
});
useAnimatedReaction(
() => {
if (typeof isActive === 'undefined') {
return true;
}
return isActive.value;
},
(currentActive) => {
if (!currentActive) {
resetSharedState();
}
},
);
const onScaleEvent = useAnimatedGestureHandler<
PinchGestureHandlerGestureEvent,
{
origin: vectors.Vector<number>;
adjustFocal: vectors.Vector<number>;
gestureScale: number;
nextScale: number;
}
>({
onInit: (_, ctx) => {
ctx.origin = vectors.create(0, 0);
ctx.gestureScale = 1;
ctx.adjustFocal = vectors.create(0, 0);
},
shouldHandleEvent: (evt) => {
return (
evt.numberOfPointers === 2 &&
(typeof outerGestureHandlerActive !== 'undefined'
? !outerGestureHandlerActive.value
: true) &&
interactionsEnabled.value
);
},
beforeEach: (evt, ctx) => {
// calculate the overall scale value
// also limits this.event.scale
ctx.nextScale = clamp(
evt.scale * scaleOffset.value,
MIN_SCALE,
MAX_SCALE + OVER_SCALE,
);
if (
ctx.nextScale > MIN_SCALE &&
ctx.nextScale < MAX_SCALE + OVER_SCALE
) {
ctx.gestureScale = evt.scale;
}
// this is just to be able to use with vectors
const focal = vectors.create(evt.focalX, evt.focalY);
const CENTER = vectors.divide(canvas, 2);
// since it works even when you release one finger
if (evt.numberOfPointers === 2) {
// focal with translate offset
// it alow us to scale into different point even then we pan the image
ctx.adjustFocal = vectors.sub(
focal,
vectors.add(CENTER, offset),
);
} else if (
evt.state === State.ACTIVE &&
evt.numberOfPointers !== 2
) {
runOnJS(disablePinch)();
}
},
afterEach: (evt, ctx) => {
if (
evt.state === State.END ||
evt.state === State.CANCELLED
) {
return;
}
scale.value = ctx.nextScale;
},
onStart: (_, ctx) => {
onInteraction('scale');
cancelAnimation(offset.x);
cancelAnimation(offset.y);
vectors.set(ctx.origin, ctx.adjustFocal);
},
onActive: (evt, ctx) => {
pinchState.value = evt.state;
const pinch = vectors.sub(ctx.adjustFocal, ctx.origin);
const nextTranslation = vectors.add(
pinch,
ctx.origin,
vectors.multiply(-1, ctx.gestureScale, ctx.origin),
);
vectors.set(scaleTranslation, nextTranslation);
},
onFinish: (evt, ctx) => {
// reset gestureScale value
ctx.gestureScale = 1;
pinchState.value = evt.state;
// store scale value
scaleOffset.value = scale.value;
vectors.set(offset, vectors.add(offset, scaleTranslation));
vectors.set(scaleTranslation, 0);
if (scaleOffset.value < 1) {
// make sure we don't add stuff below the 1
scaleOffset.value = 1;
// this runs the timing animation
scale.value = withTiming(1, timingConfig);
} else if (scaleOffset.value > MAX_SCALE) {
scaleOffset.value = MAX_SCALE;
scale.value = withTiming(MAX_SCALE, timingConfig);
}
maybeRunOnEnd();
},
});
const onTapEvent = useAnimatedGestureHandler({
shouldHandleEvent: (evt) => {
return (
evt.numberOfPointers === 1 &&
(typeof outerGestureHandlerActive !== 'undefined'
? !outerGestureHandlerActive.value
: true) &&
interactionsEnabled.value
);
},
onStart: () => {
cancelAnimation(offset.x);
cancelAnimation(offset.y);
},
onActive: () => {
onTap(scale.value > 1);
},
onEnd: () => {
maybeRunOnEnd();
},
});
const handleScaleTo = useWorkletCallback(
(x: number, y: number) => {
'worklet';
scale.value = withTiming(DOUBLE_TAP_SCALE, timingConfig);
scaleOffset.value = DOUBLE_TAP_SCALE;
const targetImageSize = vectors.multiply(
image,
DOUBLE_TAP_SCALE,
);
const CENTER = vectors.divide(canvas, 2);
const imageCenter = vectors.divide(image, 2);
const focal = vectors.create(x, y);
const origin = vectors.multiply(
-1,
vectors.sub(vectors.divide(targetImageSize, 2), CENTER),
);
const koef = vectors.sub(
vectors.multiply(vectors.divide(1, imageCenter), focal),
1,
);
const target = vectors.multiply(origin, koef);
if (targetImageSize.y < canvas.y) {
target.y = 0;
}
offset.x.value = withTiming(target.x, timingConfig);
offset.y.value = withTiming(target.y, timingConfig);
},
[DOUBLE_TAP_SCALE, timingConfig, image, canvas],
);
const onDoubleTapEvent = useAnimatedGestureHandler<
TapGestureHandlerGestureEvent,
{}
>({
shouldHandleEvent: (evt) => {
return (
evt.numberOfPointers === 1 &&
(typeof outerGestureHandlerActive !== 'undefined'
? !outerGestureHandlerActive.value
: true) &&
interactionsEnabled.value
);
},
onActive: ({ x, y }) => {
onDoubleTap(scale.value > 1);
if (scale.value > 1) {
resetSharedState(true);
} else {
handleScaleTo(x, y);
}
},
});
const animatedStyles = useAnimatedStyle<ViewStyle>(() => {
const noOffset = offset.x.value === 0 && offset.y.value === 0;
const noTranslation =
translation.x.value === 0 && translation.y.value === 0;
const noScaleTranslation =
scaleTranslation.x.value === 0 &&
scaleTranslation.y.value === 0;
const isInactive =
scale.value === 1 &&
noOffset &&
noTranslation &&
noScaleTranslation;
onStateChange(isInactive);
return {
transform: [
{
translateX:
scaleTranslation.x.value +
translation.x.value +
offset.x.value,
},
{
translateY:
scaleTranslation.y.value +
translation.y.value +
offset.y.value,
},
{ scale: scale.value },
],
};
}, []);
return (
<Animated.View
style={[styles.container, { width: targetWidth }, style]}
>
<PinchGestureHandler
enabled={enabled && pinchEnabled}
ref={pinchRef}
onGestureEvent={onScaleEvent}
simultaneousHandlers={[
panRef,
tapRef,
...outerGestureHandlerRefs,
]}
>
<Animated.View style={styles.fill}>
<PanGestureHandler
enabled={enabled}
ref={panRef}
minDist={4}
avgTouches
simultaneousHandlers={[
pinchRef,
tapRef,
...outerGestureHandlerRefs,
]}
onGestureEvent={onPanEvent}
>
<Animated.View style={styles.fill}>
<TapGestureHandler
enabled={enabled}
ref={tapRef}
numberOfTaps={1}
maxDeltaX={8}
maxDeltaY={8}
simultaneousHandlers={[
pinchRef,
panRef,
...outerGestureHandlerRefs,
]}
waitFor={doubleTapRef}
onGestureEvent={onTapEvent}
>
<Animated.View style={[styles.fill]}>
<Animated.View style={styles.fill}>
<Animated.View style={styles.wrapper}>
<TapGestureHandler
enabled={enabled}
ref={doubleTapRef}
numberOfTaps={2}
maxDelayMs={140}
maxDeltaX={16}
maxDeltaY={16}
simultaneousHandlers={[
pinchRef,
panRef,
...outerGestureHandlerRefs,
]}
onGestureEvent={onDoubleTapEvent}
>
<Animated.View style={animatedStyles}>
{typeof renderImage === 'function' ? (
renderImage({
source: imageSource,
width: targetWidth,
height: targetHeight,
onLoad: onLoadImageSuccess,
})
) : (
<ImageComponent
onLoad={onLoadImageSuccess}
source={imageSource}
style={{
width: targetWidth,
height: targetHeight,
}}
/>
)}
</Animated.View>
</TapGestureHandler>
</Animated.View>
</Animated.View>
</Animated.View>
</TapGestureHandler>
</Animated.View>
</PanGestureHandler>
</Animated.View>
</PinchGestureHandler>
</Animated.View>
);
},
)
Example #7
Source File: Pager.tsx From react-native-gallery-toolkit with MIT License | 4 votes |
Pager = typedMemo(function Pager<
TPages,
ItemT = UnpackItemT<TPages>,
>({
pages,
initialIndex,
totalCount,
numToRender = 2,
onIndexChange = workletNoop,
renderPage,
width = dimensions.width,
gutterWidth = GUTTER_WIDTH,
shouldRenderGutter = true,
keyExtractor,
pagerWrapperStyles = {},
getItem,
springConfig,
onPagerTranslateChange = workletNoop,
onGesture = workletNoop,
onEnabledGesture = workletNoop,
shouldHandleGestureEvent = workletNoopTrue,
initialDiffValue = 0,
shouldUseInteractionManager = true,
outerGestureHandlerRefs = [],
verticallyEnabled = true,
}: PagerProps<TPages, ItemT>) {
assertWorklet(onIndexChange);
assertWorklet(onPagerTranslateChange);
assertWorklet(onGesture);
assertWorklet(onEnabledGesture);
assertWorklet(shouldHandleGestureEvent);
// make sure to not calculate translate with gutter
// if we don't want to render it
if (!shouldRenderGutter) {
gutterWidth = 0;
}
const getPageTranslate = useWorkletCallback(
(i: number) => {
const t = i * width;
const g = gutterWidth * i;
return -(t + g);
},
[gutterWidth, width],
);
const pagerRef = useRef(null);
const tapRef = useRef(null);
const isActive = useSharedValue(true);
const onPageStateChange = useWorkletCallback((value: boolean) => {
isActive.value = value;
}, []);
const velocity = useSharedValue(0);
const isMounted = useRef(false);
const [diffValue, setDiffValue] = useState(initialDiffValue);
useEffect(() => {
if (shouldUseInteractionManager && !isMounted.current) {
InteractionManager.runAfterInteractions(() => {
setDiffValue(numToRender);
console.log('numToRender in interaction');
});
isMounted.current = true;
} else {
setDiffValue(numToRender);
}
}, [numToRender]);
// S2: Pager related stuff
const [activeIndex, setActiveIndex] = useState(initialIndex);
const index = useSharedValue(initialIndex);
const length = useSharedValue(totalCount);
const pagerX = useSharedValue(0);
const toValueAnimation = useSharedValue(
getPageTranslate(initialIndex),
);
const offsetX = useSharedValue(getPageTranslate(initialIndex));
const totalWidth = useDerivedValue(() => {
return length.value * width + gutterWidth * length.value - 2;
}, []);
const onIndexChangeCb = useWorkletCallback((nextIndex: number) => {
onIndexChange(nextIndex);
runOnJS(setActiveIndex)(nextIndex);
}, []);
const onIndexChangeWorklet = useWorkletCallback((i: number) => {
offsetX.value = getPageTranslate(i);
index.value = i;
onIndexChangeCb(i);
}, []);
useEffect(() => {
runOnUI(onIndexChangeWorklet)(initialIndex);
}, [initialIndex]);
const getSpringConfig = useWorkletCallback(
(noVelocity?: boolean) => {
const ratio = 1.1;
const mass = 0.4;
const stiffness = IS_ANDROID ? 200.0 : 100.0;
const damping = ratio * 2.0 * Math.sqrt(mass * stiffness);
const configToUse =
typeof springConfig !== 'undefined'
? springConfig
: {
stiffness,
mass,
damping,
restDisplacementThreshold: 1,
restSpeedThreshold: 5,
};
// @ts-ignore
// cannot use merge and spread here :(
configToUse.velocity = noVelocity ? 0 : velocity.value;
return configToUse;
},
[springConfig],
);
const onChangePageAnimation = useWorkletCallback(
(noVelocity?: boolean) => {
const config = getSpringConfig(noVelocity);
if (offsetX.value === toValueAnimation.value) {
return;
}
offsetX.value = withSpring(
toValueAnimation.value,
config,
(isCanceled) => {
if (!isCanceled) {
velocity.value = 0;
}
},
);
},
[getSpringConfig],
);
// S3 Pager
const getCanSwipe = useWorkletCallback(
(currentTranslate: number = 0) => {
const nextTranslate = offsetX.value + currentTranslate;
if (nextTranslate > 0) {
return false;
}
const totalTranslate =
width * (length.value - 1) + gutterWidth * (length.value - 1);
if (Math.abs(nextTranslate) >= totalTranslate) {
return false;
}
return true;
},
[width, gutterWidth],
);
const getNextIndex = useWorkletCallback(
(v: number) => {
const currentTranslate = Math.abs(
getPageTranslate(index.value),
);
const currentIndex = index.value;
const currentOffset = Math.abs(offsetX.value);
const nextIndex = v < 0 ? currentIndex + 1 : currentIndex - 1;
if (
nextIndex < currentIndex &&
currentOffset > currentTranslate
) {
return currentIndex;
}
if (
nextIndex > currentIndex &&
currentOffset < currentTranslate
) {
return currentIndex;
}
if (nextIndex > length.value - 1 || nextIndex < 0) {
return currentIndex;
}
return nextIndex;
},
[getPageTranslate],
);
const isPagerInProgress = useDerivedValue(() => {
return (
Math.floor(Math.abs(getPageTranslate(index.value))) !==
Math.floor(Math.abs(offsetX.value + pagerX.value))
);
}, [getPageTranslate]);
const onPan = useAnimatedGestureHandler<
PanGestureHandlerGestureEvent,
{
pagerActive: boolean;
offsetX: null | number;
}
>({
onGesture: (evt) => {
onGesture(evt, isActive);
if (isActive.value && !isPagerInProgress.value) {
onEnabledGesture(evt);
}
},
onInit: (_, ctx) => {
ctx.offsetX = null;
},
shouldHandleEvent: (evt) => {
return (
(evt.numberOfPointers === 1 &&
isActive.value &&
Math.abs(evt.velocityX) > Math.abs(evt.velocityY) &&
shouldHandleGestureEvent(evt)) ||
isPagerInProgress.value
);
},
onEvent: (evt) => {
velocity.value = clampVelocity(
evt.velocityX,
MIN_VELOCITY,
MAX_VELOCITY,
);
},
onStart: (_, ctx) => {
ctx.offsetX = null;
},
onActive: (evt, ctx) => {
// workaround alert
// the event triggers with a delay and first frame value jumps
// we capture that value and subtract from the actual one
// so the translate happens on a second frame
if (ctx.offsetX === null) {
ctx.offsetX =
evt.translationX < 0 ? evt.translationX : -evt.translationX;
}
const val = evt.translationX - ctx.offsetX;
const canSwipe = getCanSwipe(val);
pagerX.value = canSwipe ? val : friction(val);
},
onEnd: (evt, ctx) => {
const val = evt.translationX - ctx.offsetX!;
const canSwipe = getCanSwipe(val);
offsetX.value += pagerX.value;
pagerX.value = 0;
const nextIndex = getNextIndex(evt.velocityX);
const vx = Math.abs(evt.velocityX);
const translation = Math.abs(val);
const isHalf = width / 2 < translation;
const shouldMoveToNextPage = (vx > 10 || isHalf) && canSwipe;
// we invert the value since the translationY is left to right
toValueAnimation.value = -(shouldMoveToNextPage
? -getPageTranslate(nextIndex)
: -getPageTranslate(index.value));
onChangePageAnimation(!shouldMoveToNextPage);
if (shouldMoveToNextPage) {
index.value = nextIndex;
onIndexChangeCb(nextIndex);
}
},
});
const onTap = useAnimatedGestureHandler({
shouldHandleEvent: (evt) => {
return evt.numberOfPointers === 1 && isActive.value;
},
onStart: () => {
cancelAnimation(offsetX);
},
onEnd: () => {
onChangePageAnimation(true);
},
});
const pagerStyles = useAnimatedStyle<ViewStyle>(() => {
const translateX = pagerX.value + offsetX.value;
onPagerTranslateChange(translateX);
return {
width: totalWidth.value,
transform: [
{
translateX,
},
],
};
}, []);
const pagerRefs = useMemo<PageRefs>(() => [pagerRef, tapRef], []);
const pagesToRender = useMemo(() => {
const temp = [];
for (let i = 0; i < totalCount; i += 1) {
let itemToUse;
if (typeof getItem === 'function') {
itemToUse = getItem(pages, i);
} else if (Array.isArray(pages)) {
itemToUse = pages[i];
} else {
throw new Error(
'Pager: items either should be an array of getItem should be defined',
);
}
const shouldRender = getShouldRender(i, activeIndex, diffValue);
if (!shouldRender) {
temp.push(null);
} else {
temp.push(
<Page
key={keyExtractor(itemToUse, i)}
item={itemToUse}
currentIndex={index}
pagerRefs={pagerRefs}
onPageStateChange={onPageStateChange}
index={i}
length={totalCount}
gutterWidth={gutterWidth}
renderPage={renderPage}
getPageTranslate={getPageTranslate}
width={width}
isPagerInProgress={isPagerInProgress}
shouldRenderGutter={shouldRenderGutter}
/>,
);
}
}
return temp;
}, [
activeIndex,
diffValue,
keyExtractor,
getItem,
totalCount,
pages,
getShouldRender,
index,
pagerRefs,
onPageStateChange,
gutterWidth,
renderPage,
getPageTranslate,
width,
isPagerInProgress,
shouldRenderGutter,
]);
return (
<View style={StyleSheet.absoluteFillObject}>
<Animated.View style={[StyleSheet.absoluteFill]}>
<PanGestureHandler
ref={pagerRef}
minDist={0.1}
minVelocityX={0.1}
activeOffsetX={[-4, 4]}
activeOffsetY={verticallyEnabled ? [-4, 4] : undefined}
simultaneousHandlers={[tapRef, ...outerGestureHandlerRefs]}
onGestureEvent={onPan}
>
<Animated.View style={StyleSheet.absoluteFill}>
<TapGestureHandler
ref={tapRef}
maxDeltaX={10}
maxDeltaY={10}
simultaneousHandlers={pagerRef}
onGestureEvent={onTap}
>
<Animated.View
style={[StyleSheet.absoluteFill, pagerWrapperStyles]}
>
<Animated.View style={StyleSheet.absoluteFill}>
<Animated.View style={[styles.pager, pagerStyles]}>
{pagesToRender}
</Animated.View>
</Animated.View>
</Animated.View>
</TapGestureHandler>
</Animated.View>
</PanGestureHandler>
</Animated.View>
</View>
);
})