kdu-router 3.4.0-beta.0 → 4.0.0
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/LICENSE +2 -2
- package/README.md +8 -6
- package/dist/kdu-router.cjs.js +2848 -0
- package/dist/kdu-router.cjs.prod.js +2610 -0
- package/dist/kdu-router.d.ts +1255 -0
- package/dist/kdu-router.esm-browser.js +3332 -0
- package/dist/kdu-router.esm-bundler.js +3343 -0
- package/dist/kdu-router.global.js +3354 -0
- package/dist/kdu-router.global.prod.js +6 -0
- package/ketur/attributes.json +8 -14
- package/ketur/tags.json +2 -12
- package/package.json +64 -92
- package/dist/kdu-router.common.js +0 -3040
- package/dist/kdu-router.esm.browser.js +0 -3005
- package/dist/kdu-router.esm.browser.min.js +0 -11
- package/dist/kdu-router.esm.js +0 -3038
- package/dist/kdu-router.js +0 -3046
- package/dist/kdu-router.min.js +0 -11
- package/src/components/link.js +0 -197
- package/src/components/view.js +0 -149
- package/src/create-matcher.js +0 -200
- package/src/create-route-map.js +0 -205
- package/src/history/abstract.js +0 -68
- package/src/history/base.js +0 -400
- package/src/history/hash.js +0 -163
- package/src/history/html5.js +0 -94
- package/src/index.js +0 -277
- package/src/install.js +0 -52
- package/src/util/async.js +0 -18
- package/src/util/dom.js +0 -3
- package/src/util/errors.js +0 -85
- package/src/util/location.js +0 -69
- package/src/util/misc.js +0 -6
- package/src/util/params.js +0 -37
- package/src/util/path.js +0 -74
- package/src/util/push-state.js +0 -46
- package/src/util/query.js +0 -96
- package/src/util/resolve-components.js +0 -109
- package/src/util/route.js +0 -132
- package/src/util/scroll.js +0 -165
- package/src/util/state-key.js +0 -22
- package/src/util/warn.js +0 -14
- package/types/index.d.ts +0 -17
- package/types/kdu.d.ts +0 -22
- package/types/router.d.ts +0 -170
|
@@ -0,0 +1,3332 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* kdu-router v4.0.0
|
|
3
|
+
* (c) 2021 NKDuy
|
|
4
|
+
* @license MIT
|
|
5
|
+
*/
|
|
6
|
+
import { getCurrentInstance, inject, onUnmounted, onDeactivated, onActivated, computed, unref, defineComponent, reactive, h, provide, ref, watch, shallowRef, nextTick } from 'kdu';
|
|
7
|
+
|
|
8
|
+
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
|
|
9
|
+
const PolySymbol = (name) =>
|
|
10
|
+
// kr = kdu router
|
|
11
|
+
hasSymbol
|
|
12
|
+
? Symbol( '[kdu-router]: ' + name )
|
|
13
|
+
: ( '[kdu-router]: ' ) + name;
|
|
14
|
+
// rvlm = Router View Location Matched
|
|
15
|
+
/**
|
|
16
|
+
* RouteRecord being rendered by the closest ancestor Router View. Used for
|
|
17
|
+
* `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View
|
|
18
|
+
* Location Matched
|
|
19
|
+
*
|
|
20
|
+
* @internal
|
|
21
|
+
*/
|
|
22
|
+
const matchedRouteKey = /*#__PURE__*/ PolySymbol( 'router view location matched' );
|
|
23
|
+
/**
|
|
24
|
+
* Allows overriding the router view depth to control which component in
|
|
25
|
+
* `matched` is rendered. rvd stands for Router View Depth
|
|
26
|
+
*
|
|
27
|
+
* @internal
|
|
28
|
+
*/
|
|
29
|
+
const viewDepthKey = /*#__PURE__*/ PolySymbol( 'router view depth' );
|
|
30
|
+
/**
|
|
31
|
+
* Allows overriding the router instance returned by `useRouter` in tests. r
|
|
32
|
+
* stands for router
|
|
33
|
+
*
|
|
34
|
+
* @internal
|
|
35
|
+
*/
|
|
36
|
+
const routerKey = /*#__PURE__*/ PolySymbol( 'router' );
|
|
37
|
+
/**
|
|
38
|
+
* Allows overriding the current route returned by `useRoute` in tests. rl
|
|
39
|
+
* stands for route location
|
|
40
|
+
*
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
const routeLocationKey = /*#__PURE__*/ PolySymbol( 'route location' );
|
|
44
|
+
/**
|
|
45
|
+
* Allows overriding the current route used by router-view. Internally this is
|
|
46
|
+
* used when the `route` prop is passed.
|
|
47
|
+
*
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
const routerViewLocationKey = /*#__PURE__*/ PolySymbol( 'router view location' );
|
|
51
|
+
|
|
52
|
+
const isBrowser = typeof window !== 'undefined';
|
|
53
|
+
|
|
54
|
+
function isESModule(obj) {
|
|
55
|
+
return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module');
|
|
56
|
+
}
|
|
57
|
+
const assign = Object.assign;
|
|
58
|
+
function applyToParams(fn, params) {
|
|
59
|
+
const newParams = {};
|
|
60
|
+
for (const key in params) {
|
|
61
|
+
const value = params[key];
|
|
62
|
+
newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value);
|
|
63
|
+
}
|
|
64
|
+
return newParams;
|
|
65
|
+
}
|
|
66
|
+
let noop = () => { };
|
|
67
|
+
|
|
68
|
+
function warn(msg) {
|
|
69
|
+
// avoid using ...args as it breaks in older Edge builds
|
|
70
|
+
const args = Array.from(arguments).slice(1);
|
|
71
|
+
console.warn.apply(console, ['[Kdu Router warn]: ' + msg].concat(args));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const TRAILING_SLASH_RE = /\/$/;
|
|
75
|
+
const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, '');
|
|
76
|
+
/**
|
|
77
|
+
* Transforms an URI into a normalized history location
|
|
78
|
+
*
|
|
79
|
+
* @param parseQuery
|
|
80
|
+
* @param location - URI to normalize
|
|
81
|
+
* @param currentLocation - current absolute location. Allows resolving relative
|
|
82
|
+
* paths. Must start with `/`. Defaults to `/`
|
|
83
|
+
* @returns a normalized history location
|
|
84
|
+
*/
|
|
85
|
+
function parseURL(parseQuery, location, currentLocation = '/') {
|
|
86
|
+
let path, query = {}, searchString = '', hash = '';
|
|
87
|
+
// Could use URL and URLSearchParams but IE 11 doesn't support it
|
|
88
|
+
const searchPos = location.indexOf('?');
|
|
89
|
+
const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0);
|
|
90
|
+
if (searchPos > -1) {
|
|
91
|
+
path = location.slice(0, searchPos);
|
|
92
|
+
searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length);
|
|
93
|
+
query = parseQuery(searchString);
|
|
94
|
+
}
|
|
95
|
+
if (hashPos > -1) {
|
|
96
|
+
path = path || location.slice(0, hashPos);
|
|
97
|
+
// keep the # character
|
|
98
|
+
hash = location.slice(hashPos, location.length);
|
|
99
|
+
}
|
|
100
|
+
// no search and no query
|
|
101
|
+
path = resolveRelativePath(path != null ? path : location, currentLocation);
|
|
102
|
+
// empty path means a relative query or hash `?foo=f`, `#thing`
|
|
103
|
+
return {
|
|
104
|
+
fullPath: path + (searchString && '?') + searchString + hash,
|
|
105
|
+
path,
|
|
106
|
+
query,
|
|
107
|
+
hash,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Stringifies a URL object
|
|
112
|
+
*
|
|
113
|
+
* @param stringifyQuery
|
|
114
|
+
* @param location
|
|
115
|
+
*/
|
|
116
|
+
function stringifyURL(stringifyQuery, location) {
|
|
117
|
+
let query = location.query ? stringifyQuery(location.query) : '';
|
|
118
|
+
return location.path + (query && '?') + query + (location.hash || '');
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Strips off the base from the beginning of a location.pathname in a non
|
|
122
|
+
* case-sensitive way.
|
|
123
|
+
*
|
|
124
|
+
* @param pathname - location.pathname
|
|
125
|
+
* @param base - base to strip off
|
|
126
|
+
*/
|
|
127
|
+
function stripBase(pathname, base) {
|
|
128
|
+
// no base or base is not found at the beginning
|
|
129
|
+
if (!base || pathname.toLowerCase().indexOf(base.toLowerCase()))
|
|
130
|
+
return pathname;
|
|
131
|
+
return pathname.slice(base.length) || '/';
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Checks if two RouteLocation are equal. This means that both locations are
|
|
135
|
+
* pointing towards the same {@link RouteRecord} and that all `params`, `query`
|
|
136
|
+
* parameters and `hash` are the same
|
|
137
|
+
*
|
|
138
|
+
* @param a - first {@link RouteLocation}
|
|
139
|
+
* @param b - second {@link RouteLocation}
|
|
140
|
+
*/
|
|
141
|
+
function isSameRouteLocation(stringifyQuery, a, b) {
|
|
142
|
+
let aLastIndex = a.matched.length - 1;
|
|
143
|
+
let bLastIndex = b.matched.length - 1;
|
|
144
|
+
return (aLastIndex > -1 &&
|
|
145
|
+
aLastIndex === bLastIndex &&
|
|
146
|
+
isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) &&
|
|
147
|
+
isSameRouteLocationParams(a.params, b.params) &&
|
|
148
|
+
stringifyQuery(a.query) === stringifyQuery(b.query) &&
|
|
149
|
+
a.hash === b.hash);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Check if two `RouteRecords` are equal. Takes into account aliases: they are
|
|
153
|
+
* considered equal to the `RouteRecord` they are aliasing.
|
|
154
|
+
*
|
|
155
|
+
* @param a - first {@link RouteRecord}
|
|
156
|
+
* @param b - second {@link RouteRecord}
|
|
157
|
+
*/
|
|
158
|
+
function isSameRouteRecord(a, b) {
|
|
159
|
+
// since the original record has an undefined value for aliasOf
|
|
160
|
+
// but all aliases point to the original record, this will always compare
|
|
161
|
+
// the original record
|
|
162
|
+
return (a.aliasOf || a) === (b.aliasOf || b);
|
|
163
|
+
}
|
|
164
|
+
function isSameRouteLocationParams(a, b) {
|
|
165
|
+
if (Object.keys(a).length !== Object.keys(b).length)
|
|
166
|
+
return false;
|
|
167
|
+
for (let key in a) {
|
|
168
|
+
if (!isSameRouteLocationParamsValue(a[key], b[key]))
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
function isSameRouteLocationParamsValue(a, b) {
|
|
174
|
+
return Array.isArray(a)
|
|
175
|
+
? isEquivalentArray(a, b)
|
|
176
|
+
: Array.isArray(b)
|
|
177
|
+
? isEquivalentArray(b, a)
|
|
178
|
+
: a === b;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Check if two arrays are the same or if an array with one single entry is the
|
|
182
|
+
* same as another primitive value. Used to check query and parameters
|
|
183
|
+
*
|
|
184
|
+
* @param a - array of values
|
|
185
|
+
* @param b - array of values or a single value
|
|
186
|
+
*/
|
|
187
|
+
function isEquivalentArray(a, b) {
|
|
188
|
+
return Array.isArray(b)
|
|
189
|
+
? a.length === b.length && a.every((value, i) => value === b[i])
|
|
190
|
+
: a.length === 1 && a[0] === b;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Resolves a relative path that starts with `.`.
|
|
194
|
+
*
|
|
195
|
+
* @param to - path location we are resolving
|
|
196
|
+
* @param from - currentLocation.path, should start with `/`
|
|
197
|
+
*/
|
|
198
|
+
function resolveRelativePath(to, from) {
|
|
199
|
+
if (to.startsWith('/'))
|
|
200
|
+
return to;
|
|
201
|
+
if ( !from.startsWith('/')) {
|
|
202
|
+
warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`);
|
|
203
|
+
return to;
|
|
204
|
+
}
|
|
205
|
+
if (!to)
|
|
206
|
+
return from;
|
|
207
|
+
const fromSegments = from.split('/');
|
|
208
|
+
const toSegments = to.split('/');
|
|
209
|
+
let position = fromSegments.length - 1;
|
|
210
|
+
let toPosition;
|
|
211
|
+
let segment;
|
|
212
|
+
for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
|
|
213
|
+
segment = toSegments[toPosition];
|
|
214
|
+
// can't go below zero
|
|
215
|
+
if (position === 1 || segment === '.')
|
|
216
|
+
continue;
|
|
217
|
+
if (segment === '..')
|
|
218
|
+
position--;
|
|
219
|
+
// found something that is not relative path
|
|
220
|
+
else
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
return (fromSegments.slice(0, position).join('/') +
|
|
224
|
+
'/' +
|
|
225
|
+
toSegments
|
|
226
|
+
.slice(toPosition - (toPosition === toSegments.length ? 1 : 0))
|
|
227
|
+
.join('/'));
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
var NavigationType;
|
|
231
|
+
(function (NavigationType) {
|
|
232
|
+
NavigationType["pop"] = "pop";
|
|
233
|
+
NavigationType["push"] = "push";
|
|
234
|
+
})(NavigationType || (NavigationType = {}));
|
|
235
|
+
var NavigationDirection;
|
|
236
|
+
(function (NavigationDirection) {
|
|
237
|
+
NavigationDirection["back"] = "back";
|
|
238
|
+
NavigationDirection["forward"] = "forward";
|
|
239
|
+
NavigationDirection["unknown"] = "";
|
|
240
|
+
})(NavigationDirection || (NavigationDirection = {}));
|
|
241
|
+
/**
|
|
242
|
+
* Starting location for Histories
|
|
243
|
+
*/
|
|
244
|
+
const START = '';
|
|
245
|
+
// Generic utils
|
|
246
|
+
/**
|
|
247
|
+
* Normalizes a base by removing any trailing slash and reading the base tag if
|
|
248
|
+
* present.
|
|
249
|
+
*
|
|
250
|
+
* @param base - base to normalize
|
|
251
|
+
*/
|
|
252
|
+
function normalizeBase(base) {
|
|
253
|
+
if (!base) {
|
|
254
|
+
if (isBrowser) {
|
|
255
|
+
// respect <base> tag
|
|
256
|
+
const baseEl = document.querySelector('base');
|
|
257
|
+
base = (baseEl && baseEl.getAttribute('href')) || '/';
|
|
258
|
+
// strip full URL origin
|
|
259
|
+
base = base.replace(/^\w+:\/\/[^\/]+/, '');
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
base = '/';
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
// ensure leading slash when it was removed by the regex above avoid leading
|
|
266
|
+
// slash with hash because the file could be read from the disk like file://
|
|
267
|
+
// and the leading slash would cause problems
|
|
268
|
+
if (base[0] !== '/' && base[0] !== '#')
|
|
269
|
+
base = '/' + base;
|
|
270
|
+
// remove the trailing slash so all other method can just do `base + fullPath`
|
|
271
|
+
// to build an href
|
|
272
|
+
return removeTrailingSlash(base);
|
|
273
|
+
}
|
|
274
|
+
// remove any character before the hash
|
|
275
|
+
const BEFORE_HASH_RE = /^[^#]+#/;
|
|
276
|
+
function createHref(base, location) {
|
|
277
|
+
return base.replace(BEFORE_HASH_RE, '#') + location;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function getElementPosition(el, offset) {
|
|
281
|
+
const docRect = document.documentElement.getBoundingClientRect();
|
|
282
|
+
const elRect = el.getBoundingClientRect();
|
|
283
|
+
return {
|
|
284
|
+
behavior: offset.behavior,
|
|
285
|
+
left: elRect.left - docRect.left - (offset.left || 0),
|
|
286
|
+
top: elRect.top - docRect.top - (offset.top || 0),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
const computeScrollPosition = () => ({
|
|
290
|
+
left: window.pageXOffset,
|
|
291
|
+
top: window.pageYOffset,
|
|
292
|
+
});
|
|
293
|
+
function scrollToPosition(position) {
|
|
294
|
+
let scrollToOptions;
|
|
295
|
+
if ('el' in position) {
|
|
296
|
+
let positionEl = position.el;
|
|
297
|
+
const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#');
|
|
298
|
+
/**
|
|
299
|
+
* `id`s can accept pretty much any characters, including CSS combinators
|
|
300
|
+
* like `>` or `~`. It's still possible to retrieve elements using
|
|
301
|
+
* `document.getElementById('~')` but it needs to be escaped when using
|
|
302
|
+
* `document.querySelector('#\\~')` for it to be valid. The only
|
|
303
|
+
* requirements for `id`s are them to be unique on the page and to not be
|
|
304
|
+
* empty (`id=""`). Because of that, when passing an id selector, it should
|
|
305
|
+
* be properly escaped for it to work with `querySelector`. We could check
|
|
306
|
+
* for the id selector to be simple (no CSS combinators `+ >~`) but that
|
|
307
|
+
* would make things inconsistent since they are valid characters for an
|
|
308
|
+
* `id` but would need to be escaped when using `querySelector`, breaking
|
|
309
|
+
* their usage and ending up in no selector returned. Selectors need to be
|
|
310
|
+
* escaped:
|
|
311
|
+
*
|
|
312
|
+
* - `#1-thing` becomes `#\31 -thing`
|
|
313
|
+
* - `#with~symbols` becomes `#with\\~symbols`
|
|
314
|
+
*
|
|
315
|
+
* - More information about the topic can be found at
|
|
316
|
+
* https://mathiasbynens.be/notes/html5-id-class.
|
|
317
|
+
* - Practical example: https://mathiasbynens.be/demo/html5-id
|
|
318
|
+
*/
|
|
319
|
+
if ( typeof position.el === 'string') {
|
|
320
|
+
if (!isIdSelector || !document.getElementById(position.el.slice(1))) {
|
|
321
|
+
try {
|
|
322
|
+
let foundEl = document.querySelector(position.el);
|
|
323
|
+
if (isIdSelector && foundEl) {
|
|
324
|
+
warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
|
|
325
|
+
// return to avoid other warnings
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
catch (err) {
|
|
330
|
+
warn(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`);
|
|
331
|
+
// return to avoid other warnings
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const el = typeof positionEl === 'string'
|
|
337
|
+
? isIdSelector
|
|
338
|
+
? document.getElementById(positionEl.slice(1))
|
|
339
|
+
: document.querySelector(positionEl)
|
|
340
|
+
: positionEl;
|
|
341
|
+
if (!el) {
|
|
342
|
+
|
|
343
|
+
warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
scrollToOptions = getElementPosition(el, position);
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
scrollToOptions = position;
|
|
350
|
+
}
|
|
351
|
+
if ('scrollBehavior' in document.documentElement.style)
|
|
352
|
+
window.scrollTo(scrollToOptions);
|
|
353
|
+
else {
|
|
354
|
+
window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
function getScrollKey(path, delta) {
|
|
358
|
+
const position = history.state ? history.state.position - delta : -1;
|
|
359
|
+
return position + path;
|
|
360
|
+
}
|
|
361
|
+
const scrollPositions = new Map();
|
|
362
|
+
function saveScrollPosition(key, scrollPosition) {
|
|
363
|
+
scrollPositions.set(key, scrollPosition);
|
|
364
|
+
}
|
|
365
|
+
function getSavedScrollPosition(key) {
|
|
366
|
+
const scroll = scrollPositions.get(key);
|
|
367
|
+
// consume it so it's not used again
|
|
368
|
+
scrollPositions.delete(key);
|
|
369
|
+
return scroll;
|
|
370
|
+
}
|
|
371
|
+
// TODO: RFC about how to save scroll position
|
|
372
|
+
/**
|
|
373
|
+
* ScrollBehavior instance used by the router to compute and restore the scroll
|
|
374
|
+
* position when navigating.
|
|
375
|
+
*/
|
|
376
|
+
// export interface ScrollHandler<ScrollPositionEntry extends HistoryStateValue, ScrollPosition extends ScrollPositionEntry> {
|
|
377
|
+
// // returns a scroll position that can be saved in history
|
|
378
|
+
// compute(): ScrollPositionEntry
|
|
379
|
+
// // can take an extended ScrollPositionEntry
|
|
380
|
+
// scroll(position: ScrollPosition): void
|
|
381
|
+
// }
|
|
382
|
+
// export const scrollHandler: ScrollHandler<ScrollPosition> = {
|
|
383
|
+
// compute: computeScroll,
|
|
384
|
+
// scroll: scrollToPosition,
|
|
385
|
+
// }
|
|
386
|
+
|
|
387
|
+
let createBaseLocation = () => location.protocol + '//' + location.host;
|
|
388
|
+
/**
|
|
389
|
+
* Creates a normalized history location from a window.location object
|
|
390
|
+
* @param location -
|
|
391
|
+
*/
|
|
392
|
+
function createCurrentLocation(base, location) {
|
|
393
|
+
const { pathname, search, hash } = location;
|
|
394
|
+
// allows hash based url
|
|
395
|
+
const hashPos = base.indexOf('#');
|
|
396
|
+
if (hashPos > -1) {
|
|
397
|
+
// prepend the starting slash to hash so the url starts with /#
|
|
398
|
+
let pathFromHash = hash.slice(1);
|
|
399
|
+
if (pathFromHash[0] !== '/')
|
|
400
|
+
pathFromHash = '/' + pathFromHash;
|
|
401
|
+
return stripBase(pathFromHash, '');
|
|
402
|
+
}
|
|
403
|
+
const path = stripBase(pathname, base);
|
|
404
|
+
return path + search + hash;
|
|
405
|
+
}
|
|
406
|
+
function useHistoryListeners(base, historyState, currentLocation, replace) {
|
|
407
|
+
let listeners = [];
|
|
408
|
+
let teardowns = [];
|
|
409
|
+
// TODO: should it be a stack? a Dict. Check if the popstate listener
|
|
410
|
+
// can trigger twice
|
|
411
|
+
let pauseState = null;
|
|
412
|
+
const popStateHandler = ({ state, }) => {
|
|
413
|
+
const to = createCurrentLocation(base, location);
|
|
414
|
+
const from = currentLocation.value;
|
|
415
|
+
const fromState = historyState.value;
|
|
416
|
+
let delta = 0;
|
|
417
|
+
if (state) {
|
|
418
|
+
currentLocation.value = to;
|
|
419
|
+
historyState.value = state;
|
|
420
|
+
// ignore the popstate and reset the pauseState
|
|
421
|
+
if (pauseState && pauseState === from) {
|
|
422
|
+
pauseState = null;
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
delta = fromState ? state.position - fromState.position : 0;
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
replace(to);
|
|
429
|
+
}
|
|
430
|
+
// console.log({ deltaFromCurrent })
|
|
431
|
+
// Here we could also revert the navigation by calling history.go(-delta)
|
|
432
|
+
// this listener will have to be adapted to not trigger again and to wait for the url
|
|
433
|
+
// to be updated before triggering the listeners. Some kind of validation function would also
|
|
434
|
+
// need to be passed to the listeners so the navigation can be accepted
|
|
435
|
+
// call all listeners
|
|
436
|
+
listeners.forEach(listener => {
|
|
437
|
+
listener(currentLocation.value, from, {
|
|
438
|
+
delta,
|
|
439
|
+
type: NavigationType.pop,
|
|
440
|
+
direction: delta
|
|
441
|
+
? delta > 0
|
|
442
|
+
? NavigationDirection.forward
|
|
443
|
+
: NavigationDirection.back
|
|
444
|
+
: NavigationDirection.unknown,
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
};
|
|
448
|
+
function pauseListeners() {
|
|
449
|
+
pauseState = currentLocation.value;
|
|
450
|
+
}
|
|
451
|
+
function listen(callback) {
|
|
452
|
+
// setup the listener and prepare teardown callbacks
|
|
453
|
+
listeners.push(callback);
|
|
454
|
+
const teardown = () => {
|
|
455
|
+
const index = listeners.indexOf(callback);
|
|
456
|
+
if (index > -1)
|
|
457
|
+
listeners.splice(index, 1);
|
|
458
|
+
};
|
|
459
|
+
teardowns.push(teardown);
|
|
460
|
+
return teardown;
|
|
461
|
+
}
|
|
462
|
+
function beforeUnloadListener() {
|
|
463
|
+
const { history } = window;
|
|
464
|
+
if (!history.state)
|
|
465
|
+
return;
|
|
466
|
+
history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), '');
|
|
467
|
+
}
|
|
468
|
+
function destroy() {
|
|
469
|
+
for (const teardown of teardowns)
|
|
470
|
+
teardown();
|
|
471
|
+
teardowns = [];
|
|
472
|
+
window.removeEventListener('popstate', popStateHandler);
|
|
473
|
+
window.removeEventListener('beforeunload', beforeUnloadListener);
|
|
474
|
+
}
|
|
475
|
+
// setup the listeners and prepare teardown callbacks
|
|
476
|
+
window.addEventListener('popstate', popStateHandler);
|
|
477
|
+
window.addEventListener('beforeunload', beforeUnloadListener);
|
|
478
|
+
return {
|
|
479
|
+
pauseListeners,
|
|
480
|
+
listen,
|
|
481
|
+
destroy,
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Creates a state object
|
|
486
|
+
*/
|
|
487
|
+
function buildState(back, current, forward, replaced = false, computeScroll = false) {
|
|
488
|
+
return {
|
|
489
|
+
back,
|
|
490
|
+
current,
|
|
491
|
+
forward,
|
|
492
|
+
replaced,
|
|
493
|
+
position: window.history.length,
|
|
494
|
+
scroll: computeScroll ? computeScrollPosition() : null,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function useHistoryStateNavigation(base) {
|
|
498
|
+
const { history, location } = window;
|
|
499
|
+
// private variables
|
|
500
|
+
let currentLocation = {
|
|
501
|
+
value: createCurrentLocation(base, location),
|
|
502
|
+
};
|
|
503
|
+
let historyState = { value: history.state };
|
|
504
|
+
// build current history entry as this is a fresh navigation
|
|
505
|
+
if (!historyState.value) {
|
|
506
|
+
changeLocation(currentLocation.value, {
|
|
507
|
+
back: null,
|
|
508
|
+
current: currentLocation.value,
|
|
509
|
+
forward: null,
|
|
510
|
+
// the length is off by one, we need to decrease it
|
|
511
|
+
position: history.length - 1,
|
|
512
|
+
replaced: true,
|
|
513
|
+
// don't add a scroll as the user may have an anchor and we want
|
|
514
|
+
// scrollBehavior to be triggered without a saved position
|
|
515
|
+
scroll: null,
|
|
516
|
+
}, true);
|
|
517
|
+
}
|
|
518
|
+
function changeLocation(to, state, replace) {
|
|
519
|
+
// when the base has a `#`, only use that for the URL
|
|
520
|
+
const hashIndex = base.indexOf('#');
|
|
521
|
+
const url = hashIndex > -1
|
|
522
|
+
? base.slice(hashIndex) + to
|
|
523
|
+
: createBaseLocation() + base + to;
|
|
524
|
+
try {
|
|
525
|
+
// BROWSER QUIRK
|
|
526
|
+
// NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds
|
|
527
|
+
history[replace ? 'replaceState' : 'pushState'](state, '', url);
|
|
528
|
+
historyState.value = state;
|
|
529
|
+
}
|
|
530
|
+
catch (err) {
|
|
531
|
+
{
|
|
532
|
+
warn('Error with push/replace State', err);
|
|
533
|
+
}
|
|
534
|
+
// Force the navigation, this also resets the call count
|
|
535
|
+
location[replace ? 'replace' : 'assign'](url);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
function replace(to, data) {
|
|
539
|
+
const state = assign({}, history.state, buildState(historyState.value.back,
|
|
540
|
+
// keep back and forward entries but override current position
|
|
541
|
+
to, historyState.value.forward, true), data, { position: historyState.value.position });
|
|
542
|
+
changeLocation(to, state, true);
|
|
543
|
+
currentLocation.value = to;
|
|
544
|
+
}
|
|
545
|
+
function push(to, data) {
|
|
546
|
+
// Add to current entry the information of where we are going
|
|
547
|
+
// as well as saving the current position
|
|
548
|
+
const currentState = assign({},
|
|
549
|
+
// use current history state to gracefully handle a wrong call to
|
|
550
|
+
// history.replaceState
|
|
551
|
+
historyState.value, history.state, {
|
|
552
|
+
forward: to,
|
|
553
|
+
scroll: computeScrollPosition(),
|
|
554
|
+
});
|
|
555
|
+
if ( !history.state) {
|
|
556
|
+
warn(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\n` +
|
|
557
|
+
`history.replaceState(history.state, '', url)\n\n` +
|
|
558
|
+
`You can find more information at https://kdujs-router.web.app/guide/migration/#usage-of-history-state.`);
|
|
559
|
+
}
|
|
560
|
+
changeLocation(currentState.current, currentState, true);
|
|
561
|
+
const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data);
|
|
562
|
+
changeLocation(to, state, false);
|
|
563
|
+
currentLocation.value = to;
|
|
564
|
+
}
|
|
565
|
+
return {
|
|
566
|
+
location: currentLocation,
|
|
567
|
+
state: historyState,
|
|
568
|
+
push,
|
|
569
|
+
replace,
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Creates an HTML5 history. Most common history for single page applications.
|
|
574
|
+
*
|
|
575
|
+
* @param base -
|
|
576
|
+
*/
|
|
577
|
+
function createWebHistory(base) {
|
|
578
|
+
base = normalizeBase(base);
|
|
579
|
+
const historyNavigation = useHistoryStateNavigation(base);
|
|
580
|
+
const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
|
|
581
|
+
function go(delta, triggerListeners = true) {
|
|
582
|
+
if (!triggerListeners)
|
|
583
|
+
historyListeners.pauseListeners();
|
|
584
|
+
history.go(delta);
|
|
585
|
+
}
|
|
586
|
+
const routerHistory = assign({
|
|
587
|
+
// it's overridden right after
|
|
588
|
+
location: '',
|
|
589
|
+
base,
|
|
590
|
+
go,
|
|
591
|
+
createHref: createHref.bind(null, base),
|
|
592
|
+
}, historyNavigation, historyListeners);
|
|
593
|
+
Object.defineProperty(routerHistory, 'location', {
|
|
594
|
+
get: () => historyNavigation.location.value,
|
|
595
|
+
});
|
|
596
|
+
Object.defineProperty(routerHistory, 'state', {
|
|
597
|
+
get: () => historyNavigation.state.value,
|
|
598
|
+
});
|
|
599
|
+
return routerHistory;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere.
|
|
604
|
+
* It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`.
|
|
605
|
+
*
|
|
606
|
+
* @param base - Base applied to all urls, defaults to '/'
|
|
607
|
+
* @returns a history object that can be passed to the router constructor
|
|
608
|
+
*/
|
|
609
|
+
function createMemoryHistory(base = '') {
|
|
610
|
+
let listeners = [];
|
|
611
|
+
let queue = [START];
|
|
612
|
+
let position = 0;
|
|
613
|
+
function setLocation(location) {
|
|
614
|
+
position++;
|
|
615
|
+
if (position === queue.length) {
|
|
616
|
+
// we are at the end, we can simply append a new entry
|
|
617
|
+
queue.push(location);
|
|
618
|
+
}
|
|
619
|
+
else {
|
|
620
|
+
// we are in the middle, we remove everything from here in the queue
|
|
621
|
+
queue.splice(position);
|
|
622
|
+
queue.push(location);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
function triggerListeners(to, from, { direction, delta }) {
|
|
626
|
+
const info = {
|
|
627
|
+
direction,
|
|
628
|
+
delta,
|
|
629
|
+
type: NavigationType.pop,
|
|
630
|
+
};
|
|
631
|
+
for (let callback of listeners) {
|
|
632
|
+
callback(to, from, info);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
const routerHistory = {
|
|
636
|
+
// rewritten by Object.defineProperty
|
|
637
|
+
location: START,
|
|
638
|
+
state: {},
|
|
639
|
+
base,
|
|
640
|
+
createHref: createHref.bind(null, base),
|
|
641
|
+
replace(to) {
|
|
642
|
+
// remove current entry and decrement position
|
|
643
|
+
queue.splice(position--, 1);
|
|
644
|
+
setLocation(to);
|
|
645
|
+
},
|
|
646
|
+
push(to, data) {
|
|
647
|
+
setLocation(to);
|
|
648
|
+
},
|
|
649
|
+
listen(callback) {
|
|
650
|
+
listeners.push(callback);
|
|
651
|
+
return () => {
|
|
652
|
+
const index = listeners.indexOf(callback);
|
|
653
|
+
if (index > -1)
|
|
654
|
+
listeners.splice(index, 1);
|
|
655
|
+
};
|
|
656
|
+
},
|
|
657
|
+
destroy() {
|
|
658
|
+
listeners = [];
|
|
659
|
+
},
|
|
660
|
+
go(delta, shouldTrigger = true) {
|
|
661
|
+
const from = this.location;
|
|
662
|
+
const direction =
|
|
663
|
+
// we are considering delta === 0 going forward, but in abstract mode
|
|
664
|
+
// using 0 for the delta doesn't make sense like it does in html5 where
|
|
665
|
+
// it reloads the page
|
|
666
|
+
delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
|
|
667
|
+
position = Math.max(0, Math.min(position + delta, queue.length - 1));
|
|
668
|
+
if (shouldTrigger) {
|
|
669
|
+
triggerListeners(this.location, from, {
|
|
670
|
+
direction,
|
|
671
|
+
delta,
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
},
|
|
675
|
+
};
|
|
676
|
+
Object.defineProperty(routerHistory, 'location', {
|
|
677
|
+
get: () => queue[position],
|
|
678
|
+
});
|
|
679
|
+
return routerHistory;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* Creates a hash history. Useful for web applications with no host (e.g.
|
|
684
|
+
* `file://`) or when configuring a server to handle any URL.
|
|
685
|
+
*
|
|
686
|
+
* @param base - optional base to provide. Defaults to `location.pathname` or
|
|
687
|
+
* `/` if at root. If there is a `base` tag in the `head`, its value will be
|
|
688
|
+
* **ignored**.
|
|
689
|
+
*
|
|
690
|
+
* @example
|
|
691
|
+
* ```js
|
|
692
|
+
* // at https://example.com/folder
|
|
693
|
+
* createWebHashHistory() // gives a url of `https://example.com/folder#`
|
|
694
|
+
* createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
|
|
695
|
+
* // if the `#` is provided in the base, it won't be added by `createWebHashHistory`
|
|
696
|
+
* createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
|
|
697
|
+
* // you should avoid doing this because it changes the original url and breaks copying urls
|
|
698
|
+
* createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
|
|
699
|
+
*
|
|
700
|
+
* // at file:///usr/etc/folder/index.html
|
|
701
|
+
* // for locations with no `host`, the base is ignored
|
|
702
|
+
* createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
|
|
703
|
+
* ```
|
|
704
|
+
*/
|
|
705
|
+
function createWebHashHistory(base) {
|
|
706
|
+
// Make sure this implementation is fine in terms of encoding, specially for IE11
|
|
707
|
+
// for `file://`, directly use the pathname and ignore the base
|
|
708
|
+
// location.pathname contains an initial `/` even at the root: `https://example.com`
|
|
709
|
+
base = location.host ? base || location.pathname : '';
|
|
710
|
+
// allow the user to provide a `#` in the middle: `/base/#/app`
|
|
711
|
+
if (base.indexOf('#') < 0)
|
|
712
|
+
base += '#';
|
|
713
|
+
if ( !base.endsWith('#/') && !base.endsWith('#')) {
|
|
714
|
+
warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`);
|
|
715
|
+
}
|
|
716
|
+
return createWebHistory(base);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function isRouteLocation(route) {
|
|
720
|
+
return typeof route === 'string' || (route && typeof route === 'object');
|
|
721
|
+
}
|
|
722
|
+
function isRouteName(name) {
|
|
723
|
+
return typeof name === 'string' || typeof name === 'symbol';
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Initial route location where the router is. Can be used in navigation guards
|
|
728
|
+
* to differentiate the initial navigation.
|
|
729
|
+
*
|
|
730
|
+
* @example
|
|
731
|
+
* ```js
|
|
732
|
+
* import { START_LOCATION } from 'kdu-router'
|
|
733
|
+
*
|
|
734
|
+
* router.beforeEach((to, from) => {
|
|
735
|
+
* if (from === START_LOCATION) {
|
|
736
|
+
* // initial navigation
|
|
737
|
+
* }
|
|
738
|
+
* })
|
|
739
|
+
* ```
|
|
740
|
+
*/
|
|
741
|
+
const START_LOCATION_NORMALIZED = {
|
|
742
|
+
path: '/',
|
|
743
|
+
name: undefined,
|
|
744
|
+
params: {},
|
|
745
|
+
query: {},
|
|
746
|
+
hash: '',
|
|
747
|
+
fullPath: '/',
|
|
748
|
+
matched: [],
|
|
749
|
+
meta: {},
|
|
750
|
+
redirectedFrom: undefined,
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol( 'navigation failure' );
|
|
754
|
+
/**
|
|
755
|
+
* Enumeration with all possible types for navigation failures. Can be passed to
|
|
756
|
+
* {@link isNavigationFailure} to check for specific failures.
|
|
757
|
+
*/
|
|
758
|
+
var NavigationFailureType;
|
|
759
|
+
(function (NavigationFailureType) {
|
|
760
|
+
/**
|
|
761
|
+
* An aborted navigation is a navigation that failed because a navigation
|
|
762
|
+
* guard returned `false` or called `next(false)`
|
|
763
|
+
*/
|
|
764
|
+
NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted";
|
|
765
|
+
/**
|
|
766
|
+
* A cancelled navigation is a navigation that failed because a more recent
|
|
767
|
+
* navigation finished started (not necessarily finished).
|
|
768
|
+
*/
|
|
769
|
+
NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled";
|
|
770
|
+
/**
|
|
771
|
+
* A duplicated navigation is a navigation that failed because it was
|
|
772
|
+
* initiated while already being at the exact same location.
|
|
773
|
+
*/
|
|
774
|
+
NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated";
|
|
775
|
+
})(NavigationFailureType || (NavigationFailureType = {}));
|
|
776
|
+
// DEV only debug messages
|
|
777
|
+
const ErrorTypeMessages = {
|
|
778
|
+
[1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) {
|
|
779
|
+
return `No match for\n ${JSON.stringify(location)}${currentLocation
|
|
780
|
+
? '\nwhile being at\n' + JSON.stringify(currentLocation)
|
|
781
|
+
: ''}`;
|
|
782
|
+
},
|
|
783
|
+
[2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) {
|
|
784
|
+
return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
|
|
785
|
+
},
|
|
786
|
+
[4 /* NAVIGATION_ABORTED */]({ from, to }) {
|
|
787
|
+
return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`;
|
|
788
|
+
},
|
|
789
|
+
[8 /* NAVIGATION_CANCELLED */]({ from, to }) {
|
|
790
|
+
return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`;
|
|
791
|
+
},
|
|
792
|
+
[16 /* NAVIGATION_DUPLICATED */]({ from, to }) {
|
|
793
|
+
return `Avoided redundant navigation to current location: "${from.fullPath}".`;
|
|
794
|
+
},
|
|
795
|
+
};
|
|
796
|
+
function createRouterError(type, params) {
|
|
797
|
+
{
|
|
798
|
+
return assign(new Error(ErrorTypeMessages[type](params)), {
|
|
799
|
+
type,
|
|
800
|
+
[NavigationFailureSymbol]: true,
|
|
801
|
+
}, params);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
function isNavigationFailure(error, type) {
|
|
805
|
+
return (error instanceof Error &&
|
|
806
|
+
NavigationFailureSymbol in error &&
|
|
807
|
+
(type == null || !!(error.type & type)));
|
|
808
|
+
}
|
|
809
|
+
const propertiesToLog = ['params', 'query', 'hash'];
|
|
810
|
+
function stringifyRoute(to) {
|
|
811
|
+
if (typeof to === 'string')
|
|
812
|
+
return to;
|
|
813
|
+
if ('path' in to)
|
|
814
|
+
return to.path;
|
|
815
|
+
const location = {};
|
|
816
|
+
for (const key of propertiesToLog) {
|
|
817
|
+
if (key in to)
|
|
818
|
+
location[key] = to[key];
|
|
819
|
+
}
|
|
820
|
+
return JSON.stringify(location, null, 2);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// default pattern for a param: non greedy everything but /
|
|
824
|
+
const BASE_PARAM_PATTERN = '[^/]+?';
|
|
825
|
+
const BASE_PATH_PARSER_OPTIONS = {
|
|
826
|
+
sensitive: false,
|
|
827
|
+
strict: false,
|
|
828
|
+
start: true,
|
|
829
|
+
end: true,
|
|
830
|
+
};
|
|
831
|
+
// Special Regex characters that must be escaped in static tokens
|
|
832
|
+
const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
|
|
833
|
+
/**
|
|
834
|
+
* Creates a path parser from an array of Segments (a segment is an array of Tokens)
|
|
835
|
+
*
|
|
836
|
+
* @param segments - array of segments returned by tokenizePath
|
|
837
|
+
* @param extraOptions - optional options for the regexp
|
|
838
|
+
* @returns a PathParser
|
|
839
|
+
*/
|
|
840
|
+
function tokensToParser(segments, extraOptions) {
|
|
841
|
+
const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
|
|
842
|
+
// the amount of scores is the same as the length of segments except for the root segment "/"
|
|
843
|
+
let score = [];
|
|
844
|
+
// the regexp as a string
|
|
845
|
+
let pattern = options.start ? '^' : '';
|
|
846
|
+
// extracted keys
|
|
847
|
+
const keys = [];
|
|
848
|
+
for (const segment of segments) {
|
|
849
|
+
// the root segment needs special treatment
|
|
850
|
+
const segmentScores = segment.length ? [] : [90 /* Root */];
|
|
851
|
+
// allow trailing slash
|
|
852
|
+
if (options.strict && !segment.length)
|
|
853
|
+
pattern += '/';
|
|
854
|
+
for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
|
|
855
|
+
const token = segment[tokenIndex];
|
|
856
|
+
// resets the score if we are inside a sub segment /:a-other-:b
|
|
857
|
+
let subSegmentScore = 40 /* Segment */ +
|
|
858
|
+
(options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0);
|
|
859
|
+
if (token.type === 0 /* Static */) {
|
|
860
|
+
// prepend the slash if we are starting a new segment
|
|
861
|
+
if (!tokenIndex)
|
|
862
|
+
pattern += '/';
|
|
863
|
+
pattern += token.value.replace(REGEX_CHARS_RE, '\\$&');
|
|
864
|
+
subSegmentScore += 40 /* Static */;
|
|
865
|
+
}
|
|
866
|
+
else if (token.type === 1 /* Param */) {
|
|
867
|
+
const { value, repeatable, optional, regexp } = token;
|
|
868
|
+
keys.push({
|
|
869
|
+
name: value,
|
|
870
|
+
repeatable,
|
|
871
|
+
optional,
|
|
872
|
+
});
|
|
873
|
+
const re = regexp ? regexp : BASE_PARAM_PATTERN;
|
|
874
|
+
// the user provided a custom regexp /:id(\\d+)
|
|
875
|
+
if (re !== BASE_PARAM_PATTERN) {
|
|
876
|
+
subSegmentScore += 10 /* BonusCustomRegExp */;
|
|
877
|
+
// make sure the regexp is valid before using it
|
|
878
|
+
try {
|
|
879
|
+
new RegExp(`(${re})`);
|
|
880
|
+
}
|
|
881
|
+
catch (err) {
|
|
882
|
+
throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` +
|
|
883
|
+
err.message);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
// when we repeat we must take care of the repeating leading slash
|
|
887
|
+
let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`;
|
|
888
|
+
// prepend the slash if we are starting a new segment
|
|
889
|
+
if (!tokenIndex)
|
|
890
|
+
subPattern = optional ? `(?:/${subPattern})` : '/' + subPattern;
|
|
891
|
+
if (optional)
|
|
892
|
+
subPattern += '?';
|
|
893
|
+
pattern += subPattern;
|
|
894
|
+
subSegmentScore += 20 /* Dynamic */;
|
|
895
|
+
if (optional)
|
|
896
|
+
subSegmentScore += -8 /* BonusOptional */;
|
|
897
|
+
if (repeatable)
|
|
898
|
+
subSegmentScore += -20 /* BonusRepeatable */;
|
|
899
|
+
if (re === '.*')
|
|
900
|
+
subSegmentScore += -50 /* BonusWildcard */;
|
|
901
|
+
}
|
|
902
|
+
segmentScores.push(subSegmentScore);
|
|
903
|
+
}
|
|
904
|
+
// an empty array like /home/ -> [[{home}], []]
|
|
905
|
+
// if (!segment.length) pattern += '/'
|
|
906
|
+
score.push(segmentScores);
|
|
907
|
+
}
|
|
908
|
+
// only apply the strict bonus to the last score
|
|
909
|
+
if (options.strict && options.end) {
|
|
910
|
+
const i = score.length - 1;
|
|
911
|
+
score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */;
|
|
912
|
+
}
|
|
913
|
+
// TODO: dev only warn double trailing slash
|
|
914
|
+
if (!options.strict)
|
|
915
|
+
pattern += '/?';
|
|
916
|
+
if (options.end)
|
|
917
|
+
pattern += '$';
|
|
918
|
+
// allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else
|
|
919
|
+
else if (options.strict)
|
|
920
|
+
pattern += '(?:/|$)';
|
|
921
|
+
const re = new RegExp(pattern, options.sensitive ? '' : 'i');
|
|
922
|
+
function parse(path) {
|
|
923
|
+
const match = path.match(re);
|
|
924
|
+
const params = {};
|
|
925
|
+
if (!match)
|
|
926
|
+
return null;
|
|
927
|
+
for (let i = 1; i < match.length; i++) {
|
|
928
|
+
const value = match[i] || '';
|
|
929
|
+
const key = keys[i - 1];
|
|
930
|
+
params[key.name] = value && key.repeatable ? value.split('/') : value;
|
|
931
|
+
}
|
|
932
|
+
return params;
|
|
933
|
+
}
|
|
934
|
+
function stringify(params) {
|
|
935
|
+
let path = '';
|
|
936
|
+
// for optional parameters to allow to be empty
|
|
937
|
+
let avoidDuplicatedSlash = false;
|
|
938
|
+
for (const segment of segments) {
|
|
939
|
+
if (!avoidDuplicatedSlash || !path.endsWith('/'))
|
|
940
|
+
path += '/';
|
|
941
|
+
avoidDuplicatedSlash = false;
|
|
942
|
+
for (const token of segment) {
|
|
943
|
+
if (token.type === 0 /* Static */) {
|
|
944
|
+
path += token.value;
|
|
945
|
+
}
|
|
946
|
+
else if (token.type === 1 /* Param */) {
|
|
947
|
+
const { value, repeatable, optional } = token;
|
|
948
|
+
const param = value in params ? params[value] : '';
|
|
949
|
+
if (Array.isArray(param) && !repeatable)
|
|
950
|
+
throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
|
|
951
|
+
const text = Array.isArray(param) ? param.join('/') : param;
|
|
952
|
+
if (!text) {
|
|
953
|
+
if (optional) {
|
|
954
|
+
// remove the last slash as we could be at the end
|
|
955
|
+
if (path.endsWith('/'))
|
|
956
|
+
path = path.slice(0, -1);
|
|
957
|
+
// do not append a slash on the next iteration
|
|
958
|
+
else
|
|
959
|
+
avoidDuplicatedSlash = true;
|
|
960
|
+
}
|
|
961
|
+
else
|
|
962
|
+
throw new Error(`Missing required param "${value}"`);
|
|
963
|
+
}
|
|
964
|
+
path += text;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return path;
|
|
969
|
+
}
|
|
970
|
+
return {
|
|
971
|
+
re,
|
|
972
|
+
score,
|
|
973
|
+
keys,
|
|
974
|
+
parse,
|
|
975
|
+
stringify,
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Compares an array of numbers as used in PathParser.score and returns a
|
|
980
|
+
* number. This function can be used to `sort` an array
|
|
981
|
+
* @param a - first array of numbers
|
|
982
|
+
* @param b - second array of numbers
|
|
983
|
+
* @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
|
|
984
|
+
* should be sorted first
|
|
985
|
+
*/
|
|
986
|
+
function compareScoreArray(a, b) {
|
|
987
|
+
let i = 0;
|
|
988
|
+
while (i < a.length && i < b.length) {
|
|
989
|
+
const diff = b[i] - a[i];
|
|
990
|
+
// only keep going if diff === 0
|
|
991
|
+
if (diff)
|
|
992
|
+
return diff;
|
|
993
|
+
i++;
|
|
994
|
+
}
|
|
995
|
+
// if the last subsegment was Static, the shorter segments should be sorted first
|
|
996
|
+
// otherwise sort the longest segment first
|
|
997
|
+
if (a.length < b.length) {
|
|
998
|
+
return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */
|
|
999
|
+
? -1
|
|
1000
|
+
: 1;
|
|
1001
|
+
}
|
|
1002
|
+
else if (a.length > b.length) {
|
|
1003
|
+
return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */
|
|
1004
|
+
? 1
|
|
1005
|
+
: -1;
|
|
1006
|
+
}
|
|
1007
|
+
return 0;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Compare function that can be used with `sort` to sort an array of PathParser
|
|
1011
|
+
* @param a - first PathParser
|
|
1012
|
+
* @param b - second PathParser
|
|
1013
|
+
* @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
|
|
1014
|
+
*/
|
|
1015
|
+
function comparePathParserScore(a, b) {
|
|
1016
|
+
let i = 0;
|
|
1017
|
+
const aScore = a.score;
|
|
1018
|
+
const bScore = b.score;
|
|
1019
|
+
while (i < aScore.length && i < bScore.length) {
|
|
1020
|
+
const comp = compareScoreArray(aScore[i], bScore[i]);
|
|
1021
|
+
// do not return if both are equal
|
|
1022
|
+
if (comp)
|
|
1023
|
+
return comp;
|
|
1024
|
+
i++;
|
|
1025
|
+
}
|
|
1026
|
+
// if a and b share the same score entries but b has more, sort b first
|
|
1027
|
+
return bScore.length - aScore.length;
|
|
1028
|
+
// this is the ternary version
|
|
1029
|
+
// return aScore.length < bScore.length
|
|
1030
|
+
// ? 1
|
|
1031
|
+
// : aScore.length > bScore.length
|
|
1032
|
+
// ? -1
|
|
1033
|
+
// : 0
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
const ROOT_TOKEN = {
|
|
1037
|
+
type: 0 /* Static */,
|
|
1038
|
+
value: '',
|
|
1039
|
+
};
|
|
1040
|
+
const VALID_PARAM_RE = /[a-zA-Z0-9_]/;
|
|
1041
|
+
// After some profiling, the cache seems to be unnecessary because tokenizePath
|
|
1042
|
+
// (the slowest part of adding a route) is very fast
|
|
1043
|
+
// const tokenCache = new Map<string, Token[][]>()
|
|
1044
|
+
function tokenizePath(path) {
|
|
1045
|
+
if (!path)
|
|
1046
|
+
return [[]];
|
|
1047
|
+
if (path === '/')
|
|
1048
|
+
return [[ROOT_TOKEN]];
|
|
1049
|
+
if (!path.startsWith('/')) {
|
|
1050
|
+
throw new Error( `Route paths should start with a "/": "${path}" should be "/${path}".`
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
1053
|
+
// if (tokenCache.has(path)) return tokenCache.get(path)!
|
|
1054
|
+
function crash(message) {
|
|
1055
|
+
throw new Error(`ERR (${state})/"${buffer}": ${message}`);
|
|
1056
|
+
}
|
|
1057
|
+
let state = 0 /* Static */;
|
|
1058
|
+
let previousState = state;
|
|
1059
|
+
const tokens = [];
|
|
1060
|
+
// the segment will always be valid because we get into the initial state
|
|
1061
|
+
// with the leading /
|
|
1062
|
+
let segment;
|
|
1063
|
+
function finalizeSegment() {
|
|
1064
|
+
if (segment)
|
|
1065
|
+
tokens.push(segment);
|
|
1066
|
+
segment = [];
|
|
1067
|
+
}
|
|
1068
|
+
// index on the path
|
|
1069
|
+
let i = 0;
|
|
1070
|
+
// char at index
|
|
1071
|
+
let char;
|
|
1072
|
+
// buffer of the value read
|
|
1073
|
+
let buffer = '';
|
|
1074
|
+
// custom regexp for a param
|
|
1075
|
+
let customRe = '';
|
|
1076
|
+
function consumeBuffer() {
|
|
1077
|
+
if (!buffer)
|
|
1078
|
+
return;
|
|
1079
|
+
if (state === 0 /* Static */) {
|
|
1080
|
+
segment.push({
|
|
1081
|
+
type: 0 /* Static */,
|
|
1082
|
+
value: buffer,
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
else if (state === 1 /* Param */ ||
|
|
1086
|
+
state === 2 /* ParamRegExp */ ||
|
|
1087
|
+
state === 3 /* ParamRegExpEnd */) {
|
|
1088
|
+
if (segment.length > 1 && (char === '*' || char === '+'))
|
|
1089
|
+
crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
|
|
1090
|
+
segment.push({
|
|
1091
|
+
type: 1 /* Param */,
|
|
1092
|
+
value: buffer,
|
|
1093
|
+
regexp: customRe,
|
|
1094
|
+
repeatable: char === '*' || char === '+',
|
|
1095
|
+
optional: char === '*' || char === '?',
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
else {
|
|
1099
|
+
crash('Invalid state to consume buffer');
|
|
1100
|
+
}
|
|
1101
|
+
buffer = '';
|
|
1102
|
+
}
|
|
1103
|
+
function addCharToBuffer() {
|
|
1104
|
+
buffer += char;
|
|
1105
|
+
}
|
|
1106
|
+
while (i < path.length) {
|
|
1107
|
+
char = path[i++];
|
|
1108
|
+
if (char === '\\' && state !== 2 /* ParamRegExp */) {
|
|
1109
|
+
previousState = state;
|
|
1110
|
+
state = 4 /* EscapeNext */;
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
switch (state) {
|
|
1114
|
+
case 0 /* Static */:
|
|
1115
|
+
if (char === '/') {
|
|
1116
|
+
if (buffer) {
|
|
1117
|
+
consumeBuffer();
|
|
1118
|
+
}
|
|
1119
|
+
finalizeSegment();
|
|
1120
|
+
}
|
|
1121
|
+
else if (char === ':') {
|
|
1122
|
+
consumeBuffer();
|
|
1123
|
+
state = 1 /* Param */;
|
|
1124
|
+
}
|
|
1125
|
+
else {
|
|
1126
|
+
addCharToBuffer();
|
|
1127
|
+
}
|
|
1128
|
+
break;
|
|
1129
|
+
case 4 /* EscapeNext */:
|
|
1130
|
+
addCharToBuffer();
|
|
1131
|
+
state = previousState;
|
|
1132
|
+
break;
|
|
1133
|
+
case 1 /* Param */:
|
|
1134
|
+
if (char === '(') {
|
|
1135
|
+
state = 2 /* ParamRegExp */;
|
|
1136
|
+
customRe = '';
|
|
1137
|
+
}
|
|
1138
|
+
else if (VALID_PARAM_RE.test(char)) {
|
|
1139
|
+
addCharToBuffer();
|
|
1140
|
+
}
|
|
1141
|
+
else {
|
|
1142
|
+
consumeBuffer();
|
|
1143
|
+
state = 0 /* Static */;
|
|
1144
|
+
// go back one character if we were not modifying
|
|
1145
|
+
if (char !== '*' && char !== '?' && char !== '+')
|
|
1146
|
+
i--;
|
|
1147
|
+
}
|
|
1148
|
+
break;
|
|
1149
|
+
case 2 /* ParamRegExp */:
|
|
1150
|
+
// TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix)
|
|
1151
|
+
// it already works by escaping the closing )
|
|
1152
|
+
// https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB#
|
|
1153
|
+
// is this really something people need since you can also write
|
|
1154
|
+
// /prefix_:p()_suffix
|
|
1155
|
+
if (char === ')') {
|
|
1156
|
+
// handle the escaped )
|
|
1157
|
+
if (customRe[customRe.length - 1] == '\\')
|
|
1158
|
+
customRe = customRe.slice(0, -1) + char;
|
|
1159
|
+
else
|
|
1160
|
+
state = 3 /* ParamRegExpEnd */;
|
|
1161
|
+
}
|
|
1162
|
+
else {
|
|
1163
|
+
customRe += char;
|
|
1164
|
+
}
|
|
1165
|
+
break;
|
|
1166
|
+
case 3 /* ParamRegExpEnd */:
|
|
1167
|
+
// same as finalizing a param
|
|
1168
|
+
consumeBuffer();
|
|
1169
|
+
state = 0 /* Static */;
|
|
1170
|
+
// go back one character if we were not modifying
|
|
1171
|
+
if (char !== '*' && char !== '?' && char !== '+')
|
|
1172
|
+
i--;
|
|
1173
|
+
break;
|
|
1174
|
+
default:
|
|
1175
|
+
crash('Unknown state');
|
|
1176
|
+
break;
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
if (state === 2 /* ParamRegExp */)
|
|
1180
|
+
crash(`Unfinished custom RegExp for param "${buffer}"`);
|
|
1181
|
+
consumeBuffer();
|
|
1182
|
+
finalizeSegment();
|
|
1183
|
+
// tokenCache.set(path, tokens)
|
|
1184
|
+
return tokens;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
function createRouteRecordMatcher(record, parent, options) {
|
|
1188
|
+
const parser = tokensToParser(tokenizePath(record.path), options);
|
|
1189
|
+
// warn against params with the same name
|
|
1190
|
+
{
|
|
1191
|
+
const existingKeys = new Set();
|
|
1192
|
+
for (const key of parser.keys) {
|
|
1193
|
+
if (existingKeys.has(key.name))
|
|
1194
|
+
warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`);
|
|
1195
|
+
existingKeys.add(key.name);
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
const matcher = assign(parser, {
|
|
1199
|
+
record,
|
|
1200
|
+
parent,
|
|
1201
|
+
// these needs to be populated by the parent
|
|
1202
|
+
children: [],
|
|
1203
|
+
alias: [],
|
|
1204
|
+
});
|
|
1205
|
+
if (parent) {
|
|
1206
|
+
// both are aliases or both are not aliases
|
|
1207
|
+
// we don't want to mix them because the order is used when
|
|
1208
|
+
// passing originalRecord in Matcher.addRoute
|
|
1209
|
+
if (!matcher.record.aliasOf === !parent.record.aliasOf)
|
|
1210
|
+
parent.children.push(matcher);
|
|
1211
|
+
}
|
|
1212
|
+
return matcher;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
/**
|
|
1216
|
+
* Creates a Router Matcher.
|
|
1217
|
+
*
|
|
1218
|
+
* @internal
|
|
1219
|
+
* @param routes - array of initial routes
|
|
1220
|
+
* @param globalOptions - global route options
|
|
1221
|
+
*/
|
|
1222
|
+
function createRouterMatcher(routes, globalOptions) {
|
|
1223
|
+
// normalized ordered array of matchers
|
|
1224
|
+
const matchers = [];
|
|
1225
|
+
const matcherMap = new Map();
|
|
1226
|
+
globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions);
|
|
1227
|
+
function getRecordMatcher(name) {
|
|
1228
|
+
return matcherMap.get(name);
|
|
1229
|
+
}
|
|
1230
|
+
function addRoute(record, parent, originalRecord) {
|
|
1231
|
+
// used later on to remove by name
|
|
1232
|
+
let isRootAdd = !originalRecord;
|
|
1233
|
+
let mainNormalizedRecord = normalizeRouteRecord(record);
|
|
1234
|
+
// we might be the child of an alias
|
|
1235
|
+
mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
|
|
1236
|
+
const options = mergeOptions(globalOptions, record);
|
|
1237
|
+
// generate an array of records to correctly handle aliases
|
|
1238
|
+
const normalizedRecords = [
|
|
1239
|
+
mainNormalizedRecord,
|
|
1240
|
+
];
|
|
1241
|
+
if ('alias' in record) {
|
|
1242
|
+
const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias;
|
|
1243
|
+
for (const alias of aliases) {
|
|
1244
|
+
normalizedRecords.push(assign({}, mainNormalizedRecord, {
|
|
1245
|
+
// this allows us to hold a copy of the `components` option
|
|
1246
|
+
// so that async components cache is hold on the original record
|
|
1247
|
+
components: originalRecord
|
|
1248
|
+
? originalRecord.record.components
|
|
1249
|
+
: mainNormalizedRecord.components,
|
|
1250
|
+
path: alias,
|
|
1251
|
+
// we might be the child of an alias
|
|
1252
|
+
aliasOf: originalRecord
|
|
1253
|
+
? originalRecord.record
|
|
1254
|
+
: mainNormalizedRecord,
|
|
1255
|
+
}));
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
let matcher;
|
|
1259
|
+
let originalMatcher;
|
|
1260
|
+
for (const normalizedRecord of normalizedRecords) {
|
|
1261
|
+
let { path } = normalizedRecord;
|
|
1262
|
+
// Build up the path for nested routes if the child isn't an absolute
|
|
1263
|
+
// route. Only add the / delimiter if the child path isn't empty and if the
|
|
1264
|
+
// parent path doesn't have a trailing slash
|
|
1265
|
+
if (parent && path[0] !== '/') {
|
|
1266
|
+
let parentPath = parent.record.path;
|
|
1267
|
+
let connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/';
|
|
1268
|
+
normalizedRecord.path =
|
|
1269
|
+
parent.record.path + (path && connectingSlash + path);
|
|
1270
|
+
}
|
|
1271
|
+
if ( normalizedRecord.path === '*') {
|
|
1272
|
+
throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' +
|
|
1273
|
+
'See more at https://kdujs-router.web.app/guide/migration/#removed-star-or-catch-all-routes.');
|
|
1274
|
+
}
|
|
1275
|
+
// create the object before hand so it can be passed to children
|
|
1276
|
+
matcher = createRouteRecordMatcher(normalizedRecord, parent, options);
|
|
1277
|
+
if ( parent && path[0] === '/')
|
|
1278
|
+
checkMissingParamsInAbsolutePath(matcher, parent);
|
|
1279
|
+
// if we are an alias we must tell the original record that we exist
|
|
1280
|
+
// so we can be removed
|
|
1281
|
+
if (originalRecord) {
|
|
1282
|
+
originalRecord.alias.push(matcher);
|
|
1283
|
+
{
|
|
1284
|
+
checkSameParams(originalRecord, matcher);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
else {
|
|
1288
|
+
// otherwise, the first record is the original and others are aliases
|
|
1289
|
+
originalMatcher = originalMatcher || matcher;
|
|
1290
|
+
if (originalMatcher !== matcher)
|
|
1291
|
+
originalMatcher.alias.push(matcher);
|
|
1292
|
+
// remove the route if named and only for the top record (avoid in nested calls)
|
|
1293
|
+
// this works because the original record is the first one
|
|
1294
|
+
if (isRootAdd && record.name && !isAliasRecord(matcher))
|
|
1295
|
+
removeRoute(record.name);
|
|
1296
|
+
}
|
|
1297
|
+
if ('children' in mainNormalizedRecord) {
|
|
1298
|
+
let children = mainNormalizedRecord.children;
|
|
1299
|
+
for (let i = 0; i < children.length; i++) {
|
|
1300
|
+
addRoute(children[i], matcher, originalRecord && originalRecord.children[i]);
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
// if there was no original record, then the first one was not an alias and all
|
|
1304
|
+
// other alias (if any) need to reference this record when adding children
|
|
1305
|
+
originalRecord = originalRecord || matcher;
|
|
1306
|
+
// TODO: add normalized records for more flexibility
|
|
1307
|
+
// if (parent && isAliasRecord(originalRecord)) {
|
|
1308
|
+
// parent.children.push(originalRecord)
|
|
1309
|
+
// }
|
|
1310
|
+
insertMatcher(matcher);
|
|
1311
|
+
}
|
|
1312
|
+
return originalMatcher
|
|
1313
|
+
? () => {
|
|
1314
|
+
// since other matchers are aliases, they should be removed by the original matcher
|
|
1315
|
+
removeRoute(originalMatcher);
|
|
1316
|
+
}
|
|
1317
|
+
: noop;
|
|
1318
|
+
}
|
|
1319
|
+
function removeRoute(matcherRef) {
|
|
1320
|
+
if (isRouteName(matcherRef)) {
|
|
1321
|
+
const matcher = matcherMap.get(matcherRef);
|
|
1322
|
+
if (matcher) {
|
|
1323
|
+
matcherMap.delete(matcherRef);
|
|
1324
|
+
matchers.splice(matchers.indexOf(matcher), 1);
|
|
1325
|
+
matcher.children.forEach(removeRoute);
|
|
1326
|
+
matcher.alias.forEach(removeRoute);
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
else {
|
|
1330
|
+
let index = matchers.indexOf(matcherRef);
|
|
1331
|
+
if (index > -1) {
|
|
1332
|
+
matchers.splice(index, 1);
|
|
1333
|
+
if (matcherRef.record.name)
|
|
1334
|
+
matcherMap.delete(matcherRef.record.name);
|
|
1335
|
+
matcherRef.children.forEach(removeRoute);
|
|
1336
|
+
matcherRef.alias.forEach(removeRoute);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
function getRoutes() {
|
|
1341
|
+
return matchers;
|
|
1342
|
+
}
|
|
1343
|
+
function insertMatcher(matcher) {
|
|
1344
|
+
let i = 0;
|
|
1345
|
+
// console.log('i is', { i })
|
|
1346
|
+
while (i < matchers.length &&
|
|
1347
|
+
comparePathParserScore(matcher, matchers[i]) >= 0)
|
|
1348
|
+
i++;
|
|
1349
|
+
// console.log('END i is', { i })
|
|
1350
|
+
// while (i < matchers.length && matcher.score <= matchers[i].score) i++
|
|
1351
|
+
matchers.splice(i, 0, matcher);
|
|
1352
|
+
// only add the original record to the name map
|
|
1353
|
+
if (matcher.record.name && !isAliasRecord(matcher))
|
|
1354
|
+
matcherMap.set(matcher.record.name, matcher);
|
|
1355
|
+
}
|
|
1356
|
+
function resolve(location, currentLocation) {
|
|
1357
|
+
let matcher;
|
|
1358
|
+
let params = {};
|
|
1359
|
+
let path;
|
|
1360
|
+
let name;
|
|
1361
|
+
if ('name' in location && location.name) {
|
|
1362
|
+
matcher = matcherMap.get(location.name);
|
|
1363
|
+
if (!matcher)
|
|
1364
|
+
throw createRouterError(1 /* MATCHER_NOT_FOUND */, {
|
|
1365
|
+
location,
|
|
1366
|
+
});
|
|
1367
|
+
name = matcher.record.name;
|
|
1368
|
+
params = assign(
|
|
1369
|
+
// paramsFromLocation is a new object
|
|
1370
|
+
paramsFromLocation(currentLocation.params,
|
|
1371
|
+
// only keep params that exist in the resolved location
|
|
1372
|
+
// TODO: only keep optional params coming from a parent record
|
|
1373
|
+
matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params);
|
|
1374
|
+
// throws if cannot be stringified
|
|
1375
|
+
path = matcher.stringify(params);
|
|
1376
|
+
}
|
|
1377
|
+
else if ('path' in location) {
|
|
1378
|
+
// no need to resolve the path with the matcher as it was provided
|
|
1379
|
+
// this also allows the user to control the encoding
|
|
1380
|
+
path = location.path;
|
|
1381
|
+
if ( !path.startsWith('/')) {
|
|
1382
|
+
warn(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in kdu-router. Please open an issue at https://kdujs-new-issue.web.app/?repo=kdujs/router.`);
|
|
1383
|
+
}
|
|
1384
|
+
matcher = matchers.find(m => m.re.test(path));
|
|
1385
|
+
// matcher should have a value after the loop
|
|
1386
|
+
if (matcher) {
|
|
1387
|
+
// TODO: dev warning of unused params if provided
|
|
1388
|
+
// we know the matcher works because we tested the regexp
|
|
1389
|
+
params = matcher.parse(path);
|
|
1390
|
+
name = matcher.record.name;
|
|
1391
|
+
}
|
|
1392
|
+
// location is a relative path
|
|
1393
|
+
}
|
|
1394
|
+
else {
|
|
1395
|
+
// match by name or path of current route
|
|
1396
|
+
matcher = currentLocation.name
|
|
1397
|
+
? matcherMap.get(currentLocation.name)
|
|
1398
|
+
: matchers.find(m => m.re.test(currentLocation.path));
|
|
1399
|
+
if (!matcher)
|
|
1400
|
+
throw createRouterError(1 /* MATCHER_NOT_FOUND */, {
|
|
1401
|
+
location,
|
|
1402
|
+
currentLocation,
|
|
1403
|
+
});
|
|
1404
|
+
name = matcher.record.name;
|
|
1405
|
+
// since we are navigating to the same location, we don't need to pick the
|
|
1406
|
+
// params like when `name` is provided
|
|
1407
|
+
params = assign({}, currentLocation.params, location.params);
|
|
1408
|
+
path = matcher.stringify(params);
|
|
1409
|
+
}
|
|
1410
|
+
const matched = [];
|
|
1411
|
+
let parentMatcher = matcher;
|
|
1412
|
+
while (parentMatcher) {
|
|
1413
|
+
// reversed order so parents are at the beginning
|
|
1414
|
+
matched.unshift(parentMatcher.record);
|
|
1415
|
+
parentMatcher = parentMatcher.parent;
|
|
1416
|
+
}
|
|
1417
|
+
return {
|
|
1418
|
+
name,
|
|
1419
|
+
path,
|
|
1420
|
+
params,
|
|
1421
|
+
matched,
|
|
1422
|
+
meta: mergeMetaFields(matched),
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
// add initial routes
|
|
1426
|
+
routes.forEach(route => addRoute(route));
|
|
1427
|
+
return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher };
|
|
1428
|
+
}
|
|
1429
|
+
function paramsFromLocation(params, keys) {
|
|
1430
|
+
let newParams = {};
|
|
1431
|
+
for (let key of keys) {
|
|
1432
|
+
if (key in params)
|
|
1433
|
+
newParams[key] = params[key];
|
|
1434
|
+
}
|
|
1435
|
+
return newParams;
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* Normalizes a RouteRecordRaw. Creates a copy
|
|
1439
|
+
*
|
|
1440
|
+
* @param record
|
|
1441
|
+
* @returns the normalized version
|
|
1442
|
+
*/
|
|
1443
|
+
function normalizeRouteRecord(record) {
|
|
1444
|
+
return {
|
|
1445
|
+
path: record.path,
|
|
1446
|
+
redirect: record.redirect,
|
|
1447
|
+
name: record.name,
|
|
1448
|
+
meta: record.meta || {},
|
|
1449
|
+
aliasOf: undefined,
|
|
1450
|
+
beforeEnter: record.beforeEnter,
|
|
1451
|
+
props: normalizeRecordProps(record),
|
|
1452
|
+
children: record.children || [],
|
|
1453
|
+
instances: {},
|
|
1454
|
+
leaveGuards: new Set(),
|
|
1455
|
+
updateGuards: new Set(),
|
|
1456
|
+
enterCallbacks: {},
|
|
1457
|
+
components: 'components' in record
|
|
1458
|
+
? record.components || {}
|
|
1459
|
+
: { default: record.component },
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Normalize the optional `props` in a record to always be an object similar to
|
|
1464
|
+
* components. Also accept a boolean for components.
|
|
1465
|
+
* @param record
|
|
1466
|
+
*/
|
|
1467
|
+
function normalizeRecordProps(record) {
|
|
1468
|
+
const propsObject = {};
|
|
1469
|
+
// props does not exist on redirect records but we can set false directly
|
|
1470
|
+
const props = record.props || false;
|
|
1471
|
+
if ('component' in record) {
|
|
1472
|
+
propsObject.default = props;
|
|
1473
|
+
}
|
|
1474
|
+
else {
|
|
1475
|
+
// NOTE: we could also allow a function to be applied to every component.
|
|
1476
|
+
// Would need user feedback for use cases
|
|
1477
|
+
for (let name in record.components)
|
|
1478
|
+
propsObject[name] = typeof props === 'boolean' ? props : props[name];
|
|
1479
|
+
}
|
|
1480
|
+
return propsObject;
|
|
1481
|
+
}
|
|
1482
|
+
/**
|
|
1483
|
+
* Checks if a record or any of its parent is an alias
|
|
1484
|
+
* @param record
|
|
1485
|
+
*/
|
|
1486
|
+
function isAliasRecord(record) {
|
|
1487
|
+
while (record) {
|
|
1488
|
+
if (record.record.aliasOf)
|
|
1489
|
+
return true;
|
|
1490
|
+
record = record.parent;
|
|
1491
|
+
}
|
|
1492
|
+
return false;
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* Merge meta fields of an array of records
|
|
1496
|
+
*
|
|
1497
|
+
* @param matched - array of matched records
|
|
1498
|
+
*/
|
|
1499
|
+
function mergeMetaFields(matched) {
|
|
1500
|
+
return matched.reduce((meta, record) => assign(meta, record.meta), {});
|
|
1501
|
+
}
|
|
1502
|
+
function mergeOptions(defaults, partialOptions) {
|
|
1503
|
+
let options = {};
|
|
1504
|
+
for (let key in defaults) {
|
|
1505
|
+
options[key] =
|
|
1506
|
+
key in partialOptions ? partialOptions[key] : defaults[key];
|
|
1507
|
+
}
|
|
1508
|
+
return options;
|
|
1509
|
+
}
|
|
1510
|
+
function isSameParam(a, b) {
|
|
1511
|
+
return (a.name === b.name &&
|
|
1512
|
+
a.optional === b.optional &&
|
|
1513
|
+
a.repeatable === b.repeatable);
|
|
1514
|
+
}
|
|
1515
|
+
function checkSameParams(a, b) {
|
|
1516
|
+
for (let key of a.keys) {
|
|
1517
|
+
if (!b.keys.find(isSameParam.bind(null, key)))
|
|
1518
|
+
return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
|
|
1519
|
+
}
|
|
1520
|
+
for (let key of b.keys) {
|
|
1521
|
+
if (!a.keys.find(isSameParam.bind(null, key)))
|
|
1522
|
+
return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
function checkMissingParamsInAbsolutePath(record, parent) {
|
|
1526
|
+
for (let key of parent.keys) {
|
|
1527
|
+
if (!record.keys.find(isSameParam.bind(null, key)))
|
|
1528
|
+
return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`);
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ "
|
|
1534
|
+
* < > `
|
|
1535
|
+
*
|
|
1536
|
+
* On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2)
|
|
1537
|
+
* defines some extra characters to be encoded. Most browsers do not encode them
|
|
1538
|
+
* in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to
|
|
1539
|
+
* also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`)
|
|
1540
|
+
* plus `-._~`. This extra safety should be applied to query by patching the
|
|
1541
|
+
* string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\`
|
|
1542
|
+
* should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\`
|
|
1543
|
+
* into a `/` if directly typed in. The _backtick_ (`````) should also be
|
|
1544
|
+
* encoded everywhere because some browsers like FF encode it when directly
|
|
1545
|
+
* written while others don't. Safari and IE don't encode ``"<>{}``` in hash.
|
|
1546
|
+
*/
|
|
1547
|
+
// const EXTRA_RESERVED_RE = /[!'()*]/g
|
|
1548
|
+
// const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16)
|
|
1549
|
+
const HASH_RE = /#/g; // %23
|
|
1550
|
+
const AMPERSAND_RE = /&/g; // %26
|
|
1551
|
+
const SLASH_RE = /\//g; // %2F
|
|
1552
|
+
const EQUAL_RE = /=/g; // %3D
|
|
1553
|
+
const IM_RE = /\?/g; // %3F
|
|
1554
|
+
const PLUS_RE = /\+/g; // %2B
|
|
1555
|
+
/**
|
|
1556
|
+
* NOTE: It's not clear to me if we should encode the + symbol in queries, it
|
|
1557
|
+
* seems to be less flexible than not doing so and I can't find out the legacy
|
|
1558
|
+
* systems requiring this for regular requests like text/html. In the standard,
|
|
1559
|
+
* the encoding of the plus character is only mentioned for
|
|
1560
|
+
* application/x-www-form-urlencoded
|
|
1561
|
+
* (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo
|
|
1562
|
+
* leave the plus character as is in queries. To be more flexible, we allow the
|
|
1563
|
+
* plus character on the query but it can also be manually encoded by the user.
|
|
1564
|
+
*
|
|
1565
|
+
* Resources:
|
|
1566
|
+
* - https://url.spec.whatwg.org/#urlencoded-parsing
|
|
1567
|
+
* - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20
|
|
1568
|
+
*/
|
|
1569
|
+
const ENC_BRACKET_OPEN_RE = /%5B/g; // [
|
|
1570
|
+
const ENC_BRACKET_CLOSE_RE = /%5D/g; // ]
|
|
1571
|
+
const ENC_CARET_RE = /%5E/g; // ^
|
|
1572
|
+
const ENC_BACKTICK_RE = /%60/g; // `
|
|
1573
|
+
const ENC_CURLY_OPEN_RE = /%7B/g; // {
|
|
1574
|
+
const ENC_PIPE_RE = /%7C/g; // |
|
|
1575
|
+
const ENC_CURLY_CLOSE_RE = /%7D/g; // }
|
|
1576
|
+
const ENC_SPACE_RE = /%20/g; // }
|
|
1577
|
+
/**
|
|
1578
|
+
* Encode characters that need to be encoded on the path, search and hash
|
|
1579
|
+
* sections of the URL.
|
|
1580
|
+
*
|
|
1581
|
+
* @internal
|
|
1582
|
+
* @param text - string to encode
|
|
1583
|
+
* @returns encoded string
|
|
1584
|
+
*/
|
|
1585
|
+
function commonEncode(text) {
|
|
1586
|
+
return encodeURI('' + text)
|
|
1587
|
+
.replace(ENC_PIPE_RE, '|')
|
|
1588
|
+
.replace(ENC_BRACKET_OPEN_RE, '[')
|
|
1589
|
+
.replace(ENC_BRACKET_CLOSE_RE, ']');
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* Encode characters that need to be encoded on the hash section of the URL.
|
|
1593
|
+
*
|
|
1594
|
+
* @param text - string to encode
|
|
1595
|
+
* @returns encoded string
|
|
1596
|
+
*/
|
|
1597
|
+
function encodeHash(text) {
|
|
1598
|
+
return commonEncode(text)
|
|
1599
|
+
.replace(ENC_CURLY_OPEN_RE, '{')
|
|
1600
|
+
.replace(ENC_CURLY_CLOSE_RE, '}')
|
|
1601
|
+
.replace(ENC_CARET_RE, '^');
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Encode characters that need to be encoded query values on the query
|
|
1605
|
+
* section of the URL.
|
|
1606
|
+
*
|
|
1607
|
+
* @param text - string to encode
|
|
1608
|
+
* @returns encoded string
|
|
1609
|
+
*/
|
|
1610
|
+
function encodeQueryValue(text) {
|
|
1611
|
+
return (commonEncode(text)
|
|
1612
|
+
// Encode the space as +, encode the + to differentiate it from the space
|
|
1613
|
+
.replace(PLUS_RE, '%2B')
|
|
1614
|
+
.replace(ENC_SPACE_RE, '+')
|
|
1615
|
+
.replace(HASH_RE, '%23')
|
|
1616
|
+
.replace(AMPERSAND_RE, '%26')
|
|
1617
|
+
.replace(ENC_BACKTICK_RE, '`')
|
|
1618
|
+
.replace(ENC_CURLY_OPEN_RE, '{')
|
|
1619
|
+
.replace(ENC_CURLY_CLOSE_RE, '}')
|
|
1620
|
+
.replace(ENC_CARET_RE, '^'));
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* Like `encodeQueryValue` but also encodes the `=` character.
|
|
1624
|
+
*
|
|
1625
|
+
* @param text - string to encode
|
|
1626
|
+
*/
|
|
1627
|
+
function encodeQueryKey(text) {
|
|
1628
|
+
return encodeQueryValue(text).replace(EQUAL_RE, '%3D');
|
|
1629
|
+
}
|
|
1630
|
+
/**
|
|
1631
|
+
* Encode characters that need to be encoded on the path section of the URL.
|
|
1632
|
+
*
|
|
1633
|
+
* @param text - string to encode
|
|
1634
|
+
* @returns encoded string
|
|
1635
|
+
*/
|
|
1636
|
+
function encodePath(text) {
|
|
1637
|
+
return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F');
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Encode characters that need to be encoded on the path section of the URL as a
|
|
1641
|
+
* param. This function encodes everything {@link encodePath} does plus the
|
|
1642
|
+
* slash (`/`) character.
|
|
1643
|
+
*
|
|
1644
|
+
* @param text - string to encode
|
|
1645
|
+
* @returns encoded string
|
|
1646
|
+
*/
|
|
1647
|
+
function encodeParam(text) {
|
|
1648
|
+
return encodePath(text).replace(SLASH_RE, '%2F');
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Decode text using `decodeURIComponent`. Returns the original text if it
|
|
1652
|
+
* fails.
|
|
1653
|
+
*
|
|
1654
|
+
* @param text - string to decode
|
|
1655
|
+
* @returns decoded string
|
|
1656
|
+
*/
|
|
1657
|
+
function decode(text) {
|
|
1658
|
+
try {
|
|
1659
|
+
return decodeURIComponent('' + text);
|
|
1660
|
+
}
|
|
1661
|
+
catch (err) {
|
|
1662
|
+
warn(`Error decoding "${text}". Using original value`);
|
|
1663
|
+
}
|
|
1664
|
+
return '' + text;
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
/**
|
|
1668
|
+
* Transforms a queryString into a {@link LocationQuery} object. Accept both, a
|
|
1669
|
+
* version with the leading `?` and without Should work as URLSearchParams
|
|
1670
|
+
|
|
1671
|
+
* @internal
|
|
1672
|
+
*
|
|
1673
|
+
* @param search - search string to parse
|
|
1674
|
+
* @returns a query object
|
|
1675
|
+
*/
|
|
1676
|
+
function parseQuery(search) {
|
|
1677
|
+
const query = {};
|
|
1678
|
+
// avoid creating an object with an empty key and empty value
|
|
1679
|
+
// because of split('&')
|
|
1680
|
+
if (search === '' || search === '?')
|
|
1681
|
+
return query;
|
|
1682
|
+
const hasLeadingIM = search[0] === '?';
|
|
1683
|
+
const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
|
|
1684
|
+
for (let i = 0; i < searchParams.length; ++i) {
|
|
1685
|
+
// pre decode the + into space
|
|
1686
|
+
const searchParam = searchParams[i].replace(PLUS_RE, ' ');
|
|
1687
|
+
// allow the = character
|
|
1688
|
+
let eqPos = searchParam.indexOf('=');
|
|
1689
|
+
let key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
|
|
1690
|
+
let value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
|
|
1691
|
+
if (key in query) {
|
|
1692
|
+
// an extra variable for ts types
|
|
1693
|
+
let currentValue = query[key];
|
|
1694
|
+
if (!Array.isArray(currentValue)) {
|
|
1695
|
+
currentValue = query[key] = [currentValue];
|
|
1696
|
+
}
|
|
1697
|
+
currentValue.push(value);
|
|
1698
|
+
}
|
|
1699
|
+
else {
|
|
1700
|
+
query[key] = value;
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
return query;
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it
|
|
1707
|
+
* doesn't prepend a `?`
|
|
1708
|
+
*
|
|
1709
|
+
* @internal
|
|
1710
|
+
*
|
|
1711
|
+
* @param query - query object to stringify
|
|
1712
|
+
* @returns string version of the query without the leading `?`
|
|
1713
|
+
*/
|
|
1714
|
+
function stringifyQuery(query) {
|
|
1715
|
+
let search = '';
|
|
1716
|
+
for (let key in query) {
|
|
1717
|
+
if (search.length)
|
|
1718
|
+
search += '&';
|
|
1719
|
+
const value = query[key];
|
|
1720
|
+
key = encodeQueryKey(key);
|
|
1721
|
+
if (value == null) {
|
|
1722
|
+
// only null adds the value
|
|
1723
|
+
if (value !== undefined)
|
|
1724
|
+
search += key;
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
// keep null values
|
|
1728
|
+
let values = Array.isArray(value)
|
|
1729
|
+
? value.map(v => v && encodeQueryValue(v))
|
|
1730
|
+
: [value && encodeQueryValue(value)];
|
|
1731
|
+
for (let i = 0; i < values.length; i++) {
|
|
1732
|
+
// only append & with i > 0
|
|
1733
|
+
search += (i ? '&' : '') + key;
|
|
1734
|
+
if (values[i] != null)
|
|
1735
|
+
search += ('=' + values[i]);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
return search;
|
|
1739
|
+
}
|
|
1740
|
+
/**
|
|
1741
|
+
* Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting
|
|
1742
|
+
* numbers into strings, removing keys with an undefined value and replacing
|
|
1743
|
+
* undefined with null in arrays
|
|
1744
|
+
*
|
|
1745
|
+
* @param query - query object to normalize
|
|
1746
|
+
* @returns a normalized query object
|
|
1747
|
+
*/
|
|
1748
|
+
function normalizeQuery(query) {
|
|
1749
|
+
const normalizedQuery = {};
|
|
1750
|
+
for (let key in query) {
|
|
1751
|
+
let value = query[key];
|
|
1752
|
+
if (value !== undefined) {
|
|
1753
|
+
normalizedQuery[key] = Array.isArray(value)
|
|
1754
|
+
? value.map(v => (v == null ? null : '' + v))
|
|
1755
|
+
: value == null
|
|
1756
|
+
? value
|
|
1757
|
+
: '' + value;
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
return normalizedQuery;
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
/**
|
|
1764
|
+
* Create a list of callbacks that can be reset. Used to create before and after navigation guards list
|
|
1765
|
+
*/
|
|
1766
|
+
function useCallbacks() {
|
|
1767
|
+
let handlers = [];
|
|
1768
|
+
function add(handler) {
|
|
1769
|
+
handlers.push(handler);
|
|
1770
|
+
return () => {
|
|
1771
|
+
const i = handlers.indexOf(handler);
|
|
1772
|
+
if (i > -1)
|
|
1773
|
+
handlers.splice(i, 1);
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
1776
|
+
function reset() {
|
|
1777
|
+
handlers = [];
|
|
1778
|
+
}
|
|
1779
|
+
return {
|
|
1780
|
+
add,
|
|
1781
|
+
list: () => handlers,
|
|
1782
|
+
reset,
|
|
1783
|
+
};
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1786
|
+
function registerGuard(record, name, guard) {
|
|
1787
|
+
const removeFromList = () => {
|
|
1788
|
+
record[name].delete(guard);
|
|
1789
|
+
};
|
|
1790
|
+
onUnmounted(removeFromList);
|
|
1791
|
+
onDeactivated(removeFromList);
|
|
1792
|
+
onActivated(() => {
|
|
1793
|
+
record[name].add(guard);
|
|
1794
|
+
});
|
|
1795
|
+
record[name].add(guard);
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Add a navigation guard that triggers whenever the component for the current
|
|
1799
|
+
* location is about to be left. Similar to {@link beforeRouteLeave} but can be
|
|
1800
|
+
* used in any component. The guard is removed when the component is unmounted.
|
|
1801
|
+
*
|
|
1802
|
+
* @param leaveGuard - {@link NavigationGuard}
|
|
1803
|
+
*/
|
|
1804
|
+
function onBeforeRouteLeave(leaveGuard) {
|
|
1805
|
+
if ( !getCurrentInstance()) {
|
|
1806
|
+
warn('onBeforeRouteLeave must be called at the top of a setup function');
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
const activeRecord = inject(matchedRouteKey, {}).value;
|
|
1810
|
+
if (!activeRecord) {
|
|
1811
|
+
|
|
1812
|
+
warn('onBeforeRouteLeave must be called at the top of a setup function');
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
registerGuard(activeRecord, 'leaveGuards', leaveGuard);
|
|
1816
|
+
}
|
|
1817
|
+
/**
|
|
1818
|
+
* Add a navigation guard that triggers whenever the current location is about
|
|
1819
|
+
* to be updated. Similar to {@link beforeRouteUpdate} but can be used in any
|
|
1820
|
+
* component. The guard is removed when the component is unmounted.
|
|
1821
|
+
*
|
|
1822
|
+
* @param updateGuard - {@link NavigationGuard}
|
|
1823
|
+
*/
|
|
1824
|
+
function onBeforeRouteUpdate(updateGuard) {
|
|
1825
|
+
if ( !getCurrentInstance()) {
|
|
1826
|
+
warn('onBeforeRouteUpdate must be called at the top of a setup function');
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
const activeRecord = inject(matchedRouteKey, {}).value;
|
|
1830
|
+
if (!activeRecord) {
|
|
1831
|
+
|
|
1832
|
+
warn('onBeforeRouteUpdate must be called at the top of a setup function');
|
|
1833
|
+
return;
|
|
1834
|
+
}
|
|
1835
|
+
registerGuard(activeRecord, 'updateGuards', updateGuard);
|
|
1836
|
+
}
|
|
1837
|
+
function guardToPromiseFn(guard, to, from, record, name) {
|
|
1838
|
+
// keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place
|
|
1839
|
+
const enterCallbackArray = record &&
|
|
1840
|
+
// name is defined if record is because of the function overload
|
|
1841
|
+
(record.enterCallbacks[name] = record.enterCallbacks[name] || []);
|
|
1842
|
+
return () => new Promise((resolve, reject) => {
|
|
1843
|
+
const next = (valid) => {
|
|
1844
|
+
if (valid === false)
|
|
1845
|
+
reject(createRouterError(4 /* NAVIGATION_ABORTED */, {
|
|
1846
|
+
from,
|
|
1847
|
+
to,
|
|
1848
|
+
}));
|
|
1849
|
+
else if (valid instanceof Error) {
|
|
1850
|
+
reject(valid);
|
|
1851
|
+
}
|
|
1852
|
+
else if (isRouteLocation(valid)) {
|
|
1853
|
+
reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, {
|
|
1854
|
+
from: to,
|
|
1855
|
+
to: valid,
|
|
1856
|
+
}));
|
|
1857
|
+
}
|
|
1858
|
+
else {
|
|
1859
|
+
if (enterCallbackArray &&
|
|
1860
|
+
// since enterCallbackArray is truthy, both record and name also are
|
|
1861
|
+
record.enterCallbacks[name] === enterCallbackArray &&
|
|
1862
|
+
typeof valid === 'function')
|
|
1863
|
+
enterCallbackArray.push(valid);
|
|
1864
|
+
resolve();
|
|
1865
|
+
}
|
|
1866
|
+
};
|
|
1867
|
+
// wrapping with Promise.resolve allows it to work with both async and sync guards
|
|
1868
|
+
const guardReturn = guard.call(record && record.instances[name], to, from, canOnlyBeCalledOnce(next, to, from) );
|
|
1869
|
+
let guardCall = Promise.resolve(guardReturn);
|
|
1870
|
+
if (guard.length < 3)
|
|
1871
|
+
guardCall = guardCall.then(next);
|
|
1872
|
+
if ( guard.length > 2) {
|
|
1873
|
+
const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ''}:\n${guard.toString()}\n. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`;
|
|
1874
|
+
if (typeof guardReturn === 'object' && 'then' in guardReturn) {
|
|
1875
|
+
guardCall = guardCall.then(resolvedValue => {
|
|
1876
|
+
// @ts-ignore: _called is added at canOnlyBeCalledOnce
|
|
1877
|
+
if (!next._called) {
|
|
1878
|
+
warn(message);
|
|
1879
|
+
return Promise.reject(new Error('Invalid navigation guard'));
|
|
1880
|
+
}
|
|
1881
|
+
return resolvedValue;
|
|
1882
|
+
});
|
|
1883
|
+
// TODO: test me!
|
|
1884
|
+
}
|
|
1885
|
+
else if (guardReturn !== undefined) {
|
|
1886
|
+
// @ts-ignore: _called is added at canOnlyBeCalledOnce
|
|
1887
|
+
if (!next._called) {
|
|
1888
|
+
warn(message);
|
|
1889
|
+
reject(new Error('Invalid navigation guard'));
|
|
1890
|
+
return;
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
guardCall.catch(err => reject(err));
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
function canOnlyBeCalledOnce(next, to, from) {
|
|
1898
|
+
let called = 0;
|
|
1899
|
+
return function () {
|
|
1900
|
+
if (called++ === 1)
|
|
1901
|
+
warn(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`);
|
|
1902
|
+
// @ts-ignore: we put it in the original one because it's easier to check
|
|
1903
|
+
next._called = true;
|
|
1904
|
+
if (called === 1)
|
|
1905
|
+
next.apply(null, arguments);
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
function extractComponentsGuards(matched, guardType, to, from) {
|
|
1909
|
+
const guards = [];
|
|
1910
|
+
for (const record of matched) {
|
|
1911
|
+
for (const name in record.components) {
|
|
1912
|
+
let rawComponent = record.components[name];
|
|
1913
|
+
{
|
|
1914
|
+
if (!rawComponent ||
|
|
1915
|
+
(typeof rawComponent !== 'object' &&
|
|
1916
|
+
typeof rawComponent !== 'function')) {
|
|
1917
|
+
warn(`Component "${name}" in record with path "${record.path}" is not` +
|
|
1918
|
+
` a valid component. Received "${String(rawComponent)}".`);
|
|
1919
|
+
// throw to ensure we stop here but warn to ensure the message isn't
|
|
1920
|
+
// missed by the user
|
|
1921
|
+
throw new Error('Invalid route component');
|
|
1922
|
+
}
|
|
1923
|
+
else if ('then' in rawComponent) {
|
|
1924
|
+
// warn if user wrote import('/component.kdu') instead of () =>
|
|
1925
|
+
// import('./component.kdu')
|
|
1926
|
+
warn(`Component "${name}" in record with path "${record.path}" is a ` +
|
|
1927
|
+
`Promise instead of a function that returns a Promise. Did you ` +
|
|
1928
|
+
`write "import('./MyPage.kdu')" instead of ` +
|
|
1929
|
+
`"() => import('./MyPage.kdu')" ? This will break in ` +
|
|
1930
|
+
`production if not fixed.`);
|
|
1931
|
+
let promise = rawComponent;
|
|
1932
|
+
rawComponent = () => promise;
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
// skip update and leave guards if the route component is not mounted
|
|
1936
|
+
if (guardType !== 'beforeRouteEnter' && !record.instances[name])
|
|
1937
|
+
continue;
|
|
1938
|
+
if (isRouteComponent(rawComponent)) {
|
|
1939
|
+
// __vccOpts is added by kdu-class-component and contain the regular options
|
|
1940
|
+
let options = rawComponent.__vccOpts || rawComponent;
|
|
1941
|
+
const guard = options[guardType];
|
|
1942
|
+
guard && guards.push(guardToPromiseFn(guard, to, from, record, name));
|
|
1943
|
+
}
|
|
1944
|
+
else {
|
|
1945
|
+
// start requesting the chunk already
|
|
1946
|
+
let componentPromise = rawComponent();
|
|
1947
|
+
if ( !('catch' in componentPromise)) {
|
|
1948
|
+
warn(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`);
|
|
1949
|
+
componentPromise = Promise.resolve(componentPromise);
|
|
1950
|
+
}
|
|
1951
|
+
else {
|
|
1952
|
+
// display the error if any
|
|
1953
|
+
componentPromise = componentPromise.catch( err => err && warn(err) );
|
|
1954
|
+
}
|
|
1955
|
+
guards.push(() => componentPromise.then(resolved => {
|
|
1956
|
+
if (!resolved)
|
|
1957
|
+
return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`));
|
|
1958
|
+
const resolvedComponent = isESModule(resolved)
|
|
1959
|
+
? resolved.default
|
|
1960
|
+
: resolved;
|
|
1961
|
+
// replace the function with the resolved component
|
|
1962
|
+
record.components[name] = resolvedComponent;
|
|
1963
|
+
// @ts-ignore: the options types are not propagated to Component
|
|
1964
|
+
const guard = resolvedComponent[guardType];
|
|
1965
|
+
return guard && guardToPromiseFn(guard, to, from, record, name)();
|
|
1966
|
+
}));
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
return guards;
|
|
1971
|
+
}
|
|
1972
|
+
/**
|
|
1973
|
+
* Allows differentiating lazy components from functional components and kdu-class-component
|
|
1974
|
+
* @param component
|
|
1975
|
+
*/
|
|
1976
|
+
function isRouteComponent(component) {
|
|
1977
|
+
return (typeof component === 'object' ||
|
|
1978
|
+
'displayName' in component ||
|
|
1979
|
+
'props' in component ||
|
|
1980
|
+
'__vccOpts' in component);
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
// TODO: we could allow currentRoute as a prop to expose `isActive` and
|
|
1984
|
+
// `isExactActive` behavior should go through an RFC
|
|
1985
|
+
function useLink(props) {
|
|
1986
|
+
const router = inject(routerKey);
|
|
1987
|
+
const currentRoute = inject(routeLocationKey);
|
|
1988
|
+
const route = computed(() => router.resolve(unref(props.to)));
|
|
1989
|
+
const activeRecordIndex = computed(() => {
|
|
1990
|
+
let { matched } = route.value;
|
|
1991
|
+
let { length } = matched;
|
|
1992
|
+
const routeMatched = matched[length - 1];
|
|
1993
|
+
let currentMatched = currentRoute.matched;
|
|
1994
|
+
if (!routeMatched || !currentMatched.length)
|
|
1995
|
+
return -1;
|
|
1996
|
+
let index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
|
|
1997
|
+
if (index > -1)
|
|
1998
|
+
return index;
|
|
1999
|
+
// possible parent record
|
|
2000
|
+
let parentRecordPath = getOriginalPath(matched[length - 2]);
|
|
2001
|
+
return (
|
|
2002
|
+
// we are dealing with nested routes
|
|
2003
|
+
length > 1 &&
|
|
2004
|
+
// if the parent and matched route have the same path, this link is
|
|
2005
|
+
// referring to the empty child. Or we currently are on a different
|
|
2006
|
+
// child of the same parent
|
|
2007
|
+
getOriginalPath(routeMatched) === parentRecordPath &&
|
|
2008
|
+
// avoid comparing the child with its parent
|
|
2009
|
+
currentMatched[currentMatched.length - 1].path !== parentRecordPath
|
|
2010
|
+
? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2]))
|
|
2011
|
+
: index);
|
|
2012
|
+
});
|
|
2013
|
+
const isActive = computed(() => activeRecordIndex.value > -1 &&
|
|
2014
|
+
includesParams(currentRoute.params, route.value.params));
|
|
2015
|
+
const isExactActive = computed(() => activeRecordIndex.value > -1 &&
|
|
2016
|
+
activeRecordIndex.value === currentRoute.matched.length - 1 &&
|
|
2017
|
+
isSameRouteLocationParams(currentRoute.params, route.value.params));
|
|
2018
|
+
function navigate(e = {}) {
|
|
2019
|
+
if (guardEvent(e))
|
|
2020
|
+
return router[unref(props.replace) ? 'replace' : 'push'](unref(props.to));
|
|
2021
|
+
return Promise.resolve();
|
|
2022
|
+
}
|
|
2023
|
+
return {
|
|
2024
|
+
route,
|
|
2025
|
+
href: computed(() => route.value.href),
|
|
2026
|
+
isActive,
|
|
2027
|
+
isExactActive,
|
|
2028
|
+
navigate,
|
|
2029
|
+
};
|
|
2030
|
+
}
|
|
2031
|
+
const RouterLinkImpl = /*#__PURE__*/ defineComponent({
|
|
2032
|
+
name: 'RouterLink',
|
|
2033
|
+
props: {
|
|
2034
|
+
to: {
|
|
2035
|
+
type: [String, Object],
|
|
2036
|
+
required: true,
|
|
2037
|
+
},
|
|
2038
|
+
activeClass: String,
|
|
2039
|
+
// inactiveClass: String,
|
|
2040
|
+
exactActiveClass: String,
|
|
2041
|
+
custom: Boolean,
|
|
2042
|
+
ariaCurrentValue: {
|
|
2043
|
+
type: String,
|
|
2044
|
+
default: 'page',
|
|
2045
|
+
},
|
|
2046
|
+
},
|
|
2047
|
+
setup(props, { slots, attrs }) {
|
|
2048
|
+
const link = reactive(useLink(props));
|
|
2049
|
+
const { options } = inject(routerKey);
|
|
2050
|
+
const elClass = computed(() => ({
|
|
2051
|
+
[getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive,
|
|
2052
|
+
// [getLinkClass(
|
|
2053
|
+
// props.inactiveClass,
|
|
2054
|
+
// options.linkInactiveClass,
|
|
2055
|
+
// 'router-link-inactive'
|
|
2056
|
+
// )]: !link.isExactActive,
|
|
2057
|
+
[getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive,
|
|
2058
|
+
}));
|
|
2059
|
+
return () => {
|
|
2060
|
+
const children = slots.default && slots.default(link);
|
|
2061
|
+
return props.custom
|
|
2062
|
+
? children
|
|
2063
|
+
: h('a', assign({
|
|
2064
|
+
'aria-current': link.isExactActive
|
|
2065
|
+
? props.ariaCurrentValue
|
|
2066
|
+
: null,
|
|
2067
|
+
onClick: link.navigate,
|
|
2068
|
+
href: link.href,
|
|
2069
|
+
}, attrs, {
|
|
2070
|
+
class: elClass.value,
|
|
2071
|
+
}), children);
|
|
2072
|
+
};
|
|
2073
|
+
},
|
|
2074
|
+
});
|
|
2075
|
+
// export the public type for h/tsx inference
|
|
2076
|
+
// also to avoid inline import() in generated d.ts files
|
|
2077
|
+
/**
|
|
2078
|
+
* Component to render a link that triggers a navigation on click.
|
|
2079
|
+
*/
|
|
2080
|
+
const RouterLink = RouterLinkImpl;
|
|
2081
|
+
function guardEvent(e) {
|
|
2082
|
+
// don't redirect with control keys
|
|
2083
|
+
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
|
|
2084
|
+
return;
|
|
2085
|
+
// don't redirect when preventDefault called
|
|
2086
|
+
if (e.defaultPrevented)
|
|
2087
|
+
return;
|
|
2088
|
+
// don't redirect on right click
|
|
2089
|
+
if (e.button !== undefined && e.button !== 0)
|
|
2090
|
+
return;
|
|
2091
|
+
// don't redirect if `target="_blank"`
|
|
2092
|
+
// @ts-ignore getAttribute does exist
|
|
2093
|
+
if (e.currentTarget && e.currentTarget.getAttribute) {
|
|
2094
|
+
// @ts-ignore getAttribute exists
|
|
2095
|
+
const target = e.currentTarget.getAttribute('target');
|
|
2096
|
+
if (/\b_blank\b/i.test(target))
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
// this may be a Weex event which doesn't have this method
|
|
2100
|
+
if (e.preventDefault)
|
|
2101
|
+
e.preventDefault();
|
|
2102
|
+
return true;
|
|
2103
|
+
}
|
|
2104
|
+
function includesParams(outer, inner) {
|
|
2105
|
+
for (let key in inner) {
|
|
2106
|
+
let innerValue = inner[key];
|
|
2107
|
+
let outerValue = outer[key];
|
|
2108
|
+
if (typeof innerValue === 'string') {
|
|
2109
|
+
if (innerValue !== outerValue)
|
|
2110
|
+
return false;
|
|
2111
|
+
}
|
|
2112
|
+
else {
|
|
2113
|
+
if (!Array.isArray(outerValue) ||
|
|
2114
|
+
outerValue.length !== innerValue.length ||
|
|
2115
|
+
innerValue.some((value, i) => value !== outerValue[i]))
|
|
2116
|
+
return false;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
return true;
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
2122
|
+
* Get the original path value of a record by following its aliasOf
|
|
2123
|
+
* @param record
|
|
2124
|
+
*/
|
|
2125
|
+
function getOriginalPath(record) {
|
|
2126
|
+
return record ? (record.aliasOf ? record.aliasOf.path : record.path) : '';
|
|
2127
|
+
}
|
|
2128
|
+
/**
|
|
2129
|
+
* Utility class to get the active class based on defaults.
|
|
2130
|
+
* @param propClass
|
|
2131
|
+
* @param globalClass
|
|
2132
|
+
* @param defaultClass
|
|
2133
|
+
*/
|
|
2134
|
+
const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null
|
|
2135
|
+
? propClass
|
|
2136
|
+
: globalClass != null
|
|
2137
|
+
? globalClass
|
|
2138
|
+
: defaultClass;
|
|
2139
|
+
|
|
2140
|
+
const RouterViewImpl = /*#__PURE__*/ defineComponent({
|
|
2141
|
+
name: 'RouterView',
|
|
2142
|
+
props: {
|
|
2143
|
+
name: {
|
|
2144
|
+
type: String,
|
|
2145
|
+
default: 'default',
|
|
2146
|
+
},
|
|
2147
|
+
route: Object,
|
|
2148
|
+
},
|
|
2149
|
+
setup(props, { attrs, slots }) {
|
|
2150
|
+
warnDeprecatedUsage();
|
|
2151
|
+
const injectedRoute = inject(routerViewLocationKey);
|
|
2152
|
+
const routeToDisplay = computed(() => props.route || injectedRoute.value);
|
|
2153
|
+
const depth = inject(viewDepthKey, 0);
|
|
2154
|
+
const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth]);
|
|
2155
|
+
provide(viewDepthKey, depth + 1);
|
|
2156
|
+
provide(matchedRouteKey, matchedRouteRef);
|
|
2157
|
+
provide(routerViewLocationKey, routeToDisplay);
|
|
2158
|
+
const viewRef = ref();
|
|
2159
|
+
// watch at the same time the component instance, the route record we are
|
|
2160
|
+
// rendering, and the name
|
|
2161
|
+
watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => {
|
|
2162
|
+
// copy reused instances
|
|
2163
|
+
if (to) {
|
|
2164
|
+
// this will update the instance for new instances as well as reused
|
|
2165
|
+
// instances when navigating to a new route
|
|
2166
|
+
to.instances[name] = instance;
|
|
2167
|
+
// the component instance is reused for a different route or name so
|
|
2168
|
+
// we copy any saved update or leave guards
|
|
2169
|
+
if (from && from !== to && instance && instance === oldInstance) {
|
|
2170
|
+
to.leaveGuards = from.leaveGuards;
|
|
2171
|
+
to.updateGuards = from.updateGuards;
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
// trigger beforeRouteEnter next callbacks
|
|
2175
|
+
if (instance &&
|
|
2176
|
+
to &&
|
|
2177
|
+
// if there is no instance but to and from are the same this might be
|
|
2178
|
+
// the first visit
|
|
2179
|
+
(!from || !isSameRouteRecord(to, from) || !oldInstance)) {
|
|
2180
|
+
(to.enterCallbacks[name] || []).forEach(callback => callback(instance));
|
|
2181
|
+
}
|
|
2182
|
+
}, { flush: 'post' });
|
|
2183
|
+
return () => {
|
|
2184
|
+
const route = routeToDisplay.value;
|
|
2185
|
+
const matchedRoute = matchedRouteRef.value;
|
|
2186
|
+
const ViewComponent = matchedRoute && matchedRoute.components[props.name];
|
|
2187
|
+
// we need the value at the time we render because when we unmount, we
|
|
2188
|
+
// navigated to a different location so the value is different
|
|
2189
|
+
const currentName = props.name;
|
|
2190
|
+
if (!ViewComponent) {
|
|
2191
|
+
return normalizeSlot(slots.default, { Component: ViewComponent, route });
|
|
2192
|
+
}
|
|
2193
|
+
// props from route configuration
|
|
2194
|
+
const routePropsOption = matchedRoute.props[props.name];
|
|
2195
|
+
const routeProps = routePropsOption
|
|
2196
|
+
? routePropsOption === true
|
|
2197
|
+
? route.params
|
|
2198
|
+
: typeof routePropsOption === 'function'
|
|
2199
|
+
? routePropsOption(route)
|
|
2200
|
+
: routePropsOption
|
|
2201
|
+
: null;
|
|
2202
|
+
const onKnodeUnmounted = knode => {
|
|
2203
|
+
// remove the instance reference to prevent leak
|
|
2204
|
+
if (knode.component.isUnmounted) {
|
|
2205
|
+
matchedRoute.instances[currentName] = null;
|
|
2206
|
+
}
|
|
2207
|
+
};
|
|
2208
|
+
const component = h(ViewComponent, assign({}, routeProps, attrs, {
|
|
2209
|
+
onKnodeUnmounted,
|
|
2210
|
+
ref: viewRef,
|
|
2211
|
+
}));
|
|
2212
|
+
return (
|
|
2213
|
+
// pass the knode to the slot as a prop.
|
|
2214
|
+
// h and <component :is="..."> both accept knodes
|
|
2215
|
+
normalizeSlot(slots.default, { Component: component, route }) ||
|
|
2216
|
+
component);
|
|
2217
|
+
};
|
|
2218
|
+
},
|
|
2219
|
+
});
|
|
2220
|
+
function normalizeSlot(slot, data) {
|
|
2221
|
+
if (!slot)
|
|
2222
|
+
return null;
|
|
2223
|
+
const slotContent = slot(data);
|
|
2224
|
+
return slotContent.length === 1 ? slotContent[0] : slotContent;
|
|
2225
|
+
}
|
|
2226
|
+
// export the public type for h/tsx inference
|
|
2227
|
+
// also to avoid inline import() in generated d.ts files
|
|
2228
|
+
/**
|
|
2229
|
+
* Component to display the current route the user is at.
|
|
2230
|
+
*/
|
|
2231
|
+
const RouterView = RouterViewImpl;
|
|
2232
|
+
// warn against deprecated usage with <transition> & <keep-alive>
|
|
2233
|
+
// due to functional component being no longer eager in Kdu 3
|
|
2234
|
+
function warnDeprecatedUsage() {
|
|
2235
|
+
const instance = getCurrentInstance();
|
|
2236
|
+
const parentName = instance.parent && instance.parent.type.name;
|
|
2237
|
+
if (parentName &&
|
|
2238
|
+
(parentName === 'KeepAlive' || parentName.includes('Transition'))) {
|
|
2239
|
+
const comp = parentName === 'KeepAlive' ? 'keep-alive' : 'transition';
|
|
2240
|
+
warn(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.\n` +
|
|
2241
|
+
`Use slot props instead:\n\n` +
|
|
2242
|
+
`<router-view k-slot="{ Component }">\n` +
|
|
2243
|
+
` <${comp}>\n` +
|
|
2244
|
+
` <component :is="Component" />\n` +
|
|
2245
|
+
` </${comp}>\n` +
|
|
2246
|
+
`</router-view>`);
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
function getDevtoolsGlobalHook() {
|
|
2251
|
+
return getTarget().__KDU_DEVTOOLS_GLOBAL_HOOK__;
|
|
2252
|
+
}
|
|
2253
|
+
function getTarget() {
|
|
2254
|
+
// @ts-ignore
|
|
2255
|
+
return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
|
|
2256
|
+
? window
|
|
2257
|
+
: typeof global !== 'undefined'
|
|
2258
|
+
? global
|
|
2259
|
+
: {};
|
|
2260
|
+
}
|
|
2261
|
+
const isProxyAvailable = typeof Proxy === 'function';
|
|
2262
|
+
|
|
2263
|
+
const HOOK_SETUP = 'devtools-plugin:setup';
|
|
2264
|
+
const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
|
|
2265
|
+
|
|
2266
|
+
class ApiProxy {
|
|
2267
|
+
constructor(plugin, hook) {
|
|
2268
|
+
this.target = null;
|
|
2269
|
+
this.targetQueue = [];
|
|
2270
|
+
this.onQueue = [];
|
|
2271
|
+
this.plugin = plugin;
|
|
2272
|
+
this.hook = hook;
|
|
2273
|
+
const defaultSettings = {};
|
|
2274
|
+
if (plugin.settings) {
|
|
2275
|
+
for (const id in plugin.settings) {
|
|
2276
|
+
const item = plugin.settings[id];
|
|
2277
|
+
defaultSettings[id] = item.defaultValue;
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
const localSettingsSaveId = `__kdu-devtools-plugin-settings__${plugin.id}`;
|
|
2281
|
+
let currentSettings = Object.assign({}, defaultSettings);
|
|
2282
|
+
try {
|
|
2283
|
+
const raw = localStorage.getItem(localSettingsSaveId);
|
|
2284
|
+
const data = JSON.parse(raw);
|
|
2285
|
+
Object.assign(currentSettings, data);
|
|
2286
|
+
}
|
|
2287
|
+
catch (e) {
|
|
2288
|
+
// noop
|
|
2289
|
+
}
|
|
2290
|
+
this.fallbacks = {
|
|
2291
|
+
getSettings() {
|
|
2292
|
+
return currentSettings;
|
|
2293
|
+
},
|
|
2294
|
+
setSettings(value) {
|
|
2295
|
+
try {
|
|
2296
|
+
localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
|
|
2297
|
+
}
|
|
2298
|
+
catch (e) {
|
|
2299
|
+
// noop
|
|
2300
|
+
}
|
|
2301
|
+
currentSettings = value;
|
|
2302
|
+
},
|
|
2303
|
+
};
|
|
2304
|
+
if (hook) {
|
|
2305
|
+
hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
|
|
2306
|
+
if (pluginId === this.plugin.id) {
|
|
2307
|
+
this.fallbacks.setSettings(value);
|
|
2308
|
+
}
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
this.proxiedOn = new Proxy({}, {
|
|
2312
|
+
get: (_target, prop) => {
|
|
2313
|
+
if (this.target) {
|
|
2314
|
+
return this.target.on[prop];
|
|
2315
|
+
}
|
|
2316
|
+
else {
|
|
2317
|
+
return (...args) => {
|
|
2318
|
+
this.onQueue.push({
|
|
2319
|
+
method: prop,
|
|
2320
|
+
args,
|
|
2321
|
+
});
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
},
|
|
2325
|
+
});
|
|
2326
|
+
this.proxiedTarget = new Proxy({}, {
|
|
2327
|
+
get: (_target, prop) => {
|
|
2328
|
+
if (this.target) {
|
|
2329
|
+
return this.target[prop];
|
|
2330
|
+
}
|
|
2331
|
+
else if (prop === 'on') {
|
|
2332
|
+
return this.proxiedOn;
|
|
2333
|
+
}
|
|
2334
|
+
else if (Object.keys(this.fallbacks).includes(prop)) {
|
|
2335
|
+
return (...args) => {
|
|
2336
|
+
this.targetQueue.push({
|
|
2337
|
+
method: prop,
|
|
2338
|
+
args,
|
|
2339
|
+
resolve: () => { },
|
|
2340
|
+
});
|
|
2341
|
+
return this.fallbacks[prop](...args);
|
|
2342
|
+
};
|
|
2343
|
+
}
|
|
2344
|
+
else {
|
|
2345
|
+
return (...args) => {
|
|
2346
|
+
return new Promise(resolve => {
|
|
2347
|
+
this.targetQueue.push({
|
|
2348
|
+
method: prop,
|
|
2349
|
+
args,
|
|
2350
|
+
resolve,
|
|
2351
|
+
});
|
|
2352
|
+
});
|
|
2353
|
+
};
|
|
2354
|
+
}
|
|
2355
|
+
},
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
async setRealTarget(target) {
|
|
2359
|
+
this.target = target;
|
|
2360
|
+
for (const item of this.onQueue) {
|
|
2361
|
+
this.target.on[item.method](...item.args);
|
|
2362
|
+
}
|
|
2363
|
+
for (const item of this.targetQueue) {
|
|
2364
|
+
item.resolve(await this.target[item.method](...item.args));
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
|
|
2370
|
+
const target = getTarget();
|
|
2371
|
+
const hook = getDevtoolsGlobalHook();
|
|
2372
|
+
const enableProxy = isProxyAvailable && pluginDescriptor.enableEarlyProxy;
|
|
2373
|
+
if (hook && (target.__KDU_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
|
|
2374
|
+
hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
|
|
2375
|
+
}
|
|
2376
|
+
else {
|
|
2377
|
+
const proxy = enableProxy ? new ApiProxy(pluginDescriptor, hook) : null;
|
|
2378
|
+
const list = target.__KDU_DEVTOOLS_PLUGINS__ = target.__KDU_DEVTOOLS_PLUGINS__ || [];
|
|
2379
|
+
list.push({
|
|
2380
|
+
pluginDescriptor,
|
|
2381
|
+
setupFn,
|
|
2382
|
+
proxy,
|
|
2383
|
+
});
|
|
2384
|
+
if (proxy)
|
|
2385
|
+
setupFn(proxy.proxiedTarget);
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
function formatRouteLocation(routeLocation, tooltip) {
|
|
2390
|
+
const copy = {
|
|
2391
|
+
...routeLocation,
|
|
2392
|
+
// remove variables that can contain kdu instances
|
|
2393
|
+
matched: routeLocation.matched.map(({ instances, children, aliasOf, ...rest }) => rest),
|
|
2394
|
+
};
|
|
2395
|
+
return {
|
|
2396
|
+
_custom: {
|
|
2397
|
+
type: null,
|
|
2398
|
+
readOnly: true,
|
|
2399
|
+
display: routeLocation.fullPath,
|
|
2400
|
+
tooltip,
|
|
2401
|
+
value: copy,
|
|
2402
|
+
},
|
|
2403
|
+
};
|
|
2404
|
+
}
|
|
2405
|
+
function formatDisplay(display) {
|
|
2406
|
+
return {
|
|
2407
|
+
_custom: {
|
|
2408
|
+
display,
|
|
2409
|
+
},
|
|
2410
|
+
};
|
|
2411
|
+
}
|
|
2412
|
+
// to support multiple router instances
|
|
2413
|
+
let routerId = 0;
|
|
2414
|
+
function addDevtools(app, router, matcher) {
|
|
2415
|
+
// Take over router.beforeEach and afterEach
|
|
2416
|
+
// increment to support multiple router instances
|
|
2417
|
+
const id = routerId++;
|
|
2418
|
+
setupDevtoolsPlugin({
|
|
2419
|
+
id: 'Router' + id ? ' ' + id : '',
|
|
2420
|
+
label: 'Router devtools',
|
|
2421
|
+
app,
|
|
2422
|
+
}, api => {
|
|
2423
|
+
api.on.inspectComponent((payload, ctx) => {
|
|
2424
|
+
if (payload.instanceData) {
|
|
2425
|
+
payload.instanceData.state.push({
|
|
2426
|
+
type: 'Routing',
|
|
2427
|
+
key: '$route',
|
|
2428
|
+
editable: false,
|
|
2429
|
+
value: formatRouteLocation(router.currentRoute.value, 'Current Route'),
|
|
2430
|
+
});
|
|
2431
|
+
}
|
|
2432
|
+
});
|
|
2433
|
+
watch(router.currentRoute, () => {
|
|
2434
|
+
// refresh active state
|
|
2435
|
+
refreshRoutesView();
|
|
2436
|
+
// @ts-ignore
|
|
2437
|
+
api.notifyComponentUpdate();
|
|
2438
|
+
api.sendInspectorTree(routerInspectorId);
|
|
2439
|
+
});
|
|
2440
|
+
const navigationsLayerId = 'router:navigations:' + id;
|
|
2441
|
+
api.addTimelineLayer({
|
|
2442
|
+
id: navigationsLayerId,
|
|
2443
|
+
label: `Router${id ? ' ' + id : ''} Navigations`,
|
|
2444
|
+
color: 0x40a8c4,
|
|
2445
|
+
});
|
|
2446
|
+
// const errorsLayerId = 'router:errors'
|
|
2447
|
+
// api.addTimelineLayer({
|
|
2448
|
+
// id: errorsLayerId,
|
|
2449
|
+
// label: 'Router Errors',
|
|
2450
|
+
// color: 0xea5455,
|
|
2451
|
+
// })
|
|
2452
|
+
router.onError(error => {
|
|
2453
|
+
api.addTimelineEvent({
|
|
2454
|
+
layerId: navigationsLayerId,
|
|
2455
|
+
event: {
|
|
2456
|
+
// @ts-ignore
|
|
2457
|
+
logType: 'error',
|
|
2458
|
+
time: Date.now(),
|
|
2459
|
+
data: { error },
|
|
2460
|
+
},
|
|
2461
|
+
});
|
|
2462
|
+
});
|
|
2463
|
+
router.beforeEach((to, from) => {
|
|
2464
|
+
const data = {
|
|
2465
|
+
guard: formatDisplay('beforeEach'),
|
|
2466
|
+
from: formatRouteLocation(from, 'Current Location during this navigation'),
|
|
2467
|
+
to: formatRouteLocation(to, 'Target location'),
|
|
2468
|
+
};
|
|
2469
|
+
api.addTimelineEvent({
|
|
2470
|
+
layerId: navigationsLayerId,
|
|
2471
|
+
event: {
|
|
2472
|
+
time: Date.now(),
|
|
2473
|
+
meta: {},
|
|
2474
|
+
data,
|
|
2475
|
+
},
|
|
2476
|
+
});
|
|
2477
|
+
});
|
|
2478
|
+
router.afterEach((to, from, failure) => {
|
|
2479
|
+
const data = {
|
|
2480
|
+
guard: formatDisplay('afterEach'),
|
|
2481
|
+
};
|
|
2482
|
+
if (failure) {
|
|
2483
|
+
data.failure = {
|
|
2484
|
+
_custom: {
|
|
2485
|
+
type: Error,
|
|
2486
|
+
readOnly: true,
|
|
2487
|
+
display: failure ? failure.message : '',
|
|
2488
|
+
tooltip: 'Navigation Failure',
|
|
2489
|
+
value: failure,
|
|
2490
|
+
},
|
|
2491
|
+
};
|
|
2492
|
+
data.status = formatDisplay('❌');
|
|
2493
|
+
}
|
|
2494
|
+
else {
|
|
2495
|
+
data.status = formatDisplay('✅');
|
|
2496
|
+
}
|
|
2497
|
+
// we set here to have the right order
|
|
2498
|
+
data.from = formatRouteLocation(from, 'Current Location during this navigation');
|
|
2499
|
+
data.to = formatRouteLocation(to, 'Target location');
|
|
2500
|
+
api.addTimelineEvent({
|
|
2501
|
+
layerId: navigationsLayerId,
|
|
2502
|
+
event: {
|
|
2503
|
+
time: Date.now(),
|
|
2504
|
+
data,
|
|
2505
|
+
// @ts-ignore
|
|
2506
|
+
logType: failure ? 'warning' : 'default',
|
|
2507
|
+
meta: {},
|
|
2508
|
+
},
|
|
2509
|
+
});
|
|
2510
|
+
});
|
|
2511
|
+
/**
|
|
2512
|
+
* Inspector of Existing routes
|
|
2513
|
+
*/
|
|
2514
|
+
const routerInspectorId = 'router-inspector:' + id;
|
|
2515
|
+
api.addInspector({
|
|
2516
|
+
id: routerInspectorId,
|
|
2517
|
+
label: 'Routes' + (id ? ' ' + id : ''),
|
|
2518
|
+
icon: 'book',
|
|
2519
|
+
treeFilterPlaceholder: 'Search routes',
|
|
2520
|
+
});
|
|
2521
|
+
function refreshRoutesView() {
|
|
2522
|
+
// the routes view isn't active
|
|
2523
|
+
if (!activeRoutesPayload)
|
|
2524
|
+
return;
|
|
2525
|
+
const payload = activeRoutesPayload;
|
|
2526
|
+
// children routes will appear as nested
|
|
2527
|
+
let routes = matcher.getRoutes().filter(route => !route.parent);
|
|
2528
|
+
// reset match state to false
|
|
2529
|
+
routes.forEach(resetMatchStateOnRouteRecord);
|
|
2530
|
+
// apply a match state if there is a payload
|
|
2531
|
+
if (payload.filter) {
|
|
2532
|
+
routes = routes.filter(route =>
|
|
2533
|
+
// save matches state based on the payload
|
|
2534
|
+
isRouteMatching(route, payload.filter.toLowerCase()));
|
|
2535
|
+
}
|
|
2536
|
+
// mark active routes
|
|
2537
|
+
routes.forEach(route => markRouteRecordActive(route, router.currentRoute.value));
|
|
2538
|
+
payload.rootNodes = routes.map(formatRouteRecordForInspector);
|
|
2539
|
+
}
|
|
2540
|
+
let activeRoutesPayload;
|
|
2541
|
+
api.on.getInspectorTree(payload => {
|
|
2542
|
+
activeRoutesPayload = payload;
|
|
2543
|
+
if (payload.app === app && payload.inspectorId === routerInspectorId) {
|
|
2544
|
+
refreshRoutesView();
|
|
2545
|
+
}
|
|
2546
|
+
});
|
|
2547
|
+
/**
|
|
2548
|
+
* Display information about the currently selected route record
|
|
2549
|
+
*/
|
|
2550
|
+
api.on.getInspectorState(payload => {
|
|
2551
|
+
if (payload.app === app && payload.inspectorId === routerInspectorId) {
|
|
2552
|
+
const routes = matcher.getRoutes();
|
|
2553
|
+
const route = routes.find(route => route.record.__kd_id === payload.nodeId);
|
|
2554
|
+
if (route) {
|
|
2555
|
+
payload.state = {
|
|
2556
|
+
options: formatRouteRecordMatcherForStateInspector(route),
|
|
2557
|
+
};
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
});
|
|
2561
|
+
api.sendInspectorTree(routerInspectorId);
|
|
2562
|
+
api.sendInspectorState(routerInspectorId);
|
|
2563
|
+
});
|
|
2564
|
+
}
|
|
2565
|
+
function modifierForKey(key) {
|
|
2566
|
+
if (key.optional) {
|
|
2567
|
+
return key.repeatable ? '*' : '?';
|
|
2568
|
+
}
|
|
2569
|
+
else {
|
|
2570
|
+
return key.repeatable ? '+' : '';
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
function formatRouteRecordMatcherForStateInspector(route) {
|
|
2574
|
+
const { record } = route;
|
|
2575
|
+
const fields = [
|
|
2576
|
+
{ editable: false, key: 'path', value: record.path },
|
|
2577
|
+
];
|
|
2578
|
+
if (record.name != null) {
|
|
2579
|
+
fields.push({
|
|
2580
|
+
editable: false,
|
|
2581
|
+
key: 'name',
|
|
2582
|
+
value: record.name,
|
|
2583
|
+
});
|
|
2584
|
+
}
|
|
2585
|
+
fields.push({ editable: false, key: 'regexp', value: route.re });
|
|
2586
|
+
if (route.keys.length) {
|
|
2587
|
+
fields.push({
|
|
2588
|
+
editable: false,
|
|
2589
|
+
key: 'keys',
|
|
2590
|
+
value: {
|
|
2591
|
+
_custom: {
|
|
2592
|
+
type: null,
|
|
2593
|
+
readOnly: true,
|
|
2594
|
+
display: route.keys
|
|
2595
|
+
.map(key => `${key.name}${modifierForKey(key)}`)
|
|
2596
|
+
.join(' '),
|
|
2597
|
+
tooltip: 'Param keys',
|
|
2598
|
+
value: route.keys,
|
|
2599
|
+
},
|
|
2600
|
+
},
|
|
2601
|
+
});
|
|
2602
|
+
}
|
|
2603
|
+
if (record.redirect != null) {
|
|
2604
|
+
fields.push({
|
|
2605
|
+
editable: false,
|
|
2606
|
+
key: 'redirect',
|
|
2607
|
+
value: record.redirect,
|
|
2608
|
+
});
|
|
2609
|
+
}
|
|
2610
|
+
if (route.alias.length) {
|
|
2611
|
+
fields.push({
|
|
2612
|
+
editable: false,
|
|
2613
|
+
key: 'aliases',
|
|
2614
|
+
value: route.alias.map(alias => alias.record.path),
|
|
2615
|
+
});
|
|
2616
|
+
}
|
|
2617
|
+
fields.push({
|
|
2618
|
+
key: 'score',
|
|
2619
|
+
editable: false,
|
|
2620
|
+
value: {
|
|
2621
|
+
_custom: {
|
|
2622
|
+
type: null,
|
|
2623
|
+
readOnly: true,
|
|
2624
|
+
display: route.score.map(score => score.join(', ')).join(' | '),
|
|
2625
|
+
tooltip: 'Score used to sort routes',
|
|
2626
|
+
value: route.score,
|
|
2627
|
+
},
|
|
2628
|
+
},
|
|
2629
|
+
});
|
|
2630
|
+
return fields;
|
|
2631
|
+
}
|
|
2632
|
+
/**
|
|
2633
|
+
* Extracted from tailwind palette
|
|
2634
|
+
*/
|
|
2635
|
+
const PINK_500 = 0xec4899;
|
|
2636
|
+
const BLUE_600 = 0x2563eb;
|
|
2637
|
+
const LIME_500 = 0x84cc16;
|
|
2638
|
+
const CYAN_400 = 0x22d3ee;
|
|
2639
|
+
const ORANGE_400 = 0xfb923c;
|
|
2640
|
+
// const GRAY_100 = 0xf4f4f5
|
|
2641
|
+
const DARK = 0x666666;
|
|
2642
|
+
function formatRouteRecordForInspector(route) {
|
|
2643
|
+
const tags = [];
|
|
2644
|
+
const { record } = route;
|
|
2645
|
+
if (record.name != null) {
|
|
2646
|
+
tags.push({
|
|
2647
|
+
label: String(record.name),
|
|
2648
|
+
textColor: 0,
|
|
2649
|
+
backgroundColor: CYAN_400,
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
if (record.aliasOf) {
|
|
2653
|
+
tags.push({
|
|
2654
|
+
label: 'alias',
|
|
2655
|
+
textColor: 0,
|
|
2656
|
+
backgroundColor: ORANGE_400,
|
|
2657
|
+
});
|
|
2658
|
+
}
|
|
2659
|
+
if (route.__kd_match) {
|
|
2660
|
+
tags.push({
|
|
2661
|
+
label: 'matches',
|
|
2662
|
+
textColor: 0,
|
|
2663
|
+
backgroundColor: PINK_500,
|
|
2664
|
+
});
|
|
2665
|
+
}
|
|
2666
|
+
if (route.__kd_exactActive) {
|
|
2667
|
+
tags.push({
|
|
2668
|
+
label: 'exact',
|
|
2669
|
+
textColor: 0,
|
|
2670
|
+
backgroundColor: LIME_500,
|
|
2671
|
+
});
|
|
2672
|
+
}
|
|
2673
|
+
if (route.__kd_active) {
|
|
2674
|
+
tags.push({
|
|
2675
|
+
label: 'active',
|
|
2676
|
+
textColor: 0,
|
|
2677
|
+
backgroundColor: BLUE_600,
|
|
2678
|
+
});
|
|
2679
|
+
}
|
|
2680
|
+
if (record.redirect) {
|
|
2681
|
+
tags.push({
|
|
2682
|
+
label: 'redirect: ' +
|
|
2683
|
+
(typeof record.redirect === 'string' ? record.redirect : 'Object'),
|
|
2684
|
+
textColor: 0xffffff,
|
|
2685
|
+
backgroundColor: DARK,
|
|
2686
|
+
});
|
|
2687
|
+
}
|
|
2688
|
+
// add an id to be able to select it. Using the `path` is not possible because
|
|
2689
|
+
// empty path children would collide with their parents
|
|
2690
|
+
let id = String(routeRecordId++);
|
|
2691
|
+
record.__kd_id = id;
|
|
2692
|
+
return {
|
|
2693
|
+
id,
|
|
2694
|
+
label: record.path,
|
|
2695
|
+
tags,
|
|
2696
|
+
// @ts-ignore
|
|
2697
|
+
children: route.children.map(formatRouteRecordForInspector),
|
|
2698
|
+
};
|
|
2699
|
+
}
|
|
2700
|
+
// incremental id for route records and inspector state
|
|
2701
|
+
let routeRecordId = 0;
|
|
2702
|
+
const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
|
|
2703
|
+
function markRouteRecordActive(route, currentRoute) {
|
|
2704
|
+
// no route will be active if matched is empty
|
|
2705
|
+
// reset the matching state
|
|
2706
|
+
const isExactActive = currentRoute.matched.length &&
|
|
2707
|
+
isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
|
|
2708
|
+
route.__kd_exactActive = route.__kd_active = isExactActive;
|
|
2709
|
+
if (!isExactActive) {
|
|
2710
|
+
route.__kd_active = currentRoute.matched.some(match => isSameRouteRecord(match, route.record));
|
|
2711
|
+
}
|
|
2712
|
+
route.children.forEach(childRoute => markRouteRecordActive(childRoute, currentRoute));
|
|
2713
|
+
}
|
|
2714
|
+
function resetMatchStateOnRouteRecord(route) {
|
|
2715
|
+
route.__kd_match = false;
|
|
2716
|
+
route.children.forEach(resetMatchStateOnRouteRecord);
|
|
2717
|
+
}
|
|
2718
|
+
function isRouteMatching(route, filter) {
|
|
2719
|
+
const found = String(route.re).match(EXTRACT_REGEXP_RE);
|
|
2720
|
+
route.__kd_match = false;
|
|
2721
|
+
if (!found || found.length < 3) {
|
|
2722
|
+
return false;
|
|
2723
|
+
}
|
|
2724
|
+
// use a regexp without $ at the end to match nested routes better
|
|
2725
|
+
const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]);
|
|
2726
|
+
if (nonEndingRE.test(filter)) {
|
|
2727
|
+
// mark children as matches
|
|
2728
|
+
route.children.forEach(child => isRouteMatching(child, filter));
|
|
2729
|
+
// exception case: `/`
|
|
2730
|
+
if (route.record.path !== '/' || filter === '/') {
|
|
2731
|
+
route.__kd_match = route.re.test(filter);
|
|
2732
|
+
return true;
|
|
2733
|
+
}
|
|
2734
|
+
// hide the / route
|
|
2735
|
+
return false;
|
|
2736
|
+
}
|
|
2737
|
+
const path = route.record.path.toLowerCase();
|
|
2738
|
+
const decodedPath = decode(path);
|
|
2739
|
+
// also allow partial matching on the path
|
|
2740
|
+
if (!filter.startsWith('/') &&
|
|
2741
|
+
(decodedPath.includes(filter) || path.includes(filter)))
|
|
2742
|
+
return true;
|
|
2743
|
+
if (decodedPath.startsWith(filter) || path.startsWith(filter))
|
|
2744
|
+
return true;
|
|
2745
|
+
if (route.record.name && String(route.record.name).includes(filter))
|
|
2746
|
+
return true;
|
|
2747
|
+
return route.children.some(child => isRouteMatching(child, filter));
|
|
2748
|
+
}
|
|
2749
|
+
|
|
2750
|
+
/**
|
|
2751
|
+
* Creates a Router instance that can be used by a Kdu app.
|
|
2752
|
+
*
|
|
2753
|
+
* @param options - {@link RouterOptions}
|
|
2754
|
+
*/
|
|
2755
|
+
function createRouter(options) {
|
|
2756
|
+
const matcher = createRouterMatcher(options.routes, options);
|
|
2757
|
+
let parseQuery$1 = options.parseQuery || parseQuery;
|
|
2758
|
+
let stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
|
|
2759
|
+
let routerHistory = options.history;
|
|
2760
|
+
const beforeGuards = useCallbacks();
|
|
2761
|
+
const beforeResolveGuards = useCallbacks();
|
|
2762
|
+
const afterGuards = useCallbacks();
|
|
2763
|
+
const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
|
|
2764
|
+
let pendingLocation = START_LOCATION_NORMALIZED;
|
|
2765
|
+
// leave the scrollRestoration if no scrollBehavior is provided
|
|
2766
|
+
if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) {
|
|
2767
|
+
history.scrollRestoration = 'manual';
|
|
2768
|
+
}
|
|
2769
|
+
const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue);
|
|
2770
|
+
const encodeParams = applyToParams.bind(null, encodeParam);
|
|
2771
|
+
const decodeParams = applyToParams.bind(null, decode);
|
|
2772
|
+
function addRoute(parentOrRoute, route) {
|
|
2773
|
+
let parent;
|
|
2774
|
+
let record;
|
|
2775
|
+
if (isRouteName(parentOrRoute)) {
|
|
2776
|
+
parent = matcher.getRecordMatcher(parentOrRoute);
|
|
2777
|
+
record = route;
|
|
2778
|
+
}
|
|
2779
|
+
else {
|
|
2780
|
+
record = parentOrRoute;
|
|
2781
|
+
}
|
|
2782
|
+
return matcher.addRoute(record, parent);
|
|
2783
|
+
}
|
|
2784
|
+
function removeRoute(name) {
|
|
2785
|
+
let recordMatcher = matcher.getRecordMatcher(name);
|
|
2786
|
+
if (recordMatcher) {
|
|
2787
|
+
matcher.removeRoute(recordMatcher);
|
|
2788
|
+
}
|
|
2789
|
+
else {
|
|
2790
|
+
warn(`Cannot remove non-existent route "${String(name)}"`);
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
function getRoutes() {
|
|
2794
|
+
return matcher.getRoutes().map(routeMatcher => routeMatcher.record);
|
|
2795
|
+
}
|
|
2796
|
+
function hasRoute(name) {
|
|
2797
|
+
return !!matcher.getRecordMatcher(name);
|
|
2798
|
+
}
|
|
2799
|
+
function resolve(rawLocation, currentLocation) {
|
|
2800
|
+
// const objectLocation = routerLocationAsObject(rawLocation)
|
|
2801
|
+
// we create a copy to modify it later
|
|
2802
|
+
currentLocation = assign({}, currentLocation || currentRoute.value);
|
|
2803
|
+
if (typeof rawLocation === 'string') {
|
|
2804
|
+
let locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
|
|
2805
|
+
let matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation);
|
|
2806
|
+
let href = routerHistory.createHref(locationNormalized.fullPath);
|
|
2807
|
+
{
|
|
2808
|
+
if (href.startsWith('//'))
|
|
2809
|
+
warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
|
|
2810
|
+
else if (!matchedRoute.matched.length) {
|
|
2811
|
+
warn(`No match found for location with path "${rawLocation}"`);
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
// locationNormalized is always a new object
|
|
2815
|
+
return assign(locationNormalized, matchedRoute, {
|
|
2816
|
+
params: decodeParams(matchedRoute.params),
|
|
2817
|
+
hash: decode(locationNormalized.hash),
|
|
2818
|
+
redirectedFrom: undefined,
|
|
2819
|
+
href,
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
let matcherLocation;
|
|
2823
|
+
// path could be relative in object as well
|
|
2824
|
+
if ('path' in rawLocation) {
|
|
2825
|
+
if (
|
|
2826
|
+
'params' in rawLocation &&
|
|
2827
|
+
!('name' in rawLocation) &&
|
|
2828
|
+
Object.keys(rawLocation.params).length) {
|
|
2829
|
+
warn(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
|
|
2830
|
+
}
|
|
2831
|
+
matcherLocation = assign({}, rawLocation, {
|
|
2832
|
+
path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path,
|
|
2833
|
+
});
|
|
2834
|
+
}
|
|
2835
|
+
else {
|
|
2836
|
+
// pass encoded values to the matcher so it can produce encoded path and fullPath
|
|
2837
|
+
matcherLocation = assign({}, rawLocation, {
|
|
2838
|
+
params: encodeParams(rawLocation.params),
|
|
2839
|
+
});
|
|
2840
|
+
// current location params are decoded, we need to encode them in case the
|
|
2841
|
+
// matcher merges the params
|
|
2842
|
+
currentLocation.params = encodeParams(currentLocation.params);
|
|
2843
|
+
}
|
|
2844
|
+
let matchedRoute = matcher.resolve(matcherLocation, currentLocation);
|
|
2845
|
+
const hash = rawLocation.hash || '';
|
|
2846
|
+
if ( hash && !hash.startsWith('#')) {
|
|
2847
|
+
warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
|
|
2848
|
+
}
|
|
2849
|
+
// decoding them) the matcher might have merged current location params so
|
|
2850
|
+
// we need to run the decoding again
|
|
2851
|
+
matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
|
|
2852
|
+
const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
|
|
2853
|
+
hash: encodeHash(hash),
|
|
2854
|
+
path: matchedRoute.path,
|
|
2855
|
+
}));
|
|
2856
|
+
let href = routerHistory.createHref(fullPath);
|
|
2857
|
+
{
|
|
2858
|
+
if (href.startsWith('//')) {
|
|
2859
|
+
warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
|
|
2860
|
+
}
|
|
2861
|
+
else if (!matchedRoute.matched.length) {
|
|
2862
|
+
warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`);
|
|
2863
|
+
}
|
|
2864
|
+
}
|
|
2865
|
+
return assign({
|
|
2866
|
+
fullPath,
|
|
2867
|
+
// keep the hash encoded so fullPath is effectively path + encodedQuery +
|
|
2868
|
+
// hash
|
|
2869
|
+
hash,
|
|
2870
|
+
query:
|
|
2871
|
+
// if the user is using a custom query lib like qs, we might have
|
|
2872
|
+
// nested objects, so we keep the query as is, meaning it can contain
|
|
2873
|
+
// numbers at `$route.query`, but at the point, the user will have to
|
|
2874
|
+
// use their own type anyway.
|
|
2875
|
+
stringifyQuery$1 === stringifyQuery
|
|
2876
|
+
? normalizeQuery(rawLocation.query)
|
|
2877
|
+
: rawLocation.query,
|
|
2878
|
+
}, matchedRoute, {
|
|
2879
|
+
redirectedFrom: undefined,
|
|
2880
|
+
href,
|
|
2881
|
+
});
|
|
2882
|
+
}
|
|
2883
|
+
function locationAsObject(to) {
|
|
2884
|
+
return typeof to === 'string' ? { path: to } : assign({}, to);
|
|
2885
|
+
}
|
|
2886
|
+
function checkCanceledNavigation(to, from) {
|
|
2887
|
+
if (pendingLocation !== to) {
|
|
2888
|
+
return createRouterError(8 /* NAVIGATION_CANCELLED */, {
|
|
2889
|
+
from,
|
|
2890
|
+
to,
|
|
2891
|
+
});
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
function push(to) {
|
|
2895
|
+
return pushWithRedirect(to);
|
|
2896
|
+
}
|
|
2897
|
+
function replace(to) {
|
|
2898
|
+
return push(assign(locationAsObject(to), { replace: true }));
|
|
2899
|
+
}
|
|
2900
|
+
function handleRedirectRecord(to) {
|
|
2901
|
+
const lastMatched = to.matched[to.matched.length - 1];
|
|
2902
|
+
if (lastMatched && lastMatched.redirect) {
|
|
2903
|
+
const { redirect } = lastMatched;
|
|
2904
|
+
// transform it into an object to pass the original RouteLocaleOptions
|
|
2905
|
+
let newTargetLocation = locationAsObject(typeof redirect === 'function' ? redirect(to) : redirect);
|
|
2906
|
+
if (
|
|
2907
|
+
!('path' in newTargetLocation) &&
|
|
2908
|
+
!('name' in newTargetLocation)) {
|
|
2909
|
+
warn(`Invalid redirect found:\n${JSON.stringify(newTargetLocation, null, 2)}\n when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`);
|
|
2910
|
+
throw new Error('Invalid redirect');
|
|
2911
|
+
}
|
|
2912
|
+
return assign({
|
|
2913
|
+
query: to.query,
|
|
2914
|
+
hash: to.hash,
|
|
2915
|
+
params: to.params,
|
|
2916
|
+
}, newTargetLocation);
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
function pushWithRedirect(to, redirectedFrom) {
|
|
2920
|
+
const targetLocation = (pendingLocation = resolve(to));
|
|
2921
|
+
const from = currentRoute.value;
|
|
2922
|
+
const data = to.state;
|
|
2923
|
+
const force = to.force;
|
|
2924
|
+
// to could be a string where `replace` is a function
|
|
2925
|
+
const replace = to.replace === true;
|
|
2926
|
+
const shouldRedirect = handleRedirectRecord(targetLocation);
|
|
2927
|
+
if (shouldRedirect)
|
|
2928
|
+
return pushWithRedirect(assign(shouldRedirect, { state: data, force, replace }),
|
|
2929
|
+
// keep original redirectedFrom if it exists
|
|
2930
|
+
redirectedFrom || targetLocation);
|
|
2931
|
+
// if it was a redirect we already called `pushWithRedirect` above
|
|
2932
|
+
const toLocation = targetLocation;
|
|
2933
|
+
toLocation.redirectedFrom = redirectedFrom;
|
|
2934
|
+
let failure;
|
|
2935
|
+
if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
|
|
2936
|
+
failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from });
|
|
2937
|
+
// trigger scroll to allow scrolling to the same anchor
|
|
2938
|
+
handleScroll(from, from,
|
|
2939
|
+
// this is a push, the only way for it to be triggered from a
|
|
2940
|
+
// history.listen is with a redirect, which makes it become a push
|
|
2941
|
+
true,
|
|
2942
|
+
// This cannot be the first navigation because the initial location
|
|
2943
|
+
// cannot be manually navigated to
|
|
2944
|
+
false);
|
|
2945
|
+
}
|
|
2946
|
+
return (failure ? Promise.resolve(failure) : navigate(toLocation, from))
|
|
2947
|
+
.catch((error) => isNavigationFailure(error)
|
|
2948
|
+
? error
|
|
2949
|
+
: // reject any unknown error
|
|
2950
|
+
triggerError(error))
|
|
2951
|
+
.then((failure) => {
|
|
2952
|
+
if (failure) {
|
|
2953
|
+
if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
|
|
2954
|
+
if (
|
|
2955
|
+
// we are redirecting to the same location we were already at
|
|
2956
|
+
isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) &&
|
|
2957
|
+
// and we have done it a couple of times
|
|
2958
|
+
redirectedFrom &&
|
|
2959
|
+
// @ts-ignore
|
|
2960
|
+
(redirectedFrom._count = redirectedFrom._count
|
|
2961
|
+
? // @ts-ignore
|
|
2962
|
+
redirectedFrom._count + 1
|
|
2963
|
+
: 1) > 10) {
|
|
2964
|
+
warn(`Detected an infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow. This will break in production if not fixed.`);
|
|
2965
|
+
return Promise.reject(new Error('Infinite redirect in navigation guard'));
|
|
2966
|
+
}
|
|
2967
|
+
return pushWithRedirect(
|
|
2968
|
+
// keep options
|
|
2969
|
+
assign(locationAsObject(failure.to), {
|
|
2970
|
+
state: data,
|
|
2971
|
+
force,
|
|
2972
|
+
replace,
|
|
2973
|
+
}),
|
|
2974
|
+
// preserve the original redirectedFrom if any
|
|
2975
|
+
redirectedFrom || toLocation);
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
else {
|
|
2979
|
+
// if we fail we don't finalize the navigation
|
|
2980
|
+
failure = finalizeNavigation(toLocation, from, true, replace, data);
|
|
2981
|
+
}
|
|
2982
|
+
triggerAfterEach(toLocation, from, failure);
|
|
2983
|
+
return failure;
|
|
2984
|
+
});
|
|
2985
|
+
}
|
|
2986
|
+
/**
|
|
2987
|
+
* Helper to reject and skip all navigation guards if a new navigation happened
|
|
2988
|
+
* @param to
|
|
2989
|
+
* @param from
|
|
2990
|
+
*/
|
|
2991
|
+
function checkCanceledNavigationAndReject(to, from) {
|
|
2992
|
+
const error = checkCanceledNavigation(to, from);
|
|
2993
|
+
return error ? Promise.reject(error) : Promise.resolve();
|
|
2994
|
+
}
|
|
2995
|
+
// TODO: refactor the whole before guards by internally using router.beforeEach
|
|
2996
|
+
function navigate(to, from) {
|
|
2997
|
+
let guards;
|
|
2998
|
+
const [leavingRecords, updatingRecords, enteringRecords,] = extractChangingRecords(to, from);
|
|
2999
|
+
// all components here have been resolved once because we are leaving
|
|
3000
|
+
guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from);
|
|
3001
|
+
// leavingRecords is already reversed
|
|
3002
|
+
for (const record of leavingRecords) {
|
|
3003
|
+
record.leaveGuards.forEach(guard => {
|
|
3004
|
+
guards.push(guardToPromiseFn(guard, to, from));
|
|
3005
|
+
});
|
|
3006
|
+
}
|
|
3007
|
+
const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
|
|
3008
|
+
guards.push(canceledNavigationCheck);
|
|
3009
|
+
// run the queue of per route beforeRouteLeave guards
|
|
3010
|
+
return (runGuardQueue(guards)
|
|
3011
|
+
.then(() => {
|
|
3012
|
+
// check global guards beforeEach
|
|
3013
|
+
guards = [];
|
|
3014
|
+
for (const guard of beforeGuards.list()) {
|
|
3015
|
+
guards.push(guardToPromiseFn(guard, to, from));
|
|
3016
|
+
}
|
|
3017
|
+
guards.push(canceledNavigationCheck);
|
|
3018
|
+
return runGuardQueue(guards);
|
|
3019
|
+
})
|
|
3020
|
+
.then(() => {
|
|
3021
|
+
// check in components beforeRouteUpdate
|
|
3022
|
+
guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from);
|
|
3023
|
+
for (const record of updatingRecords) {
|
|
3024
|
+
record.updateGuards.forEach(guard => {
|
|
3025
|
+
guards.push(guardToPromiseFn(guard, to, from));
|
|
3026
|
+
});
|
|
3027
|
+
}
|
|
3028
|
+
guards.push(canceledNavigationCheck);
|
|
3029
|
+
// run the queue of per route beforeEnter guards
|
|
3030
|
+
return runGuardQueue(guards);
|
|
3031
|
+
})
|
|
3032
|
+
.then(() => {
|
|
3033
|
+
// check the route beforeEnter
|
|
3034
|
+
guards = [];
|
|
3035
|
+
for (const record of to.matched) {
|
|
3036
|
+
// do not trigger beforeEnter on reused views
|
|
3037
|
+
if (record.beforeEnter && from.matched.indexOf(record) < 0) {
|
|
3038
|
+
if (Array.isArray(record.beforeEnter)) {
|
|
3039
|
+
for (const beforeEnter of record.beforeEnter)
|
|
3040
|
+
guards.push(guardToPromiseFn(beforeEnter, to, from));
|
|
3041
|
+
}
|
|
3042
|
+
else {
|
|
3043
|
+
guards.push(guardToPromiseFn(record.beforeEnter, to, from));
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
guards.push(canceledNavigationCheck);
|
|
3048
|
+
// run the queue of per route beforeEnter guards
|
|
3049
|
+
return runGuardQueue(guards);
|
|
3050
|
+
})
|
|
3051
|
+
.then(() => {
|
|
3052
|
+
// NOTE: at this point to.matched is normalized and does not contain any () => Promise<Component>
|
|
3053
|
+
// clear existing enterCallbacks, these are added by extractComponentsGuards
|
|
3054
|
+
to.matched.forEach(record => (record.enterCallbacks = {}));
|
|
3055
|
+
// check in-component beforeRouteEnter
|
|
3056
|
+
guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from);
|
|
3057
|
+
guards.push(canceledNavigationCheck);
|
|
3058
|
+
// run the queue of per route beforeEnter guards
|
|
3059
|
+
return runGuardQueue(guards);
|
|
3060
|
+
})
|
|
3061
|
+
.then(() => {
|
|
3062
|
+
// check global guards beforeResolve
|
|
3063
|
+
guards = [];
|
|
3064
|
+
for (const guard of beforeResolveGuards.list()) {
|
|
3065
|
+
guards.push(guardToPromiseFn(guard, to, from));
|
|
3066
|
+
}
|
|
3067
|
+
guards.push(canceledNavigationCheck);
|
|
3068
|
+
return runGuardQueue(guards);
|
|
3069
|
+
})
|
|
3070
|
+
// catch any navigation canceled
|
|
3071
|
+
.catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */)
|
|
3072
|
+
? err
|
|
3073
|
+
: Promise.reject(err)));
|
|
3074
|
+
}
|
|
3075
|
+
function triggerAfterEach(to, from, failure) {
|
|
3076
|
+
// navigation is confirmed, call afterGuards
|
|
3077
|
+
// TODO: wrap with error handlers
|
|
3078
|
+
for (const guard of afterGuards.list())
|
|
3079
|
+
guard(to, from, failure);
|
|
3080
|
+
}
|
|
3081
|
+
/**
|
|
3082
|
+
* - Cleans up any navigation guards
|
|
3083
|
+
* - Changes the url if necessary
|
|
3084
|
+
* - Calls the scrollBehavior
|
|
3085
|
+
*/
|
|
3086
|
+
function finalizeNavigation(toLocation, from, isPush, replace, data) {
|
|
3087
|
+
// a more recent navigation took place
|
|
3088
|
+
const error = checkCanceledNavigation(toLocation, from);
|
|
3089
|
+
if (error)
|
|
3090
|
+
return error;
|
|
3091
|
+
// only consider as push if it's not the first navigation
|
|
3092
|
+
const isFirstNavigation = from === START_LOCATION_NORMALIZED;
|
|
3093
|
+
const state = !isBrowser ? {} : history.state;
|
|
3094
|
+
// change URL only if the user did a push/replace and if it's not the initial navigation because
|
|
3095
|
+
// it's just reflecting the url
|
|
3096
|
+
if (isPush) {
|
|
3097
|
+
// on the initial navigation, we want to reuse the scroll position from
|
|
3098
|
+
// history state if it exists
|
|
3099
|
+
if (replace || isFirstNavigation)
|
|
3100
|
+
routerHistory.replace(toLocation.fullPath, assign({
|
|
3101
|
+
scroll: isFirstNavigation && state && state.scroll,
|
|
3102
|
+
}, data));
|
|
3103
|
+
else
|
|
3104
|
+
routerHistory.push(toLocation.fullPath, data);
|
|
3105
|
+
}
|
|
3106
|
+
// accept current navigation
|
|
3107
|
+
currentRoute.value = toLocation;
|
|
3108
|
+
handleScroll(toLocation, from, isPush, isFirstNavigation);
|
|
3109
|
+
markAsReady();
|
|
3110
|
+
}
|
|
3111
|
+
let removeHistoryListener;
|
|
3112
|
+
// attach listener to history to trigger navigations
|
|
3113
|
+
function setupListeners() {
|
|
3114
|
+
removeHistoryListener = routerHistory.listen((to, _from, info) => {
|
|
3115
|
+
// cannot be a redirect route because it was in history
|
|
3116
|
+
let toLocation = resolve(to);
|
|
3117
|
+
// due to dynamic routing, and to hash history with manual navigation
|
|
3118
|
+
// (manually changing the url or calling history.hash = '#/somewhere'),
|
|
3119
|
+
// there could be a redirect record in history
|
|
3120
|
+
const shouldRedirect = handleRedirectRecord(toLocation);
|
|
3121
|
+
if (shouldRedirect) {
|
|
3122
|
+
pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop);
|
|
3123
|
+
return;
|
|
3124
|
+
}
|
|
3125
|
+
pendingLocation = toLocation;
|
|
3126
|
+
const from = currentRoute.value;
|
|
3127
|
+
// TODO: should be moved to web history?
|
|
3128
|
+
if (isBrowser) {
|
|
3129
|
+
saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
|
|
3130
|
+
}
|
|
3131
|
+
navigate(toLocation, from)
|
|
3132
|
+
.catch((error) => {
|
|
3133
|
+
if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) {
|
|
3134
|
+
return error;
|
|
3135
|
+
}
|
|
3136
|
+
if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
|
|
3137
|
+
// do not restore history on unknown direction
|
|
3138
|
+
if (info.delta)
|
|
3139
|
+
routerHistory.go(-info.delta, false);
|
|
3140
|
+
// the error is already handled by router.push we just want to avoid
|
|
3141
|
+
// logging the error
|
|
3142
|
+
pushWithRedirect(
|
|
3143
|
+
// TODO: should we force replace: true
|
|
3144
|
+
error.to, toLocation
|
|
3145
|
+
// avoid an uncaught rejection, let push call triggerError
|
|
3146
|
+
).catch(noop);
|
|
3147
|
+
// avoid the then branch
|
|
3148
|
+
return Promise.reject();
|
|
3149
|
+
}
|
|
3150
|
+
// do not restore history on unknown direction
|
|
3151
|
+
if (info.delta)
|
|
3152
|
+
routerHistory.go(-info.delta, false);
|
|
3153
|
+
// unrecognized error, transfer to the global handler
|
|
3154
|
+
return triggerError(error);
|
|
3155
|
+
})
|
|
3156
|
+
.then((failure) => {
|
|
3157
|
+
failure =
|
|
3158
|
+
failure ||
|
|
3159
|
+
finalizeNavigation(
|
|
3160
|
+
// after navigation, all matched components are resolved
|
|
3161
|
+
toLocation, from, false);
|
|
3162
|
+
// revert the navigation
|
|
3163
|
+
if (failure && info.delta)
|
|
3164
|
+
routerHistory.go(-info.delta, false);
|
|
3165
|
+
triggerAfterEach(toLocation, from, failure);
|
|
3166
|
+
})
|
|
3167
|
+
.catch(noop);
|
|
3168
|
+
});
|
|
3169
|
+
}
|
|
3170
|
+
// Initialization and Errors
|
|
3171
|
+
let readyHandlers = useCallbacks();
|
|
3172
|
+
let errorHandlers = useCallbacks();
|
|
3173
|
+
let ready;
|
|
3174
|
+
/**
|
|
3175
|
+
* Trigger errorHandlers added via onError and throws the error as well
|
|
3176
|
+
* @param error - error to throw
|
|
3177
|
+
* @returns the error as a rejected promise
|
|
3178
|
+
*/
|
|
3179
|
+
function triggerError(error) {
|
|
3180
|
+
markAsReady(error);
|
|
3181
|
+
errorHandlers.list().forEach(handler => handler(error));
|
|
3182
|
+
return Promise.reject(error);
|
|
3183
|
+
}
|
|
3184
|
+
function isReady() {
|
|
3185
|
+
if (ready && currentRoute.value !== START_LOCATION_NORMALIZED)
|
|
3186
|
+
return Promise.resolve();
|
|
3187
|
+
return new Promise((resolve, reject) => {
|
|
3188
|
+
readyHandlers.add([resolve, reject]);
|
|
3189
|
+
});
|
|
3190
|
+
}
|
|
3191
|
+
/**
|
|
3192
|
+
* Mark the router as ready, resolving the promised returned by isReady(). Can
|
|
3193
|
+
* only be called once, otherwise does nothing.
|
|
3194
|
+
* @param err - optional error
|
|
3195
|
+
*/
|
|
3196
|
+
function markAsReady(err) {
|
|
3197
|
+
if (ready)
|
|
3198
|
+
return;
|
|
3199
|
+
ready = true;
|
|
3200
|
+
setupListeners();
|
|
3201
|
+
readyHandlers
|
|
3202
|
+
.list()
|
|
3203
|
+
.forEach(([resolve, reject]) => (err ? reject(err) : resolve()));
|
|
3204
|
+
readyHandlers.reset();
|
|
3205
|
+
}
|
|
3206
|
+
// Scroll behavior
|
|
3207
|
+
function handleScroll(to, from, isPush, isFirstNavigation) {
|
|
3208
|
+
const { scrollBehavior } = options;
|
|
3209
|
+
if (!isBrowser || !scrollBehavior)
|
|
3210
|
+
return Promise.resolve();
|
|
3211
|
+
let scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) ||
|
|
3212
|
+
((isFirstNavigation || !isPush) &&
|
|
3213
|
+
history.state &&
|
|
3214
|
+
history.state.scroll) ||
|
|
3215
|
+
null;
|
|
3216
|
+
return nextTick()
|
|
3217
|
+
.then(() => scrollBehavior(to, from, scrollPosition))
|
|
3218
|
+
.then(position => position && scrollToPosition(position))
|
|
3219
|
+
.catch(triggerError);
|
|
3220
|
+
}
|
|
3221
|
+
const go = (delta) => routerHistory.go(delta);
|
|
3222
|
+
let started;
|
|
3223
|
+
const installedApps = new Set();
|
|
3224
|
+
const router = {
|
|
3225
|
+
currentRoute,
|
|
3226
|
+
addRoute,
|
|
3227
|
+
removeRoute,
|
|
3228
|
+
hasRoute,
|
|
3229
|
+
getRoutes,
|
|
3230
|
+
resolve,
|
|
3231
|
+
options,
|
|
3232
|
+
push,
|
|
3233
|
+
replace,
|
|
3234
|
+
go,
|
|
3235
|
+
back: () => go(-1),
|
|
3236
|
+
forward: () => go(1),
|
|
3237
|
+
beforeEach: beforeGuards.add,
|
|
3238
|
+
beforeResolve: beforeResolveGuards.add,
|
|
3239
|
+
afterEach: afterGuards.add,
|
|
3240
|
+
onError: errorHandlers.add,
|
|
3241
|
+
isReady,
|
|
3242
|
+
install(app) {
|
|
3243
|
+
const router = this;
|
|
3244
|
+
app.component('RouterLink', RouterLink);
|
|
3245
|
+
app.component('RouterView', RouterView);
|
|
3246
|
+
app.config.globalProperties.$router = router;
|
|
3247
|
+
Object.defineProperty(app.config.globalProperties, '$route', {
|
|
3248
|
+
get: () => unref(currentRoute),
|
|
3249
|
+
});
|
|
3250
|
+
// this initial navigation is only necessary on client, on server it doesn't
|
|
3251
|
+
// make sense because it will create an extra unnecessary navigation and could
|
|
3252
|
+
// lead to problems
|
|
3253
|
+
if (isBrowser &&
|
|
3254
|
+
// used for the initial navigation client side to avoid pushing
|
|
3255
|
+
// multiple times when the router is used in multiple apps
|
|
3256
|
+
!started &&
|
|
3257
|
+
currentRoute.value === START_LOCATION_NORMALIZED) {
|
|
3258
|
+
// see above
|
|
3259
|
+
started = true;
|
|
3260
|
+
push(routerHistory.location).catch(err => {
|
|
3261
|
+
warn('Unexpected error when starting the router:', err);
|
|
3262
|
+
});
|
|
3263
|
+
}
|
|
3264
|
+
const reactiveRoute = {};
|
|
3265
|
+
for (let key in START_LOCATION_NORMALIZED) {
|
|
3266
|
+
// @ts-ignore: the key matches
|
|
3267
|
+
reactiveRoute[key] = computed(() => currentRoute.value[key]);
|
|
3268
|
+
}
|
|
3269
|
+
app.provide(routerKey, router);
|
|
3270
|
+
app.provide(routeLocationKey, reactive(reactiveRoute));
|
|
3271
|
+
app.provide(routerViewLocationKey, currentRoute);
|
|
3272
|
+
let unmountApp = app.unmount;
|
|
3273
|
+
installedApps.add(app);
|
|
3274
|
+
app.unmount = function () {
|
|
3275
|
+
installedApps.delete(app);
|
|
3276
|
+
if (installedApps.size < 1) {
|
|
3277
|
+
removeHistoryListener();
|
|
3278
|
+
currentRoute.value = START_LOCATION_NORMALIZED;
|
|
3279
|
+
started = false;
|
|
3280
|
+
ready = false;
|
|
3281
|
+
}
|
|
3282
|
+
unmountApp.call(this, arguments);
|
|
3283
|
+
};
|
|
3284
|
+
{
|
|
3285
|
+
addDevtools(app, router, matcher);
|
|
3286
|
+
}
|
|
3287
|
+
},
|
|
3288
|
+
};
|
|
3289
|
+
return router;
|
|
3290
|
+
}
|
|
3291
|
+
function runGuardQueue(guards) {
|
|
3292
|
+
return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve());
|
|
3293
|
+
}
|
|
3294
|
+
function extractChangingRecords(to, from) {
|
|
3295
|
+
const leavingRecords = [];
|
|
3296
|
+
const updatingRecords = [];
|
|
3297
|
+
const enteringRecords = [];
|
|
3298
|
+
const len = Math.max(from.matched.length, to.matched.length);
|
|
3299
|
+
for (let i = 0; i < len; i++) {
|
|
3300
|
+
const recordFrom = from.matched[i];
|
|
3301
|
+
if (recordFrom) {
|
|
3302
|
+
if (to.matched.indexOf(recordFrom) < 0)
|
|
3303
|
+
leavingRecords.push(recordFrom);
|
|
3304
|
+
else
|
|
3305
|
+
updatingRecords.push(recordFrom);
|
|
3306
|
+
}
|
|
3307
|
+
const recordTo = to.matched[i];
|
|
3308
|
+
if (recordTo) {
|
|
3309
|
+
// the type doesn't matter because we are comparing per reference
|
|
3310
|
+
if (from.matched.indexOf(recordTo) < 0)
|
|
3311
|
+
enteringRecords.push(recordTo);
|
|
3312
|
+
}
|
|
3313
|
+
}
|
|
3314
|
+
return [leavingRecords, updatingRecords, enteringRecords];
|
|
3315
|
+
}
|
|
3316
|
+
|
|
3317
|
+
/**
|
|
3318
|
+
* Returns the router instance. Equivalent to using `$router` inside
|
|
3319
|
+
* templates.
|
|
3320
|
+
*/
|
|
3321
|
+
function useRouter() {
|
|
3322
|
+
return inject(routerKey);
|
|
3323
|
+
}
|
|
3324
|
+
/**
|
|
3325
|
+
* Returns the current route location. Equivalent to using `$route` inside
|
|
3326
|
+
* templates.
|
|
3327
|
+
*/
|
|
3328
|
+
function useRoute() {
|
|
3329
|
+
return inject(routeLocationKey);
|
|
3330
|
+
}
|
|
3331
|
+
|
|
3332
|
+
export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey };
|