@inglorious/web 6.28.0 → 6.30.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.
Files changed (58) hide show
  1. package/README.md +31 -2198
  2. package/package.json +50 -38
  3. package/src/auth/index.js +23 -21
  4. package/src/decorators/limit.js +67 -0
  5. package/src/decorators/with-debounce/index.js +6 -57
  6. package/src/decorators/with-throttle/index.js +12 -67
  7. package/src/device/biometrics/index.js +86 -0
  8. package/src/device/compass/handlers.js +163 -0
  9. package/src/{sensors → device}/element-size/handlers.js +2 -2
  10. package/src/device/geolocation/index.js +120 -0
  11. package/src/{keyboard → device/keyboard}/index.js +58 -21
  12. package/src/device/local-notifications/index.js +133 -0
  13. package/src/{sensors → device}/media-query/handlers.js +2 -2
  14. package/src/{sensors → device}/network-status/handlers.js +1 -1
  15. package/src/{sensors → device}/page-visibility/handlers.js +1 -1
  16. package/src/{native → device}/share/index.js +1 -1
  17. package/src/device/storage/index.js +61 -0
  18. package/src/mount.js +7 -4
  19. package/src/native/app-links/index.js +44 -30
  20. package/src/native/back-button/index.js +40 -21
  21. package/src/native/index.js +0 -32
  22. package/src/native/live-update/index.js +104 -92
  23. package/src/native/system-bars/index.js +63 -33
  24. package/src/native/update/index.js +37 -38
  25. package/src/pwa/index.js +67 -3
  26. package/src/pwa/update.js +10 -20
  27. package/types/auth.d.ts +1 -10
  28. package/types/device/biometrics.d.ts +51 -0
  29. package/types/{sensors → device}/compass.d.ts +0 -2
  30. package/types/{sensors → device}/geolocation.d.ts +25 -7
  31. package/types/device/keyboard.d.ts +28 -0
  32. package/types/device/local-notifications.d.ts +76 -0
  33. package/types/device/storage.d.ts +30 -0
  34. package/types/mount.d.ts +11 -5
  35. package/types/native/app-links.d.ts +22 -14
  36. package/types/native/back-button.d.ts +22 -12
  37. package/types/native/index.d.ts +0 -19
  38. package/types/native/live-update.d.ts +25 -32
  39. package/types/native/system-bars.d.ts +24 -8
  40. package/types/native/update.d.ts +12 -25
  41. package/types/pwa.d.ts +11 -20
  42. package/src/pwa/handlers.js +0 -17
  43. package/src/sensors/compass/handlers.js +0 -209
  44. package/src/sensors/geolocation/handlers.js +0 -168
  45. package/src/sensors/geolocation/index.js +0 -3
  46. package/types/keyboard.d.ts +0 -8
  47. /package/src/{sensors → device}/compass/index.js +0 -0
  48. /package/src/{sensors → device}/element-size/index.js +0 -0
  49. /package/src/{native → device}/haptics/index.js +0 -0
  50. /package/src/{sensors → device}/media-query/index.js +0 -0
  51. /package/src/{sensors → device}/network-status/index.js +0 -0
  52. /package/src/{sensors → device}/page-visibility/index.js +0 -0
  53. /package/types/{sensors → device}/element-size.d.ts +0 -0
  54. /package/types/{native → device}/haptics.d.ts +0 -0
  55. /package/types/{sensors → device}/media-query.d.ts +0 -0
  56. /package/types/{sensors → device}/network-status.d.ts +0 -0
  57. /package/types/{sensors → device}/page-visibility.d.ts +0 -0
  58. /package/types/{native → device}/share.d.ts +0 -0
package/README.md CHANGED
@@ -1,2233 +1,66 @@
1
1
  # @inglorious/web
2
2
 
3
- [![NPM version](https://img.shields.io/npm/v/@inglorious/web.svg)](https://www.npmjs.com/package/@inglorious/web)
3
+ [![NPM version](https://img.shields.io/npm/v/@inglorious/web.svg)](https://www.npmjs.com/package/@inglorious/web)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- A lightweight, reactive-enough web framework built on **pure JavaScript**, the entity-based state management provided by **@inglorious/store**, and the DOM-diffing efficiency of **lit-html**.
6
+ A web framework that renders the whole UI as a function of an [Inglorious Store](https://www.npmjs.com/package/@inglorious/store) of entities, and lets [lit-html](https://lit.dev/docs/libraries/standalone-templates/) update only the DOM that changed. Plain JavaScript: no compiler, no signals, no component state.
7
7
 
8
- Unlike modern frameworks that invent their own languages or rely on signals, proxies, or compilers, **@inglorious/web embraces plain JavaScript** and a transparent architecture.
8
+ **[Documentation](https://inglorious.dev/web/)**
9
9
 
10
- It's a **complete framework**: it ships with a client-side router, declarative forms, geolocation and compass state, async helpers (via `@inglorious/store/async`), and a dedicated testing utilities entry point (`@inglorious/web/test`) that re-exports `trigger` from `@inglorious/store` and `render` from `lit-html`. UI primitives (controls, data display, navigation, feedback, layout, surfaces) live in the companion package **[Inglorious UI](https://inglorious.dev/ui)**.
10
+ ## Install
11
11
 
12
- ---
13
-
14
- ## Features
15
-
16
- - **Full-tree Re-rendering with DOM Diffing**
17
- Your entire template tree re-renders on every state change, while **lit-html updates only the minimal DOM parts**.
18
- No VDOM, no signals, no hidden dependencies.
19
-
20
- - **Entity-Based Rendering Model**
21
- Each entity type defines its own `render(entity, api)` method.
22
- `api.render(id, typeName?, Type?)` composes the UI by invoking the correct renderer for each entity and can lazily register a missing type.
23
-
24
- - **Type Composition**
25
- Types can be composed as arrays of behaviors, enabling reusable patterns like authentication guards, logging, or any cross-cutting concern.
26
-
27
- - **Simple and Predictable API**
28
- Zero magic, zero reactivity graphs, zero compiler.
29
- Just JavaScript functions and store events.
30
-
31
- - **Router, Forms, Geolocation, Compass, Async, Testing utilities**
32
- High-level primitives built on the same predictable model. UI primitives (tables, virtual lists, comboboxes, and more) live in **[Inglorious UI](https://inglorious.dev/ui)**.
33
-
34
- - **Zero Component State**
35
- All state lives in the store — never inside components.
36
-
37
- - **No Signals, No Subscriptions, No Framework-Level Memory Leaks**
38
- Because every render is triggered by the store, and lit-html handles the rest — no subscription cleanup needed.
39
-
40
- - **No compilation required**
41
- Apps can run directly in the browser — no build/compile step is strictly necessary (though you may use bundlers or Vite for convenience in larger projects).
42
-
43
- ---
44
-
45
- ## Create App (scaffolding)
46
-
47
- To help bootstrap projects quickly, there's an official scaffolding tool: **[`@inglorious/create-app`](https://www.npmjs.com/package/@inglorious/create-app)**. It generates opinionated boilerplates so you can start coding right away.
48
-
49
- Available templates:
50
-
51
- - **minimal** — plain HTML, CSS, and JS (no build step)
52
- - **js** — Vite-based JavaScript project
53
- - **ts** — Vite + TypeScript project
54
- - **ssx-js** — Static Site Xecution (SSX) project using JavaScript
55
- - **ssx-ts** — Static Site Xecution (SSX) project using TypeScript
56
-
57
- Use the scaffolder to create a starter app tailored to your workflow.
58
-
59
- ---
60
-
61
- ## Key Architectural Insight
62
-
63
- ### ✨ **Inglorious Web re-renders the whole template tree on each state change.**
64
-
65
- **Important:** The DOM itself is not re-created. Only the template function reruns, and lit-html's efficient diffing updates just the changed DOM nodes.
66
-
67
- Thanks to lit-html's optimized diffing, this is fast, predictable, and surprisingly efficient.
68
-
69
- This means:
70
-
71
- - **You do NOT need fine-grained reactivity**
72
- - **You do NOT need selectors/signals/memos**
73
- - **You do NOT track dependencies between UI fragments**
74
- - **You cannot accidentally create memory leaks through subscriptions**
75
-
76
- You get Svelte-like ergonomic simplicity, but with no compiler and no magic.
77
-
78
- > "Re-render everything → let lit-html update only what changed."
79
-
80
- It's that simple — and surprisingly fast in practice.
81
-
82
- ---
83
-
84
- ## When to Use Inglorious Web
85
-
86
- - You want predictable behavior
87
- - You prefer explicit state transitions
88
- - You want to avoid complex reactive graphs
89
- - You want UI to be fully controlled by your entity-based store
90
- - You want to stay entirely in **JavaScript**, without DSLs or compilers
91
- - You want **React-like declarative UI** but without the cost and overhead of React
92
- - You want **pre-rendered sites with SSX**, static or server-rendered on request — same entity patterns, HTML from the server, and client hydration
93
-
94
- This framework is ideal for both small apps and large business UIs.
95
-
96
- ---
97
-
98
- ## When NOT to Use Inglorious Web
99
-
100
- - You're frequently mutating thousands of items without virtualization (use [Inglorious UI](https://inglorious.dev/ui))
101
- - You need framework-agnostic components for users who might not use Inglorious (use Web Components instead)
102
- - Your team is already deeply invested in React/Vue/Angular and migration costs outweigh benefits
103
-
104
- ## When Inglorious Web EXCELS
105
-
106
- - Building **internal component libraries** - Types are more customizable than React components
107
- - Creating **design systems** - Spread, override, and compose behaviors freely
108
- - Building **pattern libraries** - Ship pre-configured entity types that users can adapt
109
- - Apps where **predictable state flow** matters more than ecosystem size
110
-
111
- ---
112
-
113
- ## Why Inglorious Web Avoids Signals
114
-
115
- Other modern frameworks use:
116
-
117
- - Proxies (Vue)
118
- - Observables (MobX)
119
- - Fine-grained signals (Solid, Angular v17+)
120
- - Compiler-generated reactivity (Svelte)
121
- - Fiber or granular subscriptions (React, Preact, Qwik, etc.)
122
-
123
- These systems are powerful but introduce:
124
-
125
- - hidden dependencies
126
- - memory retention risks
127
- - unpredictable update ordering
128
- - steep learning curves
129
- - framework-specific languages
130
- - need for cleanup, teardown, and special lifecycle APIs
131
- - challenges when mixing with game engines, workers, or non-UI code
132
-
133
- ### Inglorious Web takes a different stance:
134
-
135
- ✔ **Every entity update is explicit**
136
- ✔ **Every UI update is a full diff pass**
137
- ✔ **Every part of the system is just JavaScript**
138
- ✔ **No special lifecycle**
139
- ✔ **No subscriptions needed**
140
- ✔ **No signals**
141
- ✔ **No cleanup**
142
- ✔ **No surprises**
143
-
144
- This makes it especially suitable for:
145
-
146
- - realtime applications
147
- - hybrid UI/game engine contexts
148
- - large enterprise apps where predictability matters
149
- - developers who prefer simplicity over magic
150
-
151
- ---
152
-
153
- ## Comparison with Other Frameworks
154
-
155
- ### TL;DR Quick Comparison
156
-
157
- | Framework | Reactivity | Build Transform | Runtime Compiler | Component State | Bundle Size | Learning Curve |
158
- | -------------- | -------------- | ---------------- | ---------------- | --------------- | ----------- | -------------- |
159
- | Inglorious Web | Event-based | None required | No | No (store only) | Tiny | Very Low |
160
- | React | VDOM diffing | JSX + optional\* | No | Yes | Large | Medium/High |
161
- | Vue | Proxy-based | SFC (optional) | Available | Yes | Medium | Medium |
162
- | Svelte | Compiler magic | Required | No | Yes | Small | Medium |
163
- | SolidJS | Fine signals | JSX only | No | No (runs once) | Tiny | Medium/High |
164
- | Qwik | Resumable | Required | No | Yes | Small | Very High |
165
-
166
- \*React Compiler (stable 2024+) provides automatic memoization
167
-
168
- <details>
169
- <summary><strong>Click to expand detailed framework comparisons</strong></summary>
170
-
171
- Here's how @inglorious/web compares to the major players in detail:
172
-
173
- ---
174
-
175
- ### **React**
176
-
177
- | Feature | React | Inglorious Web |
178
- | ------------------------- | ----------------------------- | ---------------------------------- |
179
- | Rendering model | VDOM diff + effects | Full tree template + lit-html diff |
180
- | Language | JSX (non-JS) | Pure JavaScript |
181
- | Component state | Yes | No — store only |
182
- | Refs & lifecycles | Many | None needed |
183
- | Signals / fine reactivity | No (but heavy reconciliation) | No (rely on lit-html diff) |
184
- | Reconciliation overhead | High (full VDOM diff) | Low (template string diff) |
185
- | Bundle size | Large | Tiny |
186
- | Learning curve | Medium/High | Very low |
187
-
188
- React is powerful but complicated. Inglorious Web is simpler, lighter, and closer to native JS.
189
-
190
- ---
191
-
192
- ### **Vue (3)**
193
-
194
- | Feature | Vue | Inglorious Web |
195
- | --------------- | -------------------------- | ----------------------------------- |
196
- | Reactivity | Proxy-based, deep tracking | Event-based updates + lit-html diff |
197
- | Templates | DSL | JavaScript templates |
198
- | Component state | Yes | No |
199
- | Lifecycle | Many | None |
200
- | Compiler | Required for SFC | None |
201
-
202
- Vue reactivity is elegant but complex. Inglorious Web avoids proxies and keeps everything explicit.
203
-
204
- ---
205
-
206
- ### **Svelte**
207
-
208
- | Feature | Svelte | Inglorious Web |
209
- | -------------- | --------------------------- | ------------------ |
210
- | Compiler | Required | None |
211
- | Reactivity | Compiler transforms $labels | Transparent JS |
212
- | Granularity | Fine-grained | Full-tree rerender |
213
- | Learning curve | Medium | Low |
214
-
215
- Svelte is magic; Inglorious Web is explicit.
216
-
217
- ---
218
-
219
- ### **SolidJS**
220
-
221
- | Feature | Solid | Inglorious Web |
222
- | ---------- | -------------------- | ------------------ |
223
- | Reactivity | Fine-grained signals | No signals |
224
- | Components | Run once | Rerun always |
225
- | Cleanup | Required | None |
226
- | Behavior | Highly optimized | Highly predictable |
227
-
228
- Solid is extremely fast but requires a mental model shift.
229
- Inglorious Web trades peak performance for simplicity and zero overhead.
230
-
231
- ---
232
-
233
- ### **Qwik**
234
-
235
- | Feature | Qwik | Inglorious Web |
236
- | -------------------- | -------------------- | -------------- |
237
- | Execution model | Resumable | Plain JS |
238
- | Framework complexity | Very high | Very low |
239
- | Reactivity | Fine-grained signals | None |
240
-
241
- Qwik targets extreme performance at extreme complexity.
242
- Inglorious Web is minimal, predictable, and tiny.
243
-
244
- ---
245
-
246
- ### **HTMX / Alpine / Vanilla DOM**
247
-
248
- Inglorious Web is closer philosophically to **HTMX** and **vanilla JS**, but with a declarative rendering model and entity-based state.
249
-
250
- </details>
251
-
252
- ---
253
-
254
- ## Why Choose Inglorious Web
255
-
256
- - Minimalistic
257
- - Pure JavaScript
258
- - Entity-based and predictable
259
- - Extremely easy to reason about
260
- - One render path, no hidden rules
261
- - No reactivity graphs
262
- - No per-component subscriptions
263
- - No framework-level memory leaks
264
- - No build step required (apps can run in the browser)
265
- - Works perfectly in hybrid UI/game engine contexts
266
- - Uses native ES modules and standards
267
-
268
- If you want a framework that **does not fight JavaScript**, this is the one.
269
-
270
- ---
271
-
272
- ## Installation
273
-
274
- ```bash
275
- pnpm add @inglorious/web
276
- ```
277
-
278
- ---
279
-
280
- ## Quick Start
281
-
282
- ### 1. Define Your Store and Entity Renders
283
-
284
- First, set up your store with entity types. For each type you want to render, add a render method that returns a `lit-html` template.
285
-
286
- ```javascript
287
- // store.js
288
- import { createStore } from "@inglorious/store"
289
- import { html } from "@inglorious/web"
290
-
291
- const types = {
292
- Counter: {
293
- increment(entity) {
294
- entity.value++
295
- },
296
-
297
- // Define how a 'counter' entity should be rendered
298
- render(entity, api) {
299
- return html`
300
- <div>
301
- <span>Count: ${entity.value}</span>
302
- <button @click=${() => api.notify(`#${entity.id}:increment`)}>
303
- +1
304
- </button>
305
- </div>
306
- `
307
- },
308
- },
309
- }
310
-
311
- const entities = {
312
- counter1: { type: "Counter", value: 0 },
313
- counter2: { type: "Counter", value: 10 },
314
- }
315
-
316
- export const store = createStore({ types, entities })
317
- ```
318
-
319
- ### 2. Create Your Root Template and Mount
320
-
321
- Write a root rendering function that uses the provided api to compose the UI, then use `mount` to attach it to the DOM.
322
-
323
- ```javascript
324
- // main.js
325
- import { mount, html } from "@inglorious/web"
326
- import { store } from "./store.js"
327
-
328
- // This function receives the API and returns a lit-html template
329
- const renderApp = (api) => {
330
- const entities = Object.values(api.getEntities())
331
-
332
- return html`
333
- <h1>Counters</h1>
334
- ${entities.map((entity) => api.render(entity.id))}
335
- `
336
- }
337
-
338
- // Mount the app to the DOM
339
- mount(store, renderApp, document.getElementById("root"))
340
- ```
341
-
342
- The `mount` function subscribes to the store and automatically re-renders your template whenever the state changes.
343
-
344
- ---
345
-
346
- ## Testing
347
-
348
- One of Inglorious Web's greatest strengths is **testability**. Entity handlers are pure functions (via Mutative.js), and render functions return simple templates. No special testing libraries, no complex setup, no mocking hell.
349
-
350
- ### Testing Utilities
351
-
352
- The `@inglorious/web/test` entry point re-exports two helpers so you can test handlers and templates without any extra setup:
353
-
354
- - **`trigger`** — comes from `@inglorious/store` (`@inglorious/store/test`). It executes an entity handler and returns the new state plus any dispatched events.
355
- - **`render`** — comes from `lit-html`. It renders a template to a DOM node so you can assert on its output.
356
-
357
- Both are re-exported from `@inglorious/web/test` purely as a convenience, so a web app only needs to depend on `@inglorious/web` to test its handlers and templates.
358
-
359
- #### `trigger(entity, handler, payload?, api?)`
360
-
361
- Execute an entity handler and get back the new state plus any events dispatched. Handlers are wrapped in Mutative.js, so they return new immutable state even though you write mutable-looking code.
362
-
363
- ```javascript
364
- import { trigger } from "@inglorious/web/test"
365
- import { counter } from "./types/counter.js"
366
-
367
- test("increment adds to value", () => {
368
- const { entity, events } = trigger(
369
- { type: "Counter", id: "counter1", value: 10 },
370
- counter.increment,
371
- { amount: 5 },
372
- )
373
-
374
- expect(entity.value).toBe(15)
375
- expect(events).toEqual([]) // No events dispatched
376
- })
377
-
378
- test("increment dispatches overflow event", () => {
379
- const { entity, events } = trigger(
380
- { type: "Counter", id: "counter1", value: 99 },
381
- counter.increment,
382
- { amount: 5 },
383
- )
384
-
385
- expect(entity.value).toBe(104)
386
- expect(events).toEqual([{ type: "overflow", payload: { id: "counter1" } }])
387
- })
388
- ```
389
-
390
- #### `render(template)`
391
-
392
- Render a lit-html template to an HTML string for testing. Perfect for testing render output with simple string assertions.
393
-
394
- ```javascript
395
- import { render } from "@inglorious/web/test"
396
- import { counter } from "./types/counter.js"
397
-
398
- test("counter renders correctly", () => {
399
- const entity = {
400
- type: "Counter",
401
- id: "counter1",
402
- value: 42,
403
- }
404
-
405
- const mockApi = {
406
- notify: jest.fn(),
407
- }
408
-
409
- const template = counter.render(entity, mockApi)
410
- const html = render(template)
411
-
412
- expect(html).toContain("Count: 42")
413
- expect(html).toContain("button")
414
- })
415
-
416
- test("counter button has click handler", () => {
417
- const entity = { type: "Counter", id: "counter1", value: 10 }
418
- const mockApi = { notify: jest.fn() }
419
-
420
- const template = counter.render(entity, mockApi)
421
- const html = render(template)
422
-
423
- expect(html).toContain("onclick")
424
- })
425
- ```
426
-
427
- ### Why Testing is Easy
428
-
429
- **No special setup required:**
430
-
431
- ```bash
432
- pnpm add -D vitest # or jest, or node:test
433
- ```
434
-
435
- That's it. No `@testing-library/react`, no `renderHook`, no `act()` wrappers.
436
-
437
- **Pure functions everywhere:**
438
-
439
- - Entity handlers are pure (thanks to Mutative.js)
440
- - Render functions are pure (they return templates)
441
- - No lifecycle hooks to manage
442
- - No async state updates to wrangle
443
-
444
- **Simple assertions:**
445
-
446
- - Test handlers: `expect(entity.value).toBe(15)`
447
- - Test renders: `expect(html).toContain('expected text')`
448
- - Test events: `expect(events).toHaveLength(1)`
449
-
450
- ### Testing Patterns
451
-
452
- #### Unit Test: Handler Logic
453
-
454
- ```javascript
455
- import { trigger } from "@inglorious/web/test"
456
- import { Todo } from "./types/todo.js"
457
-
458
- test("toggle changes completed status", () => {
459
- const { entity } = trigger(
460
- { type: "Todo", id: "todo1", text: "Buy milk", completed: false },
461
- Todo.toggle,
462
- )
463
-
464
- expect(entity.completed).toBe(true)
465
- })
466
-
467
- test("delete dispatches remove event", () => {
468
- const { events } = trigger(
469
- { type: "Todo", id: "todo1", text: "Buy milk" },
470
- Todo.delete,
471
- )
472
-
473
- expect(events).toEqual([{ type: "#todoList:removeTodo", payload: "todo1" }])
474
- })
475
- ```
476
-
477
- #### Unit Test: Render Output
478
-
479
- ```javascript
480
- import { render } from "@inglorious/web/test"
481
- import { Todo } from "./types/todo.js"
482
-
483
- test("todo renders text and status", () => {
484
- const entity = {
485
- type: "Todo",
486
- id: "todo1",
487
- text: "Buy milk",
488
- completed: false,
489
- }
490
-
491
- const html = render(Todo.render(entity, { notify: jest.fn() }))
492
-
493
- expect(html).toContain("Buy milk")
494
- expect(html).not.toContain("completed")
495
- })
496
-
497
- test("completed todo has completed class", () => {
498
- const entity = {
499
- type: "Todo",
500
- id: "todo1",
501
- text: "Buy milk",
502
- completed: true,
503
- }
504
-
505
- const html = render(Todo.render(entity, { notify: jest.fn() }))
506
-
507
- expect(html).toContain("completed")
508
- })
509
- ```
510
-
511
- #### Integration Test: Full Store
512
-
513
- ```javascript
514
- import { createStore } from "@inglorious/store"
515
- import { Counter } from "./types/counter.js"
516
-
517
- test("full user interaction flow", () => {
518
- const store = createStore({
519
- types: { Counter },
520
- entities: {
521
- counter1: { type: "Counter", id: "counter1", value: 0 },
522
- },
523
- })
524
-
525
- // User clicks increment
526
- store.notify("#counter1:increment", { amount: 5 })
527
- expect(store.entities.counter1.value).toBe(5)
528
-
529
- // User clicks increment again
530
- store.notify("#counter1:increment", { amount: 3 })
531
- expect(store.entities.counter1.value).toBe(8)
532
- })
533
- ```
534
-
535
- #### Testing Computed State
536
-
537
- ```javascript
538
- import { compute } from "@inglorious/store/select"
539
-
540
- test("filtered todos excludes completed", () => {
541
- const todos = [
542
- { id: 1, text: "Buy milk", completed: false },
543
- { id: 2, text: "Walk dog", completed: true },
544
- { id: 3, text: "Write tests", completed: false },
545
- ]
546
-
547
- const getActiveTodos = compute(
548
- (todos) => todos.filter((t) => !t.completed),
549
- [() => todos],
550
- )
551
-
552
- const result = getActiveTodos()
553
-
554
- expect(result).toHaveLength(2)
555
- expect(result[0].text).toBe("Buy milk")
556
- expect(result[1].text).toBe("Write tests")
557
- })
558
- ```
559
-
560
- ### Comparison with React Testing
561
-
562
- **React (with hooks):**
563
-
564
- ```javascript
565
- import { renderHook, act } from "@testing-library/react"
566
-
567
- test("counter increments", () => {
568
- const { result } = renderHook(() => useCounter())
569
-
570
- act(() => {
571
- result.current.increment()
572
- })
573
-
574
- expect(result.current.count).toBe(1)
575
- })
576
- ```
577
-
578
- **Inglorious Web:**
579
-
580
- ```javascript
581
- import { trigger } from "@inglorious/web/test"
582
-
583
- test("counter increments", () => {
584
- const { entity } = trigger({ value: 0 }, counter.increment)
585
-
586
- expect(entity.value).toBe(1)
587
- })
588
- ```
589
-
590
- **The difference:**
591
-
592
- - ❌ React requires `renderHook`, `act()`, special testing library
593
- - ✅ Inglorious just calls the function directly
594
- - ❌ React hooks can't be tested in isolation
595
- - ✅ Inglorious handlers are just functions
596
- - ❌ React has async timing issues
597
- - ✅ Inglorious is synchronous and predictable
598
-
599
- ### Testing Type Composition
600
-
601
- Type composition (like route guards) is also easy to test:
602
-
603
- ```javascript
604
- import { trigger } from "@inglorious/web/test"
605
- import { requireAuth } from "./guards/require-auth.js"
606
- import { AdminPage } from "./pages/admin.js"
607
-
608
- test("requireAuth blocks unauthenticated access", () => {
609
- // Compose the guard with the page type
610
- const GuardedPage = requireAuth(AdminPage)
611
-
612
- // Signed out: the guard was told of no user
613
- const { events } = trigger(
614
- { type: "GuardedPage", id: "admin", user: null },
615
- GuardedPage.routeChange,
616
- { route: "admin", path: "/admin" },
617
- )
618
-
619
- // Should redirect to login
620
- expect(events).toContainEqual(
621
- expect.objectContaining({
622
- type: "navigate",
623
- payload: expect.objectContaining({ to: "/login?from=%2Fadmin" }),
624
- }),
625
- )
626
- })
627
-
628
- test("requireAuth allows authenticated access", () => {
629
- // Signed in: the guard was told of a user
630
- const GuardedPage = requireAuth(AdminPage)
631
-
632
- const { events } = trigger(
633
- { type: "GuardedPage", id: "admin", user: { id: 1 } },
634
- GuardedPage.routeChange,
635
- { route: "admin", path: "/admin" },
636
- )
637
-
638
- // Should NOT redirect
639
- expect(events).not.toContainEqual(
640
- expect.objectContaining({ type: "navigate" }),
641
- )
642
- })
643
- ```
644
-
645
- ### Fast Test Execution
646
-
647
- Because Inglorious tests don't mount components or manipulate the DOM, they're extremely fast:
648
-
649
- ```bash
650
- # Typical test suite times
651
- React: 30-60 seconds for 100 tests
652
- Inglorious: 1-3 seconds for 100 tests
653
- ```
654
-
655
- This makes TDD (Test-Driven Development) actually enjoyable. Fast feedback loops mean you'll actually run tests while coding.
656
-
657
- ### Best Practices
658
-
659
- 1. **Test handlers separately from renders** - Unit test logic, integration test UI
660
- 2. **Use descriptive test names** - "increment adds to value" not "test increment"
661
- 3. **Test edge cases** - Empty states, max values, null checks
662
- 4. **Keep tests simple** - One assertion per test when possible
663
- 5. **Don't over-mock** - Only mock what you must (usually just `api.notify`)
664
-
665
- ### When to Write Tests
666
-
667
- - ✅ **Always test:** Complex business logic, calculations, validations
668
- - ✅ **Often test:** Event handlers, state transitions, conditional renders
669
- - ⚠️ **Sometimes test:** Simple getters, trivial renders
670
- - ❌ **Rarely test:** Third-party components, framework internals
671
-
672
- ### The Bottom Line
673
-
674
- If your framework makes testing painful, developers won't test. If testing is trivial, they will.
675
-
676
- **Inglorious Web makes testing so easy that you'll actually write tests.**
677
-
678
- No special libraries, no complex setup, just pure functions and simple assertions. Testing becomes a natural part of your workflow, not a chore you avoid.
679
-
680
- ---
681
-
682
- ## JSX Support
683
-
684
- If you prefer JSX syntax over template literals, you can use **[`@inglorious/vite-plugin-jsx`](https://www.npmjs.com/package/@inglorious/vite-plugin-jsx)**.
685
-
686
- This Vite plugin transforms standard JSX/TSX into optimized `lit-html` templates at compile time. You get the familiar developer experience of JSX without React's runtime, hooks, or VDOM overhead.
687
-
688
- To use it:
689
-
690
- 1. Install the plugin: `pnpm add -D @inglorious/vite-plugin-jsx`
691
- 2. Add it to your `vite.config.js`
692
- 3. Write your render functions using JSX
693
-
694
- ```jsx
695
- export const Counter = {
696
- render(entity, api) {
697
- return (
698
- <div className="counter">
699
- <span>Count: {entity.value}</span>
700
- <button onClick={() => api.notify(`#${entity.id}:increment`)}>
701
- +1
702
- </button>
703
- </div>
704
- )
705
- },
706
- }
707
- ```
708
-
709
- See the plugin documentation for full details on control flow, attributes, and engine components.
710
-
711
- ---
712
-
713
- ## Vue Template Support
714
-
715
- If you prefer **Vue Single-File Component–style templates**, you can use
716
- **`@inglorious/vite-plugin-vue`** to write Vue-like `<template>` syntax and compile it into optimized `lit-html` render functions for **@inglorious/web**.
717
-
718
- This plugin is **not Vue** and does **not implement Vue’s reactivity model**.
719
- Instead, it provides a **template-only compatibility layer** that maps a well-defined subset of Vue template syntax onto Inglorious Web’s entity-based rendering model.
720
-
721
- ### What This Is (and Is Not)
722
-
723
- ✔ **Is:**
724
-
725
- - A Vue-like _template syntax_ compiler
726
- - Zero-runtime, compile-time transformation
727
- - Direct output to `lit-html`
728
- - Fully compatible with Inglorious entities and store-driven rendering
729
-
730
- ❌ **Is NOT:**
731
-
732
- - Vue runtime
733
- - Vue reactivity (no proxies, refs, watchers)
734
- - Vue SFC compiler
735
- - A drop-in replacement for Vue apps
736
-
737
- Think of it as **“Vue templates as a syntax convenience”**, not Vue itself.
738
-
739
- ---
740
-
741
- ### Supported Syntax
742
-
743
- The plugin supports the most common and useful Vue template features:
744
-
745
- #### Templates
746
-
747
- ```vue
748
- <template>
749
- <div class="counter">
750
- <span>{{ value }}</span>
751
- <button @click="increment">+</button>
752
- </div>
753
- </template>
754
- ```
755
-
756
- #### Interpolations
757
-
758
- - `{{ value }}`
759
- - Automatically prefixed with `entity.` when appropriate
760
-
761
- #### Conditionals
762
-
763
- - `v-if`
764
- - `v-else-if`
765
- - `v-else`
766
-
767
- Compiled using `lit-html`’s `when()` directive.
768
-
769
- #### Loops
770
-
771
- - `v-for="item in items"`
772
- - `v-for="(item, index) in items"`
773
- - Optional `:key`
774
-
775
- Compiled using `lit-html`’s `repeat()` directive.
776
-
777
- #### Bindings
778
-
779
- - `:prop="expr"`
780
- - `v-bind:prop="expr"`
781
- - Static attributes
782
- - Correct handling of property vs attribute bindings
783
-
784
- #### Events
785
-
786
- - `@click="method"`
787
- - `@click="() => method(entity, arg)"`
788
- - `v-on:event="handler"`
789
-
790
- Method references are automatically translated to `api.notify(...)` calls.
791
-
792
- #### Components
793
-
794
- - PascalCase components are treated as entity renders:
795
-
796
- ```vue
797
- <Message />
798
- ```
799
-
800
- ```js
801
- api.render("message")
802
- ```
803
-
804
- ---
805
-
806
- ### Script Sections
807
-
808
- Both JavaScript and TypeScript are supported:
809
-
810
- ```vue
811
- <script lang="ts">
812
- const message: string = "Hello"
813
-
814
- const greet = (entity: any): void => {
815
- console.log(entity.message)
816
- }
817
- </script>
818
- ```
819
-
820
- The plugin automatically:
821
-
822
- - Separates **state variables** from **methods**
823
- - Strips TypeScript annotations
824
- - Emits clean JavaScript output
825
- - Generates entity-compatible methods
826
-
827
- ---
828
-
829
- ### Example
830
-
831
- **Vue-style input:**
832
-
833
- ```vue
834
- <template>
835
- <div>
836
- <h1>{{ title }}</h1>
837
- <TodoItem v-for="todo in todos" :key="todo.id" />
838
- </div>
839
- </template>
840
-
841
- <script>
842
- const title = "Todos"
843
- </script>
844
- ```
845
-
846
- **Generated output (simplified):**
847
-
848
- ```js
849
- export const App = {
850
- create(entity) {
851
- entity.title = "Todos"
852
- },
853
- render(entity, api) {
854
- return html`
855
- <div>
856
- <h1>${entity.title}</h1>
857
- ${repeat(entity.todos, (todo) => api.render("todoItem"))}
858
- </div>
859
- `
860
- },
861
- }
862
- ```
863
-
864
- ---
865
-
866
- ### Design Philosophy
867
-
868
- This plugin exists to support developers who:
869
-
870
- - Like Vue’s **template ergonomics**
871
- - Want to migrate incrementally from Vue
872
- - Prefer HTML-like syntax over JS mixed with tags
873
- - Still want **Inglorious Web’s explicit, predictable architecture**
874
-
875
- It deliberately avoids:
876
-
877
- - Hidden reactivity
878
- - Magic bindings
879
- - Lifecycle hooks
880
- - Framework-level state
881
-
882
- Everything still flows through **entities, events, and full-tree renders**.
883
-
884
- ---
885
-
886
- ### When to Use Native lit-html vs Vue Templates vs JSX
887
-
888
- | Choose this if you… | Use |
889
- | ----------------------------- | --------------- |
890
- | Like HTML templates | lit-html or Vue |
891
- | Want JSX ergonomics | JSX |
892
- | Prefer JavaScript-only syntax | lit-html |
893
- | Prefer declarative templates | lit-html or Vue |
894
- | Are migrating from Vue | Vue templates |
895
- | Want maximal explicitness | lit-html or JSX |
896
-
897
- Both plugins generate **the same runtime model**.
898
-
899
- ---
900
-
901
- ## Redux DevTools Integration
902
-
903
- `@inglorious/web` ships with first-class support for the **Redux DevTools Extension**, allowing you to:
904
-
905
- - inspect all store events
906
- - time-travel through state changes
907
- - restore previous states
908
- - debug your entity-based logic visually
909
-
910
- To enable DevTools, add the middleware provided by `createDevtools()`.
911
-
912
- ### 1. Create a `middlewares.js` file
913
-
914
- ```javascript
915
- // middlewares.js
916
- import { createDevtools } from "@inglorious/store/client/devtools"
917
-
918
- export const middlewares = []
919
-
920
- // Enable DevTools only in development mode
921
- if (import.meta.env.DEV) {
922
- middlewares.push(createDevtools().middleware)
923
- }
924
- ```
925
-
926
- ### 2. Pass middlewares when creating the store
927
-
928
- ```javascript
929
- // store.js
930
- import { createStore } from "@inglorious/store"
931
- import { middlewares } from "./middlewares.js"
932
-
933
- export const store = createStore({
934
- types,
935
- entities,
936
- middlewares,
937
- })
938
- ```
939
-
940
- Now your application state is fully visible in the Redux DevTools browser extension.
941
-
942
- ### What You'll See in DevTools
943
-
944
- - Each event you dispatch via `api.notify(event, payload)` will appear as an action in the DevTools timeline.
945
- - The entire store is visible under the _State_ tab.
946
- - You can time-travel or replay events exactly like in Redux.
947
-
948
- No additional configuration is needed.
949
-
950
- ---
951
-
952
- ## Client-Side Router
953
-
954
- `@inglorious/web` includes a lightweight, entity-based client-side router. It integrates directly into your `@inglorious/store` state, allowing your components to reactively update based on the current URL.
955
-
956
- ### 1. Setup the Router
957
-
958
- To enable the router, add it to your store's types and create a `router` entity. Register route patterns using the router module helpers (`setRoutes`, `addRoute`) — routes are configured at module level and not stored on the router entity itself.
959
-
960
- ```javascript
961
- // store.js
962
- import { createStore } from "@inglorious/store"
963
- import { html } from "@inglorious/web"
964
- import { PwaUpdate, watchPwaUpdate } from "@inglorious/web/pwa"
965
- import { Router, setRoutes } from "@inglorious/web/router"
966
-
967
- const types = {
968
- // 1. Add the router type to your store's types
969
- Router, // 2. Define types for your pages
970
- HomePage: {
971
- render: () => html`<h1>Welcome Home!</h1>`,
972
- },
973
- UserPage: {
974
- render: (entity, api) => {
975
- // Access route params from the router entity
976
- const { params } = api.getEntity("router")
977
- return html`<h1>User ${params?.id ?? "Unknown"} - ${entity.username}</h1>`
978
- },
979
- },
980
- NotFoundPage: {
981
- render: () => html`<h1>404 - Page Not Found</h1>`,
982
- },
983
- }
984
-
985
- const entities = {
986
- // 3. Create the router entity (no `routes` here)
987
- router: {
988
- type: "Router",
989
- },
990
- userPage: {
991
- type: "UserPage",
992
- username: "Alice",
993
- },
994
- }
995
-
996
- export const store = createStore({ types, entities })
997
-
998
- // Register routes at module level
999
- setRoutes({
1000
- "/": "homePage",
1001
- "/users/:id": "userPage",
1002
- "*": "notFoundPage",
1003
- })
1004
- ```
1005
-
1006
- ### 2. Render the Current Route
1007
-
1008
- In your root template, read the `route` property from the router entity and use `api.render()` to display the correct page.
1009
-
1010
- ```javascript
1011
- // main.js
1012
- import { mount, html } from "@inglorious/web"
1013
- import { store } from "./store.js"
1014
-
1015
- const renderApp = (api) => {
1016
- const { route } = api.getEntity("router") // e.g., "homePage" or "userPage"
1017
-
1018
- return html`
1019
- <nav><a href="/">Home</a> | <a href="/users/123">User 123</a></nav>
1020
- <main>${route ? api.render(route) : ""}</main>
1021
- `
1022
- }
1023
-
1024
- mount(store, renderApp, document.getElementById("root"))
1025
- ```
1026
-
1027
- The router automatically intercepts clicks on local `<a>` tags and handles browser back/forward events, keeping your UI in sync with the URL.
1028
-
1029
- ### 3. Programmatic Navigation
1030
-
1031
- To navigate from your JavaScript code, dispatch a `navigate` event.
1032
-
1033
- ```javascript
1034
- api.notify("navigate", "/users/456")
1035
-
1036
- // Or navigate back in history
1037
- api.notify("navigate", -1)
1038
-
1039
- // Go back, or to "/users" when the app was opened on this page and has
1040
- // nothing of its own to go back to (a deep link, a fresh tab)
1041
- api.notify("back", "/users")
1042
-
1043
- // With options
1044
- api.notify("navigate", {
1045
- to: "/users/456",
1046
- replace: true, // Replace current history entry
1047
- force: true, // Force navigation even if path is identical (useful after logout)
1048
- })
1049
- ```
1050
-
1051
- ### 4. Lazy Loading Routes
1052
-
1053
- You can improve performance by lazy-loading routes. Use a loader function that returns a dynamic import when registering the route via `setRoutes`.
1054
-
1055
- **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.
1056
-
1057
- ```javascript
1058
- // store.js
1059
- const entities = {
1060
- router: { type: "Router" },
1061
- }
1062
-
1063
- export const store = createStore({ types, entities })
1064
-
1065
- setRoutes({
1066
- "/": "homePage", // Lazy load: returns a Promise resolving to a module
1067
- "/admin": () => import("./pages/admin.js"),
1068
- })
1069
- ```
1070
-
1071
- ```javascript
1072
- // pages/admin.js
1073
- import { html } from "@inglorious/web"
1074
-
1075
- // Must be a named export matching the type name you want to use
1076
- export const AdminPage = {
1077
- render: () => html`<h1>Admin Area</h1>`,
1078
- }
1079
- ```
1080
-
1081
- 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.
1082
-
1083
- ```javascript
1084
- // pages/clients.js
1085
- export const ClientsGrid = { render: (entity) => html`…` }
1086
- export const ClientsForm = { render: (entity) => html`…` }
1087
- export const ClientsPage = { render: (entity, api) => html`…` }
1088
- export default ClientsPage
1089
- ```
1090
-
1091
- 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.
1092
-
1093
- ### 5. Page Entities
1094
-
1095
- 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.
1096
-
1097
- ```javascript
1098
- import { pageRouteChange } from "@inglorious/web/router"
1099
-
1100
- export const EventPage = {
1101
- routeChange: pageRouteChange({
1102
- select: (payload) => payload.params.eventId,
1103
- open: (entity, eventId, api) => api.notify(`#${entity.id}:fetch`, eventId),
1104
- close: (entity) => {
1105
- entity.event = null
1106
- },
1107
- }),
1108
- }
1109
- ```
1110
-
1111
- It reads the route from the payload: during `routeChange`, the router entity still names the route being left.
1112
-
1113
- ### 6. Route Guards (Type Composition)
1114
-
1115
- 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.
1116
-
1117
- Guards are simply behaviors that intercept events (like `routeChange`) and can prevent navigation, redirect, or pass through to the protected page.
1118
-
1119
- #### Example: Authentication Guard
1120
-
1121
- ```javascript
1122
- // session.js: the one place the user lives (kept between visits with
1123
- // withStorage, if at all), announcing each change
1124
- export const Session = {
1125
- signIn(entity, user, api) {
1126
- entity.user = user
1127
- api.notify("sessionChange", user)
1128
- },
1129
- signOut(entity, payload, api) {
1130
- entity.user = null
1131
- api.notify("sessionChange", null)
1132
- },
1133
- }
1134
-
1135
- // guards/require-auth.js
1136
- export const requireAuth = (type) => ({
1137
- sessionChange(entity, user, api) {
1138
- entity.user = user
1139
- type.sessionChange?.(entity, user, api)
1140
- },
1141
- routeChange(entity, payload, api) {
1142
- // Only act when navigating to this specific route
1143
- if (payload.route !== entity.id) return
1144
-
1145
- if (!entity.user) {
1146
- // Redirect to login, preserving the intended destination
1147
- api.notify("navigate", {
1148
- to: `/login?from=${encodeURIComponent(payload.path)}`,
1149
- replace: true,
1150
- })
1151
- return
1152
- }
1153
-
1154
- // User is authenticated - pass through to the actual page handler
1155
- type.routeChange?.(entity, payload, api)
1156
- },
1157
- })
1158
- ```
1159
-
1160
- The guard keeps what `sessionChange` told it rather than asking `api.getEntity("session")`, which during an update returns the state from before it: after a sign-in followed by navigation in the same chain of events, it would still have no user.
1161
-
1162
- 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) ?? "/")`.
1163
-
1164
- #### Using Guards with Type Composition
1165
-
1166
- ```javascript
1167
- // store.js
1168
- import { createStore } from "@inglorious/store"
1169
- import { Router } from "@inglorious/web/router"
1170
- import { requireAuth } from "./guards/require-auth.js"
1171
- import { AdminPage } from "./pages/admin.js"
1172
- import { LoginPage } from "./pages/login.js"
1173
-
1174
- const types = {
1175
- Router, // Public page - no guard
1176
- LoginPage, // Protected page - composed with requireAuth guard
1177
- AdminPage: [AdminPage, requireAuth],
1178
- }
1179
-
1180
- const entities = {
1181
- router: { type: "Router" },
1182
- adminPage: { type: "AdminPage" },
1183
- loginPage: { type: "LoginPage" },
1184
- }
1185
-
1186
- export const store = createStore({ types, entities })
1187
-
1188
- // Register routes via the router module API
1189
- setRoutes({
1190
- "/login": "loginPage",
1191
- "/admin": "adminPage",
1192
- })
1193
- ```
1194
-
1195
- #### How Type Composition Works
1196
-
1197
- When you define a type as an array like `[adminPage, requireAuth]`:
1198
-
1199
- 1. The behaviors compose in order (left to right)
1200
- 2. Each behavior can intercept events before they reach the next behavior
1201
- 3. Guards can choose to:
1202
- - **Block** by returning early (not calling the next handler)
1203
- - **Redirect** by triggering navigation to a different route
1204
- - **Pass through** by calling the next behavior's handler
1205
-
1206
- This pattern is extremely flexible and can be used for:
1207
-
1208
- - **Authentication** - Check if user is logged in
1209
- - **Authorization** - Check user roles or permissions
1210
- - **Analytics** - Log page views
1211
- - **Redirects** - Redirect logged-in users away from login page
1212
- - **Loading states** - Show loading UI while checking async permissions
1213
- - **Any cross-cutting concern** you can think of
1214
-
1215
- #### Multiple Guards
1216
-
1217
- You can compose multiple guards for fine-grained control:
1218
-
1219
- ```javascript
1220
- const types = {
1221
- // Require authentication AND admin role
1222
- AdminPage: [AdminPage, requireAuth, requireAdmin], // Require authentication AND resource ownership
1223
- UserProfile: [UserProfile, requireAuth, requireOwnership],
1224
- }
1225
- ```
1226
-
1227
- Guards execute in order, so earlier guards can block navigation before later guards even run.
1228
-
1229
- ---
1230
-
1231
- ## Type Composition
1232
-
1233
- One of the most powerful features of `@inglorious/store` (and therefore `@inglorious/web`) is **type composition**. Types can be defined as arrays of behaviors that wrap each other, enabling elegant solutions to cross-cutting concerns.
1234
-
1235
- ### Basic Composition
1236
-
1237
- ```javascript
1238
- const logging = (type) => ({
1239
- // Intercept the render method
1240
- render(entity, api) {
1241
- console.log(`Rendering ${entity.id}`)
1242
- return type.render(entity, api)
1243
- }, // Intercept any event
1244
- someEvent(entity, payload, api) {
1245
- console.log(`Event triggered on ${entity.id}`)
1246
- type.someEvent?.(entity, payload, api)
1247
- },
1248
- })
1249
-
1250
- const types = {
1251
- // Compose the counter type with logging
1252
- counter: [CounterBase, logging],
1253
- }
1254
- ```
1255
-
1256
- ### Use Cases
1257
-
1258
- Type composition enables elegant solutions for:
1259
-
1260
- - **Route guards** - Authentication, authorization, redirects
1261
- - **Logging/debugging** - Trace renders and events
1262
- - **Analytics** - Track user interactions
1263
- - **Error boundaries** - Catch and handle render errors gracefully
1264
- - **Loading states** - Show spinners during async operations
1265
- - **Caching/memoization** - Cache expensive computations
1266
- - **Validation** - Validate entity state before operations
1267
- - **Any cross-cutting concern**
1268
-
1269
- The composition pattern keeps your code modular and reusable without introducing framework magic.
1270
-
1271
- ---
1272
-
1273
- ## UI Primitives ([Inglorious UI](https://inglorious.dev/ui))
1274
-
1275
- For ready-made UI primitives (controls, data display, navigation, feedback, layout, surfaces), use the **[Inglorious UI](https://inglorious.dev/ui)** design system. It follows the same entity/type pattern, so you can still override `render()` and `renderItem()` when you need custom behavior.
1276
-
1277
- ---
1278
-
1279
- ## Geolocation
1280
-
1281
- `@inglorious/web` includes a `Geolocation` type for keeping browser geolocation state inside the store.
1282
-
1283
- ```javascript
1284
- import { createStore } from "@inglorious/store"
1285
- import { Geolocation } from "@inglorious/web/geolocation"
1286
-
1287
- const store = createStore({
1288
- types: { Geolocation },
1289
- autoCreateEntities: true,
1290
- })
1291
-
1292
- // The store now contains a `geolocation` entity.
1293
- store.getState().geolocation
1294
- ```
1295
-
1296
- The entity state contains:
1297
-
1298
- - `isSupported` — whether `navigator.geolocation` is available
1299
- - `isLoading` — whether a current-position request or first watch result is pending
1300
- - `isWatching` — whether a geolocation watch is active
1301
- - `position` — the latest normalized `{ coords, timestamp }` value
1302
- - `error` — the latest normalized `{ code, message }` error
1303
- - `watchId` — the active browser watch id, or `null`
1304
-
1305
- Events:
1306
-
1307
- - `geolocationRequest` — request the current position
1308
- - `geolocationWatch` — start watching position changes
1309
- - `geolocationUnwatch` — stop the active watch
1310
-
1311
- ```javascript
1312
- api.notify("geolocationRequest", {
1313
- enableHighAccuracy: true,
1314
- timeout: 5000,
1315
- })
1316
-
1317
- api.notify("geolocationWatch")
1318
- api.notify("geolocationUnwatch")
1319
- ```
1320
-
1321
- ### Example: Show current location
1322
-
1323
- ```javascript
1324
- import { mount, html } from "@inglorious/web"
1325
- import { when } from "@inglorious/web/directives/when"
1326
- import { store } from "./store.js"
1327
-
1328
- const renderApp = (api) => {
1329
- const geolocation = api.getEntity("geolocation")
1330
- const position = geolocation.position
1331
-
1332
- return html`
1333
- <section>
1334
- <h2>Geolocation</h2>
1335
- <p>Supported: ${geolocation.isSupported ? "yes" : "no"}</p>
1336
- <p>Loading: ${geolocation.isLoading ? "yes" : "no"}</p>
1337
- <p>
1338
- Position:
1339
- ${when(
1340
- position,
1341
- () =>
1342
- html`${position.coords.latitude.toFixed(4)},
1343
- ${position.coords.longitude.toFixed(4)}`,
1344
- () => "unknown",
1345
- )}
1346
- </p>
1347
- <p>Error: ${geolocation.error ? geolocation.error.message : "none"}</p>
1348
- <button
1349
- @click=${() =>
1350
- api.notify("geolocationRequest", {
1351
- enableHighAccuracy: true,
1352
- timeout: 5000,
1353
- })}
1354
- >
1355
- Request Current Position
1356
- </button>
1357
- <button @click=${() => api.notify("geolocationWatch")}>
1358
- Start Watch
1359
- </button>
1360
- <button @click=${() => api.notify("geolocationUnwatch")}>
1361
- Stop Watch
1362
- </button>
1363
- </section>
1364
- `
1365
- }
1366
-
1367
- mount(store, renderApp, document.getElementById("root"))
1368
- ```
1369
-
1370
- ---
1371
-
1372
- ## Compass
1373
-
1374
- `@inglorious/web` also includes a `Compass` type for managing device orientation and heading state inside the store.
1375
-
1376
- ```javascript
1377
- import { createStore } from "@inglorious/store"
1378
- import { Compass } from "@inglorious/web/compass"
1379
-
1380
- const store = createStore({
1381
- types: { Compass },
1382
- autoCreateEntities: true,
1383
- })
1384
-
1385
- // The store now contains a `compass` entity.
1386
- store.getState().compass
1387
- ```
1388
-
1389
- The entity state contains:
1390
-
1391
- - `isSupported` — whether device orientation sensors are available
1392
- - `isLoading` — whether permissions or heading data are pending
1393
- - `isCompassPermissionGranted` — whether compass permission has been granted
1394
- - `isCompassActive` — whether a valid heading is currently active
1395
- - `heading` — the latest heading in degrees, or `null`
1396
- - `error` — the latest normalized `{ code, message }` error
1397
- - `manualOffset` — a heading offset in degrees to apply to raw sensor values
1398
-
1399
- Events:
1400
-
1401
- - `compassPermissionsRequest` — request compass permission when needed
1402
- - `compassWatch` — start listening for device orientation events
1403
- - `compassUnwatch` — stop listening for device orientation events
1404
- - `compassPermissionsGrant` — set permission granted
1405
- - `compassActiveChange` — update active/inactive state
1406
- - `compassHeadingChange` — update the latest heading
1407
- - `compassError` — store a normalized compass error
1408
-
1409
- ```javascript
1410
- api.notify("compassPermissionsRequest")
1411
- api.notify("compassWatch")
1412
- api.notify("compassUnwatch")
1413
- ```
1414
-
1415
- ### Example: Show heading and request permission
1416
-
1417
- ```javascript
1418
- import { mount, html } from "@inglorious/web"
1419
- import { store } from "./store.js"
1420
-
1421
- const renderApp = (api) => {
1422
- const compass = api.getEntity("compass")
1423
-
1424
- return html`
1425
- <section>
1426
- <h2>Compass</h2>
1427
- <p>Supported: ${compass.isSupported ? "yes" : "no"}</p>
1428
- <p>
1429
- Permission:
1430
- ${compass.isCompassPermissionGranted ? "granted" : "unknown"}
1431
- </p>
1432
- <p>Active: ${compass.isCompassActive ? "yes" : "no"}</p>
1433
- <p>
1434
- Heading:
1435
- ${
1436
- compass.heading !== null
1437
- ? `${compass.heading.toFixed(1)}°`
1438
- : "unknown"
1439
- }
1440
- </p>
1441
- <p>Error: ${compass.error ? compass.error.message : "none"}</p>
1442
- <button @click=${() => api.notify("compassPermissionsRequest")}>
1443
- Request Permission
1444
- </button>
1445
- <button @click=${() => api.notify("compassWatch")}>Start Compass</button>
1446
- <button @click=${() => api.notify("compassUnwatch")}>Stop Compass</button>
1447
- </section>
1448
- `
1449
- }
1450
-
1451
- mount(store, renderApp, document.getElementById("root"))
1452
- ```
1453
-
1454
- ---
1455
-
1456
- ## PWA Updates
1457
-
1458
- `@inglorious/web/pwa` keeps an installed PWA on its latest version. It works with the service worker that [`vite-plugin-pwa`](https://vite-pwa-org.netlify.app/) generates, and `@inglorious/create-app --pwa` sets it up for you.
1459
-
1460
- Updates are not optional. A new version downloads in the background, and is applied with a reload at the first moment nobody is in the middle of something:
1461
-
1462
- - at launch, before anything is touched;
1463
- - each time the app goes to the background or comes back to the foreground.
1464
-
1465
- It also checks for a new version every hour and on every return to the foreground: a phone suspends an installed PWA rather than closing it, so the browser's own check may never come.
1466
-
1467
- ```javascript
1468
- import { isNative } from "@inglorious/web/native"
1469
- import { watchPwaUpdate } from "@inglorious/web/pwa"
1470
- import { registerSW } from "virtual:pwa-register"
1471
-
1472
- if (!isNative()) {
1473
- registerSW({
1474
- onRegisteredSW(url, registration) {
1475
- if (registration) watchPwaUpdate(registration)
1476
- },
1477
- })
1478
- }
1479
- ```
1480
-
1481
- Configure the plugin with `registerType: "prompt"` and `injectRegister: false`: the generated worker then waits for the `SKIP_WAITING` message this module sends, instead of taking over on its own.
1482
-
1483
- ### Offering "Update now"
1484
-
1485
- A version that lands while someone is using the app waits for the next trip to the background. To offer it right away, pass the store and register the `PwaUpdate` type:
1486
-
1487
- ```javascript
1488
- import { PwaUpdate, watchPwaUpdate } from "@inglorious/web/pwa"
1489
-
1490
- const store = createStore({ types: { PwaUpdate }, autoCreateEntities: true })
1491
-
1492
- watchPwaUpdate(registration, store)
1493
- ```
1494
-
1495
- The `pwaUpdate` entity contains:
1496
-
1497
- - `isUpdateReady` — a new version is waiting for the next reload
1498
-
1499
- Events:
1500
-
1501
- - `pwaUpdateReady` — sent by `watchPwaUpdate` when a version lands mid-session
1502
- - `pwaUpdateApply` — moves over to the waiting version now, reloading the page
1503
-
1504
- ```javascript
1505
- const renderUpdate = (api) =>
1506
- when(
1507
- api.getEntity("pwaUpdate").isUpdateReady,
1508
- () =>
1509
- html`<button @click=${() => api.notify("#pwaUpdate:pwaUpdateApply")}>
1510
- Update now
1511
- </button>`,
1512
- )
1513
- ```
1514
-
1515
- Inglorious UI's `Snackbar` is the usual place for it. `watchPwaUpdate` takes `{ id, checkEveryMs }` as a third argument, to announce to an entity with another id or to check more or less often, and returns a function that stops watching.
1516
-
1517
- ---
1518
-
1519
- ## Native App Updates
1520
-
1521
- A Capacitor app carries its web code inside the binary, so only the stores update it. `@inglorious/web/native/update` makes an update mandatory: the app reads a minimum build per platform, and a build below it is blocked until the user updates. `@inglorious/create-app --mobile --push` sets it up with Supabase.
1522
-
1523
- ```javascript
1524
- import { App } from "@capacitor/app"
1525
- import {
1526
- createNativeUpdate,
1527
- watchNativeUpdate,
1528
- } from "@inglorious/web/native/update"
1529
-
1530
- const types = { NativeUpdate: [createNativeUpdate({ adapter }), template] }
1531
- const entities = { nativeUpdate: { type: "NativeUpdate" } }
1532
-
1533
- watchNativeUpdate(App, store)
1534
- ```
1535
-
1536
- `watchNativeUpdate` reads the installed build at launch and on every resume, and does nothing outside a native app. `{ id }` as a third argument notifies another entity; it returns a function that stops watching.
1537
-
1538
- The adapter says where the minimum lives: `requirement(platform)` resolves to `{ minBuild, storeUrl }`, or `null` for no minimum. `supabaseNativeUpdate` from `@inglorious/supabase` reads it from a table.
1539
-
1540
- The `nativeUpdate` entity contains:
1541
-
1542
- - `isUpdateRequired` — the installed build is below the minimum
1543
- - `storeUrl` — where the update button goes, or `null`
1544
-
1545
- Events:
1546
-
1547
- - `nativeUpdateCheck` — `{ platform, build }`, sent by `watchNativeUpdate`
1548
- - `nativeUpdateApply` — opens the store
1549
-
1550
- A failed check keeps the last answer, so nobody is blocked by being offline. Render the whole app as the update page while `isUpdateRequired`, and raise the minimum only once the new build is live in that store.
1551
-
1552
- ---
1553
-
1554
- ## Live Updates
1555
-
1556
- A store release is only needed for native changes. `@inglorious/web/native/live-update` replaces the web code inside a Capacitor app with a newer published bundle, through [`@capawesome/capacitor-live-update`](https://capawesome.io/plugins/live-update/), whose open source plugin downloads from any URL. `publishLiveUpdate` from `@inglorious/supabase/live-update` publishes one.
1557
-
1558
- ```javascript
1559
- import { App } from "@capacitor/app"
1560
- import { LiveUpdate } from "@capawesome/capacitor-live-update"
1561
- import {
1562
- createLiveUpdate,
1563
- watchLiveUpdate,
1564
- } from "@inglorious/web/native/live-update"
1565
-
1566
- const types = { LiveUpdate: createLiveUpdate({ plugin: LiveUpdate }) }
1567
- const entities = { liveUpdate: { type: "LiveUpdate" } }
1568
-
1569
- watchLiveUpdate({
1570
- plugin: LiveUpdate,
1571
- app: App,
1572
- store,
1573
- manifestUrl,
1574
- release: Number(import.meta.env.VITE_LIVE_UPDATE_RELEASE),
1575
- })
1576
- ```
1577
-
1578
- `watchLiveUpdate` tells the plugin the running bundle works, then reads the manifest at launch, every hour (`checkEveryMs`) and on each resume. The manifest is `{ release, minBuild, url, checksum, signature }`. A bundle is wanted when its `release` is newer than the running one and the installed build is at least `minBuild` (`isLiveUpdateWanted`). It downloads in the background, is applied on the next pause, and is announced as `#liveUpdate:liveUpdateReady` meanwhile; `liveUpdateApply` moves over at once. It does nothing outside a native app, and returns a function that stops watching.
1579
-
1580
- `release` must grow with every build, like the build's timestamp, and only release builds should have one: a development build without it must not watch, or it would turn into the published code.
1581
-
1582
- Set `publicKey` in the plugin's Capacitor config so it refuses unsigned bundles, and `readyTimeout` so a bundle that doesn't start is rolled back; with `autoBlockRolledBackBundles`, `watchLiveUpdate` never downloads it again.
1583
-
1584
- ---
1585
-
1586
- ## Sign-in
1587
-
1588
- `@inglorious/web/auth` is the type behind a sign-in screen. It walks from the email to a password, a new account or a code sent by email, holds the signed-in `user`, and erases the account on request, as the App Store and Google Play require of apps that create accounts. Codes rather than links work in a native app too, since nobody has to open anything.
1589
-
1590
- ```javascript
1591
- import { supabaseAuth } from "@inglorious/supabase"
1592
- import { createAuth, watchAuth } from "@inglorious/web/auth"
1593
-
1594
- const adapter = supabaseAuth(supabase)
1595
-
1596
- const types = {
1597
- Auth: { ...createAuth({ adapter, methods: ["password", "code"] }), render },
1598
- }
1599
-
1600
- watchAuth(adapter, store) // keeps `user` in step with the session
1601
- ```
1602
-
1603
- `methods` lists what the screen offers: `"password"` (sign in, create an account confirmed with a code, reset a forgotten password with a code) and `"code"` (sign in with a code alone, creating the account on first use).
1604
-
1605
- The entity's `step` says what to ask for: `"email"`, `"password"`, `"signUp"`, `"code"` or `"reset"`. Its events take what the person typed: `emailSubmit(email)`, `signInSubmit(password)`, `signUpSubmit({ password, data })`, `codeSubmit(code)`, `resetSubmit({ code, password })`, and move between steps: `signUpShow`, `signInShow`, `codeRequest`, `codeResend`, `resetRequest`, `back`. Signed in, `signOut` and `accountEraseAsk`, then `accountErase` or `accountEraseCancel`. `isReady` turns true once the saved session is read: until then, render nothing rather than the sign-in screen.
1606
-
1607
- Whoever signs in, by password, code, link or password reset, the entity gets `signedIn` with `{ user, isNew }`, `isNew` for an account just created. Add a handler to move on:
1608
-
1609
- ```javascript
1610
- const types = {
1611
- Auth: [
1612
- createAuth({ adapter }),
1613
- {
1614
- signedIn(entity, { isNew }, api) {
1615
- api.notify("#router:navigate", isNew ? "/onboarding" : "/")
1616
- },
1617
- },
1618
- ],
1619
- }
1620
- ```
1621
-
1622
- For a page that a confirmation email's link opens, `linkSubmit({ tokenHash })` signs in with the link instead of the code. Ask for a tap first: mail scanners open links too.
1623
-
1624
- `status` is `"loading"` while waiting, and `error` is a key to put into words: `"invalidEmail"`, `"invalidCode"`, `"weakPassword"`, `"invalidCredentials"`, `"accountExists"`, `"rateLimited"`, `"captcha"`, `"network"` or `"unknown"`. An account not confirmed yet goes straight to the code.
1625
-
1626
- The adapter talks to the backend. `supabaseAuth` from `@inglorious/supabase` is one; another backend needs `onSessionChange`, `signIn`, `signUp`, `sendCode`, `verifyCode`, `verifyLink`, `resendCode`, `sendResetCode`, `updatePassword`, `signOut`, `eraseAccount` and `errorCode`, plus `accountExists` to skip straight to the password or the new account, and `prepare(action)`, called once the next step is known (`"signIn"` or `"signUp"`), such as to solve a CAPTCHA before the person submits.
1627
-
1628
- `create-app --auth` generates the screen, the account actions in the app bar, the Edge Function that erases accounts and the email templates.
1629
-
1630
- ---
1631
-
1632
- ## App Links
1633
-
1634
- With Universal Links (iOS) and App Links (Android), a link to the app's domain opens the installed app instead of the browser. `@inglorious/web/native/app-links` sends the router to that link's path, both for the link that started the app and for links that arrive while it runs. It does nothing outside a native app.
1635
-
1636
- ```javascript
1637
- import { App } from "@capacitor/app"
1638
- import { watchAppLinks } from "@inglorious/web/native/app-links"
1639
-
1640
- watchAppLinks(App, store)
1641
- ```
1642
-
1643
- `{ id }` as a third argument notifies a router with another id; it returns a function that stops listening.
1644
-
1645
- The operating system opens the app only when the domain vouches for it: iOS reads `/.well-known/apple-app-site-association` and Android `/.well-known/assetlinks.json`, and the app declares the domain (Associated Domains on iOS, an intent filter on Android). [`@inglorious/capacitor`](../capacitor) generates all of it from `native.appLinks` in `package.json`, and `@inglorious/create-app --mobile` sets it up.
1646
-
1647
- ---
1648
-
1649
- ## Back Button
1650
-
1651
- On Android, the back button and the back gesture go back in history. `@inglorious/web/native/back-button` closes the app instead on a root path, a top-level page like a tab bar's, and when there is no history left, as other Android apps do. It does nothing outside a native app, and iOS has no back button.
1652
-
1653
- ```javascript
1654
- import { App } from "@capacitor/app"
1655
- import { watchBackButton } from "@inglorious/web/native/back-button"
1656
-
1657
- watchBackButton(App, { rootPaths: ["/", "/search", "/profile"] })
1658
- ```
1659
-
1660
- `rootPaths` defaults to `["/"]`; it returns a function that stops listening. Navigate between root paths with `{ to, replace: true }`, so switching tabs does not pile up history.
1661
-
1662
- ---
1663
-
1664
- ## System Bars
1665
-
1666
- The status bar and Android's navigation bar follow the device's light or dark mode, so a light app on a phone in dark mode gets white icons on a white page. `@inglorious/web/native/system-bars` sets them from the app's own `color-scheme`, which every Inglorious UI theme sets, and follows it when the theme class changes. An app whose `color-scheme` is `light dark` keeps the device's style. It does nothing outside a native app.
1667
-
1668
- ```javascript
1669
- import { SystemBars } from "@capacitor/core"
1670
- import { watchSystemBars } from "@inglorious/web/native/system-bars"
1671
-
1672
- watchSystemBars(SystemBars)
1673
- ```
1674
-
1675
- It returns a function that stops following.
1676
-
1677
- ---
1678
-
1679
- ## Keyboard
1680
-
1681
- Phones don't shrink the page for the on-screen keyboard: iOS never does, nor does Chrome on Android. Whatever sits at the bottom of the screen, such as a bottom sheet with an input, ends up behind it. `@inglorious/web/keyboard` reads the height the keyboard covers from the visual viewport and sets it as `--iw-keyboard-height` on `<html>`, with the `iw-keyboard-open` class while the keyboard is up. It needs no plugin and works in browsers and native apps alike. Where the page does shrink for the keyboard, as in an Android app, the class is still set but the height stays `0px`, since nothing is covered.
1682
-
1683
- ```javascript
1684
- import { watchKeyboard } from "@inglorious/web/keyboard"
1685
-
1686
- watchKeyboard()
1687
- ```
1688
-
1689
- Inglorious UI's bottom sheets, snackbars and toasts move above the keyboard, and its bottom navigation hides while the keyboard is up. Your own fixed elements can do the same:
1690
-
1691
- ```css
1692
- .composer {
1693
- position: fixed;
1694
- bottom: var(--iw-keyboard-height, 0px);
1695
- }
1696
- ```
1697
-
1698
- It returns a function that stops following.
1699
-
1700
- ---
1701
-
1702
- ## Share
1703
-
1704
- `@inglorious/web/native/share` is the type behind a share button. `share` hands a title, a text, a link or a file to whatever the device does best, and the entity says what happened:
1705
-
1706
- - in a native app, the system's share sheet, through [`@capacitor/share`](https://capacitorjs.com/docs/apis/share) when you hand it over;
1707
- - in a browser, a file (a `url` with a `fileName`) downloads, since a browser has nowhere better to put it;
1708
- - otherwise the browser's share sheet where there is one (Web Share API), else the link is copied.
1709
-
1710
- ```javascript
1711
- import { Share } from "@capacitor/share"
1712
- import { createShare } from "@inglorious/web/native/share"
1713
-
1714
- const types = { Share: createShare({ plugin: Share }) }
1715
-
1716
- api.notify("#share:share", {
1717
- title: "My job",
1718
- url: "https://example.com/jobs/1",
1719
- })
1720
- api.notify("#share:share", {
1721
- title: "Wedding",
1722
- url: icsUrl,
1723
- fileName: "wedding.ics",
1724
- })
1725
- ```
1726
-
1727
- `result` is `"shared"`, `"downloaded"`, `"copied"` or `"cancelled"`: closing the sheet is not an error. `status` and `error` (`"unsupported"` or `"failed"`) come from `handleRequest`. `canShare` says whether a link can be shared at all, to hide the button where it can't.
1728
-
1729
- ---
1730
-
1731
- ## Native Storage
1732
-
1733
- iOS and Android can clear a WebView's `localStorage` when the device runs low on space. `createNativeStorage` keeps values in Capacitor Preferences instead, in the native app, and in `localStorage` in a browser. Give it to [`withStorage`](https://www.npmjs.com/package/@inglorious/store#withstorage):
1734
-
1735
- ```javascript
1736
- import { Preferences } from "@capacitor/preferences"
1737
- import { withStorage } from "@inglorious/store/storage"
1738
- import { createNativeStorage } from "@inglorious/web/native"
1739
-
1740
- const preferences = createNativeStorage({ plugin: Preferences })
1741
-
1742
- const types = {
1743
- Settings: [Settings, withStorage(["theme"], { storage: () => preferences })],
1744
- }
1745
- ```
1746
-
1747
- Preferences answers with promises, so in the native app the entity starts with its defaults and gets the stored fields back a moment later, through `storageRestore`. In a browser it uses `localStorage`.
1748
-
1749
- It works as Supabase's session storage too, so signing in survives the same clean-ups:
1750
-
1751
- ```javascript
1752
- createClient(url, key, { auth: { storage: preferences } })
12
+ ```bash
13
+ pnpm add @inglorious/store @inglorious/web
1753
14
  ```
1754
15
 
1755
- ## Haptics
1756
-
1757
- `@inglorious/web/native/haptics` plays taps the user can feel. In a native app it uses the system's haptics through [`@capacitor/haptics`](https://capacitorjs.com/docs/apis/haptics), once you hand the plugin over. Elsewhere it vibrates where the browser can (Chrome on Android), once the user has tapped the page; iOS browsers stay silent. Every call returns whether it played.
1758
-
1759
- ```javascript
1760
- import { Haptics } from "@capacitor/haptics"
1761
- import { haptics } from "@inglorious/web/native/haptics"
1762
-
1763
- haptics.use(Haptics)
16
+ Or scaffold an app, with routing, UI, i18n, sign-in, push and native builds wired:
1764
17
 
1765
- haptics.selection() // a toggle flipped, a threshold crossed
1766
- haptics.impact("heavy") // "light", "medium" (default) or "heavy"
1767
- haptics.notification("error") // "success" (default), "warning" or "error"
18
+ ```bash
19
+ pnpm create @inglorious/app
1768
20
  ```
1769
21
 
1770
- Inglorious UI plays them too: `PullToRefresh` gives a tick when letting go would refresh.
1771
-
1772
- ---
1773
-
1774
- ## Forms
1775
-
1776
- `@inglorious/web` includes a small but powerful `form` type for managing form state inside your entity store. It offers:
1777
-
1778
- - Declarative form state held on an entity (`initialValues`, `values`, `errors`, `touched`)
1779
- - Convenient helpers for reading field value/error/touched state (`getFieldValue`, `getFieldError`, `isFieldTouched`)
1780
- - Built-in handlers for field changes, blurs, array fields, sync/async validation and submission
1781
-
1782
- ### Add the `form` type
1783
-
1784
- Include `form` in your `types` and create an entity for the form (use any id you like — `form` is used below for clarity):
22
+ ## In a few lines
1785
23
 
1786
24
  ```javascript
1787
25
  import { createStore } from "@inglorious/store"
1788
- import { Form } from "@inglorious/web/form"
1789
-
1790
- const types = { Form }
1791
-
1792
- const entities = {
1793
- form: {
1794
- type: "Form",
1795
- initialValues: {
1796
- name: "",
1797
- email: "",
1798
- addresses: [],
1799
- },
1800
- },
1801
- }
1802
-
1803
- const store = createStore({ types, entities })
1804
- ```
1805
-
1806
- ### How it works (events & helpers)
1807
-
1808
- The `form` type listens for a simple set of events (target the specific entity id with `#<id>:<event>`):
1809
-
1810
- - `#<id>:fieldChange` — payload { path, value, validate? } — set a field value and optionally run a single-field validator
1811
- - `#<id>:fieldBlur` — payload { path, validate? } — mark field touched and optionally validate on blur
1812
- - `#<id>:fieldArrayAppend|fieldArrayRemove|fieldArrayInsert|fieldArrayMove` — manipulate array fields
1813
- - `#<id>:reset` — reset the form to `initialValues`
1814
- - `#<id>:validate` — synchronous whole-form validation; payload { validate }
1815
- - `#<id>:validateAsync` — async whole-form validation; payload { validate }
1816
- - `#<id>:submit` — typically handled by your `form` type's `submit` method (implement custom behavior there)
1817
-
1818
- Helpers available from the package let you read state from templates and field helper components:
1819
-
1820
- - `getFieldValue(formEntity, path)` — read a nested field value
1821
- - `getFieldError(formEntity, path)` — read a nested field's error message
1822
- - `isFieldTouched(formEntity, path)` — check if a field has been touched
1823
-
1824
- Form state includes helpful flags:
1825
-
1826
- - `isPristine` — whether the form has changed from initial values
1827
- - `isValid` — whether the current form has no validation errors
1828
- - `isValidating` — whether async validation is in progress
1829
- - `isSubmitting` — whether submission is in progress
1830
- - `submitError` — an optional submission-level error message
1831
-
1832
- ### Simple example (from examples/apps/web-form)
1833
-
1834
- Field components typically call `api.notify` and the `form` entity reacts accordingly. Example input field usage:
1835
-
1836
- ```javascript
1837
- // inside a field component render
1838
- @input=${(e) => api.notify(`#${entity.id}:fieldChange`, { path: 'name', value: e.target.value, validate: validateName })}
1839
- @blur=${() => api.notify(`#${entity.id}:fieldBlur`, { path: 'name', validate: validateName })}
1840
- ```
1841
-
1842
- Submissions and whole-form validation can be triggered from a `form` render:
1843
-
1844
- ```javascript
1845
- <form @submit=${() => { api.notify(`#form:validate`, { validate: validateForm }); api.notify(`#form:submit`) }}>
1846
- <!-- inputs / buttons -->
1847
- </form>
1848
- ```
1849
-
1850
- For a complete, working demo and helper components look at `examples/apps/web-form` which ships with the repository.
1851
-
1852
- ---
1853
-
1854
- ## Building Component Libraries with Inglorious Web
1855
-
1856
- **Inglorious types are uniquely suited for component libraries** because they're fully customizable through JavaScript's spread operator.
1857
-
1858
- ### The Pattern
1859
-
1860
- **Library publishes types:**
1861
-
1862
- ```javascript
1863
- // @acme/design-system/data-grid.js
1864
- export const DataGrid = {
1865
- render(entity, api) {
1866
- const type = api.getType(entity.type)
1867
-
1868
- return html`
1869
- <div class="data-grid">
1870
- ${entity.rows.map((row) => type.renderRow(entity, row, api))}
1871
- </div>
1872
- `
1873
- },
1874
- renderRow(entity, row, api) {
1875
- return html`<div class="data-grid-row">${row.name}</div>`
1876
- },
1877
- rowClick(entity, row) {
1878
- entity.selectedRow = row
1879
- },
1880
- }
1881
- ```
1882
-
1883
- **Users customize freely:**
1884
-
1885
- ```javascript
1886
- import { DataGrid } from "@acme/design-system/data-grid"
1887
-
1888
- // Use as-is
1889
- const SimpleGrid = { ...DataGrid }
1890
-
1891
- // Override methods
1892
- const CustomGrid = {
1893
- ...DataGrid,
1894
- renderRow(entity, row, api) {
1895
- return html`<div class="data-grid-row custom">
1896
- ${row.name} - ${row.email}
1897
- </div>`
1898
- },
1899
- }
1900
-
1901
- // Compose with behaviors
1902
- import { sortable, exportable } from "@acme/design-system/behaviors"
1903
-
1904
- const AdvancedGrid = [
1905
- DataGrid,
1906
- sortable,
1907
- exportable,
1908
- {
1909
- rowClick(entity, row) {
1910
- console.log("Custom click handler", row)
1911
- },
1912
- },
1913
- ]
1914
- ```
1915
-
1916
- ### Why This Is Better Than React Components
1917
-
1918
- | Feature | React Components | Inglorious Types |
1919
- | -------------------------- | ------------------------------ | ----------------------------------------- |
1920
- | Customize rendering | Only if `render` prop exposed | Override `render()` method directly |
1921
- | Customize behavior | Only if callback props exposed | Override any method |
1922
- | Compose multiple libraries | Wrapper hell / HOCs | Array composition `[type1, type2, {...}]` |
1923
- | Access internals | Private - must fork | Public - spread and override |
1924
- | Type safety | Props interface | Entity schema + method signatures |
1925
-
1926
- **Users get complete control** without forking your library. They can override rendering, behavior, or both—down to individual methods.
1927
-
1928
- ---
1929
-
1930
- ## Using Third-Party Web Components
1931
-
1932
- Inglorious Web works seamlessly with any Web Component library, such as Shoelace, Material Web Components, or Lion. Thanks to lit-html's efficient diffing algorithm, Web Components maintain their internal state even when the full tree re-renders - the component only updates when its properties change.
1933
-
1934
- ### ⚠️ SSG/SSR Considerations
1935
-
1936
- **Inglorious Web's built-in form type** and **[Inglorious UI](https://inglorious.dev/ui) primitives** are fully compatible with [@inglorious/ssx](https://npmjs.com/package/@inglorious/ssx) for static site generation. They render to complete HTML at build time and hydrate seamlessly on the client.
1937
-
1938
- **Third-party Web Components** currently have limited SSR/SSG support. Most Web Component libraries (including Shoelace and Material Web Components) require client-side JavaScript to initialize and render, which means:
1939
-
1940
- - They won't appear in the pre-rendered HTML
1941
- - They're not SEO-friendly in their initial state
1942
- - They may cause FOUC (Flash of Unstyled Content)
1943
- - They should be treated as client-only enhancements
1944
-
1945
- **Recommendation for SSX projects:**
1946
-
1947
- - Use Inglorious Web components for content that needs to be pre-rendered (product listings, blog posts, documentation)
1948
- - Use Web Components for interactive, client-only features (color pickers, rich text editors, admin tools)
1949
-
1950
- **Use Inglorious Web + [Inglorious UI](https://inglorious.dev/ui) primitives when:**
1951
-
1952
- - ✅ You want full architectural consistency
1953
- - ✅ You need fine-grained control over behavior
1954
- - ✅ You want to compose behaviors via type composition
1955
- - ✅ You need time-travel debugging of component state
1956
- - ✅ You want minimal bundle size
1957
- - ✅ You're building a core pattern used throughout your app
1958
- - ✅ You want the simplest possible tests
1959
- - ✅ You need custom behavior that third-party components don't provide
1960
- - ✅ You're using SSX for static site generation
1961
-
1962
- **Use Web Components (like Shoelace) when:**
1963
-
1964
- - ✅ You need complex, battle-tested UI (date pickers, rich text editors)
1965
- - ✅ You want a comprehensive design system out of the box
1966
- - ✅ Speed of development matters more than architectural purity
1967
- - ✅ You need features you don't want to build yourself (color pickers, tree views)
1968
- - ✅ The component is isolated or used infrequently
1969
- - ✅ You're okay with some state living outside the store
1970
- - ✅ You're building a client-only application (not using SSX)
26
+ import { html, mount } from "@inglorious/web"
1971
27
 
1972
- ### Example: Hybrid Approach
1973
-
1974
- ```javascript
1975
- import "@shoelace-style/shoelace/dist/components/color-picker/color-picker.js"
1976
-
1977
- const types = {
1978
- // App-specific type - full store integration
1979
- ProductTable, // Web Component - for specialized UI
1980
- ThemeEditor: {
1981
- colorChange(entity, color) {
1982
- entity.primaryColor = color
1983
- },
1984
- render(entity, api) {
1985
- return html`
1986
- <div>
1987
- <label>Primary Color</label>
1988
- <sl-color-picker
1989
- value=${entity.primaryColor}
1990
- @sl-change=${(e) =>
1991
- api.notify("#themeEditor:colorChange", e.target.value)}
1992
- ></sl-color-picker>
1993
- </div>
1994
- `
1995
- },
1996
- },
1997
- }
1998
- ```
1999
-
2000
- This hybrid approach gives you the best of both worlds: architectural consistency for core patterns, and battle-tested components for complex UI.
2001
-
2002
- ---
2003
-
2004
- ## Simplifying Entity Setup with `autoCreateEntities`
2005
-
2006
- Let's be real: in a web app you very rarely need to create more than one entity for each type, and juggling between the types file and the entities file is annoying. That's why you can initialize the store with the `autoCreateEntities` flag, which will automatically create an entity with the same id as the type name.
2007
-
2008
- ```javascript
2009
28
  const types = {
2010
- App: {
2011
- render(entity, api) {
2012
- return html`
2013
- <div class="app">${api.render("header")} ${api.render("content")}</div>
2014
- `
2015
- },
2016
- },
2017
- Header: {
2018
- render(entity, api) {
2019
- return html`<header>${entity.title}</header>`
29
+ Counter: {
30
+ increment(entity) {
31
+ entity.value++
2020
32
  },
2021
- },
2022
- Content: {
2023
33
  render(entity, api) {
2024
- return html`<main>${entity.text}</main>`
34
+ return html`<button @click=${() => api.notify(`#${entity.id}:increment`)}>
35
+ Clicked ${entity.value} times
36
+ </button>`
2025
37
  },
2026
38
  },
2027
39
  }
2028
40
 
2029
- // Without autoCreateEntities - you need to define every entity
2030
- const entities = {
2031
- app: { type: "App" },
2032
- header: { type: "Header", title: "Welcome" },
2033
- content: { type: "Content", text: "Hello World" },
2034
- }
2035
-
2036
- // With autoCreateEntities - entities are created automatically
2037
41
  const store = createStore({
2038
42
  types,
2039
- entities: {}, // Can be empty!
2040
- autoCreateEntities: true,
43
+ entities: { counter: { type: "Counter", value: 0 } },
2041
44
  })
2042
- ```
2043
-
2044
- If you want to initialize an entity with specific data, you can use the `create()` event handler:
2045
-
2046
- ```javascript
2047
- const Header = {
2048
- create(entity) {
2049
- entity.title = "Welcome"
2050
- },
2051
- render(entity, api) {
2052
- return html`<header>${entity.title}</header>`
2053
- },
2054
- }
2055
- ```
2056
-
2057
- The `create()` handler runs for each entity of that type is first created, making it perfect for setting up default values. This pattern works great for web apps where most entities are singletons that behave more like components than game objects.
2058
-
2059
- **When to use `autoCreateEntities` in web apps:**
2060
-
2061
- - ✅ Single-page applications with singleton services
2062
- - ✅ Component-like entities (headers, footers, navigation)
2063
- - ✅ Rapid prototyping where structure matters more than initial state
2064
- - ✅ Apps where you want to focus on behavior, not boilerplate
2065
-
2066
- ---
2067
-
2068
- ## API Reference
2069
-
2070
- **`mount(store, renderFn, element)`**
2071
-
2072
- Connects a store to a `lit-html` template and renders it into a DOM element. It automatically handles re-rendering on state changes.
2073
-
2074
- **Parameters:**
2075
-
2076
- - `store` (required): An instance of `@inglorious/store`.
2077
- - `renderFn(api)` (required): A function that takes an `api` object and returns a `lit-html` `TemplateResult` or `null`.
2078
- - `element` (required): The `HTMLElement` or `DocumentFragment` to render the template into.
2079
-
2080
- **Returns:**
2081
-
2082
- - `() => void`: An `unsubscribe` function to stop listening to store updates and clean up.
2083
-
2084
- ### The `api` Object
2085
-
2086
- The `renderFn` receives a powerful `api` object that contains all methods from the store's API (`getEntities`, `getEntity`, `notify`, etc.) plus special methods for the web package.
2087
-
2088
- **`api.render(id, typeName?, Type?)`**
2089
-
2090
- This method is the cornerstone of entity-based rendering. It looks up an entity by its `id`, finds its corresponding type definition, and calls the `render(entity, api)` method on that type. When you pass `typeName` and `Type`, it will lazily register the type with `api.setType(typeName, Type)` if the type is not already present.
2091
-
2092
- ### Package Entry Points
2093
-
2094
- `@inglorious/web` keeps its root entry point intentionally small:
2095
-
2096
- ```javascript
2097
- import { mount, html, svg } from "@inglorious/web"
2098
- ```
2099
-
2100
- Import everything else from the package that owns it, or from an explicit `@inglorious/web` subpath:
2101
-
2102
- ```javascript
2103
- import { createStore } from "@inglorious/store"
2104
- import { handleAsync, handleRequest } from "@inglorious/store/async"
2105
- import { optimistic } from "@inglorious/store/optimistic"
2106
- import { compute, createSelector } from "@inglorious/store/select"
2107
- import { createDevtools } from "@inglorious/store/client/devtools"
2108
-
2109
- import { classMap } from "@inglorious/web/directives/class-map"
2110
- import { ref, createRef } from "@inglorious/web/directives/ref"
2111
- import { repeat } from "@inglorious/web/directives/repeat"
2112
- import { styleMap } from "@inglorious/web/directives/style-map"
2113
- import { unsafeHTML } from "@inglorious/web/directives/unsafe-html"
2114
- import { when } from "@inglorious/web/directives/when"
2115
- import { staticHtml, unsafeStatic } from "@inglorious/web/static"
2116
- import { render, trigger } from "@inglorious/web/test"
2117
-
2118
- import { Form } from "@inglorious/web/form"
2119
- import { Router, setRoutes } from "@inglorious/web/router"
2120
- import { Geolocation } from "@inglorious/web/sensors/geolocation"
2121
- import { Compass } from "@inglorious/web/sensors/compass"
2122
- ```
2123
-
2124
- This keeps `lit-html` as an internal implementation detail while still giving applications stable, tree-shakeable import paths.
2125
-
2126
- ---
2127
-
2128
- ## Error Handling
2129
45
 
2130
- When an entity's `render()` method throws an error, it can crash your entire app since the whole tree re-renders.
2131
-
2132
- **Best practice:** Wrap your render logic in try-catch at the entity level:
2133
-
2134
- ```javascript
2135
- const MyType = {
2136
- render(entity, api) {
2137
- try {
2138
- // Your render logic
2139
- return html`<div>...</div>`
2140
- } catch (error) {
2141
- console.error("Render error:", error)
2142
- return html`<div class="error">Failed to render ${entity.id}</div>`
2143
- }
2144
- },
2145
- }
46
+ mount(store, (api) => api.render("counter"), document.getElementById("root"))
2146
47
  ```
2147
48
 
2148
- ---
2149
-
2150
- ## Performance Tips
2151
-
2152
- 1. **Keep render() pure** - No side effects, no API calls
2153
- 2. **Avoid creating new objects in render** - Use entity properties, not inline `{}`
2154
- 3. **Use `repeat()` directive for lists** - Helps lit-html track item identity
2155
- 4. **Profile with browser DevTools** - Look for slow renders (>16ms)
2156
- 5. **Consider virtualization** - Use [Inglorious UI](https://inglorious.dev/ui) for 1000+ items
2157
-
2158
- If renders are slow:
2159
-
2160
- - Move expensive computations to event handlers
2161
- - Cache derived values on the entity
2162
- - ...Or memoize them!
2163
-
2164
- ---
2165
-
2166
- ## Relationship to Inglorious Engine
2167
-
2168
- `@inglorious/web` shares its architectural philosophy with [Inglorious Engine](https://www.npmjs.com/package/@inglorious/engine):
2169
-
2170
- - **Same state management** - Both use `@inglorious/store`
2171
- - **Same event system** - Entity behaviors respond to events
2172
- - **Same rendering model** - Full-state render on every update
2173
-
2174
- The key difference:
2175
-
2176
- - **@inglorious/engine** targets game loops (60fps, Canvas/WebGL rendering)
2177
- - **@inglorious/web** targets web UIs (DOM rendering, user interactions)
2178
-
2179
- You can even mix them in the same app!
49
+ A type handles events and renders its entity. Every change is an event, applied in order; after each update the whole template reruns and lit-html patches what changed. Handlers are tested as functions, with `trigger` from `@inglorious/web/test`.
2180
50
 
2181
- ---
51
+ ## What's in it
2182
52
 
2183
- ## Static Site Generation with SSX
53
+ - [Router](https://inglorious.dev/web/featured/router): path routing, lazy pages, guards as behaviors, accessible navigation.
54
+ - [Form](https://inglorious.dev/web/featured/form): values, errors, touched state, array fields, validation.
55
+ - [Device](https://inglorious.dev/web/featured/device): sensors and features as entity types, with Capacitor plugins in a native app: compass, geolocation, element size, media queries, network status, page visibility, keyboard, share, haptics, local notifications, biometrics, storage.
56
+ - [Native app and PWA](https://inglorious.dev/web/featured/overview): app links, back button, system bars, store updates, live updates, PWA updates.
57
+ - [Sign-in](https://inglorious.dev/web/featured/sign-in), [analytics](https://inglorious.dev/web/featured/analytics) and [push](https://inglorious.dev/web/featured/push), each behind an adapter.
58
+ - [Decorators](https://inglorious.dev/web/advanced/decorators): `withDebounce`, `withThrottle`, `withLiveReload`, `withErrorBoundary`.
59
+ - [JSX](https://inglorious.dev/web/featured/jsx) and [Vue-like templates](https://inglorious.dev/web/featured/vue-templates), compiled to lit-html.
60
+ - [SSX](https://inglorious.dev/ssx/) for sites rendered at build time or on request, then hydrated.
2184
61
 
2185
- For building **static HTML sites** with full pre-rendering, client-side hydration, and automatic sitemap/RSS generation, use [**@inglorious/ssx**](https://www.npmjs.com/package/@inglorious/ssx).
2186
-
2187
- SSX is built entirely on **@inglorious/web** and lets you use the same entity-based patterns for both interactive apps and static sites, with:
2188
-
2189
- - Pre-rendered HTML at build time
2190
- - Automatic code splitting and lazy loading
2191
- - Client-side hydration with lit-html
2192
- - File-based routing
2193
- - Sitemap and RSS feed generation
2194
- - Incremental builds
2195
-
2196
- It's the perfect companion to @inglorious/web for building blazing-fast static sites, blogs, documentation, and marketing pages.
2197
-
2198
- ---
2199
-
2200
- ## Examples
2201
-
2202
- Check out these demos to see `@inglorious/web` in action:
2203
-
2204
- - **[Web TodoMVC](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/web-todomvc)** - A client-only TodoMVC implementation, a good starting point for learning the framework.
2205
- - **[Web TodoMVC-CS](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/web-todomvc-cs)** - A client-server version with JSON server, showing async event handlers and API integration with component organization (render/handlers modules).
2206
- - **[Web Form](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/web-form)** - Form handling with validation, arrays, and field helpers.
2207
- - **[Web Router](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/web-router)** - Entity-based client-side routing with hash navigation.
2208
-
2209
- ---
2210
-
2211
- ## Related Packages
2212
-
2213
- - [**@inglorious/ssx**](https://www.npmjs.com/package/@inglorious/ssx) - Static site generation with pre-rendering and client hydration
2214
- - [**@inglorious/store**](https://www.npmjs.com/package/@inglorious/store) - Entity-based state management (used by @inglorious/web)
2215
- - [**@inglorious/i18n**](https://www.npmjs.com/package/@inglorious/i18n) - Internationalization: translations, plurals and formatting driven by a store entity
2216
- - [**@inglorious/engine**](https://www.npmjs.com/package/@inglorious/engine) - Game engine with the same entity architecture
2217
- - [**@inglorious/create-app**](https://www.npmjs.com/package/@inglorious/create-app) - Scaffolding tool for quick project setup
2218
-
2219
- ---
62
+ UI components live in [Inglorious UI](https://inglorious.dev/ui).
2220
63
 
2221
64
  ## License
2222
65
 
2223
- **MIT License - Free and open source**
2224
-
2225
- Created by [Matteo Antony Mistretta](https://github.com/IngloriousCoderz)
2226
-
2227
- You're free to use, modify, and distribute this software. See [LICENSE](./LICENSE) for details.
2228
-
2229
- ---
2230
-
2231
- ## Contributing
2232
-
2233
- Contributions welcome! Please read our [Contributing Guidelines](../../CONTRIBUTING.md) first.
66
+ MIT © [Matteo Antony Mistretta](https://github.com/IngloriousCoderz)