-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathTab.tsx
More file actions
412 lines (387 loc) · 12.6 KB
/
Copy pathTab.tsx
File metadata and controls
412 lines (387 loc) · 12.6 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
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
/**
* @file Tab.tsx
* @input Uses React, StyleX, TabListContext
* @output Exports Tab component and TabProps type
* @position Core tab item; renders as button or anchor in navigation with a
* divider-overlay selected indicator. Where the TabList speaks the tabs
* pattern it is a button with role="tab".
*
* SYNC: When modified, update:
* - /packages/core/src/TabList/TabList.doc.mjs
* - /packages/core/src/TabList/index.ts
* - /packages/core/src/TabList/TabList.test.tsx
* - /packages/cli/assets/templates/blocks/components/TabList/ (showcase blocks)
*/
import React, {useCallback, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
spacingVars,
sizeVars,
radiusVars,
durationVars,
easeVars,
fontWeightVars,
typeScaleVars,
} from '../theme/tokens.stylex';
import type {BaseProps} from '../BaseProps';
import {useTabListContext} from './TabListContext';
import type {TabListSize} from './TabListContext';
import {tabScope} from './tab.markers.stylex';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
import {mergeProps} from '../utils';
import {useDevWarning} from '../hooks/useDevWarning';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
export interface TabProps extends BaseProps<HTMLButtonElement> {
/**
* Custom component to render instead of `<a>` for link tabs.
* Overrides the provider-level default set by LinkProvider.
* Only applies when `href` is provided. Must accept href, className, style, and children props.
*/
as?: LinkComponentType;
ref?: React.Ref<HTMLButtonElement>;
/**
* Unique value for this tab. Matched against TabListContext.value.
*/
value: string;
/**
* Accessible label for this tab. Used as visible text by default, or
* as aria-label when isLabelHidden is true.
*/
label: string;
/**
* Whether the label is visually hidden. When true, only the icon and
* endContent are displayed, and label is used as aria-label for accessibility.
* @default false
*/
isLabelHidden?: boolean;
/**
* URL to navigate to. When provided, renders as an anchor element.
*
* A tab that navigates keeps the strip on the navigation pattern. Ignored
* only in a TabList given an explicit `role="tablist"`: activating a tab
* there swaps a panel in place, so a tab that navigates would be a false
* statement.
*/
href?: string;
/**
* Id of the panel this tab controls, wired up as `aria-controls` where the
* TabList speaks the tabs pattern. Put the same id on the panel element.
*
* Has no effect under the navigation pattern, where there is no panel to
* associate — including where the strip picked that pattern because it
* holds something that is not a tab.
*/
panelId?: string;
/**
* Icon element shown when tab is not selected.
*/
icon?: ReactNode;
/**
* Icon element shown when tab is selected. Falls back to `icon` if not provided.
*/
selectedIcon?: ReactNode;
/**
* Content rendered after the label (e.g. a badge or status dot).
*/
endContent?: ReactNode;
}
// =============================================================================
// Styles
// =============================================================================
const styles = stylex.create({
base: {
position: 'relative',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: spacingVars['--spacing-1'],
paddingInline: spacingVars['--spacing-3'],
backgroundColor: 'transparent',
borderWidth: 0,
borderStyle: 'none',
borderRadius: radiusVars['--radius-element'],
fontFamily: 'inherit',
fontSize: typeScaleVars['--text-label-size'],
lineHeight: typeScaleVars['--text-label-leading'],
fontWeight: fontWeightVars['--font-weight-normal'],
color: colorVars['--color-text-secondary'],
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
textDecoration: 'none',
whiteSpace: 'nowrap',
transitionProperty: 'color',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
},
hoverBg: {
position: 'absolute',
inset: 0,
margin: 'auto',
width: '100%',
borderRadius: radiusVars['--radius-element'],
pointerEvents: 'none',
backgroundColor: {
default: 'transparent',
[stylex.when.ancestor(':hover', tabScope)]: {
'@media (hover: hover)': colorVars['--color-overlay-hover'],
},
},
transitionProperty: 'background-color',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
},
selected: {
color: colorVars['--color-text-primary'],
fontWeight: fontWeightVars['--font-weight-semibold'],
},
indicator: {
position: 'absolute',
// Sits on the tab's bottom edge by default (-1px). When the tab strip
// reserves space for a divider rail — TabList `hasDivider` or a Toolbar
// with a bottom divider — that ancestor sets `--_tab-indicator-bottom`
// to drop the indicator onto the rail beneath the reserved gap.
bottom: 'var(--_tab-indicator-bottom, -1px)',
insetInlineStart: spacingVars['--spacing-3'],
insetInlineEnd: spacingVars['--spacing-3'],
height: '2px',
borderRadius: radiusVars['--radius-full'],
pointerEvents: 'none',
transitionProperty: 'opacity, background-color',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
},
indicatorSelected: {
backgroundColor: colorVars['--color-accent'],
opacity: 1,
},
indicatorUnselected: {
backgroundColor: 'transparent',
opacity: 0,
},
icon: {
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
},
labelContainer: {
display: 'inline-grid',
},
labelText: {
gridRowStart: 1,
gridColumnStart: 1,
},
labelSizer: {
gridRowStart: 1,
gridColumnStart: 1,
visibility: 'hidden',
pointerEvents: 'none',
fontWeight: fontWeightVars['--font-weight-semibold'],
},
endContentWrapper: {
display: 'inline-flex',
alignItems: 'center',
flexShrink: 0,
},
});
const sizeStyles = stylex.create({
sm: {height: sizeVars['--size-element-sm']},
md: {height: sizeVars['--size-element-md']},
lg: {height: sizeVars['--size-element-lg']},
});
// Hover bg uses the standard element size (one step smaller than tab)
const hoverSizeStyles = stylex.create({
sm: {height: sizeVars['--size-element-sm']},
md: {height: sizeVars['--size-element-md']},
lg: {height: sizeVars['--size-element-lg']},
});
const layoutStyles = stylex.create({
fill: {
flex: 1,
justifyContent: 'center',
},
});
const iconSizeStyles = stylex.create({
sm: {width: '14px', height: '14px'},
md: {width: '16px', height: '16px'},
lg: {width: '18px', height: '18px'},
});
/**
* Tab item component. Renders as an anchor when `href` is provided,
* otherwise as a button.
*
* @example
* ```
* <TabList value={tab} onChange={setTab}>
* <Tab value="general" label="General" />
* <Tab value="advanced" label="Advanced" />
* </TabList>
* ```
*/
export function Tab({
as,
ref,
value,
label,
isLabelHidden = false,
href,
panelId,
icon,
selectedIcon,
endContent,
xstyle,
className,
style,
...restProps
}: TabProps) {
const tabListCtx = useTabListContext();
const LinkComponent = useLinkComponent(as);
const isSelected = tabListCtx.value === value;
const size: TabListSize = tabListCtx.size;
const isFill = tabListCtx.layout === 'fill';
const isTabsPattern = tabListCtx.pattern === 'tabs';
// An href gives way to the tabs pattern only where the consumer asked for
// that pattern. Where the strip picked it, the link stays a link: the strip
// reads its own children back and settles on the navigation pattern, so a
// tab that navigates never ends up inside a tablist.
const isLink = href != null && (!isTabsPattern || tabListCtx.isPatternAuto);
const isTabRole = isTabsPattern && !isLink;
const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;
const hasVisibleLabel = !isLabelHidden && label !== '';
const handleSelect = useCallback(() => {
tabListCtx.onChange(value);
}, [tabListCtx, value]);
useDevWarning(
'Tab',
'href is ignored in a role="tablist" TabList — a tab swaps a panel in ' +
'place rather than navigating. Drop the href, or drop the role and let ' +
'the strip pick its own pattern.',
isTabRole && href != null,
);
// A consumer who wired aria-controls by hand already said which panel this
// is, so panelId is the sugar, not the only way in.
const controls = panelId ?? restProps['aria-controls'];
// Only where the tabs pattern was asked for: a strip left to pick reaches it
// through tabs that were written for the navigation pattern, and scolding
// the consumer for a panel they were never asked for is noise.
useDevWarning(
'Tab',
'a tab in a role="tablist" TabList controls nothing: pass panelId with ' +
'the id of the panel it opens, so assistive technology can associate ' +
'the two.',
isTabRole && !tabListCtx.isPatternAuto && controls == null,
);
const iconElement = displayIcon ? (
<span {...stylex.props(styles.icon, iconSizeStyles[size])}>
{displayIcon}
</span>
) : null;
const sharedProps = {
...restProps,
...(isLabelHidden ? {'aria-label': label} : {}),
[EDGE_COMP_ATTR]: '',
'data-tab-value': value,
...(isTabRole
? {
role: 'tab' as const,
'aria-selected': isSelected,
// Only when there is a panel to point at: an aria-controls whose
// target does not exist is an invalid attribute value, which is a
// worse state than saying nothing. The dev warning above asks for
// the id instead.
'aria-controls': controls,
}
: {
// Generic `true` ("the current item within a set"), not `page`: the
// strip switches views in place at least as often as it navigates,
// and claiming "current page" when no page changed is a false
// statement to a screen reader. Stays truthful for the `href` case
// too, just less specific. A tab role states this with
// aria-selected instead.
'aria-current': isSelected ? ('true' as const) : undefined,
}),
// Roving tabindex: the tab strip is a single Tab stop. The selected tab is
// the tabbable one; the rest are reachable via arrow keys (handled by
// TabList's onKeyDown). When no tab is selected, TabList's repair effect
// makes the first stop tabbable.
tabIndex: isSelected ? 0 : -1,
...mergeProps(
themeProps('tab', {
selected: isSelected ? 'selected' : null,
}),
focusOutlineProps.focusVisible(
styles.base,
sizeStyles[size],
isSelected && styles.selected,
isFill && layoutStyles.fill,
tabScope,
xstyle,
),
className,
style,
),
};
const hoverBgElement = (
<span
aria-hidden="true"
{...stylex.props(styles.hoverBg, hoverSizeStyles[size])}
/>
);
const indicatorElement = (
<span
{...mergeProps(
themeProps('tab-indicator', {
selected: isSelected ? 'selected' : null,
}),
stylex.props(
styles.indicator,
isSelected ? styles.indicatorSelected : styles.indicatorUnselected,
),
)}
/>
);
const labelElement = hasVisibleLabel ? (
<span {...stylex.props(styles.labelContainer)}>
<span {...stylex.props(styles.labelText)}>{label}</span>
<span aria-hidden="true" {...stylex.props(styles.labelSizer)}>
{label}
</span>
</span>
) : null;
const endContentElement = endContent ? (
<span {...stylex.props(styles.endContentWrapper)}>{endContent}</span>
) : null;
if (isLink) {
return (
<LinkComponent
ref={ref}
href={href}
onClick={handleSelect}
{...sharedProps}>
{hoverBgElement}
{iconElement}
{labelElement}
{endContentElement}
{indicatorElement}
</LinkComponent>
);
}
return (
<button ref={ref} type="button" onClick={handleSelect} {...sharedProps}>
{hoverBgElement}
{iconElement}
{labelElement}
{endContentElement}
{indicatorElement}
</button>
);
}
Tab.displayName = 'Tab';