@oomfware/stacker 0.1.3 → 0.2.1

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 CHANGED
@@ -153,25 +153,68 @@ 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 using either URLs or type-safe route names and parameters:
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
- // string-based navigation
160
- router.push('/profile/alice');
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
- // name-based navigation (type-checked)
164
- router.navigate('Profile', { actor: 'alice' });
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
- // history manipulation
168
- router.popTo('Messages');
169
- router.setParams({ tab: 'media' });
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
- `setParams` replaces the current history entry, preserving scroll and focus. undeclared query keys
174
- are ignored.
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.
208
+
209
+ wrap route components in stacker's `lazy` to allow the router to preload them ahead of time.
210
+
211
+ ```tsx
212
+ const Profile = lazy(() => import('./screens/profile.tsx'));
213
+
214
+ <Link onPointerEnter={() => void router.preload('Profile')} to="/profile/alice">
215
+ alice
216
+ </Link>;
217
+ ```
175
218
 
176
219
  ### hooks
177
220
 
@@ -180,22 +223,52 @@ generate type-safe hooks bound to your route configuration using `createRouterHo
180
223
  ```tsx
181
224
  import { createRouterHooks } from '@oomfware/stacker';
182
225
 
183
- const { useNavigate, useParams } = createRouterHooks(routes);
226
+ const { useParams, useRouter } = createRouterHooks(routes);
184
227
 
185
228
  const Profile = () => {
186
- const [{ actor }, setParams] = useParams('Profile');
187
- const navigate = useNavigate();
229
+ const [{ actor }, replace] = useParams('Profile');
230
+ const router = useRouter();
188
231
 
189
232
  return (
190
233
  <>
191
234
  <h1>@{actor}</h1>
192
- <button onClick={() => setParams({ tab: 'media' })}>media</button>
193
- <button onClick={() => navigate('Settings')}>settings</button>
235
+ <button onClick={() => replace({ tab: 'media' })}>media</button>
236
+ <button onClick={() => router.navigate({ to: { name: 'Settings' } })}>settings</button>
194
237
  </>
195
238
  );
196
239
  };
197
240
  ```
198
241
 
242
+ `useParams` hands back `replace` already bound to the route it names, so it takes the patch alone.
243
+
244
+ `useRouter` types the router against your registry, so `navigate`, `href` and the rest only accept
245
+ targets your routes describe. call them on the router itself; they read state private to it, so they
246
+ do not survive being pulled off the instance.
247
+
248
+ the same factory provides `useTarget` for reading the active route as a target, which re-renders on
249
+ navigation:
250
+
251
+ ```tsx
252
+ const { useRouter, useTarget } = createRouterHooks(routes);
253
+
254
+ const Nav = () => {
255
+ const router = useRouter();
256
+ const target = useTarget();
257
+
258
+ return (
259
+ <a
260
+ aria-current={target.name === 'Settings' ? 'page' : undefined}
261
+ href={router.href({ name: 'Settings' })}
262
+ >
263
+ settings
264
+ </a>
265
+ );
266
+ };
267
+ ```
268
+
269
+ reach for `useParams` over `useTarget` inside a screen: warm screens stay mounted behind the active
270
+ one, and only `useParams` reports the branch's own route rather than whichever one is active.
271
+
199
272
  the package also exports registry-free hooks (`useLocation`, `useRoute`, `useRouter`) for components
200
273
  that do not need type-safe route definitions.
201
274
 
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as HistoryLocation, c as HistoryUpdate, i as HistoryListener, n as HistoryAction, o as HistoryNavigateOptions, r as HistoryEntry, s as HistoryScrollBehavior, t as History } from "./types-KOb6CZ7N.mjs";
2
- import { AnchorHTMLAttributes, ComponentType, EffectCallback, ReactElement, ReactNode } from "react";
2
+ import { AnchorHTMLAttributes, ComponentType, EffectCallback, LazyExoticComponent, ReactElement, ReactNode } from "react";
3
3
  //#region src/codec.d.ts
4
4
  /**
5
5
  * a bidirectional codec for a single route parameter.
@@ -199,11 +199,11 @@ declare const route: <const Params extends CodecRecord = Empty, const Query exte
199
199
  declare const layout: <const Children extends RouteChildren, const Params extends CodecRecord = Empty>(config: LayoutConfig<Children, Params>) => LayoutNode<Children, Params>;
200
200
  /** a node resolved with an id and normalized parameters. */
201
201
  interface ResolvedNode {
202
+ readonly kind: 'layout' | 'route';
202
203
  /** unique dot-separated node path. */
203
204
  readonly id: string;
204
205
  /** key name within the parent record. */
205
206
  readonly key: string;
206
- readonly kind: 'layout' | 'route';
207
207
  readonly node: RouteNode;
208
208
  /** local parameter codecs. */
209
209
  readonly params: CodecRecord;
@@ -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. */
@@ -267,9 +285,9 @@ type QueryPatchOf<R, K extends RouteName<R>> = LeafQueryPatch<LeavesMap<R>[K]>;
267
285
  //#region src/match.d.ts
268
286
  /** a node on a matched chain paired with its instance parameters. */
269
287
  interface MatchedNode {
288
+ readonly node: ResolvedNode;
270
289
  /** parameters used for instance keying. */
271
290
  readonly params: Readonly<Record<string, unknown>>;
272
- readonly node: ResolvedNode;
273
291
  }
274
292
  /** the result of matching a URL, containing the chain, leaf, name, and parameters. */
275
293
  interface RouteMatch {
@@ -346,10 +364,34 @@ 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>];
367
+ //#region src/lazy.d.ts
368
+ /** a preloadable lazily-loaded component. */
369
+ type LazyComponent<T extends ComponentType<any>> = LazyExoticComponent<T> & {
370
+ /**
371
+ * start loading the component code.
372
+ *
373
+ * @returns promise that settles once loading finishes
374
+ */
375
+ preload(): Promise<void>;
376
+ };
377
+ /**
378
+ * defines a lazily-loaded component that can be preloaded.
379
+ *
380
+ * @param init component module loader
381
+ * @returns lazy component
382
+ */
383
+ declare const lazy: <T extends ComponentType<any>>(init: () => Promise<{
384
+ default: T;
385
+ }>) => LazyComponent<T>;
351
386
  //#endregion
352
387
  //#region src/router.d.ts
388
+ /** options for a navigation. */
389
+ interface NavigateOptions<R extends RouteRegistry<unknown>> extends HistoryNavigateOptions {
390
+ /** replace the active history entry instead. */
391
+ readonly replace?: boolean;
392
+ /** where to go */
393
+ readonly to: RouteTarget<R> | string;
394
+ }
353
395
  /** options for the router constructor. */
354
396
  interface RouterOptions<R extends RouteRegistry<unknown>> {
355
397
  /** default fallback component shown during lazy chunk loading. */
@@ -380,8 +422,10 @@ declare class Router<R extends RouteRegistry<unknown>> {
380
422
  get view(): View;
381
423
  /** active history location. */
382
424
  get location(): HistoryLocation;
383
- /** active route match details. */
425
+ /** active route match details, including the matched chain that `resolveMeta` takes. */
384
426
  get route(): RouteMatch;
427
+ /** the active route's name and parameters. */
428
+ get target(): MatchedTarget<R>;
385
429
  /** whether backward history is available. */
386
430
  get canGoBack(): boolean;
387
431
  /** whether forward history is available. */
@@ -400,47 +444,53 @@ declare class Router<R extends RouteRegistry<unknown>> {
400
444
  * @returns unsubscribe function
401
445
  */
402
446
  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
447
  /**
408
- * generates a URL for a route.
448
+ * builds the URL for a route.
409
449
  *
410
- * @param name route name
411
- * @param args route parameters
450
+ * @param target route name and parameters
412
451
  * @returns relative URL
413
452
  */
414
- build<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): string;
453
+ href(target: RouteTarget<R>): string;
415
454
  /**
416
455
  * matches a URL against the route registry, without navigating to it.
417
456
  *
418
- * the URL is resolved against the active location, the same way {@link push} resolves it.
457
+ * the URL is resolved against the active location, the same way {@link navigate} resolves it.
419
458
  *
420
459
  * @param to destination relative URL
421
- * @returns the match, or undefined when no route matches
460
+ * @returns the target it resolves to, or undefined when no route matches
422
461
  */
423
- match(to: string): RouteMatch | undefined;
462
+ match(to: string): MatchedTarget<R> | undefined;
424
463
  /**
425
464
  * navigates to a route.
426
465
  *
466
+ * @param options where to go, and how to get there
467
+ */
468
+ navigate(options: NavigateOptions<R>): void;
469
+ /**
470
+ * loads the code a route needs, without navigating to it.
471
+ *
427
472
  * @param name route name
428
- * @param args route parameters
473
+ * @returns promise that settles once loading finishes
474
+ * @throws when `name` is not in the registry
429
475
  */
430
- navigate<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): void;
476
+ preload(name: RouteName<R>): Promise<void>;
431
477
  /**
432
478
  * returns to the nearest existing history entry for a route, or pushes if none exists.
433
479
  *
434
- * @param name route name
435
- * @param args route parameters
480
+ * @param to route target, or a relative URL resolved against the active location
436
481
  */
437
- popTo<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): void;
482
+ popTo(to: RouteTarget<R> | string): void;
438
483
  /**
439
- * updates query parameters in-place without pushing a new entry.
484
+ * patches the active route's query params in place, without pushing a new entry.
485
+ *
486
+ * params the patch does not mention keep their values; setting one to `undefined` drops it from the URL.
487
+ * keys the route does not declare are ignored.
440
488
  *
489
+ * @param name the active route's name, which types the patch
441
490
  * @param patch query parameter changes
491
+ * @throws when `name` is not the active route
442
492
  */
443
- setParams(patch: Readonly<Record<string, unknown>>): void;
493
+ replace<K extends RouteName<R>>(name: K, patch: QueryPatchOf<R, K>): void;
444
494
  /** navigates back one entry. */
445
495
  back(): void;
446
496
  /** navigates forward one entry. */
@@ -533,22 +583,19 @@ declare const useIsFocused: () => boolean;
533
583
  declare const useFocusEffect: (effect: EffectCallback) => void;
534
584
  /** typed hooks bound to a specific route registry. */
535
585
  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
586
  /** gets a route's parameters and a setter that patches its query in place. */
543
587
  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
588
  /** gets the typed router instance. */
547
589
  useRouter(): Router<R>;
590
+ /** gets the active route's name and parameters. */
591
+ useTarget(): MatchedTarget<R>;
548
592
  }
549
593
  /**
550
594
  * generates typed hooks bound to a specific route registry.
551
595
  *
596
+ * one-off reads of the router, like building a URL or navigating, go through {@link RouterHooks.useRouter}
597
+ * instead; only state a component has to re-render on gets a hook of its own.
598
+ *
552
599
  * @param routes the compiled registry the hooks are typed against
553
600
  * @returns typed hooks record
554
601
  * @throws when used with a router built from a different registry
@@ -573,4 +620,4 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'
573
620
  */
574
621
  declare const Link: ({ children, onClick, replace, to, ...rest }: LinkProps) => ReactElement;
575
622
  //#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 };
623
+ 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 LazyComponent, 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, lazy, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { a as resolvePath, i as parsePath, n as decodeRemainder, r as encodeRemainder, t as createPath } from "./url-gf-m_-s3.mjs";
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
+ import { Suspense, createContext, lazy as lazy$1, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
2
3
  import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
3
- import { Suspense, createContext, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  //#region src/codec.ts
6
6
  const OPTIONAL = Symbol("stacker.optional");
@@ -81,9 +81,9 @@ const nonEmpty = () => ({
81
81
  * @returns the optional codec
82
82
  */
83
83
  const optional = (codec) => ({
84
+ [OPTIONAL]: true,
84
85
  decode: (raw) => codec.decode(raw),
85
- encode: (value) => codec.encode(value),
86
- [OPTIONAL]: true
86
+ encode: (value) => codec.encode(value)
87
87
  });
88
88
  /**
89
89
  * wraps a codec with a default value.
@@ -93,9 +93,9 @@ const optional = (codec) => ({
93
93
  * @returns the defaulted codec
94
94
  */
95
95
  const withDefault = (codec, fallback) => ({
96
+ [DEFAULT]: fallback,
96
97
  decode: (raw) => codec.decode(raw),
97
- encode: (value) => codec.encode(value),
98
- [DEFAULT]: fallback
98
+ encode: (value) => codec.encode(value)
99
99
  });
100
100
  const isOptional = (codec) => {
101
101
  return OPTIONAL in codec;
@@ -182,9 +182,9 @@ const defineRoutes = (tree) => {
182
182
  if (ids.has(id)) throw new Error(`stacker: duplicate node id '${id}'`);
183
183
  const params = node.params ?? {};
184
184
  const resolved = {
185
+ kind: node.kind,
185
186
  id,
186
187
  key,
187
- kind: node.kind,
188
188
  node,
189
189
  params,
190
190
  path: node.kind === "route" ? node.path : void 0
@@ -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}'`);
@@ -519,6 +520,45 @@ const toRelative = (url) => {
519
520
  return `${pathname}${search}${hash}`;
520
521
  };
521
522
  //#endregion
523
+ //#region src/lazy.ts
524
+ const noop = () => {};
525
+ /**
526
+ * defines a lazily-loaded component that can be preloaded.
527
+ *
528
+ * @param init component module loader
529
+ * @returns lazy component
530
+ */
531
+ const lazy = (init) => {
532
+ const component = lazy$1(init);
533
+ return Object.assign(component, { preload() {
534
+ try {
535
+ const internals = component;
536
+ internals._init(internals._payload);
537
+ } catch {}
538
+ return Promise.try(init).then(noop, noop);
539
+ } });
540
+ };
541
+ const isPreloadable = (component) => {
542
+ return typeof component.preload === "function";
543
+ };
544
+ /**
545
+ * loads every preloadable component in a list.
546
+ *
547
+ * @param components components to load
548
+ * @returns promise that settles once loading finishes
549
+ */
550
+ const preloadAll = (chain) => {
551
+ const pending = [];
552
+ for (const node of chain) {
553
+ const component = node.node.component;
554
+ if (!isPreloadable(component)) continue;
555
+ try {
556
+ pending.push(component.preload().then(noop, noop));
557
+ } catch {}
558
+ }
559
+ return Promise.all(pending).then(noop);
560
+ };
561
+ //#endregion
522
562
  //#region src/build.ts
523
563
  const SEGMENT = /:([A-Za-z_]\w*)/g;
524
564
  var Builder = class {
@@ -526,8 +566,9 @@ var Builder = class {
526
566
  constructor(registry) {
527
567
  this.#registry = registry;
528
568
  }
529
- build(name, ...args) {
530
- return this.buildPath(name, args[0] ?? {});
569
+ build(target) {
570
+ const { name, ...params } = target;
571
+ return this.buildPath(name, params);
531
572
  }
532
573
  buildPath(name, params = {}) {
533
574
  const leaf = this.#registry.leaves.get(name);
@@ -545,7 +586,7 @@ var Builder = class {
545
586
  let pathname = head.replaceAll(SEGMENT, (_full, paramName) => {
546
587
  const encoded = encodeParam(paramName);
547
588
  rejectDotSegments([encoded], paramName);
548
- return encodeURIComponent(encoded);
589
+ return encodeSegment(encoded);
549
590
  });
550
591
  if (splat !== void 0) {
551
592
  const remainder = encodeParam(splat);
@@ -736,10 +777,14 @@ var Router = class {
736
777
  get location() {
737
778
  return this.#history.location;
738
779
  }
739
- /** active route match details. */
780
+ /** active route match details, including the matched chain that `resolveMeta` takes. */
740
781
  get route() {
741
782
  return this.#active().match;
742
783
  }
784
+ /** the active route's name and parameters. */
785
+ get target() {
786
+ return this.#active().target;
787
+ }
743
788
  /** whether backward history is available. */
744
789
  get canGoBack() {
745
790
  return this.#history.canGoBack;
@@ -768,87 +813,98 @@ var Router = class {
768
813
  subscribe = (listener) => {
769
814
  return this.#updates.subscribe(listener);
770
815
  };
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
816
  /**
780
- * generates a URL for a route.
817
+ * builds the URL for a route.
781
818
  *
782
- * @param name route name
783
- * @param args route parameters
819
+ * @param target route name and parameters
784
820
  * @returns relative URL
785
821
  */
786
- build(name, ...args) {
787
- return this.#builder.build(name, ...args);
822
+ href(target) {
823
+ return this.#builder.build(target);
788
824
  }
789
825
  /**
790
826
  * matches a URL against the route registry, without navigating to it.
791
827
  *
792
- * the URL is resolved against the active location, the same way {@link push} resolves it.
828
+ * the URL is resolved against the active location, the same way {@link navigate} resolves it.
793
829
  *
794
830
  * @param to destination relative URL
795
- * @returns the match, or undefined when no route matches
831
+ * @returns the target it resolves to, or undefined when no route matches
796
832
  */
797
833
  match(to) {
798
834
  const { hash, pathname, search } = resolvePath(to, this.#history.location);
799
- return this.#matcher.match(pathname, search, hash);
835
+ const match = this.#matcher.match(pathname, search, hash);
836
+ return match === void 0 ? void 0 : toTarget(match);
800
837
  }
801
838
  /**
802
839
  * navigates to a route.
803
840
  *
841
+ * @param options where to go, and how to get there
842
+ */
843
+ navigate(options) {
844
+ const { replace = false, to, ...rest } = options;
845
+ const url = typeof to === "string" ? to : this.#builder.build(to);
846
+ if (replace) this.#history.replace(url, rest);
847
+ else this.#history.push(url, rest);
848
+ }
849
+ /**
850
+ * loads the code a route needs, without navigating to it.
851
+ *
804
852
  * @param name route name
805
- * @param args route parameters
853
+ * @returns promise that settles once loading finishes
854
+ * @throws when `name` is not in the registry
806
855
  */
807
- navigate(name, ...args) {
808
- this.push(this.#builder.build(name, ...args));
856
+ preload(name) {
857
+ const leaf = this.#routes.leaves.get(name);
858
+ if (leaf === void 0) throw new Error(`stacker: unknown route '${name}'`);
859
+ return preloadAll(leaf.chain);
809
860
  }
810
861
  /**
811
862
  * returns to the nearest existing history entry for a route, or pushes if none exists.
812
863
  *
813
- * @param name route name
814
- * @param args route parameters
864
+ * @param to route target, or a relative URL resolved against the active location
815
865
  */
816
- popTo(name, ...args) {
817
- const url = this.#builder.build(name, ...args);
818
- const { hash, pathname, search } = parsePath(url);
819
- const target = this.#matcher.match(pathname, search, hash);
820
- if (target !== void 0) {
821
- const wanted = this.#canonical(target);
866
+ popTo(to) {
867
+ const url = typeof to === "string" ? to : this.#builder.build(to);
868
+ const { hash, pathname, search } = resolvePath(url, this.#history.location);
869
+ const wantedMatch = this.#matcher.match(pathname, search, hash);
870
+ if (wantedMatch !== void 0) {
871
+ const wanted = this.#canonical(wantedMatch);
822
872
  const entries = this.#history.entries();
823
873
  for (let i = this.#history.location.index; i >= 0; i--) {
824
874
  const entry = entries[i];
825
875
  if (entry === void 0 || !entry.sameDocument || entry.url === null) break;
826
876
  const parts = parsePath(entry.url);
827
877
  const match = this.#matcher.match(parts.pathname, parts.search, parts.hash);
828
- if (match !== void 0 && match.name === target.name && this.#canonical(match) === wanted) {
878
+ if (match !== void 0 && match.name === wantedMatch.name && this.#canonical(match) === wanted) {
829
879
  this.#history.traverseTo(entry.key);
830
880
  return;
831
881
  }
832
882
  }
833
883
  }
834
- this.push(url);
884
+ this.#history.push(url);
835
885
  }
836
886
  /**
837
- * updates query parameters in-place without pushing a new entry.
887
+ * patches the active route's query params in place, without pushing a new entry.
838
888
  *
889
+ * params the patch does not mention keep their values; setting one to `undefined` drops it from the URL.
890
+ * keys the route does not declare are ignored.
891
+ *
892
+ * @param name the active route's name, which types the patch
839
893
  * @param patch query parameter changes
894
+ * @throws when `name` is not the active route
840
895
  */
841
- setParams(patch) {
842
- const active = this.#entries.get(this.#activeKey);
843
- const leaf = active === void 0 ? void 0 : this.#routes.leaves.get(active.match.name);
844
- if (leaf === void 0) return;
896
+ replace(name, patch) {
897
+ const active = this.#active();
898
+ if (active.match.name !== name) throw new Error(`stacker: replace('${name}') called under route '${active.match.name}'`);
899
+ const leaf = this.#routes.leaves.get(name);
900
+ if (leaf === void 0) throw new Error(`stacker: unknown route '${name}'`);
845
901
  const location = this.#history.location;
846
902
  const search = new URLSearchParams(location.search);
847
- for (const [name, value] of Object.entries(patch)) {
848
- const codec = leaf.query[name];
903
+ for (const [param, value] of Object.entries(patch)) {
904
+ const codec = leaf.query[param];
849
905
  if (codec === void 0) continue;
850
- if (value === void 0) search.delete(name);
851
- else search.set(name, codec.encode(value));
906
+ if (value === void 0) search.delete(param);
907
+ else search.set(param, codec.encode(value));
852
908
  }
853
909
  const query = search.toString();
854
910
  const to = createPath({
@@ -934,11 +990,14 @@ var Router = class {
934
990
  for (const key of this.#entries.keys()) if (!live.has(key)) this.#entries.delete(key);
935
991
  }
936
992
  #record(location, scrollPos) {
993
+ const match = this.#match(location);
994
+ preloadAll(match.leaf.chain);
937
995
  const entry = {
938
996
  index: location.index,
939
997
  key: location.key,
940
- match: this.#match(location),
941
- scrollPos
998
+ match,
999
+ scrollPos,
1000
+ target: toTarget(match)
942
1001
  };
943
1002
  this.#entries.set(location.key, entry);
944
1003
  this.#recency = [entry.key, ...this.#recency.filter((key) => key !== entry.key)];
@@ -986,19 +1045,23 @@ var Router = class {
986
1045
  };
987
1046
  }
988
1047
  };
1048
+ const toTarget = (match) => ({
1049
+ ...match.params,
1050
+ name: match.name
1051
+ });
989
1052
  const makeNotFound = (component) => {
990
1053
  const leafNode = {
991
- component,
992
1054
  kind: "route",
1055
+ component,
993
1056
  params: {},
994
1057
  path: "*",
995
1058
  query: {},
996
1059
  type: "page"
997
1060
  };
998
1061
  const node = {
1062
+ kind: "route",
999
1063
  id: " notFound",
1000
1064
  key: " notFound",
1001
- kind: "route",
1002
1065
  node: leafNode,
1003
1066
  params: {},
1004
1067
  path: "*"
@@ -1165,6 +1228,9 @@ const useFocusEffect = (effect) => {
1165
1228
  /**
1166
1229
  * generates typed hooks bound to a specific route registry.
1167
1230
  *
1231
+ * one-off reads of the router, like building a URL or navigating, go through {@link RouterHooks.useRouter}
1232
+ * instead; only state a component has to re-render on gets a hook of its own.
1233
+ *
1168
1234
  * @param routes the compiled registry the hooks are typed against
1169
1235
  * @returns typed hooks record
1170
1236
  * @throws when used with a router built from a different registry
@@ -1177,31 +1243,21 @@ const createRouterHooks = (routes) => {
1177
1243
  return router;
1178
1244
  };
1179
1245
  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
1246
  useParams(name) {
1194
1247
  const router = useTypedRouter();
1195
1248
  const current = useContext(CurrentNodeContext);
1196
- const setParams = useMemo(() => {
1197
- return (patch) => router.setParams(patch);
1198
- }, [router]);
1249
+ const replace = useMemo(() => {
1250
+ return (patch) => router.replace(name, patch);
1251
+ }, [name, router]);
1199
1252
  if (current === null) throw new Error("stacker: useParams must be used within a route component");
1200
1253
  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, setParams];
1254
+ return [current.node.params, replace];
1202
1255
  },
1203
- useRoute,
1204
- useRouter: useTypedRouter
1256
+ useRouter: useTypedRouter,
1257
+ useTarget() {
1258
+ const router = useTypedRouter();
1259
+ return useSyncExternalStore(router.subscribe, () => router.target);
1260
+ }
1205
1261
  };
1206
1262
  };
1207
1263
  //#endregion
@@ -1230,12 +1286,14 @@ const Link = ({ children, onClick, replace, to, ...rest }) => {
1230
1286
  onClick?.(event);
1231
1287
  if (event.defaultPrevented || isModifiedClick(event) || rest.download !== void 0 || rest.target !== void 0 && rest.target !== "" && rest.target !== "_self" || !isRoutable(to)) return;
1232
1288
  event.preventDefault();
1233
- if (replace) router.replace(to);
1234
- else router.push(to);
1289
+ router.navigate({
1290
+ replace,
1291
+ to
1292
+ });
1235
1293
  },
1236
1294
  ...rest,
1237
1295
  children
1238
1296
  });
1239
1297
  };
1240
1298
  //#endregion
1241
- export { Link, NavigationHistory, Outlet, Router, RouterView, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
1299
+ export { Link, NavigationHistory, Outlet, Router, RouterView, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, lazy, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
package/dist/testing.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as resolvePath, t as createPath } from "./url-gf-m_-s3.mjs";
1
+ import { o as resolvePath, t as createPath } from "./url-DerpiRjh.mjs";
2
2
  import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
3
3
  //#region src/history/memory.ts
4
4
  const ROOT = {
@@ -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) => value.split("/").map(encodeURIComponent).join("/");
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 { resolvePath as a, parsePath as i, decodeRemainder as n, encodeRemainder as r, createPath as t };
57
+ export { parsePath as a, encodeSegment as i, decodeRemainder as n, resolvePath as o, encodeRemainder as r, createPath as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oomfware/stacker",
3
- "version": "0.1.3",
3
+ "version": "0.2.1",
4
4
  "description": "type-safe stack router for React",
5
5
  "license": "0BSD",
6
6
  "repository": {