@inglorious/web 6.13.0 → 6.14.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/README.md +25 -4
- package/package.json +1 -1
- package/src/analytics/index.js +0 -1
- package/src/decorators/with-debounce/index.js +5 -7
- package/src/decorators/with-error-boundary/index.js +4 -2
- package/src/decorators/with-live-reload/index.js +2 -5
- package/src/decorators/with-throttle/index.js +5 -7
- package/src/form/handlers.js +0 -18
- package/src/mount.js +2 -4
- package/src/push/index.js +0 -6
- package/src/pwa/update.js +0 -3
- package/src/router/accessible-navigation.js +0 -6
- package/src/router/handlers.js +3 -31
- package/src/router/index.js +3 -0
- package/src/router/page-route.js +20 -0
- package/src/router/safe-path.js +19 -0
- package/src/sensors/element-size/handlers.js +0 -1
- package/types/decorators/with-live-reload.d.ts +1 -1
- package/types/form.d.ts +1 -33
- package/types/mount.d.ts +4 -7
- package/types/router.d.ts +38 -0
package/README.md
CHANGED
|
@@ -1088,7 +1088,27 @@ export const AdminPage = {
|
|
|
1088
1088
|
}
|
|
1089
1089
|
```
|
|
1090
1090
|
|
|
1091
|
-
### 5.
|
|
1091
|
+
### 5. Page Entities
|
|
1092
|
+
|
|
1093
|
+
Every entity hears `routeChange`, so a page can load its data when it opens and drop it when it closes. `pageRouteChange({ select, open, close })` writes that handler: `open` runs when the route resolved to the entity, with what `select` picks from the route, `close` when it resolved elsewhere. Each is optional.
|
|
1094
|
+
|
|
1095
|
+
```javascript
|
|
1096
|
+
import { pageRouteChange } from "@inglorious/web/router"
|
|
1097
|
+
|
|
1098
|
+
export const EventPage = {
|
|
1099
|
+
routeChange: pageRouteChange({
|
|
1100
|
+
select: (payload) => payload.params.eventId,
|
|
1101
|
+
open: (entity, eventId, api) => api.notify(`#${entity.id}:fetch`, eventId),
|
|
1102
|
+
close: (entity) => {
|
|
1103
|
+
entity.event = null
|
|
1104
|
+
},
|
|
1105
|
+
}),
|
|
1106
|
+
}
|
|
1107
|
+
```
|
|
1108
|
+
|
|
1109
|
+
It reads the route from the payload: during `routeChange`, the router entity still names the route being left.
|
|
1110
|
+
|
|
1111
|
+
### 6. Route Guards (Type Composition)
|
|
1092
1112
|
|
|
1093
1113
|
Route guards are implemented using **type composition** — a powerful feature of `@inglorious/store` where types can be defined as arrays of behaviors that wrap and extend each other.
|
|
1094
1114
|
|
|
@@ -1101,15 +1121,14 @@ Guards are simply behaviors that intercept events (like `routeChange`) and can p
|
|
|
1101
1121
|
export const requireAuth = (type) => ({
|
|
1102
1122
|
routeChange(entity, payload, api) {
|
|
1103
1123
|
// Only act when navigating to this specific route
|
|
1104
|
-
if (payload.route !== entity.
|
|
1124
|
+
if (payload.route !== entity.id) return
|
|
1105
1125
|
|
|
1106
1126
|
// Check authentication
|
|
1107
1127
|
const user = localStorage.getItem("user")
|
|
1108
1128
|
if (!user) {
|
|
1109
1129
|
// Redirect to login, preserving the intended destination
|
|
1110
1130
|
api.notify("navigate", {
|
|
1111
|
-
to:
|
|
1112
|
-
redirectTo: window.location.pathname,
|
|
1131
|
+
to: `/login?from=${encodeURIComponent(payload.path)}`,
|
|
1113
1132
|
replace: true,
|
|
1114
1133
|
})
|
|
1115
1134
|
return
|
|
@@ -1121,6 +1140,8 @@ export const requireAuth = (type) => ({
|
|
|
1121
1140
|
})
|
|
1122
1141
|
```
|
|
1123
1142
|
|
|
1143
|
+
After signing in, `safePath(query.from)` gives the destination back only if it stays on the site, so a crafted `/login?from=//evil.com` leads nowhere: `api.notify("navigate", safePath(query.from) ?? "/")`.
|
|
1144
|
+
|
|
1124
1145
|
#### Using Guards with Type Composition
|
|
1125
1146
|
|
|
1126
1147
|
```javascript
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/web",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.14.0",
|
|
4
4
|
"description": "A new web framework that leverages the power of the Inglorious Store combined with the performance and simplicity of lit-html.",
|
|
5
5
|
"author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
|
|
6
6
|
"contributors": [
|
package/src/analytics/index.js
CHANGED
|
@@ -71,7 +71,6 @@ export function createAnalytics({ adapter, consentKey = DEFAULT_CONSENT_KEY }) {
|
|
|
71
71
|
call(() => adapter.setConsent(isGranted))
|
|
72
72
|
if (!isGranted) return
|
|
73
73
|
|
|
74
|
-
// The page the answer came from is the first one measured.
|
|
75
74
|
const router = api.getEntity("router")
|
|
76
75
|
if (router?.route) {
|
|
77
76
|
call(() => adapter.pageView({ route: router.route, path: router.path }))
|
|
@@ -37,17 +37,16 @@ export function withDebounce(config, handlerNames) {
|
|
|
37
37
|
: config
|
|
38
38
|
|
|
39
39
|
return (type) => {
|
|
40
|
-
// one debounced-fn map per entity, so instances don't share timers
|
|
41
40
|
const debouncedByEntity = new Map()
|
|
42
41
|
|
|
43
42
|
const behavior = {}
|
|
44
43
|
|
|
45
44
|
for (const handlerName of Object.keys(delays)) {
|
|
46
45
|
const originalHandler = type[handlerName]
|
|
47
|
-
if (!originalHandler) continue
|
|
46
|
+
if (!originalHandler) continue
|
|
48
47
|
|
|
49
48
|
behavior[handlerName] = (entity, payload, api) => {
|
|
50
|
-
const entityId = entity.id
|
|
49
|
+
const entityId = entity.id
|
|
51
50
|
|
|
52
51
|
let perEntity = debouncedByEntity.get(entityId)
|
|
53
52
|
if (!perEntity) {
|
|
@@ -57,8 +56,8 @@ export function withDebounce(config, handlerNames) {
|
|
|
57
56
|
|
|
58
57
|
if (!perEntity[handlerName]) {
|
|
59
58
|
perEntity[handlerName] = debounce((entityId, payload, api) => {
|
|
60
|
-
const liveEntity = api.getEntity(entityId)
|
|
61
|
-
if (!liveEntity) return
|
|
59
|
+
const liveEntity = api.getEntity(entityId)
|
|
60
|
+
if (!liveEntity) return
|
|
62
61
|
originalHandler(liveEntity, payload, api)
|
|
63
62
|
}, delays[handlerName])
|
|
64
63
|
}
|
|
@@ -67,9 +66,8 @@ export function withDebounce(config, handlerNames) {
|
|
|
67
66
|
}
|
|
68
67
|
}
|
|
69
68
|
|
|
70
|
-
// clean up any pending timers when the entity is destroyed
|
|
71
69
|
behavior.destroy = (entity, payload, api) => {
|
|
72
|
-
const entityId = entity.id
|
|
70
|
+
const entityId = entity.id
|
|
73
71
|
|
|
74
72
|
const perEntity = debouncedByEntity.get(entityId)
|
|
75
73
|
if (perEntity) {
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* @typedef {import("../../../types/mount").Api} Api
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import { nothing } from "lit-html"
|
|
6
|
+
|
|
5
7
|
/**
|
|
6
8
|
* Wraps a type's `render` in an error boundary. If the base render throws
|
|
7
9
|
* synchronously, the caught error is handed to `fallback` and its template is
|
|
@@ -34,7 +36,7 @@ export function withErrorBoundary(fallback = defaultFallback) {
|
|
|
34
36
|
return (type) => ({
|
|
35
37
|
render(entity, api) {
|
|
36
38
|
try {
|
|
37
|
-
return type.render?.(entity, api) ??
|
|
39
|
+
return type.render?.(entity, api) ?? nothing
|
|
38
40
|
} catch (error) {
|
|
39
41
|
return fallback(error, entity, api)
|
|
40
42
|
}
|
|
@@ -44,5 +46,5 @@ export function withErrorBoundary(fallback = defaultFallback) {
|
|
|
44
46
|
|
|
45
47
|
function defaultFallback(error) {
|
|
46
48
|
console.error("[withErrorBoundary] render failed:", error)
|
|
47
|
-
return
|
|
49
|
+
return nothing
|
|
48
50
|
}
|
|
@@ -2,8 +2,6 @@ import { debounce } from "@inglorious/utils/functions"
|
|
|
2
2
|
|
|
3
3
|
const DEFAULT_DELAY = 300
|
|
4
4
|
|
|
5
|
-
// Every live entity's reload, across all the types that use the decorator, so
|
|
6
|
-
// one listener can reload them all when the page comes back into view.
|
|
7
5
|
const reloads = new Set()
|
|
8
6
|
let isWatchingVisibility = false
|
|
9
7
|
|
|
@@ -63,7 +61,6 @@ export function withLiveReload({
|
|
|
63
61
|
delay = DEFAULT_DELAY,
|
|
64
62
|
}) {
|
|
65
63
|
return (type) => {
|
|
66
|
-
// entity id -> what to cancel when it goes
|
|
67
64
|
const subscriptions = new Map()
|
|
68
65
|
|
|
69
66
|
function stop(id) {
|
|
@@ -79,10 +76,10 @@ export function withLiveReload({
|
|
|
79
76
|
create(entity, createPayload, api) {
|
|
80
77
|
type.create?.(entity, createPayload, api)
|
|
81
78
|
|
|
82
|
-
const id = entity.id
|
|
79
|
+
const id = entity.id
|
|
83
80
|
stop(id)
|
|
84
81
|
const reload = debounce(() => {
|
|
85
|
-
const live = api.getEntity(id)
|
|
82
|
+
const live = api.getEntity(id)
|
|
86
83
|
if (!live || !isLive(live, api)) return
|
|
87
84
|
api.notify(`#${id}:${event}`, payload?.(live, api))
|
|
88
85
|
}, delay)
|
|
@@ -55,17 +55,16 @@ export function withThrottle(
|
|
|
55
55
|
: config
|
|
56
56
|
|
|
57
57
|
return (type) => {
|
|
58
|
-
// one throttled-fn map per entity, so instances don't share windows
|
|
59
58
|
const throttledByEntity = new Map()
|
|
60
59
|
|
|
61
60
|
const behavior = {}
|
|
62
61
|
|
|
63
62
|
for (const handlerName of Object.keys(delays)) {
|
|
64
63
|
const originalHandler = type[handlerName]
|
|
65
|
-
if (!originalHandler) continue
|
|
64
|
+
if (!originalHandler) continue
|
|
66
65
|
|
|
67
66
|
behavior[handlerName] = (entity, payload, api) => {
|
|
68
|
-
const entityId = entity.id
|
|
67
|
+
const entityId = entity.id
|
|
69
68
|
|
|
70
69
|
let perEntity = throttledByEntity.get(entityId)
|
|
71
70
|
if (!perEntity) {
|
|
@@ -76,8 +75,8 @@ export function withThrottle(
|
|
|
76
75
|
if (!perEntity[handlerName]) {
|
|
77
76
|
perEntity[handlerName] = throttle(
|
|
78
77
|
(entityId, payload, api) => {
|
|
79
|
-
const liveEntity = api.getEntity(entityId)
|
|
80
|
-
if (!liveEntity) return
|
|
78
|
+
const liveEntity = api.getEntity(entityId)
|
|
79
|
+
if (!liveEntity) return
|
|
81
80
|
originalHandler(liveEntity, payload, api)
|
|
82
81
|
},
|
|
83
82
|
delays[handlerName],
|
|
@@ -89,9 +88,8 @@ export function withThrottle(
|
|
|
89
88
|
}
|
|
90
89
|
}
|
|
91
90
|
|
|
92
|
-
// clean up any pending windows/trailing calls when the entity is destroyed
|
|
93
91
|
behavior.destroy = (entity, payload, api) => {
|
|
94
|
-
const entityId = entity.id
|
|
92
|
+
const entityId = entity.id
|
|
95
93
|
|
|
96
94
|
const perEntity = throttledByEntity.get(entityId)
|
|
97
95
|
if (perEntity) {
|
package/src/form/handlers.js
CHANGED
|
@@ -6,20 +6,16 @@ import { clone, get, set } from "@inglorious/utils/object.js"
|
|
|
6
6
|
* @typedef {import('../../types/form.js').FormFieldBlurPayload} FormFieldBlurPayload
|
|
7
7
|
*
|
|
8
8
|
* @typedef {object} FormValidatePayload
|
|
9
|
-
* @property {string|number} entityId - The ID of the target form entity.
|
|
10
9
|
* @property {(values: object) => import('../../types/form.js').FormErrors<object>} validate - A function that validates the entire form's values and returns a complete error object.
|
|
11
10
|
*
|
|
12
11
|
* @typedef {object} FormValidateAsyncPayload
|
|
13
|
-
* @property {string|number} entityId - The ID of the target form entity.
|
|
14
12
|
* @property {(values: object) => Promise<import('../../types/form.js').FormErrors<object>>} validate - An async function that validates the entire form's values.
|
|
15
13
|
*
|
|
16
14
|
* @typedef {object} FormValidationCompletePayload
|
|
17
|
-
* @property {string|number} entityId - The ID of the target form entity.
|
|
18
15
|
* @property {import('../../types/form.js').FormErrors<object>} errors - The validation errors.
|
|
19
16
|
* @property {boolean} isValid - Whether the form is valid.
|
|
20
17
|
*
|
|
21
18
|
* @typedef {object} FormValidationErrorPayload
|
|
22
|
-
* @property {string|number} entityId - The ID of the target form entity.
|
|
23
19
|
* @property {string} error - The error message.
|
|
24
20
|
*/
|
|
25
21
|
|
|
@@ -65,7 +61,6 @@ export function create(entity) {
|
|
|
65
61
|
* Appends an item to a field array.
|
|
66
62
|
* @param {FormEntity} entity - The form entity.
|
|
67
63
|
* @param {Object} payload
|
|
68
|
-
* @param {string|number} payload.entityId - The form entity ID.
|
|
69
64
|
* @param {string} payload.path - Path to the array field (e.g., 'addresses').
|
|
70
65
|
* @param {*} payload.value - The value to append.
|
|
71
66
|
*/
|
|
@@ -91,7 +86,6 @@ export function fieldArrayAppend(entity, { path, value }) {
|
|
|
91
86
|
* Removes an item from a field array by index.
|
|
92
87
|
* @param {FormEntity} entity - The form entity.
|
|
93
88
|
* @param {Object} payload
|
|
94
|
-
* @param {string|number} payload.entityId - The form entity ID.
|
|
95
89
|
* @param {string} payload.path - Path to the array field.
|
|
96
90
|
* @param {number} payload.index - The index to remove.
|
|
97
91
|
*/
|
|
@@ -117,7 +111,6 @@ export function fieldArrayRemove(entity, { path, index }) {
|
|
|
117
111
|
* Inserts an item into a field array at a specific index.
|
|
118
112
|
* @param {FormEntity} entity - The form entity.
|
|
119
113
|
* @param {Object} payload
|
|
120
|
-
* @param {string|number} payload.entityId - The form entity ID.
|
|
121
114
|
* @param {string} payload.path - Path to the array field.
|
|
122
115
|
* @param {number} payload.index - The index to insert at.
|
|
123
116
|
* @param {*} payload.value - The value to insert.
|
|
@@ -144,7 +137,6 @@ export function fieldArrayInsert(entity, { path, index, value }) {
|
|
|
144
137
|
* Moves an item in a field array from one index to another.
|
|
145
138
|
* @param {FormEntity} entity - The form entity.
|
|
146
139
|
* @param {Object} payload
|
|
147
|
-
* @param {string|number} payload.entityId - The form entity ID.
|
|
148
140
|
* @param {string} payload.path - Path to the array field.
|
|
149
141
|
* @param {number} payload.fromIndex - The source index.
|
|
150
142
|
* @param {number} payload.toIndex - The destination index.
|
|
@@ -201,7 +193,6 @@ export function fieldChange(entity, { path, value, validate }) {
|
|
|
201
193
|
/**
|
|
202
194
|
* Resets the form to its initial state.
|
|
203
195
|
* @param {FormEntity} entity - The form entity.
|
|
204
|
-
* @param {string|number} entityId - The ID of the target form entity.
|
|
205
196
|
*/
|
|
206
197
|
export function reset(entity) {
|
|
207
198
|
resetForm(entity)
|
|
@@ -266,7 +257,6 @@ function hasErrors(errors) {
|
|
|
266
257
|
}
|
|
267
258
|
|
|
268
259
|
if (typeof errors !== "object") {
|
|
269
|
-
// Leaf value - check if it's truthy (error string)
|
|
270
260
|
return Boolean(errors)
|
|
271
261
|
}
|
|
272
262
|
|
|
@@ -274,7 +264,6 @@ function hasErrors(errors) {
|
|
|
274
264
|
return errors.some((item) => hasErrors(item))
|
|
275
265
|
}
|
|
276
266
|
|
|
277
|
-
// Object - check all properties
|
|
278
267
|
return Object.values(errors).some((value) => hasErrors(value))
|
|
279
268
|
}
|
|
280
269
|
|
|
@@ -310,23 +299,16 @@ function setFieldValue(form, path, value) {
|
|
|
310
299
|
|
|
311
300
|
form.isPristine = false
|
|
312
301
|
|
|
313
|
-
// By clearing the error for this path, the form might become valid.
|
|
314
|
-
// We delegate to setFieldError(..., null) to correctly run the check.
|
|
315
302
|
setFieldError(form, path, null)
|
|
316
303
|
}
|
|
317
304
|
|
|
318
305
|
function setFieldError(form, path, error) {
|
|
319
|
-
// Ensure we set null if error is falsy, but not an empty string
|
|
320
306
|
const newError = error || null
|
|
321
307
|
set(form.errors, path, newError)
|
|
322
308
|
|
|
323
309
|
if (newError) {
|
|
324
|
-
// If we are adding an error, the form is definitely invalid.
|
|
325
|
-
// No need for an expensive check.
|
|
326
310
|
form.isValid = false
|
|
327
311
|
} else {
|
|
328
|
-
// If we are removing an error, the form MIGHT become valid.
|
|
329
|
-
// This is when we must perform the check.
|
|
330
312
|
form.isValid = !hasErrors(form.errors)
|
|
331
313
|
}
|
|
332
314
|
}
|
package/src/mount.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
/** @typedef {import('@inglorious/store').EntityType} EntityType */
|
|
4
4
|
/** @typedef {import('../types/mount').Api} Api */
|
|
5
5
|
|
|
6
|
-
import { html, render } from "lit-html"
|
|
6
|
+
import { html, nothing, render } from "lit-html"
|
|
7
7
|
|
|
8
8
|
import { isNative } from "./mobile/index.js"
|
|
9
9
|
import { createAccessibleNavigation } from "./router/accessible-navigation.js"
|
|
@@ -45,7 +45,6 @@ export async function mount(store, renderFn, element, options = {}) {
|
|
|
45
45
|
|
|
46
46
|
const shouldHydrate = allowHydrate && element.hasChildNodes()
|
|
47
47
|
|
|
48
|
-
// If we need to hydrate, load the heavy lifting only now
|
|
49
48
|
if (shouldHydrate) {
|
|
50
49
|
const { hydrate } = await import("@lit-labs/ssr-client")
|
|
51
50
|
const result = renderRoot(renderFn, api, onError, fallback)
|
|
@@ -66,7 +65,6 @@ export async function mount(store, renderFn, element, options = {}) {
|
|
|
66
65
|
const unsubscribe = store.subscribe(() => {
|
|
67
66
|
const result = renderRoot(renderFn, api, onError, fallback)
|
|
68
67
|
if (result.ok) {
|
|
69
|
-
// Standard render is already in the main bundle (it's small)
|
|
70
68
|
render(result.template, element)
|
|
71
69
|
} else if (fallback) {
|
|
72
70
|
render(result.fallback, element)
|
|
@@ -125,7 +123,7 @@ function createRender(api) {
|
|
|
125
123
|
const entity = api.getEntity(id)
|
|
126
124
|
|
|
127
125
|
if (!entity) {
|
|
128
|
-
return
|
|
126
|
+
return nothing
|
|
129
127
|
}
|
|
130
128
|
|
|
131
129
|
const entityType = api.getType(entity.type)
|
package/src/push/index.js
CHANGED
|
@@ -84,8 +84,6 @@ export function createPushPrompt({
|
|
|
84
84
|
entity.isOpen = false
|
|
85
85
|
},
|
|
86
86
|
|
|
87
|
-
// Asking the device is async, so a stop can land before the answer: the
|
|
88
|
-
// prompt only opens while started.
|
|
89
87
|
...handleAsync("pushCheck", {
|
|
90
88
|
async run() {
|
|
91
89
|
if (!(await adapter.isSupported())) return null
|
|
@@ -102,8 +100,6 @@ export function createPushPrompt({
|
|
|
102
100
|
error() {},
|
|
103
101
|
}),
|
|
104
102
|
|
|
105
|
-
// The prompt goes down as the system's dialog comes up. Dismissing the
|
|
106
|
-
// dialog leaves the permission undecided, so the next start asks again.
|
|
107
103
|
...handleAsync("pushAsk", {
|
|
108
104
|
start(entity) {
|
|
109
105
|
entity.isOpen = false
|
|
@@ -126,8 +122,6 @@ export function createPushPrompt({
|
|
|
126
122
|
entity.isOpen = false
|
|
127
123
|
},
|
|
128
124
|
|
|
129
|
-
// Nothing on screen depends on it: a device that fails to register now
|
|
130
|
-
// tries again at the next start.
|
|
131
125
|
...handleAsync("pushRegister", {
|
|
132
126
|
run() {
|
|
133
127
|
return adapter.register()
|
package/src/pwa/update.js
CHANGED
|
@@ -28,8 +28,6 @@ export function watchPwaUpdate(
|
|
|
28
28
|
store,
|
|
29
29
|
{ id = DEFAULT_ID, checkEveryMs = ONE_HOUR_MS } = {},
|
|
30
30
|
) {
|
|
31
|
-
// A first-ever install has no older version to move from: nothing to
|
|
32
|
-
// announce while the page that installed it keeps running.
|
|
33
31
|
const hadController = Boolean(navigator.serviceWorker?.controller)
|
|
34
32
|
let announced = null
|
|
35
33
|
let isApplying = false
|
|
@@ -44,7 +42,6 @@ export function watchPwaUpdate(
|
|
|
44
42
|
document.removeEventListener(VISIBILITY_EVENT, handleVisibilityChange)
|
|
45
43
|
}
|
|
46
44
|
|
|
47
|
-
// Offline, the check fails: the next one tries again.
|
|
48
45
|
function check() {
|
|
49
46
|
registration.update?.()?.catch?.(() => {})
|
|
50
47
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
const ANNOUNCER_ID = "iw-route-announcer"
|
|
2
|
-
// Long enough for screen readers to notice the live region emptied first.
|
|
3
2
|
const ANNOUNCE_DELAY_MS = 100
|
|
4
3
|
const VISUALLY_HIDDEN =
|
|
5
4
|
"position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0"
|
|
@@ -24,14 +23,11 @@ const VISUALLY_HIDDEN =
|
|
|
24
23
|
export function createAccessibleNavigation({
|
|
25
24
|
getPageName = () => document.title,
|
|
26
25
|
} = {}) {
|
|
27
|
-
// Screen readers only announce changes made after the live region is in the document.
|
|
28
26
|
const announcer = getAnnouncer()
|
|
29
27
|
let currentPath = window.location.pathname
|
|
30
28
|
let hasPendingAnnouncement = false
|
|
31
29
|
let announceTimeout = null
|
|
32
30
|
|
|
33
|
-
// Screen readers speak only when the live region changes, so it is emptied first and
|
|
34
|
-
// filled on a later task: two pages with the same name are each announced.
|
|
35
31
|
function announce(message) {
|
|
36
32
|
announcer.textContent = ""
|
|
37
33
|
clearTimeout(announceTimeout)
|
|
@@ -74,8 +70,6 @@ function getAnnouncer() {
|
|
|
74
70
|
return announcer
|
|
75
71
|
}
|
|
76
72
|
|
|
77
|
-
// Focusing the body makes the next Tab start from the top of the new page, rather
|
|
78
|
-
// than from the link that was clicked, which may no longer exist.
|
|
79
73
|
function resetFocus() {
|
|
80
74
|
const autofocus = document.querySelector("[autofocus]")
|
|
81
75
|
if (autofocus) {
|
package/src/router/handlers.js
CHANGED
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
|
|
7
7
|
import { toCamelCase } from "@inglorious/utils/data-structures/string.js"
|
|
8
8
|
|
|
9
|
-
const SKIP_FULL_MATCH_GROUP = 1
|
|
9
|
+
const SKIP_FULL_MATCH_GROUP = 1
|
|
10
10
|
const REMOVE_COLON_PREFIX = 1
|
|
11
|
-
const FIRST_HISTORY_INDEX = 0
|
|
12
|
-
const PUSH_HISTORY_STEP = 1
|
|
11
|
+
const FIRST_HISTORY_INDEX = 0
|
|
12
|
+
const PUSH_HISTORY_STEP = 1
|
|
13
13
|
|
|
14
14
|
export function createHandlers(routeConfig) {
|
|
15
15
|
/**
|
|
@@ -27,10 +27,6 @@ export function createHandlers(routeConfig) {
|
|
|
27
27
|
* @param {Api} api - The application API.
|
|
28
28
|
*/
|
|
29
29
|
init(entity, payload, api) {
|
|
30
|
-
/* Stamp the entry the app starts on, so that reloading keeps the app in
|
|
31
|
-
its place in the session history instead of restarting the count.
|
|
32
|
-
`withTransitions` reads this index back to tell a push from a traversal
|
|
33
|
-
and in which direction, so it has to be set before anything navigates. */
|
|
34
30
|
if (window.history.state?.idx == null) {
|
|
35
31
|
window.history.replaceState(
|
|
36
32
|
{ ...window.history.state, idx: FIRST_HISTORY_INDEX },
|
|
@@ -39,7 +35,6 @@ export function createHandlers(routeConfig) {
|
|
|
39
35
|
}
|
|
40
36
|
entity.idx = window.history.state?.idx ?? FIRST_HISTORY_INDEX
|
|
41
37
|
|
|
42
|
-
// Handle initial route
|
|
43
38
|
const { pathname, search } = window.location
|
|
44
39
|
const initialPath = pathname + search
|
|
45
40
|
const route = findRoute(routeConfig, initialPath)
|
|
@@ -56,38 +51,29 @@ export function createHandlers(routeConfig) {
|
|
|
56
51
|
if (areListenersInitialized) return
|
|
57
52
|
areListenersInitialized = true
|
|
58
53
|
|
|
59
|
-
// Listen for browser back/forward
|
|
60
54
|
window.addEventListener("popstate", () =>
|
|
61
55
|
api.notify(`#${entityId}:popstate`, payload),
|
|
62
56
|
)
|
|
63
57
|
|
|
64
|
-
// Intercept link clicks
|
|
65
58
|
document.addEventListener("click", (event) => {
|
|
66
|
-
// Find the closest <a> tag (handles clicks on children)
|
|
67
59
|
const link = event.target.closest("a")
|
|
68
60
|
|
|
69
61
|
if (!link) return
|
|
70
62
|
|
|
71
|
-
// Skip external links
|
|
72
63
|
if (link.target === "_blank") return
|
|
73
64
|
if (link.rel === "external") return
|
|
74
65
|
if (link.hasAttribute("data-external")) return
|
|
75
66
|
|
|
76
|
-
// Skip different origin links
|
|
77
67
|
if (link.origin !== window.location.origin) return
|
|
78
68
|
|
|
79
|
-
// Skip links with download attribute
|
|
80
69
|
if (link.hasAttribute("download")) return
|
|
81
70
|
|
|
82
|
-
// Skip mailto:, tel:, etc.
|
|
83
71
|
if (!["http:", "https:"].includes(link.protocol)) return
|
|
84
72
|
|
|
85
|
-
// Prevent default and use router
|
|
86
73
|
event.preventDefault()
|
|
87
74
|
|
|
88
75
|
const path = link.pathname + link.search + link.hash
|
|
89
76
|
|
|
90
|
-
// Stored in the history entry, for whatever moves focus after navigating.
|
|
91
77
|
if (link.hasAttribute("data-is-focus-kept")) {
|
|
92
78
|
api.notify(`#${entityId}:navigate`, {
|
|
93
79
|
to: path,
|
|
@@ -131,8 +117,6 @@ export function createHandlers(routeConfig) {
|
|
|
131
117
|
}
|
|
132
118
|
|
|
133
119
|
updateRouter(entity, route)
|
|
134
|
-
// Adopt the index of the entry just traversed, so the next push counts
|
|
135
|
-
// from where the history actually is rather than from where it was.
|
|
136
120
|
entity.idx = window.history.state?.idx ?? FIRST_HISTORY_INDEX
|
|
137
121
|
|
|
138
122
|
api.notify("routeChange", {
|
|
@@ -156,23 +140,17 @@ export function createHandlers(routeConfig) {
|
|
|
156
140
|
: payload
|
|
157
141
|
const { to, params, replace, force, state = {} } = options
|
|
158
142
|
|
|
159
|
-
// Numeric navigation (back/forward)
|
|
160
143
|
if (typeof to === "number") {
|
|
161
144
|
history.go(to)
|
|
162
145
|
return
|
|
163
146
|
}
|
|
164
147
|
|
|
165
|
-
// Build final path
|
|
166
148
|
let path = to
|
|
167
149
|
|
|
168
|
-
// If params provided and "to" looks like a pattern, build the path
|
|
169
150
|
if (params && to.includes(":")) {
|
|
170
151
|
path = buildPath(to, params)
|
|
171
152
|
}
|
|
172
153
|
|
|
173
|
-
// If "to" is already a final path (like "/users/1"), use it directly
|
|
174
|
-
// The router will match it against patterns in routeConfig
|
|
175
|
-
|
|
176
154
|
const route = findRoute(routeConfig, path)
|
|
177
155
|
const entityId = entity.id
|
|
178
156
|
|
|
@@ -182,7 +160,6 @@ export function createHandlers(routeConfig) {
|
|
|
182
160
|
}
|
|
183
161
|
|
|
184
162
|
if (!force) {
|
|
185
|
-
// Prevent navigation if the full path (including query/hash) is identical.
|
|
186
163
|
const currentFullPath =
|
|
187
164
|
entity.path + window.location.search + window.location.hash
|
|
188
165
|
if (path === currentFullPath) {
|
|
@@ -190,7 +167,6 @@ export function createHandlers(routeConfig) {
|
|
|
190
167
|
}
|
|
191
168
|
}
|
|
192
169
|
|
|
193
|
-
// Asynchronous navigation
|
|
194
170
|
if (typeof route.route === "function") {
|
|
195
171
|
entity.isLoading = true
|
|
196
172
|
entity.error = null
|
|
@@ -208,7 +184,6 @@ export function createHandlers(routeConfig) {
|
|
|
208
184
|
|
|
209
185
|
updateRouter(entity, route)
|
|
210
186
|
|
|
211
|
-
// Prepare history state
|
|
212
187
|
const historyState = {
|
|
213
188
|
...state,
|
|
214
189
|
/* Written before the notification that triggers the render, so that
|
|
@@ -221,11 +196,8 @@ export function createHandlers(routeConfig) {
|
|
|
221
196
|
path: entity.path,
|
|
222
197
|
}
|
|
223
198
|
|
|
224
|
-
// Navigate
|
|
225
199
|
const method = replace ? "replaceState" : "pushState"
|
|
226
200
|
history[method](historyState, "", path)
|
|
227
|
-
// Advance the counter as well as stamping the entry, or the next push
|
|
228
|
-
// writes the same index and reads as a replacement.
|
|
229
201
|
entity.idx = historyState.idx
|
|
230
202
|
|
|
231
203
|
api.notify("routeChange", historyState)
|
package/src/router/index.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { createHandlers } from "./handlers.js"
|
|
2
2
|
import { createHelpers } from "./helpers.js"
|
|
3
3
|
|
|
4
|
+
export { pageRouteChange } from "./page-route.js"
|
|
5
|
+
export { safePath } from "./safe-path.js"
|
|
6
|
+
|
|
4
7
|
/**
|
|
5
8
|
* Route configuration map. Keys are route patterns (e.g. `/users/:id`) and
|
|
6
9
|
* values are either a string type name or a loader function that returns a
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `routeChange` handler for a page entity: `open` when the route resolved to
|
|
3
|
+
* it, `close` when it resolved elsewhere. Each step is optional.
|
|
4
|
+
* @param {object} [handlers]
|
|
5
|
+
* @param {(payload: object) => unknown} [handlers.select] - Picks what `open` needs from the route, such as a param.
|
|
6
|
+
* @param {(entity: object, selected: unknown, api: object) => void} [handlers.open]
|
|
7
|
+
* @param {(entity: object, api: object) => void} [handlers.close]
|
|
8
|
+
* @returns {(entity: object, payload: object, api: object) => void}
|
|
9
|
+
*/
|
|
10
|
+
export function pageRouteChange({ select, open, close } = {}) {
|
|
11
|
+
return function routeChange(entity, payload, api) {
|
|
12
|
+
// The payload, not the router entity: inside the router's own notify, the
|
|
13
|
+
// entity still names the route being left.
|
|
14
|
+
if (payload.route !== entity.id) {
|
|
15
|
+
close?.(entity, api)
|
|
16
|
+
return
|
|
17
|
+
}
|
|
18
|
+
open?.(entity, select?.(payload), api)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const BASE = "http://same.invalid"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A path taken from a URL, such as where to return after signing in, if it
|
|
5
|
+
* stays on this site; `null` otherwise. Comparing origins catches the forms
|
|
6
|
+
* browsers read as another site: `//evil.com`, `/\evil.com`, `https://evil.com`.
|
|
7
|
+
* @param {unknown} value
|
|
8
|
+
* @returns {string | null}
|
|
9
|
+
*/
|
|
10
|
+
export function safePath(value) {
|
|
11
|
+
if (typeof value !== "string" || !value.startsWith("/")) return null
|
|
12
|
+
try {
|
|
13
|
+
const url = new URL(value, BASE)
|
|
14
|
+
if (url.origin !== BASE) return null
|
|
15
|
+
return url.pathname + url.search + url.hash
|
|
16
|
+
} catch {
|
|
17
|
+
return null
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -20,7 +20,7 @@ export interface LiveReloadConfig<TEntity = any> {
|
|
|
20
20
|
delay?: number
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
export
|
|
23
|
+
export type LiveReloadBehavior = {
|
|
24
24
|
create: (entity: any, payload?: any, api?: Api) => void
|
|
25
25
|
destroy: (entity: any, payload?: any, api?: Api) => void
|
|
26
26
|
}
|
package/types/form.d.ts
CHANGED
|
@@ -56,8 +56,6 @@ export interface FormEntity<T extends FormValues = FormValues> {
|
|
|
56
56
|
* The payload for the `formFieldChange` event.
|
|
57
57
|
*/
|
|
58
58
|
export interface FormFieldChangePayload<T extends FormValues = FormValues> {
|
|
59
|
-
/** The ID of the target form entity. */
|
|
60
|
-
entityId: string | number
|
|
61
59
|
/** The dot-notation path to the field (e.g., 'user.name'). */
|
|
62
60
|
path: string
|
|
63
61
|
/** The new value of the field. */
|
|
@@ -70,8 +68,6 @@ export interface FormFieldChangePayload<T extends FormValues = FormValues> {
|
|
|
70
68
|
* The payload for the `formFieldBlur` event.
|
|
71
69
|
*/
|
|
72
70
|
export interface FormFieldBlurPayload {
|
|
73
|
-
/** The ID of the target form entity. */
|
|
74
|
-
entityId: string | number
|
|
75
71
|
/** The dot-notation path to the field (e.g., 'user.name'). */
|
|
76
72
|
path: string
|
|
77
73
|
/** An optional function to validate the field's value on blur. */
|
|
@@ -82,8 +78,6 @@ export interface FormFieldBlurPayload {
|
|
|
82
78
|
* The payload for the `fieldArrayAppend` event.
|
|
83
79
|
*/
|
|
84
80
|
export interface FieldArrayAppendPayload {
|
|
85
|
-
/** The ID of the target form entity. */
|
|
86
|
-
entityId: string | number
|
|
87
81
|
/** The dot-notation path to the array field. */
|
|
88
82
|
path: string
|
|
89
83
|
/** The value to append to the array. */
|
|
@@ -94,8 +88,6 @@ export interface FieldArrayAppendPayload {
|
|
|
94
88
|
* The payload for the `fieldArrayRemove` event.
|
|
95
89
|
*/
|
|
96
90
|
export interface FieldArrayRemovePayload {
|
|
97
|
-
/** The ID of the target form entity. */
|
|
98
|
-
entityId: string | number
|
|
99
91
|
/** The dot-notation path to the array field. */
|
|
100
92
|
path: string
|
|
101
93
|
/** The index of the item to remove. */
|
|
@@ -106,8 +98,6 @@ export interface FieldArrayRemovePayload {
|
|
|
106
98
|
* The payload for the `fieldArrayInsert` event.
|
|
107
99
|
*/
|
|
108
100
|
export interface FieldArrayInsertPayload {
|
|
109
|
-
/** The ID of the target form entity. */
|
|
110
|
-
entityId: string | number
|
|
111
101
|
/** The dot-notation path to the array field. */
|
|
112
102
|
path: string
|
|
113
103
|
/** The index at which to insert the new item. */
|
|
@@ -120,8 +110,6 @@ export interface FieldArrayInsertPayload {
|
|
|
120
110
|
* The payload for the `fieldArrayMove` event.
|
|
121
111
|
*/
|
|
122
112
|
export interface FieldArrayMovePayload {
|
|
123
|
-
/** The ID of the target form entity. */
|
|
124
|
-
entityId: string | number
|
|
125
113
|
/** The dot-notation path to the array field. */
|
|
126
114
|
path: string
|
|
127
115
|
/** The source index of the item to move. */
|
|
@@ -130,20 +118,10 @@ export interface FieldArrayMovePayload {
|
|
|
130
118
|
toIndex: number
|
|
131
119
|
}
|
|
132
120
|
|
|
133
|
-
/**
|
|
134
|
-
* The payload for the `formReset` event.
|
|
135
|
-
*/
|
|
136
|
-
export interface FormResetPayload {
|
|
137
|
-
/** The ID of the target form entity. */
|
|
138
|
-
entityId: string | number
|
|
139
|
-
}
|
|
140
|
-
|
|
141
121
|
/**
|
|
142
122
|
* The payload for the `formValidate` event (synchronous validation).
|
|
143
123
|
*/
|
|
144
124
|
export interface FormValidatePayload<T extends FormValues = FormValues> {
|
|
145
|
-
/** The ID of the target form entity. */
|
|
146
|
-
entityId: string | number
|
|
147
125
|
/**
|
|
148
126
|
* A function that validates the entire form's values and returns
|
|
149
127
|
* a complete error object.
|
|
@@ -155,8 +133,6 @@ export interface FormValidatePayload<T extends FormValues = FormValues> {
|
|
|
155
133
|
* The payload for the `formValidateAsync` event (asynchronous validation).
|
|
156
134
|
*/
|
|
157
135
|
export interface FormValidateAsyncPayload<T extends FormValues = FormValues> {
|
|
158
|
-
/** The ID of the target form entity. */
|
|
159
|
-
entityId: string | number
|
|
160
136
|
/**
|
|
161
137
|
* An async function that validates the entire form's values and returns
|
|
162
138
|
* a complete error object.
|
|
@@ -170,8 +146,6 @@ export interface FormValidateAsyncPayload<T extends FormValues = FormValues> {
|
|
|
170
146
|
export interface FormValidationCompletePayload<
|
|
171
147
|
T extends FormValues = FormValues,
|
|
172
148
|
> {
|
|
173
|
-
/** The ID of the target form entity. */
|
|
174
|
-
entityId: string | number
|
|
175
149
|
/** The validation errors returned from async validation. */
|
|
176
150
|
errors: FormErrors<T>
|
|
177
151
|
/** Whether the form is valid (no errors). */
|
|
@@ -182,8 +156,6 @@ export interface FormValidationCompletePayload<
|
|
|
182
156
|
* The payload for the `formValidationError` event.
|
|
183
157
|
*/
|
|
184
158
|
export interface FormValidationErrorPayload {
|
|
185
|
-
/** The ID of the target form entity. */
|
|
186
|
-
entityId: string | number
|
|
187
159
|
/** The error message from the failed validation. */
|
|
188
160
|
error: string
|
|
189
161
|
}
|
|
@@ -261,12 +233,8 @@ export type FormType = {
|
|
|
261
233
|
/**
|
|
262
234
|
* Resets the form to its initial state.
|
|
263
235
|
* @param entity The form entity.
|
|
264
|
-
* @param payload The reset event payload.
|
|
265
236
|
*/
|
|
266
|
-
reset<T extends FormValues>(
|
|
267
|
-
entity: FormEntity<T>,
|
|
268
|
-
payload: FormResetPayload,
|
|
269
|
-
): void
|
|
237
|
+
reset<T extends FormValues>(entity: FormEntity<T>): void
|
|
270
238
|
|
|
271
239
|
/**
|
|
272
240
|
* Synchronously validates the entire form.
|
package/types/mount.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { TemplateResult } from "lit-html"
|
|
1
|
+
import type { nothing, TemplateResult } from "lit-html"
|
|
2
2
|
import type {
|
|
3
3
|
AnyTypeDefinition,
|
|
4
4
|
BaseEntity,
|
|
@@ -7,9 +7,6 @@ import type {
|
|
|
7
7
|
Api as StoreApi,
|
|
8
8
|
} from "@inglorious/store"
|
|
9
9
|
|
|
10
|
-
// `mount` gives the store's api a `render`, so loading these types gives the
|
|
11
|
-
// store's `Api` one too. There is a single `Api`: the one handlers receive,
|
|
12
|
-
// and the one components take.
|
|
13
10
|
declare module "@inglorious/store" {
|
|
14
11
|
interface Api<
|
|
15
12
|
TEntity extends BaseEntity = BaseEntity,
|
|
@@ -21,15 +18,15 @@ declare module "@inglorious/store" {
|
|
|
21
18
|
* of an unmatched path, renders nothing.
|
|
22
19
|
* @param typeName Optional type name to lazy-register.
|
|
23
20
|
* @param type Optional type definition to register when typeName is provided.
|
|
24
|
-
* @returns The rendered template or
|
|
21
|
+
* @returns The rendered template, or `nothing` if not found.
|
|
25
22
|
*/
|
|
26
23
|
render: {
|
|
27
|
-
(id: string | undefined): TemplateResult | string
|
|
24
|
+
(id: string | undefined): TemplateResult | string | typeof nothing
|
|
28
25
|
(
|
|
29
26
|
id: string,
|
|
30
27
|
typeName: string,
|
|
31
28
|
type: AnyTypeDefinition,
|
|
32
|
-
): TemplateResult | string
|
|
29
|
+
): TemplateResult | string | typeof nothing
|
|
33
30
|
}
|
|
34
31
|
}
|
|
35
32
|
}
|
package/types/router.d.ts
CHANGED
|
@@ -183,3 +183,41 @@ export function addRoute(
|
|
|
183
183
|
* @param path The route path or pattern to remove.
|
|
184
184
|
*/
|
|
185
185
|
export function removeRoute(path: string): void
|
|
186
|
+
|
|
187
|
+
/** The steps of a page entity's `routeChange`, all optional. */
|
|
188
|
+
export interface PageRouteHandlers<Entity, Selected> {
|
|
189
|
+
/** Picks what `open` needs from the route, such as a param. */
|
|
190
|
+
select?: (payload: RouteChangePayload) => Selected
|
|
191
|
+
/** The route resolved to this entity. */
|
|
192
|
+
open?: (entity: Entity, selected: Selected, api: Api) => void
|
|
193
|
+
/** The route resolved to another entity. */
|
|
194
|
+
close?: (entity: Entity, api: Api) => void
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A `routeChange` handler for a page entity: `open` when the route resolved to
|
|
199
|
+
* it, with what `select` picks from the route, and `close` when it resolved
|
|
200
|
+
* elsewhere. It reads the route from the payload: inside the router's own
|
|
201
|
+
* notify, the router entity still names the route being left.
|
|
202
|
+
*/
|
|
203
|
+
export function pageRouteChange<
|
|
204
|
+
Entity extends { id: string },
|
|
205
|
+
Selected = undefined,
|
|
206
|
+
>(
|
|
207
|
+
handlers?: PageRouteHandlers<Entity, Selected>,
|
|
208
|
+
): (entity: Entity, payload: RouteChangePayload, api: Api) => void
|
|
209
|
+
|
|
210
|
+
/** What the router broadcasts as `routeChange`. */
|
|
211
|
+
export interface RouteChangePayload {
|
|
212
|
+
route: string
|
|
213
|
+
params: RouteParams
|
|
214
|
+
query: QueryParams
|
|
215
|
+
path: string
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* A path taken from a URL, such as where to return after signing in, if it
|
|
220
|
+
* stays on this site: with its query and hash. `null` for anything a browser
|
|
221
|
+
* would read as another site, like `//evil.com` or `/\evil.com`.
|
|
222
|
+
*/
|
|
223
|
+
export function safePath(value: unknown): string | null
|