Skip to content

Reimplement Incubator.TouchableOpacity with reanimatedv2 #1380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions demo/src/screens/incubatorScreens/TouchableOpacityScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ class TouchableOpacityScreen extends Component {
{this.renderExample('feedbackColor', {backgroundColor: Colors.red30, feedbackColor: Colors.red10})}
{this.renderExample('activeScale', {activeScale: 0.95})}
{this.renderExample('activeOpacity', {activeOpacity: 0.6})}

<Incubator.TouchableOpacity2
marginT-20
onPress={this.onPress}
onLongPress={this.onLongPress}
backgroundColor={Colors.blue30}
feedbackColor={Colors.blue50}
style={{alignItems: 'center', paddingHorizontal: 20, paddingVertical: 8, borderRadius: 50}}
activeOpacity={1}
activeScale={0.98}
>
<Text white>TouchableOpacity2</Text>
</Incubator.TouchableOpacity2>
</View>
);
}
Expand Down
52 changes: 52 additions & 0 deletions generatedTypes/incubator/TouchableOpacity2.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React from 'react';
import { LayoutChangeEvent } from 'react-native';
import { State } from 'react-native-gesture-handler';
import { ViewProps } from '../components/view';
export declare type TouchableOpacityProps = {
/**
* Background color
*/
backgroundColor?: string;
/**
* Background color when actively pressing the touchable
*/
feedbackColor?: string;
/**
* Opacity value when actively pressing the touchable
*/
activeOpacity?: number;
/**
* Scale value when actively pressing the touchable
*/
activeScale?: number;
/**
* Callback for when tapping the touchable
*/
onPress?: (props: any) => void;
/**
* Callback for when long pressing the touchable
*/
onLongPress?: (props: any) => void;
/**
* Pass controlled pressState to track gesture state changes
*/
pressState?: State;
/**
* If true, disable all interactions for this component.
*/
disabled?: boolean;
/**
* Pass custom style
*/
style?: ViewProps['style'];
/**
* Custom value of any type to pass on to TouchableOpacity and receive back in onPress callback
*/
customValue?: any;
onLayout?: (event: LayoutChangeEvent) => void;
testID?: string;
};
declare const _default: React.ComponentClass<TouchableOpacityProps & {
useCustomTheme?: boolean | undefined;
}, any>;
export default _default;
1 change: 1 addition & 0 deletions generatedTypes/incubator/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { default as TabController } from './TabController';
export { default as TextField, TextFieldProps, FieldContextType } from './TextField';
export { default as TouchableOpacity, TouchableOpacityProps } from './TouchableOpacity';
export { default as TouchableOpacity2 } from './TouchableOpacity2';
export { default as WheelPicker, WheelPickerProps } from './WheelPicker';
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@
"react-autobind": "^1.0.6",
"react-dom": "^15.4.2",
"react-native": "0.64.1",
"react-native-gesture-handler": "1.9.0",
"react-native-gesture-handler": "1.10.3",
"react-native-haptic-feedback": "^1.11.0",
"react-native-keyboard-tracking-view": "^5.6.1",
"react-native-navigation": "7.6.0",
Expand Down
177 changes: 177 additions & 0 deletions src/incubator/TouchableOpacity2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import React, {PropsWithChildren, useCallback, useMemo} from 'react';
import {LayoutChangeEvent} from 'react-native';
import Reanimated, {
useAnimatedGestureHandler,
useAnimatedStyle,
useSharedValue,
withTiming,
interpolate,
interpolateColor,
runOnJS
} from 'react-native-reanimated';
import {TapGestureHandler, LongPressGestureHandler, State} from 'react-native-gesture-handler';
import {asBaseComponent, forwardRef, BaseComponentInjectedProps, ForwardRefInjectedProps} from '../commons/new';
import {ViewProps} from '../components/view';

export type TouchableOpacityProps = {
/**
* Background color
*/
backgroundColor?: string;
/**
* Background color when actively pressing the touchable
*/
feedbackColor?: string;
/**
* Opacity value when actively pressing the touchable
*/
activeOpacity?: number;
/**
* Scale value when actively pressing the touchable
*/
activeScale?: number;
/**
* Callback for when tapping the touchable
*/
onPress?: (props: any) => void;
/**
* Callback for when long pressing the touchable
*/
onLongPress?: (props: any) => void;
Comment on lines +36 to +40
Copy link
Contributor

Choose a reason for hiding this comment

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

Why does the type of props here is any?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It's because of a behavior/feature we added in uilib to our touchable components.
We pass back the props the user originally passed to the component.

Why?
It solve a common issue when rendering multiple repeating items (like in the case of lists) and other use-cases..

For instance, You can have the following renderItem method for a FlatList

renderItem = ({item, index}) => {
  return <TouchableOpacity onPress={() => doSomething(index)}  />
}

You see we have to pass an inline callback here (which is bad for performance) cause we need to pass on the specific index of the item, for each item.

With the feature we added, the user can do the following

doSomething = (touchableProps) => {
  const {index} = touchableProps;
  console.log('item index is:`, index)
}

renderItem = ({item, index}) => {
  return <TouchableOpacity onPress={doSomething} index={index}  />
}

Here we didn't have to pass an inline callback, we passed the callback by ref and another custom prop, the index.

That's why props in the onPress callback type is any, cause the user can basically pass/accept anything here.

Let me know if it's not clear, we can sync about It quickly..

/**
* Pass controlled pressState to track gesture state changes
*/
pressState?: State;
/**
* If true, disable all interactions for this component.
*/
disabled?: boolean;
/**
* Pass custom style
*/
style?: ViewProps['style'];
/**
* Custom value of any type to pass on to TouchableOpacity and receive back in onPress callback
*/
customValue?: any;
onLayout?: (event: LayoutChangeEvent) => void;
testID?: string;
};

type Props = PropsWithChildren<TouchableOpacityProps & BaseComponentInjectedProps & ForwardRefInjectedProps>;

/**
* @description: a Better, enhanced TouchableOpacity component
* @modifiers: flex, margin, padding, background
* @example: https://github.com/wix/react-native-ui-lib/blob/master/demo/src/screens/incubatorScreens/TouchableOpacityScreen.js
*/
function TouchableOpacity(props: Props) {
const {
children,
modifiers,
style,
disabled,
forwardedRef,
feedbackColor,
activeOpacity = 0.2,
activeScale = 1,
...others
} = props;
const {borderRadius, paddings, margins, alignments, flexStyle} = modifiers;

const isActive = useSharedValue(0);
/* This flag is for fixing an issue with long press triggering twice
TODO: Consider revisiting this issue to see if it still occurs */
const isLongPressed = useSharedValue(false);

const backgroundColor = useMemo(() => {
return props.backgroundColor || modifiers.backgroundColor;
}, [props.backgroundColor, modifiers.backgroundColor]);

const onPress = useCallback(() => {
props.onPress?.(props);
}, [props.onPress, props.customValue]);

const onLongPress = useCallback(() => {
props.onLongPress?.(props);
}, [props.onLongPress, props.customValue]);

const toggleActive = (value: number) => {
'worklet';
isActive.value = withTiming(value, {duration: 200});
};

const tapGestureHandler = useAnimatedGestureHandler({
onStart: () => {
toggleActive(1);
},
onEnd: () => {
toggleActive(0);

runOnJS(onPress)();
},
onFail: () => {
toggleActive(0);
}
});

const longPressGestureHandler = useAnimatedGestureHandler({
onActive: () => {
if (!isLongPressed.value) {
isLongPressed.value = true;
toggleActive(0);
runOnJS(onLongPress)();
}
},
onFinish: () => {
isLongPressed.value = false;
}
});

const animatedStyle = useAnimatedStyle(() => {
const activeColor = feedbackColor || backgroundColor;
const opacity = interpolate(isActive.value, [0, 1], [1, activeOpacity]);
const scale = interpolate(isActive.value, [0, 1], [1, activeScale]);

return {
backgroundColor: interpolateColor(isActive.value, [0, 1], [backgroundColor, activeColor]),
opacity,
transform: [{scale}]
};
}, [backgroundColor, feedbackColor]);

return (
<TapGestureHandler
// @ts-expect-error
onGestureEvent={tapGestureHandler}
shouldCancelWhenOutside
enabled={!disabled}
>
<Reanimated.View>
{/* @ts-expect-error */}
<LongPressGestureHandler onGestureEvent={longPressGestureHandler} shouldCancelWhenOutside>
<Reanimated.View
{...others}
ref={forwardedRef}
style={[
borderRadius && {borderRadius},
flexStyle,
paddings,
margins,
alignments,
backgroundColor && {backgroundColor},
style,
animatedStyle
]}
>
{children}
</Reanimated.View>
</LongPressGestureHandler>
</Reanimated.View>
</TapGestureHandler>
);
}

TouchableOpacity.displayName = 'Incubator.TouchableOpacity';

export default asBaseComponent<TouchableOpacityProps>(forwardRef<Props>(TouchableOpacity));
1 change: 1 addition & 0 deletions src/incubator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
export {default as TabController} from './TabController';
export {default as TextField, TextFieldProps, FieldContextType} from './TextField';
export {default as TouchableOpacity, TouchableOpacityProps} from './TouchableOpacity';
export {default as TouchableOpacity2} from './TouchableOpacity2';
export {default as WheelPicker, WheelPickerProps} from './WheelPicker';