@oomfware/stacker 0.1.1 → 0.1.3

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/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as HistoryLocation, i as HistoryListener, n as HistoryAction, o as HistoryNavigateOptions, r as HistoryEntry, s as HistoryUpdate, t as History } from "./types-Dj7Al7f8.mjs";
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
2
  import { AnchorHTMLAttributes, ComponentType, EffectCallback, ReactElement, ReactNode } from "react";
3
3
  //#region src/codec.d.ts
4
4
  /**
@@ -364,6 +364,8 @@ interface RouterOptions<R extends RouteRegistry<unknown>> {
364
364
  readonly pins?: readonly string[];
365
365
  /** compiled route registry. */
366
366
  readonly routes: R;
367
+ /** window whose scroll position the router restores, defaulting to the global one where there is one. */
368
+ readonly window?: Window;
367
369
  }
368
370
  /**
369
371
  * manages navigation state, history subscriptions, and active views.
@@ -410,6 +412,15 @@ declare class Router<R extends RouteRegistry<unknown>> {
410
412
  * @returns relative URL
411
413
  */
412
414
  build<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): string;
415
+ /**
416
+ * matches a URL against the route registry, without navigating to it.
417
+ *
418
+ * the URL is resolved against the active location, the same way {@link push} resolves it.
419
+ *
420
+ * @param to destination relative URL
421
+ * @returns the match, or undefined when no route matches
422
+ */
423
+ match(to: string): RouteMatch | undefined;
413
424
  /**
414
425
  * navigates to a route.
415
426
  *
@@ -444,6 +455,13 @@ declare class Router<R extends RouteRegistry<unknown>> {
444
455
  attachView(): () => void;
445
456
  /** resolves pending navigation transitions after a view commits. */
446
457
  notifyCommit(): void;
458
+ /**
459
+ * applies the viewport offset the active navigation is waiting on, if any.
460
+ *
461
+ * `RouterView` calls this from a layout effect ordered ahead of every branch's, so a branch measures its
462
+ * own offset rather than the outgoing screen's. a no-op with nothing pending.
463
+ */
464
+ restoreScroll(): void;
447
465
  /** detaches history listeners and disposes resources. */
448
466
  dispose(): void;
449
467
  }
@@ -555,4 +573,4 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'
555
573
  */
556
574
  declare const Link: ({ children, onClick, replace, to, ...rest }: LinkProps) => ReactElement;
557
575
  //#endregion
558
- export { type BuildParamsOf, type Codec, type DefaultedCodec, type History, type HistoryAction, type HistoryEntry, type HistoryListener, type HistoryLocation, type HistoryNavigateOptions, 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 };
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 };
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 resolvePath, i as parsePath, n as decodeRemainder, r as encodeRemainder, t as createPath } from "./url-gf-m_-s3.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");
@@ -409,6 +409,7 @@ var NavigationHistory = class {
409
409
  this.#ignore = options.ignore;
410
410
  this.#location = this.#read();
411
411
  this.#nav.addEventListener("navigate", this.#onNavigate);
412
+ this.#win.history.scrollRestoration = "manual";
412
413
  }
413
414
  get location() {
414
415
  return this.#location;
@@ -494,16 +495,18 @@ var NavigationHistory = class {
494
495
  if (action !== "traverse" && this.#ignore?.(new URL(event.destination.url))) return;
495
496
  const envelope = isEnvelope(event.info) ? event.info : void 0;
496
497
  const info = envelope === void 0 ? event.info : envelope.info;
497
- const preserve = (envelope?.scroll ?? "auto") === "preserve";
498
+ const scroll = envelope?.scroll ?? "auto";
499
+ const preserve = scroll === "preserve";
498
500
  event.intercept({
499
501
  focusReset: preserve ? "manual" : "after-transition",
500
- scroll: preserve ? "manual" : "after-transition",
502
+ scroll: "manual",
501
503
  handler: async () => {
502
504
  this.#location = this.#read();
503
505
  const update = {
504
506
  action,
505
507
  info,
506
- location: this.#location
508
+ location: this.#location,
509
+ scroll
507
510
  };
508
511
  await Promise.all([...this.#listeners].map(async (listener) => listener(update)));
509
512
  }
@@ -659,6 +662,10 @@ const computeView = (cached, pinned, activeKey) => {
659
662
  //#endregion
660
663
  //#region src/router.ts
661
664
  const DefaultNotFound = () => null;
665
+ const TOP = {
666
+ x: 0,
667
+ y: 0
668
+ };
662
669
  /**
663
670
  * manages navigation state, history subscriptions, and active views.
664
671
  *
@@ -674,6 +681,7 @@ var Router = class {
674
681
  #defaultFallback;
675
682
  #notFound;
676
683
  #pins;
684
+ #win;
677
685
  #updates = new SimpleEventEmitter();
678
686
  #unlisten;
679
687
  #activePins = /* @__PURE__ */ new Set();
@@ -683,6 +691,7 @@ var Router = class {
683
691
  #view;
684
692
  #commitWaiters = [];
685
693
  #viewAttached = false;
694
+ #pendingScroll = null;
686
695
  constructor(options) {
687
696
  this.#history = options.history;
688
697
  this.#routes = options.routes;
@@ -692,18 +701,31 @@ var Router = class {
692
701
  this.#defaultFallback = options.defaultFallback;
693
702
  this.#notFound = makeNotFound(options.notFound ?? DefaultNotFound);
694
703
  this.#pins = new Map((options.pins ?? []).map((name) => [name, this.#makePin(name)]));
704
+ this.#win = options.window ?? (typeof window === "undefined" ? null : window);
695
705
  const location = this.#history.location;
696
706
  this.#activeKey = location.key;
697
- this.#record(location);
707
+ this.#record(location, TOP);
698
708
  this.#view = this.#recompute();
699
- this.#unlisten = this.#history.listen(async ({ location: next }) => {
709
+ this.#unlisten = this.#history.listen(async ({ action, location: next, scroll }) => {
710
+ const win = this.#win;
711
+ const restoring = scroll === "auto" && win !== null;
712
+ if (restoring) {
713
+ const outgoing = this.#entries.get(this.#activeKey);
714
+ if (outgoing !== void 0) outgoing.scrollPos = {
715
+ x: win.scrollX,
716
+ y: win.scrollY
717
+ };
718
+ }
700
719
  this.#prune();
701
- this.#record(next);
720
+ const target = (action === "traverse" ? this.#entries.get(next.key)?.scrollPos : void 0) ?? TOP;
721
+ this.#record(next, target);
702
722
  this.#activeKey = next.key;
703
723
  this.#view = this.#recompute();
724
+ this.#pendingScroll = restoring ? target : null;
704
725
  const committed = this.#awaitCommit();
705
726
  this.#updates.emit();
706
727
  await committed;
728
+ this.restoreScroll();
707
729
  });
708
730
  }
709
731
  /** current view structure. */
@@ -765,6 +787,18 @@ var Router = class {
765
787
  return this.#builder.build(name, ...args);
766
788
  }
767
789
  /**
790
+ * matches a URL against the route registry, without navigating to it.
791
+ *
792
+ * the URL is resolved against the active location, the same way {@link push} resolves it.
793
+ *
794
+ * @param to destination relative URL
795
+ * @returns the match, or undefined when no route matches
796
+ */
797
+ match(to) {
798
+ const { hash, pathname, search } = resolvePath(to, this.#history.location);
799
+ return this.#matcher.match(pathname, search, hash);
800
+ }
801
+ /**
768
802
  * navigates to a route.
769
803
  *
770
804
  * @param name route name
@@ -855,6 +889,23 @@ var Router = class {
855
889
  notifyCommit() {
856
890
  for (const resolve of this.#commitWaiters.splice(0)) resolve();
857
891
  }
892
+ /**
893
+ * applies the viewport offset the active navigation is waiting on, if any.
894
+ *
895
+ * `RouterView` calls this from a layout effect ordered ahead of every branch's, so a branch measures its
896
+ * own offset rather than the outgoing screen's. a no-op with nothing pending.
897
+ */
898
+ restoreScroll() {
899
+ const pending = this.#pendingScroll;
900
+ const win = this.#win;
901
+ if (pending === null || win === null) return;
902
+ this.#pendingScroll = null;
903
+ win.scrollTo({
904
+ behavior: "instant",
905
+ left: pending.x,
906
+ top: pending.y
907
+ });
908
+ }
858
909
  /** detaches history listeners and disposes resources. */
859
910
  dispose() {
860
911
  this.#unlisten();
@@ -882,11 +933,12 @@ var Router = class {
882
933
  const live = new Set(this.#history.entries().map((entry) => entry.key));
883
934
  for (const key of this.#entries.keys()) if (!live.has(key)) this.#entries.delete(key);
884
935
  }
885
- #record(location) {
936
+ #record(location, scrollPos) {
886
937
  const entry = {
887
938
  index: location.index,
888
939
  key: location.key,
889
- match: this.#match(location)
940
+ match: this.#match(location),
941
+ scrollPos
890
942
  };
891
943
  this.#entries.set(location.key, entry);
892
944
  this.#recency = [entry.key, ...this.#recency.filter((key) => key !== entry.key)];
@@ -990,12 +1042,21 @@ const RouterView = ({ router }) => {
990
1042
  }, [router, view]);
991
1043
  return /* @__PURE__ */ jsx(RouterContext, {
992
1044
  value: router,
993
- children: /* @__PURE__ */ jsx(ActiveChainContext, {
1045
+ children: /* @__PURE__ */ jsxs(ActiveChainContext, {
994
1046
  value: view.activePath,
995
- children: /* @__PURE__ */ jsx(Pool, { nodes: view.roots })
1047
+ children: [/* @__PURE__ */ jsx(ScrollRestorer, {
1048
+ router,
1049
+ view
1050
+ }), /* @__PURE__ */ jsx(Pool, { nodes: view.roots })]
996
1051
  })
997
1052
  });
998
1053
  };
1054
+ const ScrollRestorer = ({ router, view }) => {
1055
+ useLayoutEffect(() => {
1056
+ router.restoreScroll();
1057
+ }, [router, view]);
1058
+ return null;
1059
+ };
999
1060
  const Pool = ({ nodes }) => {
1000
1061
  const activePath = useContext(ActiveChainContext);
1001
1062
  return /* @__PURE__ */ jsx(Fragment, { children: nodes.map((node) => /* @__PURE__ */ jsx(Branch, {
@@ -1,4 +1,4 @@
1
- import { a as HistoryLocation, i as HistoryListener, o as HistoryNavigateOptions, r as HistoryEntry, t as History } from "./types-Dj7Al7f8.mjs";
1
+ import { a as HistoryLocation, i as HistoryListener, o as HistoryNavigateOptions, r as HistoryEntry, t as History } from "./types-KOb6CZ7N.mjs";
2
2
  //#region src/history/memory.d.ts
3
3
  /** options for the memory history constructor. */
4
4
  interface MemoryHistoryOptions {
package/dist/testing.mjs CHANGED
@@ -50,7 +50,8 @@ var MemoryHistory = class {
50
50
  this.#emit({
51
51
  action: "push",
52
52
  info: options.info,
53
- location
53
+ location,
54
+ scroll: options.scroll ?? "auto"
54
55
  });
55
56
  }
56
57
  replace(to, options = {}) {
@@ -60,7 +61,8 @@ var MemoryHistory = class {
60
61
  this.#emit({
61
62
  action: "replace",
62
63
  info: options.info,
63
- location
64
+ location,
65
+ scroll: options.scroll ?? "auto"
64
66
  });
65
67
  }
66
68
  traverseTo(key) {
@@ -75,7 +77,8 @@ var MemoryHistory = class {
75
77
  this.#emit({
76
78
  action: "traverse",
77
79
  info: void 0,
78
- location: this.#current()
80
+ location: this.#current(),
81
+ scroll: "auto"
79
82
  });
80
83
  }
81
84
  back() {
@@ -40,11 +40,11 @@ interface HistoryLocation {
40
40
  readonly state: unknown;
41
41
  }
42
42
  /**
43
- * how a history write treats the user's place on the page — scroll position and focus, which the browser
44
- * resets together and which a write therefore cannot sensibly split apart.
43
+ * how a history write treats the user's place on the page — scroll position and focus, which a write cannot
44
+ * sensibly split apart.
45
45
  *
46
- * - `auto` — a new screen. the browser restores scroll on a traversal or resets it on a push, and moves focus
47
- * to the new content.
46
+ * - `auto` — a new screen. scroll is restored on a traversal if the offset is still known and reset to the top
47
+ * otherwise, and focus moves to the new content.
48
48
  * - `preserve` — the same screen with different state, like an in-place parameter patch. scroll and focus are
49
49
  * both left exactly where the user put them.
50
50
  */
@@ -64,11 +64,13 @@ interface HistoryUpdate {
64
64
  /** metadata passed to the write operation. */
65
65
  readonly info: unknown;
66
66
  readonly location: HistoryLocation;
67
+ /** viewport behavior, which listeners apply. */
68
+ readonly scroll: HistoryScrollBehavior;
67
69
  }
68
70
  /**
69
71
  * history update callback subscriber.
70
72
  *
71
- * listeners can return a promise to defer scroll restoration and focus resets.
73
+ * listeners can return a promise to defer focus resets.
72
74
  */
73
75
  type HistoryListener = (update: HistoryUpdate) => void | Promise<void>;
74
76
  /** history manager interface modeled on the web navigation API. */
@@ -126,4 +128,4 @@ interface History {
126
128
  traverseTo(key: string): void;
127
129
  }
128
130
  //#endregion
129
- export { HistoryLocation as a, HistoryListener as i, HistoryAction as n, HistoryNavigateOptions as o, HistoryEntry as r, HistoryUpdate as s, History as t };
131
+ export { HistoryLocation as a, HistoryUpdate as c, HistoryListener as i, HistoryAction as n, HistoryNavigateOptions as o, HistoryEntry as r, HistoryScrollBehavior as s, History as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oomfware/stacker",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "type-safe stack router for React",
5
5
  "license": "0BSD",
6
6
  "repository": {
@@ -42,13 +42,13 @@
42
42
  "bumpp": "^11.1.0",
43
43
  "oxfmt": "^0.59.0",
44
44
  "oxlint": "^1.74.0",
45
- "oxlint-tsgolint": "^0.24.0",
45
+ "oxlint-tsgolint": "^0.25.0",
46
46
  "playwright": "^1.61.1",
47
47
  "react": "^19.2.7",
48
48
  "react-dom": "^19.2.7",
49
- "tsdown": "^0.22.8",
49
+ "tsdown": "^0.22.9",
50
50
  "typescript": "^7.0.2",
51
- "vite": "^8.1.4",
51
+ "vite": "^8.1.5",
52
52
  "vitest": "^4.1.10"
53
53
  },
54
54
  "peerDependencies": {