-
-
Notifications
You must be signed in to change notification settings - Fork 605
/
helpers.ts
75 lines (62 loc) · 1.7 KB
/
helpers.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
import type { NavItem } from '../types'
/**
* Find first child link from a navigation node.
*/
const navBottomLink = (link: NavItem): string | undefined => {
if (!link.children) { return link._path }
for (const child of link?.children || []) {
const result = navBottomLink(child)
if (result) { return result }
}
}
/**
* Find current navigation directory node from a path.
*/
const navDirFromPath = (path: string, tree: NavItem[]): NavItem[] | undefined => {
for (const file of tree) {
if (file._path === path && !file._id) { return file.children }
if (file.children) {
const result = navDirFromPath(path, file.children)
if (result) { return result }
}
}
}
/**
* Find a navigation page node from a path.
*/
const navPageFromPath = (path: string, tree: NavItem[]): NavItem | undefined => {
for (const file of tree) {
if (file._path === path) { return file }
if (file.children) {
const result = navPageFromPath(path, file.children)
if (result) { return result }
}
}
}
/**
* Find a navigation field node from a path.
*/
const navKeyFromPath = (path: string, key: string, tree: NavItem[]) => {
let value: any
const goDeep = (path: string, tree: NavItem[]) => {
for (const file of tree) {
if (path !== '/' && file._path === '/') {
// Ignore root page
continue
}
if (path?.startsWith(file._path) && file[key]) { value = file[key] }
if (file._path === path) { return }
if (file.children) { goDeep(path, file.children) }
}
}
goDeep(path, tree)
return value
}
export const useContentHelpers = () => {
return {
navBottomLink,
navDirFromPath,
navPageFromPath,
navKeyFromPath
}
}