|
1
|
import { ToCItem } from "types" |
|
2
|
|
|
3
|
export function getToc( |
|
4
|
items: Record<string, unknown>[], |
|
5
|
maxDepth: number |
|
6
|
): ToCItem[] { |
|
7
|
const toc: ToCItem[] = [] |
|
8
|
|
|
9
|
items.forEach((i) => { |
|
10
|
const depth = i.depth as number |
|
11
|
if (depth > maxDepth) { |
|
12
|
return |
|
13
|
} |
|
14
|
|
|
15
|
const tocItem: ToCItem = { |
|
16
|
title: i.value as string, |
|
17
|
level: depth, |
|
18
|
id: i.id as string, |
|
19
|
children: [], |
|
20
|
} |
|
21
|
|
|
22
|
if (i.children && Array.isArray(i.children) && i.children.length > 0) { |
|
23
|
tocItem.children = getToc(i.children, maxDepth) |
|
24
|
} |
|
25
|
|
|
26
|
toc.push(tocItem) |
|
27
|
}) |
|
28
|
|
|
29
|
return toc |
|
30
|
} |
|
31
|
|
|
32
|
export function getTocJSX(toc: ToCItem[]): any[] { |
|
33
|
return toc.map((item) => { |
|
34
|
const itemData = { |
|
35
|
type: "ObjectExpression", |
|
36
|
properties: [ |
|
37
|
{ |
|
38
|
type: "Property", |
|
39
|
key: { type: "Identifier", name: "title" }, |
|
40
|
value: { type: "Literal", value: item.title }, |
|
41
|
kind: "init", |
|
42
|
computed: false, |
|
43
|
method: false, |
|
44
|
shorthand: false, |
|
45
|
}, |
|
46
|
{ |
|
47
|
type: "Property", |
|
48
|
key: { type: "Identifier", name: "level" }, |
|
49
|
value: { type: "Literal", value: item.level }, |
|
50
|
kind: "init", |
|
51
|
computed: false, |
|
52
|
method: false, |
|
53
|
shorthand: false, |
|
54
|
}, |
|
55
|
{ |
|
56
|
type: "Property", |
|
57
|
key: { type: "Identifier", name: "id" }, |
|
58
|
value: { type: "Literal", value: item.id }, |
|
59
|
kind: "init", |
|
60
|
computed: false, |
|
61
|
method: false, |
|
62
|
shorthand: false, |
|
63
|
}, |
|
64
|
], |
|
65
|
} |
|
66
|
|
|
67
|
if (item.children && item.children.length > 0) { |
|
68
|
itemData.properties.push({ |
|
69
|
type: "Property", |
|
70
|
key: { type: "Identifier", name: "children" }, |
|
71
|
value: { |
|
72
|
type: "ArrayExpression", |
|
73
|
elements: getTocJSX(item.children), |
|
74
|
}, |
|
75
|
kind: "init", |
|
76
|
computed: false, |
|
77
|
method: false, |
|
78
|
shorthand: false, |
|
79
|
} as any) |
|
80
|
} |
|
81
|
|
|
82
|
return itemData |
|
83
|
}) |
|
84
|
} |