@inglorious/web 6.29.0 → 6.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,2290 +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
- ## Device
1280
-
1281
- `@inglorious/web/device/*` holds what the phone or browser can sense or do. Each works in a browser through its web API. In a native app, the ones with a Capacitor plugin use it, once you hand it over as `plugin`. Entity types answer to their own entity (`#id:event`) and keep listeners, observers and watches outside it. Besides the ones below, `ElementSize`, `MediaQuery`, `NetworkStatus` and `PageVisibility` follow an element's size, a media query, the connection and the page's visibility.
1282
-
1283
- ### Geolocation
1284
-
1285
- `createGeolocation` from `@inglorious/web/device/geolocation` returns the type that keeps the device's position in the store. In a native app it uses [`@capacitor/geolocation`](https://capacitorjs.com/docs/apis/geolocation) when given as `plugin`, so iOS asks for the location once, for the app; elsewhere it uses `navigator.geolocation`.
1286
-
1287
- ```javascript
1288
- import { createStore } from "@inglorious/store"
1289
- import { Geolocation as GeolocationPlugin } from "@capacitor/geolocation"
1290
- import { createGeolocation } from "@inglorious/web/device/geolocation"
1291
-
1292
- const store = createStore({
1293
- types: { Geolocation: createGeolocation({ plugin: GeolocationPlugin }) },
1294
- autoCreateEntities: true,
1295
- })
1296
-
1297
- // The store now contains a `geolocation` entity.
1298
- store.getState().geolocation
1299
- ```
1300
-
1301
- The entity state contains:
1302
-
1303
- - `isSupported` — whether the position can be read here
1304
- - `isLoading` — whether a current-position request or first watch result is pending
1305
- - `isWatching` — whether a geolocation watch is active
1306
- - `position` — the latest normalized `{ coords, timestamp }` value
1307
- - `error` — the latest normalized `{ code, message }` error
1308
-
1309
- Events:
1310
-
1311
- - `geolocationRequest` — request the current position
1312
- - `geolocationWatch` — start watching position changes
1313
- - `geolocationUnwatch` — stop the active watch
1314
-
1315
- ```javascript
1316
- api.notify("#geolocation:geolocationRequest", {
1317
- enableHighAccuracy: true,
1318
- timeout: 5000,
1319
- })
1320
-
1321
- api.notify("#geolocation:geolocationWatch")
1322
- api.notify("#geolocation:geolocationUnwatch")
1323
- ```
1324
-
1325
- #### Example: Show current location
1326
-
1327
- ```javascript
1328
- import { mount, html } from "@inglorious/web"
1329
- import { when } from "@inglorious/web/directives/when"
1330
- import { store } from "./store.js"
1331
-
1332
- const renderApp = (api) => {
1333
- const geolocation = api.getEntity("geolocation")
1334
- const position = geolocation.position
1335
-
1336
- return html`
1337
- <section>
1338
- <h2>Geolocation</h2>
1339
- <p>Supported: ${geolocation.isSupported ? "yes" : "no"}</p>
1340
- <p>Loading: ${geolocation.isLoading ? "yes" : "no"}</p>
1341
- <p>
1342
- Position:
1343
- ${when(
1344
- position,
1345
- () =>
1346
- html`${position.coords.latitude.toFixed(4)},
1347
- ${position.coords.longitude.toFixed(4)}`,
1348
- () => "unknown",
1349
- )}
1350
- </p>
1351
- <p>Error: ${geolocation.error ? geolocation.error.message : "none"}</p>
1352
- <button
1353
- @click=${() =>
1354
- api.notify("#geolocation:geolocationRequest", {
1355
- enableHighAccuracy: true,
1356
- timeout: 5000,
1357
- })}
1358
- >
1359
- Request Current Position
1360
- </button>
1361
- <button @click=${() => api.notify("#geolocation:geolocationWatch")}>
1362
- Start Watch
1363
- </button>
1364
- <button @click=${() => api.notify("#geolocation:geolocationUnwatch")}>
1365
- Stop Watch
1366
- </button>
1367
- </section>
1368
- `
1369
- }
1370
-
1371
- mount(store, renderApp, document.getElementById("root"))
1372
- ```
1373
-
1374
- ### Compass
1375
-
1376
- `@inglorious/web` also includes a `Compass` type for managing device orientation and heading state inside the store.
1377
-
1378
- ```javascript
1379
- import { createStore } from "@inglorious/store"
1380
- import { Compass } from "@inglorious/web/compass"
1381
-
1382
- const store = createStore({
1383
- types: { Compass },
1384
- autoCreateEntities: true,
1385
- })
1386
-
1387
- // The store now contains a `compass` entity.
1388
- store.getState().compass
1389
- ```
1390
-
1391
- The entity state contains:
1392
-
1393
- - `isSupported` — whether device orientation sensors are available
1394
- - `isLoading` — whether permissions or heading data are pending
1395
- - `isCompassPermissionGranted` — whether compass permission has been granted
1396
- - `isCompassActive` — whether a valid heading is currently active
1397
- - `heading` — the latest heading in degrees, or `null`
1398
- - `error` — the latest normalized `{ code, message }` error
1399
- - `manualOffset` — a heading offset in degrees to apply to raw sensor values
1400
-
1401
- Events:
1402
-
1403
- - `compassPermissionsRequest` — request compass permission when needed
1404
- - `compassWatch` — start listening for device orientation events
1405
- - `compassUnwatch` — stop listening for device orientation events
1406
- - `compassPermissionsGrant` — set permission granted
1407
- - `compassActiveChange` — update active/inactive state
1408
- - `compassHeadingChange` — update the latest heading
1409
- - `compassError` — store a normalized compass error
1410
-
1411
- ```javascript
1412
- api.notify("#compass:compassPermissionsRequest")
1413
- api.notify("#compass:compassWatch")
1414
- api.notify("#compass:compassUnwatch")
1415
- ```
1416
-
1417
- #### Example: Show heading and request permission
1418
-
1419
- ```javascript
1420
- import { mount, html } from "@inglorious/web"
1421
- import { store } from "./store.js"
1422
-
1423
- const renderApp = (api) => {
1424
- const compass = api.getEntity("compass")
1425
-
1426
- return html`
1427
- <section>
1428
- <h2>Compass</h2>
1429
- <p>Supported: ${compass.isSupported ? "yes" : "no"}</p>
1430
- <p>
1431
- Permission:
1432
- ${compass.isCompassPermissionGranted ? "granted" : "unknown"}
1433
- </p>
1434
- <p>Active: ${compass.isCompassActive ? "yes" : "no"}</p>
1435
- <p>
1436
- Heading:
1437
- ${
1438
- compass.heading !== null
1439
- ? `${compass.heading.toFixed(1)}°`
1440
- : "unknown"
1441
- }
1442
- </p>
1443
- <p>Error: ${compass.error ? compass.error.message : "none"}</p>
1444
- <button @click=${() => api.notify("#compass:compassPermissionsRequest")}>
1445
- Request Permission
1446
- </button>
1447
- <button @click=${() => api.notify("#compass:compassWatch")}>
1448
- Start Compass
1449
- </button>
1450
- <button @click=${() => api.notify("#compass:compassUnwatch")}>
1451
- Stop Compass
1452
- </button>
1453
- </section>
1454
- `
1455
- }
1456
-
1457
- mount(store, renderApp, document.getElementById("root"))
1458
- ```
1459
-
1460
- ### Share
1461
-
1462
- `@inglorious/web/device/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:
1463
-
1464
- - in a native app, the system's share sheet, through [`@capacitor/share`](https://capacitorjs.com/docs/apis/share) when you hand it over;
1465
- - in a browser, a file (a `url` with a `fileName`) downloads, since a browser has nowhere better to put it;
1466
- - otherwise the browser's share sheet where there is one (Web Share API), else the link is copied.
1467
-
1468
- ```javascript
1469
- import { Share } from "@capacitor/share"
1470
- import { createShare } from "@inglorious/web/device/share"
1471
-
1472
- const types = { Share: createShare({ plugin: Share }) }
1473
-
1474
- api.notify("#share:share", {
1475
- title: "My job",
1476
- url: "https://example.com/jobs/1",
1477
- })
1478
- api.notify("#share:share", {
1479
- title: "Wedding",
1480
- url: icsUrl,
1481
- fileName: "wedding.ics",
1482
- })
1483
- ```
1484
-
1485
- `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.
1486
-
1487
- ### Haptics
1488
-
1489
- `@inglorious/web/device/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.
1490
-
1491
- ```javascript
1492
- import { Haptics } from "@capacitor/haptics"
1493
- import { haptics } from "@inglorious/web/device/haptics"
1494
-
1495
- haptics.use(Haptics)
1496
-
1497
- haptics.selection() // a toggle flipped, a threshold crossed
1498
- haptics.impact("heavy") // "light", "medium" (default) or "heavy"
1499
- haptics.notification("error") // "success" (default), "warning" or "error"
1500
- ```
1501
-
1502
- Inglorious UI plays them too: `PullToRefresh` gives a tick when letting go would refresh.
1503
-
1504
- ### Local Notifications
1505
-
1506
- `createLocalNotifications` from `@inglorious/web/device/local-notifications` is the type behind reminders the device shows on its own, such as "your job starts in an hour". In a native app they go through [`@capacitor/local-notifications`](https://capacitorjs.com/docs/apis/local-notifications), once you hand the plugin over, and show even with the app closed. In a browser they show only while the page is open, through the Notification API.
1507
-
1508
- ```javascript
1509
- import { LocalNotifications } from "@capacitor/local-notifications"
1510
- import { createLocalNotifications } from "@inglorious/web/device/local-notifications"
1511
-
1512
- const types = {
1513
- Reminders: createLocalNotifications({ plugin: LocalNotifications }),
1514
- }
1515
- const entities = { reminders: { type: "Reminders" } }
1516
-
1517
- api.notify("#reminders:localNotificationSchedule", {
1518
- id: 1,
1519
- title: "Wedding in an hour",
1520
- body: "Villa Erba, Cernobbio",
1521
- at: new Date(start - HOUR),
1522
- url: "/jobs/1",
1523
- })
1524
- api.notify("#reminders:localNotificationCancel", 1)
1525
- ```
1526
-
1527
- The entity's `permission` is `"granted"`, `"denied"`, `"prompt"` or `"unsupported"`, and `null` until the device says. `localNotificationsAsk` brings up the system's dialog: send it from a tap, which a browser requires.
1528
-
1529
- An `id` is a whole number, which the app chooses so it can cancel the reminder later. A tap on a reminder with a `url` navigates there, through `onTap(url, api)` in the config, by default `#router:navigate`.
1530
-
1531
- #### Secrets
1532
-
1533
- `createSecureStorage` keeps what must stay private, such as a session's tokens, in the Keychain (iOS) or Keystore (Android), through the same [`@capgo/capacitor-native-biometric`](https://github.com/Cap-go/capacitor-native-biometric) plugin. A browser has nothing safer, so there it uses `localStorage`. It works wherever `createNativeStorage` does:
1534
-
1535
- ```javascript
1536
- import { NativeBiometric } from "@capgo/capacitor-native-biometric"
1537
- import { createSecureStorage } from "@inglorious/web/device/storage"
1538
-
1539
- const secrets = createSecureStorage({ plugin: NativeBiometric })
1540
-
1541
- createClient(url, key, { auth: { storage: secrets } })
1542
- ```
1543
-
1544
- ### Biometrics
1545
-
1546
- `createBiometrics` from `@inglorious/web/device/biometrics` is the type behind "unlock with Face ID". In a native app, `verify` shows the system's biometric prompt through [`@capgo/capacitor-native-biometric`](https://github.com/Cap-go/capacitor-native-biometric), once you hand the plugin over. A browser has no equivalent, so there it is never available.
1547
-
1548
- ```javascript
1549
- import { NativeBiometric } from "@capgo/capacitor-native-biometric"
1550
- import { createBiometrics } from "@inglorious/web/device/biometrics"
1551
-
1552
- const types = { Biometrics: createBiometrics({ plugin: NativeBiometric }) }
1553
- const entities = { biometrics: { type: "Biometrics" } }
1554
-
1555
- api.notify("#biometrics:verify", { reason: "Unlock your account" })
1556
- ```
1557
-
1558
- - `isAvailable`: whether the device can verify, to hide the button otherwise.
1559
- - `biometryType`: `"face"`, `"fingerprint"`, `"iris"`, `"multiple"` or `"passcode"`, to name it.
1560
- - `result`: `"verified"` or `"cancelled"`. Closing the prompt is not an error.
1561
- - `status` and `error`: those of `handleRequest`, with `error` `"unavailable"` or `"failed"`.
1562
-
1563
- On iOS, Face ID needs an `NSFaceIDUsageDescription` in `Info.plist`.
1564
-
1565
- ### Keyboard
1566
-
1567
- 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/device/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.
1568
-
1569
- ```javascript
1570
- import { watchKeyboard } from "@inglorious/web/device/keyboard"
1571
-
1572
- watchKeyboard()
1573
- ```
1574
-
1575
- 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:
1576
-
1577
- ```css
1578
- .composer {
1579
- position: fixed;
1580
- bottom: var(--iw-keyboard-height, 0px);
1581
- }
1582
- ```
1583
-
1584
- It returns a function that stops following.
1585
-
1586
- ### Storage
1587
-
1588
- 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):
1589
-
1590
- ```javascript
1591
- import { Preferences } from "@capacitor/preferences"
1592
- import { withStorage } from "@inglorious/store/storage"
1593
- import { createNativeStorage } from "@inglorious/web/device/storage"
1594
-
1595
- const preferences = createNativeStorage({ plugin: Preferences })
1596
-
1597
- const types = {
1598
- Settings: [Settings, withStorage(["theme"], { storage: () => preferences })],
1599
- }
1600
- ```
1601
-
1602
- 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`.
1603
-
1604
- It works as Supabase's session storage too, so signing in survives the same clean-ups:
1605
-
1606
- ```javascript
1607
- createClient(url, key, { auth: { storage: preferences } })
1608
- ```
1609
-
1610
- ---
1611
-
1612
- ## Native App
1613
-
1614
- `@inglorious/web/native/*` holds what exists because the app is native. Each does nothing outside a native app, and `isNative()` from `@inglorious/web/native` says whether it is one.
1615
-
1616
- ### App Links
1617
-
1618
- 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.
1619
-
1620
- ```javascript
1621
- import { App } from "@capacitor/app"
1622
- import { watchAppLinks } from "@inglorious/web/native/app-links"
1623
-
1624
- watchAppLinks(App, store)
1625
- ```
1626
-
1627
- `{ id }` as a third argument notifies a router with another id; it returns a function that stops listening.
1628
-
1629
- 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.
1630
-
1631
- ### Back Button
1632
-
1633
- 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.
1634
-
1635
- ```javascript
1636
- import { App } from "@capacitor/app"
1637
- import { watchBackButton } from "@inglorious/web/native/back-button"
1638
-
1639
- watchBackButton(App, { rootPaths: ["/", "/search", "/profile"] })
1640
- ```
1641
-
1642
- `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.
1643
-
1644
- ### System Bars
1645
-
1646
- 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.
1647
-
1648
- ```javascript
1649
- import { SystemBars } from "@capacitor/core"
1650
- import { watchSystemBars } from "@inglorious/web/native/system-bars"
1651
-
1652
- watchSystemBars(SystemBars)
1653
- ```
1654
-
1655
- It returns a function that stops following.
1656
-
1657
- ### Native App Updates
1658
-
1659
- 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.
1660
-
1661
- ```javascript
1662
- import { App } from "@capacitor/app"
1663
- import {
1664
- createNativeUpdate,
1665
- watchNativeUpdate,
1666
- } from "@inglorious/web/native/update"
1667
-
1668
- const types = { NativeUpdate: [createNativeUpdate({ adapter }), template] }
1669
- const entities = { nativeUpdate: { type: "NativeUpdate" } }
1670
-
1671
- watchNativeUpdate(App, store)
1672
- ```
1673
-
1674
- `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.
1675
-
1676
- 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.
1677
-
1678
- The `nativeUpdate` entity contains:
1679
-
1680
- - `isUpdateRequired` — the installed build is below the minimum
1681
- - `storeUrl` — where the update button goes, or `null`
1682
-
1683
- Events:
1684
-
1685
- - `nativeUpdateCheck` — `{ platform, build }`, sent by `watchNativeUpdate`
1686
- - `nativeUpdateApply` — opens the store
1687
-
1688
- 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.
1689
-
1690
- ### Live Updates
1691
-
1692
- 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.
1693
-
1694
- ```javascript
1695
- import { App } from "@capacitor/app"
1696
- import { LiveUpdate } from "@capawesome/capacitor-live-update"
1697
- import {
1698
- createLiveUpdate,
1699
- watchLiveUpdate,
1700
- } from "@inglorious/web/native/live-update"
1701
-
1702
- const types = { LiveUpdate: createLiveUpdate({ plugin: LiveUpdate }) }
1703
- const entities = { liveUpdate: { type: "LiveUpdate" } }
1704
-
1705
- watchLiveUpdate({
1706
- plugin: LiveUpdate,
1707
- app: App,
1708
- store,
1709
- manifestUrl,
1710
- release: Number(import.meta.env.VITE_LIVE_UPDATE_RELEASE),
1711
- })
1712
- ```
1713
-
1714
- `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.
1715
-
1716
- `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.
1717
-
1718
- 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.
1719
-
1720
- ---
1721
-
1722
- ## PWA Updates
1723
-
1724
- `@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.
1725
-
1726
- 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:
1727
-
1728
- - at launch, before anything is touched;
1729
- - each time the app goes to the background or comes back to the foreground.
1730
-
1731
- 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.
1732
-
1733
- ```javascript
1734
- import { isNative } from "@inglorious/web/native"
1735
- import { watchPwaUpdate } from "@inglorious/web/pwa"
1736
- import { registerSW } from "virtual:pwa-register"
1737
-
1738
- if (!isNative()) {
1739
- registerSW({
1740
- onRegisteredSW(url, registration) {
1741
- if (registration) watchPwaUpdate(registration)
1742
- },
1743
- })
1744
- }
1745
- ```
1746
-
1747
- 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.
1748
-
1749
- ### Offering "Update now"
1750
-
1751
- 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:
1752
-
1753
- ```javascript
1754
- import { PwaUpdate, watchPwaUpdate } from "@inglorious/web/pwa"
1755
-
1756
- const store = createStore({ types: { PwaUpdate }, autoCreateEntities: true })
1757
-
1758
- watchPwaUpdate(registration, store)
1759
- ```
1760
-
1761
- The `pwaUpdate` entity contains:
1762
-
1763
- - `isUpdateReady` — a new version is waiting for the next reload
1764
-
1765
- Events:
1766
-
1767
- - `pwaUpdateReady` — sent by `watchPwaUpdate` when a version lands mid-session
1768
- - `pwaUpdateApply` — moves over to the waiting version now, reloading the page
1769
-
1770
- ```javascript
1771
- const renderUpdate = (api) =>
1772
- when(
1773
- api.getEntity("pwaUpdate").isUpdateReady,
1774
- () =>
1775
- html`<button @click=${() => api.notify("#pwaUpdate:pwaUpdateApply")}>
1776
- Update now
1777
- </button>`,
1778
- )
1779
- ```
1780
-
1781
- 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.
1782
-
1783
- ---
1784
-
1785
- ## Sign-in
1786
-
1787
- `@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.
1788
-
1789
- ```javascript
1790
- import { supabaseAuth } from "@inglorious/supabase"
1791
- import { createAuth, watchAuth } from "@inglorious/web/auth"
1792
-
1793
- const adapter = supabaseAuth(supabase)
1794
-
1795
- const types = {
1796
- Auth: { ...createAuth({ adapter, methods: ["password", "code"] }), render },
1797
- }
1798
-
1799
- watchAuth(adapter, store) // keeps `user` in step with the session
12
+ ```bash
13
+ pnpm add @inglorious/store @inglorious/web
1800
14
  ```
1801
15
 
1802
- `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).
1803
-
1804
- 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.
16
+ Or scaffold an app, with routing, UI, i18n, sign-in, push and native builds wired:
1805
17
 
1806
- 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:
1807
-
1808
- ```javascript
1809
- const types = {
1810
- Auth: [
1811
- createAuth({ adapter }),
1812
- {
1813
- signedIn(entity, { isNew }, api) {
1814
- api.notify("#router:navigate", isNew ? "/onboarding" : "/")
1815
- },
1816
- },
1817
- ],
1818
- }
18
+ ```bash
19
+ pnpm create @inglorious/app
1819
20
  ```
1820
21
 
1821
- 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.
1822
-
1823
- `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.
1824
-
1825
- 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.
1826
-
1827
- `create-app --auth` generates the screen, the account actions in the app bar, the Edge Function that erases accounts and the email templates.
1828
-
1829
- ---
1830
-
1831
- ## Forms
1832
-
1833
- `@inglorious/web` includes a small but powerful `form` type for managing form state inside your entity store. It offers:
1834
-
1835
- - Declarative form state held on an entity (`initialValues`, `values`, `errors`, `touched`)
1836
- - Convenient helpers for reading field value/error/touched state (`getFieldValue`, `getFieldError`, `isFieldTouched`)
1837
- - Built-in handlers for field changes, blurs, array fields, sync/async validation and submission
1838
-
1839
- ### Add the `form` type
1840
-
1841
- 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
1842
23
 
1843
24
  ```javascript
1844
25
  import { createStore } from "@inglorious/store"
1845
- import { Form } from "@inglorious/web/form"
1846
-
1847
- const types = { Form }
1848
-
1849
- const entities = {
1850
- form: {
1851
- type: "Form",
1852
- initialValues: {
1853
- name: "",
1854
- email: "",
1855
- addresses: [],
1856
- },
1857
- },
1858
- }
1859
-
1860
- const store = createStore({ types, entities })
1861
- ```
1862
-
1863
- ### How it works (events & helpers)
1864
-
1865
- The `form` type listens for a simple set of events (target the specific entity id with `#<id>:<event>`):
1866
-
1867
- - `#<id>:fieldChange` — payload { path, value, validate? } — set a field value and optionally run a single-field validator
1868
- - `#<id>:fieldBlur` — payload { path, validate? } — mark field touched and optionally validate on blur
1869
- - `#<id>:fieldArrayAppend|fieldArrayRemove|fieldArrayInsert|fieldArrayMove` — manipulate array fields
1870
- - `#<id>:reset` — reset the form to `initialValues`
1871
- - `#<id>:validate` — synchronous whole-form validation; payload { validate }
1872
- - `#<id>:validateAsync` — async whole-form validation; payload { validate }
1873
- - `#<id>:submit` — typically handled by your `form` type's `submit` method (implement custom behavior there)
1874
-
1875
- Helpers available from the package let you read state from templates and field helper components:
1876
-
1877
- - `getFieldValue(formEntity, path)` — read a nested field value
1878
- - `getFieldError(formEntity, path)` — read a nested field's error message
1879
- - `isFieldTouched(formEntity, path)` — check if a field has been touched
1880
-
1881
- Form state includes helpful flags:
1882
-
1883
- - `isPristine` — whether the form has changed from initial values
1884
- - `isValid` — whether the current form has no validation errors
1885
- - `isValidating` — whether async validation is in progress
1886
- - `isSubmitting` — whether submission is in progress
1887
- - `submitError` — an optional submission-level error message
1888
-
1889
- ### Simple example (from examples/apps/web-form)
1890
-
1891
- Field components typically call `api.notify` and the `form` entity reacts accordingly. Example input field usage:
1892
-
1893
- ```javascript
1894
- // inside a field component render
1895
- @input=${(e) => api.notify(`#${entity.id}:fieldChange`, { path: 'name', value: e.target.value, validate: validateName })}
1896
- @blur=${() => api.notify(`#${entity.id}:fieldBlur`, { path: 'name', validate: validateName })}
1897
- ```
1898
-
1899
- Submissions and whole-form validation can be triggered from a `form` render:
1900
-
1901
- ```javascript
1902
- <form @submit=${() => { api.notify(`#form:validate`, { validate: validateForm }); api.notify(`#form:submit`) }}>
1903
- <!-- inputs / buttons -->
1904
- </form>
1905
- ```
1906
-
1907
- For a complete, working demo and helper components look at `examples/apps/web-form` which ships with the repository.
1908
-
1909
- ---
1910
-
1911
- ## Building Component Libraries with Inglorious Web
1912
-
1913
- **Inglorious types are uniquely suited for component libraries** because they're fully customizable through JavaScript's spread operator.
1914
-
1915
- ### The Pattern
1916
-
1917
- **Library publishes types:**
1918
-
1919
- ```javascript
1920
- // @acme/design-system/data-grid.js
1921
- export const DataGrid = {
1922
- render(entity, api) {
1923
- const type = api.getType(entity.type)
1924
-
1925
- return html`
1926
- <div class="data-grid">
1927
- ${entity.rows.map((row) => type.renderRow(entity, row, api))}
1928
- </div>
1929
- `
1930
- },
1931
- renderRow(entity, row, api) {
1932
- return html`<div class="data-grid-row">${row.name}</div>`
1933
- },
1934
- rowClick(entity, row) {
1935
- entity.selectedRow = row
1936
- },
1937
- }
1938
- ```
1939
-
1940
- **Users customize freely:**
1941
-
1942
- ```javascript
1943
- import { DataGrid } from "@acme/design-system/data-grid"
1944
-
1945
- // Use as-is
1946
- const SimpleGrid = { ...DataGrid }
1947
-
1948
- // Override methods
1949
- const CustomGrid = {
1950
- ...DataGrid,
1951
- renderRow(entity, row, api) {
1952
- return html`<div class="data-grid-row custom">
1953
- ${row.name} - ${row.email}
1954
- </div>`
1955
- },
1956
- }
1957
-
1958
- // Compose with behaviors
1959
- import { sortable, exportable } from "@acme/design-system/behaviors"
1960
-
1961
- const AdvancedGrid = [
1962
- DataGrid,
1963
- sortable,
1964
- exportable,
1965
- {
1966
- rowClick(entity, row) {
1967
- console.log("Custom click handler", row)
1968
- },
1969
- },
1970
- ]
1971
- ```
1972
-
1973
- ### Why This Is Better Than React Components
1974
-
1975
- | Feature | React Components | Inglorious Types |
1976
- | -------------------------- | ------------------------------ | ----------------------------------------- |
1977
- | Customize rendering | Only if `render` prop exposed | Override `render()` method directly |
1978
- | Customize behavior | Only if callback props exposed | Override any method |
1979
- | Compose multiple libraries | Wrapper hell / HOCs | Array composition `[type1, type2, {...}]` |
1980
- | Access internals | Private - must fork | Public - spread and override |
1981
- | Type safety | Props interface | Entity schema + method signatures |
1982
-
1983
- **Users get complete control** without forking your library. They can override rendering, behavior, or both—down to individual methods.
1984
-
1985
- ---
1986
-
1987
- ## Using Third-Party Web Components
1988
-
1989
- 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.
1990
-
1991
- ### ⚠️ SSG/SSR Considerations
1992
-
1993
- **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.
1994
-
1995
- **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:
1996
-
1997
- - They won't appear in the pre-rendered HTML
1998
- - They're not SEO-friendly in their initial state
1999
- - They may cause FOUC (Flash of Unstyled Content)
2000
- - They should be treated as client-only enhancements
2001
-
2002
- **Recommendation for SSX projects:**
2003
-
2004
- - Use Inglorious Web components for content that needs to be pre-rendered (product listings, blog posts, documentation)
2005
- - Use Web Components for interactive, client-only features (color pickers, rich text editors, admin tools)
2006
-
2007
- **Use Inglorious Web + [Inglorious UI](https://inglorious.dev/ui) primitives when:**
2008
-
2009
- - ✅ You want full architectural consistency
2010
- - ✅ You need fine-grained control over behavior
2011
- - ✅ You want to compose behaviors via type composition
2012
- - ✅ You need time-travel debugging of component state
2013
- - ✅ You want minimal bundle size
2014
- - ✅ You're building a core pattern used throughout your app
2015
- - ✅ You want the simplest possible tests
2016
- - ✅ You need custom behavior that third-party components don't provide
2017
- - ✅ You're using SSX for static site generation
2018
-
2019
- **Use Web Components (like Shoelace) when:**
2020
-
2021
- - ✅ You need complex, battle-tested UI (date pickers, rich text editors)
2022
- - ✅ You want a comprehensive design system out of the box
2023
- - ✅ Speed of development matters more than architectural purity
2024
- - ✅ You need features you don't want to build yourself (color pickers, tree views)
2025
- - ✅ The component is isolated or used infrequently
2026
- - ✅ You're okay with some state living outside the store
2027
- - ✅ You're building a client-only application (not using SSX)
26
+ import { html, mount } from "@inglorious/web"
2028
27
 
2029
- ### Example: Hybrid Approach
2030
-
2031
- ```javascript
2032
- import "@shoelace-style/shoelace/dist/components/color-picker/color-picker.js"
2033
-
2034
- const types = {
2035
- // App-specific type - full store integration
2036
- ProductTable, // Web Component - for specialized UI
2037
- ThemeEditor: {
2038
- colorChange(entity, color) {
2039
- entity.primaryColor = color
2040
- },
2041
- render(entity, api) {
2042
- return html`
2043
- <div>
2044
- <label>Primary Color</label>
2045
- <sl-color-picker
2046
- value=${entity.primaryColor}
2047
- @sl-change=${(e) =>
2048
- api.notify("#themeEditor:colorChange", e.target.value)}
2049
- ></sl-color-picker>
2050
- </div>
2051
- `
2052
- },
2053
- },
2054
- }
2055
- ```
2056
-
2057
- This hybrid approach gives you the best of both worlds: architectural consistency for core patterns, and battle-tested components for complex UI.
2058
-
2059
- ---
2060
-
2061
- ## Simplifying Entity Setup with `autoCreateEntities`
2062
-
2063
- 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.
2064
-
2065
- ```javascript
2066
28
  const types = {
2067
- App: {
2068
- render(entity, api) {
2069
- return html`
2070
- <div class="app">${api.render("header")} ${api.render("content")}</div>
2071
- `
2072
- },
2073
- },
2074
- Header: {
2075
- render(entity, api) {
2076
- return html`<header>${entity.title}</header>`
29
+ Counter: {
30
+ increment(entity) {
31
+ entity.value++
2077
32
  },
2078
- },
2079
- Content: {
2080
33
  render(entity, api) {
2081
- return html`<main>${entity.text}</main>`
34
+ return html`<button @click=${() => api.notify(`#${entity.id}:increment`)}>
35
+ Clicked ${entity.value} times
36
+ </button>`
2082
37
  },
2083
38
  },
2084
39
  }
2085
40
 
2086
- // Without autoCreateEntities - you need to define every entity
2087
- const entities = {
2088
- app: { type: "App" },
2089
- header: { type: "Header", title: "Welcome" },
2090
- content: { type: "Content", text: "Hello World" },
2091
- }
2092
-
2093
- // With autoCreateEntities - entities are created automatically
2094
41
  const store = createStore({
2095
42
  types,
2096
- entities: {}, // Can be empty!
2097
- autoCreateEntities: true,
43
+ entities: { counter: { type: "Counter", value: 0 } },
2098
44
  })
2099
- ```
2100
-
2101
- If you want to initialize an entity with specific data, you can use the `create()` event handler:
2102
-
2103
- ```javascript
2104
- const Header = {
2105
- create(entity) {
2106
- entity.title = "Welcome"
2107
- },
2108
- render(entity, api) {
2109
- return html`<header>${entity.title}</header>`
2110
- },
2111
- }
2112
- ```
2113
-
2114
- 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.
2115
-
2116
- **When to use `autoCreateEntities` in web apps:**
2117
-
2118
- - ✅ Single-page applications with singleton services
2119
- - ✅ Component-like entities (headers, footers, navigation)
2120
- - ✅ Rapid prototyping where structure matters more than initial state
2121
- - ✅ Apps where you want to focus on behavior, not boilerplate
2122
-
2123
- ---
2124
-
2125
- ## API Reference
2126
-
2127
- **`mount(store, renderFn, element)`**
2128
-
2129
- Connects a store to a `lit-html` template and renders it into a DOM element. It automatically handles re-rendering on state changes.
2130
-
2131
- **Parameters:**
2132
-
2133
- - `store` (required): An instance of `@inglorious/store`.
2134
- - `renderFn(api)` (required): A function that takes an `api` object and returns a `lit-html` `TemplateResult` or `null`.
2135
- - `element` (required): The `HTMLElement` or `DocumentFragment` to render the template into.
2136
-
2137
- **Returns:**
2138
-
2139
- - `() => void`: An `unsubscribe` function to stop listening to store updates and clean up.
2140
-
2141
- ### The `api` Object
2142
-
2143
- 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.
2144
-
2145
- **`api.render(id, typeName?, Type?)`**
2146
-
2147
- 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.
2148
-
2149
- ### Package Entry Points
2150
-
2151
- `@inglorious/web` keeps its root entry point intentionally small:
2152
-
2153
- ```javascript
2154
- import { mount, html, svg } from "@inglorious/web"
2155
- ```
2156
-
2157
- Import everything else from the package that owns it, or from an explicit `@inglorious/web` subpath:
2158
-
2159
- ```javascript
2160
- import { createStore } from "@inglorious/store"
2161
- import { handleAsync, handleRequest } from "@inglorious/store/async"
2162
- import { optimistic } from "@inglorious/store/optimistic"
2163
- import { compute, createSelector } from "@inglorious/store/select"
2164
- import { createDevtools } from "@inglorious/store/client/devtools"
2165
-
2166
- import { classMap } from "@inglorious/web/directives/class-map"
2167
- import { ref, createRef } from "@inglorious/web/directives/ref"
2168
- import { repeat } from "@inglorious/web/directives/repeat"
2169
- import { styleMap } from "@inglorious/web/directives/style-map"
2170
- import { unsafeHTML } from "@inglorious/web/directives/unsafe-html"
2171
- import { when } from "@inglorious/web/directives/when"
2172
- import { staticHtml, unsafeStatic } from "@inglorious/web/static"
2173
- import { render, trigger } from "@inglorious/web/test"
2174
-
2175
- import { Form } from "@inglorious/web/form"
2176
- import { Router, setRoutes } from "@inglorious/web/router"
2177
- import { createGeolocation } from "@inglorious/web/device/geolocation"
2178
- import { Compass } from "@inglorious/web/device/compass"
2179
- ```
2180
-
2181
- This keeps `lit-html` as an internal implementation detail while still giving applications stable, tree-shakeable import paths.
2182
-
2183
- ---
2184
-
2185
- ## Error Handling
2186
45
 
2187
- When an entity's `render()` method throws an error, it can crash your entire app since the whole tree re-renders.
2188
-
2189
- **Best practice:** Wrap your render logic in try-catch at the entity level:
2190
-
2191
- ```javascript
2192
- const MyType = {
2193
- render(entity, api) {
2194
- try {
2195
- // Your render logic
2196
- return html`<div>...</div>`
2197
- } catch (error) {
2198
- console.error("Render error:", error)
2199
- return html`<div class="error">Failed to render ${entity.id}</div>`
2200
- }
2201
- },
2202
- }
46
+ mount(store, (api) => api.render("counter"), document.getElementById("root"))
2203
47
  ```
2204
48
 
2205
- ---
2206
-
2207
- ## Performance Tips
2208
-
2209
- 1. **Keep render() pure** - No side effects, no API calls
2210
- 2. **Avoid creating new objects in render** - Use entity properties, not inline `{}`
2211
- 3. **Use `repeat()` directive for lists** - Helps lit-html track item identity
2212
- 4. **Profile with browser DevTools** - Look for slow renders (>16ms)
2213
- 5. **Consider virtualization** - Use [Inglorious UI](https://inglorious.dev/ui) for 1000+ items
2214
-
2215
- If renders are slow:
2216
-
2217
- - Move expensive computations to event handlers
2218
- - Cache derived values on the entity
2219
- - ...Or memoize them!
2220
-
2221
- ---
2222
-
2223
- ## Relationship to Inglorious Engine
2224
-
2225
- `@inglorious/web` shares its architectural philosophy with [Inglorious Engine](https://www.npmjs.com/package/@inglorious/engine):
2226
-
2227
- - **Same state management** - Both use `@inglorious/store`
2228
- - **Same event system** - Entity behaviors respond to events
2229
- - **Same rendering model** - Full-state render on every update
2230
-
2231
- The key difference:
2232
-
2233
- - **@inglorious/engine** targets game loops (60fps, Canvas/WebGL rendering)
2234
- - **@inglorious/web** targets web UIs (DOM rendering, user interactions)
2235
-
2236
- 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`.
2237
50
 
2238
- ---
51
+ ## What's in it
2239
52
 
2240
- ## 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.
2241
61
 
2242
- 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).
2243
-
2244
- SSX is built entirely on **@inglorious/web** and lets you use the same entity-based patterns for both interactive apps and static sites, with:
2245
-
2246
- - Pre-rendered HTML at build time
2247
- - Automatic code splitting and lazy loading
2248
- - Client-side hydration with lit-html
2249
- - File-based routing
2250
- - Sitemap and RSS feed generation
2251
- - Incremental builds
2252
-
2253
- It's the perfect companion to @inglorious/web for building blazing-fast static sites, blogs, documentation, and marketing pages.
2254
-
2255
- ---
2256
-
2257
- ## Examples
2258
-
2259
- Check out these demos to see `@inglorious/web` in action:
2260
-
2261
- - **[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.
2262
- - **[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).
2263
- - **[Web Form](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/web-form)** - Form handling with validation, arrays, and field helpers.
2264
- - **[Web Router](https://github.com/IngloriousCoderz/inglorious-forge/tree/main/examples/apps/web-router)** - Entity-based client-side routing with hash navigation.
2265
-
2266
- ---
2267
-
2268
- ## Related Packages
2269
-
2270
- - [**@inglorious/ssx**](https://www.npmjs.com/package/@inglorious/ssx) - Static site generation with pre-rendering and client hydration
2271
- - [**@inglorious/store**](https://www.npmjs.com/package/@inglorious/store) - Entity-based state management (used by @inglorious/web)
2272
- - [**@inglorious/i18n**](https://www.npmjs.com/package/@inglorious/i18n) - Internationalization: translations, plurals and formatting driven by a store entity
2273
- - [**@inglorious/engine**](https://www.npmjs.com/package/@inglorious/engine) - Game engine with the same entity architecture
2274
- - [**@inglorious/create-app**](https://www.npmjs.com/package/@inglorious/create-app) - Scaffolding tool for quick project setup
2275
-
2276
- ---
62
+ UI components live in [Inglorious UI](https://inglorious.dev/ui).
2277
63
 
2278
64
  ## License
2279
65
 
2280
- **MIT License - Free and open source**
2281
-
2282
- Created by [Matteo Antony Mistretta](https://github.com/IngloriousCoderz)
2283
-
2284
- You're free to use, modify, and distribute this software. See [LICENSE](./LICENSE) for details.
2285
-
2286
- ---
2287
-
2288
- ## Contributing
2289
-
2290
- Contributions welcome! Please read our [Contributing Guidelines](../../CONTRIBUTING.md) first.
66
+ MIT © [Matteo Antony Mistretta](https://github.com/IngloriousCoderz)