-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathrouter.js
More file actions
275 lines (232 loc) · 8.6 KB
/
router.js
File metadata and controls
275 lines (232 loc) · 8.6 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
import { h, createContext, cloneElement, toChildArray } from 'preact';
import { useContext, useMemo, useReducer, useLayoutEffect, useRef } from 'preact/hooks';
/**
* @template T
* @typedef {import('preact').RefObject<T>} RefObject
* @typedef {import('./internal.d.ts').VNode} VNode
*/
let push, scope;
const UPDATE = (state, url) => {
push = undefined;
if (url && url.type === 'click') {
// ignore events the browser takes care of already:
if (url.ctrlKey || url.metaKey || url.altKey || url.shiftKey || url.button !== 0) {
return state;
}
const link = url.target.closest('a[href]'),
href = link && link.getAttribute('href');
if (
!link ||
link.origin != location.origin ||
/^#/.test(href) ||
!/^(_?self)?$/i.test(link.target) ||
scope && (typeof scope == 'string'
? !href.startsWith(scope)
: !scope.test(href)
)
) {
return state;
}
push = true;
url.preventDefault();
url = link.href.replace(location.origin, '');
} else if (typeof url === 'string') {
push = true;
} else if (url && url.url) {
push = !url.replace;
url = url.url;
} else {
url = location.pathname + location.search;
}
if (push === true) history.pushState(null, '', url);
else if (push === false) history.replaceState(null, '', url);
return url;
};
export const exec = (url, route, matches = {}) => {
url = url.split('/').filter(Boolean);
route = (route || '').split('/').filter(Boolean);
if (!matches.params) matches.params = {};
for (let i = 0, val, rest; i < Math.max(url.length, route.length); i++) {
let [, m, param, flag] = (route[i] || '').match(/^(:?)(.*?)([+*?]?)$/);
val = url[i];
// segment match:
if (!m && param == val) continue;
// /foo/* match
if (!m && val && flag == '*') {
matches.rest = '/' + url.slice(i).map(decodeURIComponent).join('/');
break;
}
// segment mismatch / missing required field:
if (!m || (!val && flag != '?' && flag != '*')) return;
rest = flag == '+' || flag == '*';
// rest (+/*) match:
if (rest) val = url.slice(i).map(decodeURIComponent).join('/') || undefined;
// normal/optional field:
else if (val) val = decodeURIComponent(val);
matches.params[param] = val;
if (!(param in matches)) matches[param] = val;
if (rest) break;
}
return matches;
};
/**
* @type {import('./router.d.ts').LocationProvider}
*/
export function LocationProvider(props) {
// @ts-expect-error - props.url is not implemented correctly & will be removed in the future
const [url, route] = useReducer(UPDATE, props.url || location.pathname + location.search);
if (props.scope) scope = props.scope;
const wasPush = push === true;
const value = useMemo(() => {
const u = new URL(url, location.origin);
const path = u.pathname.replace(/\/+$/g, '') || '/';
// @ts-ignore-next
return {
url,
path,
query: Object.fromEntries(u.searchParams),
route: (url, replace) => route({ url, replace }),
wasPush
};
}, [url]);
useLayoutEffect(() => {
addEventListener('click', route);
addEventListener('popstate', route);
return () => {
removeEventListener('click', route);
removeEventListener('popstate', route);
};
}, []);
// @ts-ignore
return h(LocationProvider.ctx.Provider, { value }, props.children);
}
const RESOLVED = Promise.resolve();
/** @this {import('./internal.d.ts').AugmentedComponent} */
export function Router(props) {
const [c, update] = useReducer(c => c + 1, 0);
const { url, query, wasPush, path } = useLocation();
const { rest = path, params = {} } = useContext(RouteContext);
const isLoading = useRef(false);
const prevRoute = useRef(path);
// Monotonic counter used to check if an un-suspending route is still the current route:
const count = useRef(0);
// The current route:
const cur = /** @type {RefObject<VNode<any>>} */ (useRef());
// Previous route (if current route is suspended):
const prev = /** @type {RefObject<VNode<any>>} */ (useRef());
// A not-yet-hydrated DOM root to remove once we commit:
const pendingBase = /** @type {RefObject<Element | Text>} */ (useRef());
// has this component ever successfully rendered without suspending:
const hasEverCommitted = useRef(false);
// was the most recent render successful (did not suspend):
const didSuspend = /** @type {RefObject<boolean>} */ (useRef());
didSuspend.current = false;
let pathRoute, defaultRoute, matchProps;
toChildArray(props.children).some((/** @type {VNode<any>} */ vnode) => {
const matches = exec(rest, vnode.props.path, (matchProps = { ...vnode.props, path: rest, query, params, rest: '' }));
if (matches) return (pathRoute = cloneElement(vnode, matchProps));
if (vnode.props.default) defaultRoute = cloneElement(vnode, matchProps);
});
/** @type {VNode<any> | undefined} */
let incoming = pathRoute || defaultRoute;
const isHydratingSuspense = cur.current && cur.current.__u & MODE_HYDRATE && cur.current.__u & MODE_SUSPENDED;
const isHydratingBool = cur.current && cur.current.__h;
const routeChanged = useMemo(() => {
prev.current = cur.current;
cur.current = /** @type {VNode<any>} */ (h(RouteContext.Provider, { value: matchProps }, incoming));
// Only mark as an update if the route component changed.
const outgoing = prev.current && prev.current.props.children;
if (!outgoing || !incoming || incoming.type !== outgoing.type || incoming.props.component !== outgoing.props.component) {
// This hack prevents Preact from diffing when we swap `cur` to `prev`:
if (this.__v && this.__v.__k) this.__v.__k.reverse();
count.current++;
return true;
}
return false;
}, [url, JSON.stringify(matchProps)]);
if (isHydratingSuspense) {
cur.current.__u |= MODE_HYDRATE;
cur.current.__u |= MODE_SUSPENDED;
} else if (isHydratingBool) {
cur.current.__h = true;
}
// Reset previous children - if rendering succeeds synchronously, we shouldn't render the previous children.
const p = prev.current;
prev.current = null;
// This borrows the _childDidSuspend() solution from compat.
this.__c = (e, suspendedVNode) => {
// Mark the current render as having suspended:
didSuspend.current = true;
// The new route suspended, so keep the previous route around while it loads:
prev.current = p;
// Fire an event saying we're waiting for the route:
if (props.onLoadStart) props.onLoadStart(url);
isLoading.current = true;
// Re-render on unsuspend:
let c = count.current;
e.then(() => {
// Ignore this update if it isn't the most recently suspended update:
if (c !== count.current) return;
// Successful route transition: un-suspend after a tick and stop rendering the old route:
prev.current = null;
if (cur.current) {
if (suspendedVNode.__h) {
// _hydrating
cur.current.__h = suspendedVNode.__h;
}
if (suspendedVNode.__u & MODE_SUSPENDED) {
// _flags
cur.current.__u |= MODE_SUSPENDED;
}
if (suspendedVNode.__u & MODE_HYDRATE) {
cur.current.__u |= MODE_HYDRATE;
}
}
RESOLVED.then(update);
});
};
useLayoutEffect(() => {
const currentDom = this.__v && this.__v.__e;
// Ignore suspended renders (failed commits):
if (didSuspend.current) {
// If we've never committed, mark any hydration DOM for removal on the next commit:
if (!hasEverCommitted.current && !pendingBase.current) {
pendingBase.current = currentDom;
}
return;
}
// If this is the first ever successful commit and we didn't use the hydration DOM, remove it:
if (!hasEverCommitted.current && pendingBase.current) {
if (pendingBase.current !== currentDom) pendingBase.current.remove();
pendingBase.current = null;
}
// Mark the component has having committed:
hasEverCommitted.current = true;
// The route is loaded and rendered.
if (prevRoute.current !== path) {
if (wasPush) scrollTo(0, 0);
if (props.onRouteChange) props.onRouteChange(url);
prevRoute.current = path;
}
if (props.onLoadEnd && isLoading.current) props.onLoadEnd(url);
isLoading.current = false;
}, [path, wasPush, c]);
// Note: cur MUST render first in order to set didSuspend & prev.
return routeChanged
? [h(RenderRef, { r: cur }), h(RenderRef, { r: prev })]
: h(RenderRef, { r: cur });
}
const MODE_HYDRATE = 1 << 5;
const MODE_SUSPENDED = 1 << 7;
// Lazily render a ref's current value:
const RenderRef = ({ r }) => r.current;
Router.Provider = LocationProvider;
LocationProvider.ctx = createContext(
/** @type {import('./router.d.ts').LocationHook & { wasPush: boolean }} */ ({})
);
const RouteContext = createContext(
/** @type {import('./router.d.ts').RouteHook & { rest: string }} */ ({})
);
export const Route = props => h(props.component, props);
export const useLocation = () => useContext(LocationProvider.ctx);
export const useRoute = () => useContext(RouteContext);