-
Notifications
You must be signed in to change notification settings - Fork 0
/
getBreadCrumbs.ts
32 lines (25 loc) · 1018 Bytes
/
getBreadCrumbs.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
import type { PageDescriptor, PageURL, PageId, TableOfContent } from '../types'
import { getCurrentPage } from './getCurrentPage'
/**
* Traverse the ToC data from the active page node to the root,
* collecting all visited pages in the breadcrumbs array
*
* @param toc The TOC data
* @param url Page URL
* @returns Current page and the array of its ancestors from top to bottom
*/
export const getBreadCrumbs = (toc: TableOfContent, url?: PageURL): PageDescriptor[] => {
const breadcrumbs: PageDescriptor[] = []
// We trust the API, but not completely
const visitedIds = new Set<PageId>()
if (!url) {
return breadcrumbs
}
let currentPage: PageDescriptor | undefined = getCurrentPage(toc, url)
while (currentPage && toc.entities.pages[currentPage.id] && !visitedIds.has(currentPage.id)) {
breadcrumbs.push(currentPage)
visitedIds.add(currentPage.id)
currentPage = toc.entities.pages[currentPage.parentId]
}
return breadcrumbs.reverse()
}