-
Notifications
You must be signed in to change notification settings - Fork 0
/
Modal.tsx
236 lines (224 loc) · 6.88 KB
/
Modal.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
import React from 'react';
import {
Animated,
ColorValue,
Dimensions,
KeyboardAvoidingView,
Modal as RNModal,
ModalProps as RNModalProps,
PanResponder,
PanResponderInstance,
Platform,
Pressable,
StyleProp,
StyleSheet,
TouchableWithoutFeedback,
useWindowDimensions,
ViewStyle,
} from 'react-native';
import { useHeaderContext } from '../contexts/HeaderContext';
import { useThemeContext } from '../contexts/ThemeContext';
import createStyleSheet from '../styles/createStyleSheet';
type ModalProps = {
type?: 'slide' | 'fade' | undefined;
onRequestClose: () => void;
backgroundStyle?: StyleProp<ViewStyle> | undefined;
disableBackgroundClose?: boolean | undefined;
enableKeyboardAvoid?: boolean | undefined;
backdropColor?: ColorValue | undefined;
} & Omit<RNModalProps, 'animationType' | 'onRequestClose'>;
const useModalPanResponder = (
type: 'slide' | 'fade',
translateY: Animated.Value,
show: () => void,
hide: () => void
): PanResponderInstance => {
const isHideGesture = React.useCallback(
(distanceY: number, velocityY: number) => {
return distanceY > 125 || (distanceY > 0 && velocityY > 0.1);
},
[]
);
const r = React.useRef(
PanResponder.create({
onMoveShouldSetPanResponderCapture: (_, { dy }) => dy > 8,
onPanResponderGrant: (_, __) =>
// @ts-ignore
translateY.setOffset(translateY.__getValue()),
onPanResponderMove: (_, { dy }) => dy >= 0 && translateY.setValue(dy), // Animated.event([null, { dy: translateY }], { useNativeDriver: false }),
onPanResponderRelease: (_, { dy, vy }) => {
if (isHideGesture(dy, vy)) hide();
else show();
},
})
).current;
if (type === 'fade') return { panHandlers: {} };
else return r;
};
/**
* Use custom animations.
* Custom animation has two features:
* 1. It can control the animation speed and
* 2. It can prevent fast interaction.
* For example, if the total length of the animation is 1 second, no interaction can be performed within 1 second.
* @param type animate type
* @returns animate object
*/
const useModalAnimation = (type: 'slide' | 'fade') => {
const initialY = type === 'slide' ? Dimensions.get('window').height : 0;
const baseAnimBackground = React.useRef(new Animated.Value(0)).current;
const baseAnimContent = React.useRef(new Animated.Value(initialY)).current;
const content = {
opacity: baseAnimBackground.interpolate({
inputRange: [0, 1],
outputRange: [type === 'slide' ? 1 : 0, 1],
}),
translateY: baseAnimContent,
};
const backdrop = {
opacity: baseAnimBackground.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
}),
};
const createTransition = (toValue: 0 | 1) => {
const config = { duration: 250, useNativeDriver: false };
return Animated.parallel([
Animated.timing(baseAnimBackground, { toValue, ...config }),
Animated.timing(baseAnimContent, {
toValue: toValue === 0 ? initialY : 0,
...config,
}),
]).start;
};
return {
content,
backdrop,
showTransition: createTransition(1),
hideTransition: createTransition(0),
};
};
// NOTE: onDismiss is supports iOS only
const useOnDismiss = (visible: boolean, onDismiss?: () => void) => {
const prevVisible = usePrevProp(visible);
React.useEffect(() => {
if (Platform.OS === 'ios') return;
if (prevVisible && !visible) onDismiss?.();
}, [onDismiss, prevVisible, visible]);
};
const usePrevProp = <T,>(prop: T) => {
const prev = React.useRef(prop);
const curr = React.useRef(prop);
React.useEffect(() => {
prev.current = curr.current;
curr.current = prop;
});
return prev.current;
};
/**
* Modal Open: Triggered by Modal.props.visible state changed to true
* - visible true -> modalVisible true -> animation start
*
* Modal Close: Triggered by Modal.props.onRequestClose() call
* - Modal.props.onRequestClose() -> visible false -> animation start -> modalVisible false
* */
export default function Modal({
children,
onRequestClose,
backgroundStyle,
onDismiss,
type = 'fade',
visible = false,
disableBackgroundClose = false,
enableKeyboardAvoid = false,
statusBarTranslucent,
backdropColor,
transparent,
...props
}: ModalProps): JSX.Element {
const { colors } = useThemeContext();
const { width, height } = useWindowDimensions();
const { defaultHeight } = useHeaderContext();
const [modalVisible, setModalVisible] = React.useState(false);
const { content, backdrop, showTransition, hideTransition } =
useModalAnimation(type);
const panResponder = useModalPanResponder(
type,
content.translateY,
showTransition,
onRequestClose
);
React.useEffect(() => {
if (visible) setModalVisible(true);
else hideTransition((_) => setModalVisible(false));
}, [hideTransition, visible]);
useOnDismiss(modalVisible, onDismiss);
return (
<RNModal
transparent={transparent}
hardwareAccelerated
visible={modalVisible}
onRequestClose={onRequestClose}
onShow={() => showTransition()}
onDismiss={onDismiss}
supportedOrientations={[
'portrait',
'portrait-upside-down',
'landscape',
'landscape-left',
'landscape-right',
]}
animationType="none"
{...props}
>
<TouchableWithoutFeedback
onPress={disableBackgroundClose ? undefined : onRequestClose}
>
<Animated.View
style={[
StyleSheet.absoluteFill,
{
opacity: transparent ? (backdropColor ? backdrop.opacity : 0) : 1,
backgroundColor: backdropColor ?? colors.backdrop,
},
]}
/>
</TouchableWithoutFeedback>
<KeyboardAvoidingView
// NOTE: This is trick for Android.
// When orientation is changed on Android, the offset that to avoid soft-keyboard is not updated normally.
key={`${width}-${height}`}
enabled={enableKeyboardAvoid}
style={styles.background}
behavior={Platform.select({ ios: 'padding', default: 'height' })}
pointerEvents="box-none"
keyboardVerticalOffset={
enableKeyboardAvoid && statusBarTranslucent ? -defaultHeight : 0
}
>
<Animated.View
style={[
styles.background,
backgroundStyle,
{
opacity: content.opacity,
transform: [{ translateY: content.translateY }],
},
]}
pointerEvents="box-none"
{...panResponder.panHandlers}
>
<Pressable
// NOTE: https://github.com/facebook/react-native/issues/14295
// Due to 'Pressable', the width of the children must be explicitly specified as a number.
>
{children}
</Pressable>
</Animated.View>
</KeyboardAvoidingView>
</RNModal>
);
}
const styles = createStyleSheet({
background: { flex: 1 },
});