@oomfware/stacker 0.1.2 → 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 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 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.
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 { useNavigate, useParams } = createRouterHooks(routes);
216
+ const { useParams, useRouter } = createRouterHooks(routes);
184
217
 
185
218
  const Profile = () => {
186
- const [{ actor }, setParams] = useParams('Profile');
187
- const navigate = useNavigate();
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={() => setParams({ tab: 'media' })}>media</button>
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,38 +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
- * generates a URL for a route.
428
+ * builds the URL for a route.
409
429
  *
410
- * @param name route name
411
- * @param args route parameters
430
+ * @param target route name and parameters
412
431
  * @returns relative URL
413
432
  */
414
- build<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): string;
433
+ href(target: RouteTarget<R>): string;
434
+ /**
435
+ * matches a URL against the route registry, without navigating to it.
436
+ *
437
+ * the URL is resolved against the active location, the same way {@link navigate} resolves it.
438
+ *
439
+ * @param to destination relative URL
440
+ * @returns the target it resolves to, or undefined when no route matches
441
+ */
442
+ match(to: string): MatchedTarget<R> | undefined;
415
443
  /**
416
444
  * navigates to a route.
417
445
  *
418
- * @param name route name
419
- * @param args route parameters
446
+ * @param options where to go, and how to get there
420
447
  */
421
- navigate<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): void;
448
+ navigate(options: NavigateOptions<R>): void;
422
449
  /**
423
450
  * returns to the nearest existing history entry for a route, or pushes if none exists.
424
451
  *
425
- * @param name route name
426
- * @param args route parameters
452
+ * @param to route target, or a relative URL resolved against the active location
427
453
  */
428
- popTo<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): void;
454
+ popTo(to: RouteTarget<R> | string): void;
429
455
  /**
430
- * updates query parameters in-place without pushing a new entry.
456
+ * patches the active route's query params in place, without pushing a new entry.
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.
431
460
  *
461
+ * @param name the active route's name, which types the patch
432
462
  * @param patch query parameter changes
463
+ * @throws when `name` is not the active route
433
464
  */
434
- setParams(patch: Readonly<Record<string, unknown>>): void;
465
+ replace<K extends RouteName<R>>(name: K, patch: QueryPatchOf<R, K>): void;
435
466
  /** navigates back one entry. */
436
467
  back(): void;
437
468
  /** navigates forward one entry. */
@@ -446,6 +477,13 @@ declare class Router<R extends RouteRegistry<unknown>> {
446
477
  attachView(): () => void;
447
478
  /** resolves pending navigation transitions after a view commits. */
448
479
  notifyCommit(): void;
480
+ /**
481
+ * applies the viewport offset the active navigation is waiting on, if any.
482
+ *
483
+ * `RouterView` calls this from a layout effect ordered ahead of every branch's, so a branch measures its
484
+ * own offset rather than the outgoing screen's. a no-op with nothing pending.
485
+ */
486
+ restoreScroll(): void;
449
487
  /** detaches history listeners and disposes resources. */
450
488
  dispose(): void;
451
489
  }
@@ -517,22 +555,19 @@ declare const useIsFocused: () => boolean;
517
555
  declare const useFocusEffect: (effect: EffectCallback) => void;
518
556
  /** typed hooks bound to a specific route registry. */
519
557
  interface RouterHooks<R extends RouteRegistry<unknown>> {
520
- /** returns a function to build URLs. */
521
- useBuild(): Router<R>['build'];
522
- /** gets the current location. */
523
- useLocation(): HistoryLocation;
524
- /** returns a function to navigate to routes. */
525
- useNavigate(): Router<R>['navigate'];
526
558
  /** gets a route's parameters and a setter that patches its query in place. */
527
559
  useParams<K extends RouteName<R>>(name: K): readonly [ParamsOf<R, K>, (patch: QueryPatchOf<R, K>) => void];
528
- /** gets the active route match. */
529
- useRoute(): RouteMatch;
530
560
  /** gets the typed router instance. */
531
561
  useRouter(): Router<R>;
562
+ /** gets the active route's name and parameters. */
563
+ useTarget(): MatchedTarget<R>;
532
564
  }
533
565
  /**
534
566
  * generates typed hooks bound to a specific route registry.
535
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
+ *
536
571
  * @param routes the compiled registry the hooks are typed against
537
572
  * @returns typed hooks record
538
573
  * @throws when used with a router built from a different registry
@@ -557,4 +592,4 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'
557
592
  */
558
593
  declare const Link: ({ children, onClick, replace, to, ...rest }: LinkProps) => ReactElement;
559
594
  //#endregion
560
- 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,7 +1,7 @@
1
- import { 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
2
  import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
3
3
  import { Suspense, createContext, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
4
- import { Fragment, jsx } from "react/jsx-runtime";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  //#region src/codec.ts
6
6
  const OPTIONAL = Symbol("stacker.optional");
7
7
  const DEFAULT = Symbol("stacker.default");
@@ -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(name, ...args) {
530
- return this.buildPath(name, args[0] ?? {});
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 encodeURIComponent(encoded);
550
+ return encodeSegment(encoded);
549
551
  });
550
552
  if (splat !== void 0) {
551
553
  const remainder = encodeParam(splat);
@@ -691,6 +693,7 @@ var Router = class {
691
693
  #view;
692
694
  #commitWaiters = [];
693
695
  #viewAttached = false;
696
+ #pendingScroll = null;
694
697
  constructor(options) {
695
698
  this.#history = options.history;
696
699
  this.#routes = options.routes;
@@ -720,14 +723,11 @@ var Router = class {
720
723
  this.#record(next, target);
721
724
  this.#activeKey = next.key;
722
725
  this.#view = this.#recompute();
726
+ this.#pendingScroll = restoring ? target : null;
723
727
  const committed = this.#awaitCommit();
724
728
  this.#updates.emit();
725
729
  await committed;
726
- if (restoring) win.scrollTo({
727
- behavior: "instant",
728
- left: target.x,
729
- top: target.y
730
- });
730
+ this.restoreScroll();
731
731
  });
732
732
  }
733
733
  /** current view structure. */
@@ -738,10 +738,14 @@ var Router = class {
738
738
  get location() {
739
739
  return this.#history.location;
740
740
  }
741
- /** active route match details. */
741
+ /** active route match details, including the matched chain that `resolveMeta` takes. */
742
742
  get route() {
743
743
  return this.#active().match;
744
744
  }
745
+ /** the active route's name and parameters. */
746
+ get target() {
747
+ return this.#active().target;
748
+ }
745
749
  /** whether backward history is available. */
746
750
  get canGoBack() {
747
751
  return this.#history.canGoBack;
@@ -770,75 +774,86 @@ var Router = class {
770
774
  subscribe = (listener) => {
771
775
  return this.#updates.subscribe(listener);
772
776
  };
773
- /** pushes a new location onto the history stack. */
774
- push(to) {
775
- this.#history.push(to);
776
- }
777
- /** replaces the current location on the history stack. */
778
- replace(to) {
779
- this.#history.replace(to);
780
- }
781
777
  /**
782
- * generates a URL for a route.
778
+ * builds the URL for a route.
783
779
  *
784
- * @param name route name
785
- * @param args route parameters
780
+ * @param target route name and parameters
786
781
  * @returns relative URL
787
782
  */
788
- build(name, ...args) {
789
- return this.#builder.build(name, ...args);
783
+ href(target) {
784
+ return this.#builder.build(target);
785
+ }
786
+ /**
787
+ * matches a URL against the route registry, without navigating to it.
788
+ *
789
+ * the URL is resolved against the active location, the same way {@link navigate} resolves it.
790
+ *
791
+ * @param to destination relative URL
792
+ * @returns the target it resolves to, or undefined when no route matches
793
+ */
794
+ match(to) {
795
+ const { hash, pathname, search } = resolvePath(to, this.#history.location);
796
+ const match = this.#matcher.match(pathname, search, hash);
797
+ return match === void 0 ? void 0 : toTarget(match);
790
798
  }
791
799
  /**
792
800
  * navigates to a route.
793
801
  *
794
- * @param name route name
795
- * @param args route parameters
802
+ * @param options where to go, and how to get there
796
803
  */
797
- navigate(name, ...args) {
798
- this.push(this.#builder.build(name, ...args));
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);
799
809
  }
800
810
  /**
801
811
  * returns to the nearest existing history entry for a route, or pushes if none exists.
802
812
  *
803
- * @param name route name
804
- * @param args route parameters
813
+ * @param to route target, or a relative URL resolved against the active location
805
814
  */
806
- popTo(name, ...args) {
807
- const url = this.#builder.build(name, ...args);
808
- const { hash, pathname, search } = parsePath(url);
809
- const target = this.#matcher.match(pathname, search, hash);
810
- if (target !== void 0) {
811
- const wanted = this.#canonical(target);
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);
812
821
  const entries = this.#history.entries();
813
822
  for (let i = this.#history.location.index; i >= 0; i--) {
814
823
  const entry = entries[i];
815
824
  if (entry === void 0 || !entry.sameDocument || entry.url === null) break;
816
825
  const parts = parsePath(entry.url);
817
826
  const match = this.#matcher.match(parts.pathname, parts.search, parts.hash);
818
- if (match !== void 0 && match.name === target.name && this.#canonical(match) === wanted) {
827
+ if (match !== void 0 && match.name === wantedMatch.name && this.#canonical(match) === wanted) {
819
828
  this.#history.traverseTo(entry.key);
820
829
  return;
821
830
  }
822
831
  }
823
832
  }
824
- this.push(url);
833
+ this.#history.push(url);
825
834
  }
826
835
  /**
827
- * updates query parameters in-place without pushing a new entry.
836
+ * patches the active route's query params in place, without pushing a new entry.
828
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.
840
+ *
841
+ * @param name the active route's name, which types the patch
829
842
  * @param patch query parameter changes
843
+ * @throws when `name` is not the active route
830
844
  */
831
- setParams(patch) {
832
- const active = this.#entries.get(this.#activeKey);
833
- const leaf = active === void 0 ? void 0 : this.#routes.leaves.get(active.match.name);
834
- if (leaf === void 0) return;
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}'`);
835
850
  const location = this.#history.location;
836
851
  const search = new URLSearchParams(location.search);
837
- for (const [name, value] of Object.entries(patch)) {
838
- const codec = leaf.query[name];
852
+ for (const [param, value] of Object.entries(patch)) {
853
+ const codec = leaf.query[param];
839
854
  if (codec === void 0) continue;
840
- if (value === void 0) search.delete(name);
841
- else search.set(name, codec.encode(value));
855
+ if (value === void 0) search.delete(param);
856
+ else search.set(param, codec.encode(value));
842
857
  }
843
858
  const query = search.toString();
844
859
  const to = createPath({
@@ -879,6 +894,23 @@ var Router = class {
879
894
  notifyCommit() {
880
895
  for (const resolve of this.#commitWaiters.splice(0)) resolve();
881
896
  }
897
+ /**
898
+ * applies the viewport offset the active navigation is waiting on, if any.
899
+ *
900
+ * `RouterView` calls this from a layout effect ordered ahead of every branch's, so a branch measures its
901
+ * own offset rather than the outgoing screen's. a no-op with nothing pending.
902
+ */
903
+ restoreScroll() {
904
+ const pending = this.#pendingScroll;
905
+ const win = this.#win;
906
+ if (pending === null || win === null) return;
907
+ this.#pendingScroll = null;
908
+ win.scrollTo({
909
+ behavior: "instant",
910
+ left: pending.x,
911
+ top: pending.y
912
+ });
913
+ }
882
914
  /** detaches history listeners and disposes resources. */
883
915
  dispose() {
884
916
  this.#unlisten();
@@ -907,11 +939,13 @@ var Router = class {
907
939
  for (const key of this.#entries.keys()) if (!live.has(key)) this.#entries.delete(key);
908
940
  }
909
941
  #record(location, scrollPos) {
942
+ const match = this.#match(location);
910
943
  const entry = {
911
944
  index: location.index,
912
945
  key: location.key,
913
- match: this.#match(location),
914
- scrollPos
946
+ match,
947
+ scrollPos,
948
+ target: toTarget(match)
915
949
  };
916
950
  this.#entries.set(location.key, entry);
917
951
  this.#recency = [entry.key, ...this.#recency.filter((key) => key !== entry.key)];
@@ -959,6 +993,10 @@ var Router = class {
959
993
  };
960
994
  }
961
995
  };
996
+ const toTarget = (match) => ({
997
+ ...match.params,
998
+ name: match.name
999
+ });
962
1000
  const makeNotFound = (component) => {
963
1001
  const leafNode = {
964
1002
  component,
@@ -1015,12 +1053,21 @@ const RouterView = ({ router }) => {
1015
1053
  }, [router, view]);
1016
1054
  return /* @__PURE__ */ jsx(RouterContext, {
1017
1055
  value: router,
1018
- children: /* @__PURE__ */ jsx(ActiveChainContext, {
1056
+ children: /* @__PURE__ */ jsxs(ActiveChainContext, {
1019
1057
  value: view.activePath,
1020
- children: /* @__PURE__ */ jsx(Pool, { nodes: view.roots })
1058
+ children: [/* @__PURE__ */ jsx(ScrollRestorer, {
1059
+ router,
1060
+ view
1061
+ }), /* @__PURE__ */ jsx(Pool, { nodes: view.roots })]
1021
1062
  })
1022
1063
  });
1023
1064
  };
1065
+ const ScrollRestorer = ({ router, view }) => {
1066
+ useLayoutEffect(() => {
1067
+ router.restoreScroll();
1068
+ }, [router, view]);
1069
+ return null;
1070
+ };
1024
1071
  const Pool = ({ nodes }) => {
1025
1072
  const activePath = useContext(ActiveChainContext);
1026
1073
  return /* @__PURE__ */ jsx(Fragment, { children: nodes.map((node) => /* @__PURE__ */ jsx(Branch, {
@@ -1129,6 +1176,9 @@ const useFocusEffect = (effect) => {
1129
1176
  /**
1130
1177
  * generates typed hooks bound to a specific route registry.
1131
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
+ *
1132
1182
  * @param routes the compiled registry the hooks are typed against
1133
1183
  * @returns typed hooks record
1134
1184
  * @throws when used with a router built from a different registry
@@ -1141,31 +1191,21 @@ const createRouterHooks = (routes) => {
1141
1191
  return router;
1142
1192
  };
1143
1193
  return {
1144
- useBuild() {
1145
- const router = useTypedRouter();
1146
- return useMemo(() => {
1147
- return (name, ...args) => router.build(name, ...args);
1148
- }, [router]);
1149
- },
1150
- useLocation,
1151
- useNavigate() {
1152
- const router = useTypedRouter();
1153
- return useMemo(() => {
1154
- return (name, ...args) => router.navigate(name, ...args);
1155
- }, [router]);
1156
- },
1157
1194
  useParams(name) {
1158
1195
  const router = useTypedRouter();
1159
1196
  const current = useContext(CurrentNodeContext);
1160
- const setParams = useMemo(() => {
1161
- return (patch) => router.setParams(patch);
1162
- }, [router]);
1197
+ const replace = useMemo(() => {
1198
+ return (patch) => router.replace(name, patch);
1199
+ }, [name, router]);
1163
1200
  if (current === null) throw new Error("stacker: useParams must be used within a route component");
1164
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}'`);
1165
- return [current.node.params, setParams];
1202
+ return [current.node.params, replace];
1166
1203
  },
1167
- useRoute,
1168
- useRouter: useTypedRouter
1204
+ useRouter: useTypedRouter,
1205
+ useTarget() {
1206
+ const router = useTypedRouter();
1207
+ return useSyncExternalStore(router.subscribe, () => router.target);
1208
+ }
1169
1209
  };
1170
1210
  };
1171
1211
  //#endregion
@@ -1194,8 +1234,10 @@ const Link = ({ children, onClick, replace, to, ...rest }) => {
1194
1234
  onClick?.(event);
1195
1235
  if (event.defaultPrevented || isModifiedClick(event) || rest.download !== void 0 || rest.target !== void 0 && rest.target !== "" && rest.target !== "_self" || !isRoutable(to)) return;
1196
1236
  event.preventDefault();
1197
- if (replace) router.replace(to);
1198
- else router.push(to);
1237
+ router.navigate({
1238
+ replace,
1239
+ to
1240
+ });
1199
1241
  },
1200
1242
  ...rest,
1201
1243
  children
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.2",
3
+ "version": "0.2.0",
4
4
  "description": "type-safe stack router for React",
5
5
  "license": "0BSD",
6
6
  "repository": {