@grafctory/clay 0.0.0-stage → 0.4.1
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/LICENSE +201 -0
- package/README.md +48 -2
- package/dist/asset.d.ts +24 -0
- package/dist/asset.d.ts.map +1 -0
- package/dist/asset.js +69 -0
- package/dist/asset.js.map +1 -0
- package/dist/board.d.ts +176 -0
- package/dist/board.d.ts.map +1 -0
- package/dist/board.js +222 -0
- package/dist/board.js.map +1 -0
- package/dist/fetch.d.ts +70 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +97 -0
- package/dist/fetch.js.map +1 -0
- package/dist/focus.d.ts +70 -0
- package/dist/focus.d.ts.map +1 -0
- package/dist/focus.js +65 -0
- package/dist/focus.js.map +1 -0
- package/dist/index.d.ts +78 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +137 -0
- package/dist/index.js.map +1 -0
- package/dist/model.d.ts +110 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +148 -0
- package/dist/model.js.map +1 -0
- package/dist/router.d.ts +206 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +810 -0
- package/dist/router.js.map +1 -0
- package/dist/storage.d.ts +38 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +83 -0
- package/dist/storage.js.map +1 -0
- package/dist/transfer.d.ts +402 -0
- package/dist/transfer.d.ts.map +1 -0
- package/dist/transfer.js +732 -0
- package/dist/transfer.js.map +1 -0
- package/package.json +92 -4
package/dist/router.js
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
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; otherwise the focus is cleared, so the next keystroke never acts on a control of the page left behind
|
|
238
|
+
* - a link to another site opens in a new browsing context
|
|
239
|
+
* - an image outside any link toggles its `active` attribute, which the `@grafctory/skin` stylesheet reads to show it
|
|
240
|
+
* over the whole viewport; an image inside a link is left to the link
|
|
241
|
+
*
|
|
242
|
+
* An enlarged image is restored by another click on it, by `Escape`, or as soon as the focus moves, so a keyboard user
|
|
243
|
+
* never ends up on a control the image covers. Enlarging is a visual convenience over content the image already
|
|
244
|
+
* carries, through its alternative text and the browser zoom, so images are not made reachable from the keyboard.
|
|
245
|
+
*
|
|
246
|
+
* A page mounts a single router, as each one takes over the clicks and keys of the whole page.
|
|
247
|
+
*
|
|
248
|
+
* @param options The router configuration
|
|
249
|
+
*
|
|
250
|
+
* @returns The rendered children
|
|
251
|
+
*/
|
|
252
|
+
export function Router({ children }) {
|
|
253
|
+
const [{ place, title }, setStatus] = useState(() => ({
|
|
254
|
+
place: here(),
|
|
255
|
+
title: ""
|
|
256
|
+
}));
|
|
257
|
+
const { route, annex, query } = parse(place);
|
|
258
|
+
const sync = () => update(true);
|
|
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
|
+
// the focus lands on the content, or nowhere, rather than on a control of the page left behind
|
|
291
|
+
main?.focus({ preventScroll: true });
|
|
292
|
+
if (document.activeElement !== main && document.activeElement instanceof HTMLElement) {
|
|
293
|
+
document.activeElement.blur();
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
// the focus already rests on the content, or on nothing
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}, [landing]);
|
|
300
|
+
useEffect(() => traversal ? reposition(recall(traversal.key)) : undefined, [traversal]);
|
|
301
|
+
useEffect(() => {
|
|
302
|
+
function click(event) {
|
|
303
|
+
const plain = !event.altKey
|
|
304
|
+
&& !event.ctrlKey
|
|
305
|
+
&& !event.metaKey
|
|
306
|
+
&& !event.shiftKey
|
|
307
|
+
&& !event.defaultPrevented;
|
|
308
|
+
const origin = event.target instanceof Element ? event.target : undefined;
|
|
309
|
+
const anchor = origin?.closest("a");
|
|
310
|
+
const image = origin?.closest("img");
|
|
311
|
+
if (plain && anchor
|
|
312
|
+
&& !anchor.getAttribute("href")?.startsWith("#")
|
|
313
|
+
&& (anchor.getAttribute("target") ?? "_self") === "_self") {
|
|
314
|
+
event.preventDefault();
|
|
315
|
+
follow(anchor.href);
|
|
316
|
+
}
|
|
317
|
+
else if (plain && image && !anchor) {
|
|
318
|
+
toggle(image);
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
// modified, already handled and unrelated clicks keep their default behaviour
|
|
322
|
+
}
|
|
323
|
+
function follow(href) {
|
|
324
|
+
const route = href.startsWith(app.root) ? href.substring(app.root.length - 1) : "";
|
|
325
|
+
if (route) {
|
|
326
|
+
const before = here();
|
|
327
|
+
try {
|
|
328
|
+
history.pushState(undefined, document.title, route);
|
|
329
|
+
}
|
|
330
|
+
finally {
|
|
331
|
+
sync();
|
|
332
|
+
if (lands(before, here())) {
|
|
333
|
+
setLanding({ hash: new URL(href).hash });
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
window.open(href, "_blank");
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function toggle(image) {
|
|
342
|
+
if (image.getAttribute(ActiveAttribute)) {
|
|
343
|
+
image.removeAttribute(ActiveAttribute);
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
image.setAttribute(ActiveAttribute, "true");
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function keydown(event) {
|
|
351
|
+
const images = enlarged();
|
|
352
|
+
if (event.key === "Escape" && images.length > 0) {
|
|
353
|
+
event.preventDefault();
|
|
354
|
+
restore(images);
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
// keys the router has no use for keep their default behaviour
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function focusin() {
|
|
361
|
+
restore(enlarged()); // the focus never lands on a control hidden behind an enlarged image
|
|
362
|
+
}
|
|
363
|
+
function enlarged() {
|
|
364
|
+
return document.querySelectorAll(`img[${ActiveAttribute}]`);
|
|
365
|
+
}
|
|
366
|
+
function restore(images) {
|
|
367
|
+
images.forEach(image => image.removeAttribute(ActiveAttribute)); // DOM side effect, nothing to collect
|
|
368
|
+
}
|
|
369
|
+
function leave(event) {
|
|
370
|
+
const key = navigations()?.currentEntry?.key;
|
|
371
|
+
if (event.navigationType === "replace") {
|
|
372
|
+
// the reader stays on the entry, maybe on a view just landed and still at its top: its positions stand
|
|
373
|
+
}
|
|
374
|
+
else if (isDefined(key)) {
|
|
375
|
+
store(key, measure());
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
// no entry to keep the positions for
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
function traverse() {
|
|
382
|
+
const key = navigations()?.currentEntry?.key;
|
|
383
|
+
sync();
|
|
384
|
+
if (isDefined(key)) {
|
|
385
|
+
setTraversal({ key });
|
|
386
|
+
}
|
|
387
|
+
else {
|
|
388
|
+
// no entry to recall the positions of
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
sync(); // catches up with a location changed before the listeners were in place
|
|
392
|
+
navigations()?.addEventListener("navigate", leave);
|
|
393
|
+
window.addEventListener("popstate", traverse);
|
|
394
|
+
window.addEventListener("click", click);
|
|
395
|
+
window.addEventListener("keydown", keydown);
|
|
396
|
+
window.addEventListener("focusin", focusin);
|
|
397
|
+
return () => {
|
|
398
|
+
navigations()?.removeEventListener("navigate", leave);
|
|
399
|
+
window.removeEventListener("popstate", traverse);
|
|
400
|
+
window.removeEventListener("click", click);
|
|
401
|
+
window.removeEventListener("keydown", keydown);
|
|
402
|
+
window.removeEventListener("focusin", focusin);
|
|
403
|
+
};
|
|
404
|
+
}, []);
|
|
405
|
+
const navigate = useCallback(entry => {
|
|
406
|
+
const { route, title, state, replace } = isString(entry)
|
|
407
|
+
? { route: entry, title: undefined, state: undefined, replace: false }
|
|
408
|
+
: entry;
|
|
409
|
+
const $route = opt(route, route => new URL(route, location.href).href, () => location.href);
|
|
410
|
+
const $title = opt(title, plain);
|
|
411
|
+
const $state = state === undefined
|
|
412
|
+
? history.state
|
|
413
|
+
: state;
|
|
414
|
+
const moved = $route !== location.href;
|
|
415
|
+
try {
|
|
416
|
+
history[replace || !moved ? "replaceState" : "pushState"]($state, "", $route);
|
|
417
|
+
}
|
|
418
|
+
finally {
|
|
419
|
+
update(moved, $title);
|
|
420
|
+
}
|
|
421
|
+
}, []);
|
|
422
|
+
const routing = useMemo(() => ({
|
|
423
|
+
route, annex, place: `${route}${query}`, navigate
|
|
424
|
+
}), [route, annex, query, navigate]); // a change of title alone leaves the readers of the route alone
|
|
425
|
+
return createElement(RouterContext.Provider, {
|
|
426
|
+
value: routing // the annex alone leaves the views mounted
|
|
427
|
+
}, createElement(TitleContext.Provider, {
|
|
428
|
+
value: title
|
|
429
|
+
}, children));
|
|
430
|
+
/**
|
|
431
|
+
* Brings the router up to date with the browser location and the page title.
|
|
432
|
+
*
|
|
433
|
+
* Renders again only if either actually changed.
|
|
434
|
+
*
|
|
435
|
+
* @param moved True to catch up with the browser location; false to keep the place, since a title or a state set
|
|
436
|
+
* alone leaves a query replaced outside the router through `history.replaceState` in place
|
|
437
|
+
* @param title The title of the page; if undefined, the current title on the same route, none on another one
|
|
438
|
+
*/
|
|
439
|
+
function update(moved, title) {
|
|
440
|
+
setStatus(status => {
|
|
441
|
+
const place = moved ? here() : status.place;
|
|
442
|
+
const named = title ?? (parse(place).route === parse(status.place).route ? status.title : "");
|
|
443
|
+
return place === status.place && named === status.title ? status : { place, title: named };
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Identifies the place the browser location stands at.
|
|
448
|
+
*
|
|
449
|
+
* @returns The location path and query, the hash left out as it never moves the page to another view
|
|
450
|
+
*/
|
|
451
|
+
function here() {
|
|
452
|
+
return `${location.pathname}${location.search}`;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Renders the view for the current route.
|
|
457
|
+
*
|
|
458
|
+
* Selects the view through a table of route patterns, moving the location along any redirection on the way, and
|
|
459
|
+
* renders it wherever the page layout places it; within a view, a nested table routes what the view pattern leaves
|
|
460
|
+
* over as a section of its own. Patterns, redirections and sections are described in the module overview.
|
|
461
|
+
*
|
|
462
|
+
* Renders below a {@link Router}, which keeps sole charge of the location, the history and the page clicks.
|
|
463
|
+
*
|
|
464
|
+
* Renders nothing during a redirection, so neither it nor a nested {@link Routes} shows a route on its way out.
|
|
465
|
+
*
|
|
466
|
+
* Mounts the view afresh whenever a navigation moves the location, the query included, so that a view reads the query
|
|
467
|
+
* as it mounts: a link from `/courses/` to `/courses/?~label=art` mounts the catalogue again with the new criteria. A
|
|
468
|
+
* query replaced through `history.replaceState` outside the router, as a view recording its own state in the location
|
|
469
|
+
* does, leaves the view mounted with the state it reached, until the next navigation moves the location again. A
|
|
470
|
+
* navigation changing the annex alone leaves the view mounted too, rendering again only what reads the annex.
|
|
471
|
+
*
|
|
472
|
+
* @param options The routes configuration
|
|
473
|
+
*
|
|
474
|
+
* @returns The view for the current route
|
|
475
|
+
*
|
|
476
|
+
* @throws {@link !Error Error} If a pattern other than `*` lacks a leading `/`, holds `*`, or holds `;` anywhere but
|
|
477
|
+
* before a non-empty annex on its last step, as soon as the table renders, whatever the route
|
|
478
|
+
* @throws {@link !Error Error} If the route, or one it redirects to, matches no pattern and no enclosing catch-all
|
|
479
|
+
* @throws {@link !Error Error} If redirections lead back to a route already visited
|
|
480
|
+
*/
|
|
481
|
+
export function Routes({ children }) {
|
|
482
|
+
const { route, annex, place, navigate } = useContext(RouterContext);
|
|
483
|
+
const { path, wild } = useContext(RoutesContext);
|
|
484
|
+
const title = useContext(TitleContext);
|
|
485
|
+
const table = isDefined(children[Wildcard]) || !isDefined(wild)
|
|
486
|
+
? children
|
|
487
|
+
: { ...children, [Wildcard]: wild }; // the inherited catch-all goes last, as if declared here
|
|
488
|
+
const invalid = Object.keys(table).find(glob => glob !== Wildcard && !/^\/[^*;]*(?:;[^*/]+)?$/.test(glob) // rooted, no wildcard, an annex on the last step only
|
|
489
|
+
);
|
|
490
|
+
if (isDefined(invalid)) {
|
|
491
|
+
throw new Error(`invalid route pattern <${invalid}>`);
|
|
492
|
+
}
|
|
493
|
+
const section = path.endsWith("/") ? route.slice(path.length - 1) : "/"; // the route as the table sees it
|
|
494
|
+
const origin = attach(section, annex);
|
|
495
|
+
const settled = settle(origin);
|
|
496
|
+
const target = settled === origin ? undefined : relocate(split(settled));
|
|
497
|
+
const hit = lookup(origin);
|
|
498
|
+
useLayoutEffect(() => {
|
|
499
|
+
if (isDefined(target)) {
|
|
500
|
+
navigate({ route: target, title, replace: true }); // replacing the entry, so going back never lands on it
|
|
501
|
+
}
|
|
502
|
+
else {
|
|
503
|
+
// the location already carries the route on show
|
|
504
|
+
}
|
|
505
|
+
}, [target, title, navigate]);
|
|
506
|
+
if (isDefined(target)) {
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
else if (isDefined(hit)) {
|
|
510
|
+
const tail = hit.steps.groups?.$;
|
|
511
|
+
const opened = isDefined(tail) ? route.slice(0, route.length - tail.length + 1) // up to the route below the subtree
|
|
512
|
+
: hit.glob === Wildcard ? path
|
|
513
|
+
: route;
|
|
514
|
+
return createElement(RoutesContext.Provider, {
|
|
515
|
+
key: place, // a navigation changing the query alone mounts the view afresh
|
|
516
|
+
value: { path: opened, wild: table[Wildcard] }
|
|
517
|
+
}, hit.entry);
|
|
518
|
+
}
|
|
519
|
+
else {
|
|
520
|
+
throw new Error(`unhandled route ${section}`);
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Locates a section route, along with the annex it carries, within the whole route.
|
|
524
|
+
*
|
|
525
|
+
* @returns The whole route the section route stands for, carrying its annex
|
|
526
|
+
*/
|
|
527
|
+
function relocate({ route, annex }) {
|
|
528
|
+
return attach(route === "/" ? path : `${path.replace(/\/$/, "")}${route}`, annex);
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Attaches an annex to the last step of a route.
|
|
532
|
+
*
|
|
533
|
+
* @returns The route carrying the annex, or the route alone for an empty annex
|
|
534
|
+
*/
|
|
535
|
+
function attach(route, annex) {
|
|
536
|
+
return annex ? `${route};${annex}` : route;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Follows the redirections of the table from a section route carrying its annex.
|
|
540
|
+
*
|
|
541
|
+
* @returns The route the redirections lead to, the section route itself if it is not redirected
|
|
542
|
+
*/
|
|
543
|
+
function settle(section) {
|
|
544
|
+
const trail = [section]; // the routes visited so far, grown as each redirection is followed
|
|
545
|
+
for (let route = redirect(section); isDefined(route); route = redirect(route)) {
|
|
546
|
+
if (trail.includes(route)) {
|
|
547
|
+
throw new Error(`redirection loop <${trail.join(",")}>`);
|
|
548
|
+
}
|
|
549
|
+
trail.push(route);
|
|
550
|
+
}
|
|
551
|
+
return trail.at(-1) ?? section;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Resolves the redirection the table defines for a section route carrying its annex.
|
|
555
|
+
*
|
|
556
|
+
* @returns The route the section route is redirected to, carrying the annex the target names or else the one of
|
|
557
|
+
* the section route; undefined if the table maps the section route to a view or matches no pattern for it
|
|
558
|
+
*/
|
|
559
|
+
function redirect(section) {
|
|
560
|
+
const hit = lookup(section);
|
|
561
|
+
if (isDefined(hit) && isString(hit.entry)) {
|
|
562
|
+
const { entry, steps } = hit;
|
|
563
|
+
const tail = steps.groups?.$;
|
|
564
|
+
const filled = entry.replace(/(?<=\/):(\w+)(?=[/;?#]|$)/g, (_, step) => steps.groups?.[step] ?? "");
|
|
565
|
+
const { route, annex } = split(filled);
|
|
566
|
+
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
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
else {
|
|
570
|
+
return undefined;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Looks up the first pattern of the table matching a section route carrying its annex, in table order.
|
|
575
|
+
*
|
|
576
|
+
* @returns The matching pattern, its entry and the steps it captured, or undefined if no pattern matches
|
|
577
|
+
*/
|
|
578
|
+
function lookup(section) {
|
|
579
|
+
const { route, annex } = split(section);
|
|
580
|
+
return Object.entries(table).flatMap(([glob, entry]) => {
|
|
581
|
+
const { route: stem, annex: label } = split(glob);
|
|
582
|
+
const steps = label && label !== annex ? null : pattern(stem, !label).exec(route);
|
|
583
|
+
return isNull(steps) ? [] : [{ glob, entry, steps }];
|
|
584
|
+
}).at(0);
|
|
585
|
+
/**
|
|
586
|
+
* Compiles a route pattern, capturing named steps under their name and the route below a subtree under `$`.
|
|
587
|
+
*
|
|
588
|
+
* @param glob The route pattern without its annex
|
|
589
|
+
* @param open True if a pattern ending with `/` is a subtree, false for a pattern naming an annex
|
|
590
|
+
*/
|
|
591
|
+
function pattern(glob, open) {
|
|
592
|
+
const subtree = open && glob.length > 1 && glob.endsWith("/");
|
|
593
|
+
const steps = subtree ? glob.slice(0, -1) : glob;
|
|
594
|
+
return glob === Wildcard ? /^.*$/ : new RegExp(`^${steps
|
|
595
|
+
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") // escape regex metacharacters
|
|
596
|
+
.replace(/(?<=\/):(\w+)(?=\/|$)/g, "(?<$1>[^/]+)") // named steps
|
|
597
|
+
}${subtree ? "(?<$>/.*)" : "(?:[?#].*)?"}$`); // the route below a subtree, or the ignored query and hash
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
602
|
+
/**
|
|
603
|
+
* Retrieves the route navigator.
|
|
604
|
+
*
|
|
605
|
+
* The navigator stays the same for as long as the {@link Router} providing it is mounted, so a component reading it
|
|
606
|
+
* renders again only as its own state requires, and a handler may keep it across navigations.
|
|
607
|
+
*
|
|
608
|
+
* @returns The navigator provided by the innermost enclosing {@link Router}; a no-op outside any router
|
|
609
|
+
*/
|
|
610
|
+
export function useRouter() {
|
|
611
|
+
return useContext(RouterContext).navigate;
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Retrieves the current route.
|
|
615
|
+
*
|
|
616
|
+
* Renders the component again whenever the route changes, whether through navigation or browser history.
|
|
617
|
+
*
|
|
618
|
+
* @returns The current route, as carried by the location path without its annex; an empty string outside any router
|
|
619
|
+
*/
|
|
620
|
+
export function useRoute() {
|
|
621
|
+
return useContext(RouterContext).route;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Retrieves the annex of the current route.
|
|
625
|
+
*
|
|
626
|
+
* Renders the component again whenever the annex changes, whether through navigation or browser history. The views
|
|
627
|
+
* below the router stay mounted, so a view switching presentation keeps the state it reached.
|
|
628
|
+
*
|
|
629
|
+
* @returns The annex after the `;` on the last step of the current route, as it appears in the location path and left
|
|
630
|
+
* to the caller to parse; an empty string if the route carries none, or outside any router
|
|
631
|
+
*/
|
|
632
|
+
export function useAnnex() {
|
|
633
|
+
return useContext(RouterContext).annex;
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Retrieves the title of the page on show.
|
|
637
|
+
*
|
|
638
|
+
* Renders the component again whenever the title changes, whether set through the navigator, alone or along with a
|
|
639
|
+
* route, or cleared on reaching another route. Lets a component shared by every page, such as a feedback or share
|
|
640
|
+
* action, name the page it is shown on without being handed the title the page already gave the navigator.
|
|
641
|
+
*
|
|
642
|
+
* @returns The title last passed to the navigator for the current route, tidied and without the {@link app} name; an
|
|
643
|
+
* empty string if none was set, if it equals the app name, or outside any router
|
|
644
|
+
*/
|
|
645
|
+
export function useTitle() {
|
|
646
|
+
return useContext(TitleContext);
|
|
647
|
+
}
|
|
648
|
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
649
|
+
/**
|
|
650
|
+
* Checks whether following a link lands the reader afresh on the page it leads to.
|
|
651
|
+
*
|
|
652
|
+
* Links to another route or back to the current place land afresh; links changing only the query or annex do not.
|
|
653
|
+
*
|
|
654
|
+
* @param before The place the link was followed from, path and query
|
|
655
|
+
* @param after The place the link led to
|
|
656
|
+
*
|
|
657
|
+
* @returns true if the route changed, or if neither the query nor the annex changed; false otherwise
|
|
658
|
+
*/
|
|
659
|
+
function lands(before, after) {
|
|
660
|
+
const from = parse(before);
|
|
661
|
+
const to = parse(after);
|
|
662
|
+
return from.route !== to.route || from.query === to.query && from.annex === to.annex;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Tidies a title as the page on show is named.
|
|
666
|
+
*
|
|
667
|
+
* @param title The title to tidy
|
|
668
|
+
*
|
|
669
|
+
* @returns The tidied title, or an empty string for a title equal to the {@link app} name
|
|
670
|
+
*/
|
|
671
|
+
function plain(title) {
|
|
672
|
+
const tidied = tidy(title);
|
|
673
|
+
return tidied === app.name ? "" : tidied;
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Splits a place into its route, the annex its last step carries and its query.
|
|
677
|
+
*
|
|
678
|
+
* @param place The location path and query
|
|
679
|
+
*
|
|
680
|
+
* @returns The route without the annex, the annex, and the query with its leading `?`, empty if none
|
|
681
|
+
*/
|
|
682
|
+
function parse(place) {
|
|
683
|
+
return { ...split(place.replace(/\?.*$/, "")), query: place.replace(/^[^?]*/, "") };
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Splits a route into its steps and the annex its last step carries.
|
|
687
|
+
*
|
|
688
|
+
* @param route The route to split, without any query
|
|
689
|
+
*
|
|
690
|
+
* @returns The route without the annex, and the annex following the first `;` of the last step, empty if none
|
|
691
|
+
*/
|
|
692
|
+
function split(route) {
|
|
693
|
+
const [, steps = route, annex = ""] = /^(.*?\/[^/;]*)(?:;([^/]*))?$/.exec(route) ?? [];
|
|
694
|
+
return { route: steps, annex };
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* Locates the element a fragment names.
|
|
698
|
+
*
|
|
699
|
+
* @param hash The fragment with its leading `#`, empty if none
|
|
700
|
+
*
|
|
701
|
+
* @returns The element the fragment names, or null if the fragment is empty or the document holds no such element
|
|
702
|
+
*/
|
|
703
|
+
function fragment(hash) {
|
|
704
|
+
return hash ? document.getElementById(decodeURIComponent(hash.slice(1))) : null;
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Retrieves the Navigation API of the browser.
|
|
708
|
+
*
|
|
709
|
+
* @returns The navigation of the window, or undefined if the browser lacks the API
|
|
710
|
+
*/
|
|
711
|
+
function navigations() {
|
|
712
|
+
return typeof navigation === "undefined" ? undefined : navigation;
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Measures the scroll positions the reader has reached.
|
|
716
|
+
*
|
|
717
|
+
* @returns The positions of the window and of the boxes carrying an `id` within the `main` landmark, the landmark
|
|
718
|
+
* itself included, leaving out those still at their origin, which a traversal has no need to restore
|
|
719
|
+
*/
|
|
720
|
+
function measure() {
|
|
721
|
+
const main = document.querySelector("main");
|
|
722
|
+
const boxes = main ? [main, ...main.querySelectorAll("[id]")] : [];
|
|
723
|
+
const positions = [
|
|
724
|
+
["", [window.scrollX, window.scrollY]],
|
|
725
|
+
...boxes.filter(box => box.id).map((box) => [box.id, [box.scrollLeft, box.scrollTop]])
|
|
726
|
+
];
|
|
727
|
+
return Object.fromEntries(positions.filter(([, [left, top]]) => left !== 0 || top !== 0));
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Keeps the scroll positions of a history entry.
|
|
731
|
+
*
|
|
732
|
+
* Positions are a convenience, so unavailable or full storage leaves them unkept rather than failing navigation.
|
|
733
|
+
*
|
|
734
|
+
* @param key The key of the history entry
|
|
735
|
+
* @param positions The positions to keep; an empty set removes the ones kept before
|
|
736
|
+
*/
|
|
737
|
+
function store(key, positions) {
|
|
738
|
+
try {
|
|
739
|
+
if (Object.keys(positions).length > 0) {
|
|
740
|
+
sessionStorage.setItem(`${PositionsPrefix}${key}`, JSON.stringify(positions));
|
|
741
|
+
}
|
|
742
|
+
else {
|
|
743
|
+
sessionStorage.removeItem(`${PositionsPrefix}${key}`);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
catch {
|
|
747
|
+
// storage unavailable or full
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Recalls the scroll positions of a history entry.
|
|
752
|
+
*
|
|
753
|
+
* @param key The key of the history entry
|
|
754
|
+
*
|
|
755
|
+
* @returns The positions kept for the entry; none if no well-formed positions are kept or storage is unavailable
|
|
756
|
+
*/
|
|
757
|
+
function recall(key) {
|
|
758
|
+
try {
|
|
759
|
+
const positions = JSON.parse(sessionStorage.getItem(`${PositionsPrefix}${key}`) ?? "{}");
|
|
760
|
+
return isObject(positions, offsets => isArray(offsets, [isNumber, isNumber])) ? positions : {};
|
|
761
|
+
}
|
|
762
|
+
catch {
|
|
763
|
+
return {};
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Restores scroll positions as the content they were reached on grows back.
|
|
768
|
+
*
|
|
769
|
+
* Applies the positions at once and again whenever the content changes, until every one is reached, the reader takes
|
|
770
|
+
* over through {@link ReaderInput}, or {@link RestoreTimeout} elapses with the content still too short to reach them.
|
|
771
|
+
*
|
|
772
|
+
* @param positions The positions to restore
|
|
773
|
+
*
|
|
774
|
+
* @returns A function stopping the restore before it ends on its own
|
|
775
|
+
*/
|
|
776
|
+
function reposition(positions) {
|
|
777
|
+
const observer = new MutationObserver(attempt);
|
|
778
|
+
const timer = setTimeout(stop, RestoreTimeout);
|
|
779
|
+
observer.observe(document.body, { childList: true, subtree: true });
|
|
780
|
+
ReaderInput.forEach(type => window.addEventListener(type, stop, { capture: true, passive: true }));
|
|
781
|
+
attempt();
|
|
782
|
+
return stop;
|
|
783
|
+
function attempt() {
|
|
784
|
+
const reached = Object.entries(positions).map(([box, offsets]) => place(box, offsets));
|
|
785
|
+
if (reached.every(Boolean)) {
|
|
786
|
+
stop();
|
|
787
|
+
}
|
|
788
|
+
else {
|
|
789
|
+
// waiting for the content to grow back
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
function place(box, [left, top]) {
|
|
793
|
+
const [x, y] = box ? element(document.getElementById(box)) : viewport();
|
|
794
|
+
return Math.abs(x - left) < 1 && Math.abs(y - top) < 1; // offsets may be fractional on high density displays
|
|
795
|
+
function viewport() {
|
|
796
|
+
window.scrollTo(left, top);
|
|
797
|
+
return [window.scrollX, window.scrollY];
|
|
798
|
+
}
|
|
799
|
+
function element(target) {
|
|
800
|
+
target?.scrollTo(left, top);
|
|
801
|
+
return target ? [target.scrollLeft, target.scrollTop] : [Number.NaN, Number.NaN]; // a box not rendered yet
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
function stop() {
|
|
805
|
+
observer.disconnect();
|
|
806
|
+
clearTimeout(timer);
|
|
807
|
+
ReaderInput.forEach(type => window.removeEventListener(type, stop, { capture: true }));
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
//# sourceMappingURL=router.js.map
|