Repository navigation
Expand file tree
/
Copy pathrouter.js
More file actions
executable file
·1625 lines (1471 loc) · 56.9 KB
/
Copy pathrouter.js
File metadata and controls
executable file
·1625 lines (1471 loc) · 56.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
createCache,
each,
extend,
inArray,
isEqual,
isFunction,
isPlainObject,
isPromise,
isString,
noop,
toBoolean,
toDate,
toDuration,
toNumber,
toString,
wait,
} from '@semantic-ui/utils';
import { isLazy } from './helpers/lazy.js';
import { setRouter } from './helpers/router.js';
import { IS_ROUTER } from './internal-helpers/identity.js';
import { Navigator } from './navigator.js';
import { Route } from './route.js';
import { DomView } from './view.js';
// what a data() returns through notFound(), at navigation or on the standing page
const NOT_FOUND = Symbol('notFound');
export class Router {
/*******************************
Integration
*******************************/
// what an integration's router overrides: the view it renders with, and how a moment is held
// the view a route's layout, slots and page are made with. the native one by default, functions
// returning markup or nodes, so a plain app renders from one import; an integration's router
// names its own. where there is no document, a server or a test, there is no page to render to
// and so no view
static View = globalThis.document ? DomView : null;
// writes that belong together, one moment to anything watching: the page's write, its settle
// and its render. nothing here, where nothing watches. a reactive router holds its notifications
// to the end, and a renderer with its own schedule commits the page once
batch(fn) {
return fn();
}
// brand router
get [IS_ROUTER]() {
return true;
}
static [Symbol.hasInstance](value) {
return !!value?.[IS_ROUTER];
}
static defaults = {
base: '',
// where the app goes on the page, a selector or an element
mount: 'body',
signInRoute: null,
// the user the guards read: a value, or a function of the navigation returning one or a promise of one
identity: null,
holdCommit: '300ms',
loadingDelay: '200ms',
loadingMin: '500ms',
restoreScroll: null,
attachGlobal: 'router',
// the one state key declared here: the user the guards read, which the identity door writes
// after this, so config shows the one the router started with
user: null,
onRender: null,
onChange: null,
// every error the router meets, a navigation that fails or a view that fails to render, with
// the context of the route it was met at when there is one. logged, unless the app says otherwise
onError: (error) => console.error(error),
// whether data recomputed outside a navigation moved: a deep compare, since a render costs more
// than the walk. plain data asks it of the whole entry, and a reactive entry asks its cells instead
dataChanged: (previous, next) => !isEqual(next, previous),
};
// one bag: the keys the defaults declare are the router's settings, every other key is the root
// route's, so the router holds nothing of a route's and the root nothing of the router's. a key
// neither knows lands on the root, unchecked, as it landed on the router before
constructor(options = {}) {
const defaults = new.target.defaults; // new.target so a subclass can declare its own defaults
const settings = {};
const routeOptions = {};
each(options, (value, key) => {
const owner = key in defaults ? settings : routeOptions;
owner[key] = value;
});
// the resolved settings, read from here and nowhere else; a plugin's default lands here too
this.config = extend({}, defaults, settings);
this.config.base = this.normalizeBase(this.config.base);
// not settings, though declared among the defaults so the constructor keeps them from the root
// route: the user is state the identity door writes, the callbacks are the app's to assign
this.user = this.config.user;
this.onRender = this.config.onRender;
this.onChange = this.config.onChange;
this.onError = this.config.onError;
this.routesByName = new Map();
this.leaves = [];
this.root = new Route({ ...routeOptions, isSection: true }, null, this);
this.current = null;
this.page = null;
this.pending = null;
this.error = null;
this.entryCache = createCache({ maxSize: 100 });
this.timers = new Set();
this.listeners = new Set();
this.initialAbort = null;
this.navigator = new Navigator(this);
}
// the tree is built on the root, through the router
index(options) {
return this.root.index(options);
}
section(options) {
return this.root.section(options);
}
route(options) {
return this.root.route(options);
}
normalizeBase(base) {
if (!base || base === '/') {
return '';
}
const withLeading = base.startsWith('/') ? base : `/${base}`;
return withLeading.endsWith('/') ? withLeading.slice(0, -1) : withLeading;
}
/*******************************
Lifecycle
*******************************/
async start() {
this.navigator.attach();
// the helpers reach the started router. one per document is the common case, so it also lives
// on window under this name for the console; a second router names itself otherwise
setRouter(this);
if (this.config.attachGlobal && globalThis.window) {
globalThis[this.config.attachGlobal] = this;
}
const initialUrl = this.navigator.entry?.url
?? globalThis.location?.href
?? (this.config.base || '/');
const matched = this.match(initialUrl);
this.commitRoute(matched);
this.initialAbort?.abort();
const controller = new AbortController();
this.initialAbort = controller;
// the one navigation the platform fires no event for: the same entering flow, a stand-in event
const event = {
initial: true,
navigationType: this.navigator.activation?.navigationType ?? 'push',
destination: { key: null },
signal: controller.signal,
};
try {
if (matched) {
this.setPending(matched, event.navigationType);
await this.afterCommit(this.begin(matched, event), event, { precommitRan: false });
}
else {
await this.applyNotFound(initialUrl, event);
// a route for the url may have been added while the not-found page loaded
this.routeAdded();
}
}
catch (error) {
if (!controller.signal.aborted) {
this.failed(error, event);
}
}
if (!controller.signal.aborted) {
this.pending = null;
this.notify();
}
return this;
}
// no route for the url: the root runs its entry as the routes above a refusal do, the user read
// first, so a root with data frames the cold not-found with what it reads
async applyNotFound(url, event) {
const navigation = { signal: event.signal, reload: false, previous: null };
// no route matched, so the page has none of its own
const matched = { url, params: {}, query: {}, routes: [] };
await this.resolveIdentity(navigation);
const [view, views, { activeRoutes, error }] = await Promise.all([
this.resolveStatusView(this.root, 'notFound'),
this.resolveRouteViews([this.root]),
this.loadRoutes([this.root], matched, navigation),
]);
if (error) {
throw error;
}
if (event.signal.aborted) {
return;
}
await this.applyCascade(matched, { status: 'notFound', view, views, activeRoutes }, event);
}
// a route was added: a page standing as not-found for want of a route is matched again a
// microtask later, when every route added with it is in, so a package that arrives late claims
// its own urls. the reload it starts is pending at once, so routes added together reload once
routeAdded() {
const { page } = this;
if (page?.status === 'notFound' && !page.route) {
queueMicrotask(() => !this.pending && this.match(page.url) && this.reload());
}
}
stop() {
this.navigator.detach();
setRouter(null);
if (this.config.attachGlobal && globalThis[this.config.attachGlobal] === this) {
delete globalThis[this.config.attachGlobal];
}
this.initialAbort?.abort();
this.initialAbort = null;
each(this.timers, (timer) => clearTimeout(timer));
this.timers.clear();
each(
[...(this.page?.activeRoutes ?? [])].reverse(),
({ route }) => this.destroyRoute(route, this.lifecycleContext(route, null)),
);
this.clearMountView();
this.page =
this.current =
this.pending =
this.error =
null;
this.entryCache?.clear();
}
/*******************************
Reads
*******************************/
match(url) {
if (url == null) {
return null;
}
const origin = globalThis.location?.origin ?? 'http://localhost';
let parsed;
let urlSegments;
try {
parsed = url instanceof URL ? url : new URL(String(url), origin);
// another origin is never ours, and a malformed escape is no path of ours either
if (parsed.origin !== origin) {
return null;
}
const pathname = this.stripBase(parsed.pathname);
if (pathname === null) {
return null;
}
parsed.strippedPathname = pathname;
urlSegments = pathname === '/' ? [] : pathname.slice(1).split('/').map((part) => decodeURIComponent(part));
}
catch {
return null;
}
const pathname = parsed.strippedPathname;
let bestLeaf = null;
let bestParams = null;
let bestScores = null;
each(this.leaves, (leaf) => {
const candidate = this.matchLeaf(leaf, urlSegments);
if (candidate && (!bestLeaf || this.compareScores(candidate.scores, bestScores) > 0)) {
bestLeaf = leaf;
bestParams = candidate.params;
bestScores = candidate.scores;
}
});
if (!bestLeaf) {
return null;
}
const query = this.coerceQuery(bestLeaf, parsed.searchParams);
const routes = [...bestLeaf.ancestors];
return {
route: bestLeaf,
url: parsed.href,
pathname,
search: parsed.search,
hash: parsed.hash,
params: bestParams,
query,
routes,
redirect: bestLeaf.redirect ?? null,
};
}
stripBase(rawPathname) {
if (!this.config.base) {
return this.normalizePathname(rawPathname);
}
if (rawPathname === this.config.base) {
return '/';
}
if (rawPathname.startsWith(`${this.config.base}/`)) {
return this.normalizePathname(rawPathname.slice(this.config.base.length));
}
return null;
}
normalizePathname(pathname) {
if (!pathname || pathname === '/') {
return '/';
}
const withLeading = pathname.startsWith('/') ? pathname : `/${pathname}`;
return withLeading.length > 1 && withLeading.endsWith('/')
? withLeading.slice(0, -1)
: withLeading;
}
matchLeaf(leaf, urlSegments) {
const patternSegments = leaf.segments;
if (urlSegments.length > patternSegments.length && patternSegments.at(-1) !== '*') {
return null;
}
const params = {};
const scores = [];
for (let index = 0; index < patternSegments.length; index++) {
const pattern = patternSegments[index];
const segment = urlSegments[index];
if (pattern === '*') {
// the rest takes the lowest rung, and empty it ranks below a route that ends here
params['*'] = urlSegments.slice(index).join('/');
scores.push(segment !== undefined ? 1 : -2);
break;
}
if (!pattern.startsWith(':')) {
if (segment !== pattern) {
return null;
}
scores.push(5);
continue;
}
const isOptionalFlag = pattern.endsWith('?');
const paramName = pattern.slice(1).replace(/\?$/, '');
const spec = leaf.paramSpecs[paramName];
if (segment !== undefined) {
const coerced = this.coerceValue(segment, spec);
if (
coerced === null || (spec?.allowed && !inArray(coerced, spec.allowed))
|| (spec?.validator && !spec.validator(coerced))
) {
return null;
}
params[paramName] = coerced;
// an allowed set beats a typed or validated param beats a bare one, so siblings on one segment resolve by what they claim
scores.push(
spec?.allowed
? 4
: (spec?.validator || (spec?.type && spec.type !== String && spec.type !== 'string') ? 3 : 2),
);
}
else if (spec?.default !== undefined) {
params[paramName] = spec.default;
scores.push(-1);
}
else if (isOptionalFlag) {
params[paramName] = undefined;
scores.push(-1);
}
else {
return null;
}
}
each(leaf.paramSpecs, (spec, key) => {
if (params[key] === undefined && spec.default !== undefined) {
params[key] = spec.default;
}
});
return { params, scores };
}
compareScores(scoresA, scoresB) {
const maxLength = Math.max(scoresA.length, scoresB.length);
for (let index = 0; index < maxLength; index++) {
const diff = (scoresA[index] ?? 0) - (scoresB[index] ?? 0);
if (diff !== 0) {
return diff;
}
}
return 0;
}
coerceQuery(leaf, searchParams) {
const query = {};
each(leaf.querySpecs, (spec, key) => {
if (spec.default !== undefined) {
query[key] = spec.default;
}
});
for (const [key, rawValue] of searchParams.entries()) {
// the return address is a path on this origin, declared or not
if (key === 'returnTo' && !(rawValue.startsWith('/') && this.sameOrigin(rawValue))) {
continue;
}
const spec = leaf.querySpecs[key];
if (!spec) {
query[key] = toString(rawValue);
continue;
}
const isFlag = (spec.type === Boolean || spec.type === 'boolean') && rawValue === '';
const coerced = isFlag ? true : this.coerceValue(rawValue, spec);
query[key] = (coerced === null || (spec.allowed && !inArray(coerced, spec.allowed))
|| (spec.validator && !spec.validator(coerced)))
? spec.default
: coerced;
}
return query;
}
sameOrigin(url) {
const origin = globalThis.location?.origin ?? 'http://localhost';
try {
return new URL(url, origin).origin === origin;
}
catch {
return false;
}
}
coerceValue(rawValue, spec) {
const type = spec?.type ?? String;
if (type === Boolean || type === 'boolean') { return toBoolean(rawValue); }
if (type === Number || type === 'number') { return toNumber(rawValue); }
if (type === Date || type === 'date') { return toDate(rawValue); }
return toString(rawValue);
}
// a route by name, a Route, or a literal path. args is one flat bag: a key the route declares as a
// param fills the path, every other key is query. the fragment and the origin are options
href(target, args = {}, { hash, absolute = false, keepQuery = false } = {}) {
const route = this.routeFor(target);
const { params, query: own } = this.splitArgs(route, args);
const query = keepQuery ? { ...this.current?.query, ...own } : own;
let rawPath = route ? route.path : '/';
// a literal is a url: another origin or a path outside base passes through whole, its own query and fragment ride
if (!route && isString(target) && target) {
const origin = globalThis.location?.origin ?? 'http://localhost';
const literal = new URL(target, globalThis.location?.href ?? origin);
const stripped = literal.origin === origin ? this.stripBase(literal.pathname) : null;
if (stripped === null) {
return target;
}
rawPath = stripped;
literal.searchParams.forEach((value, key) => {
query[key] ??= value;
});
hash ??= literal.hash.slice(1) || undefined;
}
const segments = rawPath === '/' ? [] : rawPath.replace(/^\//, '').split('/');
const valueFor = (paramName) => params[paramName] ?? route.paramSpecs[paramName]?.default;
const resolvedSegments = [];
for (let index = 0; index < segments.length; index++) {
const segment = segments[index];
// a literal is literal: nothing in it expands
if (!route) {
resolvedSegments.push(segment);
continue;
}
if (segment === '*') {
resolvedSegments.push(...String(params['*'] ?? '').split('/').filter(Boolean).map(encodeURIComponent));
continue;
}
if (!segment.startsWith(':')) {
resolvedSegments.push(segment);
continue;
}
const isOptionalFlag = segment.endsWith('?');
const paramName = segment.slice(1).replace(/\?$/, '');
const value = valueFor(paramName);
if (value === undefined || value === null) {
// an optional leaves the path only with every segment after it, or what follows would read back in its place
const restOmitted = segments.slice(index + 1).every((later) =>
later === '*' ? !params['*'] : later.endsWith('?') && valueFor(later.slice(1, -1)) == null
);
if (isOptionalFlag && restOmitted) {
continue;
}
throw new Error(`Router.href: missing required param "${paramName}" for "${route?.name ?? target}"`);
}
resolvedSegments.push(encodeURIComponent(this.formatParamValue(value)));
}
const pathname = `/${resolvedSegments.join('/')}`;
const pairs = [];
each(query, (value, key) => {
const spec = route?.querySpecs[key];
// a value equal to its default leaves the url, and a declared boolean's true is the bare key
if (value === undefined || value === null || isEqual(value, spec?.default)) {
return;
}
const bare = value === true && (spec?.type === Boolean || spec?.type === 'boolean');
pairs.push(
bare
? encodeURIComponent(key)
: `${encodeURIComponent(key)}=${encodeURIComponent(this.formatParamValue(value))}`,
);
});
const search = pairs.join('&');
const path = this.prependBase(search ? `${pathname}?${search}` : pathname) + (hash ? `#${hash}` : '');
return absolute && globalThis.location ? new URL(path, globalThis.location.origin).href : path;
}
// the names people reach for; one implementation
urlFor(...args) {
return this.href(...args);
}
url(...args) {
return this.href(...args);
}
// a name, a Route, or nothing: a literal path has no route and keeps every arg as query
routeFor(target) {
if (target === this) {
return this.root;
}
if (target instanceof Route) {
return target;
}
const named = isString(target) ? this.routesByName.get(target) : null;
return named ? (named.indexRoute ?? named) : null;
}
splitArgs(route, args = {}) {
const params = {};
const query = {};
each(args, (value, key) => {
if (route && key in route.paramSpecs) {
params[key] = value;
}
else {
query[key] = value;
}
});
return { params, query };
}
// the args a redirect carries: the current params the target also declares
paramsFor(target, params = {}) {
const route = this.routeFor(target);
const carried = {};
each(params, (value, key) => {
if (route && key in route.paramSpecs) {
carried[key] = value;
}
});
return carried;
}
formatParamValue(value) {
return value instanceof Date ? value.toISOString() : String(value);
}
prependBase(path) {
if (!this.config.base) { return path; }
if (path === '/') { return this.config.base; }
return path.startsWith('/') ? `${this.config.base}${path}` : `${this.config.base}/${path}`;
}
// the address a sign-in redirect carries back: a path under base, so the sign-in page can navigate to it
returnAddress({ pathname, search, hash }) {
return `${this.prependBase(pathname)}${search}${hash}`;
}
argsMatch(route, args) {
const { params, query } = this.splitArgs(route, args);
return Object.keys(params).every((key) => isEqual(this.current.params[key], params[key]))
&& Object.keys(query).every((key) => isEqual(this.current.query[key], query[key]));
}
get canGoBack() {
return this.navigator.canGoBack;
}
get canGoForward() {
return this.navigator.canGoForward;
}
get entry() {
return this.navigator.entry;
}
get entries() {
return this.navigator.entries;
}
get activation() {
return this.navigator.activation;
}
get transition() {
return this.navigator.transition;
}
/*******************************
Writes
*******************************/
navigate(
target,
args = {},
{ history = 'auto', state, info, resetScroll = true, resetFocus = true, hash, keepQuery, absolute } = {},
) {
return this.navigator.navigate(this.href(target, args, { hash, keepQuery, absolute }), {
state,
info,
history,
resetScroll,
resetFocus,
});
}
reload(options) {
return this.navigator.reload(options);
}
back(fallback = this.root.name, args = {}) {
return this.navigator.back(fallback ? this.href(fallback, args) : (this.config.base || '/'));
}
forward() {
return this.navigator.forward();
}
traverseTo(key, options) {
return this.navigator.traverseTo(key, options);
}
/*******************************
Moments
*******************************/
// the navigator hands each platform moment here by name: the only writers of the router's state
intercepted(matched, event) {
// the initial load is the one navigation the platform holds no signal for
this.initialAbort?.abort();
this.initialAbort = null;
this.setPending(matched, event.navigationType);
this.notify();
}
// the platform runs one navigation at a time, so pending is one match
setPending(matched, navigationType) {
this.pending = matched
? {
route: matched.route,
url: matched.url,
params: matched.params,
query: matched.query,
routes: matched.routes,
navigationType,
loading: false,
committed: false,
}
: null;
}
entryChanged(entry, event) {
// a state-only change, such as scroll memory, moves no route and says nothing
if (event?.navigationType === null) {
return;
}
if (this.pending) {
this.pending = { ...this.pending, committed: true };
}
const matched = this.match(entry?.url);
if (matched) {
this.commitRoute(matched);
}
else {
this.notify();
}
}
settled(event) {
this.pending = null;
this.error = null;
this.notify();
}
async failed(error, event) {
const pending = this.pending;
this.pending = null;
// a superseded, cancelled or refused navigation is not an error to show
if (error?.name === 'AbortError') {
// the loading view it showed leaves, the standing page's own view comes back
if (pending?.loading && this.page) {
this.renderPage(this.page).catch(noop);
}
this.notify();
return;
}
this.error = {
error,
// transition is still set inside navigateerror, and its from is the last page that settled
from: globalThis.navigation?.transition?.from ?? null,
url: pending?.url ?? this.navigator.entry?.url ?? null,
};
// a route's failed load was handed to onError as it failed, and its error page stands
if (this.page?.error === error) {
this.notify();
return;
}
this.onError(error, pending && this.contextFor(pending.route, pending));
// a failure before commit left the standing page in place; only a committed one is shown as an error
if (!pending || pending.committed) {
const previous = this.page;
// the error view nearest the route the navigation was going to
const route = pending?.route ?? previous?.route ?? this.root;
const view = await this.resolveStatusView(route, 'error').catch(() => null);
// the routes on screen stay active under the error page. a cold error, nothing yet shown, is
// framed by the root when it has no data of its own, since the data that failed may be the
// root's, and stands at the mount with no route active otherwise
const views = previous?.views ?? await this.resolveRouteViews([this.root]).catch(() => []);
// a newer navigation began or landed while the views loaded: the error page is not this one's
// to write. a navigation that failed is finished, so its signal says nothing of what came after
if (this.pending || this.page !== previous) {
return;
}
const activeRoutes = previous?.activeRoutes
?? (this.root.data === undefined ? [this.createActiveRoute(this.root, {})] : []);
// landed as every page is, at the page the navigation was going to, or the one standing
const matched = pending ?? { ...previous, routes: [] };
await this.applyCascade(matched, { status: 'error', error, view, views, activeRoutes })
.catch(() => this.notify());
return;
}
this.notify();
}
// back from bfcache with the dom intact: the route lifecycle sees an update, the page stays
restored() {
const matched = this.match(this.navigator.entry?.url);
if (matched) {
this.commitRoute(matched);
}
}
disposed(entry) {
if (entry?.key) {
this.entryCache?.delete(entry.key);
}
}
/*******************************
Entering a Route
*******************************/
// the guard phase answers before the url may move, the data phase may run on after commit
// read once per navigation, ahead of the guards and under holdCommit with them. absent, user is whatever the app set
async resolveIdentity(navigation) {
if (this.config.identity == null) {
return;
}
const user = (await (isFunction(this.config.identity) ? this.config.identity(navigation) : this.config.identity))
?? null;
if (!navigation.signal?.aborted) {
this.user = user;
}
}
begin(matched, event, identity = null) {
const entryKey = event.navigationType === 'traverse' ? event.destination.key : null;
// the visit's result rides its entry: a traverse back shows what was seen for the same user, reload() refreshes it
const cached = entryKey ? this.entryCache?.get(entryKey) : null;
const cachedResult = () => (cached && !this.config.dataChanged(cached.user, this.user) ? cached.resolved : null);
// what the cascade knows of the navigation: its signal, whether it is a reload, the page it leaves
const navigation = { signal: event.signal, reload: event.navigationType === 'reload', previous: this.page };
const work = {
matched,
settled: false,
redirected: null,
identity: identity ?? this.resolveIdentity(navigation),
};
work.guards = work.identity.then(() => this.runGuards(matched, navigation));
work.ready = work.guards.then((guard) => guard ?? cachedResult() ?? this.runData(matched, navigation));
const settle = () => {
work.settled = true;
};
work.ready.then(settle, settle);
return work;
}
async beforeCommit(work, event, controller) {
let active = work;
for (let hop = 0; hop < 5; hop++) {
const guard = await active.guards;
if (guard?.status !== 'redirect') {
break;
}
const isRewrite = event.navigationType === 'push' || event.navigationType === 'replace';
const redirectedMatch = this.match(guard.redirect);
if (!isRewrite || !redirectedMatch) {
// a traverse or reload cannot be redirected before commit, and a target outside the routes is
// the browser's: stay put, then go where the guard says
// a reload or a replace meant to stay, so the redirect replaces. a refused traverse leaves the user where they stood, so it pushes
this.navigator.deferNavigate(guard.redirect, {
history: event.navigationType === 'reload' || event.navigationType === 'replace'
? 'replace'
: 'push',
});
throw new DOMException('Navigation refused', 'AbortError');
}
controller.redirect(guard.redirect);
this.setPending(redirectedMatch, event.navigationType);
this.navigator.transition.url = redirectedMatch.url;
active = work.redirected = this.begin(redirectedMatch, event, active.identity);
}
// a fast load settles before the url moves, a slow one commits into its loading state
const holdMs = toDuration(this.config.holdCommit) ?? 0;
if (!active.settled && holdMs > 0) {
await Promise.race([
active.ready.catch(noop),
wait(holdMs, { abortController: event.signal, rejectOnAbort: false }),
]);
}
}
async afterCommit(work, event, { precommitRan = false } = {}) {
const active = work.redirected ?? work;
const { matched } = active;
// the handler runs only once the url has moved, so this is a commit even where the platform's event did not say so
if (this.pending) {
this.pending = { ...this.pending, committed: true };
}
const delayMs = toDuration(this.config.loadingDelay) ?? 0;
const minMs = toDuration(this.config.loadingMin) ?? 0;
let loadingShownAt = null;
if (!active.settled) {
if (delayMs > 0) {
await Promise.race([
active.ready.catch(noop),
wait(delayMs, { abortController: event.signal, rejectOnAbort: false }),
]);
}
if (!active.settled && !event.signal.aborted) {
loadingShownAt = Date.now();
if (this.pending) {
this.pending = { ...this.pending, loading: true };
}
const loadingView = await this.resolveStatusView(matched.route, 'loading');
if (loadingView) {
if (!active.settled && !event.signal.aborted) {
// page stays the settled page: a loading view is rendered over it by its last active
// route, and pending.loading says so. on a cold boot no route is active, so the render
// shows it at the mount, where the page that lands replaces it
const loading = {
...this.pageFor(matched),
views: this.page?.views ?? [],
activeRoutes: this.page?.activeRoutes ?? [],
data: this.page?.data ?? {},
view: loadingView,
status: 'loading',
};
await this.renderPage(loading, event);
}
}
this.notify();
}
}
try {
const resolved = await active.ready;
if (event.signal.aborted) {
return;
}
if (resolved.status === 'redirect' && resolved.redirect) {
if (!precommitRan) {
// no precommit on this browser: the refused url has shown, its slot becomes the redirect target,
// a task later so this handler is not aborted by its own replacement
this.navigator.deferNavigate(resolved.redirect, {
history: 'replace',
});
}
return;
}
if (loadingShownAt !== null && minMs > 0) {
const elapsed = Date.now() - loadingShownAt;
if (elapsed < minMs) {
await wait(minMs - elapsed, {
abortController: event.signal,
rejectOnAbort: false,
});
}
if (event.signal.aborted) {
return;
}
}
await this.applyCascade(matched, resolved, event);
// the error page stands, and the navigation still failed, which the platform and whoever
// awaits it are told
if (resolved.status === 'error') {
throw resolved.error;
}
}
finally {
// a cold boot's loading view, shown at the mount, leaves with a navigation that was aborted
if (event.signal.aborted) {
this.clearMountView();
}
}
}
/*******************************
Cascade
*******************************/
// the door a hook rides, with what to do should its answer change. nothing here, since plain
// data never moves on its own; the reactive scaffold runs the hook again when what it read moves
// and hands each later answer to changed. kind is guard or data: a guard runs every navigation,
// data only when its route does. a plugin's own hook rides the same door
evaluateHook(route, fn, context, { kind, changed }) {
return isFunction(fn) ? fn(context) : fn;
}
// one seam per hook, each naming its consequence: a redirect moves the page, a refused
// permission lands as it would at navigation, data replaces its entry, a title its title
evaluateRedirect(route, fn, context) {
return this.evaluateHook(route, fn, context, {
kind: 'guard',
changed: (target) => this.redirectChanged(route, target),
});
}
evaluatePermission(route, fn, context) {
return this.evaluateHook(route, fn, context, {
kind: 'guard',
changed: (allowed) => this.permissionChanged(route, allowed),
});
}
evaluateData(route, fn, context) {
return this.evaluateHook(route, fn, context, {
kind: 'data',
changed: (value) => this.updateData(route, value),
});
}
evaluateTitle(route, fn, context) {
return this.evaluateHook(route, fn, context, {
kind: 'data',
changed: (value) => this.updateTitle(route, value),
});
}
// what a hook sees. activeRoutes is what the routes above settled, route by route, none before
// the data phase, and data is theirs merged; the signal is the navigation's while one is in
// flight and the route's own otherwise
contextFor(route, matched, { activeRoutes = [], signal = route.abortSignal } = {}) {
return {
params: matched.params,
query: matched.query,
signal,
user: this.user,
route,
router: this,
data: this.getData(activeRoutes),
activeRoutes,
};
}