-
Notifications
You must be signed in to change notification settings - Fork 0
/
TabManager.tsx
219 lines (183 loc) · 6.93 KB
/
TabManager.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
import React, { useEffect, useState, useRef, useLayoutEffect } from 'react'
import { Location, useNavigate } from 'react-router-dom'
import { defaults } from 'lodash'
import { Tab, TabLayout } from './TabLayout'
import { TabContentLoading } from './TabContentLoading'
import { useReadyCore } from '../../routing/ReadyContext'
const defaultUrlParamName = 'tab'
/** Determines the current tab from the `Location` object. */
export function getTabFromLocation(
tabs: Tab[],
location: Location,
options?: {
defaultTabName?: string
urlParamName?: string
}
): string {
if (tabs.length === 0) throw new Error('tabs array cannot be empty.')
const { defaultTabName, urlParamName } = defaults(options, {
urlParamName: defaultUrlParamName,
})
const searchParams = new URLSearchParams(location.search)
const tabParam = searchParams.get(urlParamName)
if (tabParam && tabs.some((t) => t[0] === tabParam)) return tabParam
if (defaultTabName) return defaultTabName
return tabs[0][0]
}
interface UseSmoothTabTransitionOutput {
tabContentRef: React.RefObject<HTMLDivElement>
explicitTabContentHeight: number | undefined
newTabWillMount(): void
}
// When the user switches to a tab that needs to load first, keep the height
// of the tab-content the same until the new tab finishes loading to avoid
// jarring changes in height
function useSmoothTabTransition(
renderTabs: TabManagerRenderTab[],
tab: string
): UseSmoothTabTransitionOutput {
const tabContentRef = useRef<HTMLDivElement>(null)
const [explicitTabContentHeight, setExplicitTabContentHeight] = useState<number>()
const [setHeightTo, setSetHeightTo] = useState<number>()
// When a new tab is about to mount, get the height of the tabContent
// BEFORE the tabs actually switch
function newTabWillMount(): void {
if (tabContentRef.current) {
const height = tabContentRef.current.offsetHeight
if (typeof height === 'number') setSetHeightTo(height)
}
}
// Explicitly set the tabContent height immediately after the new tab becomes
// visible. useLayoutEffect is essential here because we want the effect to
// run *before the browser paints*.
useLayoutEffect(() => {
if (typeof setHeightTo === 'number') {
setExplicitTabContentHeight(setHeightTo)
setSetHeightTo(undefined)
}
}, [setHeightTo])
const currentRenderTab = renderTabs.find((rt) => rt[0] === tab)
// Set explicit height to undefined when new tab becomes ready
useLayoutEffect(() => {
if (typeof explicitTabContentHeight === 'number') {
if (currentRenderTab && currentRenderTab[1]) {
setExplicitTabContentHeight(undefined)
}
}
}, [explicitTabContentHeight, currentRenderTab])
return { tabContentRef, explicitTabContentHeight, newTabWillMount }
}
//
//
//
/**
* A tuple representing the content of a tab in [[`TabManager`]].
*
* The tuple elements represent `tabName`, `isTabReadyForDisplay` (loading
* indicator shown if false), and finally the actual tab content JSX.
*/
export type TabManagerRenderTab = [string, boolean, React.ReactNode]
export interface TabManagerProps {
tabs: Tab[]
children: TabManagerRenderTab[]
defaultTabName?: string
urlParamName?: string
renderLoadingIndicator?: () => React.ReactElement | null
mountAllTabs?: boolean
displaySingleTab?: boolean
className?: string
tabContentClassName?: string
}
/**
* A high-level component for creating user interfaces with tabs.
*
* - It stores the current tab name as a URL search params.
* - It doesn't mount the a tab until the user actually visits that tab. (You can disable this with by setting `mountAllTabs` to true.)
* - It shows a loading indicator if a tab needs to load data before it can render content.
*/
export function TabManager({
tabs,
children,
defaultTabName,
renderLoadingIndicator,
mountAllTabs = false,
urlParamName = defaultUrlParamName,
displaySingleTab = true,
className,
tabContentClassName,
}: TabManagerProps): React.ReactElement | null {
const navigate = useNavigate()
const { location } = useReadyCore()
let tab = ''
if (tabs.length > 0) {
tab = getTabFromLocation(tabs, location, { defaultTabName, urlParamName })
}
const [mountedTabs, setMountedTabs] = useState<string[]>([tab])
const { tabContentRef, explicitTabContentHeight, newTabWillMount } =
useSmoothTabTransition(children, tab)
useEffect(() => {
if (mountAllTabs) return
if (!mountedTabs.includes(tab)) {
setMountedTabs((mountedTabs) => [...mountedTabs, tab])
}
}, [mountedTabs, tab, mountAllTabs])
function onTabClick(tabName: string): void {
if (!mountedTabs.includes(tabName)) newTabWillMount()
const searchParams = new URLSearchParams(location.search)
searchParams.set(urlParamName, tabName)
navigate(
{
...location,
search: searchParams.toString(),
},
{ replace: true }
)
}
const tabNames = mountAllTabs
? new Set<string>(tabs.map((t) => t[0]))
: new Set<string>()
function renderTab(theRenderTab: TabManagerRenderTab): React.ReactElement | null {
const [thisTabName, ready, reactNode] = theRenderTab
if (!mountAllTabs && !mountedTabs.includes(thisTabName)) return null
// We allow the `children` array to include tabs that are not in the
// `tabs` array. This makes it simpler to implement tabs that are only
// visible for users with certain permissions.
if (mountAllTabs && !tabNames.has(thisTabName)) return null
return (
<div
style={{
display: tab === thisTabName ? undefined : 'none',
}}
className={!ready ? 'render-tab-loading' : undefined}
key={thisTabName}
>
{!ready && (
<TabContentLoading renderLoadingIndicator={renderLoadingIndicator} />
)}
<div hidden={!ready}>{reactNode}</div>
</div>
)
}
if (tabs.length === 1 && !displaySingleTab) {
if (!children || children.length === 0) return null
// Display contents without a tab or border
return renderTab(children[0])
}
return (
<TabLayout
tabs={tabs}
tab={tab}
onTabClick={onTabClick}
tabContentRef={tabContentRef}
tabContentStyle={
typeof explicitTabContentHeight === 'number'
? { height: explicitTabContentHeight }
: undefined
}
className={className}
tabContentClassName={tabContentClassName}
>
{children && children.map(renderTab)}
</TabLayout>
)
}