Skip to content

Commit 4a21a0e

Browse files
authored
Merge pull request #38 from Semantic-Org/refactor/whole-read-cleanup
Refactor/whole read cleanup
2 parents b32d779 + 85b390c commit 4a21a0e

4 files changed

Lines changed: 34 additions & 98 deletions

File tree

‎integrations/react/index.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,11 +125,10 @@ export class ReactRouter extends Router {
125125
}
126126
}
127127

128-
// the router's state, read in a component and kept current: useRouter((router) => router.pending)
129-
export const useRouter = (read) => {
130-
const router = getRouter();
131-
return useSyncExternalStore((listener) => router.subscribe(listener), () => read(router));
132-
};
128+
// the router's state, read in a component and kept current: useRouter((router) => router.pending).
129+
// one function for every component, so react subscribes once and not again at each render
130+
const subscribe = (listener) => getRouter().subscribe(listener);
131+
export const useRouter = (read) => useSyncExternalStore(subscribe, () => read(getRouter()));
133132

134133
export * from 'nav-router';
135134
export const reactRouter = (options) => new ReactRouter(options);

‎packages/plugins/src/head.js‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { each, extend, inArray, isArray, isFunction, isPlainObject, isPromise } from '@semantic-ui/utils';
1+
import { each, extend, isArray, isFunction, isPlainObject, isPromise } from '@semantic-ui/utils';
22
import { Router } from 'nav-router';
33

44
const PROPERTY_PREFIX = /^(og|article|profile|book|fb):/;
@@ -58,14 +58,7 @@ const restoreEntry = (key, record) => {
5858
// the hook sees what the other hooks see, with the page's data and active routes, so a reactive router
5959
// tracks what it reads. a sync answer waits for the render's write, an async one lands on its own
6060
proto.evaluateMeta = function(route) {
61-
// the hook sees what the other hooks see: the active routes of the route and the routes above it
62-
const activeRoutes = (this.page.activeRoutes ?? []).filter((activeRoute) =>
63-
inArray(activeRoute.route, route.ancestors)
64-
);
65-
const data = {};
66-
each(activeRoutes, (activeRoute) => extend(data, activeRoute.data));
67-
const context = this.contextFor(route, this.page, { data, activeRoutes });
68-
const value = this.evaluateHook(route, route.meta, context, {
61+
const value = this.evaluateHook(route, route.meta, route.viewContext(this.page), {
6962
kind: 'data',
7063
changed: (value) => this.metaChanged(route, value),
7164
});

‎src/reactive-router.js‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -246,18 +246,19 @@ export class ReactiveRouter extends Router {
246246
const current = activeRoutes.get();
247247
if (current !== cachedRoutes) {
248248
cachedRoutes = current;
249-
cachedData = router.dataFor(current);
249+
cachedData = router.getLiveData(current);
250250
}
251251
return cachedData;
252252
},
253253
};
254254
return { context: live, update: (next) => activeRoutes.set(next.activeRoutes) };
255255
}
256256

257-
// merges ancestor active routes behind per-key getters, so reading data.team tracks team's cell alone.
258-
// a getter exists for the keys an active route holds, so a key a run returns only sometimes is read plain
259-
// on the runs it is absent: a data() returns every key every run, undefined when it has none
260-
dataFor(activeRoutes) {
257+
// the data of the routes given, merged behind per-key getters, so reading data.team tracks team's
258+
// cell alone: what a live context holds, where a page holds the plain merge as it was written. a
259+
// getter exists for the keys an active route holds, so a key a run returns only sometimes is read
260+
// plain on the runs it is absent: a data() returns every key every run, undefined when it has none
261+
getLiveData(activeRoutes) {
261262
const data = {};
262263
each(activeRoutes, (activeRoute) => {
263264
each(activeRoute.data, (_, key) => {
@@ -315,7 +316,7 @@ export class ReactiveRouter extends Router {
315316
// what the hook sees of the user is live, a getter on its own context, so a guard that read it
316317
// runs again when the user moves and a hook that did not read it is left alone
317318
const createHookContext = (extra) =>
318-
Object.defineProperty({ ...context, data: this.dataFor(activeRoutes), ...extra }, 'user', {
319+
Object.defineProperty({ ...context, data: this.getLiveData(activeRoutes), ...extra }, 'user', {
319320
get: () => this.user,
320321
enumerable: true,
321322
});
@@ -395,7 +396,7 @@ export class ReactiveRouter extends Router {
395396
applyHookResult(route, changed, value) {
396397
const handleError = (error) => {
397398
if (error?.name !== 'AbortError' && this.onPage(route)) {
398-
this.onError(error, this.contextFor(route, this.page));
399+
this.onError(error, this.untrack(() => route.viewContext(this.page)));
399400
}
400401
};
401402
try {

‎src/router.js‎

Lines changed: 20 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -196,20 +196,21 @@ export class Router {
196196
// first, so a root with data frames the cold not-found with what it reads
197197
async applyNotFound(url, event) {
198198
const navigation = { signal: event.signal, reload: false, previous: null };
199+
// no route matched, so the page has none of its own
200+
const matched = { url, params: {}, query: {}, routes: [] };
199201
await this.resolveIdentity(navigation);
200202
const [view, views, { activeRoutes, error }] = await Promise.all([
201203
this.resolveStatusView(this.root, 'notFound'),
202204
this.resolveRouteViews([this.root]),
203-
this.loadRoutes([this.root], { params: {}, query: {} }, navigation),
205+
this.loadRoutes([this.root], matched, navigation),
204206
]);
205207
if (error) {
206208
throw error;
207209
}
208210
if (event.signal.aborted) {
209211
return;
210212
}
211-
// no route matched, so the page has none of its own: it lands as every page does
212-
await this.applyCascade({ url, routes: [] }, { status: 'notFound', view, views, activeRoutes }, event);
213+
await this.applyCascade(matched, { status: 'notFound', view, views, activeRoutes }, event);
213214
}
214215

215216
// a route was added: a page standing as not-found for want of a route is matched again a
@@ -748,8 +749,8 @@ export class Router {
748749
?? (this.root.data === undefined ? [this.createActiveRoute(this.root, {})] : []);
749750
// landed as every page is, at the page the navigation was going to, or the one standing
750751
const matched = pending ?? { ...previous, routes: [] };
751-
const resolved = this.buildCascadeResult(matched, { status: 'error', error, view, views, activeRoutes });
752-
await this.applyCascade(matched, resolved).catch(() => this.notify());
752+
await this.applyCascade(matched, { status: 'error', error, view, views, activeRoutes })
753+
.catch(() => this.notify());
753754
return;
754755
}
755756
this.notify();
@@ -796,21 +797,15 @@ export class Router {
796797
const work = {
797798
matched,
798799
settled: false,
799-
result: null,
800800
redirected: null,
801801
identity: identity ?? this.resolveIdentity(navigation),
802802
};
803803
work.guards = work.identity.then(() => this.runGuards(matched, navigation));
804804
work.ready = work.guards.then((guard) => guard ?? cachedResult() ?? this.runData(matched, navigation));
805-
work.ready.then(
806-
(result) => {
807-
work.settled = true;
808-
work.result = result;
809-
},
810-
() => {
811-
work.settled = true;
812-
},
813-
);
805+
const settle = () => {
806+
work.settled = true;
807+
};
808+
work.ready.then(settle, settle);
814809
return work;
815810
}
816811

@@ -901,7 +896,7 @@ export class Router {
901896
return;
902897
}
903898

904-
if (resolved?.status === 'redirect' && resolved.redirect) {
899+
if (resolved.status === 'redirect' && resolved.redirect) {
905900
if (!precommitRan) {
906901
// no precommit on this browser: the refused url has shown, its slot becomes the redirect target,
907902
// a task later so this handler is not aborted by its own replacement
@@ -928,7 +923,7 @@ export class Router {
928923
await this.applyCascade(matched, resolved, event);
929924
// the error page stands, and the navigation still failed, which the platform and whoever
930925
// awaits it are told
931-
if (resolved?.status === 'error') {
926+
if (resolved.status === 'error') {
932927
throw resolved.error;
933928
}
934929
}
@@ -944,17 +939,12 @@ export class Router {
944939
Cascade
945940
*******************************/
946941

947-
// the plain seam
948-
evaluate(route, fn, context) {
949-
return isFunction(fn) ? fn(context) : fn;
950-
}
951-
952942
// the door a hook rides, with what to do should its answer change. nothing here, since plain
953943
// data never moves on its own; the reactive scaffold runs the hook again when what it read moves
954944
// and hands each later answer to changed. kind is guard or data: a guard runs every navigation,
955945
// data only when its route does. a plugin's own hook rides the same door
956946
evaluateHook(route, fn, context, { kind, changed }) {
957-
return this.evaluate(route, fn, context);
947+
return isFunction(fn) ? fn(context) : fn;
958948
}
959949

960950
// one seam per hook, each naming its consequence: a redirect moves the page, a refused
@@ -987,10 +977,6 @@ export class Router {
987977
});
988978
}
989979

990-
async runCascade(matched, navigation) {
991-
return (await this.runGuards(matched, navigation)) ?? this.runData(matched, navigation);
992-
}
993-
994980
// what a hook sees. activeRoutes is what the routes above settled, route by route, none before
995981
// the data phase, and data is theirs merged; the signal is the navigation's while one is in
996982
// flight and the route's own otherwise
@@ -1009,12 +995,8 @@ export class Router {
1009995

1010996
// null when the route may be entered, otherwise the redirect or forbidden result
1011997
async runGuards(matched, navigation) {
1012-
if (!matched) {
1013-
return null;
1014-
}
1015998
const { signal } = navigation;
1016-
1017-
const { route, params, query, routes } = matched;
999+
const { params, routes } = matched;
10181000

10191001
for (const ancestor of routes) {
10201002
if (ancestor.redirect) {
@@ -1023,13 +1005,7 @@ export class Router {
10231005
ancestor.redirect,
10241006
this.contextFor(ancestor, matched, { signal }),
10251007
);
1026-
return {
1027-
status: 'redirect',
1028-
redirect: this.href(target, this.paramsFor(target, params)),
1029-
route,
1030-
params,
1031-
query,
1032-
};
1008+
return { status: 'redirect', redirect: this.href(target, this.paramsFor(target, params)) };
10331009
}
10341010
}
10351011

@@ -1046,9 +1022,6 @@ export class Router {
10461022
return {
10471023
status: 'redirect',
10481024
redirect: this.href(this.config.signInRoute, { returnTo: this.returnAddress(matched) }),
1049-
route,
1050-
params,
1051-
query,
10521025
};
10531026
}
10541027
// the routes above the refusing one run their data as a landing would, so their layouts
@@ -1057,19 +1030,7 @@ export class Router {
10571030
viewsReady.catch(noop);
10581031
const routesAbove = routes.slice(0, routes.indexOf(ancestor));
10591032
const loaded = await this.loadRoutes(routesAbove, matched, navigation);
1060-
if (loaded.status) {
1061-
return this.statusResult(matched, viewsReady, loaded);
1062-
}
1063-
const [view, views] = await Promise.all([
1064-
this.resolveStatusView(ancestor, 'forbidden'),
1065-
viewsReady,
1066-
]);
1067-
return this.buildCascadeResult(matched, {
1068-
status: 'forbidden',
1069-
view,
1070-
views,
1071-
activeRoutes: loaded.activeRoutes,
1072-
});
1033+
return this.statusResult(matched, viewsReady, { status: 'forbidden', ...loaded });
10731034
}
10741035
}
10751036
}
@@ -1092,7 +1053,6 @@ export class Router {
10921053
}
10931054

10941055
async runData(matched, navigation) {
1095-
const { signal } = navigation;
10961056
const { routes } = matched;
10971057

10981058
// the chunks load while the data runs, and a failed chunk waits to throw where the data's turn comes
@@ -1104,12 +1064,7 @@ export class Router {
11041064
return this.statusResult(matched, viewsReady, loaded);
11051065
}
11061066
const views = await viewsReady;
1107-
return this.buildCascadeResult(matched, {
1108-
status: 'ok',
1109-
view: views.at(-1)?.view ?? null,
1110-
views,
1111-
activeRoutes: loaded.activeRoutes,
1112-
});
1067+
return { status: 'ok', view: views.at(-1)?.view ?? null, views, activeRoutes: loaded.activeRoutes };
11131068
}
11141069

11151070
// the page's active routes in route order, each seeing the data of the routes above it: a route keeps
@@ -1169,17 +1124,17 @@ export class Router {
11691124
return { activeRoutes };
11701125
}
11711126

1172-
// a route's load ended with no page for it, in not-found or in an error: the routes above it
1127+
// a route has no page: it refused, returned not-found or failed to load. the routes above it
11731128
// are the page, and the status view stands in for it and the routes below
11741129
async statusResult(matched, viewsReady, { activeRoutes, status, error }) {
1175-
// routes load in order, so the one the load ended at is the first that is not active
1130+
// routes load in order, so the one this is for is the first that is not active
11761131
const route = matched.routes[activeRoutes.length];
11771132
if (error) {
11781133
// before anything is awaited, so a navigation superseded while its page loads has still said so
11791134
this.onError(error, this.contextFor(route, matched, { activeRoutes }));
11801135
}
11811136
const [views, view] = await Promise.all([viewsReady, this.resolveStatusView(route, status)]);
1182-
return this.buildCascadeResult(matched, { status, ...(error && { error }), view, views, activeRoutes });
1137+
return { status, ...(error && { error }), view, views, activeRoutes };
11831138
}
11841139

11851140
// a route's share of the page. the reactive scaffold gives it a signal the routes below read
@@ -1220,15 +1175,6 @@ export class Router {
12201175
return value === undefined || value === null || value === '' ? null : String(value);
12211176
}
12221177

1223-
buildCascadeResult({ route, params, query }, resolved) {
1224-
return {
1225-
route,
1226-
params,
1227-
query,
1228-
...resolved,
1229-
};
1230-
}
1231-
12321178
// the view a status shows at a route: the route's own, or the nearest above that names one, the
12331179
// root's last. null or false on a route is an answer too, and no route above is asked
12341180
getStatusView(route, status) {
@@ -1301,9 +1247,6 @@ export class Router {
13011247

13021248
// every moment carries the navigation that caused it, so a plugin never holds one across moments
13031249
async applyCascade(matched, resolved, event = null) {
1304-
if (!resolved) {
1305-
return;
1306-
}
13071250
const { key } = this.getEntrySnapshot();
13081251
const previous = this.page;
13091252
const { activeRoutes } = resolved;

0 commit comments

Comments
 (0)