-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathtabs.tsx
377 lines (339 loc) · 11.7 KB
/
tabs.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
import {
$,
JSXNode,
PropsOf,
Signal,
Slot,
component$,
useContextProvider,
useId,
useSignal,
useTask$,
type FunctionComponent,
} from '@builder.io/qwik';
import { KeyCode } from '../../utils/key-code.type';
import { Behavior } from './behavior.type';
import { findNextEnabledTab, findPrevEnabledTab, getEnabledTab } from './get-enabled-tab';
import { HTab as InternalTab, TabProps } from './tab';
import { HTabPanel as InternalTabPanel, TabPanelProps } from './tab-panel';
import { tabsContextId } from './tabs-context-id';
import { TabsContext } from './tabs-context.type';
import { HTabList as InternalTabList } from './tabs-list';
/**
* TABS TODOs
*
* aria Tabs Pattern https://www.w3.org/WAI/ARIA/apg/patterns/tabs/
* a11y lint plugin https://www.npmjs.com/package/eslint-plugin-jsx-a11y
* POST Beta
* Add automated tests for preventDefault on end, home, pageDown, pageUp
* POST V1:
* - RTL
* NOTE: scrolling support? or multiple lines? (probably not for headless but for tailwind / material )
* Add ability to close tabs with an ❌ icon (and keyboard support)
*
*/
export type TabsProps = PropsOf<'div'> & {
behavior?: Behavior;
selectedTabId?: string;
selectedIndex?: number;
vertical?: boolean;
// TODO rename to selectedClass
selectedClassName?: string;
onSelectedIndexChange$?: (index: number) => void;
onSelectedTabIdChange$?: (tabId: string) => void;
'bind:selectedIndex'?: Signal<number | undefined>;
'bind:selectedTabId'?: Signal<string | undefined>;
/** @deprecated was for the shorthand API that we decided to no longer support as part of the headless kit */
tabClass?: PropsOf<'div'>['class'];
/** @deprecated was for the shorthand API that we decided to no longer support as part of the headless kit */
panelClass?: PropsOf<'div'>['class'];
tabListComponent?: typeof InternalTabList;
tabComponent?: typeof InternalTab;
tabPanelComponent?: typeof InternalTabPanel;
};
export type TabInfo = {
tabId: string;
index: number;
tabProps: TabProps;
panelProps: TabPanelProps;
};
// This function reads the children, assigns indexes and creates a
// standard structure. It must take care to retain the props objects
// unchanged so signals keep working
export const HTabs: FunctionComponent<TabsProps> = (props) => {
const {
children,
tabListComponent: UserTabList,
tabComponent: UserTab,
tabPanelComponent: UserTabPanel,
...rest
} = props;
const TabList = UserTabList ? UserTabList : InternalTabList;
const Tab = UserTab ? UserTab : InternalTab;
const TabPanel = UserTabPanel ? UserTabPanel : InternalTabPanel;
const childrenToProcess = Array.isArray(children) ? [...children] : [children];
let tabListComponent: JSXNode | undefined;
const tabComponents: JSXNode[] = [];
const panelComponents: JSXNode[] = [];
const tabInfoList: TabInfo[] = [];
let panelIndex = 0;
let selectedIndex;
// Extract the Tab related components from the children
while (childrenToProcess.length) {
const child = childrenToProcess.shift() as JSXNode;
if (!child) {
continue;
}
if (Array.isArray(child)) {
childrenToProcess.unshift(...child);
continue;
}
switch (child.type) {
case TabList: {
tabListComponent = child;
const tabListChildren = Array.isArray(child.props.children)
? child.props.children
: [child.props.children];
childrenToProcess.unshift(...tabListChildren);
break;
}
case Tab: {
if (child.props.selected) {
const currentTabIndex = tabComponents.length;
selectedIndex = currentTabIndex;
child.props.selected = undefined;
}
tabComponents.push(child);
break;
}
case TabPanel: {
const { selected } = child.props as TabPanelProps;
// The consumer must provide a key if they change the order
const matchedTabComponent = tabComponents[panelIndex];
const tabIdFromTabMaybe =
(matchedTabComponent?.props as TabProps).tabId || matchedTabComponent?.key;
const tabId: string = tabIdFromTabMaybe || child.key || `${panelIndex}`;
if (selected) {
selectedIndex = panelIndex;
child.props.selected = undefined;
}
// Always assign a key
child.key = tabId;
// Add props but don't replace the object
child.props._tabId = tabId;
panelComponents.push(child);
tabInfoList.push({
tabId,
index: panelIndex,
tabProps: {},
panelProps: child.props,
} as TabInfo);
panelIndex++;
break;
}
default: {
console.error(`unhandled component ${child.type} given to Tabs`);
}
}
}
if (tabComponents.length !== panelIndex) {
console.error(
`mismatched number of tabs and panels: ${tabComponents.length} ${panelIndex}`,
);
}
tabComponents.forEach((tab, index) => {
const tabId = tabInfoList[index]?.tabId;
tab.key = tabId;
tab.props.tabId = tabId;
if (
tabInfoList[index].panelProps.disabled !== undefined &&
tab.props.disabled === undefined
) {
tab.props.disabled = tabInfoList[index].panelProps.disabled;
}
tabInfoList[index].tabProps = tab.props as TabProps;
});
if (tabListComponent) {
tabListComponent.children = tabComponents;
tabListComponent.props.children = tabComponents;
} else {
// Creating it as <TabList /> and adding children later doesn't work
tabListComponent = (<TabList>{tabComponents}</TabList>) as JSXNode<typeof TabList>;
}
if (typeof selectedIndex === 'number') {
rest.selectedIndex = selectedIndex;
}
return (
<TabsImpl tabInfoList={tabInfoList} {...rest}>
{tabListComponent}
{panelComponents}
</TabsImpl>
);
};
export const TabsImpl = component$((props: TabsProps & { tabInfoList: TabInfo[] }) => {
const {
// We take these out of the props for the DOM element but we must refer
// to them as e.g. props.tabs for reactivity
tabInfoList: _0,
behavior = 'manual',
selectedTabId: _1,
selectedIndex: _2,
vertical,
selectedClassName,
onSelectedIndexChange$,
onSelectedTabIdChange$,
'bind:selectedIndex': givenIndexSig,
'bind:selectedTabId': givenTabIdSig,
...rest
} = props;
const tabsPrefix = useId();
const ref = useSignal<HTMLElement | undefined>();
const initialSelectedIndexSig = useSignal<number>();
const selectedIndexSig = givenIndexSig || initialSelectedIndexSig;
const initialSelectedTabIdSig = useSignal<string>();
const selectedTabIdSig = givenTabIdSig || initialSelectedTabIdSig;
useTask$(function syncTabsTask({ track }) {
// Possible optimizer bug: tracking only works with props.tabs (and not with destructuring from props)
// TODO: Write a test in Qwik optimizer to prove this bug
const tabInfoList = track(() => props.tabInfoList);
const tabId = selectedTabIdSig.value;
syncSelectedStateSignals(
tabInfoList,
selectedIndexSig,
selectedTabIdSig,
{ tabIdToSelect: tabId },
true,
);
});
useTask$(function syncPropSelectedIndexTask({ track }) {
const updatedIndexFromProps = track(() => props.selectedIndex);
syncSelectedStateSignals(props.tabInfoList, selectedIndexSig, selectedTabIdSig, {
indexToSelect: updatedIndexFromProps,
});
});
useTask$(function syncSelectedIndexSigTask({ track }) {
const updatedIndexSignal = track(() => selectedIndexSig.value);
syncSelectedStateSignals(props.tabInfoList, selectedIndexSig, selectedTabIdSig, {
indexToSelect: updatedIndexSignal,
});
if (typeof selectedIndexSig.value !== 'undefined') {
onSelectedIndexChange$?.(selectedIndexSig.value);
}
});
useTask$(function syncPropSelectedTabIdTask({ track }) {
const updatedTabIdFromProps = track(() => props.selectedTabId);
syncSelectedStateSignals(props.tabInfoList, selectedIndexSig, selectedTabIdSig, {
tabIdToSelect: updatedTabIdFromProps,
});
});
useTask$(function syncSelectedTabIdSigTask({ track }) {
let updatedTabId = track(() => selectedTabIdSig.value);
// If we don't have a tabId by the time this task runs, select the first enabled tab
if (typeof updatedTabId !== 'string') {
const tab = getEnabledTab(props.tabInfoList, 0);
if (tab) {
updatedTabId = tab.tabId;
}
}
syncSelectedStateSignals(props.tabInfoList, selectedIndexSig, selectedTabIdSig, {
tabIdToSelect: updatedTabId,
});
if (typeof selectedTabIdSig.value !== 'undefined') {
onSelectedTabIdChange$?.(selectedTabIdSig.value);
}
});
useTask$(function callOnSelectedChangeTask({ track }) {
if (!onSelectedIndexChange$) return;
const idx = track(() => selectedIndexSig.value);
if (typeof idx === 'number' && idx >= 0) onSelectedIndexChange$(idx);
});
const selectTab$ = $((tabId: string) => {
syncSelectedStateSignals(props.tabInfoList, selectedIndexSig, selectedTabIdSig, {
tabIdToSelect: tabId,
});
});
const selectIfAutomatic$ = $((tabId: string) => {
if (behavior === 'automatic') {
selectTab$(tabId);
}
});
const onTabKeyDown$ = $((key: KeyCode, currentTabId: string) => {
const tabsRootElement = ref.value;
const currentFocusedTabIndex = props.tabInfoList.findIndex(
(tabData) => tabData.tabId === currentTabId,
);
let tabInfo;
if (
(!vertical && key === KeyCode.ArrowRight) ||
(vertical && key === KeyCode.ArrowDown)
) {
tabInfo = findNextEnabledTab(props.tabInfoList, currentFocusedTabIndex + 1, {
wrap: true,
});
} else if (
(!vertical && key === KeyCode.ArrowLeft) ||
(vertical && key === KeyCode.ArrowUp)
) {
tabInfo = findPrevEnabledTab(props.tabInfoList, currentFocusedTabIndex, {
wrap: true,
});
} else if (key === KeyCode.Home || key === KeyCode.PageUp) {
tabInfo = findNextEnabledTab(props.tabInfoList, 0);
} else if (key === KeyCode.End || key === KeyCode.PageDown) {
tabInfo = findPrevEnabledTab(props.tabInfoList, props.tabInfoList.length);
}
if (tabInfo) {
focusOnTab(tabInfo.index);
}
function focusOnTab(index: number) {
const tabListElement = tabsRootElement?.children[0];
const tabToFocusOn = tabListElement?.children[index] as HTMLElement;
tabToFocusOn.focus();
}
});
const contextService: TabsContext = {
selectTab$,
tabsPrefix,
onTabKeyDown$,
selectIfAutomatic$,
selectedTabIdSig,
selectedClassName,
};
useContextProvider(tabsContextId, contextService);
return (
<div data-qui-tabs-root ref={ref} {...rest}>
<Slot />
</div>
);
});
// This helper function is separate so that it doesn't have to be a QRL
// and it doesn't result in race conditions between tasks
// We were seeing tabId signal task running before updateSignals when it QRL
export const syncSelectedStateSignals = (
tabsInfoList: TabInfo[],
selectedIndexSig: Signal<number | undefined>,
selectedTabIdSig: Signal<string | undefined>,
{ indexToSelect, tabIdToSelect }: { indexToSelect?: number; tabIdToSelect?: string },
ignoreIndexNotFound?: boolean,
) => {
if (tabIdToSelect) {
indexToSelect = tabsInfoList.findIndex((tabInfo) => tabInfo.tabId === tabIdToSelect);
}
if (typeof indexToSelect !== 'number') return;
if (indexToSelect && indexToSelect < 0) {
if (!ignoreIndexNotFound) {
return;
}
// given index doesn't exist, find one nearby
indexToSelect = selectedIndexSig.value;
if (typeof indexToSelect !== 'number') return;
}
const tab = getEnabledTab(tabsInfoList, indexToSelect);
if (
tab &&
(tab.index !== selectedIndexSig.value || tab.tabId !== selectedTabIdSig.value)
) {
selectedIndexSig.value = tab.index;
selectedTabIdSig.value = tab.tabId;
}
};