@oomfware/stacker 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +14 -0
- package/README.md +286 -0
- package/dist/index.d.mts +548 -0
- package/dist/index.mjs +1102 -0
- package/dist/testing.d.mts +33 -0
- package/dist/testing.mjs +121 -0
- package/dist/types-Dj7Al7f8.d.mts +129 -0
- package/dist/url-CoOVqRk_.mjs +37 -0
- package/package.json +74 -0
- package/src/build.ts +53 -0
- package/src/cache.ts +53 -0
- package/src/codec.ts +182 -0
- package/src/history/memory.ts +155 -0
- package/src/history/navigation.ts +213 -0
- package/src/history/types.ts +133 -0
- package/src/index.ts +52 -0
- package/src/keys.ts +41 -0
- package/src/match.ts +180 -0
- package/src/react/context.ts +18 -0
- package/src/react/hooks.ts +178 -0
- package/src/react/link.tsx +61 -0
- package/src/react/outlet.tsx +18 -0
- package/src/react/router-view.tsx +79 -0
- package/src/router.ts +397 -0
- package/src/routes.ts +325 -0
- package/src/testing.ts +2 -0
- package/src/url.ts +41 -0
- package/src/view-model.ts +78 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1102 @@
|
|
|
1
|
+
import { n as parsePath, t as createPath } from "./url-CoOVqRk_.mjs";
|
|
2
|
+
import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
|
|
3
|
+
import { Suspense, createContext, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
|
|
4
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
5
|
+
//#region src/codec.ts
|
|
6
|
+
const OPTIONAL = Symbol("stacker.optional");
|
|
7
|
+
const DEFAULT = Symbol("stacker.default");
|
|
8
|
+
/**
|
|
9
|
+
* creates a codec for a string segment.
|
|
10
|
+
*
|
|
11
|
+
* @returns the string codec
|
|
12
|
+
*/
|
|
13
|
+
const string = () => ({
|
|
14
|
+
decode: (raw) => raw,
|
|
15
|
+
encode: (value) => value
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* creates a codec for a safe integer.
|
|
19
|
+
*
|
|
20
|
+
* @returns the integer codec
|
|
21
|
+
*/
|
|
22
|
+
const integer = () => ({
|
|
23
|
+
decode: (raw) => {
|
|
24
|
+
if (!/^(?:0|-[1-9]\d*|[1-9]\d*)$/.test(raw)) return;
|
|
25
|
+
const value = Number(raw);
|
|
26
|
+
return Number.isSafeInteger(value) ? value : void 0;
|
|
27
|
+
},
|
|
28
|
+
encode: (value) => {
|
|
29
|
+
if (!Number.isSafeInteger(value) || Object.is(value, -0)) throw new Error(`stacker: integer() cannot encode ${value}`);
|
|
30
|
+
return String(value);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
/**
|
|
34
|
+
* creates a codec for a boolean value.
|
|
35
|
+
*
|
|
36
|
+
* @returns the boolean codec
|
|
37
|
+
*/
|
|
38
|
+
const boolean = () => ({
|
|
39
|
+
decode: (raw) => {
|
|
40
|
+
switch (raw) {
|
|
41
|
+
case "false": return false;
|
|
42
|
+
case "true": return true;
|
|
43
|
+
default: return;
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
encode: (value) => value ? "true" : "false"
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* creates a codec for a fixed set of string values.
|
|
50
|
+
*
|
|
51
|
+
* @param values the allowed string values
|
|
52
|
+
* @returns the enum codec
|
|
53
|
+
*/
|
|
54
|
+
const enumOf = (values) => {
|
|
55
|
+
const set = new Set(values);
|
|
56
|
+
return {
|
|
57
|
+
decode: (raw) => set.has(raw) ? raw : void 0,
|
|
58
|
+
encode: (value) => value
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* wraps a codec to allow its parameter to be absent.
|
|
63
|
+
*
|
|
64
|
+
* @param codec the inner codec
|
|
65
|
+
* @returns the optional codec
|
|
66
|
+
*/
|
|
67
|
+
const optional = (codec) => ({
|
|
68
|
+
decode: (raw) => codec.decode(raw),
|
|
69
|
+
encode: (value) => codec.encode(value),
|
|
70
|
+
[OPTIONAL]: true
|
|
71
|
+
});
|
|
72
|
+
/**
|
|
73
|
+
* wraps a codec with a default value.
|
|
74
|
+
*
|
|
75
|
+
* @param codec the inner codec
|
|
76
|
+
* @param fallback the default value
|
|
77
|
+
* @returns the defaulted codec
|
|
78
|
+
*/
|
|
79
|
+
const withDefault = (codec, fallback) => ({
|
|
80
|
+
decode: (raw) => codec.decode(raw),
|
|
81
|
+
encode: (value) => codec.encode(value),
|
|
82
|
+
[DEFAULT]: fallback
|
|
83
|
+
});
|
|
84
|
+
const isOptional = (codec) => {
|
|
85
|
+
return OPTIONAL in codec;
|
|
86
|
+
};
|
|
87
|
+
const getDefault = (codec) => {
|
|
88
|
+
return DEFAULT in codec ? [codec[DEFAULT]] : void 0;
|
|
89
|
+
};
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/routes.ts
|
|
92
|
+
/**
|
|
93
|
+
* defines a navigable leaf route.
|
|
94
|
+
*
|
|
95
|
+
* @param config the route configuration
|
|
96
|
+
* @returns the route leaf node
|
|
97
|
+
*/
|
|
98
|
+
const route = (config) => ({
|
|
99
|
+
kind: "route",
|
|
100
|
+
...config
|
|
101
|
+
});
|
|
102
|
+
/**
|
|
103
|
+
* defines an interior layout node.
|
|
104
|
+
*
|
|
105
|
+
* @param config the layout configuration
|
|
106
|
+
* @returns the layout node
|
|
107
|
+
*/
|
|
108
|
+
const layout = (config) => ({
|
|
109
|
+
kind: "layout",
|
|
110
|
+
...config
|
|
111
|
+
});
|
|
112
|
+
const PATH_PARAM = /:([A-Za-z_]\w*)/g;
|
|
113
|
+
const pathParamNames = (path) => {
|
|
114
|
+
const names = [];
|
|
115
|
+
for (const match of path.matchAll(PATH_PARAM)) {
|
|
116
|
+
const name = match[1];
|
|
117
|
+
if (name !== void 0) names.push(name);
|
|
118
|
+
}
|
|
119
|
+
return names;
|
|
120
|
+
};
|
|
121
|
+
const sameKeySet = (a, b) => {
|
|
122
|
+
if (a.length !== b.length) return false;
|
|
123
|
+
const set = new Set(a);
|
|
124
|
+
return b.every((key) => set.has(key));
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* compiles a route tree, validating keys, paths, and parameter codecs.
|
|
128
|
+
*
|
|
129
|
+
* @param tree the route tree configuration
|
|
130
|
+
* @returns the compiled registry
|
|
131
|
+
* @throws when route definitions violate nesting, unique names, or codec constraints
|
|
132
|
+
*/
|
|
133
|
+
const defineRoutes = (tree) => {
|
|
134
|
+
const leaves = /* @__PURE__ */ new Map();
|
|
135
|
+
const ids = /* @__PURE__ */ new Set();
|
|
136
|
+
const visit = (children, parentChain, parentId) => {
|
|
137
|
+
for (const [key, node] of Object.entries(children)) {
|
|
138
|
+
if (key.includes(".")) throw new Error(`stacker: route key '${key}' must not contain '.'`);
|
|
139
|
+
const id = parentId ? `${parentId}.${key}` : key;
|
|
140
|
+
if (ids.has(id)) throw new Error(`stacker: duplicate node id '${id}'`);
|
|
141
|
+
const params = node.params ?? {};
|
|
142
|
+
const resolved = {
|
|
143
|
+
id,
|
|
144
|
+
key,
|
|
145
|
+
kind: node.kind,
|
|
146
|
+
node,
|
|
147
|
+
params,
|
|
148
|
+
path: node.kind === "route" ? node.path : void 0
|
|
149
|
+
};
|
|
150
|
+
ids.add(id);
|
|
151
|
+
const chain = [...parentChain, resolved];
|
|
152
|
+
if (node.kind === "layout") {
|
|
153
|
+
visit(node.children, chain, id);
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (leaves.has(key)) throw new Error(`stacker: duplicate route name '${key}'`);
|
|
157
|
+
if (!node.path.startsWith("/")) throw new Error(`stacker: route '${key}' path '${node.path}' must start with '/'`);
|
|
158
|
+
const query = node.query ?? {};
|
|
159
|
+
const ownPathParams = pathParamNames(node.path);
|
|
160
|
+
const declaredParams = Object.keys(params);
|
|
161
|
+
if (!sameKeySet(ownPathParams, declaredParams)) throw new Error(`stacker: route '${key}' path params [${ownPathParams.join(", ")}] do not match declared params [${declaredParams.join(", ")}]`);
|
|
162
|
+
for (const [paramName, codec] of Object.entries(params)) if (isOptional(codec) || getDefault(codec) !== void 0) throw new Error(`stacker: path param '${paramName}' of route '${key}' must not be optional() or withDefault()`);
|
|
163
|
+
for (const queryKey of Object.keys(query)) if (queryKey in params) throw new Error(`stacker: route '${key}' declares '${queryKey}' as both a path and query param`);
|
|
164
|
+
for (const ancestor of chain) {
|
|
165
|
+
if (ancestor.kind !== "layout") continue;
|
|
166
|
+
for (const layoutParam of Object.keys(ancestor.params)) if (!ownPathParams.includes(layoutParam)) throw new Error(`stacker: layout '${ancestor.id}' param '${layoutParam}' is not present in route '${key}' path '${node.path}'`);
|
|
167
|
+
}
|
|
168
|
+
leaves.set(key, {
|
|
169
|
+
chain,
|
|
170
|
+
leaf: node,
|
|
171
|
+
name: key,
|
|
172
|
+
params,
|
|
173
|
+
path: node.path,
|
|
174
|
+
query
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
visit(tree, [], "");
|
|
179
|
+
return {
|
|
180
|
+
leaves,
|
|
181
|
+
tree
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/match.ts
|
|
186
|
+
/**
|
|
187
|
+
* looks up the nearest metadata value for a key on a matched chain, searching leaf-first.
|
|
188
|
+
*
|
|
189
|
+
* @param match the route match chain
|
|
190
|
+
* @param key the metadata key to resolve
|
|
191
|
+
* @returns the nearest metadata value, or undefined if none is found
|
|
192
|
+
*/
|
|
193
|
+
const resolveMeta = (match, key) => {
|
|
194
|
+
for (let i = match.chain.length - 1; i >= 0; i--) {
|
|
195
|
+
const value = match.chain[i]?.node.node.meta?.[key];
|
|
196
|
+
if (value !== void 0) return value;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
const SEGMENT$1 = /:[A-Za-z_]\w*/g;
|
|
200
|
+
const escapeRegExp = (segment) => segment.replaceAll(/[$()*+.?[\\\]^{|}]/g, "\\$&");
|
|
201
|
+
const compile = (path) => {
|
|
202
|
+
const paramNames = [];
|
|
203
|
+
let pattern = "";
|
|
204
|
+
let lastIndex = 0;
|
|
205
|
+
for (const match of path.matchAll(SEGMENT$1)) {
|
|
206
|
+
const whole = match[0];
|
|
207
|
+
const at = match.index;
|
|
208
|
+
if (at === void 0) continue;
|
|
209
|
+
paramNames.push(whole.slice(1));
|
|
210
|
+
pattern += `${escapeRegExp(path.slice(lastIndex, at))}([^/]+)`;
|
|
211
|
+
lastIndex = at + whole.length;
|
|
212
|
+
}
|
|
213
|
+
pattern += escapeRegExp(path.slice(lastIndex));
|
|
214
|
+
const suffix = pattern.endsWith("/") ? "" : "/?";
|
|
215
|
+
return {
|
|
216
|
+
paramNames,
|
|
217
|
+
regex: new RegExp(`^${pattern}${suffix}$`)
|
|
218
|
+
};
|
|
219
|
+
};
|
|
220
|
+
/** matches URLs in declaration order against a compiled route registry. */
|
|
221
|
+
var Matcher = class {
|
|
222
|
+
#compiled;
|
|
223
|
+
constructor(registry) {
|
|
224
|
+
this.#compiled = [...registry.leaves.values()].map((leaf) => {
|
|
225
|
+
const { paramNames, regex } = compile(leaf.path);
|
|
226
|
+
return {
|
|
227
|
+
leaf,
|
|
228
|
+
paramNames,
|
|
229
|
+
regex
|
|
230
|
+
};
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
match(pathname, search = "", hash = "") {
|
|
234
|
+
const rawSearch = new URLSearchParams(search);
|
|
235
|
+
const ctx = {
|
|
236
|
+
hash,
|
|
237
|
+
pathname,
|
|
238
|
+
rawSearch,
|
|
239
|
+
search
|
|
240
|
+
};
|
|
241
|
+
for (const { leaf, paramNames, regex } of this.#compiled) {
|
|
242
|
+
const execed = regex.exec(pathname);
|
|
243
|
+
if (execed === null) continue;
|
|
244
|
+
const raw = this.#rawValues(paramNames, execed);
|
|
245
|
+
if (raw === void 0) continue;
|
|
246
|
+
const perNode = this.#decodeChain(leaf.chain, raw);
|
|
247
|
+
if (perNode === void 0) continue;
|
|
248
|
+
const query = this.#decodeQuery(leaf, rawSearch);
|
|
249
|
+
if (query === void 0) continue;
|
|
250
|
+
if (leaf.leaf.when && !leaf.leaf.when(ctx)) continue;
|
|
251
|
+
const chain = leaf.chain.map((node) => {
|
|
252
|
+
const own = perNode.get(node.id) ?? {};
|
|
253
|
+
return {
|
|
254
|
+
node,
|
|
255
|
+
params: node.kind === "route" ? {
|
|
256
|
+
...own,
|
|
257
|
+
...query
|
|
258
|
+
} : own
|
|
259
|
+
};
|
|
260
|
+
});
|
|
261
|
+
return {
|
|
262
|
+
chain,
|
|
263
|
+
leaf,
|
|
264
|
+
name: leaf.name,
|
|
265
|
+
params: chain.at(-1)?.params ?? {}
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
#rawValues(paramNames, execed) {
|
|
270
|
+
const raw = {};
|
|
271
|
+
for (const [i, name] of paramNames.entries()) {
|
|
272
|
+
const value = execed[i + 1];
|
|
273
|
+
if (value === void 0) return;
|
|
274
|
+
try {
|
|
275
|
+
raw[name] = decodeURIComponent(value);
|
|
276
|
+
} catch {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return raw;
|
|
281
|
+
}
|
|
282
|
+
#decodeChain(chain, raw) {
|
|
283
|
+
const perNode = /* @__PURE__ */ new Map();
|
|
284
|
+
for (const node of chain) {
|
|
285
|
+
const decoded = {};
|
|
286
|
+
for (const [name, codec] of Object.entries(node.params)) {
|
|
287
|
+
const rawValue = raw[name];
|
|
288
|
+
if (rawValue === void 0) return;
|
|
289
|
+
const value = codec.decode(rawValue);
|
|
290
|
+
if (value === void 0) return;
|
|
291
|
+
decoded[name] = value;
|
|
292
|
+
}
|
|
293
|
+
perNode.set(node.id, decoded);
|
|
294
|
+
}
|
|
295
|
+
return perNode;
|
|
296
|
+
}
|
|
297
|
+
#decodeQuery(leaf, rawSearch) {
|
|
298
|
+
const out = {};
|
|
299
|
+
for (const [name, codec] of Object.entries(leaf.query)) {
|
|
300
|
+
const rawValue = rawSearch.get(name);
|
|
301
|
+
if (rawValue !== null) {
|
|
302
|
+
const value = codec.decode(rawValue);
|
|
303
|
+
if (value === void 0) return;
|
|
304
|
+
out[name] = value;
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
const fallback = getDefault(codec);
|
|
308
|
+
if (fallback !== void 0) out[name] = fallback[0];
|
|
309
|
+
else if (!isOptional(codec)) return;
|
|
310
|
+
}
|
|
311
|
+
return out;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/history/navigation.ts
|
|
316
|
+
const ENVELOPE = Symbol("stacker.historyInfo");
|
|
317
|
+
const isEnvelope = (value) => typeof value === "object" && value !== null && ENVELOPE in value;
|
|
318
|
+
const toAction = (type) => {
|
|
319
|
+
switch (type) {
|
|
320
|
+
case "push":
|
|
321
|
+
case "replace":
|
|
322
|
+
case "traverse": return type;
|
|
323
|
+
default: return;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
const ignore = (result) => {
|
|
327
|
+
result.committed?.catch(() => {});
|
|
328
|
+
result.finished?.catch(() => {});
|
|
329
|
+
};
|
|
330
|
+
/**
|
|
331
|
+
* history implementation backed by the web navigation API.
|
|
332
|
+
*
|
|
333
|
+
* intercepting same-document navigations converts standard page loads into in-app renders. per-revision
|
|
334
|
+
* metadata and indices are managed natively by the browser.
|
|
335
|
+
*/
|
|
336
|
+
var NavigationHistory = class {
|
|
337
|
+
#win;
|
|
338
|
+
#nav;
|
|
339
|
+
#ignore;
|
|
340
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
341
|
+
#location;
|
|
342
|
+
constructor(options = {}) {
|
|
343
|
+
this.#win = options.window ?? window;
|
|
344
|
+
this.#nav = this.#win.navigation;
|
|
345
|
+
this.#ignore = options.ignore;
|
|
346
|
+
this.#location = this.#read();
|
|
347
|
+
this.#nav.addEventListener("navigate", this.#onNavigate);
|
|
348
|
+
}
|
|
349
|
+
get location() {
|
|
350
|
+
return this.#location;
|
|
351
|
+
}
|
|
352
|
+
get canGoBack() {
|
|
353
|
+
return this.#nav.canGoBack;
|
|
354
|
+
}
|
|
355
|
+
get canGoForward() {
|
|
356
|
+
return this.#nav.canGoForward;
|
|
357
|
+
}
|
|
358
|
+
entries() {
|
|
359
|
+
return this.#nav.entries().map((entry) => ({
|
|
360
|
+
id: entry.id,
|
|
361
|
+
index: entry.index,
|
|
362
|
+
key: entry.key,
|
|
363
|
+
sameDocument: entry.sameDocument,
|
|
364
|
+
state: entry.getState(),
|
|
365
|
+
url: toRelative(entry.url)
|
|
366
|
+
}));
|
|
367
|
+
}
|
|
368
|
+
push(to, options = {}) {
|
|
369
|
+
this.#navigate(to, "push", options);
|
|
370
|
+
}
|
|
371
|
+
replace(to, options = {}) {
|
|
372
|
+
this.#navigate(to, "replace", options);
|
|
373
|
+
}
|
|
374
|
+
traverseTo(key) {
|
|
375
|
+
ignore(this.#nav.traverseTo(key));
|
|
376
|
+
}
|
|
377
|
+
go(delta) {
|
|
378
|
+
const entries = this.#nav.entries();
|
|
379
|
+
const target = entries[Math.max(0, Math.min(this.#location.index + delta, entries.length - 1))];
|
|
380
|
+
if (target === void 0 || target.key === this.#location.key) return;
|
|
381
|
+
this.traverseTo(target.key);
|
|
382
|
+
}
|
|
383
|
+
back() {
|
|
384
|
+
if (this.#nav.canGoBack) ignore(this.#nav.back());
|
|
385
|
+
}
|
|
386
|
+
forward() {
|
|
387
|
+
if (this.#nav.canGoForward) ignore(this.#nav.forward());
|
|
388
|
+
}
|
|
389
|
+
listen(listener) {
|
|
390
|
+
this.#listeners.add(listener);
|
|
391
|
+
return () => {
|
|
392
|
+
this.#listeners.delete(listener);
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
dispose() {
|
|
396
|
+
this.#nav.removeEventListener("navigate", this.#onNavigate);
|
|
397
|
+
this.#listeners.clear();
|
|
398
|
+
}
|
|
399
|
+
#navigate(to, history, options) {
|
|
400
|
+
const url = new URL(to, this.#win.location.href).href;
|
|
401
|
+
const envelope = {
|
|
402
|
+
[ENVELOPE]: true,
|
|
403
|
+
info: options.info,
|
|
404
|
+
scroll: options.scroll ?? "auto"
|
|
405
|
+
};
|
|
406
|
+
ignore(this.#nav.navigate(url, {
|
|
407
|
+
history,
|
|
408
|
+
info: envelope,
|
|
409
|
+
state: options.state ?? null
|
|
410
|
+
}));
|
|
411
|
+
}
|
|
412
|
+
#read() {
|
|
413
|
+
const entry = this.#nav.currentEntry;
|
|
414
|
+
if (entry === null) throw new Error("stacker: the navigation API has no current entry (an opaque origin?)");
|
|
415
|
+
const { hash, pathname, search } = new URL(entry.url ?? this.#win.location.href);
|
|
416
|
+
return {
|
|
417
|
+
hash,
|
|
418
|
+
id: entry.id,
|
|
419
|
+
index: entry.index,
|
|
420
|
+
key: entry.key,
|
|
421
|
+
pathname,
|
|
422
|
+
search,
|
|
423
|
+
state: entry.getState()
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
#onNavigate = (event) => {
|
|
427
|
+
const action = toAction(event.navigationType);
|
|
428
|
+
if (action === void 0 || !event.canIntercept) return;
|
|
429
|
+
if (event.downloadRequest !== null || event.formData !== null) return;
|
|
430
|
+
if (action !== "traverse" && this.#ignore?.(new URL(event.destination.url))) return;
|
|
431
|
+
const envelope = isEnvelope(event.info) ? event.info : void 0;
|
|
432
|
+
const info = envelope === void 0 ? event.info : envelope.info;
|
|
433
|
+
const preserve = (envelope?.scroll ?? "auto") === "preserve";
|
|
434
|
+
event.intercept({
|
|
435
|
+
focusReset: preserve ? "manual" : "after-transition",
|
|
436
|
+
scroll: preserve ? "manual" : "after-transition",
|
|
437
|
+
handler: async () => {
|
|
438
|
+
this.#location = this.#read();
|
|
439
|
+
const update = {
|
|
440
|
+
action,
|
|
441
|
+
info,
|
|
442
|
+
location: this.#location
|
|
443
|
+
};
|
|
444
|
+
await Promise.all([...this.#listeners].map(async (listener) => listener(update)));
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
};
|
|
448
|
+
};
|
|
449
|
+
const toRelative = (url) => {
|
|
450
|
+
if (url === null) return null;
|
|
451
|
+
const { hash, pathname, search } = new URL(url);
|
|
452
|
+
return `${pathname}${search}${hash}`;
|
|
453
|
+
};
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region src/build.ts
|
|
456
|
+
const SEGMENT = /:([A-Za-z_]\w*)/g;
|
|
457
|
+
var Builder = class {
|
|
458
|
+
#registry;
|
|
459
|
+
constructor(registry) {
|
|
460
|
+
this.#registry = registry;
|
|
461
|
+
}
|
|
462
|
+
build(name, ...args) {
|
|
463
|
+
return this.buildPath(name, args[0] ?? {});
|
|
464
|
+
}
|
|
465
|
+
buildPath(name, params = {}) {
|
|
466
|
+
const leaf = this.#registry.leaves.get(name);
|
|
467
|
+
if (leaf === void 0) throw new Error(`stacker: unknown route '${name}'`);
|
|
468
|
+
const pathname = leaf.path.replaceAll(SEGMENT, (_full, paramName) => {
|
|
469
|
+
const codec = leaf.params[paramName];
|
|
470
|
+
const value = params[paramName];
|
|
471
|
+
if (codec === void 0 || value === void 0) throw new Error(`stacker: missing path param '${paramName}' for route '${name}'`);
|
|
472
|
+
return encodeURIComponent(codec.encode(value));
|
|
473
|
+
});
|
|
474
|
+
const search = new URLSearchParams();
|
|
475
|
+
for (const [paramName, codec] of Object.entries(leaf.query)) {
|
|
476
|
+
const value = params[paramName];
|
|
477
|
+
if (value === void 0) {
|
|
478
|
+
if (!isOptional(codec) && getDefault(codec) === void 0) throw new Error(`stacker: missing required query param '${paramName}' for route '${name}'`);
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
search.set(paramName, codec.encode(value));
|
|
482
|
+
}
|
|
483
|
+
const query = search.toString();
|
|
484
|
+
return createPath({
|
|
485
|
+
hash: "",
|
|
486
|
+
pathname,
|
|
487
|
+
search: query ? `?${query}` : ""
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
//#endregion
|
|
492
|
+
//#region src/cache.ts
|
|
493
|
+
/**
|
|
494
|
+
* computes which history entries to keep warm based on active index and recency.
|
|
495
|
+
*
|
|
496
|
+
* retains the active entry plus backward entries using an LRU policy. forward entries are dropped.
|
|
497
|
+
*/
|
|
498
|
+
const computeCachedKeys = (entries, activeIndex, recency, policy) => {
|
|
499
|
+
const cached = /* @__PURE__ */ new Set();
|
|
500
|
+
const active = entries.find((entry) => entry.index === activeIndex);
|
|
501
|
+
if (active === void 0) throw new Error(`stacker: no history entry at active index ${activeIndex}`);
|
|
502
|
+
cached.add(active.key);
|
|
503
|
+
const backward = /* @__PURE__ */ new Map();
|
|
504
|
+
for (const entry of entries) if (entry.index < activeIndex) backward.set(entry.key, entry);
|
|
505
|
+
let kept = 0;
|
|
506
|
+
const take = (key) => {
|
|
507
|
+
if (kept >= policy.max || cached.has(key) || !backward.has(key)) return;
|
|
508
|
+
cached.add(key);
|
|
509
|
+
kept += 1;
|
|
510
|
+
};
|
|
511
|
+
for (const key of recency) take(key);
|
|
512
|
+
for (const entry of [...backward.values()].toSorted((a, b) => b.index - a.index)) take(entry.key);
|
|
513
|
+
return cached;
|
|
514
|
+
};
|
|
515
|
+
//#endregion
|
|
516
|
+
//#region src/keys.ts
|
|
517
|
+
const SEP = "\0";
|
|
518
|
+
/**
|
|
519
|
+
* serializes path parameters into a stable, sorted, percent-encoded string.
|
|
520
|
+
*
|
|
521
|
+
* query parameters are excluded because they represent view state rather than instance identity.
|
|
522
|
+
*/
|
|
523
|
+
const canonical = (matched) => {
|
|
524
|
+
const codecs = matched.node.params;
|
|
525
|
+
return Object.keys(codecs).toSorted().map((name) => {
|
|
526
|
+
const codec = codecs[name];
|
|
527
|
+
if (codec === void 0) throw new Error(`stacker: no codec for param '${name}' on node '${matched.node.id}'`);
|
|
528
|
+
return `${encodeURIComponent(name)}=${encodeURIComponent(codec.encode(matched.params[name]))}`;
|
|
529
|
+
}).join("&");
|
|
530
|
+
};
|
|
531
|
+
/**
|
|
532
|
+
* generates the instance key for a node, determining if a view is reused or remounted.
|
|
533
|
+
*
|
|
534
|
+
* layouts and singleton leaves are keyed by node id and serialized path parameters, while page leaves are
|
|
535
|
+
* keyed by node id and the history slot they were reached through — one instance per entry, which is what
|
|
536
|
+
* makes a push a fresh screen and a traversal the one you left.
|
|
537
|
+
*/
|
|
538
|
+
const instanceKey = (matched, entryKey) => {
|
|
539
|
+
const resolved = matched.node;
|
|
540
|
+
if (resolved.kind === "layout") return `${resolved.id}${SEP}${canonical(matched)}`;
|
|
541
|
+
return (resolved.node.kind === "route" ? resolved.node.type ?? "page" : "page") === "singleton" ? `${resolved.id}${SEP}${canonical(matched)}` : `${resolved.id}${SEP}entry:${entryKey}`;
|
|
542
|
+
};
|
|
543
|
+
//#endregion
|
|
544
|
+
//#region src/view-model.ts
|
|
545
|
+
/**
|
|
546
|
+
* builds the active view and computes which entries and instances to prune.
|
|
547
|
+
*
|
|
548
|
+
* layout instances are shared when sibling entries resolve to matching keys. when multiple entries share an
|
|
549
|
+
* instance, the parameters from the active entry take precedence.
|
|
550
|
+
*/
|
|
551
|
+
const computeView = (cached, pinned, activeKey) => {
|
|
552
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
553
|
+
const roots = [];
|
|
554
|
+
const place = (entry, active) => {
|
|
555
|
+
let pool = roots;
|
|
556
|
+
for (const matched of entry.match.chain) {
|
|
557
|
+
const key = instanceKey(matched, entry.key);
|
|
558
|
+
let inst = byKey.get(key);
|
|
559
|
+
if (inst === void 0) {
|
|
560
|
+
inst = {
|
|
561
|
+
children: [],
|
|
562
|
+
instanceKey: key,
|
|
563
|
+
node: matched.node,
|
|
564
|
+
params: matched.params
|
|
565
|
+
};
|
|
566
|
+
byKey.set(key, inst);
|
|
567
|
+
pool.push(inst);
|
|
568
|
+
} else if (active) inst.params = matched.params;
|
|
569
|
+
pool = inst.children;
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
for (const entry of cached) place(entry, entry.key === activeKey);
|
|
573
|
+
for (const entry of pinned) place(entry, false);
|
|
574
|
+
const active = cached.find((entry) => entry.key === activeKey);
|
|
575
|
+
if (active === void 0) throw new Error(`stacker: active entry '${activeKey}' is not in the cached set`);
|
|
576
|
+
return {
|
|
577
|
+
activePath: active.match.chain.map((matched) => instanceKey(matched, active.key)),
|
|
578
|
+
roots
|
|
579
|
+
};
|
|
580
|
+
};
|
|
581
|
+
//#endregion
|
|
582
|
+
//#region src/router.ts
|
|
583
|
+
const DefaultNotFound = () => null;
|
|
584
|
+
/**
|
|
585
|
+
* manages navigation state, history subscriptions, and active views.
|
|
586
|
+
*
|
|
587
|
+
* this class acts as the store for the React router view, maintaining and caching active matched nodes and
|
|
588
|
+
* coordinates scrolling and focus.
|
|
589
|
+
*/
|
|
590
|
+
var Router = class {
|
|
591
|
+
#history;
|
|
592
|
+
#matcher;
|
|
593
|
+
#builder;
|
|
594
|
+
#routes;
|
|
595
|
+
#max;
|
|
596
|
+
#defaultFallback;
|
|
597
|
+
#notFound;
|
|
598
|
+
#pins;
|
|
599
|
+
#updates = new SimpleEventEmitter();
|
|
600
|
+
#unlisten;
|
|
601
|
+
#activePins = /* @__PURE__ */ new Set();
|
|
602
|
+
#entries = /* @__PURE__ */ new Map();
|
|
603
|
+
#activeKey;
|
|
604
|
+
#recency = [];
|
|
605
|
+
#view;
|
|
606
|
+
#commitWaiters = [];
|
|
607
|
+
#viewAttached = false;
|
|
608
|
+
constructor(options) {
|
|
609
|
+
this.#history = options.history;
|
|
610
|
+
this.#routes = options.routes;
|
|
611
|
+
this.#matcher = new Matcher(options.routes);
|
|
612
|
+
this.#builder = new Builder(options.routes);
|
|
613
|
+
this.#max = options.max ?? 5;
|
|
614
|
+
this.#defaultFallback = options.defaultFallback;
|
|
615
|
+
this.#notFound = makeNotFound(options.notFound ?? DefaultNotFound);
|
|
616
|
+
this.#pins = new Map((options.pins ?? []).map((name) => [name, this.#makePin(name)]));
|
|
617
|
+
const location = this.#history.location;
|
|
618
|
+
this.#activeKey = location.key;
|
|
619
|
+
this.#record(location);
|
|
620
|
+
this.#view = this.#recompute();
|
|
621
|
+
this.#unlisten = this.#history.listen(async ({ location: next }) => {
|
|
622
|
+
this.#prune();
|
|
623
|
+
this.#record(next);
|
|
624
|
+
this.#activeKey = next.key;
|
|
625
|
+
this.#view = this.#recompute();
|
|
626
|
+
const committed = this.#awaitCommit();
|
|
627
|
+
this.#updates.emit();
|
|
628
|
+
await committed;
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
/** current view structure. */
|
|
632
|
+
get view() {
|
|
633
|
+
return this.#view;
|
|
634
|
+
}
|
|
635
|
+
/** active history location. */
|
|
636
|
+
get location() {
|
|
637
|
+
return this.#history.location;
|
|
638
|
+
}
|
|
639
|
+
/** active route match details. */
|
|
640
|
+
get route() {
|
|
641
|
+
return this.#active().match;
|
|
642
|
+
}
|
|
643
|
+
/** whether backward history is available. */
|
|
644
|
+
get canGoBack() {
|
|
645
|
+
return this.#history.canGoBack;
|
|
646
|
+
}
|
|
647
|
+
/** whether forward history is available. */
|
|
648
|
+
get canGoForward() {
|
|
649
|
+
return this.#history.canGoForward;
|
|
650
|
+
}
|
|
651
|
+
/** default suspense fallback component. */
|
|
652
|
+
get defaultFallback() {
|
|
653
|
+
return this.#defaultFallback;
|
|
654
|
+
}
|
|
655
|
+
/** the compiled registry this router was constructed with. */
|
|
656
|
+
get routes() {
|
|
657
|
+
return this.#routes;
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* subscribes to view updates.
|
|
661
|
+
*
|
|
662
|
+
* bound to the instance, so it keeps one identity for the router's lifetime and can be handed straight to
|
|
663
|
+
* `useSyncExternalStore` — which re-subscribes whenever the function it is given changes.
|
|
664
|
+
*
|
|
665
|
+
* @param listener change callback
|
|
666
|
+
* @returns unsubscribe function
|
|
667
|
+
*/
|
|
668
|
+
subscribe = (listener) => {
|
|
669
|
+
return this.#updates.subscribe(listener);
|
|
670
|
+
};
|
|
671
|
+
/** pushes a new location onto the history stack. */
|
|
672
|
+
push(to) {
|
|
673
|
+
this.#history.push(to);
|
|
674
|
+
}
|
|
675
|
+
/** replaces the current location on the history stack. */
|
|
676
|
+
replace(to) {
|
|
677
|
+
this.#history.replace(to);
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* generates a URL for a route.
|
|
681
|
+
*
|
|
682
|
+
* @param name route name
|
|
683
|
+
* @param args route parameters
|
|
684
|
+
* @returns relative URL
|
|
685
|
+
*/
|
|
686
|
+
build(name, ...args) {
|
|
687
|
+
return this.#builder.build(name, ...args);
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* navigates to a route.
|
|
691
|
+
*
|
|
692
|
+
* @param name route name
|
|
693
|
+
* @param args route parameters
|
|
694
|
+
*/
|
|
695
|
+
navigate(name, ...args) {
|
|
696
|
+
this.push(this.#builder.build(name, ...args));
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* returns to the nearest existing history entry for a route, or pushes if none exists.
|
|
700
|
+
*
|
|
701
|
+
* @param name route name
|
|
702
|
+
* @param args route parameters
|
|
703
|
+
*/
|
|
704
|
+
popTo(name, ...args) {
|
|
705
|
+
const url = this.#builder.build(name, ...args);
|
|
706
|
+
const { hash, pathname, search } = parsePath(url);
|
|
707
|
+
const target = this.#matcher.match(pathname, search, hash);
|
|
708
|
+
if (target !== void 0) {
|
|
709
|
+
const wanted = this.#canonical(target);
|
|
710
|
+
const entries = this.#history.entries();
|
|
711
|
+
for (let i = this.#history.location.index; i >= 0; i--) {
|
|
712
|
+
const entry = entries[i];
|
|
713
|
+
if (entry === void 0 || !entry.sameDocument || entry.url === null) break;
|
|
714
|
+
const parts = parsePath(entry.url);
|
|
715
|
+
const match = this.#matcher.match(parts.pathname, parts.search, parts.hash);
|
|
716
|
+
if (match !== void 0 && match.name === target.name && this.#canonical(match) === wanted) {
|
|
717
|
+
this.#history.traverseTo(entry.key);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
this.push(url);
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* updates query parameters in-place without pushing a new entry.
|
|
726
|
+
*
|
|
727
|
+
* @param patch query parameter changes
|
|
728
|
+
*/
|
|
729
|
+
setParams(patch) {
|
|
730
|
+
const active = this.#entries.get(this.#activeKey);
|
|
731
|
+
const leaf = active === void 0 ? void 0 : this.#routes.leaves.get(active.match.name);
|
|
732
|
+
if (leaf === void 0) return;
|
|
733
|
+
const location = this.#history.location;
|
|
734
|
+
const search = new URLSearchParams(location.search);
|
|
735
|
+
for (const [name, value] of Object.entries(patch)) {
|
|
736
|
+
const codec = leaf.query[name];
|
|
737
|
+
if (codec === void 0) continue;
|
|
738
|
+
if (value === void 0) search.delete(name);
|
|
739
|
+
else search.set(name, codec.encode(value));
|
|
740
|
+
}
|
|
741
|
+
const query = search.toString();
|
|
742
|
+
const to = createPath({
|
|
743
|
+
hash: location.hash,
|
|
744
|
+
pathname: location.pathname,
|
|
745
|
+
search: query ? `?${query}` : ""
|
|
746
|
+
});
|
|
747
|
+
this.#history.replace(to, {
|
|
748
|
+
scroll: "preserve",
|
|
749
|
+
state: location.state
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
/** navigates back one entry. */
|
|
753
|
+
back() {
|
|
754
|
+
this.#history.back();
|
|
755
|
+
}
|
|
756
|
+
/** navigates forward one entry. */
|
|
757
|
+
forward() {
|
|
758
|
+
this.#history.forward();
|
|
759
|
+
}
|
|
760
|
+
/** navigates by a delta offset on the stack. */
|
|
761
|
+
go(delta) {
|
|
762
|
+
this.#history.go(delta);
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* attaches a router view to coordinate transition commits.
|
|
766
|
+
*
|
|
767
|
+
* @returns detach function
|
|
768
|
+
*/
|
|
769
|
+
attachView() {
|
|
770
|
+
this.#viewAttached = true;
|
|
771
|
+
return () => {
|
|
772
|
+
this.#viewAttached = false;
|
|
773
|
+
this.notifyCommit();
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
/** resolves pending navigation transitions after a view commits. */
|
|
777
|
+
notifyCommit() {
|
|
778
|
+
for (const resolve of this.#commitWaiters.splice(0)) resolve();
|
|
779
|
+
}
|
|
780
|
+
/** detaches history listeners and disposes resources. */
|
|
781
|
+
dispose() {
|
|
782
|
+
this.#unlisten();
|
|
783
|
+
this.#history.dispose();
|
|
784
|
+
this.notifyCommit();
|
|
785
|
+
}
|
|
786
|
+
#active() {
|
|
787
|
+
const active = this.#entries.get(this.#activeKey);
|
|
788
|
+
if (active === void 0) throw new Error(`stacker: no warm entry for the active key '${this.#activeKey}'`);
|
|
789
|
+
return active;
|
|
790
|
+
}
|
|
791
|
+
#match(location) {
|
|
792
|
+
return this.#matcher.match(location.pathname, location.search, location.hash) ?? this.#notFoundMatch();
|
|
793
|
+
}
|
|
794
|
+
#canonical(match) {
|
|
795
|
+
return this.#builder.buildPath(match.name, match.params);
|
|
796
|
+
}
|
|
797
|
+
#awaitCommit() {
|
|
798
|
+
if (!this.#viewAttached) return Promise.resolve();
|
|
799
|
+
return new Promise((resolve) => {
|
|
800
|
+
this.#commitWaiters.push(resolve);
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
#prune() {
|
|
804
|
+
const live = new Set(this.#history.entries().map((entry) => entry.key));
|
|
805
|
+
for (const key of this.#entries.keys()) if (!live.has(key)) this.#entries.delete(key);
|
|
806
|
+
}
|
|
807
|
+
#record(location) {
|
|
808
|
+
const entry = {
|
|
809
|
+
index: location.index,
|
|
810
|
+
key: location.key,
|
|
811
|
+
match: this.#match(location)
|
|
812
|
+
};
|
|
813
|
+
this.#entries.set(location.key, entry);
|
|
814
|
+
this.#recency = [entry.key, ...this.#recency.filter((key) => key !== entry.key)];
|
|
815
|
+
const pin = this.#pins.get(entry.match.name);
|
|
816
|
+
if (pin !== void 0) this.#activePins.add(pin);
|
|
817
|
+
}
|
|
818
|
+
#recompute() {
|
|
819
|
+
const active = this.#active();
|
|
820
|
+
const cachedKeys = computeCachedKeys([...this.#entries.values()].map((entry) => ({
|
|
821
|
+
index: entry.index,
|
|
822
|
+
key: entry.key
|
|
823
|
+
})), active.index, this.#recency, { max: this.#max });
|
|
824
|
+
const cached = [];
|
|
825
|
+
for (const entry of this.#entries.values()) if (cachedKeys.has(entry.key)) cached.push({
|
|
826
|
+
key: entry.key,
|
|
827
|
+
match: entry.match
|
|
828
|
+
});
|
|
829
|
+
const view = computeView(cached, [...this.#activePins], active.key);
|
|
830
|
+
for (const [key, entry] of this.#entries) if (!cachedKeys.has(entry.key)) this.#entries.delete(key);
|
|
831
|
+
this.#recency = this.#recency.filter((key) => this.#entries.has(key));
|
|
832
|
+
return view;
|
|
833
|
+
}
|
|
834
|
+
#makePin(name) {
|
|
835
|
+
const leaf = this.#routes.leaves.get(name);
|
|
836
|
+
if (leaf === void 0) throw new Error(`stacker: pinned route '${name}' is not in the registry`);
|
|
837
|
+
if ((leaf.leaf.type ?? "page") !== "singleton") throw new Error(`stacker: pinned route '${name}' must be a singleton`);
|
|
838
|
+
if (Object.keys(leaf.params).length > 0) throw new Error(`stacker: pinned route '${name}' must have no path params`);
|
|
839
|
+
const { hash, pathname, search } = parsePath(leaf.path);
|
|
840
|
+
const match = this.#matcher.match(pathname, search, hash);
|
|
841
|
+
if (match === void 0) throw new Error(`stacker: pinned route '${name}' (path '${leaf.path}') did not match`);
|
|
842
|
+
return {
|
|
843
|
+
key: `pin:${name}`,
|
|
844
|
+
match
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
#notFoundMatch() {
|
|
848
|
+
return {
|
|
849
|
+
chain: [{
|
|
850
|
+
node: this.#notFound.node,
|
|
851
|
+
params: {}
|
|
852
|
+
}],
|
|
853
|
+
leaf: this.#notFound.leaf,
|
|
854
|
+
name: this.#notFound.leaf.name,
|
|
855
|
+
params: {}
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
const makeNotFound = (component) => {
|
|
860
|
+
const leafNode = {
|
|
861
|
+
component,
|
|
862
|
+
kind: "route",
|
|
863
|
+
params: {},
|
|
864
|
+
path: "*",
|
|
865
|
+
query: {},
|
|
866
|
+
type: "page"
|
|
867
|
+
};
|
|
868
|
+
const node = {
|
|
869
|
+
id: " notFound",
|
|
870
|
+
key: " notFound",
|
|
871
|
+
kind: "route",
|
|
872
|
+
node: leafNode,
|
|
873
|
+
params: {},
|
|
874
|
+
path: "*"
|
|
875
|
+
};
|
|
876
|
+
return {
|
|
877
|
+
leaf: {
|
|
878
|
+
chain: [node],
|
|
879
|
+
leaf: leafNode,
|
|
880
|
+
name: " notFound",
|
|
881
|
+
params: {},
|
|
882
|
+
path: "*",
|
|
883
|
+
query: {}
|
|
884
|
+
},
|
|
885
|
+
node
|
|
886
|
+
};
|
|
887
|
+
};
|
|
888
|
+
//#endregion
|
|
889
|
+
//#region src/react/context.ts
|
|
890
|
+
const RouterContext = createContext(null);
|
|
891
|
+
const ActiveChainContext = createContext([]);
|
|
892
|
+
const CurrentNodeContext = createContext(null);
|
|
893
|
+
//#endregion
|
|
894
|
+
//#region src/react/router-view.tsx
|
|
895
|
+
/**
|
|
896
|
+
* renders the current view tree of the router.
|
|
897
|
+
*
|
|
898
|
+
* off-chain branches stay mounted with their state intact, hidden with `display: none` rather than unmounted,
|
|
899
|
+
* so a back-traversal returns to the instance you left. their effects keep running; a branch that wants to
|
|
900
|
+
* pause background work while stacked can gate it on `useIsFocused`.
|
|
901
|
+
*
|
|
902
|
+
* @param props.router router instance
|
|
903
|
+
* @returns rendered component tree
|
|
904
|
+
*/
|
|
905
|
+
const RouterView = ({ router }) => {
|
|
906
|
+
const view = useSyncExternalStore(router.subscribe, () => router.view);
|
|
907
|
+
useLayoutEffect(() => {
|
|
908
|
+
return router.attachView();
|
|
909
|
+
}, [router]);
|
|
910
|
+
useLayoutEffect(() => {
|
|
911
|
+
router.notifyCommit();
|
|
912
|
+
}, [router, view]);
|
|
913
|
+
return /* @__PURE__ */ jsx(RouterContext, {
|
|
914
|
+
value: router,
|
|
915
|
+
children: /* @__PURE__ */ jsx(ActiveChainContext, {
|
|
916
|
+
value: view.activePath,
|
|
917
|
+
children: /* @__PURE__ */ jsx(Pool, { nodes: view.roots })
|
|
918
|
+
})
|
|
919
|
+
});
|
|
920
|
+
};
|
|
921
|
+
const Pool = ({ nodes }) => {
|
|
922
|
+
const activePath = useContext(ActiveChainContext);
|
|
923
|
+
return /* @__PURE__ */ jsx(Fragment, { children: nodes.map((node) => /* @__PURE__ */ jsx(Branch, {
|
|
924
|
+
focused: activePath.includes(node.instanceKey),
|
|
925
|
+
node
|
|
926
|
+
}, node.instanceKey)) });
|
|
927
|
+
};
|
|
928
|
+
const Branch = ({ focused, node }) => {
|
|
929
|
+
const resolved = node.node;
|
|
930
|
+
const Component = resolved.node.component;
|
|
931
|
+
const router = useContext(RouterContext);
|
|
932
|
+
const fallback = resolved.node.fallback ?? router?.defaultFallback;
|
|
933
|
+
return /* @__PURE__ */ jsx("div", {
|
|
934
|
+
className: "stacker-branch",
|
|
935
|
+
"data-stacker-node": resolved.id,
|
|
936
|
+
style: { display: focused ? "contents" : "none" },
|
|
937
|
+
children: /* @__PURE__ */ jsx(CurrentNodeContext, {
|
|
938
|
+
value: {
|
|
939
|
+
focused,
|
|
940
|
+
node
|
|
941
|
+
},
|
|
942
|
+
children: /* @__PURE__ */ jsx(Suspense, {
|
|
943
|
+
fallback: fallback ?? null,
|
|
944
|
+
children: /* @__PURE__ */ jsx(Component, {})
|
|
945
|
+
})
|
|
946
|
+
})
|
|
947
|
+
});
|
|
948
|
+
};
|
|
949
|
+
//#endregion
|
|
950
|
+
//#region src/react/outlet.tsx
|
|
951
|
+
/**
|
|
952
|
+
* renders the child branch pool within a layout component.
|
|
953
|
+
*
|
|
954
|
+
* @returns rendered outlet child pool or null if outside a layout
|
|
955
|
+
*/
|
|
956
|
+
const Outlet = () => {
|
|
957
|
+
const current = useContext(CurrentNodeContext);
|
|
958
|
+
if (current === null) return null;
|
|
959
|
+
return /* @__PURE__ */ jsx(Pool, { nodes: current.node.children });
|
|
960
|
+
};
|
|
961
|
+
//#endregion
|
|
962
|
+
//#region src/react/hooks.ts
|
|
963
|
+
/**
|
|
964
|
+
* gets the active router instance.
|
|
965
|
+
*
|
|
966
|
+
* @returns router instance
|
|
967
|
+
* @throws when used outside a router view context
|
|
968
|
+
*/
|
|
969
|
+
const useRouter = () => {
|
|
970
|
+
const router = useContext(RouterContext);
|
|
971
|
+
if (router === null) throw new Error("stacker: useRouter must be used within a <RouterView>");
|
|
972
|
+
return router;
|
|
973
|
+
};
|
|
974
|
+
/**
|
|
975
|
+
* gets the active history location.
|
|
976
|
+
*
|
|
977
|
+
* @returns history location
|
|
978
|
+
*/
|
|
979
|
+
const useLocation = () => {
|
|
980
|
+
const router = useRouter();
|
|
981
|
+
return useSyncExternalStore(router.subscribe, () => router.location);
|
|
982
|
+
};
|
|
983
|
+
/**
|
|
984
|
+
* gets the active route match information.
|
|
985
|
+
*
|
|
986
|
+
* @returns active route match
|
|
987
|
+
*/
|
|
988
|
+
const useRoute = () => {
|
|
989
|
+
const router = useRouter();
|
|
990
|
+
return useSyncExternalStore(router.subscribe, () => router.route);
|
|
991
|
+
};
|
|
992
|
+
/**
|
|
993
|
+
* gets the untyped parameter map of the nearest enclosing route node.
|
|
994
|
+
*
|
|
995
|
+
* @returns decoded parameters
|
|
996
|
+
* @throws when used outside a route tree context
|
|
997
|
+
*/
|
|
998
|
+
const useParams = () => {
|
|
999
|
+
const current = useContext(CurrentNodeContext);
|
|
1000
|
+
if (current === null) throw new Error("stacker: useParams must be used within a route component");
|
|
1001
|
+
return current.node.params;
|
|
1002
|
+
};
|
|
1003
|
+
/**
|
|
1004
|
+
* gets whether the enclosing branch is focused (on screen).
|
|
1005
|
+
*
|
|
1006
|
+
* @returns true if focused
|
|
1007
|
+
*/
|
|
1008
|
+
const useIsFocused = () => {
|
|
1009
|
+
return useContext(CurrentNodeContext)?.focused ?? false;
|
|
1010
|
+
};
|
|
1011
|
+
/**
|
|
1012
|
+
* runs an effect callback only while the branch is focused.
|
|
1013
|
+
*
|
|
1014
|
+
* the effect re-runs whenever its identity changes, the way `useEffect` does, so wrap it in `useCallback` to
|
|
1015
|
+
* control when that happens. an effect built fresh on every render re-runs on every render.
|
|
1016
|
+
*
|
|
1017
|
+
* @param effect effect callback
|
|
1018
|
+
*/
|
|
1019
|
+
const useFocusEffect = (effect) => {
|
|
1020
|
+
const focused = useIsFocused();
|
|
1021
|
+
useEffect(() => {
|
|
1022
|
+
if (!focused) return;
|
|
1023
|
+
return effect();
|
|
1024
|
+
}, [effect, focused]);
|
|
1025
|
+
};
|
|
1026
|
+
/**
|
|
1027
|
+
* generates typed hooks bound to a specific route registry.
|
|
1028
|
+
*
|
|
1029
|
+
* @param routes the compiled registry the hooks are typed against
|
|
1030
|
+
* @returns typed hooks record
|
|
1031
|
+
* @throws when used with a router built from a different registry
|
|
1032
|
+
*/
|
|
1033
|
+
const createRouterHooks = (routes) => {
|
|
1034
|
+
const useTypedRouter = () => {
|
|
1035
|
+
const router = useContext(RouterContext);
|
|
1036
|
+
if (router === null) throw new Error("stacker: hooks must be used within a <RouterView>");
|
|
1037
|
+
if (router.routes !== routes) throw new Error("stacker: these hooks were created for a different route registry");
|
|
1038
|
+
return router;
|
|
1039
|
+
};
|
|
1040
|
+
return {
|
|
1041
|
+
useBuild() {
|
|
1042
|
+
const router = useTypedRouter();
|
|
1043
|
+
return useMemo(() => {
|
|
1044
|
+
return (name, ...args) => router.build(name, ...args);
|
|
1045
|
+
}, [router]);
|
|
1046
|
+
},
|
|
1047
|
+
useLocation,
|
|
1048
|
+
useNavigate() {
|
|
1049
|
+
const router = useTypedRouter();
|
|
1050
|
+
return useMemo(() => {
|
|
1051
|
+
return (name, ...args) => router.navigate(name, ...args);
|
|
1052
|
+
}, [router]);
|
|
1053
|
+
},
|
|
1054
|
+
useParams(name) {
|
|
1055
|
+
const router = useTypedRouter();
|
|
1056
|
+
const current = useContext(CurrentNodeContext);
|
|
1057
|
+
const setParams = useMemo(() => {
|
|
1058
|
+
return (patch) => router.setParams(patch);
|
|
1059
|
+
}, [router]);
|
|
1060
|
+
if (current === null) throw new Error("stacker: useParams must be used within a route component");
|
|
1061
|
+
if (current.node.node.kind !== "route" || current.node.node.key !== name) throw new Error(`stacker: useParams('${name}') called under ${current.node.node.kind} '${current.node.node.key}'`);
|
|
1062
|
+
return [current.node.params, setParams];
|
|
1063
|
+
},
|
|
1064
|
+
useRoute,
|
|
1065
|
+
useRouter: useTypedRouter
|
|
1066
|
+
};
|
|
1067
|
+
};
|
|
1068
|
+
//#endregion
|
|
1069
|
+
//#region src/react/link.tsx
|
|
1070
|
+
const isModifiedClick = (event) => event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
|
|
1071
|
+
const isRoutable = (to) => {
|
|
1072
|
+
try {
|
|
1073
|
+
return new URL(to, window.location.href).origin === window.location.origin;
|
|
1074
|
+
} catch {
|
|
1075
|
+
return false;
|
|
1076
|
+
}
|
|
1077
|
+
};
|
|
1078
|
+
/**
|
|
1079
|
+
* anchor element that intercepts clicks for in-app navigation.
|
|
1080
|
+
*
|
|
1081
|
+
* a destination on another origin, or under a scheme like `mailto:`, is left to the browser.
|
|
1082
|
+
*
|
|
1083
|
+
* @param props link properties
|
|
1084
|
+
* @returns rendered anchor element
|
|
1085
|
+
*/
|
|
1086
|
+
const Link = ({ children, onClick, replace, to, ...rest }) => {
|
|
1087
|
+
const router = useRouter();
|
|
1088
|
+
return /* @__PURE__ */ jsx("a", {
|
|
1089
|
+
href: to,
|
|
1090
|
+
onClick: (event) => {
|
|
1091
|
+
onClick?.(event);
|
|
1092
|
+
if (event.defaultPrevented || isModifiedClick(event) || rest.download !== void 0 || rest.target !== void 0 && rest.target !== "" && rest.target !== "_self" || !isRoutable(to)) return;
|
|
1093
|
+
event.preventDefault();
|
|
1094
|
+
if (replace) router.replace(to);
|
|
1095
|
+
else router.push(to);
|
|
1096
|
+
},
|
|
1097
|
+
...rest,
|
|
1098
|
+
children
|
|
1099
|
+
});
|
|
1100
|
+
};
|
|
1101
|
+
//#endregion
|
|
1102
|
+
export { Link, NavigationHistory, Outlet, Router, RouterView, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
|