-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTableOfContents.tsx
More file actions
92 lines (82 loc) · 2.6 KB
/
Copy pathTableOfContents.tsx
File metadata and controls
92 lines (82 loc) · 2.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
import { FC, useMemo } from 'react';
import {
HorizontalItemsContainer,
TableOfContentsContainer,
VerticalItemsContainer,
} from './TableOfContents.styles';
import { TableOfContentsItem } from './TableOfContentsItem';
import { Tabs } from 'src/molecules/Tabs/Tabs';
import { TabsScrollProps } from 'src/molecules/Tabs/Tabs.types';
import { useTableOfContents } from 'src/providers/TableOfContentsProvider';
import { getValues } from 'src/providers/TableOfContentsProvider.utils';
interface TableOfContentsBaseProps {
onlyShowSelectedChildren?: boolean;
}
interface TableOfContentsVerticalProps extends TableOfContentsBaseProps {
mode?: 'vertical';
}
interface TableOfContentsHorizontalProps extends TableOfContentsBaseProps {
mode: 'horizontal';
tabsProps?: TabsScrollProps;
}
export type TableOfContentsProps =
| TableOfContentsVerticalProps
| TableOfContentsHorizontalProps;
export const TableOfContents: FC<TableOfContentsProps> = ({
onlyShowSelectedChildren = true,
...props
}) => {
const { items, selected, setSelected } = useTableOfContents();
const activeIndex = useMemo(() => {
// Was not able to test this properly because selected can't be correctly updated in the unit test
// Created a test that check that it sets activeIndex correctly
// but could not get it to work with selected === undefined || child was true
/* v8 ignore start */
for (const [index, item] of items.entries()) {
const childValues = getValues([], item);
if (
item.value === selected ||
(selected && childValues.includes(selected))
)
return index;
}
return -1;
/* v8 ignore end */
}, [items, selected]);
if (props.mode === 'horizontal') {
return (
<HorizontalItemsContainer>
<Tabs
selected={selected}
onChange={(value) => {
if (value) setSelected(value);
}}
options={items}
{...props.tabsProps}
/>
</HorizontalItemsContainer>
);
}
return (
<TableOfContentsContainer
className="page-menu"
layoutRoot
data-testid="table-of-contents-container"
>
{items.map((item, index) => (
<VerticalItemsContainer
data-testid={`border-items-container-${item.value}`}
key={item.value}
$index={index}
$activeIndex={activeIndex}
aria-selected={activeIndex === index}
>
<TableOfContentsItem
onlyShowSelectedChildren={onlyShowSelectedChildren}
{...item}
/>
</VerticalItemsContainer>
))}
</TableOfContentsContainer>
);
};