-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathContainer.tsx
More file actions
503 lines (466 loc) · 14.2 KB
/
Container.tsx
File metadata and controls
503 lines (466 loc) · 14.2 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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import React, { useCallback } from 'react'
import { StyleSheet, useWindowDimensions, View } from 'react-native'
import PagerView from 'react-native-pager-view'
import Animated, {
runOnJS,
runOnUI,
useAnimatedReaction,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
withDelay,
withTiming,
useFrameCallback,
} from 'react-native-reanimated'
import { Context, TabNameContext } from './Context'
import { Lazy } from './Lazy'
import { MaterialTabBar, TABBAR_HEIGHT } from './MaterialTabBar'
import { Tab } from './Tab'
import { IS_IOS, ONE_FRAME_MS, scrollToImpl } from './helpers'
import {
useAnimatedDynamicRefs,
useContainerRef,
usePageScrollHandler,
useTabProps,
useLayoutHeight,
} from './hooks'
import {
CollapsibleProps,
CollapsibleRef,
ContextType,
IndexChangeEventData,
TabName,
} from './types'
const AnimatedPagerView = Animated.createAnimatedComponent(PagerView)
/**
* Basic usage looks like this:
*
* ```tsx
* import { Tabs } from 'react-native-collapsible-tab-view'
*
* const Example = () => {
* return (
* <Tabs.Container renderHeader={MyHeader}>
* <Tabs.Tab name="A">
* <ScreenA />
* </Tabs.Tab>
* <Tabs.Tab name="B">
* <ScreenB />
* </Tabs.Tab>
* </Tabs.Container>
* )
* }
* ```
*/
export const Container = React.memo(
React.forwardRef<CollapsibleRef, CollapsibleProps>(
(
{
initialTabName,
headerHeight: initialHeaderHeight,
minHeaderHeight = 0,
tabBarHeight: initialTabBarHeight = TABBAR_HEIGHT,
revealHeaderOnScroll = false,
snapThreshold,
children,
renderHeader,
renderTabBar = (props) => <MaterialTabBar {...props} />,
headerContainerStyle,
cancelTranslation,
containerStyle,
pagerProps,
onIndexChange,
onTabChange,
lazy,
cancelLazyFadeIn,
width: customWidth,
allowHeaderOverscroll,
},
ref
) => {
const containerRef = useContainerRef()
const [tabProps, tabNamesArray] = useTabProps(children, Tab)
const [refMap, setRef] = useAnimatedDynamicRefs()
const windowWidth = useWindowDimensions().width
const width = customWidth ?? windowWidth
const [containerHeight, getContainerLayoutHeight] = useLayoutHeight()
const [tabBarHeight, getTabBarHeight] =
useLayoutHeight(initialTabBarHeight)
const [headerHeight, getHeaderHeight] = useLayoutHeight(
!renderHeader ? 0 : initialHeaderHeight
)
const initialIndex = React.useMemo(
() =>
initialTabName
? tabNamesArray.findIndex((n) => n === initialTabName)
: 0,
[initialTabName, tabNamesArray]
)
const contentInset = React.useMemo(() => {
if (allowHeaderOverscroll) return 0
// necessary for the refresh control on iOS to be positioned underneath the header
// this also adjusts the scroll bars to clamp underneath the header area
return IS_IOS ? (headerHeight || 0) + (tabBarHeight || 0) : 0
}, [headerHeight, tabBarHeight, allowHeaderOverscroll])
const snappingTo: ContextType['snappingTo'] = useSharedValue(0)
const offset: ContextType['offset'] = useSharedValue(0)
const accScrollY: ContextType['accScrollY'] = useSharedValue(0)
const oldAccScrollY: ContextType['oldAccScrollY'] = useSharedValue(0)
const accDiffClamp: ContextType['accDiffClamp'] = useSharedValue(0)
const scrollYCurrent: ContextType['scrollYCurrent'] = useSharedValue(0)
const scrollY: ContextType['scrollY'] = useSharedValue(
Object.fromEntries(tabNamesArray.map((n) => [n, 0]))
)
const contentHeights: ContextType['contentHeights'] = useSharedValue(
tabNamesArray.map(() => 0)
)
const tabNames: ContextType['tabNames'] = useDerivedValue<TabName[]>(
() => tabNamesArray,
[tabNamesArray]
)
const index: ContextType['index'] = useSharedValue(initialIndex)
const focusedTab: ContextType['focusedTab'] =
useDerivedValue<TabName>(() => {
return tabNames.value[index.value]
}, [tabNames])
const calculateNextOffset = useSharedValue(initialIndex)
const headerScrollDistance: ContextType['headerScrollDistance'] =
useDerivedValue(() => {
return headerHeight !== undefined ? headerHeight - minHeaderHeight : 0
}, [headerHeight, minHeaderHeight])
const indexDecimal: ContextType['indexDecimal'] = useSharedValue(
index.value
)
const afterRender = useSharedValue(0)
React.useEffect(() => {
afterRender.value = withDelay(
ONE_FRAME_MS * 5,
withTiming(1, { duration: 0 })
)
}, [afterRender, tabNamesArray])
const resyncTabScroll = () => {
'worklet'
for (const name of tabNamesArray) {
scrollToImpl(
refMap[name],
0,
scrollYCurrent.value - contentInset,
false
)
}
}
// the purpose of this is to scroll to the proper position if dynamic tabs are changing
useAnimatedReaction(
() => {
return afterRender.value === 1
},
(trigger) => {
if (trigger) {
afterRender.value = 0
resyncTabScroll()
}
},
[tabNamesArray, refMap, afterRender, contentInset]
)
// derived from scrollX
// calculate the next offset and index if swiping
// if scrollX changes from tab press,
// the same logic must be done, but knowing
// the next index in advance
useAnimatedReaction(
() => {
const nextIndex = Math.round(indexDecimal.value)
return nextIndex
},
(nextIndex) => {
if (nextIndex !== null && nextIndex !== index.value) {
calculateNextOffset.value = nextIndex
}
},
[]
)
const propagateTabChange = React.useCallback(
(change: IndexChangeEventData<TabName>) => {
onTabChange?.(change)
onIndexChange?.(change.index)
},
[onIndexChange, onTabChange]
)
const syncCurrentTabScrollPosition = () => {
'worklet'
const name = tabNamesArray[index.value]
scrollToImpl(
refMap[name],
0,
scrollYCurrent.value - contentInset,
false
)
}
/*
* We run syncCurrentTabScrollPosition in every frame after the index
* changes for about 1500ms because the Lists can be late to accept the
* scrollTo event we send. This fixes the issue of the scroll position
* jumping when the user changes tab.
* */
const toggleSyncScrollFrame = (toggle: boolean) =>
syncScrollFrame.setActive(toggle)
const syncScrollFrame = useFrameCallback(({ timeSinceFirstFrame }) => {
syncCurrentTabScrollPosition()
if (timeSinceFirstFrame > 1500) {
runOnJS(toggleSyncScrollFrame)(false)
}
}, false)
useAnimatedReaction(
() => {
return calculateNextOffset.value
},
(i) => {
if (i !== index.value) {
offset.value =
scrollY.value[tabNames.value[index.value]] -
scrollY.value[tabNames.value[i]] +
offset.value
runOnJS(propagateTabChange)({
prevIndex: index.value,
index: i,
prevTabName: tabNames.value[index.value],
tabName: tabNames.value[i],
})
index.value = i
if (
typeof scrollY.value[tabNames.value[index.value]] === 'number'
) {
scrollYCurrent.value =
scrollY.value[tabNames.value[index.value]] || 0
}
runOnJS(toggleSyncScrollFrame)(true)
}
},
[]
)
useAnimatedReaction(
() => headerHeight,
(_current, prev) => {
if (prev === undefined) {
// sync scroll if we started with undefined header height
resyncTabScroll()
}
}
)
const headerTranslateY = useDerivedValue(() => {
return revealHeaderOnScroll
? -accDiffClamp.value
: -Math.min(scrollYCurrent.value, headerScrollDistance.value)
}, [revealHeaderOnScroll])
const stylez = useAnimatedStyle(() => {
return {
transform: [
{
translateY: headerTranslateY.value,
},
],
}
}, [revealHeaderOnScroll])
const onTabPress = React.useCallback(
(name: TabName) => {
const i = tabNames.value.findIndex((n) => n === name)
if (name === focusedTab.value) {
const ref = refMap[name]
runOnUI(scrollToImpl)(
ref,
0,
headerScrollDistance.value - contentInset,
true
)
} else {
containerRef.current?.setPage(i)
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[containerRef, refMap, contentInset]
)
useAnimatedReaction(
() => tabNamesArray.length,
(tabLength) => {
if (index.value >= tabLength) {
runOnJS(onTabPress)(tabNamesArray[tabLength - 1])
}
}
)
const pageScrollHandler = usePageScrollHandler({
onPageScroll: (e) => {
'worklet'
indexDecimal.value = e.position + e.offset
},
})
React.useImperativeHandle(
ref,
() => ({
setIndex: (index) => {
const name = tabNames.value[index]
onTabPress(name)
return true
},
jumpToTab: (name) => {
onTabPress(name)
return true
},
getFocusedTab: () => {
return tabNames.value[index.value]
},
getCurrentIndex: () => {
return index.value
},
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[onTabPress]
)
const renderContent = useCallback(
(tabName: string, i: number) => {
if (lazy) {
return (
<Lazy
startMounted={lazy ? undefined : true}
cancelLazyFadeIn={!lazy ? true : !!cancelLazyFadeIn}
// ensure that we remount the tab if its name changes but the index doesn't
key={tabName}
>
{React.Children.toArray(children)[i] as React.ReactElement}
</Lazy>
)
}
return (
<>{React.Children.toArray(children)[i] as React.ReactElement}</>
)
},
[cancelLazyFadeIn, children, lazy]
)
return (
<Context.Provider
value={{
contentInset,
tabBarHeight,
headerHeight,
refMap,
tabNames,
index,
snapThreshold,
revealHeaderOnScroll,
focusedTab,
accDiffClamp,
indexDecimal,
containerHeight,
minHeaderHeight,
scrollYCurrent,
scrollY,
setRef,
headerScrollDistance,
accScrollY,
oldAccScrollY,
offset,
snappingTo,
contentHeights,
headerTranslateY,
width,
allowHeaderOverscroll,
}}
>
<Animated.View
style={[styles.container, { width }, containerStyle]}
onLayout={getContainerLayoutHeight}
pointerEvents="box-none"
>
<Animated.View
pointerEvents="box-none"
style={[
styles.topContainer,
headerContainerStyle,
!cancelTranslation && stylez,
]}
>
<View
style={[styles.container, styles.headerContainer]}
onLayout={getHeaderHeight}
pointerEvents="box-none"
>
{renderHeader &&
renderHeader({
containerRef,
index,
tabNames: tabNamesArray,
focusedTab,
indexDecimal,
onTabPress,
tabProps,
})}
</View>
<View
style={[styles.container, styles.tabBarContainer]}
onLayout={getTabBarHeight}
pointerEvents="box-none"
>
{renderTabBar &&
renderTabBar({
containerRef,
index,
tabNames: tabNamesArray,
focusedTab,
indexDecimal,
width,
onTabPress,
tabProps,
})}
</View>
</Animated.View>
<AnimatedPagerView
ref={containerRef}
onPageScroll={pageScrollHandler}
initialPage={initialIndex}
{...pagerProps}
style={[pagerProps?.style, StyleSheet.absoluteFill]}
>
{tabNamesArray.map((tabName, i) => {
return (
<View key={i} style={styles.pageContainer}>
<TabNameContext.Provider value={tabName}>
{renderContent(tabName, i)}
</TabNameContext.Provider>
</View>
)
})}
</AnimatedPagerView>
</Animated.View>
</Context.Provider>
)
}
)
)
const styles = StyleSheet.create({
container: {
flex: 1,
},
pageContainer: {
height: '100%',
width: '100%',
},
topContainer: {
position: 'absolute',
zIndex: 100,
width: '100%',
backgroundColor: 'white',
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.23,
shadowRadius: 2.62,
elevation: 4,
},
tabBarContainer: {
zIndex: 1,
},
headerContainer: {
zIndex: 2,
},
})