-
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
BottomTabBar.tsx
470 lines (420 loc) · 12.7 KB
/
BottomTabBar.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import {
getDefaultSidebarWidth,
getLabel,
MissingIcon,
} from '@react-navigation/elements';
import {
CommonActions,
NavigationContext,
NavigationRouteContext,
type ParamListBase,
type TabNavigationState,
useLinkBuilder,
useTheme,
} from '@react-navigation/native';
import Color from 'color';
import React from 'react';
import {
Animated,
type LayoutChangeEvent,
Platform,
type StyleProp,
StyleSheet,
useWindowDimensions,
View,
type ViewStyle,
} from 'react-native';
import type { EdgeInsets } from 'react-native-safe-area-context';
import type { BottomTabBarProps, BottomTabDescriptorMap } from '../types';
import { BottomTabBarHeightCallbackContext } from '../utils/BottomTabBarHeightCallbackContext';
import { useIsKeyboardShown } from '../utils/useIsKeyboardShown';
import { BottomTabItem } from './BottomTabItem';
type Props = BottomTabBarProps & {
style?: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
};
const DEFAULT_TABBAR_HEIGHT = 49;
const COMPACT_TABBAR_HEIGHT = 32;
const DEFAULT_MAX_TAB_ITEM_WIDTH = 125;
const SPACING = 5;
const useNativeDriver = Platform.OS !== 'web';
type Options = {
state: TabNavigationState<ParamListBase>;
descriptors: BottomTabDescriptorMap;
layout: { height: number; width: number };
dimensions: { height: number; width: number };
};
const shouldUseHorizontalLabels = ({
state,
descriptors,
layout,
dimensions,
}: Options) => {
const { tabBarLabelPosition } =
descriptors[state.routes[state.index].key].options;
if (tabBarLabelPosition) {
switch (tabBarLabelPosition) {
case 'beside-icon':
return true;
case 'below-icon':
return false;
}
}
if (layout.width >= 768) {
// Screen size matches a tablet
const maxTabWidth = state.routes.reduce((acc, route) => {
const { tabBarItemStyle } = descriptors[route.key].options;
const flattenedStyle = StyleSheet.flatten(tabBarItemStyle);
if (flattenedStyle) {
if (typeof flattenedStyle.width === 'number') {
return acc + flattenedStyle.width;
} else if (typeof flattenedStyle.maxWidth === 'number') {
return acc + flattenedStyle.maxWidth;
}
}
return acc + DEFAULT_MAX_TAB_ITEM_WIDTH;
}, 0);
return maxTabWidth <= layout.width;
} else {
return dimensions.width > dimensions.height;
}
};
const getPaddingBottom = (insets: EdgeInsets) =>
Math.max(insets.bottom - Platform.select({ ios: 4, default: 0 }), 0);
export const getTabBarHeight = ({
state,
descriptors,
dimensions,
insets,
style,
...rest
}: Options & {
insets: EdgeInsets;
style: Animated.WithAnimatedValue<StyleProp<ViewStyle>> | undefined;
}) => {
const flattenedStyle = StyleSheet.flatten(style);
const customHeight =
flattenedStyle && 'height' in flattenedStyle
? flattenedStyle.height
: undefined;
if (typeof customHeight === 'number') {
return customHeight;
}
const isLandscape = dimensions.width > dimensions.height;
const horizontalLabels = shouldUseHorizontalLabels({
state,
descriptors,
dimensions,
...rest,
});
const paddingBottom = getPaddingBottom(insets);
if (
Platform.OS === 'ios' &&
!Platform.isPad &&
isLandscape &&
horizontalLabels
) {
return COMPACT_TABBAR_HEIGHT + paddingBottom;
}
return DEFAULT_TABBAR_HEIGHT + paddingBottom;
};
export function BottomTabBar({
state,
navigation,
descriptors,
insets,
style,
}: Props) {
const { colors } = useTheme();
const { buildHref } = useLinkBuilder();
const focusedRoute = state.routes[state.index];
const focusedDescriptor = descriptors[focusedRoute.key];
const focusedOptions = focusedDescriptor.options;
const {
tabBarPosition = 'bottom',
tabBarShowLabel,
tabBarHideOnKeyboard = false,
tabBarVisibilityAnimationConfig,
tabBarStyle,
tabBarBackground,
tabBarActiveTintColor,
tabBarInactiveTintColor,
tabBarActiveBackgroundColor = tabBarPosition !== 'bottom' &&
tabBarPosition !== 'top'
? Color(tabBarActiveTintColor ?? colors.primary)
.alpha(0.12)
.rgb()
.string()
: undefined,
tabBarInactiveBackgroundColor,
} = focusedOptions;
// FIXME: useSafeAreaFrame doesn't update values when window is resized on Web
const dimensions = useWindowDimensions();
const isKeyboardShown = useIsKeyboardShown();
const onHeightChange = React.useContext(BottomTabBarHeightCallbackContext);
const shouldShowTabBar = !(tabBarHideOnKeyboard && isKeyboardShown);
const visibilityAnimationConfigRef = React.useRef(
tabBarVisibilityAnimationConfig
);
React.useEffect(() => {
visibilityAnimationConfigRef.current = tabBarVisibilityAnimationConfig;
});
const [isTabBarHidden, setIsTabBarHidden] = React.useState(!shouldShowTabBar);
const [visible] = React.useState(
() => new Animated.Value(shouldShowTabBar ? 1 : 0)
);
React.useEffect(() => {
const visibilityAnimationConfig = visibilityAnimationConfigRef.current;
if (shouldShowTabBar) {
const animation =
visibilityAnimationConfig?.show?.animation === 'spring'
? Animated.spring
: Animated.timing;
animation(visible, {
toValue: 1,
useNativeDriver,
duration: 250,
...visibilityAnimationConfig?.show?.config,
}).start(({ finished }) => {
if (finished) {
setIsTabBarHidden(false);
}
});
} else {
setIsTabBarHidden(true);
const animation =
visibilityAnimationConfig?.hide?.animation === 'spring'
? Animated.spring
: Animated.timing;
animation(visible, {
toValue: 0,
useNativeDriver,
duration: 200,
...visibilityAnimationConfig?.hide?.config,
}).start();
}
return () => visible.stopAnimation();
}, [visible, shouldShowTabBar]);
const [layout, setLayout] = React.useState({
height: 0,
width: dimensions.width,
});
const handleLayout = (e: LayoutChangeEvent) => {
const { height, width } = e.nativeEvent.layout;
onHeightChange?.(height);
setLayout((layout) => {
if (height === layout.height && width === layout.width) {
return layout;
} else {
return {
height,
width,
};
}
});
};
const { routes } = state;
const paddingBottom = getPaddingBottom(insets);
const tabBarHeight = getTabBarHeight({
state,
descriptors,
insets,
dimensions,
layout,
style: [tabBarStyle, style],
});
const hasHorizontalLabels = shouldUseHorizontalLabels({
state,
descriptors,
dimensions,
layout,
});
const tabBarBackgroundElement = tabBarBackground?.();
const tabBarIsHorizontal =
tabBarPosition === 'bottom' || tabBarPosition === 'top';
return (
<Animated.View
style={[
tabBarPosition === 'left'
? styles.start
: tabBarPosition === 'right'
? styles.end
: styles.bottom,
{
backgroundColor:
tabBarBackgroundElement != null ? 'transparent' : colors.card,
borderColor: colors.border,
},
tabBarIsHorizontal
? [
{
transform: [
{
translateY: visible.interpolate({
inputRange: [0, 1],
outputRange: [
layout.height +
paddingBottom +
StyleSheet.hairlineWidth,
0,
],
}),
},
],
// Absolutely position the tab bar so that the content is below it
// This is needed to avoid gap at bottom when the tab bar is hidden
position: isTabBarHidden ? 'absolute' : undefined,
},
{
height: tabBarHeight,
paddingBottom,
paddingHorizontal: Math.max(insets.left, insets.right),
},
]
: {
paddingTop: insets.top,
paddingBottom: insets.bottom,
paddingStart: tabBarPosition === 'left' ? insets.left : 0,
paddingEnd: tabBarPosition === 'right' ? insets.right : 0,
minWidth: hasHorizontalLabels
? getDefaultSidebarWidth(dimensions)
: 0,
},
tabBarStyle,
]}
pointerEvents={isTabBarHidden ? 'none' : 'auto'}
onLayout={tabBarIsHorizontal ? handleLayout : undefined}
>
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
{tabBarBackgroundElement}
</View>
<View
accessibilityRole="tablist"
style={tabBarIsHorizontal ? styles.bottomContent : styles.sideContent}
>
{routes.map((route, index) => {
const focused = index === state.index;
const { options } = descriptors[route.key];
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
if (!focused && !event.defaultPrevented) {
navigation.dispatch({
...CommonActions.navigate(route),
target: state.key,
});
}
};
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',
target: route.key,
});
};
const label =
typeof options.tabBarLabel === 'function'
? options.tabBarLabel
: getLabel(
{ label: options.tabBarLabel, title: options.title },
route.name
);
const accessibilityLabel =
options.tabBarAccessibilityLabel !== undefined
? options.tabBarAccessibilityLabel
: typeof label === 'string' && Platform.OS === 'ios'
? `${label}, tab, ${index + 1} of ${routes.length}`
: undefined;
return (
<NavigationContext.Provider
key={route.key}
value={descriptors[route.key].navigation}
>
<NavigationRouteContext.Provider value={route}>
<BottomTabItem
href={buildHref(route.name, route.params)}
route={route}
descriptor={descriptors[route.key]}
focused={focused}
horizontal={hasHorizontalLabels}
onPress={onPress}
onLongPress={onLongPress}
accessibilityLabel={accessibilityLabel}
testID={options.tabBarButtonTestID}
allowFontScaling={options.tabBarAllowFontScaling}
activeTintColor={tabBarActiveTintColor}
inactiveTintColor={tabBarInactiveTintColor}
activeBackgroundColor={tabBarActiveBackgroundColor}
inactiveBackgroundColor={tabBarInactiveBackgroundColor}
button={options.tabBarButton}
icon={
options.tabBarIcon ??
(({ color, size }) => (
<MissingIcon color={color} size={size} />
))
}
badge={options.tabBarBadge}
badgeStyle={options.tabBarBadgeStyle}
label={label}
showLabel={tabBarShowLabel}
labelStyle={options.tabBarLabelStyle}
iconStyle={options.tabBarIconStyle}
style={[
tabBarIsHorizontal
? styles.bottomItem
: [
styles.sideItem,
hasHorizontalLabels
? { justifyContent: 'flex-start' }
: null,
],
options.tabBarItemStyle,
]}
/>
</NavigationRouteContext.Provider>
</NavigationContext.Provider>
);
})}
</View>
</Animated.View>
);
}
const styles = StyleSheet.create({
start: {
top: 0,
bottom: 0,
start: 0,
borderEndWidth: StyleSheet.hairlineWidth,
},
end: {
top: 0,
bottom: 0,
end: 0,
borderStartWidth: StyleSheet.hairlineWidth,
},
bottom: {
start: 0,
end: 0,
bottom: 0,
borderTopWidth: StyleSheet.hairlineWidth,
elevation: 8,
},
bottomContent: {
flex: 1,
flexDirection: 'row',
},
sideContent: {
flex: 1,
flexDirection: 'column',
padding: SPACING,
},
bottomItem: {
flex: 1,
},
sideItem: {
margin: SPACING,
padding: SPACING * 2,
borderRadius: 4,
},
});