-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
client.ts
505 lines (474 loc) · 12.7 KB
/
client.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
'use client';
import {
Component,
createContext,
createElement,
useCallback,
useContext,
useEffect,
useRef,
useState,
useTransition,
Fragment,
} from 'react';
import type {
ComponentProps,
FunctionComponent,
ReactNode,
AnchorHTMLAttributes,
ReactElement,
MouseEvent,
} from 'react';
import { prefetchRSC, Root, Slot, useRefetch } from '../client.js';
import {
getComponentIds,
getInputString,
PARAM_KEY_SKIP,
SHOULD_SKIP_ID,
LOCATION_ID,
} from './common.js';
import type { RouteProps, ShouldSkip } from './common.js';
declare global {
interface ImportMeta {
readonly env: Record<string, string>;
}
}
const normalizeRoutePath = (path: string) => {
for (const suffix of ['/', '/index.html']) {
if (path.endsWith(suffix)) {
return path.slice(0, -suffix.length) || '/';
}
}
return path;
};
const parseRoute = (url: URL): RouteProps => {
if ((globalThis as any).__WAKU_ROUTER_404__) {
return { path: '/404', searchParams: new URLSearchParams() };
}
const { pathname, searchParams } = url;
if (searchParams.has(PARAM_KEY_SKIP)) {
console.warn(`The search param "${PARAM_KEY_SKIP}" is reserved`);
}
return { path: normalizeRoutePath(pathname), searchParams };
};
type ChangeRoute = (
route: RouteProps,
options?: {
checkCache?: boolean;
skipRefetch?: boolean;
},
) => void;
type PrefetchRoute = (route: RouteProps) => void;
const RouterContext = createContext<{
route: RouteProps;
changeRoute: ChangeRoute;
prefetchRoute: PrefetchRoute;
} | null>(null);
export function useRouter_UNSTABLE() {
const router = useContext(RouterContext);
if (!router) {
throw new Error('Missing Router');
}
const { route, changeRoute, prefetchRoute } = router;
const push = useCallback(
(to: string) => {
const url = new URL(to, window.location.href);
window.history.pushState(
{
...window.history.state,
waku_new_path: url.pathname !== window.location.pathname,
},
'',
url,
);
changeRoute(parseRoute(url));
},
[changeRoute],
);
const replace = useCallback(
(to: string) => {
const url = new URL(to, window.location.href);
window.history.replaceState(window.history.state, '', url);
changeRoute(parseRoute(url));
},
[changeRoute],
);
const reload = useCallback(() => {
const url = new URL(window.location.href);
changeRoute(parseRoute(url));
}, [changeRoute]);
const back = useCallback(() => {
// FIXME is this correct?
window.history.back();
}, []);
const forward = useCallback(() => {
// FIXME is this correct?
window.history.forward();
}, []);
const prefetch = useCallback(
(to: string) => {
const url = new URL(to, window.location.href);
prefetchRoute(parseRoute(url));
},
[prefetchRoute],
);
return {
get value() {
console.warn(
'router.value is deprecated. Use router.path and router.searchParams instead.',
);
return route;
},
...route,
push,
replace,
reload,
back,
forward,
prefetch,
};
}
export type LinkProps = {
to: string;
pending?: ReactNode;
notPending?: ReactNode;
children: ReactNode;
unstable_prefetchOnEnter?: boolean;
} & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>;
export function Link({
to,
children,
pending,
notPending,
unstable_prefetchOnEnter,
...props
}: LinkProps): ReactElement {
const router = useContext(RouterContext);
const changeRoute = router
? router.changeRoute
: () => {
throw new Error('Missing Router');
};
const prefetchRoute = router
? router.prefetchRoute
: () => {
throw new Error('Missing Router');
};
const [isPending, startTransition] = useTransition();
const onClick = (event: MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
const url = new URL(to, window.location.href);
if (url.href !== window.location.href) {
const route = parseRoute(url);
prefetchRoute(route);
startTransition(() => {
window.history.pushState(
{
...window.history.state,
waku_new_path: url.pathname !== window.location.pathname,
},
'',
url,
);
changeRoute(route);
});
}
props.onClick?.(event);
};
const onMouseEnter = unstable_prefetchOnEnter
? (event: MouseEvent<HTMLAnchorElement>) => {
const url = new URL(to, window.location.href);
if (url.href !== window.location.href) {
const route = parseRoute(url);
prefetchRoute(route);
}
props.onMouseEnter?.(event);
}
: props.onMouseEnter;
const ele = createElement(
'a',
{ ...props, href: to, onClick, onMouseEnter },
children,
);
if (isPending && pending !== undefined) {
return createElement(Fragment, null, ele, pending);
}
if (!isPending && notPending !== undefined) {
return createElement(Fragment, null, ele, notPending);
}
return ele;
}
const getSkipList = (
shouldSkip: ShouldSkip | undefined,
componentIds: readonly string[],
route: RouteProps,
cached: Record<string, RouteProps>,
): string[] => {
const shouldSkipObj = Object.fromEntries(shouldSkip || []);
return componentIds.filter((id) => {
const prevProps = cached[id];
if (!prevProps) {
return false;
}
const shouldCheck = shouldSkipObj[id];
if (!shouldCheck) {
return false;
}
if (shouldCheck[0] && route.path !== prevProps.path) {
return false;
}
if (
shouldCheck[1]?.some(
(key) =>
route.searchParams.get(key) !== prevProps.searchParams.get(key),
)
) {
return false;
}
return true;
});
};
const equalRouteProps = (a: RouteProps, b: RouteProps) => {
if (a.path !== b.path) {
return false;
}
if (a.searchParams.size !== b.searchParams.size) {
return false;
}
if (
Array.from(a.searchParams.entries()).some(
([key, val]) => val !== b.searchParams.get(key),
)
) {
return false;
}
return true;
};
function InnerRouter({ routerData }: { routerData: RouterData }) {
const refetch = useRefetch();
const [route, setRoute] = useState(() =>
parseRoute(new URL(window.location.href)),
);
const componentIds = getComponentIds(route.path);
const [cached, setCached] = useState<Record<string, RouteProps>>(() => {
return Object.fromEntries(componentIds.map((id) => [id, route]));
});
const cachedRef = useRef(cached);
useEffect(() => {
cachedRef.current = cached;
}, [cached]);
const changeRoute: ChangeRoute = useCallback(
(route, options) => {
const { checkCache, skipRefetch } = options || {};
setRoute(route);
const componentIds = getComponentIds(route.path);
if (
checkCache &&
componentIds.every((id) => {
const cachedLoc = cachedRef.current[id];
return cachedLoc && equalRouteProps(cachedLoc, route);
})
) {
return; // everything is cached
}
const shouldSkip = routerData[0];
const skip = getSkipList(
shouldSkip,
componentIds,
route,
cachedRef.current,
);
if (componentIds.every((id) => skip.includes(id))) {
return; // everything is skipped
}
const input = getInputString(route.path);
if (!skipRefetch) {
refetch(
input,
new URLSearchParams([
...Array.from(route.searchParams.entries()),
...skip.map((id) => [PARAM_KEY_SKIP, id]),
]),
);
}
setCached((prev) => ({
...prev,
...Object.fromEntries(
componentIds.flatMap((id) =>
skip.includes(id) ? [] : [[id, route]],
),
),
}));
},
[refetch, routerData],
);
const prefetchRoute: PrefetchRoute = useCallback(
(route) => {
const componentIds = getComponentIds(route.path);
const shouldSkip = routerData[0];
const skip = getSkipList(
shouldSkip,
componentIds,
route,
cachedRef.current,
);
if (componentIds.every((id) => skip.includes(id))) {
return; // everything is cached
}
const input = getInputString(route.path);
const searchParamsString = new URLSearchParams([
...Array.from(route.searchParams.entries()),
...skip.map((id) => [PARAM_KEY_SKIP, id]),
]).toString();
prefetchRSC(input, searchParamsString);
(globalThis as any).__WAKU_ROUTER_PREFETCH__?.(route.path);
},
[routerData],
);
useEffect(() => {
const callback = () => {
const route = parseRoute(new URL(window.location.href));
changeRoute(route, { checkCache: true });
};
window.addEventListener('popstate', callback);
return () => {
window.removeEventListener('popstate', callback);
};
}, [changeRoute]);
useEffect(() => {
const callback = (pathname: string, searchParamsString: string) => {
const url = new URL(window.location.href);
url.pathname = pathname;
url.search = searchParamsString;
url.hash = '';
changeRoute(parseRoute(url), { skipRefetch: true });
};
const listeners = (routerData[1] ||= new Set());
listeners.add(callback);
return () => {
listeners.delete(callback);
};
}, [changeRoute, routerData]);
useEffect(() => {
const { hash } = window.location;
const { state } = window.history;
const element = hash && document.getElementById(hash.slice(1));
window.scrollTo({
left: 0,
top: element ? element.getBoundingClientRect().top + window.scrollY : 0,
behavior: state?.waku_new_path ? 'instant' : 'auto',
});
});
const children = componentIds.reduceRight(
(acc: ReactNode, id) => createElement(Slot, { id, fallback: acc }, acc),
null,
);
return createElement(
RouterContext.Provider,
{ value: { route, changeRoute, prefetchRoute } },
children,
);
}
// Note: The router data must be a stable mutable object (array).
type RouterData = [
shouldSkip?: ShouldSkip,
locationListners?: Set<
(pathname: string, searchParamsString: string) => void
>,
];
const DEFAULT_ROUTER_DATA: RouterData = [];
export function Router({ routerData = DEFAULT_ROUTER_DATA }) {
const route = parseRoute(new URL(window.location.href));
const initialInput = getInputString(route.path);
const initialSearchParamsString = route.searchParams.toString();
const unstable_onFetchData = (data: unknown) => {
Promise.resolve(data)
.then((data) => {
if (data && typeof data === 'object') {
// We need to process SHOULD_SKIP_ID before LOCATION_ID
if (SHOULD_SKIP_ID in data) {
routerData[0] = data[SHOULD_SKIP_ID] as ShouldSkip;
}
if (LOCATION_ID in data) {
const [pathname, searchParamsString] = data[LOCATION_ID] as [
string,
string,
];
// FIXME this check here seems ad-hoc (less readable code)
if (
window.location.pathname !== pathname ||
window.location.search.replace(/^\?/, '') !== searchParamsString
) {
routerData[1]?.forEach((listener) =>
listener(pathname, searchParamsString),
);
}
}
}
})
.catch(() => {});
};
return createElement(
ErrorBoundary,
null,
createElement(
Root as FunctionComponent<Omit<ComponentProps<typeof Root>, 'children'>>,
{ initialInput, initialSearchParamsString, unstable_onFetchData },
createElement(InnerRouter, { routerData }),
),
);
}
const notAvailableInServer = (name: string) => () => {
throw new Error(`${name} is not in the server`);
};
/**
* ServerRouter for SSR
* This is not a public API.
*/
export function ServerRouter({
children,
route,
}: {
children: ReactNode;
route: RouteProps;
}) {
return createElement(
Fragment,
null,
createElement(
RouterContext.Provider,
{
value: {
route,
changeRoute: notAvailableInServer('changeRoute'),
prefetchRoute: notAvailableInServer('prefetchRoute'),
},
},
children,
),
);
}
class ErrorBoundary extends Component<
{ children: ReactNode },
{ error?: unknown }
> {
constructor(props: { children: ReactNode }) {
super(props);
this.state = {};
}
static getDerivedStateFromError(error: unknown) {
return { error };
}
render() {
if ('error' in this.state) {
if (
this.state.error instanceof Error &&
(this.state.error as any).statusCode === 404
) {
return createElement('h1', null, 'Not Found');
}
return createElement('h1', null, String(this.state.error));
}
return this.props.children;
}
}