-
-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathdocumentDriven.ts
More file actions
246 lines (204 loc) · 7.14 KB
/
documentDriven.ts
File metadata and controls
246 lines (204 loc) · 7.14 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import type { RouteLocationNormalized, RouteLocationNormalizedLoaded } from 'vue-router'
// @ts-ignore
import { useRuntimeConfig, addRouteMiddleware } from '#app'
import { withoutTrailingSlash } from 'ufo'
import { NavItem, ParsedContent } from '../types'
// @ts-ignore
import { defineNuxtPlugin, queryContent, useContentHelpers, useContentState, fetchContentNavigation, useRoute } from '#imports'
// @ts-ignore
import layouts from '#build/layouts'
export default defineNuxtPlugin((nuxt) => {
const { documentDriven: moduleOptions } = useRuntimeConfig()?.public?.content
/**
* Finds a layout value from a cascade of objects.
*/
const findLayout = (to: RouteLocationNormalized, page: ParsedContent, navigation: NavItem[], globals: Record<string, any>) => {
// Page `layout` key has priority
if (page && page?.layout) { return page.layout }
// Resolve key from .vue page meta
if (to.matched.length && to.matched[0].meta?.layout) { return to.matched[0].meta.layout }
// Resolve key from navigation
if (navigation && page) {
const { navKeyFromPath } = useContentHelpers()
const layoutFromNav = navKeyFromPath(page._path, 'layout', navigation)
if (layoutFromNav) { return layoutFromNav }
}
// Resolve key from globals fallback
if (moduleOptions.layoutFallbacks && globals) {
let layoutFallback
for (const fallback of moduleOptions.layoutFallbacks) {
if (globals[fallback] && globals[fallback].layout) {
layoutFallback = globals[fallback].layout
break
}
}
if (layoutFallback) { return layoutFallback }
}
return 'default'
}
const refresh = async (to: RouteLocationNormalized | RouteLocationNormalizedLoaded, force: boolean = false) => {
const routeConfig = (to.meta.documentDriven || {}) as any
// Disabled document driven mode on next route
if (to.meta.documentDriven === false) {
return
}
const { navigation, pages, globals, surrounds } = useContentState()
// Normalize route path
const _path = withoutTrailingSlash(to.path)
// Promises array to be executed all at once
const promises: (() => Promise<any> | any)[] = []
/**
*
* `navigation`
*/
if (moduleOptions.navigation && routeConfig.navigation !== false) {
const navigationQuery = () => {
const { navigation } = useContentState()
if (navigation.value && !force) { return navigation.value }
return fetchContentNavigation()
.then((_navigation) => {
navigation.value = _navigation
return _navigation
})
.catch((_) => {
// eslint-disable-next-line no-console
// console.log('Could not fetch navigation!')
})
}
promises.push(navigationQuery)
} else {
promises.push(() => Promise.resolve(null))
}
/**
* `globals`
*/
if (moduleOptions.globals) {
const globalsQuery = () => {
const { globals } = useContentState()
if (
typeof moduleOptions.globals === 'object' && Array.isArray(moduleOptions.globals)
) {
// eslint-disable-next-line no-console
console.log('Globals must be a list of keys with QueryBuilderParams as a value.')
return
}
return Promise.all(
Object.entries(moduleOptions.globals).map(
([key, query]: [string, any]) => {
// Avoid fetching same file twice
if (!force && globals.value[key]) { return globals.value[key] }
// Supports `find` if passed as `query: 'find'` in the query definition.
let type = 'findOne'
if (query?.type) { type = query.type }
return queryContent(query)[type]().catch(() => {
// eslint-disable-next-line no-console
// console.log(`Could not find globals key: ${key}`)
})
}
)
).then(
(values) => {
return values.reduce(
(acc, value, index) => {
const key = Object.keys(moduleOptions.globals)[index]
acc[key] = value
return acc
}, {})
}
)
}
promises.push(globalsQuery)
} else {
promises.push(() => Promise.resolve(null))
}
/**
* `page`
*/
if (moduleOptions.page && routeConfig.page !== false) {
const pageQuery = () => {
const { pages } = useContentState()
// Return same page as page is already loaded
if (!force && pages.value[_path] && pages.value[_path]._path === _path) {
return pages.value[_path]
}
return queryContent()
.where({ _path })
.findOne()
.catch(() => {
// eslint-disable-next-line no-console
// console.log(`Could not find page: ${to.path}`)
})
}
promises.push(pageQuery)
} else {
promises.push(() => Promise.resolve(null))
}
/**
* `surround`
*/
if (moduleOptions.surround && routeConfig.surround !== false) {
const surroundQuery = () => {
const { surrounds } = useContentState()
// Return same surround as page is already loaded
if (!force && surrounds.value[_path]) {
return surrounds.value[_path]
}
return queryContent()
.where({
_partial: { $not: true },
navigation: { $not: false }
})
// Exclude `body` for `surround`
.without(['body'])
.findSurround(_path)
.catch(() => {
// eslint-disable-next-line no-console
// console.log(`Could not find surrounding pages for: ${to.path}`)
})
}
promises.push(surroundQuery)
} else {
promises.push(() => Promise.resolve(null))
}
return await Promise.all(promises.map(promise => promise())).then(async ([
_navigation,
_globals,
_page,
_surround
]) => {
if (_navigation) {
navigation.value = _navigation
}
if (_globals) {
globals.value = _globals
}
// Use `redirect` key to redirect to another page
if (_page?.redirect) { return _page?.redirect }
if (_page) {
// Find used layout
const layoutName = findLayout(to, _page, _navigation, _globals)
// Prefetch layout component
const layout = layouts[layoutName]
if (layout && layout?.__asyncLoader && !layout.__asyncResolved) {
await layout.__asyncLoader()
}
// Apply layout
to.meta.layout = layoutName
// Update values
pages.value[_path] = _page
}
if (_surround) {
surrounds.value[_path] = _surround
}
})
}
// Route middleware
addRouteMiddleware(async (to) => {
// TODO: Remove this (https://github.com/nuxt/framework/pull/5274)
if (to.path.includes('favicon.ico')) { return }
const redirect = await refresh(to, false)
if (redirect) { return redirect }
})
// @ts-ignore - Refresh on client-side
nuxt.hook('app:data:refresh', async () => process.client && await refresh(useRoute(), true))
})