|
1 | 1 | import { createRouter, createWebHistory, createMemoryHistory } from '@ionic/vue-router' |
2 | 2 |
|
3 | | -import { defineNuxtPlugin, useRuntimeConfig } from '#imports' |
| 3 | +import { computed, ComputedRef, reactive, shallowRef } from 'vue' |
| 4 | +import { createWebHashHistory, NavigationGuard, RouteLocation } from 'vue-router' |
| 5 | +import { createError } from 'h3' |
| 6 | +import { withoutBase, isEqual } from 'ufo' |
| 7 | +import { |
| 8 | + callWithNuxt, |
| 9 | + defineNuxtPlugin, |
| 10 | + useRuntimeConfig, |
| 11 | + showError, |
| 12 | + clearError, |
| 13 | + navigateTo, |
| 14 | + useError, |
| 15 | + useState, |
| 16 | +} from '#app' |
4 | 17 |
|
| 18 | +// @ts-expect-error virtual module |
| 19 | +import { globalMiddleware, namedMiddleware } from '#build/middleware' |
5 | 20 | // @ts-expect-error virtual module |
6 | 21 | import routerOptions from '#build/router.options' |
7 | 22 | // @ts-expect-error virtual module generated by Nuxt |
8 | | -import routes from '#build/routes' |
| 23 | +import _routes from '#build/routes' |
| 24 | + |
| 25 | +export default defineNuxtPlugin(async nuxtApp => { |
| 26 | + let routerBase = useRuntimeConfig().app.baseURL |
| 27 | + if (routerOptions.hashMode && !routerBase.includes('#')) { |
| 28 | + // allow the user to provide a `#` in the middle: `/base/#/app` |
| 29 | + routerBase += '#' |
| 30 | + } |
| 31 | + |
| 32 | + const history = |
| 33 | + routerOptions.history?.(routerBase) ?? |
| 34 | + (process.client |
| 35 | + ? routerOptions.hashMode |
| 36 | + ? createWebHashHistory(routerBase) |
| 37 | + : createWebHistory(routerBase) |
| 38 | + : createMemoryHistory(routerBase)) |
9 | 39 |
|
10 | | -export default defineNuxtPlugin(nuxtApp => { |
11 | | - const config = useRuntimeConfig() |
12 | | - const baseURL = config.app.baseURL |
| 40 | + const routes = routerOptions.routes?.(_routes) ?? _routes |
13 | 41 |
|
| 42 | + const initialURL = process.server |
| 43 | + ? nuxtApp.ssrContext!.url |
| 44 | + : createCurrentLocation(routerBase, window.location) |
14 | 45 | const router = createRouter({ |
15 | 46 | ...routerOptions, |
16 | | - history: process.server ? createMemoryHistory(baseURL) : createWebHistory(baseURL), |
| 47 | + history, |
17 | 48 | routes, |
18 | 49 | }) |
19 | | - |
20 | 50 | nuxtApp.vueApp.use(router) |
| 51 | + const previousRoute = shallowRef(router.currentRoute.value) |
| 52 | + router.afterEach((_to, from) => { |
| 53 | + previousRoute.value = from |
| 54 | + }) |
| 55 | + |
| 56 | + Object.defineProperty(nuxtApp.vueApp.config.globalProperties, 'previousRoute', { |
| 57 | + get: () => previousRoute.value, |
| 58 | + }) |
| 59 | + |
| 60 | + // Allows suspending the route object until page navigation completes |
| 61 | + const _route = shallowRef(router.resolve(initialURL) as RouteLocation) |
| 62 | + const syncCurrentRoute = () => { |
| 63 | + _route.value = router.currentRoute.value |
| 64 | + } |
| 65 | + nuxtApp.hook('page:finish', syncCurrentRoute) |
| 66 | + router.afterEach((to, from) => { |
| 67 | + // We won't trigger suspense if the component is reused between routes |
| 68 | + // so we need to update the route manually |
| 69 | + if (to.matched[0]?.components?.default === from.matched[0]?.components?.default) { |
| 70 | + syncCurrentRoute() |
| 71 | + } |
| 72 | + }) |
| 73 | + |
| 74 | + // https://github.com/vuejs/router/blob/main/packages/router/src/router.ts#L1225-L1233 |
| 75 | + const route = {} as { [K in keyof RouteLocation]: ComputedRef<RouteLocation[K]> } |
| 76 | + for (const key in _route.value) { |
| 77 | + route[key as 'path'] = computed(() => _route.value[key as 'path']) |
| 78 | + } |
| 79 | + |
| 80 | + nuxtApp._route = reactive(route) |
| 81 | + |
| 82 | + nuxtApp._middleware = nuxtApp._middleware || { |
| 83 | + global: [], |
| 84 | + named: {}, |
| 85 | + } |
| 86 | + |
| 87 | + const error = useError() |
| 88 | + |
| 89 | + const initialLayout = useState<string>('_layout') |
| 90 | + router.beforeEach(async (to, from) => { |
| 91 | + to.meta = reactive(to.meta) |
| 92 | + if (nuxtApp.isHydrating) { |
| 93 | + to.meta.layout = initialLayout.value ?? to.meta.layout |
| 94 | + } |
| 95 | + nuxtApp._processingMiddleware = true |
| 96 | + |
| 97 | + type MiddlewareDef = string | NavigationGuard |
| 98 | + const middlewareEntries = new Set<MiddlewareDef>([ |
| 99 | + ...globalMiddleware, |
| 100 | + ...nuxtApp._middleware.global, |
| 101 | + ]) |
| 102 | + for (const component of to.matched) { |
| 103 | + const componentMiddleware = component.meta.middleware as MiddlewareDef | MiddlewareDef[] |
| 104 | + if (!componentMiddleware) { |
| 105 | + continue |
| 106 | + } |
| 107 | + if (Array.isArray(componentMiddleware)) { |
| 108 | + for (const entry of componentMiddleware) { |
| 109 | + middlewareEntries.add(entry) |
| 110 | + } |
| 111 | + } else { |
| 112 | + middlewareEntries.add(componentMiddleware) |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + for (const entry of middlewareEntries) { |
| 117 | + const middleware = |
| 118 | + typeof entry === 'string' |
| 119 | + ? nuxtApp._middleware.named[entry] || |
| 120 | + (await namedMiddleware[entry]?.().then((r: any) => r.default || r)) |
| 121 | + : entry |
| 122 | + |
| 123 | + if (!middleware) { |
| 124 | + if (process.dev) { |
| 125 | + throw new Error( |
| 126 | + `Unknown route middleware: '${entry}'. Valid middleware: ${Object.keys(namedMiddleware) |
| 127 | + .map(mw => `'${mw}'`) |
| 128 | + .join(', ')}.` |
| 129 | + ) |
| 130 | + } |
| 131 | + throw new Error(`Unknown route middleware: '${entry}'.`) |
| 132 | + } |
| 133 | + |
| 134 | + const result = await callWithNuxt(nuxtApp, middleware, [to, from]) |
| 135 | + if (process.server || (!nuxtApp.payload.serverRendered && nuxtApp.isHydrating)) { |
| 136 | + if (result === false || result instanceof Error) { |
| 137 | + const error = |
| 138 | + result || |
| 139 | + createError({ |
| 140 | + statusMessage: `Route navigation aborted: ${initialURL}`, |
| 141 | + }) |
| 142 | + return callWithNuxt(nuxtApp, showError, [error]) |
| 143 | + } |
| 144 | + } |
| 145 | + if (result || result === false) { |
| 146 | + return result |
| 147 | + } |
| 148 | + } |
| 149 | + }) |
| 150 | + |
| 151 | + router.afterEach(async to => { |
| 152 | + delete nuxtApp._processingMiddleware |
| 153 | + |
| 154 | + if (process.client && !nuxtApp.isHydrating && error.value) { |
| 155 | + // Clear any existing errors |
| 156 | + await callWithNuxt(nuxtApp, clearError) |
| 157 | + } |
| 158 | + if (to.matched.length === 0) { |
| 159 | + callWithNuxt(nuxtApp, showError, [ |
| 160 | + createError({ |
| 161 | + statusCode: 404, |
| 162 | + fatal: false, |
| 163 | + statusMessage: `Page not found: ${to.fullPath}`, |
| 164 | + }), |
| 165 | + ]) |
| 166 | + } else if (process.server && to.matched[0].name === '404' && nuxtApp.ssrContext) { |
| 167 | + nuxtApp.ssrContext.event.res.statusCode = 404 |
| 168 | + } else if (process.server) { |
| 169 | + const currentURL = to.fullPath || '/' |
| 170 | + if (!isEqual(currentURL, initialURL)) { |
| 171 | + await callWithNuxt(nuxtApp, navigateTo, [currentURL]) |
| 172 | + } |
| 173 | + } |
| 174 | + }) |
| 175 | + |
| 176 | + return { provide: { router } } |
21 | 177 | }) |
| 178 | + |
| 179 | +// https://github.com/vuejs/router/blob/4a0cc8b9c1e642cdf47cc007fa5bbebde70afc66/packages/router/src/history/html5.ts#L37 |
| 180 | +function createCurrentLocation (base: string, location: Location): string { |
| 181 | + const { pathname, search, hash } = location |
| 182 | + // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end |
| 183 | + const hashPos = base.indexOf('#') |
| 184 | + if (hashPos > -1) { |
| 185 | + const slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1 |
| 186 | + let pathFromHash = hash.slice(slicePos) |
| 187 | + // prepend the starting slash to hash so the url starts with /# |
| 188 | + if (pathFromHash[0] !== '/') { |
| 189 | + pathFromHash = '/' + pathFromHash |
| 190 | + } |
| 191 | + return withoutBase(pathFromHash, '') |
| 192 | + } |
| 193 | + const path = withoutBase(pathname, base) |
| 194 | + return path + search + hash |
| 195 | +} |
0 commit comments