@oomfware/stacker 0.1.3 → 0.2.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/README.md +80 -17
- package/dist/index.d.mts +51 -32
- package/dist/index.mjs +73 -67
- package/dist/testing.mjs +1 -1
- package/dist/{url-gf-m_-s3.mjs → url-DerpiRjh.mjs} +14 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -153,25 +153,58 @@ use `<Link>` to route in-app:
|
|
|
153
153
|
|
|
154
154
|
plain `<a>` elements also route in-app automatically under `NavigationHistory`.
|
|
155
155
|
|
|
156
|
-
drive the router imperatively
|
|
156
|
+
drive the router imperatively with a _route target_: a route name and its parameters in one object,
|
|
157
|
+
type-checked against the registry.
|
|
157
158
|
|
|
158
159
|
```ts
|
|
159
|
-
|
|
160
|
-
router.
|
|
161
|
-
router.replace('/profile/alice');
|
|
160
|
+
router.navigate({ to: { name: 'Profile', actor: 'alice' } });
|
|
161
|
+
router.navigate({ to: { name: 'Profile', actor: 'alice' }, replace: true });
|
|
162
162
|
|
|
163
|
-
//
|
|
164
|
-
router.navigate(
|
|
165
|
-
router.build('Profile', { actor: 'alice' }); // -> "/profile/alice"
|
|
163
|
+
// a URL works too, for destinations the registry cannot spell
|
|
164
|
+
router.navigate({ to: '/profile/alice' });
|
|
166
165
|
|
|
167
|
-
//
|
|
168
|
-
router.
|
|
169
|
-
router.
|
|
166
|
+
// without navigating
|
|
167
|
+
router.href({ name: 'Profile', actor: 'alice' }); // -> "/profile/alice"
|
|
168
|
+
router.match('/profile/alice'); // -> { name: 'Profile', actor: 'alice' }
|
|
169
|
+
|
|
170
|
+
// returns to the nearest entry for the route, pushing if there is none
|
|
171
|
+
router.popTo({ name: 'Messages' });
|
|
170
172
|
router.back();
|
|
171
173
|
```
|
|
172
174
|
|
|
173
|
-
`
|
|
174
|
-
|
|
175
|
+
`navigate` passes `info`, `scroll` and `state` to the history entry. `scroll` defaults to `'auto'` —
|
|
176
|
+
top on a push, saved offset on a traversal; `'preserve'` holds the viewport and focus still.
|
|
177
|
+
|
|
178
|
+
`router.replace` patches the active route's query params in place, reusing the history entry so the
|
|
179
|
+
scroll offset and the focused element survive:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
router.replace('Profile', { tab: 'media' }); // -> /profile/alice?tab=media
|
|
183
|
+
router.replace('Profile', { tab: undefined }); // -> /profile/alice
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
unmentioned params keep their values, undeclared keys are ignored, and naming a route other than the
|
|
187
|
+
one on screen throws.
|
|
188
|
+
|
|
189
|
+
a route target is a discriminated union, so narrowing on `name` narrows the params with it:
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
import type { RouteTarget } from '@oomfware/stacker';
|
|
193
|
+
|
|
194
|
+
const label = (target: RouteTarget<typeof routes>): string => {
|
|
195
|
+
switch (target.name) {
|
|
196
|
+
case 'Profile': {
|
|
197
|
+
return `@${target.actor}`;
|
|
198
|
+
}
|
|
199
|
+
default: {
|
|
200
|
+
return 'stacker';
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
because a target spells its params alongside `name`, a route cannot declare a param called `name`;
|
|
207
|
+
`defineRoutes` rejects it.
|
|
175
208
|
|
|
176
209
|
### hooks
|
|
177
210
|
|
|
@@ -180,22 +213,52 @@ generate type-safe hooks bound to your route configuration using `createRouterHo
|
|
|
180
213
|
```tsx
|
|
181
214
|
import { createRouterHooks } from '@oomfware/stacker';
|
|
182
215
|
|
|
183
|
-
const {
|
|
216
|
+
const { useParams, useRouter } = createRouterHooks(routes);
|
|
184
217
|
|
|
185
218
|
const Profile = () => {
|
|
186
|
-
const [{ actor },
|
|
187
|
-
const
|
|
219
|
+
const [{ actor }, replace] = useParams('Profile');
|
|
220
|
+
const router = useRouter();
|
|
188
221
|
|
|
189
222
|
return (
|
|
190
223
|
<>
|
|
191
224
|
<h1>@{actor}</h1>
|
|
192
|
-
<button onClick={() =>
|
|
193
|
-
<button onClick={() => navigate('Settings')}>settings</button>
|
|
225
|
+
<button onClick={() => replace({ tab: 'media' })}>media</button>
|
|
226
|
+
<button onClick={() => router.navigate({ to: { name: 'Settings' } })}>settings</button>
|
|
194
227
|
</>
|
|
195
228
|
);
|
|
196
229
|
};
|
|
197
230
|
```
|
|
198
231
|
|
|
232
|
+
`useParams` hands back `replace` already bound to the route it names, so it takes the patch alone.
|
|
233
|
+
|
|
234
|
+
`useRouter` types the router against your registry, so `navigate`, `href` and the rest only accept
|
|
235
|
+
targets your routes describe. call them on the router itself; they read state private to it, so they
|
|
236
|
+
do not survive being pulled off the instance.
|
|
237
|
+
|
|
238
|
+
the same factory provides `useTarget` for reading the active route as a target, which re-renders on
|
|
239
|
+
navigation:
|
|
240
|
+
|
|
241
|
+
```tsx
|
|
242
|
+
const { useRouter, useTarget } = createRouterHooks(routes);
|
|
243
|
+
|
|
244
|
+
const Nav = () => {
|
|
245
|
+
const router = useRouter();
|
|
246
|
+
const target = useTarget();
|
|
247
|
+
|
|
248
|
+
return (
|
|
249
|
+
<a
|
|
250
|
+
aria-current={target.name === 'Settings' ? 'page' : undefined}
|
|
251
|
+
href={router.href({ name: 'Settings' })}
|
|
252
|
+
>
|
|
253
|
+
settings
|
|
254
|
+
</a>
|
|
255
|
+
);
|
|
256
|
+
};
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
reach for `useParams` over `useTarget` inside a screen: warm screens stay mounted behind the active
|
|
260
|
+
one, and only `useParams` reports the branch's own route rather than whichever one is active.
|
|
261
|
+
|
|
199
262
|
the package also exports registry-free hooks (`useLocation`, `useRoute`, `useRouter`) for components
|
|
200
263
|
that do not need type-safe route definitions.
|
|
201
264
|
|
package/dist/index.d.mts
CHANGED
|
@@ -252,8 +252,26 @@ type PathShape<P extends CodecRecord> = { -readonly [K in keyof P]: Infer<P[K]>;
|
|
|
252
252
|
type LeafDecode<L> = L extends RouteLeaf<infer P, infer Q> ? Prettify<DecodeShape<Q> & PathShape<P>> : never;
|
|
253
253
|
type LeafBuild<L> = L extends RouteLeaf<infer P, infer Q> ? Prettify<BuildShape<Q> & PathShape<P>> : never;
|
|
254
254
|
type LeafQueryPatch<L> = L extends RouteLeaf<infer _P, infer Q> ? Prettify<{ readonly [P in keyof Q]?: Infer<Q[P]> | undefined; }> : never;
|
|
255
|
+
type LeafTarget<K, L> = Prettify<{
|
|
256
|
+
readonly name: K;
|
|
257
|
+
} & LeafBuild<L>>;
|
|
258
|
+
type LeafMatched<K, L> = Prettify<{
|
|
259
|
+
readonly name: K;
|
|
260
|
+
} & LeafDecode<L>>;
|
|
255
261
|
/** a union of all navigable route names. */
|
|
256
262
|
type RouteName<R> = keyof LeavesMap<R> & string;
|
|
263
|
+
/**
|
|
264
|
+
* a route name plus the parameters needed to reach it. `href`, `navigate`, and `popTo` all take one.
|
|
265
|
+
*
|
|
266
|
+
* narrow the union on `name` to get at a specific route's parameters.
|
|
267
|
+
*/
|
|
268
|
+
type RouteTarget<R> = { [K in RouteName<R>]: LeafTarget<K, LeavesMap<R>[K]>; }[RouteName<R>];
|
|
269
|
+
/**
|
|
270
|
+
* what matching a URL gives back: a route name plus its decoded parameters.
|
|
271
|
+
*
|
|
272
|
+
* unlike {@link RouteTarget}, query params with a default are always present.
|
|
273
|
+
*/
|
|
274
|
+
type MatchedTarget<R> = { [K in RouteName<R>]: LeafMatched<K, LeavesMap<R>[K]>; }[RouteName<R>];
|
|
257
275
|
/** the decoded parameter shape for a route name. */
|
|
258
276
|
type ParamsOf<R, K extends RouteName<R>> = LeafDecode<LeavesMap<R>[K]>;
|
|
259
277
|
/** the parameter shape required to build a URL or navigate to a route. */
|
|
@@ -346,10 +364,14 @@ interface View {
|
|
|
346
364
|
readonly roots: readonly InstanceNode[];
|
|
347
365
|
}
|
|
348
366
|
//#endregion
|
|
349
|
-
//#region src/build.d.ts
|
|
350
|
-
type BuildArgs<R, K extends RouteName<R>> = Record<never, never> extends BuildParamsOf<R, K> ? [params?: BuildParamsOf<R, K>] : [params: BuildParamsOf<R, K>];
|
|
351
|
-
//#endregion
|
|
352
367
|
//#region src/router.d.ts
|
|
368
|
+
/** options for a navigation. */
|
|
369
|
+
interface NavigateOptions<R extends RouteRegistry<unknown>> extends HistoryNavigateOptions {
|
|
370
|
+
/** replace the active history entry instead. */
|
|
371
|
+
readonly replace?: boolean;
|
|
372
|
+
/** where to go */
|
|
373
|
+
readonly to: RouteTarget<R> | string;
|
|
374
|
+
}
|
|
353
375
|
/** options for the router constructor. */
|
|
354
376
|
interface RouterOptions<R extends RouteRegistry<unknown>> {
|
|
355
377
|
/** default fallback component shown during lazy chunk loading. */
|
|
@@ -380,8 +402,10 @@ declare class Router<R extends RouteRegistry<unknown>> {
|
|
|
380
402
|
get view(): View;
|
|
381
403
|
/** active history location. */
|
|
382
404
|
get location(): HistoryLocation;
|
|
383
|
-
/** active route match details. */
|
|
405
|
+
/** active route match details, including the matched chain that `resolveMeta` takes. */
|
|
384
406
|
get route(): RouteMatch;
|
|
407
|
+
/** the active route's name and parameters. */
|
|
408
|
+
get target(): MatchedTarget<R>;
|
|
385
409
|
/** whether backward history is available. */
|
|
386
410
|
get canGoBack(): boolean;
|
|
387
411
|
/** whether forward history is available. */
|
|
@@ -400,47 +424,45 @@ declare class Router<R extends RouteRegistry<unknown>> {
|
|
|
400
424
|
* @returns unsubscribe function
|
|
401
425
|
*/
|
|
402
426
|
readonly subscribe: (listener: () => void) => (() => void);
|
|
403
|
-
/** pushes a new location onto the history stack. */
|
|
404
|
-
push(to: string): void;
|
|
405
|
-
/** replaces the current location on the history stack. */
|
|
406
|
-
replace(to: string): void;
|
|
407
427
|
/**
|
|
408
|
-
*
|
|
428
|
+
* builds the URL for a route.
|
|
409
429
|
*
|
|
410
|
-
* @param
|
|
411
|
-
* @param args route parameters
|
|
430
|
+
* @param target route name and parameters
|
|
412
431
|
* @returns relative URL
|
|
413
432
|
*/
|
|
414
|
-
|
|
433
|
+
href(target: RouteTarget<R>): string;
|
|
415
434
|
/**
|
|
416
435
|
* matches a URL against the route registry, without navigating to it.
|
|
417
436
|
*
|
|
418
|
-
* the URL is resolved against the active location, the same way {@link
|
|
437
|
+
* the URL is resolved against the active location, the same way {@link navigate} resolves it.
|
|
419
438
|
*
|
|
420
439
|
* @param to destination relative URL
|
|
421
|
-
* @returns the
|
|
440
|
+
* @returns the target it resolves to, or undefined when no route matches
|
|
422
441
|
*/
|
|
423
|
-
match(to: string):
|
|
442
|
+
match(to: string): MatchedTarget<R> | undefined;
|
|
424
443
|
/**
|
|
425
444
|
* navigates to a route.
|
|
426
445
|
*
|
|
427
|
-
* @param
|
|
428
|
-
* @param args route parameters
|
|
446
|
+
* @param options where to go, and how to get there
|
|
429
447
|
*/
|
|
430
|
-
navigate
|
|
448
|
+
navigate(options: NavigateOptions<R>): void;
|
|
431
449
|
/**
|
|
432
450
|
* returns to the nearest existing history entry for a route, or pushes if none exists.
|
|
433
451
|
*
|
|
434
|
-
* @param
|
|
435
|
-
* @param args route parameters
|
|
452
|
+
* @param to route target, or a relative URL resolved against the active location
|
|
436
453
|
*/
|
|
437
|
-
popTo
|
|
454
|
+
popTo(to: RouteTarget<R> | string): void;
|
|
438
455
|
/**
|
|
439
|
-
*
|
|
456
|
+
* patches the active route's query params in place, without pushing a new entry.
|
|
440
457
|
*
|
|
458
|
+
* params the patch does not mention keep their values; setting one to `undefined` drops it from the URL.
|
|
459
|
+
* keys the route does not declare are ignored.
|
|
460
|
+
*
|
|
461
|
+
* @param name the active route's name, which types the patch
|
|
441
462
|
* @param patch query parameter changes
|
|
463
|
+
* @throws when `name` is not the active route
|
|
442
464
|
*/
|
|
443
|
-
|
|
465
|
+
replace<K extends RouteName<R>>(name: K, patch: QueryPatchOf<R, K>): void;
|
|
444
466
|
/** navigates back one entry. */
|
|
445
467
|
back(): void;
|
|
446
468
|
/** navigates forward one entry. */
|
|
@@ -533,22 +555,19 @@ declare const useIsFocused: () => boolean;
|
|
|
533
555
|
declare const useFocusEffect: (effect: EffectCallback) => void;
|
|
534
556
|
/** typed hooks bound to a specific route registry. */
|
|
535
557
|
interface RouterHooks<R extends RouteRegistry<unknown>> {
|
|
536
|
-
/** returns a function to build URLs. */
|
|
537
|
-
useBuild(): Router<R>['build'];
|
|
538
|
-
/** gets the current location. */
|
|
539
|
-
useLocation(): HistoryLocation;
|
|
540
|
-
/** returns a function to navigate to routes. */
|
|
541
|
-
useNavigate(): Router<R>['navigate'];
|
|
542
558
|
/** gets a route's parameters and a setter that patches its query in place. */
|
|
543
559
|
useParams<K extends RouteName<R>>(name: K): readonly [ParamsOf<R, K>, (patch: QueryPatchOf<R, K>) => void];
|
|
544
|
-
/** gets the active route match. */
|
|
545
|
-
useRoute(): RouteMatch;
|
|
546
560
|
/** gets the typed router instance. */
|
|
547
561
|
useRouter(): Router<R>;
|
|
562
|
+
/** gets the active route's name and parameters. */
|
|
563
|
+
useTarget(): MatchedTarget<R>;
|
|
548
564
|
}
|
|
549
565
|
/**
|
|
550
566
|
* generates typed hooks bound to a specific route registry.
|
|
551
567
|
*
|
|
568
|
+
* one-off reads of the router, like building a URL or navigating, go through {@link RouterHooks.useRouter}
|
|
569
|
+
* instead; only state a component has to re-render on gets a hook of its own.
|
|
570
|
+
*
|
|
552
571
|
* @param routes the compiled registry the hooks are typed against
|
|
553
572
|
* @returns typed hooks record
|
|
554
573
|
* @throws when used with a router built from a different registry
|
|
@@ -573,4 +592,4 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'
|
|
|
573
592
|
*/
|
|
574
593
|
declare const Link: ({ children, onClick, replace, to, ...rest }: LinkProps) => ReactElement;
|
|
575
594
|
//#endregion
|
|
576
|
-
export { type BuildParamsOf, type Codec, type DefaultedCodec, type History, type HistoryAction, type HistoryEntry, type HistoryListener, type HistoryLocation, type HistoryNavigateOptions, type HistoryScrollBehavior, type HistoryUpdate, type Infer, type InstanceNode, type LayoutConfig, type LayoutNode, type LeafType, Link, type LinkProps, type MatchedNode, NavigationHistory, type NavigationHistoryOptions, type OptionalCodec, Outlet, type ParamsOf, type QueryPatchOf, type ReadonlyURLSearchParams, type ResolvedLeaf, type ResolvedNode, type RouteChildren, type RouteConfig, type RouteLeaf, type RouteMatch, type RouteMeta, type RouteName, type RouteNode, type RouteRegistry, Router, type RouterHooks, type RouterOptions, RouterView, type View, type WhenContext, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
|
|
595
|
+
export { type BuildParamsOf, type Codec, type DefaultedCodec, type History, type HistoryAction, type HistoryEntry, type HistoryListener, type HistoryLocation, type HistoryNavigateOptions, type HistoryScrollBehavior, type HistoryUpdate, type Infer, type InstanceNode, type LayoutConfig, type LayoutNode, type LeafType, Link, type LinkProps, type MatchedNode, type MatchedTarget, type NavigateOptions, NavigationHistory, type NavigationHistoryOptions, type OptionalCodec, Outlet, type ParamsOf, type QueryPatchOf, type ReadonlyURLSearchParams, type ResolvedLeaf, type ResolvedNode, type RouteChildren, type RouteConfig, type RouteLeaf, type RouteMatch, type RouteMeta, type RouteName, type RouteNode, type RouteRegistry, type RouteTarget, Router, type RouterHooks, type RouterOptions, RouterView, type View, type WhenContext, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as parsePath, i as encodeSegment, n as decodeRemainder, o as resolvePath, r as encodeRemainder, t as createPath } from "./url-DerpiRjh.mjs";
|
|
2
2
|
import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
|
|
3
3
|
import { Suspense, createContext, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
|
|
4
4
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
@@ -204,6 +204,7 @@ const defineRoutes = (tree) => {
|
|
|
204
204
|
if (!sameKeySet(ownPathParams, declaredParams)) throw new Error(`stacker: route '${key}' path params [${ownPathParams.join(", ")}] do not match declared params [${declaredParams.join(", ")}]`);
|
|
205
205
|
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()`);
|
|
206
206
|
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`);
|
|
207
|
+
if ("name" in params || "name" in query) throw new Error(`stacker: route '${key}' must not declare a param named 'name'`);
|
|
207
208
|
for (const ancestor of chain) {
|
|
208
209
|
if (ancestor.kind !== "layout") continue;
|
|
209
210
|
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}'`);
|
|
@@ -526,8 +527,9 @@ var Builder = class {
|
|
|
526
527
|
constructor(registry) {
|
|
527
528
|
this.#registry = registry;
|
|
528
529
|
}
|
|
529
|
-
build(
|
|
530
|
-
|
|
530
|
+
build(target) {
|
|
531
|
+
const { name, ...params } = target;
|
|
532
|
+
return this.buildPath(name, params);
|
|
531
533
|
}
|
|
532
534
|
buildPath(name, params = {}) {
|
|
533
535
|
const leaf = this.#registry.leaves.get(name);
|
|
@@ -545,7 +547,7 @@ var Builder = class {
|
|
|
545
547
|
let pathname = head.replaceAll(SEGMENT, (_full, paramName) => {
|
|
546
548
|
const encoded = encodeParam(paramName);
|
|
547
549
|
rejectDotSegments([encoded], paramName);
|
|
548
|
-
return
|
|
550
|
+
return encodeSegment(encoded);
|
|
549
551
|
});
|
|
550
552
|
if (splat !== void 0) {
|
|
551
553
|
const remainder = encodeParam(splat);
|
|
@@ -736,10 +738,14 @@ var Router = class {
|
|
|
736
738
|
get location() {
|
|
737
739
|
return this.#history.location;
|
|
738
740
|
}
|
|
739
|
-
/** active route match details. */
|
|
741
|
+
/** active route match details, including the matched chain that `resolveMeta` takes. */
|
|
740
742
|
get route() {
|
|
741
743
|
return this.#active().match;
|
|
742
744
|
}
|
|
745
|
+
/** the active route's name and parameters. */
|
|
746
|
+
get target() {
|
|
747
|
+
return this.#active().target;
|
|
748
|
+
}
|
|
743
749
|
/** whether backward history is available. */
|
|
744
750
|
get canGoBack() {
|
|
745
751
|
return this.#history.canGoBack;
|
|
@@ -768,87 +774,86 @@ var Router = class {
|
|
|
768
774
|
subscribe = (listener) => {
|
|
769
775
|
return this.#updates.subscribe(listener);
|
|
770
776
|
};
|
|
771
|
-
/** pushes a new location onto the history stack. */
|
|
772
|
-
push(to) {
|
|
773
|
-
this.#history.push(to);
|
|
774
|
-
}
|
|
775
|
-
/** replaces the current location on the history stack. */
|
|
776
|
-
replace(to) {
|
|
777
|
-
this.#history.replace(to);
|
|
778
|
-
}
|
|
779
777
|
/**
|
|
780
|
-
*
|
|
778
|
+
* builds the URL for a route.
|
|
781
779
|
*
|
|
782
|
-
* @param
|
|
783
|
-
* @param args route parameters
|
|
780
|
+
* @param target route name and parameters
|
|
784
781
|
* @returns relative URL
|
|
785
782
|
*/
|
|
786
|
-
|
|
787
|
-
return this.#builder.build(
|
|
783
|
+
href(target) {
|
|
784
|
+
return this.#builder.build(target);
|
|
788
785
|
}
|
|
789
786
|
/**
|
|
790
787
|
* matches a URL against the route registry, without navigating to it.
|
|
791
788
|
*
|
|
792
|
-
* the URL is resolved against the active location, the same way {@link
|
|
789
|
+
* the URL is resolved against the active location, the same way {@link navigate} resolves it.
|
|
793
790
|
*
|
|
794
791
|
* @param to destination relative URL
|
|
795
|
-
* @returns the
|
|
792
|
+
* @returns the target it resolves to, or undefined when no route matches
|
|
796
793
|
*/
|
|
797
794
|
match(to) {
|
|
798
795
|
const { hash, pathname, search } = resolvePath(to, this.#history.location);
|
|
799
|
-
|
|
796
|
+
const match = this.#matcher.match(pathname, search, hash);
|
|
797
|
+
return match === void 0 ? void 0 : toTarget(match);
|
|
800
798
|
}
|
|
801
799
|
/**
|
|
802
800
|
* navigates to a route.
|
|
803
801
|
*
|
|
804
|
-
* @param
|
|
805
|
-
* @param args route parameters
|
|
802
|
+
* @param options where to go, and how to get there
|
|
806
803
|
*/
|
|
807
|
-
navigate(
|
|
808
|
-
|
|
804
|
+
navigate(options) {
|
|
805
|
+
const { replace = false, to, ...rest } = options;
|
|
806
|
+
const url = typeof to === "string" ? to : this.#builder.build(to);
|
|
807
|
+
if (replace) this.#history.replace(url, rest);
|
|
808
|
+
else this.#history.push(url, rest);
|
|
809
809
|
}
|
|
810
810
|
/**
|
|
811
811
|
* returns to the nearest existing history entry for a route, or pushes if none exists.
|
|
812
812
|
*
|
|
813
|
-
* @param
|
|
814
|
-
* @param args route parameters
|
|
813
|
+
* @param to route target, or a relative URL resolved against the active location
|
|
815
814
|
*/
|
|
816
|
-
popTo(
|
|
817
|
-
const url = this.#builder.build(
|
|
818
|
-
const { hash, pathname, search } =
|
|
819
|
-
const
|
|
820
|
-
if (
|
|
821
|
-
const wanted = this.#canonical(
|
|
815
|
+
popTo(to) {
|
|
816
|
+
const url = typeof to === "string" ? to : this.#builder.build(to);
|
|
817
|
+
const { hash, pathname, search } = resolvePath(url, this.#history.location);
|
|
818
|
+
const wantedMatch = this.#matcher.match(pathname, search, hash);
|
|
819
|
+
if (wantedMatch !== void 0) {
|
|
820
|
+
const wanted = this.#canonical(wantedMatch);
|
|
822
821
|
const entries = this.#history.entries();
|
|
823
822
|
for (let i = this.#history.location.index; i >= 0; i--) {
|
|
824
823
|
const entry = entries[i];
|
|
825
824
|
if (entry === void 0 || !entry.sameDocument || entry.url === null) break;
|
|
826
825
|
const parts = parsePath(entry.url);
|
|
827
826
|
const match = this.#matcher.match(parts.pathname, parts.search, parts.hash);
|
|
828
|
-
if (match !== void 0 && match.name ===
|
|
827
|
+
if (match !== void 0 && match.name === wantedMatch.name && this.#canonical(match) === wanted) {
|
|
829
828
|
this.#history.traverseTo(entry.key);
|
|
830
829
|
return;
|
|
831
830
|
}
|
|
832
831
|
}
|
|
833
832
|
}
|
|
834
|
-
this.push(url);
|
|
833
|
+
this.#history.push(url);
|
|
835
834
|
}
|
|
836
835
|
/**
|
|
837
|
-
*
|
|
836
|
+
* patches the active route's query params in place, without pushing a new entry.
|
|
837
|
+
*
|
|
838
|
+
* params the patch does not mention keep their values; setting one to `undefined` drops it from the URL.
|
|
839
|
+
* keys the route does not declare are ignored.
|
|
838
840
|
*
|
|
841
|
+
* @param name the active route's name, which types the patch
|
|
839
842
|
* @param patch query parameter changes
|
|
843
|
+
* @throws when `name` is not the active route
|
|
840
844
|
*/
|
|
841
|
-
|
|
842
|
-
const active = this.#
|
|
843
|
-
|
|
844
|
-
|
|
845
|
+
replace(name, patch) {
|
|
846
|
+
const active = this.#active();
|
|
847
|
+
if (active.match.name !== name) throw new Error(`stacker: replace('${name}') called under route '${active.match.name}'`);
|
|
848
|
+
const leaf = this.#routes.leaves.get(name);
|
|
849
|
+
if (leaf === void 0) throw new Error(`stacker: unknown route '${name}'`);
|
|
845
850
|
const location = this.#history.location;
|
|
846
851
|
const search = new URLSearchParams(location.search);
|
|
847
|
-
for (const [
|
|
848
|
-
const codec = leaf.query[
|
|
852
|
+
for (const [param, value] of Object.entries(patch)) {
|
|
853
|
+
const codec = leaf.query[param];
|
|
849
854
|
if (codec === void 0) continue;
|
|
850
|
-
if (value === void 0) search.delete(
|
|
851
|
-
else search.set(
|
|
855
|
+
if (value === void 0) search.delete(param);
|
|
856
|
+
else search.set(param, codec.encode(value));
|
|
852
857
|
}
|
|
853
858
|
const query = search.toString();
|
|
854
859
|
const to = createPath({
|
|
@@ -934,11 +939,13 @@ var Router = class {
|
|
|
934
939
|
for (const key of this.#entries.keys()) if (!live.has(key)) this.#entries.delete(key);
|
|
935
940
|
}
|
|
936
941
|
#record(location, scrollPos) {
|
|
942
|
+
const match = this.#match(location);
|
|
937
943
|
const entry = {
|
|
938
944
|
index: location.index,
|
|
939
945
|
key: location.key,
|
|
940
|
-
match
|
|
941
|
-
scrollPos
|
|
946
|
+
match,
|
|
947
|
+
scrollPos,
|
|
948
|
+
target: toTarget(match)
|
|
942
949
|
};
|
|
943
950
|
this.#entries.set(location.key, entry);
|
|
944
951
|
this.#recency = [entry.key, ...this.#recency.filter((key) => key !== entry.key)];
|
|
@@ -986,6 +993,10 @@ var Router = class {
|
|
|
986
993
|
};
|
|
987
994
|
}
|
|
988
995
|
};
|
|
996
|
+
const toTarget = (match) => ({
|
|
997
|
+
...match.params,
|
|
998
|
+
name: match.name
|
|
999
|
+
});
|
|
989
1000
|
const makeNotFound = (component) => {
|
|
990
1001
|
const leafNode = {
|
|
991
1002
|
component,
|
|
@@ -1165,6 +1176,9 @@ const useFocusEffect = (effect) => {
|
|
|
1165
1176
|
/**
|
|
1166
1177
|
* generates typed hooks bound to a specific route registry.
|
|
1167
1178
|
*
|
|
1179
|
+
* one-off reads of the router, like building a URL or navigating, go through {@link RouterHooks.useRouter}
|
|
1180
|
+
* instead; only state a component has to re-render on gets a hook of its own.
|
|
1181
|
+
*
|
|
1168
1182
|
* @param routes the compiled registry the hooks are typed against
|
|
1169
1183
|
* @returns typed hooks record
|
|
1170
1184
|
* @throws when used with a router built from a different registry
|
|
@@ -1177,31 +1191,21 @@ const createRouterHooks = (routes) => {
|
|
|
1177
1191
|
return router;
|
|
1178
1192
|
};
|
|
1179
1193
|
return {
|
|
1180
|
-
useBuild() {
|
|
1181
|
-
const router = useTypedRouter();
|
|
1182
|
-
return useMemo(() => {
|
|
1183
|
-
return (name, ...args) => router.build(name, ...args);
|
|
1184
|
-
}, [router]);
|
|
1185
|
-
},
|
|
1186
|
-
useLocation,
|
|
1187
|
-
useNavigate() {
|
|
1188
|
-
const router = useTypedRouter();
|
|
1189
|
-
return useMemo(() => {
|
|
1190
|
-
return (name, ...args) => router.navigate(name, ...args);
|
|
1191
|
-
}, [router]);
|
|
1192
|
-
},
|
|
1193
1194
|
useParams(name) {
|
|
1194
1195
|
const router = useTypedRouter();
|
|
1195
1196
|
const current = useContext(CurrentNodeContext);
|
|
1196
|
-
const
|
|
1197
|
-
return (patch) => router.
|
|
1198
|
-
}, [router]);
|
|
1197
|
+
const replace = useMemo(() => {
|
|
1198
|
+
return (patch) => router.replace(name, patch);
|
|
1199
|
+
}, [name, router]);
|
|
1199
1200
|
if (current === null) throw new Error("stacker: useParams must be used within a route component");
|
|
1200
1201
|
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}'`);
|
|
1201
|
-
return [current.node.params,
|
|
1202
|
+
return [current.node.params, replace];
|
|
1202
1203
|
},
|
|
1203
|
-
|
|
1204
|
-
|
|
1204
|
+
useRouter: useTypedRouter,
|
|
1205
|
+
useTarget() {
|
|
1206
|
+
const router = useTypedRouter();
|
|
1207
|
+
return useSyncExternalStore(router.subscribe, () => router.target);
|
|
1208
|
+
}
|
|
1205
1209
|
};
|
|
1206
1210
|
};
|
|
1207
1211
|
//#endregion
|
|
@@ -1230,8 +1234,10 @@ const Link = ({ children, onClick, replace, to, ...rest }) => {
|
|
|
1230
1234
|
onClick?.(event);
|
|
1231
1235
|
if (event.defaultPrevented || isModifiedClick(event) || rest.download !== void 0 || rest.target !== void 0 && rest.target !== "" && rest.target !== "_self" || !isRoutable(to)) return;
|
|
1232
1236
|
event.preventDefault();
|
|
1233
|
-
|
|
1234
|
-
|
|
1237
|
+
router.navigate({
|
|
1238
|
+
replace,
|
|
1239
|
+
to
|
|
1240
|
+
});
|
|
1235
1241
|
},
|
|
1236
1242
|
...rest,
|
|
1237
1243
|
children
|
package/dist/testing.mjs
CHANGED
|
@@ -27,6 +27,16 @@ const resolvePath = (to, base) => {
|
|
|
27
27
|
search: resolved.search
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
|
+
const OUTSIDE_PCHAR = /[^\w!$&'()*+,\-.:;=@~]+/gu;
|
|
31
|
+
/**
|
|
32
|
+
* percent-encodes a value so that it stays inside one path segment.
|
|
33
|
+
*
|
|
34
|
+
* @param value the raw value
|
|
35
|
+
* @returns the encoded segment
|
|
36
|
+
*/
|
|
37
|
+
const encodeSegment = (value) => {
|
|
38
|
+
return value.replaceAll(OUTSIDE_PCHAR, (chunk) => encodeURIComponent(chunk));
|
|
39
|
+
};
|
|
30
40
|
/**
|
|
31
41
|
* decodes a splat remainder one segment at a time, so that separators survive decoding.
|
|
32
42
|
*
|
|
@@ -34,7 +44,9 @@ const resolvePath = (to, base) => {
|
|
|
34
44
|
*/
|
|
35
45
|
const decodeRemainder = (raw) => raw.split("/").map(decodeURIComponent).join("/");
|
|
36
46
|
/** encodes a splat remainder one segment at a time, the inverse of {@link decodeRemainder}. */
|
|
37
|
-
const encodeRemainder = (value) =>
|
|
47
|
+
const encodeRemainder = (value) => {
|
|
48
|
+
return value.split("/").map((segment) => encodeSegment(segment)).join("/");
|
|
49
|
+
};
|
|
38
50
|
const createPath = ({ hash, pathname, search }) => {
|
|
39
51
|
let out = pathname || "/";
|
|
40
52
|
if (search && search !== "?") out += search.startsWith("?") ? search : `?${search}`;
|
|
@@ -42,4 +54,4 @@ const createPath = ({ hash, pathname, search }) => {
|
|
|
42
54
|
return out;
|
|
43
55
|
};
|
|
44
56
|
//#endregion
|
|
45
|
-
export {
|
|
57
|
+
export { parsePath as a, encodeSegment as i, decodeRemainder as n, resolvePath as o, encodeRemainder as r, createPath as t };
|