@inglorious/web 6.15.0 → 6.17.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 CHANGED
@@ -272,7 +272,7 @@ If you want a framework that **does not fight JavaScript**, this is the one.
272
272
  ## Installation
273
273
 
274
274
  ```bash
275
- npm install @inglorious/web
275
+ pnpm add @inglorious/web
276
276
  ```
277
277
 
278
278
  ---
@@ -429,7 +429,7 @@ test("counter button has click handler", () => {
429
429
  **No special setup required:**
430
430
 
431
431
  ```bash
432
- npm install --save-dev vitest # or jest, or node:test
432
+ pnpm add -D vitest # or jest, or node:test
433
433
  ```
434
434
 
435
435
  That's it. No `@testing-library/react`, no `renderHook`, no `act()` wrappers.
@@ -697,7 +697,7 @@ This Vite plugin transforms standard JSX/TSX into optimized `lit-html` templates
697
697
 
698
698
  To use it:
699
699
 
700
- 1. Install the plugin: `npm install -D @inglorious/vite-plugin-jsx`
700
+ 1. Install the plugin: `pnpm add -D @inglorious/vite-plugin-jsx`
701
701
  2. Add it to your `vite.config.js`
702
702
  3. Write your render functions using JSX
703
703
 
@@ -1062,7 +1062,7 @@ api.notify("navigate", {
1062
1062
 
1063
1063
  You can improve performance by lazy-loading routes. Use a loader function that returns a dynamic import when registering the route via `setRoutes`.
1064
1064
 
1065
- **Note:** The imported module must use a named export for the entity type (not `export default`), so the router can register it with a unique name in the store.
1065
+ **Note:** The imported module must use a named export for the entity type, so the router can register it with a unique name in the store.
1066
1066
 
1067
1067
  ```javascript
1068
1068
  // store.js
@@ -1088,6 +1088,18 @@ export const AdminPage = {
1088
1088
  }
1089
1089
  ```
1090
1090
 
1091
+ A module can hold more types than the page, such as its grid and form. The router registers every export that an entity is of, and those entities get their `create` once their type arrives. The route goes to the default export's entity, or to the first export that renders when there is no default: name the page with `export default` when other exports render too.
1092
+
1093
+ ```javascript
1094
+ // pages/clients.js
1095
+ export const ClientsGrid = { render: (entity) => html`…` }
1096
+ export const ClientsForm = { render: (entity) => html`…` }
1097
+ export const ClientsPage = { render: (entity, api) => html`…` }
1098
+ export default ClientsPage
1099
+ ```
1100
+
1101
+ While a route loads, the router entity has `isLoading` and `loadingPath`. Navigating to the same path again doesn't load it twice. Navigating elsewhere meanwhile wins: the module still registers when it arrives, but the router stays where the user went.
1102
+
1091
1103
  ### 5. Page Entities
1092
1104
 
1093
1105
  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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/web",
3
- "version": "6.15.0",
3
+ "version": "6.17.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": [
@@ -121,12 +121,12 @@
121
121
  },
122
122
  "sideEffects": false,
123
123
  "dependencies": {
124
- "@inglorious/utils": "^5.1.0",
124
+ "@inglorious/utils": "^5.2.0",
125
125
  "@lit-labs/ssr-client": "^1.1.8",
126
126
  "lit-html": "^3.3.3"
127
127
  },
128
128
  "peerDependencies": {
129
- "@inglorious/store": "^12.1.1"
129
+ "@inglorious/store": "^12.3.0"
130
130
  },
131
131
  "devDependencies": {
132
132
  "@inglorious/eslint-config": "1.2.0",
@@ -28,7 +28,7 @@ const DENIED = "denied"
28
28
  * @param {string} [config.consentKey] - The localStorage key of the choice.
29
29
  *
30
30
  * @example
31
- * const types = { Analytics: [createAnalytics({ adapter }), renderers] }
31
+ * const types = { Analytics: [createAnalytics({ adapter }), template] }
32
32
  * const entities = { analytics: { type: "Analytics" } }
33
33
  * // later, anywhere
34
34
  * api.notify("#analytics:analyticsTrack", { name: "sign_up" })
@@ -31,10 +31,13 @@ let areListenersInitialized = false
31
31
  export function init() {
32
32
  if (areListenersInitialized) return
33
33
 
34
+ // Only a press that would submit or reset a form without saying so: any
35
+ // other button's default is its own, such as a `commandfor` opening a menu.
34
36
  document.addEventListener("click", (event) => {
35
37
  const button = event.target.closest("button")
36
38
 
37
- if (!button || button.getAttribute("type") === "submit") return
39
+ if (!button?.form || button.type === "button") return
40
+ if (button.getAttribute("type") === "submit") return
38
41
 
39
42
  event.preventDefault()
40
43
  })
package/src/push/index.js CHANGED
@@ -45,7 +45,7 @@ const tappedAdapters = new WeakSet()
45
45
  * const types = {
46
46
  * PushPrompt: {
47
47
  * ...prompt,
48
- * ...renderers,
48
+ * ...template,
49
49
  * sessionStart: prompt.pushStart,
50
50
  * sessionEnd: prompt.pushStop,
51
51
  * },
@@ -98,24 +98,20 @@ export function createHandlers(routeConfig) {
98
98
  async popstate(entity, payload, api) {
99
99
  const path = window.location.pathname + window.location.search
100
100
  const route = findRoute(routeConfig, path)
101
- const entityId = entity.id
102
101
 
103
102
  if (route) {
104
103
  if (typeof route.route === "function") {
105
- entity.isLoading = true
106
- entity.error = null
107
-
108
- try {
109
- const module = await route.route()
110
- api.notify(`#${entityId}:routeLoadSuccess`, { module, route })
111
- api.notify(`#${entityId}:popstate`, payload)
112
- } catch (error) {
113
- api.notify(`#${entityId}:routeLoadError`, { error, path })
114
- }
115
-
104
+ await loadRoute(
105
+ entity,
106
+ route,
107
+ path,
108
+ { event: "popstate", payload },
109
+ api,
110
+ )
116
111
  return
117
112
  }
118
113
 
114
+ stopLoading(entity)
119
115
  updateRouter(entity, route)
120
116
  entity.idx = window.history.state?.idx ?? FIRST_HISTORY_INDEX
121
117
 
@@ -152,7 +148,6 @@ export function createHandlers(routeConfig) {
152
148
  }
153
149
 
154
150
  const route = findRoute(routeConfig, path)
155
- const entityId = entity.id
156
151
 
157
152
  if (!route) {
158
153
  console.warn(`No route matches path: ${path}`)
@@ -168,20 +163,17 @@ export function createHandlers(routeConfig) {
168
163
  }
169
164
 
170
165
  if (typeof route.route === "function") {
171
- entity.isLoading = true
172
- entity.error = null
173
-
174
- try {
175
- const module = await route.route()
176
- api.notify(`#${entityId}:routeLoadSuccess`, { module, route })
177
- api.notify(`#${entityId}:navigate`, payload)
178
- } catch (error) {
179
- api.notify(`#${entityId}:routeLoadError`, { error, path })
180
- }
181
-
166
+ await loadRoute(
167
+ entity,
168
+ route,
169
+ path,
170
+ { event: "navigate", payload },
171
+ api,
172
+ )
182
173
  return
183
174
  }
184
175
 
176
+ stopLoading(entity)
185
177
  updateRouter(entity, route)
186
178
 
187
179
  const historyState = {
@@ -226,41 +218,94 @@ export function createHandlers(routeConfig) {
226
218
 
227
219
  /**
228
220
  * Handles successful loading of a lazily-loaded route module.
229
- * Registers the loaded type in the runtime type registry via `api.setType`
230
- * and updates the `routeConfig` entry for the pattern.
221
+ * Registers the module's types that are not registered yet: the routed
222
+ * one, which is the default export or else the first export that renders,
223
+ * and every other export that an entity is of, such as a page's grid or
224
+ * form. The pattern then routes to the routed type's entity, and the
225
+ * navigation resumes unless another one started while this module loaded.
231
226
  * @param {RouterEntity} entity
232
- * @param {{module: object, route: {pattern: string, route: string}}} payload
227
+ * @param {{module: object, route: {pattern: string}, path: string, resume?: {event: string, payload: unknown}}} payload
233
228
  * @param {Api} api
234
229
  */
235
230
  routeLoadSuccess(entity, payload, api) {
236
- const { module, route } = payload
231
+ const { module, route, path, resume } = payload
237
232
 
238
- const [typeName, type] = Object.entries(module).find(
239
- ([, type]) => type?.render,
233
+ const exports = Object.entries(module).filter(
234
+ ([name]) => name !== "default",
240
235
  )
236
+ const [routedName] =
237
+ exports.find(([, type]) => type === module.default) ??
238
+ exports.find(([, type]) => type?.render)
239
+
240
+ for (const [typeName, type] of exports) {
241
+ if (api.getType(typeName)) continue
242
+ if (typeName !== routedName && !api.getEntities(typeName).length) {
243
+ continue
244
+ }
245
+ api.setType(typeName, type)
246
+ }
241
247
 
242
- api.setType(typeName, type)
243
- const [routeEntity] = api.getEntities(typeName)
244
- routeConfig[route.pattern] = routeEntity?.id ?? toCamelCase(typeName)
248
+ const [routeEntity] = api.getEntities(routedName)
249
+ routeConfig[route.pattern] = routeEntity?.id ?? toCamelCase(routedName)
245
250
 
246
- entity.isLoading = false
251
+ if (entity.loadingPath !== path) return
252
+ stopLoading(entity)
253
+ if (resume) api.notify(`#${entity.id}:${resume.event}`, resume.payload)
247
254
  },
248
255
 
249
256
  /**
250
- * Handles errors during lazy route loading.
257
+ * Handles errors during lazy route loading, unless another navigation
258
+ * started while the route loaded.
251
259
  * @param {RouterEntity} entity - The router entity.
252
260
  * @param {{error: Error, path: string}} payload - The error payload.
253
261
  */
254
262
  routeLoadError(entity, payload) {
255
263
  const { error, path } = payload
256
264
  console.error(`Failed to load route ${path}:`, error)
265
+ if (entity.loadingPath !== path) return
266
+ stopLoading(entity)
257
267
  entity.path = path
258
- entity.isLoading = false
259
268
  entity.error = error
260
269
  },
261
270
  }
262
271
  }
263
272
 
273
+ /**
274
+ * Loads a lazy route's module, unless the same path is loading already: a
275
+ * second load would register its types and open its page twice.
276
+ * @param {RouterEntity} entity - The router entity.
277
+ * @param {object} route - The matched route, whose `route` is the loader.
278
+ * @param {string} path - The path being loaded.
279
+ * @param {{event: string, payload: unknown}} resume - The event to run again once loaded.
280
+ * @param {Api} api - The application API.
281
+ */
282
+ async function loadRoute(entity, route, path, resume, api) {
283
+ if (entity.isLoading && entity.loadingPath === path) return
284
+
285
+ const entityId = entity.id
286
+ entity.isLoading = true
287
+ entity.loadingPath = path
288
+ entity.error = null
289
+
290
+ try {
291
+ const module = await route.route()
292
+ api.notify(`#${entityId}:routeLoadSuccess`, { module, route, path, resume })
293
+ } catch (error) {
294
+ api.notify(`#${entityId}:routeLoadError`, { error, path })
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Marks the router as no longer loading, so that a route still loading does
300
+ * not take over once it arrives.
301
+ * @param {RouterEntity} entity - The router entity.
302
+ */
303
+ function stopLoading(entity) {
304
+ if (!entity.isLoading) return
305
+ entity.isLoading = false
306
+ entity.loadingPath = null
307
+ }
308
+
264
309
  /**
265
310
  * Builds a URL path by substituting parameters into a route pattern.
266
311
  * @param {string} pattern - The route pattern (e.g., "/users/:userId").
package/types/mount.d.ts CHANGED
@@ -1,16 +1,19 @@
1
1
  import type { nothing, TemplateResult } from "lit-html"
2
2
  import type {
3
+ AnyEvents,
3
4
  AnyTypeDefinition,
5
+ Api,
4
6
  BaseEntity,
5
7
  EntitiesState,
6
8
  Store,
7
- Api as StoreApi,
8
9
  } from "@inglorious/store"
9
10
 
10
11
  declare module "@inglorious/store" {
11
12
  interface Api<
12
13
  TEntity extends BaseEntity = BaseEntity,
13
14
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
15
+ // Unused here, but every declaration of `Api` must take the same parameters.
16
+ TEvents = AnyEvents,
14
17
  > {
15
18
  /**
16
19
  * Renders an entity or a type component by its ID.
@@ -31,10 +34,12 @@ declare module "@inglorious/store" {
31
34
  }
32
35
  }
33
36
 
34
- export type Api<
35
- TEntity extends BaseEntity = BaseEntity,
36
- TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
37
- > = StoreApi<TEntity, TState>
37
+ /**
38
+ * The store's api, with `render` added above. It is the store's own interface,
39
+ * re-exported rather than aliased: an interface is resolved lazily, so an app
40
+ * can tell its api the events of types whose handlers take that same api.
41
+ */
42
+ export type { Api }
38
43
 
39
44
  /**
40
45
  * Root error-boundary options for `mount`.
@@ -77,9 +82,10 @@ export interface MountOptions<
77
82
  export function mount<
78
83
  TEntity extends BaseEntity = BaseEntity,
79
84
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
85
+ TEvents = AnyEvents,
80
86
  >(
81
- store: Store<TEntity, TState>,
82
- renderFn: (api: Api<TEntity, TState>) => TemplateResult | null,
87
+ store: Store<TEntity, TState, TEvents>,
88
+ renderFn: (api: Api<TEntity, TState, TEvents>) => TemplateResult | null,
83
89
  element: HTMLElement | DocumentFragment,
84
90
  options?: MountOptions<TEntity, TState>,
85
91
  ): () => void
package/types/router.d.ts CHANGED
@@ -42,10 +42,30 @@ export interface RouterEntity {
42
42
  idx?: number
43
43
  /** Whether a route is currently loading asynchronously. */
44
44
  isLoading?: boolean
45
+ /** The path whose route is loading; a navigation elsewhere clears it. */
46
+ loadingPath?: string | null
45
47
  /** An error that occurred during route loading. */
46
48
  error?: Error | null
47
49
  }
48
50
 
51
+ /** The payload of `routeLoadSuccess`. */
52
+ export interface RouteLoadSuccessPayload {
53
+ /** The loaded module. */
54
+ module: Record<string, unknown>
55
+ /** The matched route. */
56
+ route: { pattern: string }
57
+ /** The path that was loaded. */
58
+ path: string
59
+ /** The event to run again once loaded. */
60
+ resume?: { event: "navigate" | "popstate"; payload: unknown }
61
+ }
62
+
63
+ /** The payload of `routeLoadError`. */
64
+ export interface RouteLoadErrorPayload {
65
+ error: Error
66
+ path: string
67
+ }
68
+
49
69
  /**
50
70
  * The payload for the `navigate` function.
51
71
  */
@@ -135,15 +155,22 @@ export type RouterType = {
135
155
  popstate(entity: RouterEntity, payload: any, api: Api): void | Promise<void>
136
156
 
137
157
  /**
138
- * Handles successful async route loading for a pattern.
139
- * Registers the loaded type and updates runtime route config.
158
+ * Handles successful async route loading for a pattern. Registers the
159
+ * module's types that entities are of, routes the pattern to the default
160
+ * export (or else the first export that renders) and resumes the navigation,
161
+ * unless another one started while the module loaded.
140
162
  */
141
- routeLoadSuccess(entity: RouterEntity, payload: any, api: Api): void
163
+ routeLoadSuccess(
164
+ entity: RouterEntity,
165
+ payload: RouteLoadSuccessPayload,
166
+ api: Api,
167
+ ): void
142
168
 
143
169
  /**
144
- * Handles errors that occurred while loading a lazy route.
170
+ * Handles errors that occurred while loading a lazy route, unless another
171
+ * navigation started while it loaded.
145
172
  */
146
- routeLoadError(entity: RouterEntity, payload: any): void
173
+ routeLoadError(entity: RouterEntity, payload: RouteLoadErrorPayload): void
147
174
  }
148
175
 
149
176
  export declare const Router: RouterType