@grafctory/clay 0.0.0-stage → 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/dist/router.js ADDED
@@ -0,0 +1,828 @@
1
+ /*
2
+ * Copyright © 2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * Client-side routing.
18
+ *
19
+ * Maps the browser location to the view a page renders, keeping the two in step: {@link Router} tracks the current
20
+ * route as it changes, whether a component navigates, a local link is followed or the browser moves through its
21
+ * history, and {@link Routes} renders the view for it wherever the page layout places it. Components below the router
22
+ * read the current route and the title of the page on show, and navigate, without being handed any of them.
23
+ *
24
+ * Routes are root-relative location paths such as `/users/123`, so the site has to serve the app page for every one.
25
+ *
26
+ * # Route Tables
27
+ *
28
+ * {@link Routes} selects the view through a table mapping route patterns to views or redirections:
29
+ *
30
+ * ```tsx
31
+ * <Routes>{{
32
+ * "/": <Home/>,
33
+ * "/users/": <Users/>,
34
+ * "/people/:id": "/users/:id",
35
+ * "*": <NotFound/>
36
+ * }}</Routes>
37
+ * ```
38
+ *
39
+ * A route is handled by the first pattern it matches, in table order, so specific patterns go before the general ones
40
+ * they overlap. The query and the hash of a route never take part in matching, and a route matching no pattern is
41
+ * rejected, unless an enclosing table declares a catch-all the table inherits, as described under *Sections*.
42
+ *
43
+ * # Route Patterns
44
+ *
45
+ * A pattern other than the catch-all starts with `/`, and every pattern is matched against the whole route:
46
+ *
47
+ * | Pattern | Kind | Matches | Section sees |
48
+ * |---------------------|-----------|---------------------------|--------------|
49
+ * | `/` | root | `/` alone | `/` |
50
+ * | `/section/page` | exact | `/section/page` alone | `/` |
51
+ * | `/section/:slug` | exact | `/section/{slug}` | `/` |
52
+ * | `/section/` | subtree | `/section/` | `/` |
53
+ * | | | `/section/{path}` | `/{path}` |
54
+ * | `/section/;view` | annexed | `/section/;view` alone | `/` |
55
+ * | `/section/:slug;v` | annexed | `/section/{slug};v` alone | `/` |
56
+ * | `*` | catch-all | any route | the route |
57
+ *
58
+ * - **Named steps**: `:slug` standing for a whole path step matches any non-empty step, where `slug` is a sequence of
59
+ * word characters: `/users/:id` matches `/users/123`, but neither `/users/` nor `/users/123/posts`
60
+ * - **Subtrees**: a pattern ending with `/`, except the root `/`, matches the route up to it and every route below it
61
+ * - **Annexes**: a pattern ending with a non-empty annex, as `/;info`, `/page;info` or `/section/;info`, matches
62
+ * the route only while it carries exactly that annex, and never acts as a subtree; a pattern without annex matches
63
+ * whatever annex the route carries, so an annexed pattern goes before the plain pattern it refines
64
+ * - **Catch-all**: `*` matches any route; placed last, it handles the routes the patterns before it leave unhandled,
65
+ * as a not-found view shown within the layout of the section or as a redirection; `*` is rejected within any other
66
+ * pattern, so `/users/*` and `/*` are not glob patterns but invalid ones
67
+ *
68
+ * A view needing the matched steps reads the route with {@link useRoute}.
69
+ *
70
+ * # Redirections
71
+ *
72
+ * A pattern mapped to a route rather than a view moves the location to that route, replacing the current history
73
+ * entry, so going back never lands on the route redirected from. In the target, `:slug` is replaced with the matched
74
+ * step, and a trailing `/` from a subtree pattern carries the route below the subtree along:
75
+ *
76
+ * | Pattern | Target | Route | Moves to |
77
+ * |---------------|--------------|---------------|--------------|
78
+ * | `/people/:id` | `/users/:id` | `/people/123` | `/users/123` |
79
+ * | `/old/` | `/new/` | `/old/a/b` | `/new/a/b` |
80
+ * | `*` | `/` | `/missing` | `/` |
81
+ * | `/;old` | `/;new` | `/;old` | `/;new` |
82
+ * | `/;info` | `/about;` | `/;info` | `/about` |
83
+ *
84
+ * A redirection carries the annex of the route along, unless its target names an annex of its own, which takes its
85
+ * place; a target ending with a bare `;` drops the annex, landing on the route alone.
86
+ *
87
+ * Redirections are followed until a view is reached, and rejected if they lead back to a route already visited.
88
+ *
89
+ * # Annexes
90
+ *
91
+ * A route may carry an annex, an opaque string attached to its last step after a `;`, as in `/courses/;grid` or
92
+ * `/courses/123;lessons`. An annex keeps view state in the location, such as the presentation a view is switched to,
93
+ * where the query is already taken by list filters and the hash by heading anchors.
94
+ *
95
+ * The `;` separator follows the per-segment parameter practice noted in
96
+ * [RFC 3986 §3.3](https://www.rfc-editor.org/rfc/rfc3986#section-3.3), which allows it unencoded within a path step
97
+ * and leaves its meaning to the application; an encoded `%3B` is part of the step, as
98
+ * [RFC 3986 §2.2](https://www.rfc-editor.org/rfc/rfc3986#section-2.2) tells reserved characters and their encodings
99
+ * apart. The annex is confined to the last step, so that the route without it is the plain address of the page on show.
100
+ *
101
+ * The annex takes part in matching only for patterns naming one, as described under *Route Patterns*:
102
+ * {@link useRoute} returns the route without its annex, and {@link useAnnex} the annex alone. As with the query, the
103
+ * view parses the annex itself; a bare `;` carries an empty annex, read as none.
104
+ *
105
+ * On a root or a subtree the annex follows the trailing `/`: `/courses;grid` is the route `/courses`, matched as such
106
+ * rather than as the subtree `/courses/`, so a subtree carries its annex as `/courses/;grid`.
107
+ *
108
+ * A change to the annex alone renders the components reading it again, without mounting the views afresh, so a view
109
+ * switching presentation keeps the state it reached, unless it moves the route to a view of another pattern.
110
+ *
111
+ * A view moves to another annex through a route built from {@link useRoute}, as `${route};table`, rather than through
112
+ * a relative `;table`: [RFC 3986 §5.2.3](https://www.rfc-editor.org/rfc/rfc3986#section-5.2.3) resolves a relative
113
+ * path by replacing the last step of the base, so `;table` sets the annex of a root or a subtree, but moves the
114
+ * route `/courses/123` to `/courses/;table`. The router resolves references as the RFC prescribes, like the
115
+ * browser does, so a link lands on the same page whether followed by the router, opened in a new tab or copied. Being
116
+ * a path, the annexed route leaves the query and the hash behind, so a view keeping its filters across a change of
117
+ * annex restores them from its own state, such as the history state, rather than from the location.
118
+ *
119
+ * # Sections
120
+ *
121
+ * A view may render a nested {@link Routes}, routing what its pattern leaves over as a section of its own, as listed
122
+ * under *Section sees* above: a section declares its sub-routes where it is implemented rather than in the table at
123
+ * the top of the app, and keeps working wherever that table mounts it. Sections nest to any depth, and a view mapped
124
+ * to a subtree handles every route below it, whether or not it renders a nested {@link Routes}.
125
+ *
126
+ * Patterns and redirections within a section are relative to it, starting at its root `/`: under `/users/`, the
127
+ * pattern `/:id` matches `/users/123`, the redirection `/all` moves the location to `/users/all`, and a catch-all
128
+ * redirection to `/` moves it to `/users/`. Components below still read the full route with {@link useRoute} and
129
+ * navigate with {@link useRouter}, so links and navigators keep working unchanged wherever a section is mounted.
130
+ *
131
+ * A section declaring no catch-all inherits the one of the nearest enclosing table declaring one, as if declared
132
+ * there, so a single `*` in the table at the top of the app handles the unknown routes of every section, a view
133
+ * being shown in place of the section, within the layout of the views enclosing it.
134
+ *
135
+ * > [!WARNING]
136
+ * >
137
+ * > An inherited catch-all is resolved **within the section it handles**, not within the table declaring it: a
138
+ * > redirection is relative to the section, like any other redirection declared there. With `"*": "/"` at the top of
139
+ * > the app, an unknown route below `/users/`, such as `/users/123/posts`, moves the location to `/users/`, the root
140
+ * > of the section, and **not** to the home page `/`.
141
+ * >
142
+ * > A section whose unknown routes are to go elsewhere declares a `*` of its own, which takes precedence over the
143
+ * > inherited one; a catch-all redirection to a route the section leaves unhandled is rejected as a redirection loop.
144
+ *
145
+ * @module
146
+ */
147
+ import { isArray, isDefined, isNull, isNumber, isObject, isString, opt } from "@grafctory/core";
148
+ import { tidy } from "@grafctory/core/strings";
149
+ import { createContext, createElement } from "preact";
150
+ import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState } from "preact/hooks";
151
+ import { app } from "./index.js";
152
+ const Wildcard = "*";
153
+ const ActiveAttribute = "active";
154
+ /**
155
+ * The prefix of the `sessionStorage` entries holding the scroll positions of a history entry.
156
+ */
157
+ const PositionsPrefix = "@grafctory/clay/router:positions:";
158
+ /**
159
+ * The time restoring the scroll positions of a history entry waits for its content to grow back (ms).
160
+ */
161
+ const RestoreTimeout = 5000;
162
+ /**
163
+ * The reader input that stops restoring, so a page the reader has taken over is never moved under them.
164
+ */
165
+ const ReaderInput = ["wheel", "touchstart", "pointerdown", "keydown"];
166
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
167
+ /**
168
+ * The routing provided by the enclosing {@link Router}.
169
+ */
170
+ const RouterContext = createContext({
171
+ route: "",
172
+ annex: "",
173
+ place: "",
174
+ navigate: () => { }
175
+ });
176
+ /**
177
+ * The title of the page on show, as returned by {@link useTitle}.
178
+ *
179
+ * Kept apart from the routing, so a change of title renders again only the components reading it.
180
+ */
181
+ const TitleContext = createContext("");
182
+ /**
183
+ * The section opened by the enclosing {@link Routes}.
184
+ */
185
+ const RoutesContext = createContext({
186
+ path: "/",
187
+ wild: undefined
188
+ });
189
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
190
+ /**
191
+ * Tracks the current route.
192
+ *
193
+ * Provides the current route, its annex, the page title and a navigator to the components below it, through
194
+ * {@link useRoute}, {@link useAnnex}, {@link useTitle} and {@link useRouter}. The views render again whenever the
195
+ * route or its annex changes, whether through navigation or browser history; a change of title alone renders again
196
+ * only the components reading it. The {@link Routes} nested below it select the views for the current route, at any
197
+ * depth and wherever the page layout places them, so a layout is free to arrange the views it wraps.
198
+ *
199
+ * The title belongs to the route it was set on. Reaching another route clears it, whether by a link, by browser
200
+ * history or by a navigation naming no title, so the title of the page left behind is never taken for the new one.
201
+ * The view arrived on sets its own title again as it mounts. This also covers browser history, since the browser
202
+ * keeps no title for a history entry. A redirection carries the title along to the route it lands on.
203
+ *
204
+ * > [!IMPORTANT]
205
+ * >
206
+ * > A title is expected to be set by a view that {@link Routes} renders, since such a view mounts afresh on every
207
+ * > route. A component staying mounted across routes, such as a layout wrapping the views, has to set its title again
208
+ * > on every change of route, for instance from an effect depending on {@link useRoute}. Otherwise the title is cleared
209
+ * > on the first navigation away, leaving the document title to the app name alone.
210
+ *
211
+ * A page loaded or reloaded on a fragment is brought to the element the fragment names, if the view holds it on its
212
+ * first render. The browser cannot do this on its own, as it looks for the element before the view is rendered.
213
+ *
214
+ * Going back or forward through the browser history returns the reader to where they were reading. The window gets
215
+ * back the position it had as the entry was left, and so does every box carrying an `id` within the `main` landmark,
216
+ * the landmark included. A box without an `id` opens at its top. A box meant to keep its place, such as the body a list
217
+ * scrolls in, needs an `id` that stays the same each time its view mounts, unlike one generated by `useId`. Restoring
218
+ * waits for content the view loads after landing, so a list grows back to its length before its position is restored.
219
+ * It stops once the reader scrolls, points or presses a key, or after a few seconds, never moving the page under them.
220
+ *
221
+ * Positions are kept per history entry in `sessionStorage`, leaving the history state to the app. Restoring them takes
222
+ * the [Navigation API](https://developer.mozilla.org/docs/Web/API/Navigation_API): browsers lacking it fall back on
223
+ * their own scroll restoring, which brings back the position of the window alone and leaves every box at its top.
224
+ *
225
+ * Takes over plain clicks anywhere in the page, leaving clicks with a modifier key or already handled to the browser:
226
+ *
227
+ * - a link to the same site is followed without reloading the page, unless it points at a fragment of the current
228
+ * page or targets another browsing context through a `target` attribute other than `_self`; a link leading to
229
+ * another route, or back to the current place, then lands the page as a page loaded afresh would, at its top or on
230
+ * the element its fragment names once the view shows it, so the reader is never left halfway down the view they
231
+ * left; the top is the start of the document, of the `main` landmark and of every box scrolling inside it, so an app
232
+ * scrolling its content in a box of its own lands there as well, while a box scrolling outside the landmark, such
233
+ * as a side column, keeps its place; a link changing the query or the annex alone, as a filter or an alternate view
234
+ * does, keeps the reader in place on whatever they were reading before following it
235
+ * - a page landed afresh also moves the focus to its `main` landmark, so a screen reader announces the page arrived
236
+ * on; the landmark takes the focus only if it is focusable, as a `tabindex` of `-1` makes it without adding a tab
237
+ * stop, and may pass it on to an element within itself, such as the box scrolling its content; otherwise the focus
238
+ * is cleared, so the next keystroke never acts on a control of the page left behind
239
+ * - a link to another site opens in a new browsing context
240
+ * - an image outside any link toggles its `active` attribute, which the `@grafctory/skin` stylesheet reads to show it
241
+ * over the whole viewport; an image inside a link is left to the link
242
+ *
243
+ * An enlarged image is restored by another click on it, by `Escape`, or as soon as the focus moves, so a keyboard user
244
+ * never ends up on a control the image covers. Enlarging is a visual convenience over content the image already
245
+ * carries, through its alternative text and the browser zoom, so images are not made reachable from the keyboard.
246
+ *
247
+ * A page mounts a single router, as each one takes over the clicks and keys of the whole page.
248
+ *
249
+ * @param options The router configuration
250
+ *
251
+ * @returns The rendered children
252
+ */
253
+ export function Router({ children }) {
254
+ const [{ place, title }, setStatus] = useState(() => ({
255
+ place: here(),
256
+ title: ""
257
+ }));
258
+ const { route, annex, query } = parse(place);
259
+ // document.title lives outside the rendered tree, so it follows the title once rendered
260
+ useLayoutEffect(() => {
261
+ document.title = [title, app.name].filter(Boolean).join(" | ");
262
+ }, [title]);
263
+ /*
264
+ * A followed link lands the page once the view it leads to has rendered, which is when the element its fragment
265
+ * names exists; the landing is a fresh object every time, so following the same link twice lands twice.
266
+ */
267
+ const [landing, setLanding] = useState();
268
+ /*
269
+ * A history traversal restores the positions of the entry arrived on once its view has rendered, since the boxes
270
+ * left behind are gone; a fresh object every time, so traversing to the same entry twice restores twice.
271
+ */
272
+ const [traversal, setTraversal] = useState();
273
+ /*
274
+ * A page loaded on a fragment is brought to the element it names after the first render: the browser looks for
275
+ * that element while the document loads, before the view exists, and on a reload restores the old position instead.
276
+ */
277
+ useEffect(() => {
278
+ fragment(location.hash)?.scrollIntoView();
279
+ }, []);
280
+ useEffect(() => {
281
+ if (landing) {
282
+ const target = fragment(landing.hash);
283
+ const main = document.querySelector("main");
284
+ const boxes = main ? [main, ...main.querySelectorAll("*")] : []; // apps may scroll content in their own box
285
+ window.scrollTo(0, 0);
286
+ boxes
287
+ .filter(box => box.scrollTop !== 0 || box.scrollLeft !== 0)
288
+ .forEach(box => box.scrollTo(0, 0));
289
+ target?.scrollIntoView();
290
+ /*
291
+ * The focus lands on the content, or nowhere, rather than on a control of the page left behind. A landmark is
292
+ * focusable through its tabindex alone, so one without it leaves a control it holds to be cleared as well.
293
+ */
294
+ const content = main?.hasAttribute("tabindex") ? main : undefined;
295
+ content?.focus({ preventScroll: true });
296
+ if (!content?.contains(document.activeElement) && document.activeElement instanceof HTMLElement) {
297
+ document.activeElement.blur();
298
+ }
299
+ else {
300
+ // the focus already rests on the content, or on nothing
301
+ }
302
+ }
303
+ else {
304
+ // no link followed yet
305
+ }
306
+ }, [landing]);
307
+ useEffect(() => traversal ? reposition(recall(traversal.key)) : undefined, [traversal]);
308
+ useEffect(() => {
309
+ function click(event) {
310
+ const plain = !event.altKey
311
+ && !event.ctrlKey
312
+ && !event.metaKey
313
+ && !event.shiftKey
314
+ && !event.defaultPrevented;
315
+ const origin = event.target instanceof Element ? event.target : undefined;
316
+ const anchor = origin?.closest("a");
317
+ const image = origin?.closest("img");
318
+ if (plain && anchor
319
+ && !anchor.getAttribute("href")?.startsWith("#")
320
+ && (anchor.getAttribute("target") ?? "_self") === "_self") {
321
+ event.preventDefault();
322
+ follow(anchor.href);
323
+ }
324
+ else if (plain && image && !anchor) {
325
+ toggle(image);
326
+ }
327
+ else {
328
+ // modified, already handled and unrelated clicks keep their default behaviour
329
+ }
330
+ function follow(href) {
331
+ const route = href.startsWith(app.root) ? href.substring(app.root.length - 1) : "";
332
+ if (route) {
333
+ const before = here();
334
+ try {
335
+ history.pushState(undefined, document.title, route);
336
+ }
337
+ finally {
338
+ update(true);
339
+ if (lands(before, here())) {
340
+ setLanding({ hash: new URL(href).hash });
341
+ }
342
+ else {
343
+ // a change of query or annex alone keeps the reader in place
344
+ }
345
+ }
346
+ }
347
+ else {
348
+ window.open(href, "_blank");
349
+ }
350
+ }
351
+ function toggle(image) {
352
+ if (image.getAttribute(ActiveAttribute)) {
353
+ image.removeAttribute(ActiveAttribute);
354
+ }
355
+ else {
356
+ image.setAttribute(ActiveAttribute, "true");
357
+ }
358
+ }
359
+ }
360
+ function keydown(event) {
361
+ const images = enlarged();
362
+ if (event.key === "Escape" && images.length > 0) {
363
+ event.preventDefault();
364
+ restore(images);
365
+ }
366
+ else {
367
+ // keys the router has no use for keep their default behaviour
368
+ }
369
+ }
370
+ function focusin() {
371
+ restore(enlarged()); // the focus never lands on a control hidden behind an enlarged image
372
+ }
373
+ function enlarged() {
374
+ return document.querySelectorAll(`img[${ActiveAttribute}]`);
375
+ }
376
+ function restore(images) {
377
+ images.forEach(image => image.removeAttribute(ActiveAttribute)); // DOM side effect, nothing to collect
378
+ }
379
+ function leave(event) {
380
+ const key = navigations()?.currentEntry?.key;
381
+ if (event.navigationType === "replace") {
382
+ // the reader stays on the entry, maybe on a view just landed and still at its top: its positions stand
383
+ }
384
+ else if (isDefined(key)) {
385
+ store(key, measure());
386
+ }
387
+ else {
388
+ // no entry to keep the positions for
389
+ }
390
+ }
391
+ function traverse() {
392
+ const key = navigations()?.currentEntry?.key;
393
+ update(true);
394
+ if (isDefined(key)) {
395
+ setTraversal({ key });
396
+ }
397
+ else {
398
+ // no entry to recall the positions of
399
+ }
400
+ }
401
+ update(true); // catches up with a location changed before the listeners were in place
402
+ navigations()?.addEventListener("navigate", leave);
403
+ window.addEventListener("popstate", traverse);
404
+ window.addEventListener("click", click);
405
+ window.addEventListener("keydown", keydown);
406
+ window.addEventListener("focusin", focusin);
407
+ return () => {
408
+ navigations()?.removeEventListener("navigate", leave);
409
+ window.removeEventListener("popstate", traverse);
410
+ window.removeEventListener("click", click);
411
+ window.removeEventListener("keydown", keydown);
412
+ window.removeEventListener("focusin", focusin);
413
+ };
414
+ }, []);
415
+ const navigate = useCallback(entry => {
416
+ const { route, title, state, replace } = isString(entry)
417
+ ? { route: entry, title: undefined, state: undefined, replace: false }
418
+ : entry;
419
+ const $route = opt(route, route => new URL(route, location.href).href, () => location.href);
420
+ const $title = opt(title, plain);
421
+ const $state = state === undefined
422
+ ? history.state
423
+ : state;
424
+ const moved = $route !== location.href;
425
+ try {
426
+ history[replace || !moved ? "replaceState" : "pushState"]($state, "", $route);
427
+ }
428
+ finally {
429
+ update(moved, $title);
430
+ }
431
+ }, []);
432
+ const routing = useMemo(() => ({
433
+ route, annex, place: `${route}${query}`, navigate
434
+ }), [route, annex, query, navigate]); // a change of title alone leaves the readers of the route alone
435
+ return createElement(RouterContext.Provider, {
436
+ value: routing // the annex alone leaves the views mounted
437
+ }, createElement(TitleContext.Provider, {
438
+ value: title
439
+ }, children));
440
+ /**
441
+ * Brings the router up to date with the browser location and the page title.
442
+ *
443
+ * Renders again only if either actually changed.
444
+ *
445
+ * @param moved True to catch up with the browser location; false to keep the place, since a title or a state set
446
+ * alone leaves a query replaced outside the router through `history.replaceState` in place
447
+ * @param title The title of the page; if undefined, the current title on the same route, none on another one
448
+ */
449
+ function update(moved, title) {
450
+ setStatus(status => {
451
+ const place = moved ? here() : status.place;
452
+ const named = title ?? (parse(place).route === parse(status.place).route ? status.title : "");
453
+ return place === status.place && named === status.title ? status : { place, title: named };
454
+ });
455
+ }
456
+ /**
457
+ * Identifies the place the browser location stands at.
458
+ *
459
+ * @returns The location path and query, the hash left out as it never moves the page to another view
460
+ */
461
+ function here() {
462
+ return `${location.pathname}${location.search}`;
463
+ }
464
+ }
465
+ /**
466
+ * Renders the view for the current route.
467
+ *
468
+ * Selects the view through a table of route patterns, moving the location along any redirection on the way, and
469
+ * renders it wherever the page layout places it; within a view, a nested table routes what the view pattern leaves
470
+ * over as a section of its own. Patterns, redirections and sections are described in the module overview.
471
+ *
472
+ * Renders below a {@link Router}, which keeps sole charge of the location, the history and the page clicks.
473
+ *
474
+ * Renders nothing during a redirection, so neither it nor a nested {@link Routes} shows a route on its way out.
475
+ *
476
+ * Mounts the view afresh whenever a navigation moves the location, the query included, so that a view reads the query
477
+ * as it mounts: a link from `/courses/` to `/courses/?~label=art` mounts the catalogue again with the new criteria. A
478
+ * query replaced through `history.replaceState` outside the router, as a view recording its own state in the location
479
+ * does, leaves the view mounted with the state it reached, until the next navigation moves the location again. A
480
+ * navigation changing the annex alone leaves the view mounted too, rendering again only what reads the annex.
481
+ *
482
+ * @param options The routes configuration
483
+ *
484
+ * @returns The view for the current route
485
+ *
486
+ * @throws {@link !Error Error} If a pattern other than `*` lacks a leading `/`, holds `*`, or holds `;` anywhere but
487
+ * before a non-empty annex on its last step, as soon as the table renders, whatever the route
488
+ * @throws {@link !Error Error} If the route, or one it redirects to, matches no pattern and no enclosing catch-all
489
+ * @throws {@link !Error Error} If redirections lead back to a route already visited
490
+ */
491
+ export function Routes({ children }) {
492
+ const { route, annex, place, navigate } = useContext(RouterContext);
493
+ const { path, wild } = useContext(RoutesContext);
494
+ const title = useContext(TitleContext);
495
+ const table = isDefined(children[Wildcard]) || !isDefined(wild)
496
+ ? children
497
+ : { ...children, [Wildcard]: wild }; // the inherited catch-all goes last, as if declared here
498
+ const invalid = Object.keys(table).find(glob => glob !== Wildcard && !/^\/[^*;]*(?:;[^*/]+)?$/.test(glob) // rooted, no wildcard, an annex on the last step only
499
+ );
500
+ if (isDefined(invalid)) {
501
+ throw new Error(`invalid route pattern <${invalid}>`);
502
+ }
503
+ const section = path.endsWith("/") ? route.slice(path.length - 1) : "/"; // the route as the table sees it
504
+ const origin = attach(section, annex);
505
+ const settled = settle(origin);
506
+ const target = settled === origin ? undefined : relocate(split(settled));
507
+ const hit = lookup(origin);
508
+ useLayoutEffect(() => {
509
+ if (isDefined(target)) {
510
+ navigate({ route: target, title, replace: true }); // replacing the entry, so going back never lands on it
511
+ }
512
+ else {
513
+ // the location already carries the route on show
514
+ }
515
+ }, [target, title, navigate]);
516
+ if (isDefined(target)) {
517
+ return null;
518
+ }
519
+ else if (isDefined(hit)) {
520
+ const tail = hit.steps.groups?.$;
521
+ const opened = isDefined(tail) ? route.slice(0, route.length - tail.length + 1) // up to the route below the subtree
522
+ : hit.glob === Wildcard ? path
523
+ : route;
524
+ return createElement(RoutesContext.Provider, {
525
+ key: place, // a navigation changing the query alone mounts the view afresh
526
+ value: { path: opened, wild: table[Wildcard] }
527
+ }, hit.entry);
528
+ }
529
+ else {
530
+ throw new Error(`unhandled route ${section}`);
531
+ }
532
+ /**
533
+ * Locates a section route, along with the annex it carries, within the whole route.
534
+ *
535
+ * @returns The whole route the section route stands for, carrying its annex
536
+ */
537
+ function relocate({ route, annex }) {
538
+ return attach(route === "/" ? path : `${path.replace(/\/$/, "")}${route}`, annex);
539
+ }
540
+ /**
541
+ * Attaches an annex to the last step of a route.
542
+ *
543
+ * @returns The route carrying the annex, or the route alone for an empty annex
544
+ */
545
+ function attach(route, annex) {
546
+ return annex ? `${route};${annex}` : route;
547
+ }
548
+ /**
549
+ * Follows the redirections of the table from a section route carrying its annex.
550
+ *
551
+ * @param section The section route to start from
552
+ * @param trail The routes already followed to reach `section`, a loop being detected as a return to one of them
553
+ *
554
+ * @returns The route the redirections lead to, the section route itself if it is not redirected
555
+ *
556
+ * @throws {@link !Error Error} If the redirections lead back to a route already followed
557
+ */
558
+ function settle(section, trail = []) {
559
+ const visited = [...trail, section];
560
+ const route = redirect(section);
561
+ if (!isDefined(route)) {
562
+ return section;
563
+ }
564
+ else if (visited.includes(route)) {
565
+ throw new Error(`redirection loop <${visited.join(",")}>`);
566
+ }
567
+ else {
568
+ return settle(route, visited);
569
+ }
570
+ }
571
+ /**
572
+ * Resolves the redirection the table defines for a section route carrying its annex.
573
+ *
574
+ * @returns The route the section route is redirected to, carrying the annex the target names or else the one of
575
+ * the section route; undefined if the table maps the section route to a view or matches no pattern for it
576
+ */
577
+ function redirect(section) {
578
+ const hit = lookup(section);
579
+ if (isDefined(hit) && isString(hit.entry)) {
580
+ const { entry, steps } = hit;
581
+ const tail = steps.groups?.$;
582
+ const filled = entry.replace(/(?<=\/):(\w+)(?=[/;?#]|$)/g, (_, step) => steps.groups?.[step] ?? "");
583
+ const { route, annex } = split(filled);
584
+ return attach(isDefined(tail) && route.endsWith("/") ? `${route.slice(0, -1)}${tail}` : route, route === filled ? split(section).annex : annex // a target with no annex keeps the current one
585
+ );
586
+ }
587
+ else {
588
+ return undefined;
589
+ }
590
+ }
591
+ /**
592
+ * Looks up the first pattern of the table matching a section route carrying its annex, in table order.
593
+ *
594
+ * @returns The matching pattern, its entry and the steps it captured, or undefined if no pattern matches
595
+ */
596
+ function lookup(section) {
597
+ const { route, annex } = split(section);
598
+ return Object.entries(table).flatMap(([glob, entry]) => {
599
+ const { route: stem, annex: label } = split(glob);
600
+ const steps = label && label !== annex ? null : pattern(stem, !label).exec(route);
601
+ return isNull(steps) ? [] : [{ glob, entry, steps }];
602
+ }).at(0);
603
+ /**
604
+ * Compiles a route pattern, capturing named steps under their name and the route below a subtree under `$`.
605
+ *
606
+ * @param glob The route pattern without its annex
607
+ * @param open True if a pattern ending with `/` is a subtree, false for a pattern naming an annex
608
+ */
609
+ function pattern(glob, open) {
610
+ const subtree = open && glob.length > 1 && glob.endsWith("/");
611
+ const steps = subtree ? glob.slice(0, -1) : glob;
612
+ return glob === Wildcard ? /^.*$/ : new RegExp(`^${steps
613
+ .replace(/[.*+?^${}()|[\]\\]/g, "\\$&") // escape regex metacharacters
614
+ .replace(/(?<=\/):(\w+)(?=\/|$)/g, "(?<$1>[^/]+)") // named steps
615
+ }${subtree ? "(?<$>/.*)" : "(?:[?#].*)?"}$`); // the route below a subtree, or the ignored query and hash
616
+ }
617
+ }
618
+ }
619
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
620
+ /**
621
+ * Retrieves the route navigator.
622
+ *
623
+ * The navigator stays the same for as long as the {@link Router} providing it is mounted, so a component reading it
624
+ * renders again only as its own state requires, and a handler may keep it across navigations.
625
+ *
626
+ * @returns The navigator provided by the innermost enclosing {@link Router}; a no-op outside any router
627
+ */
628
+ export function useRouter() {
629
+ return useContext(RouterContext).navigate;
630
+ }
631
+ /**
632
+ * Retrieves the current route.
633
+ *
634
+ * Renders the component again whenever the route changes, whether through navigation or browser history.
635
+ *
636
+ * @returns The current route, as carried by the location path without its annex; an empty string outside any router
637
+ */
638
+ export function useRoute() {
639
+ return useContext(RouterContext).route;
640
+ }
641
+ /**
642
+ * Retrieves the annex of the current route.
643
+ *
644
+ * Renders the component again whenever the annex changes, whether through navigation or browser history. The views
645
+ * below the router stay mounted, so a view switching presentation keeps the state it reached.
646
+ *
647
+ * @returns The annex after the `;` on the last step of the current route, as it appears in the location path and left
648
+ * to the caller to parse; an empty string if the route carries none, or outside any router
649
+ */
650
+ export function useAnnex() {
651
+ return useContext(RouterContext).annex;
652
+ }
653
+ /**
654
+ * Retrieves the title of the page on show.
655
+ *
656
+ * Renders the component again whenever the title changes, whether set through the navigator, alone or along with a
657
+ * route, or cleared on reaching another route. Lets a component shared by every page, such as a feedback or share
658
+ * action, name the page it is shown on without being handed the title the page already gave the navigator.
659
+ *
660
+ * @returns The title last passed to the navigator for the current route, tidied and without the {@link app} name; an
661
+ * empty string if none was set, if it equals the app name, or outside any router
662
+ */
663
+ export function useTitle() {
664
+ return useContext(TitleContext);
665
+ }
666
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
667
+ /**
668
+ * Checks whether following a link lands the reader afresh on the page it leads to.
669
+ *
670
+ * Links to another route or back to the current place land afresh; links changing only the query or annex do not.
671
+ *
672
+ * @param before The place the link was followed from, path and query
673
+ * @param after The place the link led to
674
+ *
675
+ * @returns true if the route changed, or if neither the query nor the annex changed; false otherwise
676
+ */
677
+ function lands(before, after) {
678
+ const from = parse(before);
679
+ const to = parse(after);
680
+ return from.route !== to.route || from.query === to.query && from.annex === to.annex;
681
+ }
682
+ /**
683
+ * Tidies a title as the page on show is named.
684
+ *
685
+ * @param title The title to tidy
686
+ *
687
+ * @returns The tidied title, or an empty string for a title equal to the {@link app} name
688
+ */
689
+ function plain(title) {
690
+ const tidied = tidy(title);
691
+ return tidied === app.name ? "" : tidied;
692
+ }
693
+ /**
694
+ * Splits a place into its route, the annex its last step carries and its query.
695
+ *
696
+ * @param place The location path and query
697
+ *
698
+ * @returns The route without the annex, the annex, and the query with its leading `?`, empty if none
699
+ */
700
+ function parse(place) {
701
+ return { ...split(place.replace(/\?.*$/, "")), query: place.replace(/^[^?]*/, "") };
702
+ }
703
+ /**
704
+ * Splits a route into its steps and the annex its last step carries.
705
+ *
706
+ * @param route The route to split, without any query
707
+ *
708
+ * @returns The route without the annex, and the annex following the first `;` of the last step, empty if none
709
+ */
710
+ function split(route) {
711
+ const [, steps = route, annex = ""] = /^(.*?\/[^/;]*)(?:;([^/]*))?$/.exec(route) ?? [];
712
+ return { route: steps, annex };
713
+ }
714
+ /**
715
+ * Locates the element a fragment names.
716
+ *
717
+ * @param hash The fragment with its leading `#`, empty if none
718
+ *
719
+ * @returns The element the fragment names, or null if the fragment is empty or the document holds no such element
720
+ */
721
+ function fragment(hash) {
722
+ return hash ? document.getElementById(decodeURIComponent(hash.slice(1))) : null;
723
+ }
724
+ /**
725
+ * Retrieves the Navigation API of the browser.
726
+ *
727
+ * @returns The navigation of the window, or undefined if the browser lacks the API
728
+ */
729
+ function navigations() {
730
+ return typeof navigation === "undefined" ? undefined : navigation;
731
+ }
732
+ /**
733
+ * Measures the scroll positions the reader has reached.
734
+ *
735
+ * @returns The positions of the window and of the boxes carrying an `id` within the `main` landmark, the landmark
736
+ * itself included, leaving out those still at their origin, which a traversal has no need to restore
737
+ */
738
+ function measure() {
739
+ const main = document.querySelector("main");
740
+ const boxes = main ? [main, ...main.querySelectorAll("[id]")] : [];
741
+ const positions = [
742
+ ["", [window.scrollX, window.scrollY]],
743
+ ...boxes.filter(box => box.id).map((box) => [box.id, [box.scrollLeft, box.scrollTop]])
744
+ ];
745
+ return Object.fromEntries(positions.filter(([, [left, top]]) => left !== 0 || top !== 0));
746
+ }
747
+ /**
748
+ * Keeps the scroll positions of a history entry.
749
+ *
750
+ * Positions are a convenience, so unavailable or full storage leaves them unkept rather than failing navigation.
751
+ *
752
+ * @param key The key of the history entry
753
+ * @param positions The positions to keep; an empty set removes the ones kept before
754
+ */
755
+ function store(key, positions) {
756
+ try {
757
+ if (Object.keys(positions).length > 0) {
758
+ sessionStorage.setItem(`${PositionsPrefix}${key}`, JSON.stringify(positions));
759
+ }
760
+ else {
761
+ sessionStorage.removeItem(`${PositionsPrefix}${key}`);
762
+ }
763
+ }
764
+ catch {
765
+ // storage unavailable or full
766
+ }
767
+ }
768
+ /**
769
+ * Recalls the scroll positions of a history entry.
770
+ *
771
+ * @param key The key of the history entry
772
+ *
773
+ * @returns The positions kept for the entry; none if no well-formed positions are kept or storage is unavailable
774
+ */
775
+ function recall(key) {
776
+ try {
777
+ const positions = JSON.parse(sessionStorage.getItem(`${PositionsPrefix}${key}`) ?? "{}");
778
+ return isObject(positions, offsets => isArray(offsets, [isNumber, isNumber])) ? positions : {};
779
+ }
780
+ catch {
781
+ return {};
782
+ }
783
+ }
784
+ /**
785
+ * Restores scroll positions as the content they were reached on grows back.
786
+ *
787
+ * Applies the positions at once and again whenever the content changes, until every one is reached, the reader takes
788
+ * over through {@link ReaderInput}, or {@link RestoreTimeout} elapses with the content still too short to reach them.
789
+ *
790
+ * @param positions The positions to restore
791
+ *
792
+ * @returns A function stopping the restore before it ends on its own
793
+ */
794
+ function reposition(positions) {
795
+ const observer = new MutationObserver(attempt);
796
+ const timer = setTimeout(stop, RestoreTimeout);
797
+ observer.observe(document.body, { childList: true, subtree: true });
798
+ ReaderInput.forEach(type => window.addEventListener(type, stop, { capture: true, passive: true }));
799
+ attempt();
800
+ return stop;
801
+ function attempt() {
802
+ const reached = Object.entries(positions).map(([box, offsets]) => place(box, offsets));
803
+ if (reached.every(Boolean)) {
804
+ stop();
805
+ }
806
+ else {
807
+ // waiting for the content to grow back
808
+ }
809
+ }
810
+ function place(box, [left, top]) {
811
+ const [x, y] = box ? element(document.getElementById(box)) : viewport();
812
+ return Math.abs(x - left) < 1 && Math.abs(y - top) < 1; // offsets may be fractional on high density displays
813
+ function viewport() {
814
+ window.scrollTo(left, top);
815
+ return [window.scrollX, window.scrollY];
816
+ }
817
+ function element(target) {
818
+ target?.scrollTo(left, top);
819
+ return target ? [target.scrollLeft, target.scrollTop] : [Number.NaN, Number.NaN]; // a box not rendered yet
820
+ }
821
+ }
822
+ function stop() {
823
+ observer.disconnect();
824
+ clearTimeout(timer);
825
+ ReaderInput.forEach(type => window.removeEventListener(type, stop, { capture: true }));
826
+ }
827
+ }
828
+ //# sourceMappingURL=router.js.map