@tschk/moonshine-vue 0.4.49 → 0.4.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -34
- package/package.json +8 -5
- package/src/app.ts +426 -13
- package/src/context.ts +222 -16
- package/src/lifecycle.ts +80 -1
- package/src/map.ts +196 -0
- package/src/reactive.ts +1017 -28
- package/src/router.ts +1562 -0
- package/src/server-renderer.ts +257 -0
- package/src/slots.ts +26 -0
- package/src/store.ts +1042 -0
package/src/router.ts
ADDED
|
@@ -0,0 +1,1562 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-free Vue Router 4 runtime on the Moonshine reactive graph.
|
|
3
|
+
* Provides `createRouter`, `createMemoryHistory`, `createWebHistory`,
|
|
4
|
+
* `createWebHashHistory`, `useRouter`, `useRoute`, `useLink`,
|
|
5
|
+
* `onBeforeRouteLeave`, `onBeforeRouteUpdate`, `RouterLink`, `RouterView`,
|
|
6
|
+
* navigation guards, dynamic route matching, and `NavigationFailure` helpers.
|
|
7
|
+
*/
|
|
8
|
+
import { peekComponentContext } from "@tschk/moonshine-dom/component";
|
|
9
|
+
import { h as hDOM } from "@tschk/moonshine-dom/dom";
|
|
10
|
+
import { getOwner, onCleanup, untrack } from "@tschk/moonshine-dom/reactive";
|
|
11
|
+
import { h as hSSR } from "@tschk/moonshine-dom/ssr";
|
|
12
|
+
import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
|
|
13
|
+
import {
|
|
14
|
+
hasInjectionContext,
|
|
15
|
+
inject,
|
|
16
|
+
provide,
|
|
17
|
+
type InjectionKey,
|
|
18
|
+
} from "./context";
|
|
19
|
+
import {
|
|
20
|
+
computed,
|
|
21
|
+
ref,
|
|
22
|
+
toRaw,
|
|
23
|
+
unref,
|
|
24
|
+
type MaybeRef,
|
|
25
|
+
type Ref,
|
|
26
|
+
} from "./reactive";
|
|
27
|
+
import { getDefaultSlotFactory } from "./slots";
|
|
28
|
+
|
|
29
|
+
export type RouteParamValue = string;
|
|
30
|
+
export type RouteParams = Record<string, RouteParamValue | RouteParamValue[]>;
|
|
31
|
+
export type LocationQueryValue = string | null;
|
|
32
|
+
export type LocationQuery = Record<
|
|
33
|
+
string,
|
|
34
|
+
LocationQueryValue | LocationQueryValue[]
|
|
35
|
+
>;
|
|
36
|
+
export type LocationQueryValueRaw = LocationQueryValue | number | undefined;
|
|
37
|
+
export type LocationQueryRaw = Record<
|
|
38
|
+
string | number,
|
|
39
|
+
LocationQueryValueRaw | LocationQueryValueRaw[]
|
|
40
|
+
>;
|
|
41
|
+
export type RouteMeta = Record<string | number | symbol, unknown>;
|
|
42
|
+
export type RouteRecordName = string | symbol;
|
|
43
|
+
|
|
44
|
+
export interface RouteLocationOptions {
|
|
45
|
+
replace?: boolean;
|
|
46
|
+
force?: boolean;
|
|
47
|
+
state?: HistoryState;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type HistoryState = Record<string, any>;
|
|
51
|
+
|
|
52
|
+
export interface RouteLocationPathRaw extends RouteLocationOptions {
|
|
53
|
+
path: string;
|
|
54
|
+
query?: LocationQueryRaw;
|
|
55
|
+
hash?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface RouteLocationNamedRaw extends RouteLocationOptions {
|
|
59
|
+
name: RouteRecordName;
|
|
60
|
+
params?: Record<string, any>;
|
|
61
|
+
query?: LocationQueryRaw;
|
|
62
|
+
hash?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type RouteLocationRaw =
|
|
66
|
+
string | RouteLocationPathRaw | RouteLocationNamedRaw;
|
|
67
|
+
|
|
68
|
+
export type RouteComponent = (...args: any[]) => any;
|
|
69
|
+
|
|
70
|
+
export interface RouteRecordRaw {
|
|
71
|
+
path: string;
|
|
72
|
+
name?: RouteRecordName;
|
|
73
|
+
component?: RouteComponent;
|
|
74
|
+
components?: Record<string, RouteComponent>;
|
|
75
|
+
redirect?:
|
|
76
|
+
RouteLocationRaw | ((to: RouteLocationNormalized) => RouteLocationRaw);
|
|
77
|
+
alias?: string | string[];
|
|
78
|
+
children?: RouteRecordRaw[];
|
|
79
|
+
meta?: RouteMeta;
|
|
80
|
+
props?:
|
|
81
|
+
| boolean
|
|
82
|
+
| Record<string, any>
|
|
83
|
+
| ((to: RouteLocationNormalizedLoaded) => Record<string, any>);
|
|
84
|
+
beforeEnter?: NavigationGuard | NavigationGuard[];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface RouteRecordNormalized {
|
|
88
|
+
path: string;
|
|
89
|
+
name: RouteRecordName | undefined;
|
|
90
|
+
components: Record<string, RouteComponent>;
|
|
91
|
+
redirect?:
|
|
92
|
+
RouteLocationRaw | ((to: RouteLocationNormalized) => RouteLocationRaw);
|
|
93
|
+
aliasOf: RouteRecordNormalized | undefined;
|
|
94
|
+
children: RouteRecordRaw[];
|
|
95
|
+
meta: RouteMeta;
|
|
96
|
+
props: Record<
|
|
97
|
+
string,
|
|
98
|
+
| boolean
|
|
99
|
+
| Record<string, any>
|
|
100
|
+
| ((to: RouteLocationNormalizedLoaded) => Record<string, any>)
|
|
101
|
+
>;
|
|
102
|
+
beforeGuards: NavigationGuard[];
|
|
103
|
+
leaveGuards: Set<NavigationGuard>;
|
|
104
|
+
updateGuards: Set<NavigationGuard>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface RouteLocationNormalized {
|
|
108
|
+
path: string;
|
|
109
|
+
fullPath: string;
|
|
110
|
+
name: RouteRecordName | null | undefined;
|
|
111
|
+
params: RouteParams;
|
|
112
|
+
query: LocationQuery;
|
|
113
|
+
hash: string;
|
|
114
|
+
matched: RouteRecordNormalized[];
|
|
115
|
+
meta: RouteMeta;
|
|
116
|
+
redirectedFrom: RouteLocationNormalized | undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export type RouteLocationNormalizedLoaded = RouteLocationNormalized;
|
|
120
|
+
|
|
121
|
+
export type NavigationGuardReturn =
|
|
122
|
+
void | Error | boolean | RouteLocationRaw | ((vm: any) => any);
|
|
123
|
+
|
|
124
|
+
export type NavigationGuardNext = (
|
|
125
|
+
valid?: boolean | RouteLocationRaw | Error | ((vm: any) => any),
|
|
126
|
+
) => void;
|
|
127
|
+
|
|
128
|
+
export type NavigationGuard = (
|
|
129
|
+
to: RouteLocationNormalized,
|
|
130
|
+
from: RouteLocationNormalizedLoaded,
|
|
131
|
+
next: NavigationGuardNext,
|
|
132
|
+
) => NavigationGuardReturn | Promise<NavigationGuardReturn>;
|
|
133
|
+
|
|
134
|
+
export type NavigationHookAfter = (
|
|
135
|
+
to: RouteLocationNormalized,
|
|
136
|
+
from: RouteLocationNormalizedLoaded,
|
|
137
|
+
failure?: NavigationFailure | void,
|
|
138
|
+
) => any;
|
|
139
|
+
|
|
140
|
+
export enum NavigationFailureType {
|
|
141
|
+
aborted = 4,
|
|
142
|
+
cancelled = 8,
|
|
143
|
+
duplicated = 16,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface NavigationFailure extends Error {
|
|
147
|
+
type: NavigationFailureType;
|
|
148
|
+
from: RouteLocationNormalizedLoaded;
|
|
149
|
+
to: RouteLocationNormalized;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const navigationFailureSymbol = /* @__PURE__ */ Symbol(
|
|
153
|
+
"moonshine.vue.router.failure",
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
export function createRouterError(
|
|
157
|
+
type: NavigationFailureType,
|
|
158
|
+
from: RouteLocationNormalizedLoaded,
|
|
159
|
+
to: RouteLocationNormalized,
|
|
160
|
+
): NavigationFailure {
|
|
161
|
+
const descriptions: Record<NavigationFailureType, string> = {
|
|
162
|
+
[NavigationFailureType.aborted]: `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`,
|
|
163
|
+
[NavigationFailureType.cancelled]: `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`,
|
|
164
|
+
[NavigationFailureType.duplicated]: `Avoided redundant navigation to current location: "${from.fullPath}".`,
|
|
165
|
+
};
|
|
166
|
+
const err = new Error(descriptions[type]) as NavigationFailure & {
|
|
167
|
+
[navigationFailureSymbol]: boolean;
|
|
168
|
+
};
|
|
169
|
+
err.type = type;
|
|
170
|
+
err.from = from;
|
|
171
|
+
err.to = to;
|
|
172
|
+
err[navigationFailureSymbol] = true;
|
|
173
|
+
return err;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function isNavigationFailure(
|
|
177
|
+
error: unknown,
|
|
178
|
+
type?: NavigationFailureType,
|
|
179
|
+
): error is NavigationFailure {
|
|
180
|
+
if (
|
|
181
|
+
typeof error !== "object" ||
|
|
182
|
+
error === null ||
|
|
183
|
+
!(navigationFailureSymbol in error)
|
|
184
|
+
) {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
if (type === undefined) return true;
|
|
188
|
+
return Boolean((error as unknown as NavigationFailure).type & type);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export enum NavigationDirection {
|
|
192
|
+
back = "back",
|
|
193
|
+
forward = "forward",
|
|
194
|
+
unknown = "",
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export enum NavigationType {
|
|
198
|
+
pop = "pop",
|
|
199
|
+
push = "push",
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export interface NavigationInformation {
|
|
203
|
+
type: NavigationType;
|
|
204
|
+
direction: NavigationDirection;
|
|
205
|
+
delta: number;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export type NavigationCallback = (
|
|
209
|
+
to: string,
|
|
210
|
+
from: string,
|
|
211
|
+
information: NavigationInformation,
|
|
212
|
+
) => void;
|
|
213
|
+
|
|
214
|
+
export interface RouterHistory {
|
|
215
|
+
readonly base: string;
|
|
216
|
+
readonly location: string;
|
|
217
|
+
readonly state: HistoryState;
|
|
218
|
+
push(to: string, data?: HistoryState): void;
|
|
219
|
+
replace(to: string, data?: HistoryState): void;
|
|
220
|
+
go(delta: number, triggerListeners?: boolean): void;
|
|
221
|
+
listen(callback: NavigationCallback): () => void;
|
|
222
|
+
createHref(location: string): string;
|
|
223
|
+
destroy(): void;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function normalizeBase(base?: string): string {
|
|
227
|
+
if (!base) return "";
|
|
228
|
+
let cleaned = base.trim();
|
|
229
|
+
if (!cleaned.startsWith("/") && !cleaned.startsWith("#")) {
|
|
230
|
+
cleaned = "/" + cleaned;
|
|
231
|
+
}
|
|
232
|
+
return cleaned.replace(/\/+$/, "");
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function createMemoryHistory(base = ""): RouterHistory {
|
|
236
|
+
const normalizedBase = normalizeBase(base);
|
|
237
|
+
let queue: string[] = ["/"];
|
|
238
|
+
let states: HistoryState[] = [{}];
|
|
239
|
+
let position = 0;
|
|
240
|
+
const listeners = new Set<NavigationCallback>();
|
|
241
|
+
|
|
242
|
+
function setLocation(location: string, state: HistoryState = {}): void {
|
|
243
|
+
queue.push(location);
|
|
244
|
+
states.push(state);
|
|
245
|
+
position++;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const routerHistory: RouterHistory = {
|
|
249
|
+
base: normalizedBase,
|
|
250
|
+
get location() {
|
|
251
|
+
return queue[position] ?? "/";
|
|
252
|
+
},
|
|
253
|
+
get state() {
|
|
254
|
+
return states[position] ?? {};
|
|
255
|
+
},
|
|
256
|
+
push(to, data = {}) {
|
|
257
|
+
queue.splice(position + 1);
|
|
258
|
+
states.splice(position + 1);
|
|
259
|
+
setLocation(to, data);
|
|
260
|
+
},
|
|
261
|
+
replace(to, data = {}) {
|
|
262
|
+
queue[position] = to;
|
|
263
|
+
states[position] = data;
|
|
264
|
+
},
|
|
265
|
+
go(delta, shouldTrigger = true) {
|
|
266
|
+
const from = this.location;
|
|
267
|
+
const direction =
|
|
268
|
+
delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
|
|
269
|
+
position = Math.max(0, Math.min(queue.length - 1, position + delta));
|
|
270
|
+
if (shouldTrigger) {
|
|
271
|
+
for (const cb of Array.from(listeners)) {
|
|
272
|
+
cb(this.location, from, {
|
|
273
|
+
direction,
|
|
274
|
+
delta,
|
|
275
|
+
type: NavigationType.pop,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
listen(callback) {
|
|
281
|
+
listeners.add(callback);
|
|
282
|
+
return () => {
|
|
283
|
+
listeners.delete(callback);
|
|
284
|
+
};
|
|
285
|
+
},
|
|
286
|
+
createHref(location) {
|
|
287
|
+
return (
|
|
288
|
+
normalizedBase + (location.startsWith("/") ? location : "/" + location)
|
|
289
|
+
);
|
|
290
|
+
},
|
|
291
|
+
destroy() {
|
|
292
|
+
listeners.clear();
|
|
293
|
+
queue = ["/"];
|
|
294
|
+
states = [{}];
|
|
295
|
+
position = 0;
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
return routerHistory;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function createWebHistory(base?: string): RouterHistory {
|
|
303
|
+
const normalizedBase = normalizeBase(base);
|
|
304
|
+
if (
|
|
305
|
+
typeof window === "undefined" ||
|
|
306
|
+
typeof window.history === "undefined" ||
|
|
307
|
+
typeof window.location === "undefined"
|
|
308
|
+
) {
|
|
309
|
+
return createMemoryHistory(normalizedBase);
|
|
310
|
+
}
|
|
311
|
+
const memory = createMemoryHistory(normalizedBase);
|
|
312
|
+
const initialPath =
|
|
313
|
+
(window.location.pathname.startsWith(normalizedBase)
|
|
314
|
+
? window.location.pathname.slice(normalizedBase.length) || "/"
|
|
315
|
+
: window.location.pathname || "/") +
|
|
316
|
+
(window.location.search || "") +
|
|
317
|
+
(window.location.hash || "");
|
|
318
|
+
memory.replace(initialPath, (window.history.state as HistoryState) ?? {});
|
|
319
|
+
|
|
320
|
+
const onPopState = (ev: PopStateEvent) => {
|
|
321
|
+
const prev = memory.location;
|
|
322
|
+
const next =
|
|
323
|
+
(window.location.pathname.startsWith(normalizedBase)
|
|
324
|
+
? window.location.pathname.slice(normalizedBase.length) || "/"
|
|
325
|
+
: window.location.pathname || "/") +
|
|
326
|
+
(window.location.search || "") +
|
|
327
|
+
(window.location.hash || "");
|
|
328
|
+
memory.replace(next, (ev.state as HistoryState) ?? {});
|
|
329
|
+
for (const cb of Array.from(popListeners)) {
|
|
330
|
+
cb(next, prev, {
|
|
331
|
+
direction: NavigationDirection.unknown,
|
|
332
|
+
delta: 0,
|
|
333
|
+
type: NavigationType.pop,
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const popListeners = new Set<NavigationCallback>();
|
|
339
|
+
window.addEventListener("popstate", onPopState);
|
|
340
|
+
|
|
341
|
+
return {
|
|
342
|
+
base: normalizedBase,
|
|
343
|
+
get location() {
|
|
344
|
+
return memory.location;
|
|
345
|
+
},
|
|
346
|
+
get state() {
|
|
347
|
+
return memory.state;
|
|
348
|
+
},
|
|
349
|
+
push(to, data = {}) {
|
|
350
|
+
memory.push(to, data);
|
|
351
|
+
try {
|
|
352
|
+
window.history.pushState(data, "", this.createHref(to));
|
|
353
|
+
} catch {
|
|
354
|
+
// Ignore history pushState errors in synthetic DOM environments
|
|
355
|
+
}
|
|
356
|
+
},
|
|
357
|
+
replace(to, data = {}) {
|
|
358
|
+
memory.replace(to, data);
|
|
359
|
+
try {
|
|
360
|
+
window.history.replaceState(data, "", this.createHref(to));
|
|
361
|
+
} catch {
|
|
362
|
+
// Ignore history replaceState errors in synthetic DOM environments
|
|
363
|
+
}
|
|
364
|
+
},
|
|
365
|
+
go(delta, triggerListeners = true) {
|
|
366
|
+
memory.go(delta, triggerListeners);
|
|
367
|
+
try {
|
|
368
|
+
window.history.go(delta);
|
|
369
|
+
} catch {
|
|
370
|
+
// Ignore
|
|
371
|
+
}
|
|
372
|
+
},
|
|
373
|
+
listen(callback) {
|
|
374
|
+
popListeners.add(callback);
|
|
375
|
+
const unsub = memory.listen(callback);
|
|
376
|
+
return () => {
|
|
377
|
+
popListeners.delete(callback);
|
|
378
|
+
unsub();
|
|
379
|
+
};
|
|
380
|
+
},
|
|
381
|
+
createHref(location) {
|
|
382
|
+
return memory.createHref(location);
|
|
383
|
+
},
|
|
384
|
+
destroy() {
|
|
385
|
+
window.removeEventListener("popstate", onPopState);
|
|
386
|
+
popListeners.clear();
|
|
387
|
+
memory.destroy();
|
|
388
|
+
},
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function createWebHashHistory(base?: string): RouterHistory {
|
|
393
|
+
const prefix = base ? normalizeBase(base) + "/#" : "#";
|
|
394
|
+
const history = createMemoryHistory(prefix);
|
|
395
|
+
return {
|
|
396
|
+
...history,
|
|
397
|
+
createHref(location) {
|
|
398
|
+
const normalized = location.startsWith("/") ? location : "/" + location;
|
|
399
|
+
return prefix + normalized;
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export function parseQuery(search: string): LocationQuery {
|
|
405
|
+
const query: LocationQuery = {};
|
|
406
|
+
const cleaned = search.replace(/^\?/, "");
|
|
407
|
+
if (!cleaned) return query;
|
|
408
|
+
for (const part of cleaned.split("&")) {
|
|
409
|
+
if (!part) continue;
|
|
410
|
+
const eqIdx = part.indexOf("=");
|
|
411
|
+
const rawKey = eqIdx >= 0 ? part.slice(0, eqIdx) : part;
|
|
412
|
+
const rawVal = eqIdx >= 0 ? part.slice(eqIdx + 1) : null;
|
|
413
|
+
const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
|
|
414
|
+
const val =
|
|
415
|
+
rawVal === null ? null : decodeURIComponent(rawVal.replace(/\+/g, " "));
|
|
416
|
+
if (key in query) {
|
|
417
|
+
const existing = query[key];
|
|
418
|
+
if (Array.isArray(existing)) {
|
|
419
|
+
existing.push(val);
|
|
420
|
+
} else {
|
|
421
|
+
query[key] = [existing as LocationQueryValue, val];
|
|
422
|
+
}
|
|
423
|
+
} else {
|
|
424
|
+
query[key] = val;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return query;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function stringifyQuery(query?: LocationQueryRaw): string {
|
|
431
|
+
if (!query) return "";
|
|
432
|
+
const parts: string[] = [];
|
|
433
|
+
for (const [key, rawValue] of Object.entries(query)) {
|
|
434
|
+
if (rawValue === undefined) continue;
|
|
435
|
+
const encodedKey = encodeURIComponent(key);
|
|
436
|
+
if (rawValue === null) {
|
|
437
|
+
parts.push(encodedKey);
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
const values = Array.isArray(rawValue) ? rawValue : [rawValue];
|
|
441
|
+
for (const item of values) {
|
|
442
|
+
if (item === undefined) continue;
|
|
443
|
+
if (item === null) {
|
|
444
|
+
parts.push(encodedKey);
|
|
445
|
+
} else {
|
|
446
|
+
parts.push(`${encodedKey}=${encodeURIComponent(String(item))}`);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return parts.join("&");
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export const START_LOCATION: RouteLocationNormalizedLoaded =
|
|
454
|
+
/* @__PURE__ */ Object.freeze({
|
|
455
|
+
path: "/",
|
|
456
|
+
name: undefined,
|
|
457
|
+
params: Object.freeze({}),
|
|
458
|
+
query: Object.freeze({}),
|
|
459
|
+
hash: "",
|
|
460
|
+
fullPath: "/",
|
|
461
|
+
matched: [],
|
|
462
|
+
meta: Object.freeze({}),
|
|
463
|
+
redirectedFrom: undefined,
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
export const routerKey: InjectionKey<Router> = /* @__PURE__ */ Symbol(
|
|
467
|
+
"moonshine.vue.router",
|
|
468
|
+
) as InjectionKey<Router>;
|
|
469
|
+
|
|
470
|
+
export const routeLocationKey: InjectionKey<RouteLocationNormalizedLoaded> =
|
|
471
|
+
/* @__PURE__ */ Symbol(
|
|
472
|
+
"moonshine.vue.routeLocation",
|
|
473
|
+
) as InjectionKey<RouteLocationNormalizedLoaded>;
|
|
474
|
+
|
|
475
|
+
export const routerViewLocationKey: InjectionKey<
|
|
476
|
+
Ref<RouteLocationNormalizedLoaded>
|
|
477
|
+
> = /* @__PURE__ */ Symbol("moonshine.vue.routerViewLocation") as InjectionKey<
|
|
478
|
+
Ref<RouteLocationNormalizedLoaded>
|
|
479
|
+
>;
|
|
480
|
+
|
|
481
|
+
export const viewDepthKey: InjectionKey<number> = /* @__PURE__ */ Symbol(
|
|
482
|
+
"moonshine.vue.routerViewDepth",
|
|
483
|
+
) as InjectionKey<number>;
|
|
484
|
+
|
|
485
|
+
export interface RouterOptions {
|
|
486
|
+
history: RouterHistory;
|
|
487
|
+
routes: ReadonlyArray<RouteRecordRaw>;
|
|
488
|
+
parseQuery?: typeof parseQuery;
|
|
489
|
+
stringifyQuery?: typeof stringifyQuery;
|
|
490
|
+
linkActiveClass?: string;
|
|
491
|
+
linkExactActiveClass?: string;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export interface Router {
|
|
495
|
+
readonly currentRoute: Ref<RouteLocationNormalizedLoaded>;
|
|
496
|
+
readonly options: RouterOptions;
|
|
497
|
+
listening: boolean;
|
|
498
|
+
addRoute(parentName: RouteRecordName, route: RouteRecordRaw): () => void;
|
|
499
|
+
addRoute(route: RouteRecordRaw): () => void;
|
|
500
|
+
removeRoute(name: RouteRecordName): void;
|
|
501
|
+
hasRoute(name: RouteRecordName): boolean;
|
|
502
|
+
getRoutes(): RouteRecordNormalized[];
|
|
503
|
+
resolve(
|
|
504
|
+
rawLocation: RouteLocationRaw,
|
|
505
|
+
currentLocation?: RouteLocationNormalizedLoaded,
|
|
506
|
+
): RouteLocationNormalized & { href: string };
|
|
507
|
+
push(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>;
|
|
508
|
+
replace(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>;
|
|
509
|
+
back(): ReturnType<Router["go"]>;
|
|
510
|
+
forward(): ReturnType<Router["go"]>;
|
|
511
|
+
go(delta: number): void;
|
|
512
|
+
beforeEach(guard: NavigationGuard): () => void;
|
|
513
|
+
beforeResolve(guard: NavigationGuard): () => void;
|
|
514
|
+
afterEach(hook: NavigationHookAfter): () => void;
|
|
515
|
+
onError(
|
|
516
|
+
handler: (
|
|
517
|
+
error: any,
|
|
518
|
+
to: RouteLocationNormalized,
|
|
519
|
+
from: RouteLocationNormalizedLoaded,
|
|
520
|
+
) => any,
|
|
521
|
+
): () => void;
|
|
522
|
+
isReady(): Promise<void>;
|
|
523
|
+
install(app?: any): void;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
interface CompiledRouteEntry {
|
|
527
|
+
record: RouteRecordNormalized;
|
|
528
|
+
chain: RouteRecordNormalized[];
|
|
529
|
+
regex: RegExp;
|
|
530
|
+
paramKeys: Array<{ name: string; repeatable: boolean; optional: boolean }>;
|
|
531
|
+
score: number;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function joinPaths(parentPath: string, childPath: string): string {
|
|
535
|
+
if (!childPath) return parentPath || "/";
|
|
536
|
+
if (childPath.startsWith("/")) return childPath;
|
|
537
|
+
const base = parentPath.replace(/\/+$/, "");
|
|
538
|
+
return `${base}/${childPath}`.replace(/\/+/g, "/");
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function compileRoutePattern(path: string): {
|
|
542
|
+
regex: RegExp;
|
|
543
|
+
paramKeys: Array<{ name: string; repeatable: boolean; optional: boolean }>;
|
|
544
|
+
score: number;
|
|
545
|
+
} {
|
|
546
|
+
const normalized = path === "" ? "/" : path;
|
|
547
|
+
if (normalized === "/") {
|
|
548
|
+
return { regex: /^\/$/, paramKeys: [], score: 100 };
|
|
549
|
+
}
|
|
550
|
+
const segments = normalized.replace(/^\/+|\/+$/g, "").split("/");
|
|
551
|
+
const paramKeys: Array<{
|
|
552
|
+
name: string;
|
|
553
|
+
repeatable: boolean;
|
|
554
|
+
optional: boolean;
|
|
555
|
+
}> = [];
|
|
556
|
+
let pattern = "^";
|
|
557
|
+
let score = 0;
|
|
558
|
+
|
|
559
|
+
for (const seg of segments) {
|
|
560
|
+
if (seg.startsWith(":")) {
|
|
561
|
+
const match = /^:([A-Za-z0-9_]+)(?:\(([^)]+)\))?([?*+]?)$/.exec(seg);
|
|
562
|
+
if (match) {
|
|
563
|
+
const name = match[1]!;
|
|
564
|
+
const customRegex = match[2];
|
|
565
|
+
const modifier = match[3] || "";
|
|
566
|
+
const repeatable = modifier === "+" || modifier === "*";
|
|
567
|
+
const optional = modifier === "?" || modifier === "*";
|
|
568
|
+
paramKeys.push({ name, repeatable, optional });
|
|
569
|
+
if (customRegex && modifier === "*") {
|
|
570
|
+
pattern += `(?:/(.*))?`;
|
|
571
|
+
score += 1;
|
|
572
|
+
} else if (repeatable && optional) {
|
|
573
|
+
pattern += `(?:/(.+))?`;
|
|
574
|
+
score += 2;
|
|
575
|
+
} else if (repeatable) {
|
|
576
|
+
pattern += `/(.+)`;
|
|
577
|
+
score += 5;
|
|
578
|
+
} else if (optional) {
|
|
579
|
+
pattern += `(?:/(${customRegex ?? "[^/]+"}))?`;
|
|
580
|
+
score += 8;
|
|
581
|
+
} else {
|
|
582
|
+
pattern += `/(${customRegex ?? "[^/]+"})`;
|
|
583
|
+
score += 10;
|
|
584
|
+
}
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (seg === "*") {
|
|
589
|
+
paramKeys.push({ name: "pathMatch", repeatable: true, optional: true });
|
|
590
|
+
pattern += `(?:/(.*))?`;
|
|
591
|
+
score += 1;
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
const escaped = seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
595
|
+
pattern += `/${escaped}`;
|
|
596
|
+
score += 20;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
pattern += "/?$";
|
|
600
|
+
return { regex: new RegExp(pattern), paramKeys, score };
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function parseLocationString(
|
|
604
|
+
raw: string,
|
|
605
|
+
parseQueryFn: (query: string) => LocationQuery,
|
|
606
|
+
): { path: string; hash: string; query: LocationQuery } {
|
|
607
|
+
let hash = "";
|
|
608
|
+
let query: LocationQuery = {};
|
|
609
|
+
const hashIdx = raw.indexOf("#");
|
|
610
|
+
if (hashIdx >= 0) {
|
|
611
|
+
hash = raw.slice(hashIdx);
|
|
612
|
+
raw = raw.slice(0, hashIdx);
|
|
613
|
+
}
|
|
614
|
+
const queryIdx = raw.indexOf("?");
|
|
615
|
+
if (queryIdx >= 0) {
|
|
616
|
+
query = parseQueryFn(raw.slice(queryIdx + 1));
|
|
617
|
+
raw = raw.slice(0, queryIdx);
|
|
618
|
+
}
|
|
619
|
+
return { path: raw, hash, query };
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function matchRouteRegex(
|
|
623
|
+
path: string,
|
|
624
|
+
entries: CompiledRouteEntry[],
|
|
625
|
+
): {
|
|
626
|
+
matched: RouteRecordNormalized[];
|
|
627
|
+
name: RouteRecordName | null | undefined;
|
|
628
|
+
params: RouteParams;
|
|
629
|
+
} | null {
|
|
630
|
+
for (const entry of entries) {
|
|
631
|
+
const m = entry.regex.exec(path);
|
|
632
|
+
if (m) {
|
|
633
|
+
const matched = entry.chain.map((r) => r.aliasOf ?? r);
|
|
634
|
+
const leaf = matched[matched.length - 1];
|
|
635
|
+
const name = leaf?.name;
|
|
636
|
+
const params: RouteParams = {};
|
|
637
|
+
entry.paramKeys.forEach((keyInfo, i) => {
|
|
638
|
+
const rawVal = m[i + 1];
|
|
639
|
+
if (rawVal === undefined) {
|
|
640
|
+
if (keyInfo.repeatable) params[keyInfo.name] = [];
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
if (keyInfo.repeatable) {
|
|
644
|
+
params[keyInfo.name] = rawVal
|
|
645
|
+
.split("/")
|
|
646
|
+
.map((part) => decodeURIComponent(part));
|
|
647
|
+
} else {
|
|
648
|
+
params[keyInfo.name] = decodeURIComponent(rawVal);
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
return { matched, name, params };
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return null;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function normalizePropsOption(
|
|
658
|
+
raw: RouteRecordRaw,
|
|
659
|
+
): RouteRecordNormalized["props"] {
|
|
660
|
+
if (!raw.props) return {};
|
|
661
|
+
if (typeof raw.props === "object" && !raw.component && raw.components) {
|
|
662
|
+
return raw.props as RouteRecordNormalized["props"];
|
|
663
|
+
}
|
|
664
|
+
return { default: raw.props };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
let activeRouter: Router | undefined;
|
|
668
|
+
|
|
669
|
+
export function setActiveRouter(router: Router | undefined): void {
|
|
670
|
+
activeRouter = router;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
export function createRouter(options: RouterOptions): Router {
|
|
674
|
+
const routerHistory = options.history ?? createMemoryHistory();
|
|
675
|
+
const parseQueryFn = options.parseQuery ?? parseQuery;
|
|
676
|
+
const stringifyQueryFn = options.stringifyQuery ?? stringifyQuery;
|
|
677
|
+
|
|
678
|
+
const entries: CompiledRouteEntry[] = [];
|
|
679
|
+
const namedMap = new Map<RouteRecordName, CompiledRouteEntry>();
|
|
680
|
+
const beforeGuards = new Set<NavigationGuard>();
|
|
681
|
+
const beforeResolveGuards = new Set<NavigationGuard>();
|
|
682
|
+
const afterHooks = new Set<NavigationHookAfter>();
|
|
683
|
+
const errorHandlers = new Set<
|
|
684
|
+
(
|
|
685
|
+
error: any,
|
|
686
|
+
to: RouteLocationNormalized,
|
|
687
|
+
from: RouteLocationNormalizedLoaded,
|
|
688
|
+
) => any
|
|
689
|
+
>();
|
|
690
|
+
|
|
691
|
+
let currentNavigationId = 0;
|
|
692
|
+
let ready = false;
|
|
693
|
+
let readyWaiters: Array<{
|
|
694
|
+
resolve: () => void;
|
|
695
|
+
reject: (err: any) => void;
|
|
696
|
+
}> = [];
|
|
697
|
+
|
|
698
|
+
function markReady(err?: any) {
|
|
699
|
+
if (ready) return;
|
|
700
|
+
ready = true;
|
|
701
|
+
const waiters = readyWaiters.splice(0);
|
|
702
|
+
for (const w of waiters) {
|
|
703
|
+
if (err) w.reject(err);
|
|
704
|
+
else w.resolve();
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function insertRouteRecord(
|
|
709
|
+
raw: RouteRecordRaw,
|
|
710
|
+
parent?: CompiledRouteEntry,
|
|
711
|
+
aliasOf?: RouteRecordNormalized,
|
|
712
|
+
): () => void {
|
|
713
|
+
const fullPath = parent
|
|
714
|
+
? joinPaths(parent.record.path, raw.path)
|
|
715
|
+
: raw.path || "/";
|
|
716
|
+
const components: Record<string, RouteComponent> = raw.components
|
|
717
|
+
? { ...raw.components }
|
|
718
|
+
: raw.component
|
|
719
|
+
? { default: raw.component }
|
|
720
|
+
: {};
|
|
721
|
+
const beforeEnterList = raw.beforeEnter
|
|
722
|
+
? Array.isArray(raw.beforeEnter)
|
|
723
|
+
? [...raw.beforeEnter]
|
|
724
|
+
: [raw.beforeEnter]
|
|
725
|
+
: [];
|
|
726
|
+
|
|
727
|
+
const normalized: RouteRecordNormalized = {
|
|
728
|
+
path: fullPath,
|
|
729
|
+
name: raw.name,
|
|
730
|
+
components,
|
|
731
|
+
redirect: raw.redirect,
|
|
732
|
+
aliasOf,
|
|
733
|
+
children: raw.children ?? [],
|
|
734
|
+
meta: { ...raw.meta },
|
|
735
|
+
props: normalizePropsOption(raw),
|
|
736
|
+
beforeGuards: beforeEnterList,
|
|
737
|
+
leaveGuards: new Set(),
|
|
738
|
+
updateGuards: new Set(),
|
|
739
|
+
};
|
|
740
|
+
|
|
741
|
+
const chain = parent ? [...parent.chain, normalized] : [normalized];
|
|
742
|
+
const { regex, paramKeys, score } = compileRoutePattern(fullPath);
|
|
743
|
+
const entry: CompiledRouteEntry = {
|
|
744
|
+
record: normalized,
|
|
745
|
+
chain,
|
|
746
|
+
regex,
|
|
747
|
+
paramKeys,
|
|
748
|
+
score,
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
entries.push(entry);
|
|
752
|
+
entries.sort((a, b) => b.score - a.score);
|
|
753
|
+
if (normalized.name !== undefined && !aliasOf) {
|
|
754
|
+
namedMap.set(normalized.name, entry);
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
const childRemovers: Array<() => void> = [];
|
|
758
|
+
if (raw.children) {
|
|
759
|
+
for (const child of raw.children) {
|
|
760
|
+
childRemovers.push(insertRouteRecord(child, entry));
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
if (raw.alias && !aliasOf) {
|
|
765
|
+
const aliases = Array.isArray(raw.alias) ? raw.alias : [raw.alias];
|
|
766
|
+
for (const aliasPath of aliases) {
|
|
767
|
+
childRemovers.push(
|
|
768
|
+
insertRouteRecord(
|
|
769
|
+
{ ...raw, path: aliasPath, alias: undefined },
|
|
770
|
+
parent,
|
|
771
|
+
normalized,
|
|
772
|
+
),
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
return () => {
|
|
778
|
+
for (const removeChild of childRemovers) removeChild();
|
|
779
|
+
const idx = entries.indexOf(entry);
|
|
780
|
+
if (idx >= 0) entries.splice(idx, 1);
|
|
781
|
+
if (
|
|
782
|
+
normalized.name !== undefined &&
|
|
783
|
+
namedMap.get(normalized.name) === entry
|
|
784
|
+
) {
|
|
785
|
+
namedMap.delete(normalized.name);
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
for (const route of options.routes) {
|
|
791
|
+
insertRouteRecord(route);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const currentRoute = ref<RouteLocationNormalizedLoaded>(START_LOCATION);
|
|
795
|
+
|
|
796
|
+
function buildPathFromEntry(
|
|
797
|
+
entry: CompiledRouteEntry,
|
|
798
|
+
params: Record<string, any> = {},
|
|
799
|
+
): { path: string; params: RouteParams } {
|
|
800
|
+
const normalizedParams: RouteParams = {};
|
|
801
|
+
const segments = entry.record.path.replace(/^\/+|\/+$/g, "").split("/");
|
|
802
|
+
if (entry.record.path === "/" || segments[0] === "") {
|
|
803
|
+
return { path: "/", params: normalizedParams };
|
|
804
|
+
}
|
|
805
|
+
const outSegments: string[] = [];
|
|
806
|
+
for (const seg of segments) {
|
|
807
|
+
if (seg.startsWith(":")) {
|
|
808
|
+
const match = /^:([A-Za-z0-9_]+)(?:\(([^)]+)\))?([?*+]?)$/.exec(seg);
|
|
809
|
+
if (match) {
|
|
810
|
+
const name = match[1]!;
|
|
811
|
+
const modifier = match[3] || "";
|
|
812
|
+
const optional = modifier === "?" || modifier === "*";
|
|
813
|
+
const val = params[name];
|
|
814
|
+
if (val === undefined || val === null || val === "") {
|
|
815
|
+
if (optional) continue;
|
|
816
|
+
throw new Error(`Missing required param "${name}"`);
|
|
817
|
+
}
|
|
818
|
+
if (Array.isArray(val)) {
|
|
819
|
+
const strArr = val.map((v) => String(v));
|
|
820
|
+
normalizedParams[name] = strArr;
|
|
821
|
+
outSegments.push(...strArr.map((v) => encodeURIComponent(v)));
|
|
822
|
+
} else {
|
|
823
|
+
const strVal = String(val);
|
|
824
|
+
normalizedParams[name] = strVal;
|
|
825
|
+
outSegments.push(encodeURIComponent(strVal));
|
|
826
|
+
}
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
outSegments.push(seg);
|
|
831
|
+
}
|
|
832
|
+
return {
|
|
833
|
+
path: "/" + outSegments.join("/"),
|
|
834
|
+
params: normalizedParams,
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function resolve(
|
|
839
|
+
rawLocation: RouteLocationRaw,
|
|
840
|
+
currentLocation: RouteLocationNormalizedLoaded = currentRoute.value,
|
|
841
|
+
): RouteLocationNormalized & { href: string } {
|
|
842
|
+
let path = "/";
|
|
843
|
+
let query: LocationQuery = {};
|
|
844
|
+
let hash = "";
|
|
845
|
+
let params: RouteParams = {};
|
|
846
|
+
let matched: RouteRecordNormalized[] = [];
|
|
847
|
+
let name: RouteRecordName | null | undefined;
|
|
848
|
+
|
|
849
|
+
if (typeof rawLocation === "string") {
|
|
850
|
+
const parsed = parseLocationString(rawLocation, parseQueryFn);
|
|
851
|
+
hash = parsed.hash;
|
|
852
|
+
query = parsed.query;
|
|
853
|
+
const raw = parsed.path;
|
|
854
|
+
|
|
855
|
+
if (!raw) {
|
|
856
|
+
path = currentLocation.path || "/";
|
|
857
|
+
} else if (raw.startsWith("/")) {
|
|
858
|
+
path = raw;
|
|
859
|
+
} else {
|
|
860
|
+
const baseDir = currentLocation.path.replace(/\/[^/]*$/, "");
|
|
861
|
+
path = `${baseDir}/${raw}`.replace(/\/+/g, "/");
|
|
862
|
+
}
|
|
863
|
+
} else if ("name" in rawLocation && rawLocation.name !== undefined) {
|
|
864
|
+
const entry = namedMap.get(rawLocation.name);
|
|
865
|
+
if (!entry) {
|
|
866
|
+
throw new Error(
|
|
867
|
+
`No match for route named "${String(rawLocation.name)}"`,
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
const mergedParams = {
|
|
871
|
+
...currentLocation.params,
|
|
872
|
+
...rawLocation.params,
|
|
873
|
+
};
|
|
874
|
+
const built = buildPathFromEntry(entry, mergedParams);
|
|
875
|
+
path = built.path;
|
|
876
|
+
params = built.params;
|
|
877
|
+
matched = entry.chain.map((r) => r.aliasOf ?? r);
|
|
878
|
+
name = entry.record.name;
|
|
879
|
+
query = rawLocation.query
|
|
880
|
+
? parseQueryFn(stringifyQueryFn(rawLocation.query))
|
|
881
|
+
: {};
|
|
882
|
+
hash = rawLocation.hash
|
|
883
|
+
? rawLocation.hash.startsWith("#")
|
|
884
|
+
? rawLocation.hash
|
|
885
|
+
: "#" + rawLocation.hash
|
|
886
|
+
: "";
|
|
887
|
+
} else if ("path" in rawLocation) {
|
|
888
|
+
const rawInput = rawLocation.path || "/";
|
|
889
|
+
const parsed = parseLocationString(rawInput, parseQueryFn);
|
|
890
|
+
hash = parsed.hash;
|
|
891
|
+
query = parsed.query;
|
|
892
|
+
const raw = parsed.path;
|
|
893
|
+
|
|
894
|
+
if (rawLocation.query) {
|
|
895
|
+
query = {
|
|
896
|
+
...query,
|
|
897
|
+
...parseQueryFn(stringifyQueryFn(rawLocation.query)),
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
if (rawLocation.hash) {
|
|
901
|
+
hash = rawLocation.hash.startsWith("#")
|
|
902
|
+
? rawLocation.hash
|
|
903
|
+
: "#" + rawLocation.hash;
|
|
904
|
+
}
|
|
905
|
+
path = raw.startsWith("/") ? raw : "/" + raw;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
if (matched.length === 0) {
|
|
909
|
+
const matchResult = matchRouteRegex(path, entries);
|
|
910
|
+
if (matchResult) {
|
|
911
|
+
matched = matchResult.matched;
|
|
912
|
+
name = matchResult.name;
|
|
913
|
+
params = matchResult.params;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const meta: RouteMeta = {};
|
|
918
|
+
for (const record of matched) {
|
|
919
|
+
Object.assign(meta, record.meta);
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
const queryString = stringifyQueryFn(query);
|
|
923
|
+
const fullPath =
|
|
924
|
+
path + (queryString ? `?${queryString}` : "") + (hash || "");
|
|
925
|
+
const href = routerHistory.createHref(fullPath);
|
|
926
|
+
|
|
927
|
+
return {
|
|
928
|
+
path,
|
|
929
|
+
fullPath,
|
|
930
|
+
name,
|
|
931
|
+
params,
|
|
932
|
+
query,
|
|
933
|
+
hash,
|
|
934
|
+
matched,
|
|
935
|
+
meta,
|
|
936
|
+
redirectedFrom: undefined,
|
|
937
|
+
href,
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
async function runGuardQueue(
|
|
942
|
+
guards: NavigationGuard[],
|
|
943
|
+
to: RouteLocationNormalized,
|
|
944
|
+
from: RouteLocationNormalizedLoaded,
|
|
945
|
+
): Promise<NavigationGuardReturn> {
|
|
946
|
+
for (const guard of guards) {
|
|
947
|
+
let nextCalled = false;
|
|
948
|
+
let nextArg: any;
|
|
949
|
+
const next: NavigationGuardNext = (arg?: any) => {
|
|
950
|
+
nextCalled = true;
|
|
951
|
+
nextArg = arg;
|
|
952
|
+
};
|
|
953
|
+
const ret = await guard(to, from, next);
|
|
954
|
+
const outcome = nextCalled ? nextArg : ret;
|
|
955
|
+
if (outcome === false) return false;
|
|
956
|
+
if (outcome instanceof Error) throw outcome;
|
|
957
|
+
if (
|
|
958
|
+
typeof outcome === "string" ||
|
|
959
|
+
(typeof outcome === "object" &&
|
|
960
|
+
outcome !== null &&
|
|
961
|
+
("path" in outcome || "name" in outcome))
|
|
962
|
+
) {
|
|
963
|
+
return outcome as RouteLocationRaw;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
return undefined;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
async function navigate(
|
|
970
|
+
rawTo: RouteLocationRaw,
|
|
971
|
+
replaceFlag: boolean,
|
|
972
|
+
redirectedFrom?: RouteLocationNormalized,
|
|
973
|
+
): Promise<NavigationFailure | void | undefined> {
|
|
974
|
+
const navId = ++currentNavigationId;
|
|
975
|
+
const from = currentRoute.value;
|
|
976
|
+
let to: RouteLocationNormalized & { href: string };
|
|
977
|
+
try {
|
|
978
|
+
to = resolve(rawTo, from);
|
|
979
|
+
} catch (err) {
|
|
980
|
+
markReady(err);
|
|
981
|
+
for (const handler of Array.from(errorHandlers)) {
|
|
982
|
+
handler(err, START_LOCATION, from);
|
|
983
|
+
}
|
|
984
|
+
throw err;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
if (redirectedFrom) {
|
|
988
|
+
to.redirectedFrom = redirectedFrom;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
const force =
|
|
992
|
+
typeof rawTo === "object" && rawTo !== null && "force" in rawTo
|
|
993
|
+
? Boolean(rawTo.force)
|
|
994
|
+
: false;
|
|
995
|
+
const shouldReplace =
|
|
996
|
+
replaceFlag ||
|
|
997
|
+
(typeof rawTo === "object" && rawTo !== null && "replace" in rawTo
|
|
998
|
+
? Boolean(rawTo.replace)
|
|
999
|
+
: false);
|
|
1000
|
+
|
|
1001
|
+
if (
|
|
1002
|
+
!force &&
|
|
1003
|
+
from !== START_LOCATION &&
|
|
1004
|
+
to.fullPath === from.fullPath &&
|
|
1005
|
+
!redirectedFrom
|
|
1006
|
+
) {
|
|
1007
|
+
const failure = createRouterError(
|
|
1008
|
+
NavigationFailureType.duplicated,
|
|
1009
|
+
from,
|
|
1010
|
+
to,
|
|
1011
|
+
);
|
|
1012
|
+
markReady();
|
|
1013
|
+
for (const hook of Array.from(afterHooks)) {
|
|
1014
|
+
hook(to, from, failure);
|
|
1015
|
+
}
|
|
1016
|
+
return failure;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const leafRecord = to.matched[to.matched.length - 1];
|
|
1020
|
+
if (leafRecord?.redirect) {
|
|
1021
|
+
const redirectTarget =
|
|
1022
|
+
typeof leafRecord.redirect === "function"
|
|
1023
|
+
? leafRecord.redirect(to)
|
|
1024
|
+
: leafRecord.redirect;
|
|
1025
|
+
return navigate(redirectTarget, shouldReplace, redirectedFrom ?? to);
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
const toMatchedRaw = to.matched.map((r) => toRaw(r));
|
|
1029
|
+
const fromMatchedRaw = from.matched.map((r) => toRaw(r));
|
|
1030
|
+
const leavingRecords = fromMatchedRaw.filter(
|
|
1031
|
+
(record) => !toMatchedRaw.includes(record),
|
|
1032
|
+
);
|
|
1033
|
+
const updatingRecords = fromMatchedRaw.filter((record) =>
|
|
1034
|
+
toMatchedRaw.includes(record),
|
|
1035
|
+
);
|
|
1036
|
+
const enteringRecords = toMatchedRaw.filter(
|
|
1037
|
+
(record) => !fromMatchedRaw.includes(record),
|
|
1038
|
+
);
|
|
1039
|
+
|
|
1040
|
+
const guards: NavigationGuard[] = [];
|
|
1041
|
+
for (const record of leavingRecords.toReversed()) {
|
|
1042
|
+
for (const g of record.leaveGuards) guards.push(g);
|
|
1043
|
+
}
|
|
1044
|
+
for (const g of beforeGuards) {
|
|
1045
|
+
guards.push(g);
|
|
1046
|
+
}
|
|
1047
|
+
for (const record of updatingRecords) {
|
|
1048
|
+
for (const g of record.updateGuards) guards.push(g);
|
|
1049
|
+
}
|
|
1050
|
+
for (const record of enteringRecords) {
|
|
1051
|
+
for (const g of record.beforeGuards) guards.push(g);
|
|
1052
|
+
}
|
|
1053
|
+
for (const g of beforeResolveGuards) {
|
|
1054
|
+
guards.push(g);
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
let guardResult: NavigationGuardReturn;
|
|
1058
|
+
try {
|
|
1059
|
+
guardResult = await runGuardQueue(guards, to, from);
|
|
1060
|
+
} catch (err) {
|
|
1061
|
+
markReady(err);
|
|
1062
|
+
for (const handler of Array.from(errorHandlers)) {
|
|
1063
|
+
handler(err, to, from);
|
|
1064
|
+
}
|
|
1065
|
+
throw err;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
if (navId !== currentNavigationId) {
|
|
1069
|
+
return createRouterError(NavigationFailureType.cancelled, from, to);
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
if (guardResult === false) {
|
|
1073
|
+
const failure = createRouterError(
|
|
1074
|
+
NavigationFailureType.aborted,
|
|
1075
|
+
from,
|
|
1076
|
+
to,
|
|
1077
|
+
);
|
|
1078
|
+
markReady();
|
|
1079
|
+
for (const hook of Array.from(afterHooks)) {
|
|
1080
|
+
hook(to, from, failure);
|
|
1081
|
+
}
|
|
1082
|
+
return failure;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
if (
|
|
1086
|
+
typeof guardResult === "string" ||
|
|
1087
|
+
(typeof guardResult === "object" &&
|
|
1088
|
+
guardResult !== null &&
|
|
1089
|
+
("path" in guardResult || "name" in guardResult))
|
|
1090
|
+
) {
|
|
1091
|
+
return navigate(guardResult, shouldReplace, redirectedFrom ?? to);
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
const stateData =
|
|
1095
|
+
typeof rawTo === "object" && rawTo !== null && "state" in rawTo
|
|
1096
|
+
? rawTo.state
|
|
1097
|
+
: undefined;
|
|
1098
|
+
if (shouldReplace || from === START_LOCATION) {
|
|
1099
|
+
routerHistory.replace(to.fullPath, stateData);
|
|
1100
|
+
} else {
|
|
1101
|
+
routerHistory.push(to.fullPath, stateData);
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
currentRoute.value = to;
|
|
1105
|
+
markReady();
|
|
1106
|
+
|
|
1107
|
+
for (const hook of Array.from(afterHooks)) {
|
|
1108
|
+
hook(to, from, undefined);
|
|
1109
|
+
}
|
|
1110
|
+
return undefined;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
let removeHistoryListener: (() => void) | undefined;
|
|
1114
|
+
|
|
1115
|
+
function setupListeners() {
|
|
1116
|
+
if (removeHistoryListener) return;
|
|
1117
|
+
removeHistoryListener = routerHistory.listen((to) => {
|
|
1118
|
+
void navigate(to, true);
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
const initialLocation = resolve(
|
|
1123
|
+
routerHistory.location || "/",
|
|
1124
|
+
START_LOCATION,
|
|
1125
|
+
);
|
|
1126
|
+
const initialLeaf =
|
|
1127
|
+
initialLocation.matched[initialLocation.matched.length - 1];
|
|
1128
|
+
if (initialLeaf?.redirect) {
|
|
1129
|
+
const redirectTarget =
|
|
1130
|
+
typeof initialLeaf.redirect === "function"
|
|
1131
|
+
? initialLeaf.redirect(initialLocation)
|
|
1132
|
+
: initialLeaf.redirect;
|
|
1133
|
+
try {
|
|
1134
|
+
const redirected = resolve(redirectTarget, initialLocation);
|
|
1135
|
+
redirected.redirectedFrom = initialLocation;
|
|
1136
|
+
currentRoute.value = redirected;
|
|
1137
|
+
routerHistory.replace(redirected.fullPath);
|
|
1138
|
+
} catch {
|
|
1139
|
+
currentRoute.value = initialLocation;
|
|
1140
|
+
}
|
|
1141
|
+
} else {
|
|
1142
|
+
currentRoute.value = initialLocation;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
const router: Router = {
|
|
1146
|
+
currentRoute,
|
|
1147
|
+
options,
|
|
1148
|
+
listening: true,
|
|
1149
|
+
addRoute(
|
|
1150
|
+
parentOrRoute: RouteRecordName | RouteRecordRaw,
|
|
1151
|
+
maybeRoute?: RouteRecordRaw,
|
|
1152
|
+
) {
|
|
1153
|
+
if (typeof parentOrRoute === "object" && parentOrRoute !== null) {
|
|
1154
|
+
return insertRouteRecord(parentOrRoute);
|
|
1155
|
+
}
|
|
1156
|
+
const parentEntry = namedMap.get(parentOrRoute);
|
|
1157
|
+
if (!parentEntry || !maybeRoute) {
|
|
1158
|
+
throw new Error(
|
|
1159
|
+
`Parent route "${String(parentOrRoute)}" not found for addRoute`,
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
return insertRouteRecord(maybeRoute, parentEntry);
|
|
1163
|
+
},
|
|
1164
|
+
removeRoute(name) {
|
|
1165
|
+
const entry = namedMap.get(name);
|
|
1166
|
+
if (!entry) return;
|
|
1167
|
+
namedMap.delete(name);
|
|
1168
|
+
const toRemove = entries.filter((e) => e.chain.includes(entry.record));
|
|
1169
|
+
for (const item of toRemove) {
|
|
1170
|
+
const idx = entries.indexOf(item);
|
|
1171
|
+
if (idx >= 0) entries.splice(idx, 1);
|
|
1172
|
+
if (item.record.name !== undefined) {
|
|
1173
|
+
namedMap.delete(item.record.name);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
},
|
|
1177
|
+
hasRoute(name) {
|
|
1178
|
+
return namedMap.has(name);
|
|
1179
|
+
},
|
|
1180
|
+
getRoutes() {
|
|
1181
|
+
return entries.filter((e) => !e.record.aliasOf).map((e) => e.record);
|
|
1182
|
+
},
|
|
1183
|
+
resolve,
|
|
1184
|
+
push(to) {
|
|
1185
|
+
setupListeners();
|
|
1186
|
+
return navigate(to, false);
|
|
1187
|
+
},
|
|
1188
|
+
replace(to) {
|
|
1189
|
+
setupListeners();
|
|
1190
|
+
return navigate(to, true);
|
|
1191
|
+
},
|
|
1192
|
+
back() {
|
|
1193
|
+
return this.go(-1);
|
|
1194
|
+
},
|
|
1195
|
+
forward() {
|
|
1196
|
+
return this.go(1);
|
|
1197
|
+
},
|
|
1198
|
+
go(delta) {
|
|
1199
|
+
setupListeners();
|
|
1200
|
+
routerHistory.go(delta, true);
|
|
1201
|
+
},
|
|
1202
|
+
beforeEach(guard) {
|
|
1203
|
+
beforeGuards.add(guard);
|
|
1204
|
+
return () => {
|
|
1205
|
+
beforeGuards.delete(guard);
|
|
1206
|
+
};
|
|
1207
|
+
},
|
|
1208
|
+
beforeResolve(guard) {
|
|
1209
|
+
beforeResolveGuards.add(guard);
|
|
1210
|
+
return () => {
|
|
1211
|
+
beforeResolveGuards.delete(guard);
|
|
1212
|
+
};
|
|
1213
|
+
},
|
|
1214
|
+
afterEach(hook) {
|
|
1215
|
+
afterHooks.add(hook);
|
|
1216
|
+
return () => {
|
|
1217
|
+
afterHooks.delete(hook);
|
|
1218
|
+
};
|
|
1219
|
+
},
|
|
1220
|
+
onError(handler) {
|
|
1221
|
+
errorHandlers.add(handler);
|
|
1222
|
+
return () => {
|
|
1223
|
+
errorHandlers.delete(handler);
|
|
1224
|
+
};
|
|
1225
|
+
},
|
|
1226
|
+
isReady() {
|
|
1227
|
+
if (ready && currentRoute.value !== START_LOCATION) {
|
|
1228
|
+
return Promise.resolve();
|
|
1229
|
+
}
|
|
1230
|
+
ready = true;
|
|
1231
|
+
return Promise.resolve();
|
|
1232
|
+
},
|
|
1233
|
+
install(app?: any) {
|
|
1234
|
+
setActiveRouter(router);
|
|
1235
|
+
setupListeners();
|
|
1236
|
+
const reactiveRoute = createReactiveRouteProxy(currentRoute);
|
|
1237
|
+
if (app && typeof app === "object") {
|
|
1238
|
+
if (typeof app.provide === "function") {
|
|
1239
|
+
app.provide(routerKey, router);
|
|
1240
|
+
app.provide(routerViewLocationKey, currentRoute);
|
|
1241
|
+
app.provide(routeLocationKey, reactiveRoute);
|
|
1242
|
+
}
|
|
1243
|
+
if (typeof app.component === "function") {
|
|
1244
|
+
app.component("RouterLink", RouterLink);
|
|
1245
|
+
app.component("RouterView", RouterView);
|
|
1246
|
+
}
|
|
1247
|
+
if (app.config && app.config.globalProperties) {
|
|
1248
|
+
app.config.globalProperties.$router = router;
|
|
1249
|
+
Object.defineProperty(app.config.globalProperties, "$route", {
|
|
1250
|
+
enumerable: true,
|
|
1251
|
+
configurable: true,
|
|
1252
|
+
get: () => currentRoute.value,
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
if (peekComponentContext()) {
|
|
1257
|
+
provide(routerKey, router);
|
|
1258
|
+
provide(routerViewLocationKey, currentRoute);
|
|
1259
|
+
provide(routeLocationKey, reactiveRoute);
|
|
1260
|
+
}
|
|
1261
|
+
},
|
|
1262
|
+
};
|
|
1263
|
+
|
|
1264
|
+
setActiveRouter(router);
|
|
1265
|
+
setupListeners();
|
|
1266
|
+
return router;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
const reactiveRouteProxies = new WeakMap<
|
|
1270
|
+
Ref<RouteLocationNormalizedLoaded>,
|
|
1271
|
+
RouteLocationNormalizedLoaded
|
|
1272
|
+
>();
|
|
1273
|
+
|
|
1274
|
+
function createReactiveRouteProxy(
|
|
1275
|
+
routeRef: Ref<RouteLocationNormalizedLoaded>,
|
|
1276
|
+
): RouteLocationNormalizedLoaded {
|
|
1277
|
+
const existing = reactiveRouteProxies.get(routeRef);
|
|
1278
|
+
if (existing) return existing;
|
|
1279
|
+
const proxy = new Proxy({} as RouteLocationNormalizedLoaded, {
|
|
1280
|
+
get(_target, prop, receiver) {
|
|
1281
|
+
return Reflect.get(routeRef.value, prop, receiver);
|
|
1282
|
+
},
|
|
1283
|
+
has(_target, prop) {
|
|
1284
|
+
return Reflect.has(routeRef.value, prop);
|
|
1285
|
+
},
|
|
1286
|
+
ownKeys() {
|
|
1287
|
+
return Reflect.ownKeys(routeRef.value);
|
|
1288
|
+
},
|
|
1289
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
1290
|
+
const desc = Reflect.getOwnPropertyDescriptor(routeRef.value, prop);
|
|
1291
|
+
if (desc) return { ...desc, configurable: true };
|
|
1292
|
+
return undefined;
|
|
1293
|
+
},
|
|
1294
|
+
});
|
|
1295
|
+
reactiveRouteProxies.set(routeRef, proxy);
|
|
1296
|
+
return proxy;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
export function useRouter(): Router {
|
|
1300
|
+
if (hasInjectionContext()) {
|
|
1301
|
+
const injected = inject(routerKey);
|
|
1302
|
+
if (injected) return injected;
|
|
1303
|
+
}
|
|
1304
|
+
if (activeRouter) return activeRouter;
|
|
1305
|
+
throw new Error(
|
|
1306
|
+
"useRouter() requires an active Router instance (call createRouter() first)",
|
|
1307
|
+
);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
export function useRoute(): RouteLocationNormalizedLoaded {
|
|
1311
|
+
if (hasInjectionContext()) {
|
|
1312
|
+
const injected = inject(routeLocationKey);
|
|
1313
|
+
if (injected) return injected;
|
|
1314
|
+
}
|
|
1315
|
+
const router = useRouter();
|
|
1316
|
+
return createReactiveRouteProxy(router.currentRoute);
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
export function onBeforeRouteLeave(leaveGuard: NavigationGuard): void {
|
|
1320
|
+
const router = useRouter();
|
|
1321
|
+
const current = untrack(() => router.currentRoute.value);
|
|
1322
|
+
const leaf = current.matched[current.matched.length - 1];
|
|
1323
|
+
if (leaf) {
|
|
1324
|
+
leaf.leaveGuards.add(leaveGuard);
|
|
1325
|
+
if (getOwner()) {
|
|
1326
|
+
onCleanup(() => {
|
|
1327
|
+
leaf.leaveGuards.delete(leaveGuard);
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
const remove = router.beforeEach((to, from, next) => {
|
|
1333
|
+
if (to.path !== from.path) {
|
|
1334
|
+
return leaveGuard(to, from, next);
|
|
1335
|
+
}
|
|
1336
|
+
next();
|
|
1337
|
+
});
|
|
1338
|
+
if (getOwner()) {
|
|
1339
|
+
onCleanup(remove);
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
export function onBeforeRouteUpdate(updateGuard: NavigationGuard): void {
|
|
1344
|
+
const router = useRouter();
|
|
1345
|
+
const current = untrack(() => router.currentRoute.value);
|
|
1346
|
+
const leaf = current.matched[current.matched.length - 1];
|
|
1347
|
+
if (leaf) {
|
|
1348
|
+
leaf.updateGuards.add(updateGuard);
|
|
1349
|
+
if (getOwner()) {
|
|
1350
|
+
onCleanup(() => {
|
|
1351
|
+
leaf.updateGuards.delete(updateGuard);
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
const remove = router.beforeEach((to, from, next) => {
|
|
1357
|
+
if (to.matched.some((r) => from.matched.includes(r))) {
|
|
1358
|
+
return updateGuard(to, from, next);
|
|
1359
|
+
}
|
|
1360
|
+
next();
|
|
1361
|
+
});
|
|
1362
|
+
if (getOwner()) {
|
|
1363
|
+
onCleanup(remove);
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
export interface UseLinkOptions {
|
|
1368
|
+
to: MaybeRef<RouteLocationRaw>;
|
|
1369
|
+
replace?: MaybeRef<boolean | undefined>;
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
export interface UseLinkReturn {
|
|
1373
|
+
route: Readonly<Ref<RouteLocationNormalized & { href: string }>>;
|
|
1374
|
+
href: Readonly<Ref<string>>;
|
|
1375
|
+
isActive: Readonly<Ref<boolean>>;
|
|
1376
|
+
isExactActive: Readonly<Ref<boolean>>;
|
|
1377
|
+
navigate: (e?: MouseEvent) => Promise<void | NavigationFailure>;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
export function useLink(props: UseLinkOptions): UseLinkReturn {
|
|
1381
|
+
const router = useRouter();
|
|
1382
|
+
const currentRoute = router.currentRoute;
|
|
1383
|
+
|
|
1384
|
+
const route = computed(() => router.resolve(unref(props.to)));
|
|
1385
|
+
const href = computed(() => route.value.href);
|
|
1386
|
+
const isExactActive = computed(
|
|
1387
|
+
() => currentRoute.value.fullPath === route.value.fullPath,
|
|
1388
|
+
);
|
|
1389
|
+
const isActive = computed(() => {
|
|
1390
|
+
const currentPath = currentRoute.value.path;
|
|
1391
|
+
const targetPath = route.value.path;
|
|
1392
|
+
if (targetPath === "/") return currentPath === "/";
|
|
1393
|
+
return (
|
|
1394
|
+
currentPath === targetPath || currentPath.startsWith(targetPath + "/")
|
|
1395
|
+
);
|
|
1396
|
+
});
|
|
1397
|
+
|
|
1398
|
+
const navigate = (e?: MouseEvent): Promise<void | NavigationFailure> => {
|
|
1399
|
+
if (e) {
|
|
1400
|
+
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) {
|
|
1401
|
+
return Promise.resolve();
|
|
1402
|
+
}
|
|
1403
|
+
if (e.defaultPrevented) return Promise.resolve();
|
|
1404
|
+
if (e.button !== undefined && e.button !== 0) return Promise.resolve();
|
|
1405
|
+
if (typeof e.preventDefault === "function") e.preventDefault();
|
|
1406
|
+
}
|
|
1407
|
+
const to = unref(props.to);
|
|
1408
|
+
return unref(props.replace) ? router.replace(to) : router.push(to);
|
|
1409
|
+
};
|
|
1410
|
+
|
|
1411
|
+
return {
|
|
1412
|
+
route,
|
|
1413
|
+
href,
|
|
1414
|
+
isActive,
|
|
1415
|
+
isExactActive,
|
|
1416
|
+
navigate,
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
export interface RouterLinkProps {
|
|
1421
|
+
to: RouteLocationRaw;
|
|
1422
|
+
replace?: boolean;
|
|
1423
|
+
activeClass?: string;
|
|
1424
|
+
exactActiveClass?: string;
|
|
1425
|
+
ariaCurrentValue?:
|
|
1426
|
+
"page" | "step" | "location" | "date" | "time" | "true" | "false";
|
|
1427
|
+
custom?: boolean;
|
|
1428
|
+
label?: string;
|
|
1429
|
+
children?: any;
|
|
1430
|
+
[key: string]: any;
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
function isSSRMode(): boolean {
|
|
1434
|
+
const frame = peekComponentContext();
|
|
1435
|
+
return frame?.mode === "ssr" || isSSRRendering();
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
export function RouterLink(props: RouterLinkProps): any {
|
|
1439
|
+
const router = useRouter();
|
|
1440
|
+
const link = useLink({
|
|
1441
|
+
to: computed(() => props.to),
|
|
1442
|
+
replace: computed(() => props.replace),
|
|
1443
|
+
});
|
|
1444
|
+
const frame = peekComponentContext();
|
|
1445
|
+
const slotFactory = getDefaultSlotFactory(props, frame);
|
|
1446
|
+
|
|
1447
|
+
const computeClass = () => {
|
|
1448
|
+
const classes: string[] = [];
|
|
1449
|
+
if (typeof props.class === "string" && props.class) {
|
|
1450
|
+
classes.push(props.class);
|
|
1451
|
+
}
|
|
1452
|
+
const activeCls =
|
|
1453
|
+
props.activeClass ??
|
|
1454
|
+
router.options.linkActiveClass ??
|
|
1455
|
+
"router-link-active";
|
|
1456
|
+
const exactCls =
|
|
1457
|
+
props.exactActiveClass ??
|
|
1458
|
+
router.options.linkExactActiveClass ??
|
|
1459
|
+
"router-link-exact-active";
|
|
1460
|
+
if (link.isActive.value && activeCls) classes.push(activeCls);
|
|
1461
|
+
if (link.isExactActive.value && exactCls) classes.push(exactCls);
|
|
1462
|
+
return classes.join(" ") || undefined;
|
|
1463
|
+
};
|
|
1464
|
+
|
|
1465
|
+
const resolveChildren = () => {
|
|
1466
|
+
if (slotFactory) return slotFactory();
|
|
1467
|
+
if (typeof props.children === "function") return props.children(link);
|
|
1468
|
+
if (props.children !== undefined) return props.children;
|
|
1469
|
+
if (props.label !== undefined) return props.label;
|
|
1470
|
+
return link.href.value;
|
|
1471
|
+
};
|
|
1472
|
+
|
|
1473
|
+
if (props.custom) {
|
|
1474
|
+
return resolveChildren();
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
if (isSSRMode()) {
|
|
1478
|
+
return hSSR(
|
|
1479
|
+
"a",
|
|
1480
|
+
{
|
|
1481
|
+
href: link.href.value,
|
|
1482
|
+
class: computeClass(),
|
|
1483
|
+
"aria-current": link.isExactActive.value
|
|
1484
|
+
? (props.ariaCurrentValue ?? "page")
|
|
1485
|
+
: undefined,
|
|
1486
|
+
},
|
|
1487
|
+
resolveChildren(),
|
|
1488
|
+
);
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
return hDOM(
|
|
1492
|
+
"a",
|
|
1493
|
+
{
|
|
1494
|
+
get href() {
|
|
1495
|
+
return link.href.value;
|
|
1496
|
+
},
|
|
1497
|
+
get class() {
|
|
1498
|
+
return computeClass();
|
|
1499
|
+
},
|
|
1500
|
+
get "aria-current"() {
|
|
1501
|
+
return link.isExactActive.value
|
|
1502
|
+
? (props.ariaCurrentValue ?? "page")
|
|
1503
|
+
: undefined;
|
|
1504
|
+
},
|
|
1505
|
+
onClick: (e: MouseEvent) => {
|
|
1506
|
+
void link.navigate(e);
|
|
1507
|
+
},
|
|
1508
|
+
},
|
|
1509
|
+
resolveChildren(),
|
|
1510
|
+
);
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
export interface RouterViewProps {
|
|
1514
|
+
name?: string;
|
|
1515
|
+
route?: RouteLocationNormalizedLoaded;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
export function RouterView(props: RouterViewProps = {}): any {
|
|
1519
|
+
const router = useRouter();
|
|
1520
|
+
const frame = peekComponentContext();
|
|
1521
|
+
const depth = frame ? (inject(viewDepthKey, 0) ?? 0) : 0;
|
|
1522
|
+
if (frame) {
|
|
1523
|
+
provide(viewDepthKey, depth + 1);
|
|
1524
|
+
provide(routerKey, router);
|
|
1525
|
+
provide(routeLocationKey, createReactiveRouteProxy(router.currentRoute));
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
const viewName = props.name ?? "default";
|
|
1529
|
+
const slotFactory = getDefaultSlotFactory(props, frame);
|
|
1530
|
+
|
|
1531
|
+
const renderMatched = () => {
|
|
1532
|
+
const current = props.route ?? router.currentRoute.value;
|
|
1533
|
+
const matchedRecord = current.matched[depth];
|
|
1534
|
+
if (!matchedRecord) {
|
|
1535
|
+
return slotFactory ? slotFactory() : null;
|
|
1536
|
+
}
|
|
1537
|
+
const ViewComponent = matchedRecord.components[viewName];
|
|
1538
|
+
if (!ViewComponent) {
|
|
1539
|
+
return null;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
const rawPropsOption = matchedRecord.props[viewName];
|
|
1543
|
+
let routeProps: Record<string, any> = {};
|
|
1544
|
+
if (rawPropsOption === true) {
|
|
1545
|
+
routeProps = { ...current.params };
|
|
1546
|
+
} else if (typeof rawPropsOption === "function") {
|
|
1547
|
+
routeProps = rawPropsOption(current) ?? {};
|
|
1548
|
+
} else if (rawPropsOption && typeof rawPropsOption === "object") {
|
|
1549
|
+
routeProps = { ...rawPropsOption };
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
if (isSSRMode()) {
|
|
1553
|
+
return hSSR(ViewComponent, routeProps);
|
|
1554
|
+
}
|
|
1555
|
+
return hDOM(ViewComponent, routeProps);
|
|
1556
|
+
};
|
|
1557
|
+
|
|
1558
|
+
if (isSSRMode()) {
|
|
1559
|
+
return renderMatched();
|
|
1560
|
+
}
|
|
1561
|
+
return () => renderMatched();
|
|
1562
|
+
}
|