lit-navigation-router 0.4.0 → 0.5.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/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Fixed
6
+
7
+ - **Routes can match on `search` and `hash`**
8
+ ([#13](https://github.com/VanLandinghamLabs/lit-router/issues/13), inherited
9
+ from [lit/lit#3517](https://github.com/lit/lit/issues/3517)). Patterns were
10
+ executed as `exec({pathname})`, and `URLPattern` defaults every component the
11
+ caller omits to the empty string — so `new URLPattern({hash: 'one'})` was
12
+ compared against a hash of `''` and could never match. A hash- or
13
+ search-constrained route matched nothing at all, which made `goto()` throw
14
+ `No route found` on every load rather than merely failing to fire. Matching
15
+ now sees the whole location. Named groups captured from the search and hash
16
+ are merged into `params`; positional ones are not, since each component
17
+ numbers its groups from zero and a merged `"0"` would masquerade as a tail.
18
+ - **`goto()` is handed the search and hash.** `Router` called
19
+ `goto(window.location.pathname)` and `goto(url.pathname)`, so both were
20
+ discarded before matching ran. `goto()` now accepts and parses
21
+ `path?search#hash`, and passes them down to child controllers alongside the
22
+ tail.
23
+ - **Fragment-only navigation is routed when a route asks for it.** `Router`
24
+ declined every navigation with `hashChange` set, so a hash route could not be
25
+ reached by clicking a link even once matching was fixed. Such navigations are
26
+ now intercepted when — and only when — some route in the tree constrains the
27
+ hash, so pathname-only apps keep the browser's native in-page scrolling.
28
+
29
+ ### Changed
30
+
31
+ - `URLPatternLike` requires `hash`: the pattern string, which a real
32
+ `URLPattern` exposes and which is how `Router` decides whether a
33
+ fragment-only navigation is its business. Its `test()`/`exec()` take a
34
+ `{pathname, search, hash}` input, and `exec()` returns the `search` and
35
+ `hash` groups alongside the pathname's.
36
+
37
+ ### Documentation
38
+
39
+ - The `URLPatternRouteConfig` doc comment claimed patterns were "limited to
40
+ checking `pathname` and `search`". `search` never worked either; both now do.
41
+
3
42
  ## 0.4.0
4
43
 
5
44
  ### Fixed
package/README.md CHANGED
@@ -1,6 +1,9 @@
1
1
  # lit-navigation-router
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/lit-navigation-router)](https://www.npmjs.com/package/lit-navigation-router)
4
+
3
5
  A router for Lit, built on the [Navigation API](https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API).
6
+ Published on npm as [`lit-navigation-router`](https://www.npmjs.com/package/lit-navigation-router).
4
7
 
5
8
  Fork of [`@lit-labs/router`](https://github.com/lit/lit/tree/main/packages/labs/router)
6
9
  — see [NOTICE.md](./NOTICE.md) for provenance, licence and the full list of
@@ -85,6 +88,31 @@ children nor stripped from `link()`. A `fallback` behaves like a `/*` route and
85
88
  passes the whole pathname on as the tail. Nested, it accepts the slash-less
86
89
  tail it is handed and passes that on.
87
90
 
91
+ ## Search and hash routes
92
+
93
+ A `pattern` route can constrain `search` and `hash`, not just `pathname`:
94
+
95
+ ```ts
96
+ {pattern: new URLPattern({pathname: '/docs', hash: ':section'}),
97
+ render: ({section}) => html`<doc-page .section=${section}></doc-page>`}
98
+
99
+ {pattern: new URLPattern({pathname: '/search', search: 'q=:term'}),
100
+ render: ({term}) => html`<results-for .term=${term}></results-for>`}
101
+ ```
102
+
103
+ Named groups captured from the search and hash join the pathname's in `params`.
104
+ Positional ones do not: every component numbers its groups from zero
105
+ independently, so merging them would make a fragment indistinguishable from a
106
+ tail. Name the groups you need.
107
+
108
+ Only the pathname nests. A child controller is handed the parent's tail as its
109
+ pathname and the *same* search and hash — there is no way to split a query
110
+ string or a fragment across a route tree.
111
+
112
+ Fragment-only navigation (`<a href="#section">`) is intercepted **only** when
113
+ some route constrains the hash. An app that routes on pathnames alone keeps the
114
+ browser's native in-page scrolling.
115
+
88
116
  ## Browser support — please read
89
117
 
90
118
  This router **requires the Navigation API**. There is no legacy fallback.
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAqBnC,uEAAuE;AACvE,MAAM,WAAW,gBAAgB;IAC/B,UAAU,CAAC,EAAE,kBAAkB,GAAG,QAAQ,CAAC;IAC3C,MAAM,CAAC,EAAE,kBAAkB,GAAG,QAAQ,CAAC;CACxC;AAgBD;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,QAAO,OAEgB,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,qBAAa,MAAO,SAAQ,MAAM;IAChC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IAEpC,OAAO,CAAC,UAAU,CAAS;IAElB,aAAa;IAwBb,gBAAgB;IAQzB;;;OAGG;IACH,OAAO,CAAC,WAAW,CA6DjB;CACH"}
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAqBnC,uEAAuE;AACvE,MAAM,WAAW,gBAAgB;IAC/B,UAAU,CAAC,EAAE,kBAAkB,GAAG,QAAQ,CAAC;IAC3C,MAAM,CAAC,EAAE,kBAAkB,GAAG,QAAQ,CAAC;CACxC;AAyBD;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,QAAO,OAEgB,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,qBAAa,MAAO,SAAQ,MAAM;IAChC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IAEpC,OAAO,CAAC,UAAU,CAAS;IAElB,aAAa;IAwBb,gBAAgB;IAQzB;;;OAGG;IACH,OAAO,CAAC,WAAW,CAkEjB;CACH"}
@@ -8,6 +8,13 @@
8
8
  */
9
9
  import { Routes } from './routes.js';
10
10
  const getNavigation = () => window.navigation;
11
+ /**
12
+ * The current location as a path string, in the form `goto()` parses.
13
+ *
14
+ * Only the origin is dropped: this router matches within one origin, and
15
+ * `_onNavigate` declines anything else before it gets here.
16
+ */
17
+ const currentPath = () => window.location.pathname + window.location.search + window.location.hash;
11
18
  /**
12
19
  * True when the Navigation API is available — Baseline Newly Available since
13
20
  * January 2026 (Chrome/Edge, Safari 26.2, Firefox 147).
@@ -84,7 +91,7 @@ export class Router extends Routes {
84
91
  // Surfaced rather than left as a bare unhandled rejection, matching the
85
92
  // convention in routes.ts: on an engine without the API this is the *only*
86
93
  // rendering path, and a deep link with no matching route throws here.
87
- void this.goto(window.location.pathname).catch((err) => {
94
+ void this.goto(currentPath()).catch((err) => {
88
95
  queueMicrotask(() => {
89
96
  throw err;
90
97
  });
@@ -103,15 +110,20 @@ export class Router extends Routes {
103
110
  */
104
111
  _onNavigate = (e) => {
105
112
  // Not ours to handle: anything the browser says cannot be intercepted,
106
- // fragment-only moves, downloads, and POST form submissions.
113
+ // downloads, and POST form submissions.
107
114
  //
108
115
  // `!= null`, not `!== null`: the spec types both as nullable-but-present,
109
116
  // but a polyfill that leaves either unset would make a strict check true
110
117
  // for every ordinary link and silently decline the whole app.
111
- if (!e.canIntercept ||
112
- e.hashChange ||
113
- e.downloadRequest != null ||
114
- e.formData != null) {
118
+ if (!e.canIntercept || e.downloadRequest != null || e.formData != null) {
119
+ return;
120
+ }
121
+ // Fragment-only moves belong to the browser unless a route actually reads
122
+ // the fragment. Intercepting them unconditionally would cost every
123
+ // pathname-only app its native in-page scrolling — and re-render the same
124
+ // route to no effect — while declining them unconditionally is the
125
+ // lit/lit#3517 bug this router inherited.
126
+ if (e.hashChange && !this._constrainsHash()) {
115
127
  return;
116
128
  }
117
129
  // Reloads must stay reloads. `canIntercept` is true for them, so without
@@ -144,7 +156,8 @@ export class Router extends Routes {
144
156
  // throws "No route found", and the address bar is left pointing somewhere
145
157
  // the outlet never went. Declining lets the browser do the real
146
158
  // navigation, which is the correct outcome.
147
- if (!this.hasRouteFor(url.pathname)) {
159
+ const path = url.pathname + url.search + url.hash;
160
+ if (!this.hasRouteFor(path)) {
148
161
  return;
149
162
  }
150
163
  e.intercept({
@@ -152,7 +165,7 @@ export class Router extends Routes {
152
165
  handler: async () => {
153
166
  // `e.signal` aborts if another navigation starts before this handler
154
167
  // resolves; goto() checks it after `enter()` and stands down.
155
- await this.goto(url.pathname, { signal: e.signal });
168
+ await this.goto(path, { signal: e.signal });
156
169
  },
157
170
  });
158
171
  };
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAsCnC,MAAM,aAAa,GAAG,GAA+B,EAAE,CACpD,MAAmD,CAAC,UAAU,CAAC;AAElE;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAY,EAAE,CACjD,OAAO,MAAM,KAAK,WAAW;IAC7B,OAAO,aAAa,EAAE,EAAE,gBAAgB,KAAK,UAAU,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,MAAM,OAAO,MAAO,SAAQ,MAAM;IAChC;;;OAGG;IACH,gBAAgB,CAAoB;IAE5B,UAAU,GAAG,KAAK,CAAC;IAElB,aAAa;QACpB,KAAK,CAAC,aAAa,EAAE,CAAC;QACtB,sEAAsE;QACtE,uEAAuE;QACvE,wEAAwE;QACxE,2EAA2E;QAC3E,iBAAiB;QACjB,IAAI,qBAAqB,EAAE,EAAE,CAAC;YAC5B,aAAa,EAAG,CAAC,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;YAChE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACzB,CAAC;QACD,2EAA2E;QAC3E,yEAAyE;QACzE,uEAAuE;QACvE,wEAAwE;QACxE,2EAA2E;QAC3E,sEAAsE;QACtE,K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C,CAAC;QACvC,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;YAC1C,OAAO;QACT,CAAC;QAED,yEAAyE;QACzE,yEAAyE;QACzE,oEAAoE;QACpE,qEAAqE;QACrE,0EAA0E;QAC1E,gEAAgE;QAChE,4CAA4C;QAC5C,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACpC,OAAO;QACT,CAAC;QAED,CAAC,CAAC,SAAS,CAAC;YACV,GAAG,IAAI,CAAC,gBAAgB;YACxB,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,qEAAqE;gBACrE,8DAA8D;gBAC9D,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAC,CAAC,CAAC;YACpD,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;CACH","sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Modifications Copyright 2026 VanLandingham Labs, same license.\n * Rebuilt on the Navigation API; see NOTICE.md.\n */\n\nimport {Routes} from './routes.js';\n\n/**\n * The slice of `NavigateEvent` this router reads. Declared locally rather than\n * typing the handler `any`: these properties *are* the correctness boundary, so\n * a typo like `hashchange` for `hashChange` would silently disable a filter\n * forever. Names verified against Chromium's `NavigateEvent.prototype`.\n */\ninterface NavigateEventLike {\n readonly canIntercept: boolean;\n readonly hashChange: boolean;\n readonly downloadRequest: string | null;\n readonly formData: FormData | null;\n readonly navigationType: 'push' | 'replace' | 'reload' | 'traverse';\n readonly signal: AbortSignal;\n readonly destination: {readonly url: string};\n /** Not in every engine yet; used only as a best-effort `rel` check. */\n readonly sourceElement?: Element | null;\n intercept(options: InterceptOptions & {handler?: () => Promise<void>}): void;\n}\n\n/** The subset of `NavigationInterceptOptions` this router forwards. */\nexport interface InterceptOptions {\n focusReset?: 'after-transition' | 'manual';\n scroll?: 'after-transition' | 'manual';\n}\n\ninterface NavigationLike {\n addEventListener(\n type: 'navigate',\n listener: (e: NavigateEventLike) => void\n ): void;\n removeEventListener(\n type: 'navigate',\n listener: (e: NavigateEventLike) => void\n ): void;\n}\n\nconst getNavigation = (): NavigationLike | undefined =>\n (window as unknown as {navigation?: NavigationLike}).navigation;\n\n/**\n * True when the Navigation API is available — Baseline Newly Available since\n * January 2026 (Chrome/Edge, Safari 26.2, Firefox 147).\n *\n * This router **requires** it. Exported so an app can detect an unsupported\n * engine at boot and say so, rather than leaving the user to notice that every\n * link reloads the page.\n */\nexport const supportsNavigationApi = (): boolean =>\n typeof window !== 'undefined' &&\n typeof getNavigation()?.addEventListener === 'function';\n\n/**\n * A root-level router that intercepts navigation via the Navigation API.\n *\n * This class extends Routes so that it can also have a route configuration.\n *\n * There should only be one Router instance on a page, since the Router\n * installs a global listener. Nested routes should be configured with the\n * `Routes` class.\n *\n * ## Why the Navigation API\n *\n * Upstream intercepted navigation with a global click listener plus `popstate`\n * and committed with `history.pushState()`. That is structurally racy:\n * `pushState` is synchronous and `popstate` fires *after* the URL has already\n * moved, but `goto()` awaits `route.enter()` before swapping the outlet. The\n * URL leads and the outlet lags, leaving two sources of truth — the outgoing\n * route re-renders with stale params, and two quick navigations commit in\n * whatever order their `enter()` hooks happen to resolve.\n *\n * `navigateEvent.intercept({handler})` collapses that. The browser commits the\n * URL and holds the navigation un-finished while the handler runs, and it\n * aborts `navigateEvent.signal` when a newer navigation supersedes this one —\n * which `goto()` honours, so a superseded route can no longer win the outlet.\n *\n * ## No legacy fallback\n *\n * An earlier version of this fork kept upstream's click/popstate path for\n * pre-2026 engines. It was removed deliberately. Ten review rounds found\n * divergences between the two paths and **every one was in the click handler**,\n * never in this one — which is structural, not luck: this handler reads a\n * decision the browser has already made, while the click handler had to\n * re-derive it, re-implementing the rules for choosing a navigable, the\n * fragment-navigation predicate, and the modifier-key rules. Each round found\n * another place where the re-implementation and the spec disagreed.\n *\n * On an engine without the API, links fall back to ordinary full page loads.\n * For an app whose server serves the shell on every route that still works —\n * it is slower, not broken — and `supportsNavigationApi()` lets you detect it.\n * If real pre-2026 support is ever needed, use a Navigation API polyfill: one\n * decision path, with compatibility isolated in a layer whose whole job is\n * spec accuracy.\n */\nexport class Router extends Routes {\n /**\n * Options forwarded to `navigateEvent.intercept()`. Leaving these unset\n * gives the browser's default scroll and focus handling.\n */\n interceptOptions?: InterceptOptions;\n\n private _listening = false;\n\n override hostConnected() {\n super.hostConnected();\n // Gated on the exported predicate, not on `navigation !== undefined`:\n // a stub or partial polyfill under that name would otherwise make this\n // branch throw out of connectedCallback while `supportsNavigationApi()`\n // told the app it was unsupported — and then even the initial render below\n // would not run.\n if (supportsNavigationApi()) {\n getNavigation()!.addEventListener('navigate', this._onNavigate);\n this._listening = true;\n }\n // Kick off routed rendering by going to the current URL. Done even without\n // the API: a full page load still renders the right route, which is what\n // makes the unsupported-engine degradation \"slow\" rather than \"blank\".\n // Surfaced rather than left as a bare unhandled rejection, matching the\n // convention in routes.ts: on an engine without the API this is the *only*\n // rendering path, and a deep link with no matching route throws here.\n void this.goto(window.location.pathname).catch((err) => {\n queueMicrotask(() => {\n throw err;\n });\n });\n }\n\n override hostDisconnected() {\n super.hostDisconnected();\n if (this._listening) {\n getNavigation()?.removeEventListener('navigate', this._onNavigate);\n this._listening = false;\n }\n }\n\n /**\n * Handles same-document navigation from every source at once: anchor clicks,\n * `navigation.navigate()`, `history.pushState()`, and back/forward.\n */\n private _onNavigate = (e: NavigateEventLike) => {\n // Not ours to handle: anything the browser says cannot be intercepted,\n // fragment-only moves, downloads, and POST form submissions.\n //\n // `!= null`, not `!== null`: the spec types both as nullable-but-present,\n // but a polyfill that leaves either unset would make a strict check true\n // for every ordinary link and silently decline the whole app.\n if (\n !e.canIntercept ||\n e.hashChange ||\n e.downloadRequest != null ||\n e.formData != null\n ) {\n return;\n }\n\n // Reloads must stay reloads. `canIntercept` is true for them, so without\n // this `location.reload()` silently degrades to re-running goto() on the\n // same path — the document is never replaced, breaking the standard\n // \"new version available, reload\" escape hatch. (It would also disagree\n // with the browser's own refresh button, which is not interceptable.)\n if (e.navigationType === 'reload') {\n return;\n }\n\n // `rel=\"external\"` is a convention this router honours — it is not defined\n // by HTML or by the Navigation API, so the browser will not decline these\n // for us. Best-effort: `sourceElement` is not in every engine, and is\n // absent for programmatic navigation.\n if (e.sourceElement?.getAttribute?.('rel') === 'external') {\n return;\n }\n\n // Read per navigation rather than cached at module scope: the value cannot\n // change, but reading it on import makes merely importing this module throw\n // where there is no `location` (SSR, a bundler evaluating for tree-shaking\n // under the package's `sideEffects: false` claim).\n const url = new URL(e.destination.url);\n if (url.origin !== window.location.origin) {\n return;\n }\n\n // Only intercept what we can actually render. `canIntercept` is true for\n // any same-origin URL, including cross-document ones — so without this a\n // link to a server-rendered page, an export endpoint, or a GET form\n // (whose `formData` is null) gets swallowed: the URL commits, goto()\n // throws \"No route found\", and the address bar is left pointing somewhere\n // the outlet never went. Declining lets the browser do the real\n // navigation, which is the correct outcome.\n if (!this.hasRouteFor(url.pathname)) {\n return;\n }\n\n e.intercept({\n ...this.interceptOptions,\n handler: async () => {\n // `e.signal` aborts if another navigation starts before this handler\n // resolves; goto() checks it after `enter()` and stands down.\n await this.goto(url.pathname, {signal: e.signal});\n },\n });\n };\n}\n"]}
1
+ {"version":3,"file":"router.js","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAsCnC,MAAM,aAAa,GAAG,GAA+B,EAAE,CACpD,MAAmD,CAAC,UAAU,CAAC;AAElE;;;;;GAKG;AACH,MAAM,WAAW,GAAG,GAAW,EAAE,CAC/B,MAAM,CAAC,QAAQ,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;AAE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AAO;QACT,CAAC;QAED,CAAC,CAAC,SAAS,CAAC;YACV,GAAG,IAAI,CAAC,gBAAgB;YACxB,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,qEAAqE;gBACrE,8DAA8D;gBAC9D,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,EAAC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAC,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;CACH","sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Modifications Copyright 2026 VanLandingham Labs, same license.\n * Rebuilt on the Navigation API; see NOTICE.md.\n */\n\nimport {Routes} from './routes.js';\n\n/**\n * The slice of `NavigateEvent` this router reads. Declared locally rather than\n * typing the handler `any`: these properties *are* the correctness boundary, so\n * a typo like `hashchange` for `hashChange` would silently disable a filter\n * forever. Names verified against Chromium's `NavigateEvent.prototype`.\n */\ninterface NavigateEventLike {\n readonly canIntercept: boolean;\n readonly hashChange: boolean;\n readonly downloadRequest: string | null;\n readonly formData: FormData | null;\n readonly navigationType: 'push' | 'replace' | 'reload' | 'traverse';\n readonly signal: AbortSignal;\n readonly destination: {readonly url: string};\n /** Not in every engine yet; used only as a best-effort `rel` check. */\n readonly sourceElement?: Element | null;\n intercept(options: InterceptOptions & {handler?: () => Promise<void>}): void;\n}\n\n/** The subset of `NavigationInterceptOptions` this router forwards. */\nexport interface InterceptOptions {\n focusReset?: 'after-transition' | 'manual';\n scroll?: 'after-transition' | 'manual';\n}\n\ninterface NavigationLike {\n addEventListener(\n type: 'navigate',\n listener: (e: NavigateEventLike) => void\n ): void;\n removeEventListener(\n type: 'navigate',\n listener: (e: NavigateEventLike) => void\n ): void;\n}\n\nconst getNavigation = (): NavigationLike | undefined =>\n (window as unknown as {navigation?: NavigationLike}).navigation;\n\n/**\n * The current location as a path string, in the form `goto()` parses.\n *\n * Only the origin is dropped: this router matches within one origin, and\n * `_onNavigate` declines anything else before it gets here.\n */\nconst currentPath = (): string =>\n window.location.pathname + window.location.search + window.location.hash;\n\n/**\n * True when the Navigation API is available — Baseline Newly Available since\n * January 2026 (Chrome/Edge, Safari 26.2, Firefox 147).\n *\n * This router **requires** it. Exported so an app can detect an unsupported\n * engine at boot and say so, rather than leaving the user to notice that every\n * link reloads the page.\n */\nexport const supportsNavigationApi = (): boolean =>\n typeof window !== 'undefined' &&\n typeof getNavigation()?.addEventListener === 'function';\n\n/**\n * A root-level router that intercepts navigation via the Navigation API.\n *\n * This class extends Routes so that it can also have a route configuration.\n *\n * There should only be one Router instance on a page, since the Router\n * installs a global listener. Nested routes should be configured with the\n * `Routes` class.\n *\n * ## Why the Navigation API\n *\n * Upstream intercepted navigation with a global click listener plus `popstate`\n * and committed with `history.pushState()`. That is structurally racy:\n * `pushState` is synchronous and `popstate` fires *after* the URL has already\n * moved, but `goto()` awaits `route.enter()` before swapping the outlet. The\n * URL leads and the outlet lags, leaving two sources of truth — the outgoing\n * route re-renders with stale params, and two quick navigations commit in\n * whatever order their `enter()` hooks happen to resolve.\n *\n * `navigateEvent.intercept({handler})` collapses that. The browser commits the\n * URL and holds the navigation un-finished while the handler runs, and it\n * aborts `navigateEvent.signal` when a newer navigation supersedes this one —\n * which `goto()` honours, so a superseded route can no longer win the outlet.\n *\n * ## No legacy fallback\n *\n * An earlier version of this fork kept upstream's click/popstate path for\n * pre-2026 engines. It was removed deliberately. Ten review rounds found\n * divergences between the two paths and **every one was in the click handler**,\n * never in this one — which is structural, not luck: this handler reads a\n * decision the browser has already made, while the click handler had to\n * re-derive it, re-implementing the rules for choosing a navigable, the\n * fragment-navigation predicate, and the modifier-key rules. Each round found\n * another place where the re-implementation and the spec disagreed.\n *\n * On an engine without the API, links fall back to ordinary full page loads.\n * For an app whose server serves the shell on every route that still works —\n * it is slower, not broken — and `supportsNavigationApi()` lets you detect it.\n * If real pre-2026 support is ever needed, use a Navigation API polyfill: one\n * decision path, with compatibility isolated in a layer whose whole job is\n * spec accuracy.\n */\nexport class Router extends Routes {\n /**\n * Options forwarded to `navigateEvent.intercept()`. Leaving these unset\n * gives the browser's default scroll and focus handling.\n */\n interceptOptions?: InterceptOptions;\n\n private _listening = false;\n\n override hostConnected() {\n super.hostConnected();\n // Gated on the exported predicate, not on `navigation !== undefined`:\n // a stub or partial polyfill under that name would otherwise make this\n // branch throw out of connectedCallback while `supportsNavigationApi()`\n // told the app it was unsupported — and then even the initial render below\n // would not run.\n if (supportsNavigationApi()) {\n getNavigation()!.addEventListener('navigate', this._onNavigate);\n this._listening = true;\n }\n // Kick off routed rendering by going to the current URL. Done even without\n // the API: a full page load still renders the right route, which is what\n // makes the unsupported-engine degradation \"slow\" rather than \"blank\".\n // Surfaced rather than left as a bare unhandled rejection, matching the\n // convention in routes.ts: on an engine without the API this is the *only*\n // rendering path, and a deep link with no matching route throws here.\n void this.goto(currentPath()).catch((err) => {\n queueMicrotask(() => {\n throw err;\n });\n });\n }\n\n override hostDisconnected() {\n super.hostDisconnected();\n if (this._listening) {\n getNavigation()?.removeEventListener('navigate', this._onNavigate);\n this._listening = false;\n }\n }\n\n /**\n * Handles same-document navigation from every source at once: anchor clicks,\n * `navigation.navigate()`, `history.pushState()`, and back/forward.\n */\n private _onNavigate = (e: NavigateEventLike) => {\n // Not ours to handle: anything the browser says cannot be intercepted,\n // downloads, and POST form submissions.\n //\n // `!= null`, not `!== null`: the spec types both as nullable-but-present,\n // but a polyfill that leaves either unset would make a strict check true\n // for every ordinary link and silently decline the whole app.\n if (!e.canIntercept || e.downloadRequest != null || e.formData != null) {\n return;\n }\n\n // Fragment-only moves belong to the browser unless a route actually reads\n // the fragment. Intercepting them unconditionally would cost every\n // pathname-only app its native in-page scrolling — and re-render the same\n // route to no effect — while declining them unconditionally is the\n // lit/lit#3517 bug this router inherited.\n if (e.hashChange && !this._constrainsHash()) {\n return;\n }\n\n // Reloads must stay reloads. `canIntercept` is true for them, so without\n // this `location.reload()` silently degrades to re-running goto() on the\n // same path — the document is never replaced, breaking the standard\n // \"new version available, reload\" escape hatch. (It would also disagree\n // with the browser's own refresh button, which is not interceptable.)\n if (e.navigationType === 'reload') {\n return;\n }\n\n // `rel=\"external\"` is a convention this router honours — it is not defined\n // by HTML or by the Navigation API, so the browser will not decline these\n // for us. Best-effort: `sourceElement` is not in every engine, and is\n // absent for programmatic navigation.\n if (e.sourceElement?.getAttribute?.('rel') === 'external') {\n return;\n }\n\n // Read per navigation rather than cached at module scope: the value cannot\n // change, but reading it on import makes merely importing this module throw\n // where there is no `location` (SSR, a bundler evaluating for tree-shaking\n // under the package's `sideEffects: false` claim).\n const url = new URL(e.destination.url);\n if (url.origin !== window.location.origin) {\n return;\n }\n\n // Only intercept what we can actually render. `canIntercept` is true for\n // any same-origin URL, including cross-document ones — so without this a\n // link to a server-rendered page, an export endpoint, or a GET form\n // (whose `formData` is null) gets swallowed: the URL commits, goto()\n // throws \"No route found\", and the address bar is left pointing somewhere\n // the outlet never went. Declining lets the browser do the real\n // navigation, which is the correct outcome.\n const path = url.pathname + url.search + url.hash;\n if (!this.hasRouteFor(path)) {\n return;\n }\n\n e.intercept({\n ...this.interceptOptions,\n handler: async () => {\n // `e.signal` aborts if another navigation starts before this handler\n // resolves; goto() checks it after `enter()` and stands down.\n await this.goto(path, {signal: e.signal});\n },\n });\n };\n}\n"]}
@@ -27,8 +27,8 @@ export interface PathRouteConfig extends BaseRouteConfig {
27
27
  *
28
28
  * While `URLPattern` can match against protocols, hostnames, and ports,
29
29
  * routes will only be checked for matches if they're part of the current
30
- * origin. This means that the pattern is limited to checking `pathname` and
31
- * `search`.
30
+ * origin. This means the pattern is limited to checking `pathname`, `search`
31
+ * and `hash`.
32
32
  */
33
33
  export interface URLPatternRouteConfig extends BaseRouteConfig {
34
34
  pattern: URLPatternLike;
@@ -50,19 +50,46 @@ export interface URLPatternLike {
50
50
  * the groups object alone cannot (see `tailOf`).
51
51
  */
52
52
  readonly pathname: string;
53
- test(input: {
54
- pathname: string;
55
- }): boolean;
56
- exec(input: {
57
- pathname: string;
58
- }): {
53
+ /**
54
+ * The hash pattern string. `'*'` means the route places no constraint on the
55
+ * fragment, which is what `URLPattern` fills in for any component the caller
56
+ * omits. `Router` reads this to decide whether a fragment-only navigation is
57
+ * its business or the browser's.
58
+ */
59
+ readonly hash: string;
60
+ test(input: RouteLocation): boolean;
61
+ exec(input: RouteLocation): {
59
62
  pathname: {
60
63
  groups: {
61
64
  [key: string]: string | undefined;
62
65
  };
63
66
  };
67
+ search: {
68
+ groups: {
69
+ [key: string]: string | undefined;
70
+ };
71
+ };
72
+ hash: {
73
+ groups: {
74
+ [key: string]: string | undefined;
75
+ };
76
+ };
64
77
  } | null;
65
78
  }
79
+ /**
80
+ * The parts of a location this router matches against, split out of a path
81
+ * string by `parseLocation`.
82
+ *
83
+ * `search` and `hash` carry no leading `?` or `#`. `URLPattern` canonicalises
84
+ * either form away on an init input, but only for a real `URLPattern` — the
85
+ * structural `URLPatternLike` above admits other implementations, so the
86
+ * delimiters are stripped here rather than left to the pattern.
87
+ */
88
+ export interface RouteLocation {
89
+ pathname: string;
90
+ search: string;
91
+ hash: string;
92
+ }
66
93
  /**
67
94
  * A description of a route, which path or pattern to match against, and a
68
95
  * render() callback used to render a match to the outlet.
@@ -89,6 +116,15 @@ export declare class Routes implements ReactiveController {
89
116
  private _gotoSeq;
90
117
  private _currentPathname;
91
118
  private _currentTail;
119
+ /**
120
+ * The search and hash of the current location.
121
+ *
122
+ * Ambient rather than tailed: only the pathname nests, so a child controller
123
+ * is handed the parent's tail as its pathname but the *same* search and
124
+ * hash. There is no meaningful way to split a fragment across a route tree.
125
+ */
126
+ private _currentSearch;
127
+ private _currentHash;
92
128
  private _currentRoute;
93
129
  private _currentParams;
94
130
  /**
@@ -119,7 +155,7 @@ export declare class Routes implements ReactiveController {
119
155
  * and the outlet ends up on a route the URL has already left. `Router`
120
156
  * threads `NavigateEvent.signal` through for exactly this reason.
121
157
  */
122
- goto(pathname: string, options?: {
158
+ goto(path: string, options?: {
123
159
  signal?: AbortSignal;
124
160
  }): Promise<void>;
125
161
  /**
@@ -161,7 +197,21 @@ export declare class Routes implements ReactiveController {
161
197
  */
162
198
  private _supersede;
163
199
  /**
164
- * True when this controller can render `pathname` — i.e. a route matches, or
200
+ * True when this controller, or any controller below it, has a route that
201
+ * constrains the hash.
202
+ *
203
+ * `Router` gates interception of fragment-only navigation on this. Left
204
+ * ungated, a pathname-only app would have every in-page anchor swallowed and
205
+ * re-rendered instead of scrolled; gated, such an app behaves exactly as it
206
+ * did before hash routes existed.
207
+ *
208
+ * Walks children because a nested controller may route on the hash while the
209
+ * top-level `Router` does not — and only the top-level one sees the
210
+ * navigate event.
211
+ */
212
+ protected _constrainsHash(seen?: Set<Routes>): boolean;
213
+ /**
214
+ * True when this controller can render `path` — i.e. a route matches, or
165
215
  * a fallback is configured.
166
216
  *
167
217
  * `Router` gates interception on this: intercepting a path we cannot render
@@ -169,7 +219,7 @@ export declare class Routes implements ReactiveController {
169
219
  * moved and the outlet stale. Letting the browser handle it instead means a
170
220
  * server-rendered page, an export endpoint, or a GET form still works.
171
221
  */
172
- hasRouteFor(pathname: string): boolean;
222
+ hasRouteFor(path: string): boolean;
173
223
  /**
174
224
  * Matches `pathname` against the installed routes and returns the first match
175
225
  * with its parsed parameters, or the fallback's match if one is configured.
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,KAAK,EAAC,kBAAkB,EAAE,sBAAsB,EAAC,MAAM,KAAK,CAAC;AAEpE,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;KAAC,KAAK,OAAO,CAAC;IAClE,KAAK,CAAC,EAAE,CAAC,MAA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AC,WAAW;IAoBnB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAqBlB;;;;;;;;;;;;OAYG;IACH,SAAS,CAAC,eAAe,CAAC,IAAI,GAAE,GAAG,CAAC,MAAM,CAAa,GAAG,OAAO;IAYjE;;;;;;;;OAQG;IACH,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAclC;;;;;;;OAOG;IACH,OAAO,CAAC,MAAM;IAyCd,aAAa;IAUb,gBAAgB;IAkBhB,OAAO,CAAC,kBAAkB,CAwBxB;CACH;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,MAAM,CAAC,QAAQ,CAAC,SAAS,0BAA0B;IACnD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;gBAEd,MAAM,EAAE,MAAM;CAQ3B;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,mBAAmB;QAC3B,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE,oBAAoB,CAAC;KACxD;CACF"}
@@ -5,6 +5,26 @@
5
5
  *
6
6
  * Modifications Copyright 2026 VanLandingham Labs, same license. See NOTICE.md.
7
7
  */
8
+ /**
9
+ * Splits `path` into the components a pattern is matched against.
10
+ *
11
+ * Deliberately not `new URL(path, origin)`: a nested controller's path is a
12
+ * *tail* — a bare relative segment like `abc` — which `URL` would resolve
13
+ * against the current directory and mangle.
14
+ */
15
+ const parseLocation = (path) => {
16
+ const hashIndex = path.indexOf('#');
17
+ const hash = hashIndex === -1 ? '' : path.slice(hashIndex + 1);
18
+ const beforeHash = hashIndex === -1 ? path : path.slice(0, hashIndex);
19
+ const searchIndex = beforeHash.indexOf('?');
20
+ return {
21
+ pathname: searchIndex === -1 ? beforeHash : beforeHash.slice(0, searchIndex),
22
+ search: searchIndex === -1 ? '' : beforeHash.slice(searchIndex + 1),
23
+ hash,
24
+ };
25
+ };
26
+ /** Re-attaches `search` and `hash` to a pathname. Inverse of `parseLocation`. */
27
+ const formatLocation = (pathname, { search, hash }) => pathname + (search === '' ? '' : `?${search}`) + (hash === '' ? '' : `#${hash}`);
8
28
  // A cache of URLPatterns created for PathRouteConfig.
9
29
  // Rather than converting all given RoutConfigs to URLPatternRouteConfig, this
10
30
  // lets us make `routes` mutable so users can add new PathRouteConfigs
@@ -105,6 +125,15 @@ export class Routes {
105
125
  _gotoSeq = 0;
106
126
  _currentPathname;
107
127
  _currentTail;
128
+ /**
129
+ * The search and hash of the current location.
130
+ *
131
+ * Ambient rather than tailed: only the pathname nests, so a child controller
132
+ * is handed the parent's tail as its pathname but the *same* search and
133
+ * hash. There is no meaningful way to split a fragment across a route tree.
134
+ */
135
+ _currentSearch = '';
136
+ _currentHash = '';
108
137
  _currentRoute;
109
138
  _currentParams = {};
110
139
  /**
@@ -148,12 +177,10 @@ export class Routes {
148
177
  * and the outlet ends up on a route the URL has already left. `Router`
149
178
  * threads `NavigateEvent.signal` through for exactly this reason.
150
179
  */
151
- async goto(pathname, options) {
180
+ async goto(path, options) {
152
181
  // TODO (justinfagnani): handle absolute vs relative paths separately.
153
- // TODO (justinfagnani): generalize this to handle query params and
154
- // fragments. It currently only handles path names because it's easier to
155
- // completely disregard the origin for now. The click handler only does
156
- // an in-page navigation if the origin matches anyway.
182
+ const location = parseLocation(path);
183
+ const { pathname } = location;
157
184
  // Last-goto-wins, per controller. The navigation signal alone is not
158
185
  // enough: a child controller mounts as a *result* of its parent's render,
159
186
  // so its first goto() comes from `_onRoutesConnected` — after the parent's
@@ -173,9 +200,9 @@ export class Routes {
173
200
  this._currentParams = { 0: tail };
174
201
  }
175
202
  else {
176
- const match = this._match(pathname);
203
+ const match = this._match(location);
177
204
  if (match === undefined) {
178
- throw new Error(`No route found for ${pathname}`);
205
+ throw new Error(`No route found for ${path}`);
179
206
  }
180
207
  const { route, params } = match;
181
208
  tail = match.tail;
@@ -200,6 +227,8 @@ export class Routes {
200
227
  : pathname.substring(0, pathname.length - tail.length);
201
228
  }
202
229
  this._currentTail = tail;
230
+ this._currentSearch = location.search;
231
+ this._currentHash = location.hash;
203
232
  // Propagate the tail match to children — deliberately NOT awaited.
204
233
  //
205
234
  // Awaiting looks like it would make `navigation.finished` cover the whole
@@ -258,11 +287,19 @@ export class Routes {
258
287
  * replacement. Supersession is the counter's job.
259
288
  */
260
289
  _routeChild(child, tail) {
261
- if (tail === undefined || !child.hasRouteFor(tail)) {
290
+ if (tail === undefined) {
262
291
  child._supersede();
263
292
  return;
264
293
  }
265
- void child.goto(tail).catch((err) => {
294
+ const childPath = formatLocation(tail, {
295
+ search: this._currentSearch,
296
+ hash: this._currentHash,
297
+ });
298
+ if (!child.hasRouteFor(childPath)) {
299
+ child._supersede();
300
+ return;
301
+ }
302
+ void child.goto(childPath).catch((err) => {
266
303
  queueMicrotask(() => {
267
304
  throw err;
268
305
  });
@@ -293,7 +330,29 @@ export class Routes {
293
330
  }
294
331
  }
295
332
  /**
296
- * True when this controller can render `pathname` — i.e. a route matches, or
333
+ * True when this controller, or any controller below it, has a route that
334
+ * constrains the hash.
335
+ *
336
+ * `Router` gates interception of fragment-only navigation on this. Left
337
+ * ungated, a pathname-only app would have every in-page anchor swallowed and
338
+ * re-rendered instead of scrolled; gated, such an app behaves exactly as it
339
+ * did before hash routes existed.
340
+ *
341
+ * Walks children because a nested controller may route on the hash while the
342
+ * top-level `Router` does not — and only the top-level one sees the
343
+ * navigate event.
344
+ */
345
+ _constrainsHash(seen = new Set()) {
346
+ // Cycle guard, matching `_supersede`; see the note there.
347
+ if (seen.has(this)) {
348
+ return false;
349
+ }
350
+ seen.add(this);
351
+ return (this.routes.some((r) => getPattern(r).hash !== '*') ||
352
+ this._childRoutes.some((c) => c._constrainsHash(seen)));
353
+ }
354
+ /**
355
+ * True when this controller can render `path` — i.e. a route matches, or
297
356
  * a fallback is configured.
298
357
  *
299
358
  * `Router` gates interception on this: intercepting a path we cannot render
@@ -301,7 +360,7 @@ export class Routes {
301
360
  * moved and the outlet stale. Letting the browser handle it instead means a
302
361
  * server-rendered page, an export endpoint, or a GET form still works.
303
362
  */
304
- hasRouteFor(pathname) {
363
+ hasRouteFor(path) {
305
364
  // A fallback matches everything, and a controller with no routes of its own
306
365
  // behaves as if it had a single `/*` route (goto()'s special case). Either
307
366
  // way the answer is yes without running a single pattern — worth
@@ -311,7 +370,8 @@ export class Routes {
311
370
  }
312
371
  // `test()`, not `_match()`: this only needs the yes/no, and `exec()` pays
313
372
  // ~8x on a hit to build a groups object the caller would throw away.
314
- return this.routes.some((r) => getPattern(r).test({ pathname }));
373
+ const location = parseLocation(path);
374
+ return this.routes.some((r) => getPattern(r).test(location));
315
375
  }
316
376
  /**
317
377
  * Matches `pathname` against the installed routes and returns the first match
@@ -321,12 +381,25 @@ export class Routes {
321
381
  * extract: that ran the winning pattern twice, and every caller that wants a
322
382
  * route wants its params too.
323
383
  */
324
- _match(pathname) {
384
+ _match(location) {
325
385
  for (const route of this.routes) {
326
- const result = getPattern(route).exec({ pathname });
386
+ const result = getPattern(route).exec(location);
327
387
  if (result !== null) {
328
- const params = result.pathname.groups;
329
- return { route, params, tail: tailOf(route, params) };
388
+ const params = {
389
+ ...result.pathname.groups,
390
+ };
391
+ // Named groups only. A positional group is keyed by index in every
392
+ // component independently, so `/child/*` with a hash of `*` yields a
393
+ // "0" in both — and `tailOf` picks the tail by highest numeric key.
394
+ // Merging them would let a fragment masquerade as the tail.
395
+ for (const groups of [result.search.groups, result.hash.groups]) {
396
+ for (const [key, value] of Object.entries(groups)) {
397
+ if (!/^\d+$/.test(key)) {
398
+ params[key] = value;
399
+ }
400
+ }
401
+ }
402
+ return { route, params, tail: tailOf(route, result.pathname.groups) };
330
403
  }
331
404
  }
332
405
  if (this.fallback === undefined) {
@@ -338,6 +411,7 @@ export class Routes {
338
411
  // nested controller is handed its tail *without* a leading slash, which
339
412
  // `/*` does not match, so a nested fallback matched nothing — empty
340
413
  // params, no tail, and its own children never routed.
414
+ const { pathname } = location;
341
415
  const tail = pathname.startsWith('/') ? pathname.slice(1) : pathname;
342
416
  return { route: { ...this.fallback, path: '/*' }, params: { 0: tail }, tail };
343
417
  }
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA+DH,sDAAsD;AACtD,8EAA8E;AAC9E,sEAAsE;AACtE,eAAe;AACf,MAAM,YAAY,GAAG,IAAI,OAAO,EAAmC,CAAC;AAEpE,MAAM,eAAe,GAAG,CAAC,KAAkB,EAAkC,EAAE,CAC5E,KAA+B,CAAC,OAAO,KAAK,SAAS,CAAC;AAEzD,MAAM,UAAU,GAAG,CAAC,KAAkB,EAAkB,EAAE;IACxD,IAAI,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IACD,IAAI,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACtC,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,YAAY,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,OAAO,GAAG,IAAI,UAAU,CAAC,EAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,EAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,iBAAiB,GAAG,sCAAsC,CAAC;AAEjE;;;;;;;;;;GAUG;AACH,MAAM,MAAM,GAAG,CACb,KAAkB,EAClB,MAA2C,EACvB,EAAE;IACtB,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,SAAS,GAAG,CAAC,CAAC,CAAC;IACnB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAA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AC5E,4EAA4E;QAC5E,kDAAkD;QAClD,IAAI,CAAC,WAAW,CAAC,WAAW,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IACnD,CAAC,CAAC;CACH;AAED;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC7C,MAAM,CAAU,SAAS,GAAG,sBAAsB,CAAC;IAC1C,MAAM,CAAS;IACxB,YAAY,CAAc;IAE1B,YAAY,MAAc;QACxB,KAAK,CAAC,oBAAoB,CAAC,SAAS,EAAE;YACpC,OAAO,EAAE,IAAI;YACb,QAAQ,EAAE,IAAI;YACd,UAAU,EAAE,KAAK;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC","sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Modifications Copyright 2026 VanLandingham Labs, same license. See NOTICE.md.\n */\n\n/// <reference types=\"urlpattern-polyfill\" />\n\nimport type {ReactiveController, ReactiveControllerHost} from 'lit';\n\nexport interface BaseRouteConfig {\n name?: string | undefined;\n render?: (params: {[key: string]: string | undefined}) => unknown;\n enter?: (params: {\n [key: string]: string | undefined;\n }) => Promise<boolean> | boolean;\n}\n\n/**\n * A RouteConfig that matches against a `path` string. `path` must be a\n * [`URLPattern` compatible pathname pattern](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern/pathname).\n */\nexport interface PathRouteConfig extends BaseRouteConfig {\n path: string;\n}\n\n/**\n * A RouteConfig that matches against a given [`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern)\n *\n * While `URLPattern` can match against protocols, hostnames, and ports,\n * routes will only be checked for matches if they're part of the current\n * origin. This means that the pattern is limited to checking `pathname` and\n * `search`.\n */\nexport interface URLPatternRouteConfig extends BaseRouteConfig {\n pattern: URLPatternLike;\n}\n\n/**\n * The part of `URLPattern` this router uses.\n *\n * Declared structurally rather than referencing the global so the emitted\n * `.d.ts` is self-contained: the `/// <reference types=\"urlpattern-polyfill\" />`\n * above is not carried into declaration output, and `URLPattern` is not in\n * TypeScript's bundled `lib.dom`, so a published package typed against the\n * global fails a consumer build with `TS2304: Cannot find name 'URLPattern'`.\n * A real `URLPattern` satisfies this, so passing one still type-checks.\n */\nexport interface URLPatternLike {\n /**\n * The pathname pattern string, as `URLPattern.prototype.pathname` returns\n * it. Read to tell a trailing wildcard from any other positional group —\n * the groups object alone cannot (see `tailOf`).\n */\n readonly pathname: string;\n test(input: {pathname: string}): boolean;\n exec(input: {pathname: string}): {\n pathname: {groups: {[key: string]: string | undefined}};\n } | null;\n}\n\n/**\n * A description of a route, which path or pattern to match against, and a\n * render() callback used to render a match to the outlet.\n */\nexport type RouteConfig = PathRouteConfig | URLPatternRouteConfig;\n\n// A cache of URLPatterns created for PathRouteConfig.\n// Rather than converting all given RoutConfigs to URLPatternRouteConfig, this\n// lets us make `routes` mutable so users can add new PathRouteConfigs\n// dynamically.\nconst patternCache = new WeakMap<PathRouteConfig, URLPatternLike>();\n\nconst isPatternConfig = (route: RouteConfig): route is URLPatternRouteConfig =>\n (route as URLPatternRouteConfig).pattern !== undefined;\n\nconst getPattern = (route: RouteConfig): URLPatternLike => {\n if (isPatternConfig(route)) {\n return route.pattern;\n }\n let pattern = patternCache.get(route);\n if (pattern === undefined) {\n patternCache.set(route, (pattern = new URLPattern({pathname: route.path})));\n }\n return pattern;\n};\n\n/**\n * Matches a pathname pattern that ends in a wildcard, in the forms\n * `URLPattern.prototype.pathname` regenerates one: a bare `*` — which a\n * trailing `(.*)` also normalises to — or `{*}`, which the generator emits for\n * a wildcard after a modified group, e.g. `/docs{/}?*`. Either may be\n * optional (`*?`). Not a wildcard: an escaped `\\*`, or a `*` that is the\n * modifier on a group (`(\\d+)*`, `{/}*`) or on a named param (`:rest*`).\n * Those exclusions matter when an earlier positional group exists —\n * `/x/(\\d+)/:rest*` — since that group would otherwise be taken for the tail.\n */\nconst TRAILING_WILDCARD = /(?:(?<![\\\\)}]|:[\\w$]+)\\*|\\{\\*\\})\\??$/;\n\n/**\n * The tail of a match — what a trailing wildcard (`/foo/*`) captured — or\n * undefined when the pattern has none.\n *\n * Decided from the pattern, not from the groups object: an unnamed regex group\n * (`/post/(\\d+)`) and a wildcard that is not last (`/foo/*` followed by\n * `/bar`) are keyed by index exactly as a tail is, and reading either as one\n * truncated `link()` and handed a child the wrong segment. When a trailing\n * wildcard is present it is the last group in the pattern, so its key is the\n * highest positional index.\n */\nconst tailOf = (\n route: RouteConfig,\n params: {[key: string]: string | undefined}\n): string | undefined => {\n if (!TRAILING_WILDCARD.test(getPattern(route).pathname)) {\n return undefined;\n }\n let tailIndex = -1;\n for (const key of Object.keys(params)) {\n // Numeric, not lexicographic: '9' sorts above '10' as a string, so a\n // pattern with eleven or more wildcards picked group 9 as its tail.\n if (/^\\d+$/.test(key) && Number(key) > tailIndex) {\n tailIndex = Number(key);\n }\n }\n return tailIndex < 0 ? undefined : params[String(tailIndex)];\n};\n\n/**\n * A reactive controller that performs location-based routing using a\n * configuration of URL patterns and associated render callbacks.\n */\nexport class Routes implements ReactiveController {\n private readonly _host: ReactiveControllerHost & HTMLElement;\n\n /*\n * The currently installed set of routes in precedence order.\n *\n * This array is mutable. To dynamically add a new route you can write:\n *\n * ```ts\n * this._routes.routes.push({\n * path: '/foo',\n * render: () => html`<p>Foo</p>`,\n * });\n * ```\n *\n * Mutating this property does not trigger any route transitions. If the\n * changes may result is a different route matching for the current path, you\n * must instigate a route update with `goto()`.\n */\n routes: Array<RouteConfig> = [];\n\n /**\n * A default fallback route which will always be matched if none of the\n * {@link routes} match. Behaves like a `/*` route: `params[0]` is the whole\n * pathname minus its leading slash, and is handed to child controllers as\n * their tail. A nested controller's own pathname is a tail, with no leading\n * slash; the fallback accepts that too.\n */\n fallback?: BaseRouteConfig;\n\n /*\n * The current set of child Routes controllers. These are connected via\n * the routes-connected event.\n */\n private readonly _childRoutes: Array<Routes> = [];\n\n private _parentRoutes: Routes | undefined;\n\n /*\n * State related to the current matching route.\n *\n * We keep this so that consuming code can access current parameters, and so\n * that we can propagate tail matches to child routes if they are added after\n * navigation / matching.\n */\n /** Monotonic goto counter; see the last-goto-wins note in goto(). */\n private _gotoSeq = 0;\n\n private _currentPathname: string | undefined;\n private _currentTail: string | undefined;\n private _currentRoute: RouteConfig | undefined;\n private _currentParams: {\n [key: string]: string | undefined;\n } = {};\n\n /**\n * Callback to call when this controller is disconnected.\n *\n * It's critical to call this immediately in hostDisconnected so that this\n * controller instance doesn't receive a tail match meant for another route.\n */\n // TODO (justinfagnani): Do we need this now that we have a direct reference\n // to the parent? We can call `this._parentRoutes.disconnect(this)`.\n private _onDisconnect: (() => void) | undefined;\n\n constructor(\n host: ReactiveControllerHost & HTMLElement,\n routes: Array<RouteConfig>,\n options?: {fallback?: BaseRouteConfig}\n ) {\n (this._host = host).addController(this);\n this.routes = [...routes];\n this.fallback = options?.fallback;\n }\n\n /**\n * Returns a URL string of the current route, including parent routes,\n * optionally replacing the local path with `pathname`.\n */\n link(pathname?: string): string {\n if (pathname?.startsWith('/')) {\n return pathname;\n }\n if (pathname?.startsWith('.')) {\n throw new Error('Not implemented');\n }\n pathname ??= this._currentPathname;\n return (this._parentRoutes?.link() ?? '') + pathname;\n }\n\n /**\n * Navigates this routes controller to `pathname`.\n *\n * This does not navigate parent routes, so it isn't (yet) a general page\n * navigation API. It does navigate child routes if pathname matches a\n * pattern with a tail wildcard pattern (`/*`).\n *\n * Pass `options.signal` to make the navigation abandonable. `enter()` is\n * awaited, so a second `goto()` can start — and finish — while the first is\n * still resolving its route; without a signal the slower one commits last\n * and the outlet ends up on a route the URL has already left. `Router`\n * threads `NavigateEvent.signal` through for exactly this reason.\n */\n async goto(pathname: string, options?: {signal?: AbortSignal}) {\n // TODO (justinfagnani): handle absolute vs relative paths separately.\n\n // TODO (justinfagnani): generalize this to handle query params and\n // fragments. It currently only handles path names because it's easier to\n // completely disregard the origin for now. The click handler only does\n // an in-page navigation if the origin matches anyway.\n // Last-goto-wins, per controller. The navigation signal alone is not\n // enough: a child controller mounts as a *result* of its parent's render,\n // so its first goto() comes from `_onRoutesConnected` — after the parent's\n // navigation has already finished, and therefore with a signal that will\n // never abort. Without this counter a slow first child load commits over a\n // newer one. This also keeps `Routes` correct when used on its own, with\n // no `Router` and no Navigation API in the picture.\n const seq = ++this._gotoSeq;\n let tail: string | undefined;\n\n if (this.routes.length === 0 && this.fallback === undefined) {\n // If a routes controller has none of its own routes it acts like it has\n // one route of `/*` so that it passes the whole pathname as a tail\n // match.\n tail = pathname;\n this._currentPathname = '';\n // Simulate a tail group with the whole pathname\n this._currentParams = {0: tail};\n } else {\n const match = this._match(pathname);\n if (match === undefined) {\n throw new Error(`No route found for ${pathname}`);\n }\n const {route, params} = match;\n tail = match.tail;\n if (typeof route.enter === 'function') {\n const success = await route.enter(params);\n // If enter() returns false, cancel this navigation\n if (success === false) {\n return;\n }\n }\n // A newer navigation superseded this one while `enter` was awaiting.\n // Committing now would swap the outlet onto a route the URL has left.\n if (options?.signal?.aborted === true || seq !== this._gotoSeq) {\n return;\n }\n // Only update route state if the enter handler completes successfully\n this._currentRoute = route;\n this._currentParams = params;\n this._currentPathname =\n tail === undefined\n ? pathname\n : pathname.substring(0, pathname.length - tail.length);\n }\n this._currentTail = tail;\n\n // Propagate the tail match to children — deliberately NOT awaited.\n //\n // Awaiting looks like it would make `navigation.finished` cover the whole\n // tree, and an earlier revision of this fork did it. It is wrong twice\n // over. At this point `requestUpdate()` has not run, so `_childRoutes`\n // still holds the *outgoing* branch's controller: awaiting it gates the\n // parent's outlet swap on an `enter()` for a tail that controller will\n // never render (a hung one blocks the navigation forever), and if that\n // child has no route for the new tail its `No route found` throw\n // propagates out of here and `requestUpdate()` below never runs — URL\n // committed, outlet stranded, i.e. this fork's own thesis bug one level\n // down. Nested supersession is handled by the goto counter above, not by\n // awaiting. `_routeChild` covers the per-child filtering and error policy.\n //\n // Runs whether or not there is a tail. A route without one has nothing for\n // the children to render, but they must still be superseded — otherwise a\n // child mid-`enter()` for the previous tail stays current and commits over\n // a URL that has moved on.\n for (const childRoutes of this._childRoutes) {\n this._routeChild(childRoutes, tail);\n }\n this._host.requestUpdate();\n }\n\n /**\n * The result of calling the current route's render() callback.\n */\n outlet() {\n return this._currentRoute?.render?.(this._currentParams);\n }\n\n /**\n * The current parsed route parameters.\n */\n get params() {\n return this._currentParams;\n }\n\n /**\n * Hands a tail match to a child controller. Shared by the propagation loop in\n * `goto()` and the late-mount path in `_onRoutesConnected`, so that identical\n * input cannot be silent on one and an uncaught global throw on the other.\n *\n * A child with no route for the new tail is the expected case, not an error —\n * the outgoing branch mid-swap, or a deep link to a path the child cannot\n * render. Filtered structurally rather than by swallowing every rejection, so\n * a genuine `enter()` rejection still surfaces the way it does upstream.\n * Skipping must still supersede: `goto()` is where the counter is bumped, so\n * returning without it would leave an in-flight child navigation current,\n * free to commit over a URL that has moved on. A parent route with no tail\n * at all is the same case: nothing to route, but still something to stand\n * down.\n *\n * No abort signal is threaded through, and the goto is deliberately not\n * awaited. The parent commits its own state before children run, so a child\n * handed an already-aborted signal stands down with no newer goto() arriving\n * to correct it, leaving the nested outlet stuck — reachable, because a\n * hash-only navigation aborts the outstanding one without producing a\n * replacement. Supersession is the counter's job.\n */\n private _routeChild(child: Routes, tail: string | undefined) {\n if (tail === undefined || !child.hasRouteFor(tail)) {\n child._supersede();\n return;\n }\n void child.goto(tail).catch((err) => {\n queueMicrotask(() => {\n throw err;\n });\n });\n }\n\n /**\n * Invalidate any in-flight `goto()` on this controller without starting a\n * new one. Same-class access, so `_gotoSeq` stays private to `Routes`.\n */\n private _supersede(seen: Set<Routes> = new Set()): void {\n // Unreachable defence in depth. Upstream *can* produce a `_childRoutes`\n // cycle — a host carrying two Routes controllers, disconnected and\n // reconnected, ends up with each registered as the other's child — but\n // `hostDisconnected` below removes the listener that causes it, and a test\n // asserts the cycle cannot form. Kept because an unguarded recursive walk\n // over a cycle is a stack overflow rather than a misrender.\n if (seen.has(this)) {\n return;\n }\n seen.add(this);\n this._gotoSeq++;\n // Recursive: on the navigating branch the child's own propagation loop\n // reaches the grandchildren, but a skipped child never runs one — so\n // without this an in-flight grandchild `enter()` stays current and commits\n // over a URL that has moved on, the same defect one level deeper.\n for (const child of this._childRoutes) {\n child._supersede(seen);\n }\n }\n\n /**\n * True when this controller can render `pathname` — i.e. a route matches, or\n * a fallback is configured.\n *\n * `Router` gates interception on this: intercepting a path we cannot render\n * commits the URL and then throws out of `goto()`, leaving the address bar\n * moved and the outlet stale. Letting the browser handle it instead means a\n * server-rendered page, an export endpoint, or a GET form still works.\n */\n hasRouteFor(pathname: string): boolean {\n // A fallback matches everything, and a controller with no routes of its own\n // behaves as if it had a single `/*` route (goto()'s special case). Either\n // way the answer is yes without running a single pattern — worth\n // short-circuiting, since `Router` asks this on every navigation.\n if (this.fallback !== undefined || this.routes.length === 0) {\n return true;\n }\n // `test()`, not `_match()`: this only needs the yes/no, and `exec()` pays\n // ~8x on a hit to build a groups object the caller would throw away.\n return this.routes.some((r) => getPattern(r).test({pathname}));\n }\n\n /**\n * Matches `pathname` against the installed routes and returns the first match\n * with its parsed parameters, or the fallback's match if one is configured.\n *\n * One `exec()` per candidate rather than `test()` to select and `exec()` to\n * extract: that ran the winning pattern twice, and every caller that wants a\n * route wants its params too.\n */\n private _match(pathname: string):\n | {\n route: RouteConfig;\n params: {[key: string]: string | undefined};\n tail: string | undefined;\n }\n | undefined {\n for (const route of this.routes) {\n const result = getPattern(route).exec({pathname});\n if (result !== null) {\n const params = result.pathname.groups;\n return {route, params, tail: tailOf(route, params)};\n }\n }\n if (this.fallback === undefined) {\n return undefined;\n }\n // The fallback route behaves like it has a \"/*\" path. This is hidden from\n // the public API; the `path` is there to return a valid RouteConfig. The\n // match itself is done by hand rather than with a real `/*` pattern: a\n // nested controller is handed its tail *without* a leading slash, which\n // `/*` does not match, so a nested fallback matched nothing — empty\n // params, no tail, and its own children never routed.\n const tail = pathname.startsWith('/') ? pathname.slice(1) : pathname;\n return {route: {...this.fallback, path: '/*'}, params: {0: tail}, tail};\n }\n\n hostConnected() {\n this._host.addEventListener(\n RoutesConnectedEvent.eventName,\n this._onRoutesConnected\n );\n const event = new RoutesConnectedEvent(this);\n this._host.dispatchEvent(event);\n this._onDisconnect = event.onDisconnect;\n }\n\n hostDisconnected() {\n // Remove the listener hostConnected added. Without this a host that is\n // disconnected and reconnected (a repeat() reorder, a tab swap) leaves the\n // sibling controller's listener installed, so on the second connect it\n // claims the re-dispatching controller as *its* child and the pair point\n // at each other — a real `_childRoutes` cycle, which recursive walks turn\n // into a stack overflow.\n this._host.removeEventListener(\n RoutesConnectedEvent.eventName,\n this._onRoutesConnected\n );\n // When this child routes controller is disconnected because a parent\n // outlet rendered a different template, disconnecting will ensure that\n // this controller doesn't receive a tail match meant for another route.\n this._onDisconnect?.();\n this._parentRoutes = undefined;\n }\n\n private _onRoutesConnected = (e: RoutesConnectedEvent) => {\n // Don't handle the event fired by this routes controller, which we get\n // because we do this.dispatchEvent(...)\n if (e.routes === this) {\n return;\n }\n\n const childRoutes = e.routes;\n this._childRoutes.push(childRoutes);\n childRoutes._parentRoutes = this;\n\n e.stopImmediatePropagation();\n e.onDisconnect = () => {\n const index = this._childRoutes.indexOf(childRoutes);\n if (index !== -1) {\n this._childRoutes.splice(index, 1);\n }\n };\n\n // A child that mounts under an existing tail match has to be caught up to\n // it — it missed the propagation loop in goto() that ran before it existed.\n // With no tail there is nothing to catch up to, and `_routeChild` then only\n // supersedes, a no-op on a freshly mounted child.\n this._routeChild(childRoutes, this._currentTail);\n };\n}\n\n/**\n * This event is fired from Routes controllers when their host is connected to\n * announce the child route and potentially connect to a parent routes controller.\n */\nexport class RoutesConnectedEvent extends Event {\n static readonly eventName = 'lit-routes-connected';\n readonly routes: Routes;\n onDisconnect?: () => void;\n\n constructor(routes: Routes) {\n super(RoutesConnectedEvent.eventName, {\n bubbles: true,\n composed: true,\n cancelable: false,\n });\n this.routes = routes;\n }\n}\n\ndeclare global {\n interface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AAC;gBACjB,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;YACrC,CAAC;QACH,CAAC,CAAC;QAEF,0EAA0E;QAC1E,4EAA4E;QAC5E,4EAA4E;QAC5E,kDAAkD;QAClD,IAAI,CAAC,WAAW,CAAC,WAAW,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IACnD,CAAC,CAAC;CACH;AAED;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC7C,MAAM,CAAU,SAAS,GAAG,sBAAsB,CAAC;IAC1C,MAAM,CAAS;IACxB,YAAY,CAAc;IAE1B,YAAY,MAAc;QACxB,KAAK,CAAC,oBAAoB,CAAC,SAAS,EAAE;YACpC,OAAO,EAAE,IAAI;YACb,QAAQ,EAAE,IAAI;YACd,UAAU,EAAE,KAAK;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC","sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Modifications Copyright 2026 VanLandingham Labs, same license. See NOTICE.md.\n */\n\n/// <reference types=\"urlpattern-polyfill\" />\n\nimport type {ReactiveController, ReactiveControllerHost} from 'lit';\n\nexport interface BaseRouteConfig {\n name?: string | undefined;\n render?: (params: {[key: string]: string | undefined}) => unknown;\n enter?: (params: {\n [key: string]: string | undefined;\n }) => Promise<boolean> | boolean;\n}\n\n/**\n * A RouteConfig that matches against a `path` string. `path` must be a\n * [`URLPattern` compatible pathname pattern](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern/pathname).\n */\nexport interface PathRouteConfig extends BaseRouteConfig {\n path: string;\n}\n\n/**\n * A RouteConfig that matches against a given [`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern)\n *\n * While `URLPattern` can match against protocols, hostnames, and ports,\n * routes will only be checked for matches if they're part of the current\n * origin. This means the pattern is limited to checking `pathname`, `search`\n * and `hash`.\n */\nexport interface URLPatternRouteConfig extends BaseRouteConfig {\n pattern: URLPatternLike;\n}\n\n/**\n * The part of `URLPattern` this router uses.\n *\n * Declared structurally rather than referencing the global so the emitted\n * `.d.ts` is self-contained: the `/// <reference types=\"urlpattern-polyfill\" />`\n * above is not carried into declaration output, and `URLPattern` is not in\n * TypeScript's bundled `lib.dom`, so a published package typed against the\n * global fails a consumer build with `TS2304: Cannot find name 'URLPattern'`.\n * A real `URLPattern` satisfies this, so passing one still type-checks.\n */\nexport interface URLPatternLike {\n /**\n * The pathname pattern string, as `URLPattern.prototype.pathname` returns\n * it. Read to tell a trailing wildcard from any other positional group —\n * the groups object alone cannot (see `tailOf`).\n */\n readonly pathname: string;\n /**\n * The hash pattern string. `'*'` means the route places no constraint on the\n * fragment, which is what `URLPattern` fills in for any component the caller\n * omits. `Router` reads this to decide whether a fragment-only navigation is\n * its business or the browser's.\n */\n readonly hash: string;\n test(input: RouteLocation): boolean;\n exec(input: RouteLocation): {\n pathname: {groups: {[key: string]: string | undefined}};\n search: {groups: {[key: string]: string | undefined}};\n hash: {groups: {[key: string]: string | undefined}};\n } | null;\n}\n\n/**\n * The parts of a location this router matches against, split out of a path\n * string by `parseLocation`.\n *\n * `search` and `hash` carry no leading `?` or `#`. `URLPattern` canonicalises\n * either form away on an init input, but only for a real `URLPattern` — the\n * structural `URLPatternLike` above admits other implementations, so the\n * delimiters are stripped here rather than left to the pattern.\n */\nexport interface RouteLocation {\n pathname: string;\n search: string;\n hash: string;\n}\n\n/**\n * Splits `path` into the components a pattern is matched against.\n *\n * Deliberately not `new URL(path, origin)`: a nested controller's path is a\n * *tail* — a bare relative segment like `abc` — which `URL` would resolve\n * against the current directory and mangle.\n */\nconst parseLocation = (path: string): RouteLocation => {\n const hashIndex = path.indexOf('#');\n const hash = hashIndex === -1 ? '' : path.slice(hashIndex + 1);\n const beforeHash = hashIndex === -1 ? path : path.slice(0, hashIndex);\n const searchIndex = beforeHash.indexOf('?');\n return {\n pathname: searchIndex === -1 ? beforeHash : beforeHash.slice(0, searchIndex),\n search: searchIndex === -1 ? '' : beforeHash.slice(searchIndex + 1),\n hash,\n };\n};\n\n/** Re-attaches `search` and `hash` to a pathname. Inverse of `parseLocation`. */\nconst formatLocation = (\n pathname: string,\n {search, hash}: {search: string; hash: string}\n): string =>\n pathname + (search === '' ? '' : `?${search}`) + (hash === '' ? '' : `#${hash}`);\n\n/**\n * A description of a route, which path or pattern to match against, and a\n * render() callback used to render a match to the outlet.\n */\nexport type RouteConfig = PathRouteConfig | URLPatternRouteConfig;\n\n// A cache of URLPatterns created for PathRouteConfig.\n// Rather than converting all given RoutConfigs to URLPatternRouteConfig, this\n// lets us make `routes` mutable so users can add new PathRouteConfigs\n// dynamically.\nconst patternCache = new WeakMap<PathRouteConfig, URLPatternLike>();\n\nconst isPatternConfig = (route: RouteConfig): route is URLPatternRouteConfig =>\n (route as URLPatternRouteConfig).pattern !== undefined;\n\nconst getPattern = (route: RouteConfig): URLPatternLike => {\n if (isPatternConfig(route)) {\n return route.pattern;\n }\n let pattern = patternCache.get(route);\n if (pattern === undefined) {\n patternCache.set(route, (pattern = new URLPattern({pathname: route.path})));\n }\n return pattern;\n};\n\n/**\n * Matches a pathname pattern that ends in a wildcard, in the forms\n * `URLPattern.prototype.pathname` regenerates one: a bare `*` — which a\n * trailing `(.*)` also normalises to — or `{*}`, which the generator emits for\n * a wildcard after a modified group, e.g. `/docs{/}?*`. Either may be\n * optional (`*?`). Not a wildcard: an escaped `\\*`, or a `*` that is the\n * modifier on a group (`(\\d+)*`, `{/}*`) or on a named param (`:rest*`).\n * Those exclusions matter when an earlier positional group exists —\n * `/x/(\\d+)/:rest*` — since that group would otherwise be taken for the tail.\n */\nconst TRAILING_WILDCARD = /(?:(?<![\\\\)}]|:[\\w$]+)\\*|\\{\\*\\})\\??$/;\n\n/**\n * The tail of a match — what a trailing wildcard (`/foo/*`) captured — or\n * undefined when the pattern has none.\n *\n * Decided from the pattern, not from the groups object: an unnamed regex group\n * (`/post/(\\d+)`) and a wildcard that is not last (`/foo/*` followed by\n * `/bar`) are keyed by index exactly as a tail is, and reading either as one\n * truncated `link()` and handed a child the wrong segment. When a trailing\n * wildcard is present it is the last group in the pattern, so its key is the\n * highest positional index.\n */\nconst tailOf = (\n route: RouteConfig,\n params: {[key: string]: string | undefined}\n): string | undefined => {\n if (!TRAILING_WILDCARD.test(getPattern(route).pathname)) {\n return undefined;\n }\n let tailIndex = -1;\n for (const key of Object.keys(params)) {\n // Numeric, not lexicographic: '9' sorts above '10' as a string, so a\n // pattern with eleven or more wildcards picked group 9 as its tail.\n if (/^\\d+$/.test(key) && Number(key) > tailIndex) {\n tailIndex = Number(key);\n }\n }\n return tailIndex < 0 ? undefined : params[String(tailIndex)];\n};\n\n/**\n * A reactive controller that performs location-based routing using a\n * configuration of URL patterns and associated render callbacks.\n */\nexport class Routes implements ReactiveController {\n private readonly _host: ReactiveControllerHost & HTMLElement;\n\n /*\n * The currently installed set of routes in precedence order.\n *\n * This array is mutable. To dynamically add a new route you can write:\n *\n * ```ts\n * this._routes.routes.push({\n * path: '/foo',\n * render: () => html`<p>Foo</p>`,\n * });\n * ```\n *\n * Mutating this property does not trigger any route transitions. If the\n * changes may result is a different route matching for the current path, you\n * must instigate a route update with `goto()`.\n */\n routes: Array<RouteConfig> = [];\n\n /**\n * A default fallback route which will always be matched if none of the\n * {@link routes} match. Behaves like a `/*` route: `params[0]` is the whole\n * pathname minus its leading slash, and is handed to child controllers as\n * their tail. A nested controller's own pathname is a tail, with no leading\n * slash; the fallback accepts that too.\n */\n fallback?: BaseRouteConfig;\n\n /*\n * The current set of child Routes controllers. These are connected via\n * the routes-connected event.\n */\n private readonly _childRoutes: Array<Routes> = [];\n\n private _parentRoutes: Routes | undefined;\n\n /*\n * State related to the current matching route.\n *\n * We keep this so that consuming code can access current parameters, and so\n * that we can propagate tail matches to child routes if they are added after\n * navigation / matching.\n */\n /** Monotonic goto counter; see the last-goto-wins note in goto(). */\n private _gotoSeq = 0;\n\n private _currentPathname: string | undefined;\n private _currentTail: string | undefined;\n /**\n * The search and hash of the current location.\n *\n * Ambient rather than tailed: only the pathname nests, so a child controller\n * is handed the parent's tail as its pathname but the *same* search and\n * hash. There is no meaningful way to split a fragment across a route tree.\n */\n private _currentSearch = '';\n private _currentHash = '';\n private _currentRoute: RouteConfig | undefined;\n private _currentParams: {\n [key: string]: string | undefined;\n } = {};\n\n /**\n * Callback to call when this controller is disconnected.\n *\n * It's critical to call this immediately in hostDisconnected so that this\n * controller instance doesn't receive a tail match meant for another route.\n */\n // TODO (justinfagnani): Do we need this now that we have a direct reference\n // to the parent? We can call `this._parentRoutes.disconnect(this)`.\n private _onDisconnect: (() => void) | undefined;\n\n constructor(\n host: ReactiveControllerHost & HTMLElement,\n routes: Array<RouteConfig>,\n options?: {fallback?: BaseRouteConfig}\n ) {\n (this._host = host).addController(this);\n this.routes = [...routes];\n this.fallback = options?.fallback;\n }\n\n /**\n * Returns a URL string of the current route, including parent routes,\n * optionally replacing the local path with `pathname`.\n */\n link(pathname?: string): string {\n if (pathname?.startsWith('/')) {\n return pathname;\n }\n if (pathname?.startsWith('.')) {\n throw new Error('Not implemented');\n }\n pathname ??= this._currentPathname;\n return (this._parentRoutes?.link() ?? '') + pathname;\n }\n\n /**\n * Navigates this routes controller to `pathname`.\n *\n * This does not navigate parent routes, so it isn't (yet) a general page\n * navigation API. It does navigate child routes if pathname matches a\n * pattern with a tail wildcard pattern (`/*`).\n *\n * Pass `options.signal` to make the navigation abandonable. `enter()` is\n * awaited, so a second `goto()` can start — and finish — while the first is\n * still resolving its route; without a signal the slower one commits last\n * and the outlet ends up on a route the URL has already left. `Router`\n * threads `NavigateEvent.signal` through for exactly this reason.\n */\n async goto(path: string, options?: {signal?: AbortSignal}) {\n // TODO (justinfagnani): handle absolute vs relative paths separately.\n\n const location = parseLocation(path);\n const {pathname} = location;\n\n // Last-goto-wins, per controller. The navigation signal alone is not\n // enough: a child controller mounts as a *result* of its parent's render,\n // so its first goto() comes from `_onRoutesConnected` — after the parent's\n // navigation has already finished, and therefore with a signal that will\n // never abort. Without this counter a slow first child load commits over a\n // newer one. This also keeps `Routes` correct when used on its own, with\n // no `Router` and no Navigation API in the picture.\n const seq = ++this._gotoSeq;\n let tail: string | undefined;\n\n if (this.routes.length === 0 && this.fallback === undefined) {\n // If a routes controller has none of its own routes it acts like it has\n // one route of `/*` so that it passes the whole pathname as a tail\n // match.\n tail = pathname;\n this._currentPathname = '';\n // Simulate a tail group with the whole pathname\n this._currentParams = {0: tail};\n } else {\n const match = this._match(location);\n if (match === undefined) {\n throw new Error(`No route found for ${path}`);\n }\n const {route, params} = match;\n tail = match.tail;\n if (typeof route.enter === 'function') {\n const success = await route.enter(params);\n // If enter() returns false, cancel this navigation\n if (success === false) {\n return;\n }\n }\n // A newer navigation superseded this one while `enter` was awaiting.\n // Committing now would swap the outlet onto a route the URL has left.\n if (options?.signal?.aborted === true || seq !== this._gotoSeq) {\n return;\n }\n // Only update route state if the enter handler completes successfully\n this._currentRoute = route;\n this._currentParams = params;\n this._currentPathname =\n tail === undefined\n ? pathname\n : pathname.substring(0, pathname.length - tail.length);\n }\n this._currentTail = tail;\n this._currentSearch = location.search;\n this._currentHash = location.hash;\n\n // Propagate the tail match to children — deliberately NOT awaited.\n //\n // Awaiting looks like it would make `navigation.finished` cover the whole\n // tree, and an earlier revision of this fork did it. It is wrong twice\n // over. At this point `requestUpdate()` has not run, so `_childRoutes`\n // still holds the *outgoing* branch's controller: awaiting it gates the\n // parent's outlet swap on an `enter()` for a tail that controller will\n // never render (a hung one blocks the navigation forever), and if that\n // child has no route for the new tail its `No route found` throw\n // propagates out of here and `requestUpdate()` below never runs — URL\n // committed, outlet stranded, i.e. this fork's own thesis bug one level\n // down. Nested supersession is handled by the goto counter above, not by\n // awaiting. `_routeChild` covers the per-child filtering and error policy.\n //\n // Runs whether or not there is a tail. A route without one has nothing for\n // the children to render, but they must still be superseded — otherwise a\n // child mid-`enter()` for the previous tail stays current and commits over\n // a URL that has moved on.\n for (const childRoutes of this._childRoutes) {\n this._routeChild(childRoutes, tail);\n }\n this._host.requestUpdate();\n }\n\n /**\n * The result of calling the current route's render() callback.\n */\n outlet() {\n return this._currentRoute?.render?.(this._currentParams);\n }\n\n /**\n * The current parsed route parameters.\n */\n get params() {\n return this._currentParams;\n }\n\n /**\n * Hands a tail match to a child controller. Shared by the propagation loop in\n * `goto()` and the late-mount path in `_onRoutesConnected`, so that identical\n * input cannot be silent on one and an uncaught global throw on the other.\n *\n * A child with no route for the new tail is the expected case, not an error —\n * the outgoing branch mid-swap, or a deep link to a path the child cannot\n * render. Filtered structurally rather than by swallowing every rejection, so\n * a genuine `enter()` rejection still surfaces the way it does upstream.\n * Skipping must still supersede: `goto()` is where the counter is bumped, so\n * returning without it would leave an in-flight child navigation current,\n * free to commit over a URL that has moved on. A parent route with no tail\n * at all is the same case: nothing to route, but still something to stand\n * down.\n *\n * No abort signal is threaded through, and the goto is deliberately not\n * awaited. The parent commits its own state before children run, so a child\n * handed an already-aborted signal stands down with no newer goto() arriving\n * to correct it, leaving the nested outlet stuck — reachable, because a\n * hash-only navigation aborts the outstanding one without producing a\n * replacement. Supersession is the counter's job.\n */\n private _routeChild(child: Routes, tail: string | undefined) {\n if (tail === undefined) {\n child._supersede();\n return;\n }\n const childPath = formatLocation(tail, {\n search: this._currentSearch,\n hash: this._currentHash,\n });\n if (!child.hasRouteFor(childPath)) {\n child._supersede();\n return;\n }\n void child.goto(childPath).catch((err) => {\n queueMicrotask(() => {\n throw err;\n });\n });\n }\n\n /**\n * Invalidate any in-flight `goto()` on this controller without starting a\n * new one. Same-class access, so `_gotoSeq` stays private to `Routes`.\n */\n private _supersede(seen: Set<Routes> = new Set()): void {\n // Unreachable defence in depth. Upstream *can* produce a `_childRoutes`\n // cycle — a host carrying two Routes controllers, disconnected and\n // reconnected, ends up with each registered as the other's child — but\n // `hostDisconnected` below removes the listener that causes it, and a test\n // asserts the cycle cannot form. Kept because an unguarded recursive walk\n // over a cycle is a stack overflow rather than a misrender.\n if (seen.has(this)) {\n return;\n }\n seen.add(this);\n this._gotoSeq++;\n // Recursive: on the navigating branch the child's own propagation loop\n // reaches the grandchildren, but a skipped child never runs one — so\n // without this an in-flight grandchild `enter()` stays current and commits\n // over a URL that has moved on, the same defect one level deeper.\n for (const child of this._childRoutes) {\n child._supersede(seen);\n }\n }\n\n /**\n * True when this controller, or any controller below it, has a route that\n * constrains the hash.\n *\n * `Router` gates interception of fragment-only navigation on this. Left\n * ungated, a pathname-only app would have every in-page anchor swallowed and\n * re-rendered instead of scrolled; gated, such an app behaves exactly as it\n * did before hash routes existed.\n *\n * Walks children because a nested controller may route on the hash while the\n * top-level `Router` does not — and only the top-level one sees the\n * navigate event.\n */\n protected _constrainsHash(seen: Set<Routes> = new Set()): boolean {\n // Cycle guard, matching `_supersede`; see the note there.\n if (seen.has(this)) {\n return false;\n }\n seen.add(this);\n return (\n this.routes.some((r) => getPattern(r).hash !== '*') ||\n this._childRoutes.some((c) => c._constrainsHash(seen))\n );\n }\n\n /**\n * True when this controller can render `path` — i.e. a route matches, or\n * a fallback is configured.\n *\n * `Router` gates interception on this: intercepting a path we cannot render\n * commits the URL and then throws out of `goto()`, leaving the address bar\n * moved and the outlet stale. Letting the browser handle it instead means a\n * server-rendered page, an export endpoint, or a GET form still works.\n */\n hasRouteFor(path: string): boolean {\n // A fallback matches everything, and a controller with no routes of its own\n // behaves as if it had a single `/*` route (goto()'s special case). Either\n // way the answer is yes without running a single pattern — worth\n // short-circuiting, since `Router` asks this on every navigation.\n if (this.fallback !== undefined || this.routes.length === 0) {\n return true;\n }\n // `test()`, not `_match()`: this only needs the yes/no, and `exec()` pays\n // ~8x on a hit to build a groups object the caller would throw away.\n const location = parseLocation(path);\n return this.routes.some((r) => getPattern(r).test(location));\n }\n\n /**\n * Matches `pathname` against the installed routes and returns the first match\n * with its parsed parameters, or the fallback's match if one is configured.\n *\n * One `exec()` per candidate rather than `test()` to select and `exec()` to\n * extract: that ran the winning pattern twice, and every caller that wants a\n * route wants its params too.\n */\n private _match(location: RouteLocation):\n | {\n route: RouteConfig;\n params: {[key: string]: string | undefined};\n tail: string | undefined;\n }\n | undefined {\n for (const route of this.routes) {\n const result = getPattern(route).exec(location);\n if (result !== null) {\n const params: {[key: string]: string | undefined} = {\n ...result.pathname.groups,\n };\n // Named groups only. A positional group is keyed by index in every\n // component independently, so `/child/*` with a hash of `*` yields a\n // \"0\" in both — and `tailOf` picks the tail by highest numeric key.\n // Merging them would let a fragment masquerade as the tail.\n for (const groups of [result.search.groups, result.hash.groups]) {\n for (const [key, value] of Object.entries(groups)) {\n if (!/^\\d+$/.test(key)) {\n params[key] = value;\n }\n }\n }\n return {route, params, tail: tailOf(route, result.pathname.groups)};\n }\n }\n if (this.fallback === undefined) {\n return undefined;\n }\n // The fallback route behaves like it has a \"/*\" path. This is hidden from\n // the public API; the `path` is there to return a valid RouteConfig. The\n // match itself is done by hand rather than with a real `/*` pattern: a\n // nested controller is handed its tail *without* a leading slash, which\n // `/*` does not match, so a nested fallback matched nothing — empty\n // params, no tail, and its own children never routed.\n const {pathname} = location;\n const tail = pathname.startsWith('/') ? pathname.slice(1) : pathname;\n return {route: {...this.fallback, path: '/*'}, params: {0: tail}, tail};\n }\n\n hostConnected() {\n this._host.addEventListener(\n RoutesConnectedEvent.eventName,\n this._onRoutesConnected\n );\n const event = new RoutesConnectedEvent(this);\n this._host.dispatchEvent(event);\n this._onDisconnect = event.onDisconnect;\n }\n\n hostDisconnected() {\n // Remove the listener hostConnected added. Without this a host that is\n // disconnected and reconnected (a repeat() reorder, a tab swap) leaves the\n // sibling controller's listener installed, so on the second connect it\n // claims the re-dispatching controller as *its* child and the pair point\n // at each other — a real `_childRoutes` cycle, which recursive walks turn\n // into a stack overflow.\n this._host.removeEventListener(\n RoutesConnectedEvent.eventName,\n this._onRoutesConnected\n );\n // When this child routes controller is disconnected because a parent\n // outlet rendered a different template, disconnecting will ensure that\n // this controller doesn't receive a tail match meant for another route.\n this._onDisconnect?.();\n this._parentRoutes = undefined;\n }\n\n private _onRoutesConnected = (e: RoutesConnectedEvent) => {\n // Don't handle the event fired by this routes controller, which we get\n // because we do this.dispatchEvent(...)\n if (e.routes === this) {\n return;\n }\n\n const childRoutes = e.routes;\n this._childRoutes.push(childRoutes);\n childRoutes._parentRoutes = this;\n\n e.stopImmediatePropagation();\n e.onDisconnect = () => {\n const index = this._childRoutes.indexOf(childRoutes);\n if (index !== -1) {\n this._childRoutes.splice(index, 1);\n }\n };\n\n // A child that mounts under an existing tail match has to be caught up to\n // it — it missed the propagation loop in goto() that ran before it existed.\n // With no tail there is nothing to catch up to, and `_routeChild` then only\n // supersedes, a no-op on a freshly mounted child.\n this._routeChild(childRoutes, this._currentTail);\n };\n}\n\n/**\n * This event is fired from Routes controllers when their host is connected to\n * announce the child route and potentially connect to a parent routes controller.\n */\nexport class RoutesConnectedEvent extends Event {\n static readonly eventName = 'lit-routes-connected';\n readonly routes: Routes;\n onDisconnect?: () => void;\n\n constructor(routes: Routes) {\n super(RoutesConnectedEvent.eventName, {\n bubbles: true,\n composed: true,\n cancelable: false,\n });\n this.routes = routes;\n }\n}\n\ndeclare global {\n interface HTMLElementEventMap {\n [RoutesConnectedEvent.eventName]: RoutesConnectedEvent;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lit-navigation-router",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "A router for Lit built on the Navigation API. Fork of @lit-labs/router.",
5
5
  "license": "BSD-3-Clause",
6
6
  "repository": {
package/src/router.ts CHANGED
@@ -48,6 +48,15 @@ interface NavigationLike {
48
48
  const getNavigation = (): NavigationLike | undefined =>
49
49
  (window as unknown as {navigation?: NavigationLike}).navigation;
50
50
 
51
+ /**
52
+ * The current location as a path string, in the form `goto()` parses.
53
+ *
54
+ * Only the origin is dropped: this router matches within one origin, and
55
+ * `_onNavigate` declines anything else before it gets here.
56
+ */
57
+ const currentPath = (): string =>
58
+ window.location.pathname + window.location.search + window.location.hash;
59
+
51
60
  /**
52
61
  * True when the Navigation API is available — Baseline Newly Available since
53
62
  * January 2026 (Chrome/Edge, Safari 26.2, Firefox 147).
@@ -128,7 +137,7 @@ export class Router extends Routes {
128
137
  // Surfaced rather than left as a bare unhandled rejection, matching the
129
138
  // convention in routes.ts: on an engine without the API this is the *only*
130
139
  // rendering path, and a deep link with no matching route throws here.
131
- void this.goto(window.location.pathname).catch((err) => {
140
+ void this.goto(currentPath()).catch((err) => {
132
141
  queueMicrotask(() => {
133
142
  throw err;
134
143
  });
@@ -149,17 +158,21 @@ export class Router extends Routes {
149
158
  */
150
159
  private _onNavigate = (e: NavigateEventLike) => {
151
160
  // Not ours to handle: anything the browser says cannot be intercepted,
152
- // fragment-only moves, downloads, and POST form submissions.
161
+ // downloads, and POST form submissions.
153
162
  //
154
163
  // `!= null`, not `!== null`: the spec types both as nullable-but-present,
155
164
  // but a polyfill that leaves either unset would make a strict check true
156
165
  // for every ordinary link and silently decline the whole app.
157
- if (
158
- !e.canIntercept ||
159
- e.hashChange ||
160
- e.downloadRequest != null ||
161
- e.formData != null
162
- ) {
166
+ if (!e.canIntercept || e.downloadRequest != null || e.formData != null) {
167
+ return;
168
+ }
169
+
170
+ // Fragment-only moves belong to the browser unless a route actually reads
171
+ // the fragment. Intercepting them unconditionally would cost every
172
+ // pathname-only app its native in-page scrolling — and re-render the same
173
+ // route to no effect — while declining them unconditionally is the
174
+ // lit/lit#3517 bug this router inherited.
175
+ if (e.hashChange && !this._constrainsHash()) {
163
176
  return;
164
177
  }
165
178
 
@@ -196,7 +209,8 @@ export class Router extends Routes {
196
209
  // throws "No route found", and the address bar is left pointing somewhere
197
210
  // the outlet never went. Declining lets the browser do the real
198
211
  // navigation, which is the correct outcome.
199
- if (!this.hasRouteFor(url.pathname)) {
212
+ const path = url.pathname + url.search + url.hash;
213
+ if (!this.hasRouteFor(path)) {
200
214
  return;
201
215
  }
202
216
 
@@ -205,7 +219,7 @@ export class Router extends Routes {
205
219
  handler: async () => {
206
220
  // `e.signal` aborts if another navigation starts before this handler
207
221
  // resolves; goto() checks it after `enter()` and stands down.
208
- await this.goto(url.pathname, {signal: e.signal});
222
+ await this.goto(path, {signal: e.signal});
209
223
  },
210
224
  });
211
225
  };
package/src/routes.ts CHANGED
@@ -31,8 +31,8 @@ export interface PathRouteConfig extends BaseRouteConfig {
31
31
  *
32
32
  * While `URLPattern` can match against protocols, hostnames, and ports,
33
33
  * routes will only be checked for matches if they're part of the current
34
- * origin. This means that the pattern is limited to checking `pathname` and
35
- * `search`.
34
+ * origin. This means the pattern is limited to checking `pathname`, `search`
35
+ * and `hash`.
36
36
  */
37
37
  export interface URLPatternRouteConfig extends BaseRouteConfig {
38
38
  pattern: URLPatternLike;
@@ -55,12 +55,62 @@ export interface URLPatternLike {
55
55
  * the groups object alone cannot (see `tailOf`).
56
56
  */
57
57
  readonly pathname: string;
58
- test(input: {pathname: string}): boolean;
59
- exec(input: {pathname: string}): {
58
+ /**
59
+ * The hash pattern string. `'*'` means the route places no constraint on the
60
+ * fragment, which is what `URLPattern` fills in for any component the caller
61
+ * omits. `Router` reads this to decide whether a fragment-only navigation is
62
+ * its business or the browser's.
63
+ */
64
+ readonly hash: string;
65
+ test(input: RouteLocation): boolean;
66
+ exec(input: RouteLocation): {
60
67
  pathname: {groups: {[key: string]: string | undefined}};
68
+ search: {groups: {[key: string]: string | undefined}};
69
+ hash: {groups: {[key: string]: string | undefined}};
61
70
  } | null;
62
71
  }
63
72
 
73
+ /**
74
+ * The parts of a location this router matches against, split out of a path
75
+ * string by `parseLocation`.
76
+ *
77
+ * `search` and `hash` carry no leading `?` or `#`. `URLPattern` canonicalises
78
+ * either form away on an init input, but only for a real `URLPattern` — the
79
+ * structural `URLPatternLike` above admits other implementations, so the
80
+ * delimiters are stripped here rather than left to the pattern.
81
+ */
82
+ export interface RouteLocation {
83
+ pathname: string;
84
+ search: string;
85
+ hash: string;
86
+ }
87
+
88
+ /**
89
+ * Splits `path` into the components a pattern is matched against.
90
+ *
91
+ * Deliberately not `new URL(path, origin)`: a nested controller's path is a
92
+ * *tail* — a bare relative segment like `abc` — which `URL` would resolve
93
+ * against the current directory and mangle.
94
+ */
95
+ const parseLocation = (path: string): RouteLocation => {
96
+ const hashIndex = path.indexOf('#');
97
+ const hash = hashIndex === -1 ? '' : path.slice(hashIndex + 1);
98
+ const beforeHash = hashIndex === -1 ? path : path.slice(0, hashIndex);
99
+ const searchIndex = beforeHash.indexOf('?');
100
+ return {
101
+ pathname: searchIndex === -1 ? beforeHash : beforeHash.slice(0, searchIndex),
102
+ search: searchIndex === -1 ? '' : beforeHash.slice(searchIndex + 1),
103
+ hash,
104
+ };
105
+ };
106
+
107
+ /** Re-attaches `search` and `hash` to a pathname. Inverse of `parseLocation`. */
108
+ const formatLocation = (
109
+ pathname: string,
110
+ {search, hash}: {search: string; hash: string}
111
+ ): string =>
112
+ pathname + (search === '' ? '' : `?${search}`) + (hash === '' ? '' : `#${hash}`);
113
+
64
114
  /**
65
115
  * A description of a route, which path or pattern to match against, and a
66
116
  * render() callback used to render a match to the outlet.
@@ -182,6 +232,15 @@ export class Routes implements ReactiveController {
182
232
 
183
233
  private _currentPathname: string | undefined;
184
234
  private _currentTail: string | undefined;
235
+ /**
236
+ * The search and hash of the current location.
237
+ *
238
+ * Ambient rather than tailed: only the pathname nests, so a child controller
239
+ * is handed the parent's tail as its pathname but the *same* search and
240
+ * hash. There is no meaningful way to split a fragment across a route tree.
241
+ */
242
+ private _currentSearch = '';
243
+ private _currentHash = '';
185
244
  private _currentRoute: RouteConfig | undefined;
186
245
  private _currentParams: {
187
246
  [key: string]: string | undefined;
@@ -235,13 +294,12 @@ export class Routes implements ReactiveController {
235
294
  * and the outlet ends up on a route the URL has already left. `Router`
236
295
  * threads `NavigateEvent.signal` through for exactly this reason.
237
296
  */
238
- async goto(pathname: string, options?: {signal?: AbortSignal}) {
297
+ async goto(path: string, options?: {signal?: AbortSignal}) {
239
298
  // TODO (justinfagnani): handle absolute vs relative paths separately.
240
299
 
241
- // TODO (justinfagnani): generalize this to handle query params and
242
- // fragments. It currently only handles path names because it's easier to
243
- // completely disregard the origin for now. The click handler only does
244
- // an in-page navigation if the origin matches anyway.
300
+ const location = parseLocation(path);
301
+ const {pathname} = location;
302
+
245
303
  // Last-goto-wins, per controller. The navigation signal alone is not
246
304
  // enough: a child controller mounts as a *result* of its parent's render,
247
305
  // so its first goto() comes from `_onRoutesConnected` — after the parent's
@@ -261,9 +319,9 @@ export class Routes implements ReactiveController {
261
319
  // Simulate a tail group with the whole pathname
262
320
  this._currentParams = {0: tail};
263
321
  } else {
264
- const match = this._match(pathname);
322
+ const match = this._match(location);
265
323
  if (match === undefined) {
266
- throw new Error(`No route found for ${pathname}`);
324
+ throw new Error(`No route found for ${path}`);
267
325
  }
268
326
  const {route, params} = match;
269
327
  tail = match.tail;
@@ -288,6 +346,8 @@ export class Routes implements ReactiveController {
288
346
  : pathname.substring(0, pathname.length - tail.length);
289
347
  }
290
348
  this._currentTail = tail;
349
+ this._currentSearch = location.search;
350
+ this._currentHash = location.hash;
291
351
 
292
352
  // Propagate the tail match to children — deliberately NOT awaited.
293
353
  //
@@ -350,11 +410,19 @@ export class Routes implements ReactiveController {
350
410
  * replacement. Supersession is the counter's job.
351
411
  */
352
412
  private _routeChild(child: Routes, tail: string | undefined) {
353
- if (tail === undefined || !child.hasRouteFor(tail)) {
413
+ if (tail === undefined) {
414
+ child._supersede();
415
+ return;
416
+ }
417
+ const childPath = formatLocation(tail, {
418
+ search: this._currentSearch,
419
+ hash: this._currentHash,
420
+ });
421
+ if (!child.hasRouteFor(childPath)) {
354
422
  child._supersede();
355
423
  return;
356
424
  }
357
- void child.goto(tail).catch((err) => {
425
+ void child.goto(childPath).catch((err) => {
358
426
  queueMicrotask(() => {
359
427
  throw err;
360
428
  });
@@ -387,7 +455,32 @@ export class Routes implements ReactiveController {
387
455
  }
388
456
 
389
457
  /**
390
- * True when this controller can render `pathname` — i.e. a route matches, or
458
+ * True when this controller, or any controller below it, has a route that
459
+ * constrains the hash.
460
+ *
461
+ * `Router` gates interception of fragment-only navigation on this. Left
462
+ * ungated, a pathname-only app would have every in-page anchor swallowed and
463
+ * re-rendered instead of scrolled; gated, such an app behaves exactly as it
464
+ * did before hash routes existed.
465
+ *
466
+ * Walks children because a nested controller may route on the hash while the
467
+ * top-level `Router` does not — and only the top-level one sees the
468
+ * navigate event.
469
+ */
470
+ protected _constrainsHash(seen: Set<Routes> = new Set()): boolean {
471
+ // Cycle guard, matching `_supersede`; see the note there.
472
+ if (seen.has(this)) {
473
+ return false;
474
+ }
475
+ seen.add(this);
476
+ return (
477
+ this.routes.some((r) => getPattern(r).hash !== '*') ||
478
+ this._childRoutes.some((c) => c._constrainsHash(seen))
479
+ );
480
+ }
481
+
482
+ /**
483
+ * True when this controller can render `path` — i.e. a route matches, or
391
484
  * a fallback is configured.
392
485
  *
393
486
  * `Router` gates interception on this: intercepting a path we cannot render
@@ -395,7 +488,7 @@ export class Routes implements ReactiveController {
395
488
  * moved and the outlet stale. Letting the browser handle it instead means a
396
489
  * server-rendered page, an export endpoint, or a GET form still works.
397
490
  */
398
- hasRouteFor(pathname: string): boolean {
491
+ hasRouteFor(path: string): boolean {
399
492
  // A fallback matches everything, and a controller with no routes of its own
400
493
  // behaves as if it had a single `/*` route (goto()'s special case). Either
401
494
  // way the answer is yes without running a single pattern — worth
@@ -405,7 +498,8 @@ export class Routes implements ReactiveController {
405
498
  }
406
499
  // `test()`, not `_match()`: this only needs the yes/no, and `exec()` pays
407
500
  // ~8x on a hit to build a groups object the caller would throw away.
408
- return this.routes.some((r) => getPattern(r).test({pathname}));
501
+ const location = parseLocation(path);
502
+ return this.routes.some((r) => getPattern(r).test(location));
409
503
  }
410
504
 
411
505
  /**
@@ -416,7 +510,7 @@ export class Routes implements ReactiveController {
416
510
  * extract: that ran the winning pattern twice, and every caller that wants a
417
511
  * route wants its params too.
418
512
  */
419
- private _match(pathname: string):
513
+ private _match(location: RouteLocation):
420
514
  | {
421
515
  route: RouteConfig;
422
516
  params: {[key: string]: string | undefined};
@@ -424,10 +518,23 @@ export class Routes implements ReactiveController {
424
518
  }
425
519
  | undefined {
426
520
  for (const route of this.routes) {
427
- const result = getPattern(route).exec({pathname});
521
+ const result = getPattern(route).exec(location);
428
522
  if (result !== null) {
429
- const params = result.pathname.groups;
430
- return {route, params, tail: tailOf(route, params)};
523
+ const params: {[key: string]: string | undefined} = {
524
+ ...result.pathname.groups,
525
+ };
526
+ // Named groups only. A positional group is keyed by index in every
527
+ // component independently, so `/child/*` with a hash of `*` yields a
528
+ // "0" in both — and `tailOf` picks the tail by highest numeric key.
529
+ // Merging them would let a fragment masquerade as the tail.
530
+ for (const groups of [result.search.groups, result.hash.groups]) {
531
+ for (const [key, value] of Object.entries(groups)) {
532
+ if (!/^\d+$/.test(key)) {
533
+ params[key] = value;
534
+ }
535
+ }
536
+ }
537
+ return {route, params, tail: tailOf(route, result.pathname.groups)};
431
538
  }
432
539
  }
433
540
  if (this.fallback === undefined) {
@@ -439,6 +546,7 @@ export class Routes implements ReactiveController {
439
546
  // nested controller is handed its tail *without* a leading slash, which
440
547
  // `/*` does not match, so a nested fallback matched nothing — empty
441
548
  // params, no tail, and its own children never routed.
549
+ const {pathname} = location;
442
550
  const tail = pathname.startsWith('/') ? pathname.slice(1) : pathname;
443
551
  return {route: {...this.fallback, path: '/*'}, params: {0: tail}, tail};
444
552
  }