Skip to content

Commit cbeeddb

Browse files
authored
Merge pull request #16 from Semantic-Org/refactor/config
Read every setting from config, and stop copying the settings onto the router
2 parents c594d1f + 9e60a7d commit cbeeddb

4 files changed

Lines changed: 54 additions & 48 deletions

File tree

‎packages/nav-router/src/navigator.js‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ export class Navigator {
163163
if (this.canGoBack) {
164164
return this.catchNavigation(globalThis.navigation.back());
165165
}
166-
return this.navigate(fallbackUrl ?? (this.router.base || '/'), { history: 'push' });
166+
return this.navigate(fallbackUrl ?? (this.router.config.base || '/'), { history: 'push' });
167167
}
168168

169169
forward() {
@@ -216,11 +216,11 @@ export class Navigator {
216216
Scroll Memory
217217
*******************************/
218218

219-
// the platform restores the viewport and nothing else. the containers router.restoreScroll
219+
// the platform restores the viewport and nothing else. the containers router.config.restoreScroll
220220
// names ride the entry's state, saved on the way out and put back on a traverse
221221

222222
saveScroll() {
223-
const selectors = this.router.restoreScroll;
223+
const selectors = this.router.config.restoreScroll;
224224
const nav = globalThis.navigation;
225225
if (!selectors || !globalThis.document || !nav?.currentEntry) {
226226
return;

‎packages/nav-router/src/plugins/dom.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export default ({ mount: defaultMount = 'body' } = {}, Router) => {
2121
Router.defaults.mount ??= defaultMount;
2222

2323
const mountElement = (router) => {
24-
const target = router.mount ?? defaultMount;
24+
const target = router.config.mount ?? defaultMount;
2525
return isString(target) ? document.querySelector(target) : target;
2626
};
2727

‎packages/nav-router/src/reactive-router.js‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export class ReactiveRouter extends Router {
3535
// the helpers and an app's chrome among them. core writes the fields as it always has
3636
const { equality } = this.constructor;
3737
each(['current', 'page', 'pending', 'error'], (key) => this.cellFor(key, equality.snapshot));
38-
this.cellFor('user', (before, after) => !this.dataChanged(before, after));
38+
this.cellFor('user', (before, after) => !this.config.dataChanged(before, after));
3939
// the page's params and query, live by key: params.org tracks org alone. the page's and so the
4040
// router's, written once per settle, which is what keeps a kept layout's reads current
4141
this.paramCells = this.createStore({});
@@ -106,7 +106,7 @@ export class ReactiveRouter extends Router {
106106
// boot's among them, and asks again otherwise, once per navigation as core does: an identity
107107
// reading nothing reactive, a cookie or a fetch, still moves with the page
108108
async start() {
109-
if (isFunction(this.identity)) {
109+
if (isFunction(this.config.identity)) {
110110
this.lifetime = new AbortController();
111111
this.identityRun = this.createReaction(() => {
112112
this.identityFresh = true;
@@ -138,7 +138,7 @@ export class ReactiveRouter extends Router {
138138
// and an aborted navigation's lands nothing. settled, it is no navigation's to take; failed, it
139139
// is dropped, so the navigation that awaited it fails with it and the next asks again
140140
askIdentity(context) {
141-
const answer = Promise.resolve(this.identity(context)).then((user) => {
141+
const answer = Promise.resolve(this.config.identity(context)).then((user) => {
142142
if (this.identityAnswer === answer && !context.signal?.aborted) {
143143
this.user = user ?? null;
144144
}
@@ -188,7 +188,7 @@ export class ReactiveRouter extends Router {
188188
// a data cell compares as the router's dataChanged says, the instance's word on data
189189
cells.set(
190190
key,
191-
this.createSignal(initialValue[key], { equals: (before, after) => !this.dataChanged(before, after) }),
191+
this.createSignal(initialValue[key], { equals: (before, after) => !this.config.dataChanged(before, after) }),
192192
);
193193
}
194194
return cells.get(key);

‎packages/nav-router/src/router.js‎

Lines changed: 46 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,15 @@ export class Router {
8181
const owner = key in defaults ? settings : routeOptions;
8282
owner[key] = value;
8383
});
84-
// the resolved settings in one place, for the console and for anything that introspects
84+
// the resolved settings, read from here and nowhere else; a plugin's default lands here too
8585
this.config = extend({}, defaults, settings);
86-
extend(this, this.config);
87-
this.base = this.normalizeBase(this.base);
88-
this.statusViews = { ...defaults.statusViews, ...settings.statusViews };
86+
this.config.base = this.normalizeBase(this.config.base);
87+
this.config.statusViews = { ...defaults.statusViews, ...settings.statusViews };
88+
// not settings, though declared among the defaults so the constructor keeps them from the root
89+
// route: the user is state the identity door writes, the two callbacks are the app's to assign
90+
this.user = this.config.user;
91+
this.onRender = this.config.onRender;
92+
this.onChange = this.config.onChange;
8993

9094
this.routesByName = new Map();
9195
this.leaves = [];
@@ -134,13 +138,13 @@ export class Router {
134138
// the helpers reach the started router. one per document is the common case, so it also lives
135139
// on window under this name for the console; a second router names itself otherwise
136140
setRouter(this);
137-
if (this.attachGlobal && globalThis.window) {
138-
globalThis[this.attachGlobal] = this;
141+
if (this.config.attachGlobal && globalThis.window) {
142+
globalThis[this.config.attachGlobal] = this;
139143
}
140144

141145
const initialUrl = this.navigator.entry?.url
142146
?? globalThis.location?.href
143-
?? (this.base || '/');
147+
?? (this.config.base || '/');
144148

145149
const matched = this.match(initialUrl);
146150
this.commitRoute(matched);
@@ -182,7 +186,7 @@ export class Router {
182186
const navigation = { signal: event.signal, reload: false, previous: null };
183187
await this.resolveIdentity(navigation);
184188
const [view, views, { data, slices }] = await Promise.all([
185-
this.resolveView(this.statusViews?.notFound),
189+
this.resolveView(this.config.statusViews?.notFound),
186190
this.resolveRouteViews([this.root]),
187191
this.runSlices([this.root], { params: {}, query: {} }, navigation),
188192
]);
@@ -215,8 +219,8 @@ export class Router {
215219
stop() {
216220
this.navigator.detach();
217221
setRouter(null);
218-
if (this.attachGlobal && globalThis[this.attachGlobal] === this) {
219-
delete globalThis[this.attachGlobal];
222+
if (this.config.attachGlobal && globalThis[this.config.attachGlobal] === this) {
223+
delete globalThis[this.config.attachGlobal];
220224
}
221225
this.activeAbort?.abort();
222226
this.activeAbort = null;
@@ -300,14 +304,14 @@ export class Router {
300304
}
301305

302306
stripBase(rawPathname) {
303-
if (!this.base) {
307+
if (!this.config.base) {
304308
return this.normalizePathname(rawPathname);
305309
}
306-
if (rawPathname === this.base) {
310+
if (rawPathname === this.config.base) {
307311
return '/';
308312
}
309-
if (rawPathname.startsWith(`${this.base}/`)) {
310-
return this.normalizePathname(rawPathname.slice(this.base.length));
313+
if (rawPathname.startsWith(`${this.config.base}/`)) {
314+
return this.normalizePathname(rawPathname.slice(this.config.base.length));
311315
}
312316
return null;
313317
}
@@ -571,9 +575,9 @@ export class Router {
571575
}
572576

573577
prependBase(path) {
574-
if (!this.base) { return path; }
575-
if (path === '/') { return this.base; }
576-
return path.startsWith('/') ? `${this.base}${path}` : `${this.base}/${path}`;
578+
if (!this.config.base) { return path; }
579+
if (path === '/') { return this.config.base; }
580+
return path.startsWith('/') ? `${this.config.base}${path}` : `${this.config.base}/${path}`;
577581
}
578582

579583
// the address a sign-in redirect carries back: a path under base, so the sign-in page can navigate to it
@@ -631,7 +635,7 @@ export class Router {
631635
}
632636

633637
back(fallback = this.root.name, args = {}) {
634-
return this.navigator.back(fallback ? this.href(fallback, args) : (this.base || '/'));
638+
return this.navigator.back(fallback ? this.href(fallback, args) : (this.config.base || '/'));
635639
}
636640

637641
forward() {
@@ -715,12 +719,12 @@ export class Router {
715719
};
716720
// a failure before commit left the standing page in place; only a committed one is shown as an error
717721
const committed = !pending || pending.committed;
718-
if (committed && this.errorRoute) {
719-
this.navigator.deferNavigate(this.href(this.errorRoute), { history: 'replace' });
722+
if (committed && this.config.errorRoute) {
723+
this.navigator.deferNavigate(this.href(this.config.errorRoute), { history: 'replace' });
720724
}
721725
else if (committed) {
722726
const previous = this.page;
723-
const view = await this.resolveView(this.statusViews?.error).catch(() => null);
727+
const view = await this.resolveView(this.config.statusViews?.error).catch(() => null);
724728
if (!view) {
725729
this.logError(error);
726730
}
@@ -780,10 +784,11 @@ export class Router {
780784
// the guard phase answers before the url may move, the data phase may run on after commit
781785
// read once per navigation, ahead of the guards and under holdCommit with them. absent, user is whatever the app set
782786
async resolveIdentity(navigation) {
783-
if (this.identity == null) {
787+
if (this.config.identity == null) {
784788
return;
785789
}
786-
const user = (await (isFunction(this.identity) ? this.identity(navigation) : this.identity)) ?? null;
790+
const user = (await (isFunction(this.config.identity) ? this.config.identity(navigation) : this.config.identity))
791+
?? null;
787792
if (!navigation.signal?.aborted) {
788793
this.user = user;
789794
}
@@ -793,7 +798,8 @@ export class Router {
793798
const entryKey = event.navigationType === 'traverse' ? event.destination.key : null;
794799
// the visit's result rides its entry: a traverse back shows what was seen for the same user, reload() refreshes it
795800
const remembered = entryKey ? this.entryCache?.get(entryKey) : null;
796-
const cached = () => (remembered && !this.dataChanged(remembered.user, this.user) ? remembered.resolved : null);
801+
const cached =
802+
() => (remembered && !this.config.dataChanged(remembered.user, this.user) ? remembered.resolved : null);
797803
// what the cascade knows of the navigation: its signal, whether it is a reload, the page it leaves
798804
const navigation = { signal: event.signal, reload: event.navigationType === 'reload', previous: this.page };
799805
const work = {
@@ -844,7 +850,7 @@ export class Router {
844850
}
845851

846852
// a fast load settles before the url moves, a slow one commits into its loading state
847-
const holdMs = toDuration(this.holdCommit) ?? 0;
853+
const holdMs = toDuration(this.config.holdCommit) ?? 0;
848854
if (!active.settled && holdMs > 0) {
849855
await Promise.race([
850856
active.ready.catch(noop),
@@ -861,8 +867,8 @@ export class Router {
861867
this.pending = { ...this.pending, committed: true };
862868
}
863869

864-
const delayMs = toDuration(this.loadingDelay) ?? 0;
865-
const minMs = toDuration(this.loadingMin) ?? 0;
870+
const delayMs = toDuration(this.config.loadingDelay) ?? 0;
871+
const minMs = toDuration(this.config.loadingMin) ?? 0;
866872
let loadingShownAt = null;
867873
let coldLoading = null;
868874

@@ -878,8 +884,8 @@ export class Router {
878884
if (this.pending) {
879885
this.pending = { ...this.pending, loading: true };
880886
}
881-
if (this.statusViews?.loading) {
882-
const loadingView = await this.resolveView(this.statusViews.loading);
887+
if (this.config.statusViews?.loading) {
888+
const loadingView = await this.resolveView(this.config.statusViews.loading);
883889
if (!active.settled && !event.signal.aborted) {
884890
// page stays the settled page: a loading view is rendered over it with its slices, so a
885891
// leaf's own slots re-render against what stands, and pending.loading says so. on a cold
@@ -1043,11 +1049,11 @@ export class Router {
10431049
this.contextFor(ancestor, matched, { signal }),
10441050
);
10451051
if (!allowed) {
1046-
if ((!this.user || !this.statusViews?.forbidden) && this.signInRoute) {
1052+
if ((!this.user || !this.config.statusViews?.forbidden) && this.config.signInRoute) {
10471053
// the return address rides to the sign-in page, which reads it as query.returnTo
10481054
return {
10491055
status: 'redirect',
1050-
redirect: this.href(this.signInRoute, { returnTo: this.returnAddress(matched) }),
1056+
redirect: this.href(this.config.signInRoute, { returnTo: this.returnAddress(matched) }),
10511057
route,
10521058
params,
10531059
query,
@@ -1063,7 +1069,7 @@ export class Router {
10631069
return this.notFoundResult(matched, viewsReady, { data, slices, signal });
10641070
}
10651071
const [view, views, { title, titles }] = await Promise.all([
1066-
this.resolveView(this.statusViews?.forbidden),
1072+
this.resolveView(this.config.statusViews?.forbidden),
10671073
viewsReady,
10681074
this.evaluateTitles(currentRoutes, matched, { data, slices, signal }),
10691075
]);
@@ -1090,7 +1096,7 @@ export class Router {
10901096
// when the url as the route sees it did not move, unless every route runs again, on a reload or
10911097
// for another user
10921098
keptSlice(route, matched, { reload = false, previous = null }) {
1093-
if (!previous || reload || this.dataChanged(previous.user, this.user)) {
1099+
if (!previous || reload || this.config.dataChanged(previous.user, this.user)) {
10941100
return null;
10951101
}
10961102
const slice = previous.slices?.find((item) => item.route === route);
@@ -1172,7 +1178,7 @@ export class Router {
11721178
async notFoundResult(matched, viewsReady, { data, slices, signal }) {
11731179
const [views, view, { title, titles }] = await Promise.all([
11741180
viewsReady,
1175-
this.resolveView(this.statusViews?.notFound),
1181+
this.resolveView(this.config.statusViews?.notFound),
11761182
this.evaluateTitles(matched.currentRoutes, matched, { data, slices, signal }),
11771183
]);
11781184
return this.buildCascadeResult(matched, { status: 'notFound', view, views, data, slices, title, titles });
@@ -1430,13 +1436,13 @@ export class Router {
14301436
}
14311437
return;
14321438
}
1433-
if ((!this.user || !this.statusViews?.forbidden) && this.signInRoute) {
1434-
this.navigator.navigate(this.href(this.signInRoute, { returnTo: this.returnAddress(this.current) }), {
1439+
if ((!this.user || !this.config.statusViews?.forbidden) && this.config.signInRoute) {
1440+
this.navigator.navigate(this.href(this.config.signInRoute, { returnTo: this.returnAddress(this.current) }), {
14351441
history: 'replace',
14361442
});
14371443
return;
14381444
}
1439-
const view = await this.resolveView(this.statusViews?.forbidden);
1445+
const view = await this.resolveView(this.config.statusViews?.forbidden);
14401446
if (stale()) {
14411447
return;
14421448
}
@@ -1491,7 +1497,7 @@ export class Router {
14911497
return;
14921498
}
14931499
if (resolved === NOT_FOUND) {
1494-
const view = await this.resolveView(this.statusViews?.notFound);
1500+
const view = await this.resolveView(this.config.statusViews?.notFound);
14951501
if (stale()) {
14961502
return;
14971503
}
@@ -1508,7 +1514,7 @@ export class Router {
15081514
// sets the slice and says whether it moved, one dataChanged compare. the reactive scaffold
15091515
// writes each key through its cell and lets the cell's equality say
15101516
setSlice(slice, data) {
1511-
if (!this.dataChanged(slice.data, data)) {
1517+
if (!this.config.dataChanged(slice.data, data)) {
15121518
return false;
15131519
}
15141520
slice.data = data;
@@ -1556,7 +1562,7 @@ export class Router {
15561562
leaf.update(page);
15571563
}
15581564
await this.onRender?.(page, event);
1559-
if (event?.navigationType === 'traverse' && this.restoreScroll && page.status !== 'loading') {
1565+
if (event?.navigationType === 'traverse' && this.config.restoreScroll && page.status !== 'loading') {
15601566
this.navigator.restoreScroll(this.navigator.entry);
15611567
}
15621568
}

0 commit comments

Comments
 (0)