-
Notifications
You must be signed in to change notification settings - Fork 372
Expand file tree
/
Copy pathKeyboardCompatibleViewFC.tsx
More file actions
248 lines (219 loc) · 7.12 KB
/
KeyboardCompatibleViewFC.tsx
File metadata and controls
248 lines (219 loc) · 7.12 KB
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
import React, { useEffect, useRef, useState } from 'react';
import {
AppState,
AppStateStatus,
EmitterSubscription,
Keyboard,
KeyboardAvoidingViewProps,
KeyboardEvent,
KeyboardEventListener,
KeyboardMetrics,
LayoutAnimation,
LayoutChangeEvent,
LayoutRectangle,
Platform,
StyleSheet,
View,
} from 'react-native';
import { KeyboardProvider } from '../../contexts/keyboardContext/KeyboardContext';
/**
* View that moves out of the way when the keyboard appears by automatically
* adjusting its height, position, or bottom padding.
*
* Following piece of code has been mostly copied from KeyboardAvoidingView component, with few additional tweaks.
*/
export const KeyboardCompatibleView = ({
behavior = Platform.OS === 'ios' ? 'padding' : 'position',
children,
contentContainerStyle,
enabled = true,
keyboardVerticalOffset = Platform.OS === 'ios' ? 86.5 : -300,
style,
...props
}: KeyboardAvoidingViewProps) => {
const frame = useRef<LayoutRectangle>(undefined);
const initialFrameHeight = useRef(0);
const keyboardEvent = useRef<KeyboardEvent>(undefined);
const subscriptions = useRef<EmitterSubscription[]>([]);
const viewRef = useRef<View | null>(null);
const [appState, setAppState] = useState<AppStateStatus>(AppState.currentState);
const [bottom, setBottom] = useState(0);
const [isKeyboardOpen, setIsKeyboardOpen] = useState(false);
useEffect(() => {
const handleAppStateChange = (nextAppState: AppStateStatus) => {
if (appState.match(/inactive|background/) && nextAppState === 'active') {
setKeyboardListeners();
}
if (nextAppState.match(/inactive|background/)) {
unsetKeyboardListeners();
}
setAppState(nextAppState);
};
const onKeyboardChange: KeyboardEventListener = (event) => {
keyboardEvent.current = event;
};
const setKeyboardListeners = () => {
if (Platform.OS === 'ios') {
subscriptions.current = [
Keyboard.addListener('keyboardWillChangeFrame', onKeyboardChange),
Keyboard.addListener('keyboardDidHide', () => {
setIsKeyboardOpen(false);
}),
Keyboard.addListener('keyboardDidShow', () => {
setIsKeyboardOpen(true);
}),
];
} else {
subscriptions.current = [
Keyboard.addListener('keyboardDidHide', (event) => {
onKeyboardChange(event);
setIsKeyboardOpen(false);
}),
Keyboard.addListener('keyboardDidShow', (event) => {
onKeyboardChange(event);
setIsKeyboardOpen(true);
}),
];
}
};
const unsetKeyboardListeners = () => {
subscriptions.current = subscriptions.current.filter((subscription) => {
subscription.remove();
return false;
});
};
const subscription = AppState.addEventListener('change', handleAppStateChange);
setKeyboardListeners();
return () => {
// Following if-else condition to avoid deprecated warning coming RN 0.65
if (subscription?.remove) {
subscription?.remove();
}
// @ts-ignore
else if (AppState.removeEventListener) {
// @ts-ignore
AppState.removeEventListener('change', handleAppStateChange);
}
unsetKeyboardListeners();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
updateBottomIfNecessary();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [keyboardEvent.current]);
const dismissKeyboard: () => Promise<void> | undefined = () => {
if (!isKeyboardOpen) {
return;
}
return new Promise((resolve) => {
const subscription = Keyboard.addListener('keyboardDidHide', () => {
resolve();
subscription.remove();
});
Keyboard.dismiss();
});
};
const onLayout: (event: LayoutChangeEvent) => void = (event) => {
frame.current = event.nativeEvent.layout;
if (!initialFrameHeight.current) {
// save the initial frame height, before the keyboard is visible
initialFrameHeight.current = frame.current.height;
}
updateBottomIfNecessary();
};
const relativeKeyboardHeight = (keyboardFrame: KeyboardMetrics) => {
if (!frame.current || !keyboardFrame) {
return 0;
}
const keyboardY = keyboardFrame.screenY - keyboardVerticalOffset;
// Calculate the displacement needed for the view such that it
// no longer overlaps with the keyboard
return Math.max(frame.current.y + frame.current.height - keyboardY, 0);
};
const updateBottomIfNecessary = () => {
if (!keyboardEvent.current) {
setBottom(0);
return;
}
const { duration, easing, endCoordinates } = keyboardEvent.current;
const height = relativeKeyboardHeight(endCoordinates);
if (bottom === height) {
return;
}
if (duration && easing) {
LayoutAnimation.configureNext({
// We have to pass the duration equal to minimal accepted duration defined here: RCTLayoutAnimation.m
duration: duration > 10 ? duration : 10,
update: {
duration: duration > 10 ? duration : 10,
type: LayoutAnimation.Types[easing] || 'keyboard',
},
});
}
setBottom(height);
};
const bottomHeight = enabled ? bottom : 0;
switch (behavior) {
case 'height':
// eslint-disable-next-line no-case-declarations
let heightStyle;
if (frame.current && bottom > 0) {
// Note that we only apply a height change when there is keyboard present,
// i.e. this.state.bottom is greater than 0. If we remove that condition,
// this.frame.height will never go back to its original value.
// When height changes, we need to disable flex.
heightStyle = {
flex: 0,
height: initialFrameHeight.current - bottomHeight,
};
}
return (
<KeyboardProvider value={{ dismissKeyboard }}>
<View
onLayout={onLayout}
ref={viewRef}
style={StyleSheet.compose(style, heightStyle)}
{...props}
>
{children}
</View>
</KeyboardProvider>
);
case 'position':
return (
<KeyboardProvider value={{ dismissKeyboard }}>
<View onLayout={onLayout} ref={viewRef} style={style} {...props}>
<View
style={StyleSheet.compose(contentContainerStyle, {
bottom: bottomHeight,
})}
>
{children}
</View>
</View>
</KeyboardProvider>
);
case 'padding':
return (
<KeyboardProvider value={{ dismissKeyboard }}>
<View
onLayout={onLayout}
ref={viewRef}
style={StyleSheet.compose(style, { paddingBottom: bottomHeight })}
{...props}
>
{children}
</View>
</KeyboardProvider>
);
default:
return (
<KeyboardProvider value={{ dismissKeyboard }}>
<View onLayout={onLayout} ref={viewRef} style={style} {...props}>
{children}
</View>
</KeyboardProvider>
);
}
};