-
-
Notifications
You must be signed in to change notification settings - Fork 607
/
Copy pathget-page-table-of-contents.ts
103 lines (87 loc) · 2.4 KB
/
get-page-table-of-contents.ts
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
import * as types from 'notion-types'
import { getTextContent } from './get-text-content'
export interface TableOfContentsEntry {
id: types.ID
type: types.BlockType
text: string
indentLevel: number
}
const indentLevels = {
header: 0,
sub_header: 1,
sub_sub_header: 2
}
/**
* Recursive function to traverse blocks and build the table of contents.
*/
const traverseBlocks = (
blockIds: string[],
recordMap: types.ExtendedRecordMap
): Array<TableOfContentsEntry> => {
const toc: Array<TableOfContentsEntry> = []
for (const blockId of blockIds) {
const block = recordMap.block[blockId]?.value
if (block) {
const { type } = block
if (
type === 'header' ||
type === 'sub_header' ||
type === 'sub_sub_header'
) {
toc.push({
id: blockId,
type,
text: getTextContent(block.properties?.title),
indentLevel: indentLevels[type]
})
}
// If the block has content, recursively traverse it
if (block.content) {
const nestedHeaders = traverseBlocks(block.content, recordMap)
toc.push(...nestedHeaders)
}
}
}
return toc
}
/**
* Gets the metadata for a table of contents block by parsing the page's
* H1, H2, and H3 elements.
*/
export const getPageTableOfContents = (
page: types.PageBlock,
recordMap: types.ExtendedRecordMap
): Array<TableOfContentsEntry> => {
const toc = traverseBlocks(page.content ?? [], recordMap)
const indentLevelStack = [
{
actual: -1,
effective: -1
}
]
// Adjust indent levels to always change smoothly.
// This is a little tricky, but the key is that when increasing indent levels,
// they should never jump more than one at a time.
for (const tocItem of toc) {
const { indentLevel } = tocItem
const actual = indentLevel
do {
const prevIndent = indentLevelStack[indentLevelStack.length - 1]
const { actual: prevActual, effective: prevEffective } = prevIndent
if (actual > prevActual) {
tocItem.indentLevel = prevEffective + 1
indentLevelStack.push({
actual,
effective: tocItem.indentLevel
})
} else if (actual === prevActual) {
tocItem.indentLevel = prevEffective
break
} else {
indentLevelStack.pop()
}
// eslint-disable-next-line no-constant-condition
} while (true)
}
return toc
}