-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathTabs.tsx
1792 lines (1571 loc) · 46.9 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
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { ChevronLeft, ChevronRight } from '@carbon/icons-react';
import { breakpoints } from '@carbon/layout';
import cx from 'classnames';
import { debounce } from 'es-toolkit/compat';
import PropTypes from 'prop-types';
import React, {
useCallback,
useState,
useRef,
useEffect,
forwardRef,
type ReactNode,
type MouseEvent,
type KeyboardEvent,
type SyntheticEvent,
type HTMLAttributes,
type RefObject,
type ComponentType,
type ReactHTML,
type ElementType,
} from 'react';
import { Grid } from '../Grid';
import { isElement } from 'react-is';
import { Tooltip } from '../Tooltip';
import { useControllableState } from '../../internal/useControllableState';
import { useEffectOnce } from '../../internal/useEffectOnce';
import { useId } from '../../internal/useId';
import useIsomorphicEffect from '../../internal/useIsomorphicEffect';
import { useMergedRefs } from '../../internal/useMergedRefs';
import { getInteractiveContent } from '../../internal/useNoInteractiveChildren';
import { usePrefix } from '../../internal/usePrefix';
import { keys, match, matches } from '../../internal/keyboard';
import { usePressable } from './usePressable';
import deprecate from '../../prop-types/deprecate';
import { Close } from '@carbon/icons-react';
import { useEvent } from '../../internal/useEvent';
import { useMatchMedia } from '../../internal/useMatchMedia';
import { Text } from '../Text';
const verticalTabHeight = 64;
// Used to manage the overall state of the Tabs
type TabsContextType = {
baseId: string;
activeIndex: number;
defaultSelectedIndex: number;
dismissable?: boolean;
onTabCloseRequest?(index: number): void;
setActiveIndex(index: number): void;
selectedIndex: number;
setSelectedIndex(index: number): void;
};
const TabsContext = React.createContext<TabsContextType>({
baseId: '',
activeIndex: 0,
defaultSelectedIndex: 0,
dismissable: false,
onTabCloseRequest() {},
setActiveIndex() {},
selectedIndex: 0,
setSelectedIndex() {},
});
// Used to keep track of position in a tablist
const TabContext = React.createContext<{
contained?: boolean;
index: number;
hasSecondaryLabel: boolean;
}>({
index: 0,
hasSecondaryLabel: false,
});
const lgMediaQuery = `(min-width: ${breakpoints.lg.width})`;
const smMediaQuery = `(max-width: ${breakpoints.md.width})`;
// Used to keep track of position in a list of tab panels
const TabPanelContext = React.createContext<number>(0);
type DivAttributes = HTMLAttributes<HTMLDivElement>;
/**
* Tabs
*/
export interface TabsProps {
/**
* Provide child elements to be rendered inside the `Tabs`.
* These elements should render either `TabsList` or `TabsPanels`
*/
children?: ReactNode;
/**
* Specify which content tab should be initially selected when the component
* is first rendered
*/
defaultSelectedIndex?: number;
/**
* Whether the rendered Tab children should be dismissable.
*/
dismissable?: boolean;
/**
* Provide an optional function which is called
* whenever the state of the `Tabs` changes
*/
onChange?(state: { selectedIndex: number }): void;
/**
* If specifying the `onTabCloseRequest` prop, provide a callback function
* responsible for removing the tab when close button is pressed on one of the Tab elements
*/
onTabCloseRequest?(tabIndex: number): void;
/**
* Control which content panel is currently selected. This puts the component
* in a controlled mode and should be used along with `onChange`
*/
selectedIndex?: number;
}
function Tabs({
children,
defaultSelectedIndex = 0,
onChange,
selectedIndex: controlledSelectedIndex,
dismissable,
onTabCloseRequest,
}: TabsProps) {
const baseId = useId('ccs');
// The active index is used to track the element which has focus in our tablist
const [activeIndex, setActiveIndex] = useState(defaultSelectedIndex);
// The selected index is used for the tab/panel pairing which is "visible"
const [selectedIndex, setSelectedIndex] = useControllableState({
value: controlledSelectedIndex,
defaultValue: defaultSelectedIndex,
onChange: (value) => onChange?.({ selectedIndex: value }),
});
const value: TabsContextType = {
baseId,
activeIndex,
defaultSelectedIndex,
dismissable,
onTabCloseRequest,
setActiveIndex,
selectedIndex,
setSelectedIndex,
};
return <TabsContext.Provider value={value}>{children}</TabsContext.Provider>;
}
Tabs.propTypes = {
/**
* Provide child elements to be rendered inside the `Tabs`.
* These elements should render either `TabsList` or `TabsPanels`
*/
children: PropTypes.node,
/**
* Specify which content tab should be initially selected when the component
* is first rendered
*/
defaultSelectedIndex: PropTypes.number,
/**
* Whether the render Tab children should be dismissable.
*/
dismissable: PropTypes.bool,
/**
* Provide an optional function which is called whenever the state of the
* `Tabs` changes
*/
onChange: PropTypes.func,
/**
* If specifying the `onTabCloseRequest` prop, provide a callback function
* responsible for removing the tab when close button is pressed on one of the Tab elements
*/
onTabCloseRequest: (props) => {
if (props.dismissable && !props.onTabCloseRequest) {
return new Error(
'dismissable property specified without also providing an onTabCloseRequest property.'
);
}
return undefined;
},
/**
* Control which content panel is currently selected. This puts the component
* in a controlled mode and should be used along with `onChange`
*/
selectedIndex: PropTypes.number,
};
export interface TabsVerticalProps {
/**
* Provide child elements to be rendered inside the `TabsVertical`.
* These elements should render either `TabsListVertical` or `TabsPanels`
*/
children?: ReactNode;
/**
* Specify which content tab should be initially selected when the component
* is first rendered
*/
defaultSelectedIndex?: number;
/**
* Option to set a height style only if using vertical variation
*/
height?: string;
/**
* Provide an optional function which is called
* whenever the state of the `Tabs` changes
*/
onChange?(state: { selectedIndex: number }): void;
/**
* Control which content panel is currently selected. This puts the component
* in a controlled mode and should be used along with `onChange`
*/
selectedIndex?: number;
}
function TabsVertical({
children,
height,
defaultSelectedIndex = 0,
onChange,
selectedIndex: controlledSelectedIndex,
...rest
}: TabsVerticalProps) {
const [selectedIndex, setSelectedIndex] = useControllableState({
value: controlledSelectedIndex,
defaultValue: defaultSelectedIndex,
onChange: (value) => onChange?.({ selectedIndex: value }),
});
const props = {
...rest,
selectedIndex,
onChange: ({ selectedIndex }) => setSelectedIndex(selectedIndex),
};
const isSm = useMatchMedia(smMediaQuery);
if (!isSm) {
return (
// eslint-disable-next-line react/forbid-component-props
<Grid style={{ height: height }}>
<Tabs {...props}>{children}</Tabs>
</Grid>
);
}
return <Tabs {...props}>{children}</Tabs>;
}
TabsVertical.propTypes = {
/**
* Provide child elements to be rendered inside the `TabsVertical`.
* These elements should render either `TabsListVertical` or `TabsPanels`
*/
children: PropTypes.node,
/**
* Specify which content tab should be initially selected when the component
* is first rendered
*/
defaultSelectedIndex: PropTypes.number,
/**
* Option to set a height style only if using vertical variation
*/
height: PropTypes.string,
/**
* Provide an optional function which is called whenever the state of the
* `Tabs` changes
*/
onChange: PropTypes.func,
/**
* Control which content panel is currently selected. This puts the component
* in a controlled mode and should be used along with `onChange`
*/
selectedIndex: PropTypes.number,
};
/**
* Get the next index for a given keyboard event
* given a count of the total items and the current index
*/
function getNextIndex(
event: SyntheticEvent,
total: number,
index: number
): number {
switch (true) {
case match(event, keys.ArrowRight):
return (index + 1) % total;
case match(event, keys.ArrowLeft):
return (total + index - 1) % total;
case match(event, keys.Home):
return 0;
case match(event, keys.End):
return total - 1;
default:
return index;
}
}
/**
* Get the next index for a given keyboard event
* given a count of the total items and the current index
*/
function getNextIndexVertical(
event: SyntheticEvent,
total: number,
index: number
): number {
switch (true) {
case match(event, keys.ArrowDown):
return (index + 1) % total;
case match(event, keys.ArrowUp):
return (total + index - 1) % total;
case match(event, keys.Home):
return 0;
case match(event, keys.End):
return total - 1;
default:
return index;
}
}
/**
* TabList
*/
export interface TabListProps extends DivAttributes {
/**
* Specify whether the content tab should be activated automatically or
* manually
*/
activation?: 'automatic' | 'manual';
/**
* Provide an accessible label to be read when a user interacts with this
* component
*/
'aria-label': string;
/**
* Provide child elements to be rendered inside `ContentTabs`.
* These elements should render a `ContentTab`
*/
children?: ReactNode;
/**
* Specify an optional className to be added to the container node
*/
className?: string;
/**
* Specify whether component is contained type
*/
contained?: boolean;
/**
* Used for tabs within a grid, this makes it so tabs span the full container width and have the same width. Only available on contained tabs with <9 children
*/
fullWidth?: boolean;
/**
* If using `IconTab`, specify the size of the icon being used.
*/
iconSize?: 'default' | 'lg';
/**
* Provide the props that describe the left overflow button
*/
leftOverflowButtonProps?: HTMLAttributes<HTMLButtonElement>;
/**
* Specify whether to use the light component variant
*/
light?: boolean;
/**
* Provide the props that describe the right overflow button
*/
rightOverflowButtonProps?: HTMLAttributes<HTMLButtonElement>;
/**
* Optionally provide a delay (in milliseconds) passed to the lodash
* debounce of the onScroll handler. This will impact the responsiveness
* of scroll arrow buttons rendering when scrolling to the first or last tab.
*/
scrollDebounceWait?: number;
/**
* Choose whether to automatically scroll to newly selected tabs
* on component rerender
*/
scrollIntoView?: boolean;
}
type TabElement = HTMLElement & { disabled?: boolean };
function TabList({
activation = 'automatic',
'aria-label': label,
children,
className: customClassName,
contained = false,
fullWidth = false,
iconSize,
leftOverflowButtonProps,
light,
rightOverflowButtonProps,
scrollDebounceWait = 200,
scrollIntoView,
...rest
}: TabListProps) {
const {
activeIndex,
selectedIndex,
setSelectedIndex,
setActiveIndex,
dismissable,
} = React.useContext(TabsContext);
const prefix = usePrefix();
const ref = useRef<HTMLDivElement>(null);
const previousButton = useRef<HTMLButtonElement>(null);
const nextButton = useRef<HTMLButtonElement>(null);
const [isScrollable, setIsScrollable] = useState(false);
const [scrollLeft, setScrollLeft] = useState<number>(0);
let hasSecondaryLabelTabs = false;
if (contained) {
hasSecondaryLabelTabs = React.Children.toArray(children).some((child) => {
return isElement(child) && !!child.props.secondaryLabel;
});
}
const isLg = useMatchMedia(lgMediaQuery);
const distributeWidth =
fullWidth &&
contained &&
isLg &&
React.Children.toArray(children).length < 9;
const className = cx(
`${prefix}--tabs`,
{
[`${prefix}--tabs--contained`]: contained,
[`${prefix}--tabs--light`]: light,
[`${prefix}--tabs__icon--default`]: iconSize === 'default',
[`${prefix}--tabs__icon--lg`]: iconSize === 'lg', // TODO: V12 - Remove this class
[`${prefix}--layout--size-lg`]: iconSize === 'lg',
[`${prefix}--tabs--tall`]: hasSecondaryLabelTabs,
[`${prefix}--tabs--full-width`]: distributeWidth,
[`${prefix}--tabs--dismissable`]: dismissable,
},
customClassName
);
// Previous Button
// VISIBLE IF:
// SCROLLABLE
// AND SCROLL_LEFT > 0
const buttonWidth = 44;
// Next Button
// VISIBLE IF:
// SCROLLABLE
// AND SCROLL_LEFT + CLIENT_WIDTH < SCROLL_WIDTH
const [isNextButtonVisible, setIsNextButtonVisible] = useState(
ref.current
? scrollLeft + buttonWidth + ref.current.clientWidth <
ref.current.scrollWidth
: false
);
const isPreviousButtonVisible = ref.current
? isScrollable && scrollLeft > 0
: false;
const previousButtonClasses = cx(
`${prefix}--tab--overflow-nav-button`,
`${prefix}--tab--overflow-nav-button--previous`,
{
[`${prefix}--tab--overflow-nav-button--hidden`]: !isPreviousButtonVisible,
}
);
const nextButtonClasses = cx(
`${prefix}--tab--overflow-nav-button`,
`${prefix}--tab--overflow-nav-button--next`,
{
[`${prefix}--tab--overflow-nav-button--hidden`]: !isNextButtonVisible,
}
);
const tabs = useRef<TabElement[]>([]);
const debouncedOnScroll = useCallback(() => {
return debounce((event) => {
setScrollLeft(event.target.scrollLeft);
}, scrollDebounceWait);
}, [scrollDebounceWait]);
function onKeyDown(event: KeyboardEvent) {
if (
matches(event, [keys.ArrowRight, keys.ArrowLeft, keys.Home, keys.End])
) {
event.preventDefault();
const filteredTabs = tabs.current.filter((tab) => tab !== null);
const activeTabs: TabElement[] = filteredTabs.filter(
(tab) => !tab.disabled
);
const currentIndex = activeTabs.indexOf(
tabs.current[activation === 'automatic' ? selectedIndex : activeIndex]
);
const nextIndex = tabs.current.indexOf(
activeTabs[getNextIndex(event, activeTabs.length, currentIndex)]
);
if (activation === 'automatic') {
setSelectedIndex(nextIndex);
} else if (activation === 'manual') {
setActiveIndex(nextIndex);
}
tabs.current[nextIndex]?.focus();
}
}
function handleBlur({
relatedTarget: currentActiveNode,
}: React.FocusEvent<HTMLDivElement>) {
if (ref.current?.contains(currentActiveNode)) {
return;
}
// reset active index to selected tab index for manual activation
if (activation === 'manual') {
setActiveIndex(selectedIndex);
}
}
/**
* Scroll the tab into view if it is not already visible
* @param tab - The tab to scroll into view
* @returns {void}
*/
function scrollTabIntoView(tab) {
if (!isScrollable || !ref.current) {
return;
}
if (tab) {
// The width of the "scroll buttons"
const { width: tabWidth } = tab.getBoundingClientRect();
// The start and end position of the selected tab
const start = tab.offsetLeft;
const end = tab.offsetLeft + tabWidth;
// The start and end of the visible area for the tabs
const visibleStart = ref.current.scrollLeft + buttonWidth;
const visibleEnd =
ref.current.scrollLeft + ref.current.clientWidth - buttonWidth;
// The beginning of the tab is clipped and not visible
if (start < visibleStart) {
setScrollLeft(start - buttonWidth);
}
// The end of the tab is clipped and not visible
if (end > visibleEnd) {
setScrollLeft(end + buttonWidth - ref.current.clientWidth);
}
}
}
useEffectOnce(() => {
const tab = tabs.current[selectedIndex];
if (scrollIntoView && tab) {
tab.scrollIntoView({
block: 'nearest',
inline: 'nearest',
});
}
});
useEffect(() => {
//adding 1 in calculation for firefox support
setIsNextButtonVisible(
ref.current
? scrollLeft + buttonWidth + ref.current.clientWidth + 1 <
ref.current.scrollWidth
: false
);
if (dismissable) {
if (ref.current) {
setIsScrollable(ref.current.scrollWidth > ref.current.clientWidth);
}
}
}, [scrollLeft, children, dismissable, isScrollable]);
useEffectOnce(() => {
if (tabs.current[selectedIndex]?.disabled) {
const activeTabs = tabs.current.filter((tab) => {
return !tab.disabled;
});
if (activeTabs.length > 0) {
const tab = activeTabs[0];
setSelectedIndex(tabs.current.indexOf(tab));
}
}
});
useIsomorphicEffect(() => {
if (ref.current) {
// adding 1 in calculation for firefox support
setIsScrollable(ref.current.scrollWidth > ref.current.clientWidth + 1);
}
function handler() {
if (ref.current) {
// adding 1 in calculation for firefox support
setIsScrollable(ref.current.scrollWidth > ref.current.clientWidth + 1);
}
}
const debouncedHandler = debounce(handler, 200);
window.addEventListener('resize', debouncedHandler);
return () => {
debouncedHandler.cancel();
window.removeEventListener('resize', debouncedHandler);
};
}, []);
// updates scroll location for all scroll behavior.
useIsomorphicEffect(() => {
if (scrollLeft !== null && ref.current) {
ref.current.scrollLeft = scrollLeft;
}
}, [scrollLeft]);
// scroll manual tabs when active index changes (focus outline movement)
useIsomorphicEffect(() => {
const tab =
activation === 'manual'
? tabs.current[activeIndex]
: tabs.current[selectedIndex];
scrollTabIntoView(tab);
}, [activation, activeIndex]);
// scroll tabs when selected index changes
useIsomorphicEffect(() => {
const tab = tabs.current[selectedIndex];
scrollTabIntoView(tab);
}, [selectedIndex, isScrollable, children]);
usePressable(previousButton, {
onPress({ longPress }) {
if (!longPress && ref.current) {
setScrollLeft(
Math.max(
scrollLeft - (ref.current.scrollWidth / tabs.current.length) * 1.5,
0
)
);
}
},
onLongPress() {
return createLongPressBehavior(ref, 'backward', setScrollLeft);
},
});
usePressable(nextButton, {
onPress({ longPress }) {
if (!longPress && ref.current) {
setScrollLeft(
Math.min(
scrollLeft + (ref.current.scrollWidth / tabs.current.length) * 1.5,
ref.current.scrollWidth - ref.current.clientWidth
)
);
}
},
onLongPress() {
return createLongPressBehavior(ref, 'forward', setScrollLeft);
},
});
return (
<div className={className}>
<button
aria-hidden="true"
tabIndex={-1}
aria-label="Scroll left"
ref={previousButton}
className={previousButtonClasses}
type="button"
{...leftOverflowButtonProps}>
<ChevronLeft />
</button>
{/* eslint-disable-next-line jsx-a11y/interactive-supports-focus */}
<div
{...rest}
aria-label={label}
ref={ref}
role="tablist"
className={`${prefix}--tab--list`}
onScroll={debouncedOnScroll}
onKeyDown={onKeyDown}
onBlur={handleBlur}>
{React.Children.map(children, (child, index) => {
return !isElement(child) ? null : (
<TabContext.Provider
value={{
index,
hasSecondaryLabel: hasSecondaryLabelTabs,
contained,
}}>
{React.cloneElement(child, {
ref: (node) => {
tabs.current[index] = node;
},
})}
</TabContext.Provider>
);
})}
</div>
<button
aria-hidden="true"
tabIndex={-1}
aria-label="Scroll right"
ref={nextButton}
className={nextButtonClasses}
type="button"
{...rightOverflowButtonProps}>
<ChevronRight />
</button>
</div>
);
}
TabList.propTypes = {
/**
* Specify whether the content tab should be activated automatically or
* manually
*/
activation: PropTypes.oneOf(['automatic', 'manual']),
/**
* Provide an accessible label to be read when a user interacts with this
* component
*/
'aria-label': PropTypes.string.isRequired,
/**
* Provide child elements to be rendered inside `ContentTabs`.
* These elements should render a `ContentTab`
*/
children: PropTypes.node,
/**
* Specify an optional className to be added to the container node
*/
className: PropTypes.string,
/**
* Specify whether component is contained type
*/
contained: PropTypes.bool,
/**
* Used for tabs within a grid, this makes it so tabs span the full container width and have the same width. Only available on contained tabs with <9 children
*/
fullWidth: PropTypes.bool,
/**
* If using `IconTab`, specify the size of the icon being used.
*/
iconSize: PropTypes.oneOf(['default', 'lg']),
/**
* Provide the props that describe the left overflow button
*/
leftOverflowButtonProps: PropTypes.object,
/**
* Specify whether to use the light component variant
*/
light: deprecate(
PropTypes.bool,
'The `light` prop for `TabList` has ' +
'been deprecated in favor of the new `Layer` component. It will be removed in the next major release.'
),
/**
* Provide the props that describe the right overflow button
*/
rightOverflowButtonProps: PropTypes.object,
/**
* Optionally provide a delay (in milliseconds) passed to the lodash
* debounce of the onScroll handler. This will impact the responsiveness
* of scroll arrow buttons rendering when scrolling to the first or last tab.
*/
scrollDebounceWait: PropTypes.number,
/**
* Choose whether to automatically scroll
* to newly selected tabs on component rerender
*/
scrollIntoView: PropTypes.bool,
};
/**
* TabListVertical
*/
export interface TabListVerticalProps extends DivAttributes {
/**
* Specify whether the content tab should be activated automatically or
* manually
*/
activation?: 'automatic' | 'manual';
/**
* Provide an accessible label to be read when a user interacts with this
* component
*/
'aria-label': string;
/**
* Provide child elements to be rendered inside `ContentTabs`.
* These elements should render a `ContentTab`
*/
children?: ReactNode;
/**
* Specify an optional className to be added to the container node
*/
className?: string;
/**
* Choose whether to automatically scroll to newly selected tabs
* on component rerender
*/
scrollIntoView?: boolean;
}
// type TabElement = HTMLElement & { disabled?: boolean };
function TabListVertical({
activation = 'automatic',
'aria-label': label,
children,
className: customClassName,
scrollIntoView,
...rest
}: TabListVerticalProps) {
const { activeIndex, selectedIndex, setSelectedIndex, setActiveIndex } =
React.useContext(TabsContext);
const prefix = usePrefix();
const ref = useRef<HTMLDivElement>(null);
const [isOverflowingBottom, setIsOverflowingBottom] = useState(false);
const [isOverflowingTop, setIsOverflowingTop] = useState(false);
const isSm = useMatchMedia(smMediaQuery);
const className = cx(
`${prefix}--tabs`,
`${prefix}--tabs--vertical`,
`${prefix}--tabs--contained`,
customClassName
);
const tabs = useRef<TabElement[]>([]);
function onKeyDown(event: KeyboardEvent) {
if (matches(event, [keys.ArrowDown, keys.ArrowUp, keys.Home, keys.End])) {
event.preventDefault();
const filteredTabs = tabs.current.filter((tab) => tab !== null);
const activeTabs: TabElement[] = filteredTabs.filter(
(tab) => !tab.disabled
);
const currentIndex = activeTabs.indexOf(
tabs.current[activation === 'automatic' ? selectedIndex : activeIndex]
);
const nextIndex = tabs.current.indexOf(
activeTabs[getNextIndexVertical(event, activeTabs.length, currentIndex)]
);
if (activation === 'automatic') {
setSelectedIndex(nextIndex);
} else if (activation === 'manual') {
setActiveIndex(nextIndex);
}
tabs.current[nextIndex]?.focus();
}
}
function handleBlur({
relatedTarget: currentActiveNode,
}: React.FocusEvent<HTMLDivElement>) {
if (ref.current?.contains(currentActiveNode)) {
return;
}
// reset active index to selected tab index for manual activation
if (activation === 'manual') {
setActiveIndex(selectedIndex);
}
}
useEffectOnce(() => {
if (tabs.current[selectedIndex]?.disabled) {
const activeTabs = tabs.current.filter((tab) => {
return !tab.disabled;
});
if (activeTabs.length > 0) {
const tab = activeTabs[0];
setSelectedIndex(tabs.current.indexOf(tab));
}
}
});
useEffect(() => {
function handler() {
const containerHeight = ref.current?.offsetHeight;
const containerTop = ref.current?.getBoundingClientRect().top;
const selectedPositionTop =
tabs.current[selectedIndex]?.getBoundingClientRect().top;
const halfTabHeight = verticalTabHeight / 2;
if (containerTop && containerHeight) {
// scrolls so selected tab is in view
if (
selectedPositionTop - halfTabHeight < containerTop ||
selectedPositionTop -
containerTop +
verticalTabHeight +
halfTabHeight >
containerHeight
) {
ref.current.scrollTo({
top: (selectedIndex - 1) * verticalTabHeight,
behavior: 'smooth',
});
}
}
}
window.addEventListener('resize', handler);
handler();
return () => {
window.removeEventListener('resize', handler);
};
}, [selectedIndex, scrollIntoView]);
useEffect(() => {
const element = ref.current;
if (!element) {
return;
}
const handler = () => {
const halfTabHeight = verticalTabHeight / 2;
setIsOverflowingBottom(
element.scrollTop + element.clientHeight + halfTabHeight <=
element.scrollHeight