@k8ordo/router 1.4.0 → 1.4.2

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/base.d.mts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/base.d.ts
2
1
  /**
3
2
  * A pathname in the table's terms, as the URL spells it: the base in front.
4
3
  * Under `base: '/docs/'`, `/products` → `/docs/products` and `/` → `/docs/`.
@@ -12,5 +11,4 @@ export declare const withBase: (pathname: string, base?: string) => string;
12
11
  * `base: '/docs/'`, `/docs/products` → `/products`, and `/docs` and `/docs/`
13
12
  * → `/`.
14
13
  */
15
- export declare const withoutBase: (pathname: string, base?: string) => string | null;
16
- //#endregion
14
+ export declare const withoutBase: (pathname: string, base?: string) => string | null;
package/dist/base.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { normalizePathname } from "./paths.mjs";
2
- //#region src/base.ts
2
+ // src/base.ts
3
3
  /**
4
4
  * Where Vite serves the application — its `base`, as `import.meta.env.BASE_URL`
5
5
  * spells it (`/`, `/docs/`). Read when a caller does not pass a base: code
@@ -41,5 +41,4 @@ const withoutBase = (pathname, base = viteBase()) => {
41
41
  if (!pathname.startsWith(`${prefix}/`)) return null;
42
42
  return pathname.slice(prefix.length);
43
43
  };
44
- //#endregion
45
44
  export { withBase, withoutBase };
@@ -1,5 +1,4 @@
1
1
  import { ComponentType, ReactNode } from "react";
2
- //#region src/boundary.d.ts
3
2
  /**
4
3
  * What a route table's `error` component receives: what was thrown, and a
5
4
  * way to try the subtree again in place.
@@ -24,5 +23,4 @@ type BoundaryProps = {
24
23
  * application's layouts with it.
25
24
  */
26
25
  export declare const RouteErrorBoundary: ({ fallback, children }: BoundaryProps) => ReactNode;
27
- //#endregion
28
26
  export {};
package/dist/boundary.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { NavigationGeneration } from "./navigation.mjs";
3
3
  import { Component, Suspense, createElement, use } from "react";
4
- //#region src/boundary.tsx
4
+ // src/boundary.tsx
5
5
  var Catch = class extends Component {
6
6
  state = {
7
7
  error: void 0,
@@ -53,5 +53,4 @@ const RouteErrorBoundary = ({ fallback, children }) => {
53
53
  fallback
54
54
  }, children));
55
55
  };
56
- //#endregion
57
56
  export { RouteErrorBoundary };
@@ -1,7 +1,6 @@
1
1
  import { ErrorComponent } from "./boundary.mjs";
2
2
  import { Join, PathMatching } from "./paths.mjs";
3
3
  import { ComponentType, ReactNode } from "react";
4
- //#region src/define-routes.d.ts
5
4
  /**
6
5
  * Any component, whatever props it declares. The table is written once and
7
6
  * rendered by different renderers — a client app renders leaves with no
@@ -68,5 +67,4 @@ export type Routes<R extends RoutesRecord = RoutesRecord> = {
68
67
  };
69
68
  export declare const setBoundaryOutlet: (render: () => ReactNode) => void;
70
69
  export declare function defineRoutes<R extends RoutesRecord>(record: R): Routes<R>;
71
- //#endregion
72
70
  export {};
@@ -1,7 +1,7 @@
1
1
  import { isGroupKey, joinPattern, normalizePathname } from "./paths.mjs";
2
2
  import { RouteErrorBoundary } from "./boundary.mjs";
3
3
  import { Suspense, createElement } from "react";
4
- //#region src/define-routes.ts
4
+ // src/define-routes.ts
5
5
  const isBranch = (node) => typeof node === "object" && "children" in node;
6
6
  /**
7
7
  * A branch's `error` becomes an element of the stack — after the layout, so
@@ -93,5 +93,4 @@ function defineRoutes(record) {
93
93
  match
94
94
  };
95
95
  }
96
- //#endregion
97
96
  export { defineRoutes, setBoundaryOutlet };
package/dist/links.d.mts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { ParamValue } from "./paths.mjs";
2
2
  import { RegisteredNavigablePattern, RegisteredParams } from "./register.mjs";
3
- //#region src/links.d.ts
4
3
  type HrefArgs<Params> = keyof Params extends never ? [] : [params: Readonly<Params & Record<never, never>>];
5
4
  export type NavigateToOptions = {
6
5
  /**
@@ -57,5 +56,4 @@ export type BoundLinks<Bound extends BoundParams> = {
57
56
  * ```
58
57
  */
59
58
  export declare const bindParams: <const Bound extends BoundParams>(source: () => Bound) => BoundLinks<Bound>;
60
- //#endregion
61
59
  export {};
package/dist/links.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { buildHref } from "./paths.mjs";
2
2
  import { withBase } from "./base.mjs";
3
- //#region src/links.ts
3
+ // src/links.ts
4
4
  const navigate = (pattern, params, options) => navigation.navigate(withBase(buildHref(pattern, params)), { history: options?.history ?? "push" });
5
5
  /**
6
6
  * Builds the URL a link points at from a pattern and its params — no route
@@ -57,5 +57,4 @@ const bindParams = (source) => ({
57
57
  }, options);
58
58
  }
59
59
  });
60
- //#endregion
61
60
  export { bindParams, href, navigateTo };
@@ -1,5 +1,4 @@
1
1
  import { ReactNode } from "react";
2
- //#region src/location.d.ts
3
2
  /**
4
3
  * The pathname the render started from. A client component's first render can
5
4
  * happen where there is no Navigation API — on the server, and again during
@@ -43,5 +42,4 @@ export declare const appPathname: () => string;
43
42
  * every search change would defeat `@k8ordo/state`'s keyed subscriptions, and
44
43
  * the split at the `?` is the whole boundary between the two packages.
45
44
  */
46
- export declare function usePathname(): string;
47
- //#endregion
45
+ export declare function usePathname(): string;
package/dist/location.mjs CHANGED
@@ -4,7 +4,7 @@ import { withoutBase } from "./base.mjs";
4
4
  import { createContext, use, useMemo, useSyncExternalStore } from "react";
5
5
  import { browser } from "react-dom";
6
6
  import { jsx } from "react/jsx-runtime";
7
- //#region src/location.tsx
7
+ // src/location.tsx
8
8
  /** Below `BrowserPathname`: the render has no pathname, the browser does. */
9
9
  const IN_BROWSER = Symbol("k8ordo.browser-pathname");
10
10
  const ServerPathname = createContext(null);
@@ -36,8 +36,10 @@ const BrowserPathname = ({ children }) => /* @__PURE__ */ jsx(ServerPathname, {
36
36
  });
37
37
  const subscribe = (onChange) => {
38
38
  navigation.addEventListener("currententrychange", onChange);
39
+ window.addEventListener("popstate", onChange);
39
40
  return () => {
40
41
  navigation.removeEventListener("currententrychange", onChange);
42
+ window.removeEventListener("popstate", onChange);
41
43
  };
42
44
  };
43
45
  /**
@@ -70,5 +72,4 @@ function usePathname() {
70
72
  return fromServer;
71
73
  });
72
74
  }
73
- //#endregion
74
75
  export { BrowserPathname, PathnameProvider, appPathname, usePathname };
package/dist/match.d.mts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { ParamsOf } from "./paths.mjs";
2
2
  import { RegisteredNavigablePattern, RegisteredPattern } from "./register.mjs";
3
- //#region src/match.d.ts
4
3
  /**
5
4
  * A pattern from the table, or a table pattern followed by `/*` to mean
6
5
  * "everything below it" — the shape a navigation asks about when it wants
@@ -30,5 +29,4 @@ export declare const matchPath: <P extends MatchablePattern>(pattern: P, pathnam
30
29
  * sidebar can ask "is a page under `/docs/*` showing" without a table in the
31
30
  * browser, which is the question `useRoute` cannot answer under the framework.
32
31
  */
33
- export declare function useMatch<P extends MatchablePattern>(pattern: P, options?: MatchOptions): ParamsOf<P> | null;
34
- //#endregion
32
+ export declare function useMatch<P extends MatchablePattern>(pattern: P, options?: MatchOptions): ParamsOf<P> | null;
package/dist/match.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { normalizePathname } from "./paths.mjs";
3
3
  import { usePathname } from "./location.mjs";
4
- //#region src/match.ts
4
+ // src/match.ts
5
5
  const decode = (value) => {
6
6
  try {
7
7
  return decodeURIComponent(value);
@@ -36,5 +36,4 @@ const matchPath = (pattern, pathname, options) => {
36
36
  function useMatch(pattern, options) {
37
37
  return matchPath(pattern, usePathname(), options);
38
38
  }
39
- //#endregion
40
39
  export { matchPath, useMatch };
@@ -1,4 +1,3 @@
1
- //#region src/navigation.d.ts
2
1
  /**
3
2
  * What the decision below reads. Spelled out rather than taking the event,
4
3
  * because a `NavigateEvent` cannot be constructed in a test — its destination
@@ -120,5 +119,4 @@ export declare const NavigationGeneration: import("react").Context<number>;
120
119
  */
121
120
  export declare function useInterceptedNavigation<T>(handler: NavigationHandler<T>): {
122
121
  readonly generation: number;
123
- };
124
- //#endregion
122
+ };
@@ -2,7 +2,7 @@
2
2
  import { normalizePathname } from "./paths.mjs";
3
3
  import { withoutBase } from "./base.mjs";
4
4
  import { addTransitionType, createContext, startTransition, useDeferredValue, useEffect, useEffectEvent, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
5
- //#region src/navigation.ts
5
+ // src/navigation.ts
6
6
  /**
7
7
  * Whether this navigation is the application's to handle at all.
8
8
  *
@@ -63,6 +63,7 @@ const applyScroll = (plan) => {
63
63
  };
64
64
  const leftAt = /* @__PURE__ */ new Map();
65
65
  const LEFT_AT_KEY = "@k8ordo/router:left-at";
66
+ const LEFT_AT_LIMIT = 100;
66
67
  const readLeftAt = () => {
67
68
  try {
68
69
  const saved = sessionStorage.getItem(LEFT_AT_KEY);
@@ -71,12 +72,19 @@ const readLeftAt = () => {
71
72
  } catch {}
72
73
  };
73
74
  const rememberLeftAt = (entry) => {
75
+ leftAt.delete(entry);
74
76
  leftAt.set(entry, {
75
77
  left: window.scrollX,
76
78
  top: window.scrollY
77
79
  });
78
- const live = new Set(navigation.entries().map(({ key }) => key));
79
- for (const key of leftAt.keys()) if (!live.has(key)) leftAt.delete(key);
80
+ if (leftAt.size > LEFT_AT_LIMIT) {
81
+ const listed = new Set(navigation.entries().map(({ key }) => key));
82
+ const keys = [...leftAt.keys()];
83
+ for (const key of [...keys.filter((k) => !listed.has(k)), ...keys]) {
84
+ if (leftAt.size <= LEFT_AT_LIMIT) break;
85
+ leftAt.delete(key);
86
+ }
87
+ }
80
88
  try {
81
89
  sessionStorage.setItem(LEFT_AT_KEY, JSON.stringify([...leftAt]));
82
90
  } catch {}
@@ -175,16 +183,28 @@ function useInterceptedNavigation(handler) {
175
183
  shown.current = normalizePathname(location.pathname);
176
184
  readLeftAt();
177
185
  const onNavigate = (event) => {
186
+ const traverse = event.navigationType === "traverse";
187
+ if (traverse && isOurs(event) && onScreenEntry.current === null && event.destination.key === navigation.currentEntry?.key) {
188
+ event.intercept({
189
+ scroll: "manual",
190
+ focusReset: "manual"
191
+ });
192
+ return;
193
+ }
178
194
  const leaving = onScreenEntry.current ?? navigation.currentEntry?.key;
179
- if (leaving !== void 0) rememberLeftAt(leaving);
180
- if (!isOurs(event)) return;
195
+ if (leaving !== void 0 && leaving !== "") rememberLeftAt(leaving);
196
+ const keyless = traverse && event.destination.key === "";
197
+ if (!isOurs(event)) {
198
+ if (keyless) onScreenEntry.current = "";
199
+ else if (onScreenEntry.current === "") onScreenEntry.current = null;
200
+ return;
201
+ }
181
202
  const url = new URL(event.destination.url);
182
203
  const pathname = normalizePathname(url.pathname);
183
204
  const inPlace = pathname === shown.current;
184
- const traverse = event.navigationType === "traverse";
185
205
  if (inPlace && !refresh(url)) {
186
- const calledOff = event.destination.key === (onScreenEntry.current ?? navigation.currentEntry?.key);
187
- onScreenEntry.current = null;
206
+ const calledOff = event.destination.key !== "" && event.destination.key === onScreenEntry.current;
207
+ onScreenEntry.current = keyless ? "" : null;
188
208
  if (!traverse || calledOff) {
189
209
  event.intercept({
190
210
  scroll: "manual",
@@ -200,8 +220,9 @@ function useInterceptedNavigation(handler) {
200
220
  resolve: () => {
201
221
  resolve(void 0);
202
222
  },
203
- scroll: scrollPlanFor("traverse", url.hash, leftAt.get(event.destination.key)),
204
- types: []
223
+ scroll: keyless ? null : scrollPlanFor("traverse", url.hash, leftAt.get(event.destination.key)),
224
+ types: [],
225
+ keyless
205
226
  });
206
227
  event.signal.addEventListener("abort", () => {
207
228
  pending.current.delete(id);
@@ -209,7 +230,7 @@ function useInterceptedNavigation(handler) {
209
230
  }, { once: true });
210
231
  setTraversed(id);
211
232
  event.intercept({
212
- scroll: "manual",
233
+ scroll: keyless ? "after-transition" : "manual",
213
234
  focusReset: "manual",
214
235
  handler: () => promise
215
236
  });
@@ -223,10 +244,10 @@ function useInterceptedNavigation(handler) {
223
244
  const settled = () => {
224
245
  if (latest.current === id) setPendingPathname(null);
225
246
  };
226
- const scroll = inPlace && !traverse ? null : scrollPlanFor(event.navigationType, url.hash, leftAt.get(event.destination.key));
247
+ const scroll = inPlace && !traverse || keyless ? null : scrollPlanFor(event.navigationType, url.hash, leftAt.get(event.destination.key));
227
248
  event.intercept({
228
249
  ...inPlace ? { focusReset: "manual" } : {},
229
- scroll: "manual",
250
+ scroll: keyless ? "after-transition" : "manual",
230
251
  handler: async () => {
231
252
  event.signal.addEventListener("abort", settled, { once: true });
232
253
  let value;
@@ -241,7 +262,8 @@ function useInterceptedNavigation(handler) {
241
262
  pending.current.set(id, {
242
263
  resolve,
243
264
  scroll,
244
- types: inPlace ? [] : transitionTypesFor(event.navigationType)
265
+ types: inPlace ? [] : transitionTypesFor(event.navigationType),
266
+ keyless
245
267
  });
246
268
  event.signal.addEventListener("abort", () => {
247
269
  pending.current.delete(id);
@@ -255,15 +277,20 @@ function useInterceptedNavigation(handler) {
255
277
  });
256
278
  };
257
279
  navigation.addEventListener("navigate", onNavigate);
280
+ const onPopState = () => {
281
+ if (navigation.currentEntry === null) location.reload();
282
+ };
283
+ window.addEventListener("popstate", onPopState);
258
284
  return () => {
259
285
  navigation.removeEventListener("navigate", onNavigate);
286
+ window.removeEventListener("popstate", onPopState);
260
287
  };
261
288
  }, []);
262
289
  const settle = useEffectEvent((id) => {
263
290
  const entry = pending.current.get(id);
264
291
  if (entry === void 0) return;
265
292
  pending.current.delete(id);
266
- onScreenEntry.current = null;
293
+ onScreenEntry.current = entry.keyless ? "" : null;
267
294
  if (entry.scroll !== null) applyScroll(entry.scroll);
268
295
  if (latest.current === id) setPendingPathname(null);
269
296
  entry.resolve();
@@ -283,5 +310,4 @@ function useInterceptedNavigation(handler) {
283
310
  }, [applied, onScreen]);
284
311
  return { generation: onScreen };
285
312
  }
286
- //#endregion
287
313
  export { NavigationGeneration, isOurs, scrollPlanFor, transitionTypesFor, useInterceptedNavigation, usePendingPathname };
@@ -1,4 +1,3 @@
1
- //#region src/not-found.d.ts
2
1
  /**
3
2
  * Says, from a page, that its pathname is not a page after all — the
4
3
  * product the id names does not exist. Thrown, so the lines after it never
@@ -7,5 +6,4 @@
7
6
  */
8
7
  export declare function notFound(): never;
9
8
  /** Whether a thrown value is what `notFound()` throws. */
10
- export declare const isNotFound: (value: unknown) => boolean;
11
- //#endregion
9
+ export declare const isNotFound: (value: unknown) => boolean;
@@ -1,4 +1,4 @@
1
- //#region src/not-found.ts
1
+ // src/not-found.ts
2
2
  /**
3
3
  * Branded with a registry symbol rather than recognised by class: the page
4
4
  * that throws it and the framework that catches it may hold two copies of
@@ -24,5 +24,4 @@ function notFound() {
24
24
  }
25
25
  /** Whether a thrown value is what `notFound()` throws. */
26
26
  const isNotFound = (value) => typeof value === "object" && value !== null && value[BRAND] === true;
27
- //#endregion
28
27
  export { isNotFound, notFound };
package/dist/paths.d.mts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/paths.d.ts
2
1
  /**
3
2
  * The type half of the route table: everything here is derived from the
4
3
  * pattern strings by inference alone — no code generation. A pattern like
@@ -80,5 +79,4 @@ export declare const normalizePathname: (pathname: string) => string;
80
79
  /** What a param value may be on the way into a link: anything with one spelling. */
81
80
  export type ParamValue = string | number | bigint | boolean;
82
81
  export declare const buildHref: (pattern: string, params: Readonly<Record<string, unknown>> | undefined) => string;
83
- //#endregion
84
82
  export {};
package/dist/paths.mjs CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/paths.ts
1
+ // src/paths.ts
2
2
  const isGroupKey = (key) => /^\/\([^)]+\)$/u.test(key);
3
3
  const joinPattern = (prefix, key) => key === "/" || isGroupKey(key) ? prefix === "" ? "/" : prefix : `${prefix}${key}`;
4
4
  /**
@@ -22,5 +22,4 @@ const buildHref = (pattern, params) => {
22
22
  return encodeURIComponent(String(value));
23
23
  }).join("/");
24
24
  };
25
- //#endregion
26
25
  export { buildHref, isGroupKey, joinPattern, normalizePathname };
@@ -1,7 +1,6 @@
1
1
  import { ParamValue, ParamsOf } from "./paths.mjs";
2
2
  import { NavigablePatternOf, PatternOf, Routes, RoutesRecord } from "./define-routes.mjs";
3
3
  import { ReactNode } from "react";
4
- //#region src/register.d.ts
5
4
  /**
6
5
  * The app-side hook for the route table's type. An application augments this
7
6
  * once:
@@ -113,5 +112,4 @@ export type RouteContext<P extends RegisteredPattern> = {
113
112
  readonly request: Request;
114
113
  readonly params: RegisteredPageParams<P>;
115
114
  };
116
- //#endregion
117
115
  export {};
package/dist/router.d.mts CHANGED
@@ -2,7 +2,6 @@ import { ParamsOf } from "./paths.mjs";
2
2
  import { Match, Routes } from "./define-routes.mjs";
3
3
  import { RegisteredPattern } from "./register.mjs";
4
4
  import { FC, ReactNode } from "react";
5
- //#region src/router.d.ts
6
5
  /** Renders the next element of the matched stack — a layout's hole. */
7
6
  export declare const Outlet: FC;
8
7
  /**
@@ -34,5 +33,4 @@ export declare function useRoute(): Pick<Match, 'pattern' | 'params'>;
34
33
  * `<Router>` above it: under `@k8ordo/framework` a page receives `params` as
35
34
  * a prop, and a component below it reads them with `useMatch`.
36
35
  */
37
- export declare function useParams<P extends RegisteredPattern>(pattern: P): ParamsOf<P>;
38
- //#endregion
36
+ export declare function useParams<P extends RegisteredPattern>(pattern: P): ParamsOf<P>;
package/dist/router.mjs CHANGED
@@ -7,7 +7,7 @@ import { PathnameProvider, appPathname } from "./location.mjs";
7
7
  import { TreePathname } from "./tree-pathname.mjs";
8
8
  import { createContext, use, useDeferredValue, useMemo, useState } from "react";
9
9
  import { jsx } from "react/jsx-runtime";
10
- //#region src/router.tsx
10
+ // src/router.tsx
11
11
  const RouterContext = createContext(null);
12
12
  const StackContext = createContext(null);
13
13
  const RenderStack = ({ stack, index }) => {
@@ -110,5 +110,4 @@ function useParams(pattern) {
110
110
  if (current !== pattern) throw new Error(`useParams("${pattern}") rendered under "${current}"`);
111
111
  return params;
112
112
  }
113
- //#endregion
114
113
  export { Outlet, Router, useParams, useRoute };
@@ -1,4 +1,2 @@
1
1
  import { Context } from "react";
2
- //#region src/tree-pathname.d.ts
3
- export declare const TreePathname: Context<string | null>;
4
- //#endregion
2
+ export declare const TreePathname: Context<string | null>;
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { createContext } from "react";
3
- //#region src/tree-pathname.ts
3
+ // src/tree-pathname.ts
4
4
  /**
5
5
  * The pathname the tree a component renders in was applied for, normalized
6
6
  * and in the URL's terms (`withBase`'s, not the table's), or `null` where no
@@ -12,5 +12,4 @@ import { createContext } from "react";
12
12
  */
13
13
  const KEY = Symbol.for("@k8ordo/router/tree-pathname");
14
14
  const TreePathname = globalThis[KEY] ??= createContext(null);
15
- //#endregion
16
15
  export { TreePathname };
package/docs/GUIDE.md CHANGED
@@ -469,6 +469,15 @@ change called off while it loaded — starts at the top, or at its fragment,
469
469
  as a new page does. Only the document's scroll position comes back: an
470
470
  element scrolled inside the page and the pinch-zoom scale do not.
471
471
 
472
+ WebKit is the exception. In a document it loaded again on coming back from
473
+ another origin, it gives a traversal to an earlier entry no key, so the router
474
+ has no recorded position to look up and the browser restores it instead. If
475
+ the visitor scrolled the page still on screen while the next one loaded, the
476
+ browser does not restore it, and the page stays where they scrolled it. Coming
477
+ back from another site, WebKit does not report that traversal at all, so the
478
+ router reloads the page: the browser restores the position of a page rendered
479
+ on the server, and a page rendered on the client starts at the top.
480
+
472
481
  Any other state change never moves the viewport — same pathname, same
473
482
  place — so a filter update does not scroll the reader back to the top.
474
483
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/router",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "The pathname axis of the URL, owned. One route table derives the types, the matching, the links, and the navigation, over the Navigation API and URLPattern.",
5
5
  "keywords": [
6
6
  "navigation-api",
@@ -49,8 +49,8 @@
49
49
  "react": "19.3.1",
50
50
  "react-dom": "19.3.1",
51
51
  "typescript": "7.0.2",
52
- "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0",
53
- "vite-plus": "1.3.0",
52
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
53
+ "vite-plus": "1.4.0",
54
54
  "vitest": "5.0.5",
55
55
  "vitest-browser-react": "2.3.0"
56
56
  },