-
Notifications
You must be signed in to change notification settings - Fork 147
/
routing.ts
544 lines (487 loc) · 14.2 KB
/
routing.ts
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
import type { Component, JSX, Accessor } from "solid-js";
import {
createComponent,
createContext,
createMemo,
createRenderEffect,
createSignal,
on,
onCleanup,
untrack,
useContext,
startTransition,
resetErrorBoundaries
} from "solid-js";
import { isServer, delegateEvents } from "solid-js/web";
import { normalizeIntegration } from "./integration";
import { createBeforeLeave } from "./lifecycle";
import type {
BeforeLeaveEventArgs,
Branch,
Location,
LocationChange,
LocationChangeSignal,
MatchFilters,
NavigateOptions,
Navigator,
Params,
Route,
RouteContext,
RouteDataFunc,
RouteDefinition,
RouteMatch,
RouterContext,
RouterIntegration,
RouterOutput,
SetParams
} from "./types";
import {
createMemoObject,
extractSearchParams,
invariant,
resolvePath,
createMatcher,
joinPaths,
scoreRoute,
mergeSearchString,
expandOptionals
} from "./utils";
const MAX_REDIRECTS = 100;
interface MaybePreloadableComponent extends Component {
preload?: () => void;
}
export const RouterContextObj = createContext<RouterContext>();
export const RouteContextObj = createContext<RouteContext>();
export const useRouter = () =>
invariant(useContext(RouterContextObj), "Make sure your app is wrapped in a <Router />");
let TempRoute: RouteContext | undefined;
export const useRoute = () => TempRoute || useContext(RouteContextObj) || useRouter().base;
export const useResolvedPath = (path: () => string) => {
const route = useRoute();
return createMemo(() => route.resolvePath(path()));
};
export const useHref = (to: () => string | undefined) => {
const router = useRouter();
return createMemo(() => {
const to_ = to();
return to_ !== undefined ? router.renderPath(to_) : to_;
});
};
export const useNavigate = () => useRouter().navigatorFactory();
export const useLocation = <S = unknown>() => useRouter().location as Location<S>;
export const useIsRouting = () => useRouter().isRouting;
export const useMatch = <S extends string>(path: () => S, matchFilters?: MatchFilters<S>) => {
const location = useLocation();
const matchers = createMemo(() =>
expandOptionals(path()).map(path => createMatcher(path, undefined, matchFilters))
);
return createMemo(() => {
for (const matcher of matchers()) {
const match = matcher(location.pathname);
if (match) return match;
}
});
};
export const useParams = <T extends Params>() => useRoute().params as T;
type MaybeReturnType<T> = T extends (...args: any) => infer R ? R : T;
export const useRouteData = <T>() => useRoute().data as MaybeReturnType<T>;
export const useSearchParams = <T extends Params>(): [
T,
(params: SetParams, options?: Partial<NavigateOptions>) => void
] => {
const location = useLocation();
const navigate = useNavigate();
const setSearchParams = (params: SetParams, options?: Partial<NavigateOptions>) => {
const searchString = untrack(() => mergeSearchString(location.search, params));
navigate(location.pathname + searchString + location.hash, {
scroll: false,
resolve: false,
...options
});
};
return [location.query as T, setSearchParams];
};
export const useBeforeLeave = (listener: (e: BeforeLeaveEventArgs) => void) => {
const s = useRouter().beforeLeave.subscribe({
listener,
location: useLocation(),
navigate: useNavigate()
});
onCleanup(s);
};
export function createRoutes(
routeDef: RouteDefinition,
base: string = "",
fallback?: Component
): Route[] {
const { component, data, children } = routeDef;
const isLeaf = !children || (Array.isArray(children) && !children.length);
const shared = {
key: routeDef,
element: component
? () => createComponent(component, {})
: () => {
const { element } = routeDef;
return element === undefined && fallback
? createComponent(fallback, {})
: (element as JSX.Element);
},
preload: routeDef.component
? (component as MaybePreloadableComponent).preload
: routeDef.preload,
data
};
return asArray(routeDef.path).reduce<Route[]>((acc, path) => {
for (const originalPath of expandOptionals(path)) {
const path = joinPaths(base, originalPath);
const pattern = isLeaf ? path : path.split("/*", 1)[0];
acc.push({
...shared,
originalPath,
pattern,
matcher: createMatcher(pattern, !isLeaf, routeDef.matchFilters)
});
}
return acc;
}, []);
}
export function createBranch(routes: Route[], index: number = 0): Branch {
return {
routes,
score: scoreRoute(routes[routes.length - 1]) * 10000 - index,
matcher(location) {
const matches: RouteMatch[] = [];
for (let i = routes.length - 1; i >= 0; i--) {
const route = routes[i];
const match = route.matcher(location);
if (!match) {
return null;
}
matches.unshift({
...match,
route
});
}
return matches;
}
};
}
function asArray<T>(value: T | T[]): T[] {
return Array.isArray(value) ? value : [value];
}
export function createBranches(
routeDef: RouteDefinition | RouteDefinition[],
base: string = "",
fallback?: Component,
stack: Route[] = [],
branches: Branch[] = []
): Branch[] {
const routeDefs = asArray(routeDef);
for (let i = 0, len = routeDefs.length; i < len; i++) {
const def = routeDefs[i];
if (def && typeof def === "object" && def.hasOwnProperty("path")) {
const routes = createRoutes(def, base, fallback);
for (const route of routes) {
stack.push(route);
const isEmptyArray = Array.isArray(def.children) && def.children.length === 0;
if (def.children && !isEmptyArray) {
createBranches(def.children, route.pattern, fallback, stack, branches);
} else {
const branch = createBranch([...stack], branches.length);
branches.push(branch);
}
stack.pop();
}
}
}
// Stack will be empty on final return
return stack.length ? branches : branches.sort((a, b) => b.score - a.score);
}
export function getRouteMatches(branches: Branch[], location: string): RouteMatch[] {
for (let i = 0, len = branches.length; i < len; i++) {
const match = branches[i].matcher(location);
if (match) {
return match;
}
}
return [];
}
export function createLocation(path: Accessor<string>, state: Accessor<any>): Location {
const origin = new URL("http://sar");
const url = createMemo<URL>(
prev => {
const path_ = path();
try {
return new URL(path_, origin);
} catch (err) {
console.error(`Invalid path ${path_}`);
return prev;
}
},
origin,
{
equals: (a, b) => a.href === b.href
}
);
const pathname = createMemo(() => url().pathname);
const search = createMemo(() => url().search, true);
const hash = createMemo(() => url().hash);
const key = createMemo(() => "");
return {
get pathname() {
return pathname();
},
get search() {
return search();
},
get hash() {
return hash();
},
get state() {
return state();
},
get key() {
return key();
},
query: createMemoObject(on(search, () => extractSearchParams(url())) as () => Params)
};
}
export function createRouterContext(
integration?: RouterIntegration | LocationChangeSignal,
base: string = "",
data?: RouteDataFunc,
out?: object
): RouterContext {
const {
signal: [source, setSource],
utils = {}
} = normalizeIntegration(integration);
const parsePath = utils.parsePath || (p => p);
const renderPath = utils.renderPath || (p => p);
const beforeLeave = utils.beforeLeave || createBeforeLeave();
const basePath = resolvePath("", base);
const output =
isServer && out
? (Object.assign(out, {
matches: [],
url: undefined
}) as RouterOutput)
: undefined;
if (basePath === undefined) {
throw new Error(`${basePath} is not a valid base path`);
} else if (basePath && !source().value) {
setSource({ value: basePath, replace: true, scroll: false });
}
const [isRouting, setIsRouting] = createSignal(false);
const start = async (callback: () => void) => {
setIsRouting(true);
try {
await startTransition(callback);
} finally {
setIsRouting(false);
}
};
const [reference, setReference] = createSignal(source().value);
const [state, setState] = createSignal(source().state);
const location = createLocation(reference, state);
const referrers: LocationChange[] = [];
const baseRoute: RouteContext = {
pattern: basePath,
params: {},
path: () => basePath,
outlet: () => null,
resolvePath(to: string) {
return resolvePath(basePath, to);
}
};
if (data) {
try {
TempRoute = baseRoute;
baseRoute.data = data({
data: undefined,
params: {},
location,
navigate: navigatorFactory(baseRoute)
});
} finally {
TempRoute = undefined;
}
}
function navigateFromRoute(
route: RouteContext,
to: string | number,
options?: Partial<NavigateOptions>
) {
// Untrack in case someone navigates in an effect - don't want to track `reference` or route paths
untrack(() => {
if (typeof to === "number") {
if (!to) {
// A delta of 0 means stay at the current location, so it is ignored
} else if (utils.go) {
beforeLeave.confirm(to, options) && utils.go(to);
} else {
console.warn("Router integration does not support relative routing");
}
return;
}
const {
replace,
resolve,
scroll,
state: nextState
} = {
replace: false,
resolve: true,
scroll: true,
...options
};
const resolvedTo = resolve ? route.resolvePath(to) : resolvePath("", to);
if (resolvedTo === undefined) {
throw new Error(`Path '${to}' is not a routable path`);
} else if (referrers.length >= MAX_REDIRECTS) {
throw new Error("Too many redirects");
}
const current = reference();
if (resolvedTo !== current || nextState !== state()) {
if (isServer) {
if (output) {
output.url = resolvedTo;
}
setSource({ value: resolvedTo, replace, scroll, state: nextState });
} else if (beforeLeave.confirm(resolvedTo, options)) {
const len = referrers.push({ value: current, replace, scroll, state: state() });
start(() => {
setReference(resolvedTo);
setState(nextState);
resetErrorBoundaries();
}).then(() => {
if (referrers.length === len) {
navigateEnd({
value: resolvedTo,
state: nextState
});
}
});
}
}
});
}
function navigatorFactory(route?: RouteContext): Navigator {
// Workaround for vite issue (https://github.com/vitejs/vite/issues/3803)
route = route || useContext(RouteContextObj) || baseRoute;
return (to: string | number, options?: Partial<NavigateOptions>) =>
navigateFromRoute(route!, to, options);
}
function navigateEnd(next: LocationChange) {
const first = referrers[0];
if (first) {
if (next.value !== first.value || next.state !== first.state) {
setSource({
...next,
replace: first.replace,
scroll: first.scroll
});
}
referrers.length = 0;
}
}
createRenderEffect(() => {
const { value, state } = source();
// Untrack this whole block so `start` doesn't cause Solid's Listener to be preserved
untrack(() => {
if (value !== reference()) {
start(() => {
setReference(value);
setState(state);
});
}
});
});
if (!isServer) {
function handleAnchorClick(evt: MouseEvent) {
if (
evt.defaultPrevented ||
evt.button !== 0 ||
evt.metaKey ||
evt.altKey ||
evt.ctrlKey ||
evt.shiftKey
)
return;
const a = evt
.composedPath()
.find(el => el instanceof Node && el.nodeName.toUpperCase() === "A") as
| HTMLAnchorElement
| undefined;
if (!a || !a.hasAttribute("link")) return;
const href = a.href;
if (a.target || (!href && !a.hasAttribute("state"))) return;
const rel = (a.getAttribute("rel") || "").split(/\s+/);
if (a.hasAttribute("download") || (rel && rel.includes("external"))) return;
const url = new URL(href);
if (
url.origin !== window.location.origin ||
(basePath && url.pathname && !url.pathname.toLowerCase().startsWith(basePath.toLowerCase()))
)
return;
const to = parsePath(url.pathname + url.search + url.hash);
const state = a.getAttribute("state");
evt.preventDefault();
navigateFromRoute(baseRoute, to, {
resolve: false,
replace: a.hasAttribute("replace"),
scroll: !a.hasAttribute("noscroll"),
state: state && JSON.parse(state)
});
}
// ensure delegated events run first
delegateEvents(["click"]);
document.addEventListener("click", handleAnchorClick);
onCleanup(() => document.removeEventListener("click", handleAnchorClick));
}
return {
base: baseRoute,
out: output,
location,
isRouting,
renderPath,
parsePath,
navigatorFactory,
beforeLeave
};
}
export function createRouteContext(
router: RouterContext,
parent: RouteContext,
child: () => RouteContext,
match: () => RouteMatch,
params: Params
): RouteContext {
const { base, location, navigatorFactory } = router;
const { pattern, element: outlet, preload, data } = match().route;
const path = createMemo(() => match().path);
preload && preload();
const route: RouteContext = {
parent,
pattern,
get child() {
return child();
},
path,
params,
data: parent.data,
outlet,
resolvePath(to: string) {
return resolvePath(base.path(), to, path());
}
};
if (data) {
try {
TempRoute = route;
route.data = data({ data: parent.data, params, location, navigate: navigatorFactory(route) });
} finally {
TempRoute = undefined;
}
}
return route;
}