-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
/
Tabs.js
953 lines (870 loc) · 28.2 KB
/
Tabs.js
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
'use client';
import * as React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@mui/utils';
import { unstable_composeClasses as composeClasses, useSlotProps } from '@mui/base';
import styled from '../styles/styled';
import useThemeProps from '../styles/useThemeProps';
import useTheme from '../styles/useTheme';
import debounce from '../utils/debounce';
import { getNormalizedScrollLeft, detectScrollType } from '../utils/scrollLeft';
import animate from '../internal/animate';
import ScrollbarSize from './ScrollbarSize';
import TabScrollButton from '../TabScrollButton';
import useEventCallback from '../utils/useEventCallback';
import tabsClasses, { getTabsUtilityClass } from './tabsClasses';
import ownerDocument from '../utils/ownerDocument';
import ownerWindow from '../utils/ownerWindow';
const nextItem = (list, item) => {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return list.firstChild;
};
const previousItem = (list, item) => {
if (list === item) {
return list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return list.lastChild;
};
const moveFocus = (list, currentFocus, traversalFunction) => {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return;
}
wrappedOnce = true;
}
// Same logic as useAutocomplete.js
const nextFocusDisabled =
nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
if (!nextFocus.hasAttribute('tabindex') || nextFocusDisabled) {
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus);
} else {
nextFocus.focus();
return;
}
}
};
const useUtilityClasses = (ownerState) => {
const {
vertical,
fixed,
hideScrollbar,
scrollableX,
scrollableY,
centered,
scrollButtonsHideMobile,
classes,
} = ownerState;
const slots = {
root: ['root', vertical && 'vertical'],
scroller: [
'scroller',
fixed && 'fixed',
hideScrollbar && 'hideScrollbar',
scrollableX && 'scrollableX',
scrollableY && 'scrollableY',
],
flexContainer: ['flexContainer', vertical && 'flexContainerVertical', centered && 'centered'],
indicator: ['indicator'],
scrollButtons: ['scrollButtons', scrollButtonsHideMobile && 'scrollButtonsHideMobile'],
scrollableX: [scrollableX && 'scrollableX'],
hideScrollbar: [hideScrollbar && 'hideScrollbar'],
};
return composeClasses(slots, getTabsUtilityClass, classes);
};
const TabsRoot = styled('div', {
name: 'MuiTabs',
slot: 'Root',
overridesResolver: (props, styles) => {
const { ownerState } = props;
return [
{ [`& .${tabsClasses.scrollButtons}`]: styles.scrollButtons },
{
[`& .${tabsClasses.scrollButtons}`]:
ownerState.scrollButtonsHideMobile && styles.scrollButtonsHideMobile,
},
styles.root,
ownerState.vertical && styles.vertical,
];
},
})(({ ownerState, theme }) => ({
overflow: 'hidden',
minHeight: 48,
// Add iOS momentum scrolling for iOS < 13.0
WebkitOverflowScrolling: 'touch',
display: 'flex',
...(ownerState.vertical && {
flexDirection: 'column',
}),
...(ownerState.scrollButtonsHideMobile && {
[`& .${tabsClasses.scrollButtons}`]: {
[theme.breakpoints.down('sm')]: {
display: 'none',
},
},
}),
}));
const TabsScroller = styled('div', {
name: 'MuiTabs',
slot: 'Scroller',
overridesResolver: (props, styles) => {
const { ownerState } = props;
return [
styles.scroller,
ownerState.fixed && styles.fixed,
ownerState.hideScrollbar && styles.hideScrollbar,
ownerState.scrollableX && styles.scrollableX,
ownerState.scrollableY && styles.scrollableY,
];
},
})(({ ownerState }) => ({
position: 'relative',
display: 'inline-block',
flex: '1 1 auto',
whiteSpace: 'nowrap',
...(ownerState.fixed && {
overflowX: 'hidden',
width: '100%',
}),
...(ownerState.hideScrollbar && {
// Hide dimensionless scrollbar on macOS
scrollbarWidth: 'none', // Firefox
'&::-webkit-scrollbar': {
display: 'none', // Safari + Chrome
},
}),
...(ownerState.scrollableX && {
overflowX: 'auto',
overflowY: 'hidden',
}),
...(ownerState.scrollableY && {
overflowY: 'auto',
overflowX: 'hidden',
}),
}));
const FlexContainer = styled('div', {
name: 'MuiTabs',
slot: 'FlexContainer',
overridesResolver: (props, styles) => {
const { ownerState } = props;
return [
styles.flexContainer,
ownerState.vertical && styles.flexContainerVertical,
ownerState.centered && styles.centered,
];
},
})(({ ownerState }) => ({
display: 'flex',
...(ownerState.vertical && {
flexDirection: 'column',
}),
...(ownerState.centered && {
justifyContent: 'center',
}),
}));
const TabsIndicator = styled('span', {
name: 'MuiTabs',
slot: 'Indicator',
overridesResolver: (props, styles) => styles.indicator,
})(({ ownerState, theme }) => ({
position: 'absolute',
height: 2,
bottom: 0,
width: '100%',
transition: theme.transitions.create(),
...(ownerState.indicatorColor === 'primary' && {
backgroundColor: (theme.vars || theme).palette.primary.main,
}),
...(ownerState.indicatorColor === 'secondary' && {
backgroundColor: (theme.vars || theme).palette.secondary.main,
}),
...(ownerState.vertical && {
height: '100%',
width: 2,
right: 0,
}),
}));
const TabsScrollbarSize = styled(ScrollbarSize, {
name: 'MuiTabs',
slot: 'ScrollbarSize',
})({
overflowX: 'auto',
overflowY: 'hidden',
// Hide dimensionless scrollbar on macOS
scrollbarWidth: 'none', // Firefox
'&::-webkit-scrollbar': {
display: 'none', // Safari + Chrome
},
});
const defaultIndicatorStyle = {};
let warnedOnceTabPresent = false;
const Tabs = React.forwardRef(function Tabs(inProps, ref) {
const props = useThemeProps({ props: inProps, name: 'MuiTabs' });
const theme = useTheme();
const isRtl = theme.direction === 'rtl';
const {
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
action,
centered = false,
children: childrenProp,
className,
component = 'div',
allowScrollButtonsMobile = false,
indicatorColor = 'primary',
onChange,
orientation = 'horizontal',
ScrollButtonComponent = TabScrollButton,
scrollButtons = 'auto',
selectionFollowsFocus,
slots = {},
slotProps = {},
TabIndicatorProps = {},
TabScrollButtonProps = {},
textColor = 'primary',
value,
variant = 'standard',
visibleScrollbar = false,
...other
} = props;
const scrollable = variant === 'scrollable';
const vertical = orientation === 'vertical';
const scrollStart = vertical ? 'scrollTop' : 'scrollLeft';
const start = vertical ? 'top' : 'left';
const end = vertical ? 'bottom' : 'right';
const clientSize = vertical ? 'clientHeight' : 'clientWidth';
const size = vertical ? 'height' : 'width';
const ownerState = {
...props,
component,
allowScrollButtonsMobile,
indicatorColor,
orientation,
vertical,
scrollButtons,
textColor,
variant,
visibleScrollbar,
fixed: !scrollable,
hideScrollbar: scrollable && !visibleScrollbar,
scrollableX: scrollable && !vertical,
scrollableY: scrollable && vertical,
centered: centered && !scrollable,
scrollButtonsHideMobile: !allowScrollButtonsMobile,
};
const classes = useUtilityClasses(ownerState);
const startScrollButtonIconProps = useSlotProps({
elementType: slots.StartScrollButtonIcon,
externalSlotProps: slotProps.startScrollButtonIcon,
ownerState,
});
const endScrollButtonIconProps = useSlotProps({
elementType: slots.EndScrollButtonIcon,
externalSlotProps: slotProps.endScrollButtonIcon,
ownerState,
});
if (process.env.NODE_ENV !== 'production') {
if (centered && scrollable) {
console.error(
'MUI: You can not use the `centered={true}` and `variant="scrollable"` properties ' +
'at the same time on a `Tabs` component.',
);
}
}
const [mounted, setMounted] = React.useState(false);
const [indicatorStyle, setIndicatorStyle] = React.useState(defaultIndicatorStyle);
const [displayStartScroll, setDisplayStartScroll] = React.useState(false);
const [displayEndScroll, setDisplayEndScroll] = React.useState(false);
const [updateScrollObserver, setUpdateScrollObserver] = React.useState(false);
const [scrollerStyle, setScrollerStyle] = React.useState({
overflow: 'hidden',
scrollbarWidth: 0,
});
const valueToIndex = new Map();
const tabsRef = React.useRef(null);
const tabListRef = React.useRef(null);
const getTabsMeta = () => {
const tabsNode = tabsRef.current;
let tabsMeta;
if (tabsNode) {
const rect = tabsNode.getBoundingClientRect();
// create a new object with ClientRect class props + scrollLeft
tabsMeta = {
clientWidth: tabsNode.clientWidth,
scrollLeft: tabsNode.scrollLeft,
scrollTop: tabsNode.scrollTop,
scrollLeftNormalized: getNormalizedScrollLeft(tabsNode, theme.direction),
scrollWidth: tabsNode.scrollWidth,
top: rect.top,
bottom: rect.bottom,
left: rect.left,
right: rect.right,
};
}
let tabMeta;
if (tabsNode && value !== false) {
const children = tabListRef.current.children;
if (children.length > 0) {
const tab = children[valueToIndex.get(value)];
if (process.env.NODE_ENV !== 'production') {
if (!tab) {
console.error(
[
`MUI: The \`value\` provided to the Tabs component is invalid.`,
`None of the Tabs' children match with "${value}".`,
valueToIndex.keys
? `You can provide one of the following values: ${Array.from(
valueToIndex.keys(),
).join(', ')}.`
: null,
].join('\n'),
);
}
}
tabMeta = tab ? tab.getBoundingClientRect() : null;
if (process.env.NODE_ENV !== 'production') {
if (
process.env.NODE_ENV !== 'test' &&
!warnedOnceTabPresent &&
tabMeta &&
tabMeta.width === 0 &&
tabMeta.height === 0 &&
// if the whole Tabs component is hidden, don't warn
tabsMeta.clientWidth !== 0
) {
tabsMeta = null;
console.error(
[
'MUI: The `value` provided to the Tabs component is invalid.',
`The Tab with this \`value\` ("${value}") is not part of the document layout.`,
"Make sure the tab item is present in the document or that it's not `display: none`.",
].join('\n'),
);
warnedOnceTabPresent = true;
}
}
}
}
return { tabsMeta, tabMeta };
};
const updateIndicatorState = useEventCallback(() => {
const { tabsMeta, tabMeta } = getTabsMeta();
let startValue = 0;
let startIndicator;
if (vertical) {
startIndicator = 'top';
if (tabMeta && tabsMeta) {
startValue = tabMeta.top - tabsMeta.top + tabsMeta.scrollTop;
}
} else {
startIndicator = isRtl ? 'right' : 'left';
if (tabMeta && tabsMeta) {
const correction = isRtl
? tabsMeta.scrollLeftNormalized + tabsMeta.clientWidth - tabsMeta.scrollWidth
: tabsMeta.scrollLeft;
startValue =
(isRtl ? -1 : 1) * (tabMeta[startIndicator] - tabsMeta[startIndicator] + correction);
}
}
const newIndicatorStyle = {
[startIndicator]: startValue,
// May be wrong until the font is loaded.
[size]: tabMeta ? tabMeta[size] : 0,
};
// IE11 support, replace with Number.isNaN
// eslint-disable-next-line no-restricted-globals
if (isNaN(indicatorStyle[startIndicator]) || isNaN(indicatorStyle[size])) {
setIndicatorStyle(newIndicatorStyle);
} else {
const dStart = Math.abs(indicatorStyle[startIndicator] - newIndicatorStyle[startIndicator]);
const dSize = Math.abs(indicatorStyle[size] - newIndicatorStyle[size]);
if (dStart >= 1 || dSize >= 1) {
setIndicatorStyle(newIndicatorStyle);
}
}
});
const scroll = (scrollValue, { animation = true } = {}) => {
if (animation) {
animate(scrollStart, tabsRef.current, scrollValue, {
duration: theme.transitions.duration.standard,
});
} else {
tabsRef.current[scrollStart] = scrollValue;
}
};
const moveTabsScroll = (delta) => {
let scrollValue = tabsRef.current[scrollStart];
if (vertical) {
scrollValue += delta;
} else {
scrollValue += delta * (isRtl ? -1 : 1);
// Fix for Edge
scrollValue *= isRtl && detectScrollType() === 'reverse' ? -1 : 1;
}
scroll(scrollValue);
};
const getScrollSize = () => {
const containerSize = tabsRef.current[clientSize];
let totalSize = 0;
const children = Array.from(tabListRef.current.children);
for (let i = 0; i < children.length; i += 1) {
const tab = children[i];
if (totalSize + tab[clientSize] > containerSize) {
// If the first item is longer than the container size, then only scroll
// by the container size.
if (i === 0) {
totalSize = containerSize;
}
break;
}
totalSize += tab[clientSize];
}
return totalSize;
};
const handleStartScrollClick = () => {
moveTabsScroll(-1 * getScrollSize());
};
const handleEndScrollClick = () => {
moveTabsScroll(getScrollSize());
};
// TODO Remove <ScrollbarSize /> as browser support for hiding the scrollbar
// with CSS improves.
const handleScrollbarSizeChange = React.useCallback((scrollbarWidth) => {
setScrollerStyle({
overflow: null,
scrollbarWidth,
});
}, []);
const getConditionalElements = () => {
const conditionalElements = {};
conditionalElements.scrollbarSizeListener = scrollable ? (
<TabsScrollbarSize
onChange={handleScrollbarSizeChange}
className={clsx(classes.scrollableX, classes.hideScrollbar)}
/>
) : null;
const scrollButtonsActive = displayStartScroll || displayEndScroll;
const showScrollButtons =
scrollable && ((scrollButtons === 'auto' && scrollButtonsActive) || scrollButtons === true);
conditionalElements.scrollButtonStart = showScrollButtons ? (
<ScrollButtonComponent
slots={{ StartScrollButtonIcon: slots.StartScrollButtonIcon }}
slotProps={{ startScrollButtonIcon: startScrollButtonIconProps }}
orientation={orientation}
direction={isRtl ? 'right' : 'left'}
onClick={handleStartScrollClick}
disabled={!displayStartScroll}
{...TabScrollButtonProps}
className={clsx(classes.scrollButtons, TabScrollButtonProps.className)}
/>
) : null;
conditionalElements.scrollButtonEnd = showScrollButtons ? (
<ScrollButtonComponent
slots={{ EndScrollButtonIcon: slots.EndScrollButtonIcon }}
slotProps={{
endScrollButtonIcon: endScrollButtonIconProps,
}}
orientation={orientation}
direction={isRtl ? 'left' : 'right'}
onClick={handleEndScrollClick}
disabled={!displayEndScroll}
{...TabScrollButtonProps}
className={clsx(classes.scrollButtons, TabScrollButtonProps.className)}
/>
) : null;
return conditionalElements;
};
const scrollSelectedIntoView = useEventCallback((animation) => {
const { tabsMeta, tabMeta } = getTabsMeta();
if (!tabMeta || !tabsMeta) {
return;
}
if (tabMeta[start] < tabsMeta[start]) {
// left side of button is out of view
const nextScrollStart = tabsMeta[scrollStart] + (tabMeta[start] - tabsMeta[start]);
scroll(nextScrollStart, { animation });
} else if (tabMeta[end] > tabsMeta[end]) {
// right side of button is out of view
const nextScrollStart = tabsMeta[scrollStart] + (tabMeta[end] - tabsMeta[end]);
scroll(nextScrollStart, { animation });
}
});
const updateScrollButtonState = useEventCallback(() => {
if (scrollable && scrollButtons !== false) {
setUpdateScrollObserver(!updateScrollObserver);
}
});
React.useEffect(() => {
const handleResize = debounce(() => {
// If the Tabs component is replaced by Suspense with a fallback, the last
// ResizeObserver's handler that runs because of the change in the layout is trying to
// access a dom node that is no longer there (as the fallback component is being shown instead).
// See https://github.com/mui/material-ui/issues/33276
// TODO: Add tests that will ensure the component is not failing when
// replaced by Suspense with a fallback, once React is updated to version 18
if (tabsRef.current) {
updateIndicatorState();
}
});
const win = ownerWindow(tabsRef.current);
win.addEventListener('resize', handleResize);
let resizeObserver;
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(handleResize);
Array.from(tabListRef.current.children).forEach((child) => {
resizeObserver.observe(child);
});
}
return () => {
handleResize.clear();
win.removeEventListener('resize', handleResize);
if (resizeObserver) {
resizeObserver.disconnect();
}
};
}, [updateIndicatorState]);
/**
* Toggle visibility of start and end scroll buttons
* Using IntersectionObserver on first and last Tabs.
*/
React.useEffect(() => {
const tabListChildren = Array.from(tabListRef.current.children);
const length = tabListChildren.length;
if (
typeof IntersectionObserver !== 'undefined' &&
length > 0 &&
scrollable &&
scrollButtons !== false
) {
const firstTab = tabListChildren[0];
const lastTab = tabListChildren[length - 1];
const observerOptions = {
root: tabsRef.current,
threshold: 0.99,
};
const handleScrollButtonStart = (entries) => {
setDisplayStartScroll(!entries[0].isIntersecting);
};
const firstObserver = new IntersectionObserver(handleScrollButtonStart, observerOptions);
firstObserver.observe(firstTab);
const handleScrollButtonEnd = (entries) => {
setDisplayEndScroll(!entries[0].isIntersecting);
};
const lastObserver = new IntersectionObserver(handleScrollButtonEnd, observerOptions);
lastObserver.observe(lastTab);
return () => {
firstObserver.disconnect();
lastObserver.disconnect();
};
}
return undefined;
}, [scrollable, scrollButtons, updateScrollObserver, childrenProp?.length]);
React.useEffect(() => {
setMounted(true);
}, []);
React.useEffect(() => {
updateIndicatorState();
});
React.useEffect(() => {
// Don't animate on the first render.
scrollSelectedIntoView(defaultIndicatorStyle !== indicatorStyle);
}, [scrollSelectedIntoView, indicatorStyle]);
React.useImperativeHandle(
action,
() => ({
updateIndicator: updateIndicatorState,
updateScrollButtons: updateScrollButtonState,
}),
[updateIndicatorState, updateScrollButtonState],
);
const indicator = (
<TabsIndicator
{...TabIndicatorProps}
className={clsx(classes.indicator, TabIndicatorProps.className)}
ownerState={ownerState}
style={{
...indicatorStyle,
...TabIndicatorProps.style,
}}
/>
);
let childIndex = 0;
const children = React.Children.map(childrenProp, (child) => {
if (!React.isValidElement(child)) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(
[
"MUI: The Tabs component doesn't accept a Fragment as a child.",
'Consider providing an array instead.',
].join('\n'),
);
}
}
const childValue = child.props.value === undefined ? childIndex : child.props.value;
valueToIndex.set(childValue, childIndex);
const selected = childValue === value;
childIndex += 1;
return React.cloneElement(child, {
fullWidth: variant === 'fullWidth',
indicator: selected && !mounted && indicator,
selected,
selectionFollowsFocus,
onChange,
textColor,
value: childValue,
...(childIndex === 1 && value === false && !child.props.tabIndex ? { tabIndex: 0 } : {}),
});
});
const handleKeyDown = (event) => {
const list = tabListRef.current;
const currentFocus = ownerDocument(list).activeElement;
// Keyboard navigation assumes that [role="tab"] are siblings
// though we might warn in the future about nested, interactive elements
// as a a11y violation
const role = currentFocus.getAttribute('role');
if (role !== 'tab') {
return;
}
let previousItemKey = orientation === 'horizontal' ? 'ArrowLeft' : 'ArrowUp';
let nextItemKey = orientation === 'horizontal' ? 'ArrowRight' : 'ArrowDown';
if (orientation === 'horizontal' && isRtl) {
// swap previousItemKey with nextItemKey
previousItemKey = 'ArrowRight';
nextItemKey = 'ArrowLeft';
}
switch (event.key) {
case previousItemKey:
event.preventDefault();
moveFocus(list, currentFocus, previousItem);
break;
case nextItemKey:
event.preventDefault();
moveFocus(list, currentFocus, nextItem);
break;
case 'Home':
event.preventDefault();
moveFocus(list, null, nextItem);
break;
case 'End':
event.preventDefault();
moveFocus(list, null, previousItem);
break;
default:
break;
}
};
const conditionalElements = getConditionalElements();
return (
<TabsRoot
className={clsx(classes.root, className)}
ownerState={ownerState}
ref={ref}
as={component}
{...other}
>
{conditionalElements.scrollButtonStart}
{conditionalElements.scrollbarSizeListener}
<TabsScroller
className={classes.scroller}
ownerState={ownerState}
style={{
overflow: scrollerStyle.overflow,
[vertical ? `margin${isRtl ? 'Left' : 'Right'}` : 'marginBottom']: visibleScrollbar
? undefined
: -scrollerStyle.scrollbarWidth,
}}
ref={tabsRef}
>
{/* The tablist isn't interactive but the tabs are */}
<FlexContainer
aria-label={ariaLabel}
aria-labelledby={ariaLabelledBy}
aria-orientation={orientation === 'vertical' ? 'vertical' : null}
className={classes.flexContainer}
ownerState={ownerState}
onKeyDown={handleKeyDown}
ref={tabListRef}
role="tablist"
>
{children}
</FlexContainer>
{mounted && indicator}
</TabsScroller>
{conditionalElements.scrollButtonEnd}
</TabsRoot>
);
});
Tabs.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Callback fired when the component mounts.
* This is useful when you want to trigger an action programmatically.
* It supports two actions: `updateIndicator()` and `updateScrollButtons()`
*
* @param {object} actions This object contains all possible actions
* that can be triggered programmatically.
*/
action: refType,
/**
* If `true`, the scroll buttons aren't forced hidden on mobile.
* By default the scroll buttons are hidden on mobile and takes precedence over `scrollButtons`.
* @default false
*/
allowScrollButtonsMobile: PropTypes.bool,
/**
* The label for the Tabs as a string.
*/
'aria-label': PropTypes.string,
/**
* An id or list of ids separated by a space that label the Tabs.
*/
'aria-labelledby': PropTypes.string,
/**
* If `true`, the tabs are centered.
* This prop is intended for large views.
* @default false
*/
centered: PropTypes.bool,
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* Determines the color of the indicator.
* @default 'primary'
*/
indicatorColor: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['primary', 'secondary']),
PropTypes.string,
]),
/**
* Callback fired when the value changes.
*
* @param {React.SyntheticEvent} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {any} value We default to the index of the child (number)
*/
onChange: PropTypes.func,
/**
* The component orientation (layout flow direction).
* @default 'horizontal'
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The component used to render the scroll buttons.
* @default TabScrollButton
*/
ScrollButtonComponent: PropTypes.elementType,
/**
* Determine behavior of scroll buttons when tabs are set to scroll:
*
* - `auto` will only present them when not all the items are visible.
* - `true` will always present them.
* - `false` will never present them.
*
* By default the scroll buttons are hidden on mobile.
* This behavior can be disabled with `allowScrollButtonsMobile`.
* @default 'auto'
*/
scrollButtons: PropTypes /* @typescript-to-proptypes-ignore */.oneOf(['auto', false, true]),
/**
* If `true` the selected tab changes on focus. Otherwise it only
* changes on activation.
*/
selectionFollowsFocus: PropTypes.bool,
/**
* The extra props for the slot components.
* You can override the existing props or add new ones.
* @default {}
*/
slotProps: PropTypes.shape({
endScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
startScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside.
* @default {}
*/
slots: PropTypes.shape({
EndScrollButtonIcon: PropTypes.elementType,
StartScrollButtonIcon: PropTypes.elementType,
}),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])),
PropTypes.func,
PropTypes.object,
]),
/**
* Props applied to the tab indicator element.
* @default {}
*/
TabIndicatorProps: PropTypes.object,
/**
* Props applied to the [`TabScrollButton`](/material-ui/api/tab-scroll-button/) element.
* @default {}
*/
TabScrollButtonProps: PropTypes.object,
/**
* Determines the color of the `Tab`.
* @default 'primary'
*/
textColor: PropTypes.oneOf(['inherit', 'primary', 'secondary']),
/**
* The value of the currently selected `Tab`.
* If you don't want any selected `Tab`, you can set this prop to `false`.
*/
value: PropTypes.any,
/**
* Determines additional display behavior of the tabs:
*
* - `scrollable` will invoke scrolling properties and allow for horizontally
* scrolling (or swiping) of the tab bar.
* -`fullWidth` will make the tabs grow to use all the available space,
* which should be used for small views, like on mobile.
* - `standard` will render the default state.
* @default 'standard'
*/
variant: PropTypes.oneOf(['fullWidth', 'scrollable', 'standard']),
/**
* If `true`, the scrollbar is visible. It can be useful when displaying
* a long vertical list of tabs.
* @default false
*/
visibleScrollbar: PropTypes.bool,
};
export default Tabs;