Skip to content

Commit db4aac8

Browse files
author
katiegoines
committed
nest toc h3 beneath h2
1 parent 5ac6f98 commit db4aac8

File tree

2 files changed

+59
-14
lines changed

2 files changed

+59
-14
lines changed

src/components/Layout/Layout.tsx

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,15 @@ export const Layout = ({
147147

148148
pageHeadings.forEach((node) => {
149149
const { innerText, id, localName } = node as HTMLElement;
150-
if (innerText && id && (localName == 'h2' || localName == 'h3')) {
150+
if (innerText && id && localName == 'h2') {
151151
headings.push({
152+
linkText: innerText,
153+
hash: id,
154+
level: localName,
155+
subheadings: []
156+
});
157+
} else if (innerText && id && localName == 'h3') {
158+
headings[headings.length - 1].subheadings.push({
152159
linkText: innerText,
153160
hash: id,
154161
level: localName

src/components/TableOfContents/TableOfContents.tsx

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export interface HeadingInterface {
44
linkText: string;
55
hash: string;
66
level: string;
7+
subheadings: Array<object>;
78
}
89
interface TableOfContents {
910
headers?: HeadingInterface[];
@@ -21,20 +22,57 @@ export const TableOfContents = ({ headers }) => {
2122
)}
2223
<View as="ul" className="toc-list">
2324
{headers.map(({ linkText, hash, level }, index) => {
24-
return (
25-
<View
26-
as="li"
27-
className={`toc-item toc-item--${level}`}
28-
key={`toc-${index}`}
29-
>
30-
<Link
31-
href={`#${hash}`}
32-
className={`toc-item__link toc-item__link--${level}`}
25+
if (headers[index].subheadings?.length === 0) {
26+
return (
27+
<View
28+
as="li"
29+
className={`toc-item toc-item--${level}`}
30+
key={`toc-${index}`}
3331
>
34-
{linkText}
35-
</Link>
36-
</View>
37-
);
32+
<Link
33+
href={`#${hash}`}
34+
className={`toc-item__link toc-item__link--${level}`}
35+
>
36+
{linkText}
37+
</Link>
38+
</View>
39+
);
40+
} else {
41+
return (
42+
<View
43+
as="li"
44+
className={`toc-item toc-item--${level}`}
45+
key={`toc-${index}`}
46+
>
47+
<Link
48+
href={`#${hash}`}
49+
className={`toc-item__link toc-item__link--${level}`}
50+
>
51+
{linkText}
52+
</Link>
53+
<View as="ul" className="toc-list">
54+
{headers[index].subheadings?.map(
55+
({ linkText, hash, level }, index) => {
56+
return (
57+
<View
58+
as="li"
59+
className={`toc-item toc-item--${level}`}
60+
key={`toc-${index}`}
61+
>
62+
<Link
63+
href={`#${hash}`}
64+
className={`toc-item__link toc-item__link--${level}`}
65+
>
66+
{linkText}
67+
</Link>
68+
</View>
69+
);
70+
}
71+
)}
72+
</View>
73+
</View>
74+
);
75+
}
3876
})}
3977
</View>
4078
</Flex>

0 commit comments

Comments
 (0)