-
-
Notifications
You must be signed in to change notification settings - Fork 663
/
Copy pathnavigation.ts
212 lines (182 loc) · 6.67 KB
/
navigation.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import type { ContentNavigationItem, PageCollectionItemBase, CollectionQueryBuilder } from '@nuxt/content'
import { pascalCase } from 'scule'
/**
* Create NavItem array to be consumed from runtime plugin.
*/
export async function generateNavigationTree<T extends PageCollectionItemBase>(queryBuilder: CollectionQueryBuilder<T>, extraFields: Array<keyof T> = []) {
// @ts-expect-error -- internal
const params = queryBuilder.__params
if (!params?.orderBy?.length) {
queryBuilder = queryBuilder.order('stem', 'ASC')
}
const collecitonItems = await queryBuilder
.orWhere(group => group
.where('navigation', '<>', 'false')
.where('navigation', 'IS NULL'),
)
.select('navigation', 'stem', 'path', 'title', 'meta', ...(extraFields || []))
.all() as unknown as PageCollectionItemBase[]
const { contents, configs } = collecitonItems.reduce((acc, c) => {
if (String(c.stem).split('/').pop() === '.navigation') {
c.title = c.title?.toLowerCase() === 'navigation' ? '' : c.title
const key = c.path!.split('/').slice(0, -1).join('/') || '/'
acc.configs[key] = {
...c,
...c.body,
}
}
else {
acc.contents.push(c)
}
return acc
}, { configs: {}, contents: [] } as { configs: Record<string, PageCollectionItemBase>, contents: PageCollectionItemBase[] })
// Navigation fields picker
const pickConfigNavigationFields = (content: PageCollectionItemBase) => ({
...pick(['title', ...(extraFields as string[])])(content as unknown as Record<string, unknown>),
...content.meta as unknown as Record<string, unknown>,
...(isObject(content?.navigation) ? (content.navigation as Record<string, unknown>) : {}),
})
const pickNavigationFields = (content: PageCollectionItemBase) => ({
...pick(['title', ...(extraFields as string[])])(content as unknown as Record<string, unknown>),
...(isObject(content?.navigation) ? (content.navigation as Record<string, unknown>) : {}),
})
// Create navigation object
const nav = contents
.reduce((nav, content) => {
// Resolve path and id parts
const parts = content.path!.substring(1).split('/')
const idParts = content.stem.split('/')
// Check if node is `*:index.md`
const isIndex = !!idParts[idParts.length - 1]?.match(/([1-9]\d*\.)?index/g)
const getNavItem = (content: PageCollectionItemBase) => ({
title: content.title,
path: content.path,
stem: content.stem,
children: [],
...pickNavigationFields(content),
} as ContentNavigationItem)
// Create navigation item from content
const navItem: ContentNavigationItem = getNavItem(content)
// Push index
if (isIndex) {
// Grab index directory config
const dirConfig = configs[navItem.path]
// Drop item if current directory config has `navigation: false`
if (typeof dirConfig?.navigation !== 'undefined' && dirConfig?.navigation === false) {
return nav
}
// Skip root `index.md` as it has to be pushed as a page
if (content.path !== '/') {
const indexItem = getNavItem(content)
navItem.children!.push(indexItem)
}
if (dirConfig) {
// Merge navigation fields with navItem
Object.assign(
navItem,
pickConfigNavigationFields(dirConfig),
)
}
}
// First-level item, push it straight to nav
if (parts.length === 1) {
// Check for duplicate link
const existed = nav.find(item => item.path === navItem.path && item.page === false)
if (isIndex && existed) {
Object.assign(existed, {
page: undefined,
children: [
...navItem.children,
...existed.children,
],
})
}
else {
nav.push(navItem)
}
return nav
}
// Find siblings of current item and push them to parent children key
const siblings = parts.slice(0, -1).reduce((nodes: ContentNavigationItem[], part: string, i: number) => {
// Part of current path
const currentPathPart: string = '/' + parts.slice(0, i + 1).join('/')
// Get current node _dir.yml config
const conf = configs[currentPathPart]
// Drop childrens if .navigation.yml has `navigation: false`
if (typeof conf?.navigation !== 'undefined' && conf.navigation === false) {
return []
}
// Find parent node
let parent: ContentNavigationItem | undefined = nodes.find(n => n.path === currentPathPart)
// Create dummy parent if not found
if (!parent) {
const navigationConfig = (conf ? pickConfigNavigationFields(conf) : {}) as ContentNavigationItem
parent = {
...navigationConfig,
title: navigationConfig.title || generateTitle(part),
path: currentPathPart,
stem: idParts.slice(0, i + 1).join('/'),
children: [],
page: false,
}
nodes.push(parent!)
}
return parent!.children!
}, nav)
// Check for duplicate link
const existed = siblings.find(item => item.path === navItem.path && item.page === false)
if (existed) {
Object.assign(existed, {
...navItem,
page: undefined,
children: [
...navItem.children,
...existed.children,
],
})
}
else {
siblings.push(navItem)
}
return nav
}, [] as ContentNavigationItem[])
return sortAndClear(nav)
}
// const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
/**
* Sort items by path and clear empty children keys.
*/
function sortAndClear(nav: ContentNavigationItem[]) {
const sorted = nav// .sort((a, b) => collator.compare(a.stem!, b.stem!))
for (const item of sorted) {
if (item.children?.length) {
// Sort children
sortAndClear(item.children)
}
else {
// Remove empty children
delete item.children
}
// Remove path after sort
// delete item.stem
}
return nav
}
/**
* Returns a new object with the specified keys
*/
function pick(keys?: string[]) {
return (obj: Record<string, unknown>) => {
obj = obj || {}
if (keys && keys.length) {
return keys
.filter(key => typeof obj[key] !== 'undefined')
.reduce((newObj, key) => Object.assign(newObj, { [key]: obj[key] }), {})
}
return obj
}
}
function isObject(obj: unknown) {
return obj !== null && Object.prototype.toString.call(obj) === '[object Object]'
}
export const generateTitle = (path: string) => path.split(/[\s-]/g).map(pascalCase).join(' ')