Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 40 additions & 24 deletions packages/notion-utils/src/get-page-table-of-contents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,45 @@ const indentLevels = {
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.
Expand All @@ -23,30 +62,7 @@ export const getPageTableOfContents = (
page: types.PageBlock,
recordMap: types.ExtendedRecordMap
): Array<TableOfContentsEntry> => {
const toc = (page.content ?? [])
.map((blockId: string) => {
const block = recordMap.block[blockId]?.value

if (block) {
const { type } = block

if (
type === 'header' ||
type === 'sub_header' ||
type === 'sub_sub_header'
) {
return {
id: blockId,
type,
text: getTextContent(block.properties?.title),
indentLevel: indentLevels[type]
}
}
}

return null
})
.filter(Boolean) as Array<TableOfContentsEntry>
const toc = traverseBlocks(page.content ?? [], recordMap)

const indentLevelStack = [
{
Expand Down
5 changes: 0 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -9602,11 +9602,6 @@ normalize-url@^7.0.3:
resolved "https://registry.npmjs.org/normalize-url/-/normalize-url-7.0.3.tgz"
integrity sha512-RiCOdwdPnzvwcBFJE4iI1ss3dMVRIrEzFpn8ftje6iBfzBInqlnRrNhxcLwBEKjPPXQKzm1Ptlxtaiv9wdcj5w==

notion-types@^6.15.6:
version "6.15.6"
resolved "https://registry.yarnpkg.com/notion-types/-/notion-types-6.15.6.tgz#eabbb28e1c514f421f0ffbf06ecdecd90e8ec8e3"
integrity sha512-JgLWDN4oHg/1sNdHDCeKUfdPl1AYsjOTnYkq+Zn7vITPykxbhw7nIxbAJ7owWUTro1cYTPh+GVmdX0mPiZGujg==

npm-bundled@^1.1.1:
version "1.1.2"
resolved "https://registry.npmjs.org/npm-bundled/-/npm-bundled-1.1.2.tgz"
Expand Down