forked from keystonejs/keystone
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetHeadings.ts
More file actions
26 lines (24 loc) · 789 Bytes
/
Copy pathgetHeadings.ts
File metadata and controls
26 lines (24 loc) · 789 Bytes
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
import { Children, ReactNode } from 'react';
import slugify from '@sindresorhus/slugify';
export type Heading = {
id: string;
depth: number;
label: string;
};
export function getHeadings(children: ReactNode): Heading[] {
return Children.toArray(children)
.filter((child: any) => {
return child.type && ['h1', 'h2', 'h3'].includes(child.type);
})
.map((child: any) => {
const childrenText = Array.isArray(child.props.children)
? child.props.children.join('').replace('[object Object]', '')
: child.props.children;
const depth = (child.type && parseInt(child.type.replace('h', ''), 0)) ?? 0;
return {
id: depth > 0 ? `${slugify(childrenText)}` : '',
depth,
label: child.props.children,
};
});
}