@aegis-framework/pandora 0.4.2 → 0.6.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,1064 +1,1699 @@
1
1
  # Pandora
2
2
 
3
- Pandora is a lightweight Web Components library that allows you to create simple and reusable custom HTML elements with reactive state management, lifecycle hooks, and Shadow DOM support. It includes built-in [lit-html](https://lit.dev/docs/libraries/standalone-templates/) integration for efficient DOM updates.
3
+ Pandora is a lightweight web components library with a decorator-first API, automatic rendering via microtask batching, and built-in [lit-html](https://lit.dev/docs/libraries/standalone-templates/) integration for efficient DOM updates.
4
4
 
5
- ## Installation
6
-
7
- ```bash
8
- # Using npm
9
- npm install @aegis-framework/pandora
10
-
11
- # Using yarn
12
- yarn add @aegis-framework/pandora
13
-
14
- # Using bun
15
- bun add @aegis-framework/pandora
16
- ```
5
+ **This is a breaking API redesign from pre-0.6 versions.** The state/props bags, `setState()`, `setProps()`, and most lifecycle hooks have been removed in favor of decorator-driven reactivity. See the [Migration Guide](#migration-guide) for a complete mapping of old APIs to new ones.
17
6
 
18
- ## Quick Start
7
+ ```typescript
8
+ import { Component, Register, State, Listen, html } from '@aegis-framework/pandora';
19
9
 
20
- ### Basic Component (String Templates)
10
+ @Register('my-counter')
11
+ class MyCounter extends Component {
12
+ @State() count = 0;
21
13
 
22
- ```javascript
23
- import { Component } from '@aegis-framework/pandora';
24
-
25
- class CustomElement extends Component {
26
- constructor() {
27
- super();
28
- this.props = {
29
- text: ''
30
- };
14
+ @Listen('click')
15
+ increment() {
16
+ this.count++; // auto-renders
31
17
  }
32
18
 
33
19
  render() {
34
- return `<h2>${this.props.text}</h2>`;
20
+ return html`<button>Count: ${this.count}</button>`;
35
21
  }
36
22
  }
23
+ ```
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ # npm
29
+ npm install @aegis-framework/pandora
37
30
 
38
- console.log(CustomElement.tag); // 'custom-element'
31
+ # yarn
32
+ yarn add @aegis-framework/pandora
39
33
 
40
- // Register the custom element
41
- window.customElements.define(CustomElement.tag, CustomElement);
34
+ # bun
35
+ bun add @aegis-framework/pandora
42
36
  ```
43
37
 
44
- ### Basic Component (lit-html Templates)
38
+ ## Quick Start
45
39
 
46
- For better performance with frequent updates, use lit-html's tagged templates:
40
+ The simplest component you can build: a prop that auto-renders on change.
47
41
 
48
- ```javascript
49
- import { Component, html } from '@aegis-framework/pandora';
42
+ ```typescript
43
+ import { Component, Register, Attribute, html } from '@aegis-framework/pandora';
50
44
 
51
- class CustomElement extends Component {
52
- constructor() {
53
- super();
54
- this.props = { text: '' };
55
- }
45
+ @Register('my-greeting')
46
+ class MyGreeting extends Component {
47
+ @Attribute() name = 'World';
56
48
 
57
49
  render() {
58
- return html`<h2>${this.props.text}</h2>`;
50
+ return html`<h1>Hello, ${this.name}!</h1>`;
59
51
  }
60
52
  }
61
53
  ```
62
54
 
63
- Using it in the HTML:
64
-
65
55
  ```html
66
- <custom-element text="Hello World!"></custom-element>
56
+ <my-greeting name="Alice"></my-greeting>
67
57
  ```
68
58
 
69
- ### TypeScript Support
70
-
71
- Pandora supports generic types for props and state:
59
+ That's all you need. No constructor, no `forceRender()`, no lifecycle boilerplate. When `name` changes -- whether from an attribute update or a direct property assignment -- the component re-renders automatically.
72
60
 
73
- ```typescript
74
- import { Component, html } from '@aegis-framework/pandora';
61
+ ## Decorators Reference
75
62
 
76
- interface MyProps {
77
- name: string;
78
- count: number;
79
- }
63
+ Pandora uses [TC39 Stage 3 decorators](https://github.com/tc39/proposal-decorators), supported in TypeScript 5.0+ and modern build tools (Vite, esbuild, Bun). For environments without decorator support, see [Non-Decorator Usage](#non-decorator-usage).
80
64
 
81
- interface MyState {
82
- active: boolean;
83
- }
65
+ ### @Register(tagName)
84
66
 
85
- class TypedComponent extends Component<MyProps, MyState> {
86
- constructor() {
87
- super();
88
- this.props = {
89
- name: '',
90
- count: 0
91
- };
92
- this.state = {
93
- active: false
94
- };
95
- }
67
+ Class decorator. Registers the component with the custom elements registry under the given tag name. Same thing as calling `Registry.register(tagName, MyClass)` by hand.
96
68
 
69
+ ```typescript
70
+ @Register('my-button')
71
+ class MyButton extends Component {
97
72
  render() {
98
- return html`
99
- <div class="${this.state.active ? 'active' : ''}">
100
- <h2>${this.props.name}</h2>
101
- <span>Count: ${this.props.count}</span>
102
- </div>
103
- `;
73
+ return html`<button>${this.slotContent}</button>`;
104
74
  }
105
75
  }
106
76
  ```
107
77
 
108
- ### Using Decorators
78
+ ### @State(options?)
109
79
 
110
- Pandora provides decorators for cleaner component registration and state binding:
80
+ Field decorator. Declares a reactive instance field. Any assignment queues a re-render on the next microtask, and multiple changes within the same synchronous block coalesce into a single render.
111
81
 
112
82
  ```typescript
113
- import { Component, Register, Consumer, Prop, html } from '@aegis-framework/pandora';
114
-
115
- @Register('my-counter')
116
- class MyCounter extends Component {
117
- @Prop()
118
- initialCount: number = 0;
119
-
120
- @Consumer('app.theme')
121
- theme!: string;
122
-
123
- state = { count: 0 };
83
+ @Register('my-toggle')
84
+ class MyToggle extends Component {
85
+ @State() open = false;
124
86
 
125
87
  render() {
126
88
  return html`
127
- <div class="theme-${this.theme}">
128
- Count: ${this.state.count}
129
- </div>
89
+ <button @click=${() => { this.open = !this.open; }}>Toggle</button>
90
+ ${this.open ? html`<div class="panel">Content</div>` : nothing}
130
91
  `;
131
92
  }
132
93
  }
133
94
  ```
134
95
 
135
- ## Components
96
+ **Options:**
136
97
 
137
- ### Component
98
+ | Option | Type | Default | Description |
99
+ |--------|------|---------|-------------|
100
+ | `render` | `boolean` | `true` | Whether changes queue a re-render |
138
101
 
139
- The base class for creating custom elements.
102
+ **`@State({ render: false })`** keeps the field reactive (`@Watch` callbacks and `didChange` still fire) but skips the render queue. Reach for it when a field updates at high frequency, or when you'd rather handle DOM updates imperatively via `@Watch`:
140
103
 
141
- ```javascript
142
- class MyComponent extends Component {
143
- constructor() {
144
- super();
145
-
146
- // Define props with default values
147
- this.props = {
148
- title: '',
149
- visible: true
150
- };
151
-
152
- // Define internal state
153
- this.state = {
154
- count: 0
155
- };
104
+ ```typescript
105
+ @Register('media-player')
106
+ class MediaPlayer extends Component {
107
+ @State() track = 'Song A';
108
+ @State({ render: false }) currentTime = 0; // updates 60x/sec
109
+
110
+ @Query('.time-display') timeDisplay!: HTMLSpanElement;
111
+
112
+ @Watch('currentTime')
113
+ onTimeUpdate(newVal: number) {
114
+ if (this.isReady) {
115
+ this.timeDisplay.textContent = `${newVal.toFixed(1)}s`;
116
+ }
156
117
  }
157
118
 
158
119
  render() {
159
- return `<div>${this.props.title}: ${this.state.count}</div>`;
120
+ return html`
121
+ <div>Now playing: ${this.track}</div>
122
+ <span class="time-display">0.0s</span>
123
+ `;
160
124
  }
161
125
  }
162
126
  ```
163
127
 
164
- ### ShadowComponent
128
+ When to use `render: false`:
165
129
 
166
- A component that uses Shadow DOM for style encapsulation. ShadowComponent uses [Constructable Stylesheets](https://web.dev/constructable-stylesheets/) for high-performance styling - styles are shared across all instances of the same component class and updates use `replaceSync()` for fast synchronous changes.
130
+ - The field updates at animation-frame frequency (media time, scroll position, WebGL uniforms)
131
+ - The render function is expensive and you want surgical DOM updates instead
132
+ - You need to call imperative third-party APIs (canvas, WebGL, widget libraries)
167
133
 
168
- ```javascript
169
- import { ShadowComponent, html } from '@aegis-framework/pandora';
134
+ Most of the time the default auto-render is what you want -- lit-html's DOM diffing means only changed bindings update, not the whole tree. Reach for `render: false` when profiling shows a real bottleneck, not before.
170
135
 
171
- class MyShadowComponent extends ShadowComponent {
172
- constructor() {
173
- super();
174
- this.props = { text: '' };
175
- }
136
+ ### @Property(options?)
176
137
 
177
- willMount() {
178
- // Set scoped styles
179
- this.setStyle({
180
- ':host': { display: 'block' },
181
- h2: { color: 'blue' }
182
- });
138
+ Field decorator. Declares a reactive field that **never triggers a render**. Designed for **container components** -- ones whose children are defined in HTML or managed from outside. `@Watch` callbacks and `didChange()` still fire; `_queueRender()` never does.
183
139
 
184
- return Promise.resolve();
140
+ ```typescript
141
+ @Register('game-screen')
142
+ class GameScreen extends Component {
143
+ @Property() open = false;
144
+
145
+ @Watch('open')
146
+ onOpenChange() {
147
+ this.classList.toggle('active', this.open);
185
148
  }
186
149
 
187
- render() {
188
- // Can use string templates or lit-html
189
- return html`<h2>${this.props.text}</h2>`;
150
+ render(): void {
151
+ // void = preserve HTML children
190
152
  }
191
153
  }
192
154
  ```
193
155
 
194
- ## API Reference
156
+ **Options:**
195
157
 
196
- ### Static Properties
158
+ | Option | Type | Default | Description |
159
+ |--------|------|---------|-------------|
160
+ | `attribute` | `string \| false` | `false` | Attribute name to sync, or `false` for property-only |
161
+ | `equals` | `(a, b) => boolean` | `===` | Custom equality check |
197
162
 
198
- | Property | Type | Description |
199
- |----------|------|-------------|
200
- | `tag` | `string` | The custom element tag name (auto-generated from class name or manually set) |
201
- | `observedAttributes` | `string[]` | Attributes to observe for changes |
163
+ **When to use @Property vs @State:**
202
164
 
203
- ### Instance Properties
165
+ | Scenario | Decorator | Why |
166
+ |----------|-----------|-----|
167
+ | Leaf component with rendered content | `@State()` | Needs auto-render |
168
+ | Container with HTML children | `@Property()` | Re-render would destroy children |
169
+ | High-frequency value (animation, scroll) | `@State({ render: false })` | Same behavior, but field lives on a rendering component |
170
+ | Property set from outside that shouldn't re-render | `@Property()` | Intent is clear |
204
171
 
205
- | Property | Type | Description |
206
- |----------|------|-------------|
207
- | `props` | `object` | Component properties (read via proxy) |
208
- | `state` | `object` | Internal component state |
209
- | `dom` | `HTMLElement` | Reference to the component's DOM |
210
- | `slotContent` | `string` | Original innerHTML content before rendering (for content projection) |
211
- | `width` | `number` | Computed width in pixels |
212
- | `height` | `number` | Computed height in pixels |
213
- | `isConnected` | `boolean` | Whether the component is connected to the DOM |
214
- | `isReady` | `boolean` | Whether the component has completed its initial mount |
172
+ `@Property()` is functionally equivalent to `@State({ render: false })`, but the intent is clearer at a glance: this component doesn't re-render, its children are its content.
215
173
 
216
- ### Methods
174
+ ### @Attribute(attributeNameOrOptions?)
217
175
 
218
- #### State & Props
176
+ Field decorator. Declares a property that syncs with a DOM attribute. `@Attribute` registers the attribute as observed for you -- no need to set `static observedAttributes` by hand. Assignments sync back to the DOM attribute, and external attribute changes sync back to the property. Either direction queues a re-render.
219
177
 
220
- ```javascript
221
- // Update props (triggers update cycle)
222
- element.setProps({ title: 'New Title' });
178
+ **String shorthand** -- custom attribute name:
223
179
 
224
- // Update state (triggers update cycle)
225
- element.setState({ count: 5 });
180
+ ```typescript
181
+ @Register('my-input')
182
+ class MyInput extends Component {
183
+ @Attribute() placeholder = '';
184
+ @Attribute('max-length') maxLength = 100; // maps to attribute "max-length"
185
+ @Attribute() disabled = false;
226
186
 
227
- // Set component styles
228
- element.setStyle({
229
- h2: { color: 'red', fontSize: '24px' }
230
- });
187
+ render() {
188
+ return html`
189
+ <input
190
+ placeholder=${this.placeholder}
191
+ maxlength=${this.maxLength}
192
+ ?disabled=${this.disabled}
193
+ >
194
+ `;
195
+ }
196
+ }
231
197
  ```
232
198
 
233
- #### Event Helpers
234
-
235
- ```javascript
236
- // Add event listener (chainable)
237
- element.on('click', (e) => console.log('Clicked!'));
238
-
239
- // Add one-time event listener (auto-removes after first trigger)
240
- element.once('click', (e) => console.log('Only fires once!'));
199
+ ```html
200
+ <my-input placeholder="Enter text" max-length="50" disabled></my-input>
201
+ ```
241
202
 
242
- // Remove event listener (chainable)
243
- element.off('click', handler);
203
+ Attribute values are coerced for you: `''` and `'true'` become `true`, `'false'` becomes `false`, numeric strings become numbers, and everything else stays a string.
244
204
 
245
- // Emit custom event
246
- element.emit('custom-event', { data: 'value' });
247
- ```
205
+ **Property-only mode** -- use `@Property()`:
248
206
 
249
- #### Query Helpers
207
+ For inputs that hold complex values (objects, arrays, functions), use `@Property()` instead of `@Attribute()`. The field stays reactive but skips attribute sync entirely. See [Attribute Value Types](#attribute-value-types) for when to reach for each.
250
208
 
251
- ```javascript
252
- // Query single element within component
253
- const button = element.query('button');
209
+ ```typescript
210
+ @Register('data-table')
211
+ class DataTable extends Component {
212
+ @Attribute() title = '';
213
+ @Property() columns: string[] = [];
214
+ @Property() rows: Record<string, unknown>[] = [];
215
+ @Property() onRowClick?: (row: Record<string, unknown>) => void;
254
216
 
255
- // Query all matching elements
256
- const items = element.queryAll('.item');
217
+ render() {
218
+ return html`
219
+ <h2>${this.title}</h2>
220
+ <table>
221
+ <thead><tr>${this.columns.map(c => html`<th>${c}</th>`)}</tr></thead>
222
+ <tbody>
223
+ ${this.rows.map(row => html`
224
+ <tr @click=${() => this.onRowClick?.(row)}>
225
+ ${this.columns.map(c => html`<td>${row[c]}</td>`)}
226
+ </tr>
227
+ `)}
228
+ </tbody>
229
+ </table>
230
+ `;
231
+ }
232
+ }
257
233
  ```
258
234
 
259
- #### Rendering
260
-
261
235
  ```javascript
262
- // Force re-render
263
- await element.forceRender();
264
-
265
- // Register ready callback
266
- element.ready(() => {
267
- console.log('Component is ready!');
268
- });
236
+ const table = document.querySelector('data-table');
237
+ table.columns = ['name', 'email'];
238
+ table.rows = [{ name: 'Alice', email: 'alice@example.com' }];
239
+ table.onRowClick = (row) => console.log('Clicked:', row);
269
240
  ```
270
241
 
271
- > **Note:** The `render()` method supports both sync and async returns. You can return a value directly, use `async/await`, or return a Promise. The component will automatically await Promises before updating the DOM.
272
-
273
- ### Lifecycle Hooks
274
-
275
- Override these methods to hook into the component lifecycle:
276
-
277
- #### Mount Cycle
278
-
279
- - `willMount()` - Called before the component is rendered
280
- - `didMount()` - Called after the component is rendered
281
-
282
- #### Update Cycle
283
-
284
- - `willUpdate(origin, property, oldValue, newValue, oldObject, newObject)` - Called before an update
285
- - `update(origin, property, oldValue, newValue, oldObject, newObject)` - Called during an update
286
- - `didUpdate(origin, property, oldValue, newValue, oldObject, newObject)` - Called after an update
287
- - `onStateUpdate(property, oldValue, newValue, oldObject, newObject)` - Called when state changes
288
- - `onPropsUpdate(property, oldValue, newValue, oldObject, newObject)` - Called when props change
289
-
290
- The `origin` parameter can be `'props'`, `'state'`, or `'attribute'` depending on what triggered the update.
291
-
292
- #### Unmount Cycle
242
+ ### @Watch(property)
293
243
 
294
- - `willUnmount()` - Called before the component is removed
295
- - `unmount()` - Called when the component is being removed
296
- - `didUnmount()` - Called after the component is removed
244
+ Method decorator. Runs the decorated method synchronously when a `@State` or `@Attribute` field changes, before the queued render. The method receives `(newValue, oldValue)`.
297
245
 
298
- ```javascript
299
- class MyComponent extends Component {
300
- willMount() {
301
- console.log('About to mount');
302
- return Promise.resolve();
303
- }
304
-
305
- didMount() {
306
- console.log('Mounted!');
307
- return Promise.resolve();
246
+ ```typescript
247
+ @Register('search-box')
248
+ class SearchBox extends Component {
249
+ @Attribute() query = '';
250
+
251
+ @Watch('query')
252
+ onQueryChange(newVal: string, oldVal: string) {
253
+ console.log(`Query changed: "${oldVal}" -> "${newVal}"`);
254
+ this.fetchResults(newVal);
308
255
  }
309
256
 
310
- onPropsUpdate(property, oldValue, newValue) {
311
- console.log(`Prop ${property} changed from ${oldValue} to ${newValue}`);
312
- return Promise.resolve();
257
+ render() {
258
+ return html`<input .value=${this.query}>`;
313
259
  }
314
260
  }
315
261
  ```
316
262
 
317
- ### Observed Attributes
318
-
319
- To react to HTML attribute changes, define which attributes to observe:
263
+ Watch callbacks fire synchronously inside the setter, before the microtask render. Any state you modify from a watcher gets batched into the same render.
320
264
 
321
- ```javascript
322
- class MyComponent extends Component {
323
- static observedAttributes = ['title', 'count', 'disabled'];
265
+ Multiple methods can watch the same property, and one method can watch multiple properties by stacking decorators:
324
266
 
325
- attributeChangedCallback(name, oldValue, newValue) {
326
- // This is called automatically, which triggers the update cycle
327
- // You can also override onPropsUpdate to handle attribute changes
328
- }
267
+ ```typescript
268
+ @Watch('width')
269
+ @Watch('height')
270
+ onDimensionChange(newVal: number) {
271
+ this.recalculateLayout();
329
272
  }
330
273
  ```
331
274
 
332
- ## Templates
275
+ ### @Computed(...dependencies)
333
276
 
334
- You can use HTML templates instead of the render method:
277
+ Getter decorator. Caches the return value and only recalculates when one of its dependencies (`@State`, `@Attribute`, `@Property`) changes. List dependencies by property name.
335
278
 
336
- ```html
337
- <template id="my-component">
338
- <div class="wrapper">
339
- <!-- For light DOM components, use slotContent in render() instead -->
340
- <!-- For ShadowComponent, use native <slot> -->
341
- </div>
342
- </template>
343
- ```
279
+ ```typescript
280
+ @Register('task-list')
281
+ class TaskList extends Component {
282
+ @State() tasks: Array<{ text: string; done: boolean }> = [];
283
+ @State() filter: 'all' | 'active' | 'done' = 'all';
284
+
285
+ @Computed('tasks', 'filter')
286
+ get filteredTasks() {
287
+ if (this.filter === 'all') return this.tasks;
288
+ return this.tasks.filter(t => this.filter === 'done' ? t.done : !t.done);
289
+ }
344
290
 
345
- Or set templates programmatically:
291
+ @Computed('tasks')
292
+ get completedCount() {
293
+ return this.tasks.filter(t => t.done).length;
294
+ }
346
295
 
347
- ```javascript
348
- // String template
349
- MyComponent.template(`
350
- <div class="wrapper">
351
- <h2>{{title}}</h2>
352
- </div>
353
- `);
354
-
355
- // Function returning string
356
- MyComponent.template((context) => `
357
- <div class="wrapper">
358
- <h2>${context.props.title}</h2>
359
- </div>
360
- `);
361
-
362
- // Function returning lit-html (recommended for dynamic content)
363
- import { html } from '@aegis-framework/pandora';
364
-
365
- MyComponent.template((context) => html`
366
- <div class="wrapper">
367
- <h2>${context.props.title}</h2>
368
- <button @click=${() => context.handleClick()}>Click me</button>
369
- </div>
370
- `);
371
-
372
- // Async function (for data fetching)
373
- MyComponent.template(async (context) => {
374
- const data = await fetchData(context.props.id);
375
- return html`<div>${data.content}</div>`;
376
- });
296
+ render() {
297
+ return html`
298
+ <p>${this.completedCount}/${this.tasks.length} done</p>
299
+ ${this.filteredTasks.map(t => html`<div>${t.text}</div>`)}
300
+ `;
301
+ }
302
+ }
377
303
  ```
378
304
 
379
- ## lit-html Integration
380
-
381
- Pandora includes [lit-html](https://lit.dev/docs/libraries/standalone-templates/) and re-exports its utilities for convenience. You don't need to install lit-html separately.
382
-
383
- ### Exports
384
-
385
- ```javascript
386
- import {
387
- // Tagged template functions
388
- html, // For HTML templates
389
- svg, // For SVG templates
390
-
391
- // Special values
392
- nothing, // Render nothing
393
- noChange, // Skip updating a value
305
+ Without `@Computed`, the getters would re-evaluate on every access -- every render, every template binding. With `@Computed`, the value is cached after the first calculation and only recomputed when `tasks` or `filter` actually changes.
394
306
 
395
- // Manual rendering (rarely needed)
396
- render,
307
+ ### @Subscribe(stateKey)
397
308
 
398
- // Types (TypeScript)
399
- TemplateResult,
400
- SVGTemplateResult,
401
- RenderOptions
402
- } from '@aegis-framework/pandora';
403
- ```
309
+ Field decorator. Binds a property to a global Registry state key. The component subscribes on connect and unsubscribes on disconnect, all for you. When the global value changes, the property updates and a render is queued.
404
310
 
405
- ### String vs lit-html Templates
311
+ ```typescript
312
+ Registry.setState('app.theme', 'light');
406
313
 
407
- Both rendering modes work seamlessly. Use strings for simple components, lit-html for complex UIs:
314
+ @Register('themed-card')
315
+ class ThemedCard extends Component {
316
+ @Subscribe('app.theme') theme!: string;
408
317
 
409
- ```javascript
410
- // String template (simple, familiar)
411
- render() {
412
- return `<div>${this.props.name}</div>`;
318
+ render() {
319
+ return html`<div class="card theme-${this.theme}">...</div>`;
320
+ }
413
321
  }
414
322
 
415
- // lit-html template (efficient updates, event binding)
416
- render() {
417
- return html`
418
- <div>
419
- ${this.props.name}
420
- <button @click=${() => this.handleClick()}>Click</button>
421
- </div>
422
- `;
423
- }
323
+ // All ThemedCard instances re-render automatically
324
+ Registry.setState('app.theme', 'dark');
325
+ ```
424
326
 
425
- // Async render (fetch data before rendering)
426
- // Can use async/await OR return a Promise directly
427
- async render() {
428
- const data = await fetchUserData();
429
- return html`<div>Hello, ${data.name}!</div>`;
430
- }
327
+ Setting the property from inside the component also updates the global state, so every other consumer sees the change too.
431
328
 
432
- // Promise-based render (no async keyword needed)
433
- render() {
434
- return fetchUserData().then(data =>
435
- html`<div>Hello, ${data.name}!</div>`
436
- );
437
- }
438
- ```
329
+ ### @Query(selector) / @QueryAll(selector)
439
330
 
440
- ### lit-html Features
331
+ Field decorators. Give you lazy DOM references. Each access calls `query()` or `queryAll()` on the component (or the shadow root for `ShadowComponent`), so references are always current after a render.
441
332
 
442
- When using `html` templates, you get access to lit-html features:
333
+ ```typescript
334
+ @Register('my-form')
335
+ class MyForm extends Component {
336
+ @Query('.submit-btn') submitButton!: HTMLButtonElement;
337
+ @QueryAll('.field') fields!: NodeListOf<HTMLInputElement>;
443
338
 
444
- ```javascript
445
- import { html, nothing } from '@aegis-framework/pandora';
339
+ async didMount() {
340
+ this.submitButton.focus();
341
+ }
446
342
 
447
- class MyComponent extends Component {
448
343
  render() {
449
344
  return html`
450
- <!-- Conditional rendering -->
451
- ${this.state.show ? html`<div>Visible</div>` : nothing}
452
-
453
- <!-- List rendering -->
454
- <ul>
455
- ${this.state.items.map(item => html`<li>${item}</li>`)}
456
- </ul>
457
-
458
- <!-- Event binding -->
459
- <button @click=${(e) => this.handleClick(e)}>Click</button>
460
-
461
- <!-- Property binding -->
462
- <input .value=${this.state.name}>
463
-
464
- <!-- Boolean attributes -->
465
- <button ?disabled=${this.state.loading}>Submit</button>
345
+ <input class="field" name="email">
346
+ <input class="field" name="name">
347
+ <button class="submit-btn">Submit</button>
466
348
  `;
467
349
  }
468
350
  }
469
351
  ```
470
352
 
471
- ### Content Projection with slotContent
472
-
473
- Use the `slotContent` property to include the original innerHTML in your templates:
353
+ ### @Slot(name?)
474
354
 
475
- ```html
476
- <!-- Usage -->
477
- <my-card>
478
- <h3>Card Title</h3>
479
- <p>Card content goes here.</p>
480
- </my-card>
481
- ```
355
+ Field decorator for `ShadowComponent`. Gives you a lazy reference to a `<slot>` element inside the shadow root. Re-queried on every access, so the reference is always current.
482
356
 
483
- ```javascript
484
- class MyCard extends Component {
485
- render() {
486
- // String template
487
- return `
488
- <div class="card">
489
- <div class="card-body">
490
- ${this.slotContent}
491
- </div>
492
- </div>
493
- `;
357
+ ```typescript
358
+ @Register('card-layout')
359
+ class CardLayout extends ShadowComponent {
360
+ @Slot() defaultSlot!: HTMLSlotElement;
361
+ @Slot('header') headerSlot!: HTMLSlotElement;
362
+
363
+ async didMount() {
364
+ this.headerSlot?.addEventListener('slotchange', () => {
365
+ console.log('Header slot changed');
366
+ });
494
367
  }
495
- }
496
368
 
497
- // Or with lit-html
498
- class MyCard extends Component {
499
369
  render() {
500
370
  return html`
501
- <div class="card">
502
- <div class="card-body">
503
- ${this.slotContent}
504
- </div>
505
- </div>
371
+ <div class="header"><slot name="header"></slot></div>
372
+ <div class="body"><slot></slot></div>
506
373
  `;
507
374
  }
508
375
  }
509
376
  ```
510
377
 
511
- > **Note:** For ShadowComponent, use the native `<slot>` element instead of `slotContent` for proper Shadow DOM content projection.
378
+ `@Slot()` with no argument targets the default slot (`slot:not([name])`). `@Slot('name')` targets a named slot (`slot[name="name"]`). Returns `null` when no matching slot exists in the shadow root.
512
379
 
513
- ## Decorators
380
+ ### @Listen(event, options?)
514
381
 
515
- Pandora provides TypeScript/JavaScript decorators for cleaner component definitions.
382
+ Method decorator. Attaches an event listener on mount and removes it on unmount, automatically. The method is auto-bound to the instance. Saves you from wiring up `this.on(...)` in `didMount` and `this.off(...)` in `willUnmount` by hand.
516
383
 
517
- > **Note:** Decorators require TypeScript or a build tool (Babel, esbuild, etc.) that supports the decorator syntax. For plain browser JavaScript, use the functional form: `Register('my-tag')(MyClass)` instead of `@Register('my-tag')`.
518
-
519
- ### @Register(tagName)
384
+ ```typescript
385
+ @Register('modal-dialog')
386
+ class ModalDialog extends Component {
387
+ @Listen('click')
388
+ handleClick(e: MouseEvent) {
389
+ if ((e.target as Element).matches('.close-btn')) {
390
+ this.close();
391
+ }
392
+ }
520
393
 
521
- Automatically registers the component with the CustomElementsRegistry:
394
+ @Listen('resize', { target: 'window' })
395
+ handleResize() {
396
+ this.recalculatePosition();
397
+ }
522
398
 
523
- ```typescript
524
- import { Component, Register } from '@aegis-framework/pandora';
399
+ @Listen('keydown', { target: 'document', capture: true })
400
+ handleKeydown(e: KeyboardEvent) {
401
+ if (e.key === 'Escape') this.close();
402
+ }
525
403
 
526
- @Register('my-button')
527
- class MyButton extends Component {
528
- render() {
529
- return `<button>${this.slotContent}</button>`;
404
+ // Delegated: fires only when a descendant matching the selector is clicked
405
+ @Listen('click', { delegate: '[data-action="save"]' })
406
+ onSaveClick(e: Event) {
407
+ this.save();
530
408
  }
531
409
  }
532
-
533
- // No need for: Registry.register('my-button', MyButton);
534
410
  ```
535
411
 
536
- ### @Consumer(stateKey)
412
+ **Options:**
537
413
 
538
- Binds a class property to global Registry state. Automatically subscribes on connect and unsubscribes on disconnect:
414
+ | Option | Type | Default | Description |
415
+ |--------|------|---------|-------------|
416
+ | `target` | `'self' \| 'window' \| 'document' \| string` | `'self'` | Where to attach the listener. A CSS selector string queries within the component. |
417
+ | `delegate` | `string` | -- | CSS selector for event delegation. The handler only fires when `event.target.closest(delegate)` matches. |
418
+ | `capture` | `boolean` | `false` | Use capture phase |
419
+ | `passive` | `boolean` | `false` | Mark as passive |
420
+ | `once` | `boolean` | `false` | Remove after first fire |
539
421
 
540
- ```typescript
541
- import { Component, Register, Consumer, html } from '@aegis-framework/pandora';
542
- import { Registry } from '@aegis-framework/pandora';
422
+ **Event delegation:** With `delegate` set, the listener attaches to the component (or `target`), but the handler only fires when the event originates from a descendant matching the selector. This is the same delegation pattern you'd recognize from jQuery, Backbone, and most UI frameworks -- handy for dynamic children without re-attaching listeners every render.
543
423
 
544
- // Set initial state
545
- Registry.setState('user.theme', 'light');
546
- Registry.setState('user.name', 'Guest');
424
+ ### @Emitter(eventName)
547
425
 
548
- @Register('user-greeting')
549
- class UserGreeting extends Component {
550
- @Consumer('user.theme')
551
- theme!: string;
426
+ Field decorator. Creates a typed function that dispatches a `CustomEvent` with `bubbles: true`, `cancelable: true`, and `composed: true`. Returns the result of `dispatchEvent` -- `false` if a listener cancelled the event.
552
427
 
553
- @Consumer('user.name')
554
- name!: string;
428
+ ```typescript
429
+ @Register('file-input')
430
+ class FileInput extends Component {
431
+ @Emitter('file-select') emitFileSelect!: (detail: { file: File }) => boolean;
432
+ @Emitter('file-error') emitFileError!: (detail: { message: string }) => boolean;
433
+
434
+ handleChange(e: Event) {
435
+ const file = (e.target as HTMLInputElement).files?.[0];
436
+ if (file) {
437
+ this.emitFileSelect({ file });
438
+ } else {
439
+ this.emitFileError({ message: 'No file selected' });
440
+ }
441
+ }
555
442
 
556
443
  render() {
557
- return html`
558
- <div class="theme-${this.theme}">
559
- Hello, ${this.name}!
560
- </div>
561
- `;
444
+ return html`<input type="file" @change=${this.handleChange.bind(this)}>`;
562
445
  }
563
446
  }
564
-
565
- // Later, updating state automatically updates all @Consumer properties
566
- Registry.setState('user.name', 'Alice'); // All UserGreeting instances re-render
567
447
  ```
568
448
 
569
- ### @Prop(attributeName?)
570
-
571
- Declares a property that syncs with a DOM attribute:
449
+ ```javascript
450
+ // Parent listens with standard DOM events
451
+ document.querySelector('file-input').addEventListener('file-select', (e) => {
452
+ console.log(e.detail.file.name);
453
+ });
454
+ ```
572
455
 
573
- ```typescript
574
- import { Component, Register, Prop, html } from '@aegis-framework/pandora';
456
+ ### @Style(css)
575
457
 
576
- @Register('my-input')
577
- class MyInput extends Component {
578
- @Prop()
579
- placeholder: string = '';
458
+ Class decorator. Declaratively applies styles at component definition time. Accepts a CSS object or a raw CSS string. Styles go through Constructable Stylesheets, shared across every instance of the class, and are applied once on first mount.
580
459
 
581
- @Prop('max-length') // Custom attribute name
582
- maxLength: number = 100;
460
+ **Object form:**
583
461
 
584
- @Prop()
585
- disabled: boolean = false;
462
+ ```typescript
463
+ @Register('my-card')
464
+ @Style({
465
+ ':host': { display: 'block', padding: '16px' },
466
+ h3: { color: '#333', fontSize: '18px' },
467
+ '.body': { marginTop: '8px' }
468
+ })
469
+ class MyCard extends Component {
470
+ @Attribute() title = '';
586
471
 
587
472
  render() {
588
473
  return html`
589
- <input
590
- placeholder=${this.placeholder}
591
- maxlength=${this.maxLength}
592
- ?disabled=${this.disabled}
593
- >
474
+ <h3>${this.title}</h3>
475
+ <div class="body">${this.slotContent}</div>
594
476
  `;
595
477
  }
596
478
  }
597
479
  ```
598
480
 
599
- ```html
600
- <!-- Attributes sync with properties -->
601
- <my-input placeholder="Enter text" max-length="50" disabled></my-input>
481
+ **String form:**
482
+
483
+ ```typescript
484
+ @Register('my-card')
485
+ @Style(`
486
+ :host { display: block; }
487
+ h3 { color: #333; }
488
+ `)
489
+ class MyCard extends Component { /* ... */ }
602
490
  ```
603
491
 
604
- ## Registry
492
+ For `ShadowComponent`, `:host` and normal selectors are naturally scoped by Shadow DOM. For regular `Component`, selectors are prefixed with the component tag name for you.
605
493
 
606
- The Registry provides centralized component management:
494
+ ### @ClassList(map)
607
495
 
608
- ```javascript
609
- import { Registry, Component } from '@aegis-framework/pandora';
496
+ Class decorator. Toggles CSS classes on the host element based on reactive field values. Takes a map of class names to conditions, in one of two forms:
610
497
 
611
- // Register a component
612
- Registry.register('my-tag', MyComponent);
498
+ - **Property name string** -- the class tracks the truthiness of that field. Uses `@Watch` internally, so it only re-evaluates when that specific field changes.
499
+ - **Function condition** -- `(self) => boolean`, re-evaluated on every `didChange` (whenever any reactive field changes).
613
500
 
614
- // Check if a component is registered
615
- if (Registry.has('my-tag')) {
616
- console.log('Component is registered');
501
+ ```typescript
502
+ @Register('game-screen')
503
+ @ClassList({
504
+ active: 'open', // 'active' when this.open is truthy
505
+ 'mode-nvl': (self) => self.mode === 'nvl' // function condition
506
+ })
507
+ class GameScreen extends Component {
508
+ @Property() open = false;
509
+ @Property() mode = 'adv';
510
+
511
+ render(): void {}
617
512
  }
513
+ ```
618
514
 
619
- // Get the component class
620
- const MyComponentClass = Registry.get('my-tag');
621
-
622
- // Evolve an existing component (hot reload)
623
- Registry.evolve('my-tag', UpdatedComponent);
515
+ Initial classes are applied on `connectedCallback`, and subsequent updates react to field changes automatically. You can mix both forms in the same map.
624
516
 
625
- // Evolve and re-render all existing instances
626
- Registry.evolve('my-tag', UpdatedComponent, true);
517
+ ## Component API
627
518
 
628
- // Get all instances of a component
629
- const instances = Registry.instances('my-tag');
519
+ ### Status Getters
630
520
 
631
- // Execute callback on all instances
632
- Registry.instances('my-tag', (instance) => {
633
- instance.setProps({ updated: true });
634
- });
521
+ | Property | Type | Description |
522
+ |----------|------|-------------|
523
+ | `isConnected` | `boolean` | True when in the DOM |
524
+ | `isReady` | `boolean` | True after first render + `didMount` complete |
525
+ | `isFirstMount` | `boolean` | True until first mount completes |
526
+ | `slotContent` | `string` | Original `innerHTML` captured before first render |
635
527
 
636
- // Create new instance with props
637
- const element = Registry.instantiate('my-tag', { title: 'Hello' });
638
- ```
528
+ ### Rendering
639
529
 
640
- ### Registry Methods
530
+ | Method / Property | Signature | Description |
531
+ |-------------------|-----------|-------------|
532
+ | `render()` | `() => string \| TemplateResult \| void \| Promise<...>` | Override to provide template. `void` = preserve children. `''` = clear. |
533
+ | `forceRender()` | `() => Promise<void>` | Immediate render (escape hatch -- prefer reactive fields) |
534
+ | `batch(fn)` | `(() => void) => void` | Group state changes; `@Watch`/`didChange` deferred until batch completes, one render queued |
535
+ | `ready(callback)` | `(() => void) => void` | Call after component is mounted. Fires immediately (via microtask) if already mounted. |
536
+ | `static template` | `string \| ((self) => TemplateValue)` | External template; setting it auto-re-renders mounted instances |
641
537
 
642
- #### Component Management
538
+ ### Styles
643
539
 
644
- | Method | Description |
645
- |--------|-------------|
646
- | `register(tag, component)` | Register a new component with the custom elements registry |
647
- | `has(tag)` | Check if a component is registered |
648
- | `get(tag)` | Get the component class by tag name |
649
- | `evolve(tag, component, rerender?)` | Update an existing component's implementation (optionally re-render instances) |
650
- | `instances(tag, callback?)` | Get all instances or execute callback on each |
651
- | `instantiate(tag, props)` | Create a new instance with the given props |
540
+ | Method | Signature | Description |
541
+ |--------|-----------|-------------|
542
+ | `setStyle(style, reset?)` | `(Style \| string, boolean?) => Style` | Apply styles; `reset=true` replaces instead of merging |
652
543
 
653
- #### Debugging
544
+ ### Events
654
545
 
655
- | Method/Property | Description |
656
- |-----------------|-------------|
657
- | `debug` | Boolean property - enable/disable debug logging |
658
- | `log(message, data?)` | Log a debug message (only when debug is enabled) |
659
- | `list()` | Get array of all registered component tags |
660
- | `stats(tag?)` | Get stats for one or all components (instanceCount, isRegistered, isLazy) |
546
+ | Method | Signature | Description |
547
+ |--------|-----------|-------------|
548
+ | `on(event, callback, options?)` | Returns `this` | Add event listener (chainable) |
549
+ | `off(event, callback, options?)` | Returns `this` | Remove event listener (chainable) |
550
+ | `once(event, callback, options?)` | Returns `this` | One-time listener (chainable) |
551
+ | `emit(event, detail?, options?)` | Returns `boolean` | Dispatch `CustomEvent` (bubbles, composed, cancelable) |
661
552
 
662
- #### Global Lifecycle Hooks
553
+ ### DOM Helpers
663
554
 
664
- | Method | Description |
665
- |--------|-------------|
666
- | `onMount(callback)` | Register callback for when any component mounts (returns unsubscribe) |
667
- | `onUnmount(callback)` | Register callback for when any component unmounts (returns unsubscribe) |
555
+ | Method | Signature | Description |
556
+ |--------|-----------|-------------|
557
+ | `query<E>(selector)` | `(string) => E \| null` | `querySelector` within the component |
558
+ | `queryAll<E>(selector)` | `(string) => NodeListOf<E>` | `querySelectorAll` within the component |
668
559
 
669
- #### Error Handling
560
+ For `ShadowComponent`, `query` and `queryAll` search within the shadow root.
670
561
 
671
- | Method | Description |
672
- |--------|-------------|
673
- | `onError(callback)` | Register global error handler for component errors (returns unsubscribe) |
562
+ ### Registration
674
563
 
675
- #### Component Aliases
564
+ | Method / Property | Description |
565
+ |-------------------|-------------|
566
+ | `static register()` | Manual registration (equivalent to `@Register`) |
567
+ | `static tag` | Tag name (auto-derived from class name, or set by `@Register`) |
676
568
 
677
- | Method | Description |
678
- |--------|-------------|
679
- | `alias(aliasTag, originalTag)` | Create an alias tag name for an existing component |
680
- | `isAlias(tag)` | Check if a tag is an alias |
681
- | `getOriginalTag(aliasTag)` | Get the original tag name for an alias |
569
+ ## Lifecycle
682
570
 
683
- #### Lazy Loading
571
+ ```
572
+ Mount: willMount -> render -> didMount (first time) / didReconnect (subsequent)
573
+ Unmount: willUnmount -> didUnmount
574
+ Changes: @Watch callbacks -> didChange -> queued microtask render
575
+ ```
684
576
 
685
- | Method | Description |
686
- |--------|-------------|
687
- | `lazy(tag, loader)` | Register a component to be loaded on first use |
688
- | `isLazy(tag)` | Check if a component is registered as lazy |
689
- | `preload(tag)` | Preload a lazy component without mounting |
577
+ All lifecycle hooks are async. Override only the hooks you need.
690
578
 
691
- #### Middleware
579
+ | Hook | When it runs | Common use |
580
+ |------|-------------|------------|
581
+ | `willMount()` | Before every render on connect | Setup that must run before the DOM is ready |
582
+ | `didMount()` | After the first render only | One-time subscriptions, timers, third-party init |
583
+ | `didReconnect()` | After re-insertion (not first mount) | Refresh data, re-sync state |
584
+ | `willUnmount()` | Before removal | Save state, cancel pending requests |
585
+ | `didUnmount()` | After removal | Final cleanup |
692
586
 
693
- | Method | Description |
694
- |--------|-------------|
695
- | `use(type, middleware)` | Register middleware for 'props', 'state', or 'render' (returns unsubscribe) |
587
+ ### Lifecycle Events
696
588
 
697
- #### Global State
589
+ Components dispatch DOM events after mount completes and before teardown, which bubble up through the tree and cross shadow DOM boundaries (`bubbles: true, composed: true`). That lets outside code react to component lifecycle without subclassing.
698
590
 
699
- | Method | Description |
700
- |--------|-------------|
701
- | `setState(key, value)` | Set a global state value |
702
- | `getState(key)` | Get a global state value |
703
- | `hasState(key)` | Check if a state key exists |
704
- | `deleteState(key)` | Delete a state value |
705
- | `subscribe(key, callback)` | Subscribe to state changes (returns unsubscribe function) |
706
- | `unsubscribe(key, callback)` | Unsubscribe from state changes |
707
- | `getAllState()` | Get a copy of all global state |
708
- | `clearState()` | Clear all global state |
591
+ | Event | When | `event.detail` |
592
+ |-------|------|----------------|
593
+ | `pandora:ready` | After `didMount` completes (first mount) | `{ firstMount: boolean, tag: string }` |
594
+ | `pandora:unmount` | Before `willUnmount` runs | `{ tag: string }` |
709
595
 
710
- ## Global State
596
+ ```javascript
597
+ // Listen on an ancestor or the document
598
+ document.addEventListener('pandora:ready', (e) => {
599
+ console.log(`<${e.detail.tag}> is ready`);
600
+ });
711
601
 
712
- The Registry provides a simple global state system for sharing data between components:
602
+ document.addEventListener('pandora:unmount', (e) => {
603
+ console.log(`<${e.detail.tag}> is unmounting`);
604
+ });
605
+ ```
713
606
 
714
- ```javascript
715
- import { Registry } from '@aegis-framework/pandora';
607
+ In lit-html templates or HTML event binding:
716
608
 
717
- // Set global state
718
- Registry.setState('theme', 'dark');
719
- Registry.setState('user', { name: 'John', id: 123 });
609
+ ```html
610
+ <game-screen @pandora:ready="onScreenReady"></game-screen>
611
+ ```
720
612
 
721
- // Get global state
722
- const theme = Registry.getState('theme'); // 'dark'
723
- const user = Registry.getState('user'); // { name: 'John', id: 123 }
613
+ These events complement `Registry.onMount` / `Registry.onUnmount`. Reach for the DOM events when you want to listen to a specific subtree or respond from a parent component's template; reach for `Registry.onMount` when you need a global observer across every tag.
724
614
 
725
- // Check if state exists
726
- if (Registry.hasState('theme')) {
727
- console.log('Theme is set');
728
- }
615
+ ### didChange(property, oldValue, newValue, source?)
729
616
 
730
- // Subscribe to state changes
731
- const unsubscribe = Registry.subscribe('theme', (newValue, oldValue) => {
732
- console.log(`Theme changed from ${oldValue} to ${newValue}`);
733
- });
617
+ A generic change observer that fires whenever any `@State`, `@Attribute`, `@Property`, or `@Subscribe` field changes value. Override it when you want a single interception point across every reactive field, instead of writing individual `@Watch` methods.
734
618
 
735
- // Update state (triggers subscribers)
736
- Registry.setState('theme', 'light'); // Logs: "Theme changed from dark to light"
619
+ **Timing:** fires synchronously in the setter, after `@Watch` callbacks, before the queued render.
737
620
 
738
- // Unsubscribe when done
739
- unsubscribe();
621
+ **Source values:**
740
622
 
741
- // Delete state
742
- Registry.deleteState('theme');
623
+ | Source | Meaning |
624
+ |--------|---------|
625
+ | `'state'` | `@State` field setter |
626
+ | `'prop'` | `@Attribute` field setter (property assignment) |
627
+ | `'prop-attribute'` | `@Attribute` attribute change (external HTML attribute modification) |
628
+ | `'property'` | `@Property` field setter |
629
+ | `'consumer'` | `@Subscribe` global state update |
630
+ | `'reactive'` | `reactive()` primitive |
743
631
 
744
- // Get all state
745
- const allState = Registry.getAllState();
632
+ ```typescript
633
+ @Register('audit-form')
634
+ class AuditForm extends Component {
635
+ @State() name = '';
636
+ @State() email = '';
637
+ @Attribute() role = 'user';
638
+
639
+ didChange(property: string, oldValue: unknown, newValue: unknown, source?: string) {
640
+ console.log(`[${source}:${property}] ${oldValue} -> ${newValue}`);
641
+ analytics.track('field_change', { property, newValue, source });
642
+ }
746
643
 
747
- // Clear all state
748
- Registry.clearState();
644
+ render() {
645
+ return html`
646
+ <input .value=${this.name} @input=${(e: Event) => { this.name = (e.target as HTMLInputElement).value; }}>
647
+ <input .value=${this.email} @input=${(e: Event) => { this.email = (e.target as HTMLInputElement).value; }}>
648
+ `;
649
+ }
650
+ }
749
651
  ```
750
652
 
751
- ## Debugging
653
+ Reach for `didChange` when you want to observe every field change uniformly (logging, analytics, dirty tracking). Reach for `@Watch` when you need targeted reactions to specific fields.
752
654
 
753
- Enable debug mode to log component lifecycle events:
655
+ ### Lifecycle Example
754
656
 
755
- ```javascript
756
- import { Registry } from '@aegis-framework/pandora';
657
+ ```typescript
658
+ @Register('data-list')
659
+ class DataList extends Component {
660
+ @State() items: string[] = [];
661
+ private _pollInterval: number | undefined;
757
662
 
758
- // Enable debug logging
759
- Registry.debug = true;
663
+ async willMount() {
664
+ // Runs on every connect -- safe for synchronous setup
665
+ }
760
666
 
761
- // Manually log messages (only when debug is enabled)
762
- Registry.log('Custom debug message', { data: 'value' });
667
+ async didMount() {
668
+ // Runs once -- safe for subscriptions and timers
669
+ this._pollInterval = setInterval(() => this.refresh(), 5000);
670
+ await this.refresh();
671
+ }
763
672
 
764
- // List all registered components
765
- console.log(Registry.list()); // ['my-component', 'other-component']
673
+ async didReconnect() {
674
+ // Component was re-inserted (e.g., moved in the DOM)
675
+ await this.refresh();
676
+ }
766
677
 
767
- // Get stats for a specific component
768
- const stats = Registry.stats('my-component');
769
- // { tag: 'my-component', instanceCount: 3, isRegistered: true, isLazy: false }
678
+ async willUnmount() {
679
+ clearInterval(this._pollInterval);
680
+ }
770
681
 
771
- // Get stats for all components
772
- const allStats = Registry.stats();
773
- ```
682
+ async refresh() {
683
+ this.items = await fetchItems();
684
+ }
774
685
 
775
- ## Global Lifecycle Hooks
686
+ render() {
687
+ return html`<ul>${this.items.map(i => html`<li>${i}</li>`)}</ul>`;
688
+ }
689
+ }
690
+ ```
776
691
 
777
- Listen to mount/unmount events across all components:
692
+ ## Decorator Inheritance
778
693
 
779
- ```javascript
780
- import { Registry } from '@aegis-framework/pandora';
694
+ When you subclass a decorated component, it helps to know how decorators interact with inheritance:
781
695
 
782
- // Subscribe to all component mounts
783
- const unsubscribeMount = Registry.onMount((component, tag) => {
784
- console.log(`Component <${tag}> mounted`, component);
785
- });
696
+ ### @Watch and Method Overrides
786
697
 
787
- // Subscribe to all component unmounts
788
- const unsubscribeUnmount = Registry.onUnmount((component, tag) => {
789
- console.log(`Component <${tag}> unmounted`, component);
790
- });
698
+ `@Watch` metadata inherits from parent classes via `Symbol.metadata`. When a child overrides a watched method, what happens next depends on whether the child re-declares `@Watch`:
699
+
700
+ ```typescript
701
+ class ScreenComponent extends Component {
702
+ @Property() open = false;
703
+
704
+ @Watch('open')
705
+ onOpenChange() {
706
+ this.classList.toggle('active', this.open);
707
+ }
708
+ }
791
709
 
792
- // Clean up when done
793
- unsubscribeMount();
794
- unsubscribeUnmount();
710
+ // Case 1: Override method WITH @Watch — child's version runs (normal JS override)
711
+ class MainScreen extends ScreenComponent {
712
+ @Watch('open')
713
+ override onOpenChange() {
714
+ super.onOpenChange(); // call parent's logic
715
+ if (this.open) this.playAmbient();
716
+ }
717
+ }
718
+
719
+ // Case 2: Override method WITHOUT @Watch — parent's @Watch entry still
720
+ // points to 'onOpenChange', but the instance resolves to the child's
721
+ // override. Same result: child's version runs.
722
+ class GameScreen extends ScreenComponent {
723
+ override onOpenChange() {
724
+ super.onOpenChange();
725
+ if (this.open) this.startGame();
726
+ }
727
+ }
728
+
729
+ // Case 3: Add a NEW watcher with a DIFFERENT name — BOTH fire
730
+ class DialogScreen extends ScreenComponent {
731
+ @Watch('open')
732
+ onOpenAnimation() {
733
+ this.animate(); // fires in addition to parent's onOpenChange
734
+ }
735
+ }
795
736
  ```
796
737
 
797
- ## Error Handling
738
+ **Rules:**
798
739
 
799
- Register global error handlers to catch component errors:
740
+ 1. `@Watch` entries are stored in class metadata, which inherits via the prototype chain.
741
+ 2. `getWatchersForProperty` looks up methods by name on the **instance**. If the child overrides the method, the child's version runs (standard JavaScript).
742
+ 3. Adding a new `@Watch` with a **different method name** on the same property creates an additional watcher -- both the parent's and child's fire.
743
+ 4. `super.method()` works normally inside overridden watchers.
800
744
 
801
- ```javascript
802
- import { Registry } from '@aegis-framework/pandora';
745
+ ### @State and @Attribute Inheritance
803
746
 
804
- // Register a global error handler
805
- const unsubscribe = Registry.onError((error, component, tag, lifecycle) => {
806
- console.error(`Error in <${tag}> during ${lifecycle}:`, error);
807
- // Send to error tracking service, etc.
747
+ Decorated fields on parent classes are inherited. A child can add new decorated fields without touching the parent's:
748
+
749
+ ```typescript
750
+ class BaseComponent extends Component {
751
+ @State() loading = false;
752
+ }
753
+
754
+ class UserCard extends BaseComponent {
755
+ @State() name = ''; // adds a new field; loading is inherited
756
+ }
757
+ ```
758
+
759
+ To override a parent's field default, re-declare the field in the child:
760
+
761
+ ```typescript
762
+ class DarkCard extends BaseComponent {
763
+ @State() loading = true; // overrides default
764
+ }
765
+ ```
766
+
767
+ ## Render Timing and Batching
768
+
769
+ Knowing when renders actually happen saves surprises later. Here's the exact sequence when a reactive field changes:
770
+
771
+ ```
772
+ this.count = 5
773
+ |
774
+ +--> setter fires
775
+ | |
776
+ | +--> @Watch callbacks fire (synchronous)
777
+ | |
778
+ | +--> didChange() fires (synchronous)
779
+ | |
780
+ | +--> _queueRender() called -- sets a flag, schedules a microtask
781
+ |
782
+ this.name = 'Alice' <-- same synchronous block
783
+ |
784
+ +--> setter fires
785
+ | |
786
+ | +--> @Watch / didChange fire (synchronous)
787
+ | |
788
+ | +--> _queueRender() called -- flag already set, no-op
789
+ |
790
+ ... synchronous code finishes ...
791
+ |
792
+ +--> microtask fires: ONE render with count=5, name='Alice'
793
+ ```
794
+
795
+ Key points:
796
+
797
+ - **`@Watch` and `didChange` fire synchronously** in the setter, so you can read the new value right away and modify other state in response. Those follow-up modifications are batched into the same render.
798
+ - **Multiple synchronous changes produce exactly one render.** The first change schedules a microtask; later changes in the same synchronous block see the flag is already set and skip scheduling.
799
+ - **`forceRender()` bypasses batching.** It triggers an immediate render. Reach for it when you need the DOM updated before the next line of code runs (rare), or when you're updating plain non-decorated fields.
800
+ - **Renders are skipped while disconnected.** If the component isn't in the DOM (`isConnected` is `false`), `_queueRender()` is a no-op.
801
+ - **Renders are skipped during initialization.** Field defaults set during construction don't trigger a re-render -- only changes after the first mount cycle do.
802
+
803
+ ### render() Return Value Semantics
804
+
805
+ | Return value | Behavior |
806
+ |---|---|
807
+ | `void` / `undefined` | **No-op** -- preserve existing DOM. For container components whose HTML-defined children ARE the content. |
808
+ | `''` (empty string) | **Clear** -- explicitly empties the component's innerHTML. |
809
+ | `nothing` (lit-html) | **Clear** -- explicitly renders nothing via lit-html. |
810
+ | `'<div>...'` | **Render** -- string template applied to DOM. |
811
+ | `` html`...` `` | **Render** -- lit-html template diffed against DOM. |
812
+
813
+ The default `render()` returns `void`, so components that don't override it (container / structural components) keep their HTML-defined children intact. That matters for components like `<visual-novel>` or `<main-screen>`, where the children are set in HTML and managed from outside.
814
+
815
+ ### batch()
816
+
817
+ When you want to update multiple fields and only fire `@Watch` / `didChange` once per field, after every change lands:
818
+
819
+ ```typescript
820
+ this.batch(() => {
821
+ this.x = 1;
822
+ this.y = 2;
823
+ this.z = 3;
808
824
  });
825
+ // @Watch fires once per changed field, in order
826
+ // One render is queued for the entire batch
827
+ ```
828
+
829
+ Without `batch()`, each assignment fires `@Watch` / `didChange` synchronously -- the render is already batched by microtask, but the watchers fire three times. With `batch()`, watchers are deferred and run after every assignment is done.
830
+
831
+ ### Deferred Registration
832
+
833
+ For engines and frameworks that need to control exactly when `customElements.define()` runs:
834
+
835
+ ```typescript
836
+ @Register('game-screen', { defer: true })
837
+ class GameScreen extends Component {
838
+ // Class is set up but NOT registered with the browser
839
+ }
840
+
841
+ // Later, when ready:
842
+ Registry.define('game-screen', GameScreen);
843
+ ```
844
+
845
+ `{ defer: true }` sets the static `tag` property but skips both `customElements.define()` and Registry registration. Call `Registry.define(tag, ComponentClass)` once your setup is ready.
846
+
847
+ ## Plain Fields vs @State
848
+
849
+ Not every piece of instance data needs to be a `@State` field. Here's how to decide:
809
850
 
810
- // If no error handlers are registered, errors will be thrown normally
811
- // If handlers are registered, they receive the error instead of it being thrown
851
+ | Scenario | Use | Why |
852
+ |----------|-----|-----|
853
+ | Value is shown in the template | `@State() count = 0` | Changes must trigger a re-render |
854
+ | Value is internal bookkeeping (timer IDs, references) | `private _timer = 0` | No render needed -- plain field is simpler |
855
+ | Value updates at high frequency but drives targeted DOM updates | `@State({ render: false }) time = 0` | Reactive (fires `@Watch`) but skips the render queue |
856
+ | Value is passed in from a parent element | `@Attribute() label = ''` | Syncs with DOM attributes automatically |
857
+ | Value is passed in but is a complex object | `@Property() data = []` | Reactive but no attribute sync |
858
+
859
+ ```typescript
860
+ @Register('stopwatch-element')
861
+ class StopwatchElement extends Component {
862
+ @State() elapsed = 0; // shown in template
863
+ @State({ render: false }) isRunning = false; // drives @Watch, not template
864
+ private _intervalId: number | undefined; // internal bookkeeping
865
+
866
+ @Watch('isRunning')
867
+ onRunningChange(running: boolean) {
868
+ if (running) {
869
+ this._intervalId = setInterval(() => { this.elapsed++; }, 1000);
870
+ } else {
871
+ clearInterval(this._intervalId);
872
+ }
873
+ }
874
+
875
+ @Listen('click')
876
+ toggle() {
877
+ this.isRunning = !this.isRunning;
878
+ }
879
+
880
+ render() {
881
+ return html`<button>${this.elapsed}s -- ${this.isRunning ? 'Stop' : 'Start'}</button>`;
882
+ }
883
+ }
812
884
  ```
813
885
 
814
- ## Component Aliases
886
+ ## Attribute Value Types
887
+
888
+ `@Attribute()` syncs values with DOM attributes by default. That works well for strings, numbers, and booleans, which all serialize cleanly to attribute strings. Complex values -- arrays, objects, functions -- can't round-trip through attributes.
815
889
 
816
- Create alternative tag names for existing components:
890
+ | Value type | Decorator | Behavior |
891
+ |------------|-----------|----------|
892
+ | `string` | `@Attribute()` | Syncs to/from attribute as a string |
893
+ | `number` | `@Attribute()` | Syncs to/from attribute; numeric strings auto-coerced |
894
+ | `boolean` | `@Attribute()` | Present attribute = `true`, absent = `false` |
895
+ | `object` / `array` | `@Property()` | Property-only -- no attribute sync, no render |
896
+ | `function` | `@Property()` | Property-only -- no attribute sync, no render |
897
+
898
+ **Setting attribute-friendly props from HTML:**
899
+
900
+ ```html
901
+ <my-input placeholder="Type here" max-length="50" disabled></my-input>
902
+ ```
903
+
904
+ **Setting complex props from JavaScript:**
817
905
 
818
906
  ```javascript
819
- import { Registry } from '@aegis-framework/pandora';
907
+ const table = document.createElement('data-table');
908
+ table.title = 'Users'; // attribute-backed @Attribute
909
+ table.columns = ['name', 'email']; // property-only via @Property()
910
+ table.rows = [{ name: 'Alice' }]; // property-only
911
+ table.onRowClick = (row) => alert(row); // property-only
912
+ document.body.appendChild(table);
913
+ ```
820
914
 
821
- // Register the original component
822
- Registry.register('my-button', MyButton);
915
+ If you use `@Attribute()` (the default, attribute-backed one) with an object or array value, the property still works reactively, but the value won't reflect to a DOM attribute. Reach for `@Property()` instead -- the intent is clearer and there's nothing to be surprised by later.
823
916
 
824
- // Create aliases (must contain a hyphen, per custom elements spec)
825
- Registry.alias('app-button', 'my-button');
826
- Registry.alias('custom-button', 'my-button');
917
+ ## ShadowComponent
918
+
919
+ `ShadowComponent` extends `Component` with an open shadow root. The API is identical -- every decorator works the same way. The differences:
920
+
921
+ - `query()` and `queryAll()` search within the shadow root
922
+ - `setStyle()` adopts the stylesheet into the shadow root (scoped by Shadow DOM, not by tag prefix)
923
+ - Use native `<slot>` elements for content projection instead of `slotContent`
924
+ - `@Style` styles are naturally encapsulated
925
+
926
+ ```typescript
927
+ import { ShadowComponent, Register, Attribute, Style, html } from '@aegis-framework/pandora';
827
928
 
828
- // Check if a tag is an alias
829
- Registry.isAlias('app-button'); // true
830
- Registry.isAlias('my-button'); // false
929
+ @Register('fancy-button')
930
+ @Style({
931
+ ':host': { display: 'inline-block' },
932
+ 'button': { padding: '8px 16px', borderRadius: '4px' }
933
+ })
934
+ class FancyButton extends ShadowComponent {
935
+ @Attribute() variant = 'primary';
831
936
 
832
- // Get the original tag
833
- Registry.getOriginalTag('app-button'); // 'my-button'
937
+ render() {
938
+ return html`
939
+ <button class="btn-${this.variant}">
940
+ <slot></slot>
941
+ </button>
942
+ `;
943
+ }
944
+ }
834
945
  ```
835
946
 
836
947
  ```html
837
- <!-- All of these create the same component -->
838
- <my-button>Click me</my-button>
839
- <app-button>Click me</app-button>
840
- <custom-button>Click me</custom-button>
948
+ <fancy-button variant="secondary">Click me</fancy-button>
841
949
  ```
842
950
 
843
- ## Lazy Loading
951
+ Access the shadow root via `element.shadowRoot`.
844
952
 
845
- Load components on demand when they're first used:
953
+ ## Registry
846
954
 
847
- ```javascript
955
+ The Registry is Pandora's central hub for component management, global state, and cross-cutting concerns.
956
+
957
+ ### Component Management
958
+
959
+ ```typescript
848
960
  import { Registry } from '@aegis-framework/pandora';
849
961
 
850
- // Register a lazy component
851
- Registry.lazy('heavy-chart', () => import('./components/HeavyChart.js'));
962
+ // Register (usually handled by @Register decorator)
963
+ Registry.register('my-tag', MyComponent);
964
+
965
+ // Check / retrieve
966
+ Registry.has('my-tag') // boolean
967
+ Registry.get('my-tag') // ComponentClass | undefined
968
+ Registry.list() // string[] -- all registered tags
969
+
970
+ // Evolve: swap the implementation for a registered tag
971
+ // Useful for hot module replacement and plugin patterns
972
+ Registry.evolve('my-tag', UpdatedComponent) // swap, no re-render
973
+ Registry.evolve('my-tag', UpdatedComponent, true) // swap + re-render all instances
974
+ // Note: `observedAttributes` is captured by the browser at register() time and
975
+ // cannot be changed afterward. If the evolved class adds NEW @Attribute fields
976
+ // whose names weren't observed originally, DOM-driven changes to those new
977
+ // attributes won't fire attributeChangedCallback. Property access still works.
978
+
979
+ // Instances
980
+ Registry.instances('my-tag') // NodeListOf<Element>
981
+ Registry.instances('my-tag', (el) => { }) // iterate
982
+
983
+ // Programmatic instantiation
984
+ const el = Registry.instantiate('my-tag', { title: 'Hello' });
985
+ document.body.appendChild(el);
986
+
987
+ // Stats
988
+ Registry.stats('my-tag') // { tag, instanceCount, isRegistered, isLazy }
989
+ Registry.stats() // ComponentStats[] for all tags
990
+ ```
852
991
 
853
- // The component will be loaded when first used in the DOM
854
- // <heavy-chart></heavy-chart>
992
+ ### Lazy Loading
993
+
994
+ Register a component to be code-split and only loaded when it first appears in the DOM:
995
+
996
+ ```typescript
997
+ Registry.lazy('heavy-chart', () => import('./components/HeavyChart.js'));
855
998
 
856
- // Check if a component is lazy
857
- Registry.isLazy('heavy-chart'); // true (before loaded), false (after loaded)
999
+ // Check status
1000
+ Registry.isLazy('heavy-chart') // true before loaded
858
1001
 
859
- // Preload a lazy component (useful for anticipated navigation)
1002
+ // Preload eagerly (e.g., on route anticipation)
860
1003
  await Registry.preload('heavy-chart');
861
1004
  ```
862
1005
 
863
- ### Lazy Loading with Dynamic Imports
1006
+ ### Aliases
864
1007
 
865
- ```javascript
866
- // Components are loaded only when first mounted
867
- Registry.lazy('data-table', async () => {
868
- const module = await import('./components/DataTable.js');
869
- return module.default;
870
- });
1008
+ Create alternative tag names for an existing component:
1009
+
1010
+ ```typescript
1011
+ Registry.register('my-button', MyButton);
1012
+ Registry.alias('app-button', 'my-button');
1013
+ Registry.alias('ui-button', 'my-button');
871
1014
 
872
- Registry.lazy('chart-widget', () => import('./components/ChartWidget.js'));
1015
+ Registry.isAlias('app-button') // true
1016
+ Registry.getOriginalTag('app-button') // 'my-button'
873
1017
  ```
874
1018
 
875
- ## Middleware
1019
+ ```html
1020
+ <!-- All render the same component -->
1021
+ <my-button>Save</my-button>
1022
+ <app-button>Save</app-button>
1023
+ <ui-button>Save</ui-button>
1024
+ ```
876
1025
 
877
- Intercept and modify props, state, or render output across all components:
1026
+ ### Lifecycle Hooks
878
1027
 
879
- ```javascript
880
- import { Registry } from '@aegis-framework/pandora';
1028
+ Listen to mount and unmount events across all registered components:
881
1029
 
882
- // Props middleware - runs on every setProps call
883
- const unsubscribeProps = Registry.use('props', (component, props) => {
884
- // Validate or transform props
885
- return {
886
- ...props,
887
- timestamp: Date.now() // Add timestamp to all props
888
- };
1030
+ ```typescript
1031
+ const off = Registry.onMount((component, tag) => {
1032
+ console.log(`<${tag}> mounted`);
1033
+ });
1034
+
1035
+ const off2 = Registry.onUnmount((component, tag) => {
1036
+ console.log(`<${tag}> unmounted`);
889
1037
  });
890
1038
 
891
- // State middleware - runs on every setState call
892
- const unsubscribeState = Registry.use('state', (component, state) => {
893
- // Log state changes
894
- console.log(`State update in <${component.static.tag}>:`, state);
895
- return state;
1039
+ // Clean up
1040
+ off();
1041
+ off2();
1042
+ ```
1043
+
1044
+ ### Error Handling
1045
+
1046
+ Register a global error handler. Once it's in place, errors thrown from component lifecycle hooks flow through here instead of going uncaught:
1047
+
1048
+ ```typescript
1049
+ const off = Registry.onError((error, component, tag, lifecycle) => {
1050
+ console.error(`Error in <${tag}> during ${lifecycle}:`, error);
1051
+ reportToErrorTracker(error, { tag, lifecycle });
896
1052
  });
1053
+ ```
1054
+
1055
+ ### Middleware
897
1056
 
898
- // Render middleware - can modify rendered output
899
- // The third parameter `renderType` indicates if the template is 'string' or 'lit'
900
- const unsubscribeRender = Registry.use('render', (component, value, renderType) => {
1057
+ Intercept and transform render output across all components:
1058
+
1059
+ ```typescript
1060
+ // Render middleware -- receives (component, value, renderType)
1061
+ // renderType is 'string' for string templates, 'lit' for lit-html TemplateResults
1062
+ const off = Registry.use('render', (component, value, renderType) => {
901
1063
  if (renderType === 'string') {
902
- // String templates can be modified directly
903
- return value.replace('{{timestamp}}', Date.now());
1064
+ return value.replace(/{{version}}/g, '1.0.0');
904
1065
  }
905
- // lit-html TemplateResults should be returned as-is or wrapped
906
- return value;
1066
+ return value; // pass lit-html results through unchanged
907
1067
  });
908
1068
 
909
- // Clean up middleware
910
- unsubscribeProps();
911
- unsubscribeState();
912
- unsubscribeRender();
1069
+ // Remove middleware
1070
+ off();
913
1071
  ```
914
1072
 
915
- ### Example: Development Tools Middleware
1073
+ ### Debug Mode
916
1074
 
917
- ```javascript
918
- if (process.env.NODE_ENV === 'development') {
919
- // Log all state changes
920
- Registry.use('state', (component, state) => {
921
- console.log(`[${component.static.tag}] setState:`, state);
922
- return state;
923
- });
1075
+ ```typescript
1076
+ Registry.debug = true; // enables [Pandora] console logs for all lifecycle events
924
1077
 
925
- // Track render performance (type-aware)
926
- Registry.use('render', (component, value, renderType) => {
927
- if (renderType === 'string') {
928
- console.log(`[${component.static.tag}] rendered ${value.length} chars (string)`);
929
- } else {
930
- console.log(`[${component.static.tag}] rendered (lit-html)`);
931
- }
932
- return value;
933
- });
1078
+ Registry.log('custom message', { extra: 'data' }); // only logs when debug is true
1079
+ ```
1080
+
1081
+ ## Global State
1082
+
1083
+ The Registry ships a simple key-value state system for sharing data across components. Inside a component, the main way to consume global state is `@Subscribe`. The methods below are for setting and observing state from outside components.
1084
+
1085
+ ```typescript
1086
+ // Set / get
1087
+ Registry.setState('app.user', { name: 'Alice', id: 1 });
1088
+ Registry.getState('app.user') // { name: 'Alice', id: 1 }
1089
+ Registry.hasState('app.user') // true
1090
+
1091
+ // Subscribe
1092
+ const unsubscribe = Registry.subscribe('app.user', (newVal, oldVal) => {
1093
+ console.log('User changed:', newVal);
1094
+ });
1095
+
1096
+ Registry.setState('app.user', { name: 'Bob', id: 2 }); // fires subscriber
1097
+
1098
+ unsubscribe();
1099
+
1100
+ // Delete and clear
1101
+ Registry.deleteState('app.user') // notifies subscribers with undefined
1102
+ Registry.getAllState() // { 'app.user': ..., ... }
1103
+ Registry.clearState() // deletes all keys, notifies each subscriber
1104
+ ```
1105
+
1106
+ ### Using @Subscribe
1107
+
1108
+ ```typescript
1109
+ Registry.setState('app.locale', 'en');
1110
+
1111
+ @Register('date-display')
1112
+ class DateDisplay extends Component {
1113
+ @Subscribe('app.locale') locale!: string;
1114
+
1115
+ render() {
1116
+ return html`<time>${new Date().toLocaleDateString(this.locale)}</time>`;
1117
+ }
934
1118
  }
1119
+
1120
+ // All DateDisplay instances re-render automatically
1121
+ Registry.setState('app.locale', 'fr');
935
1122
  ```
936
1123
 
937
- ### Using Global State in Components
1124
+ ### Typed State
938
1125
 
939
- ```javascript
1126
+ `createState` wraps a Registry key with full TypeScript type safety. Reach for it when you want compile-time checking on `get`, `set`, and `subscribe` instead of untyped `Registry.setState` / `Registry.getState` calls.
1127
+
1128
+ ```typescript
1129
+ import { createState } from '@aegis-framework/pandora';
1130
+
1131
+ const theme = createState<'light' | 'dark'>('app.theme', 'light');
1132
+
1133
+ theme.get(); // returns 'light' | 'dark'
1134
+ theme.set('dark'); // type-checked -- 'midnight' would be a TS error
1135
+ theme.subscribe((val) => {
1136
+ document.documentElement.setAttribute('data-theme', val);
1137
+ });
1138
+ theme.has(); // boolean
1139
+ theme.delete(); // removes the key and notifies subscribers
1140
+ ```
1141
+
1142
+ The optional second argument to `createState` sets a default value when the key doesn't already exist in the Registry. The returned object is a plain value, not a decorator -- stash it in a module-level variable and import it wherever you need it.
1143
+
1144
+ `@Subscribe(key)` binds a component field to the same key:
1145
+
1146
+ ```typescript
1147
+ import { theme } from './state';
1148
+
1149
+ @Register('theme-toggle')
940
1150
  class ThemeToggle extends Component {
941
- constructor() {
942
- super();
943
- this.state = {
944
- theme: Registry.getState('theme') || 'light'
945
- };
1151
+ @Subscribe(theme.key) currentTheme!: 'light' | 'dark';
1152
+
1153
+ render() {
1154
+ return html`
1155
+ <button @click=${() => theme.set(this.currentTheme === 'light' ? 'dark' : 'light')}>
1156
+ ${this.currentTheme}
1157
+ </button>
1158
+ `;
946
1159
  }
1160
+ }
1161
+ ```
947
1162
 
948
- didMount() {
949
- // Subscribe to theme changes
950
- this._unsubscribe = Registry.subscribe('theme', (newTheme) => {
951
- this.setState({ theme: newTheme });
952
- this.forceRender();
1163
+ ## Extending Pandora
1164
+
1165
+ Pandora exposes its reactive primitives as a public API, so you can build your own decorators that plug into the render cycle, lifecycle, and hot-reload system alongside the built-ins. This is a stable, intentional extension surface -- not internal hacks you have to guard against.
1166
+
1167
+ ### Public Extension API
1168
+
1169
+ ```typescript
1170
+ import { reactive, addDecoratorEffect, addTeardown } from '@aegis-framework/pandora';
1171
+ ```
1172
+
1173
+ | Export | Purpose |
1174
+ |--------|---------|
1175
+ | `reactive(instance, propertyKey, options?)` | Make a field reactive: installs getter/setter, auto-renders on change, fires `onChange` callback |
1176
+ | `addDecoratorEffect(metadata, effectFn)` | Register a function to replay when `Registry.evolve()` or `Registry.lazy()` upgrades a live instance |
1177
+ | `addTeardown(instance, cleanupFn)` | Register a cleanup function that runs before decorator effects are replayed (unsubscribe, remove listeners, etc.) |
1178
+
1179
+ Additionally, the `Util` namespace export gives access to metadata symbols if you need to read or extend decorator metadata directly:
1180
+
1181
+ ```typescript
1182
+ import { Util } from '@aegis-framework/pandora';
1183
+
1184
+ // Available symbols:
1185
+ Util.PROP_ATTRIBUTES // string[] of observed attribute names
1186
+ Util.WATCH_HANDLERS // @Watch registrations: { property, methodName }[]
1187
+ Util.LISTEN_HANDLERS // @Listen registrations: { event, methodName, options }[]
1188
+ Util.STYLE_METADATA // @Style CSS data (object or string)
1189
+ Util.DECORATOR_EFFECTS // effect functions for evolve/lazy replay
1190
+ Util.DECORATOR_TEARDOWNS // cleanup functions on instances
1191
+ ```
1192
+
1193
+ ### reactive(instance, propertyKey, options?)
1194
+
1195
+ The core reactive primitive. Installs a getter/setter on `instance` backed by a Symbol-keyed storage slot. The setter skips no-op assignments, fires `onChange`, and calls `_queueRender()` on the instance for you.
1196
+
1197
+ ```typescript
1198
+ reactive(instance, propertyKey, options?);
1199
+ ```
1200
+
1201
+ **Options:**
1202
+
1203
+ | Option | Type | Default | Description |
1204
+ |--------|------|---------|-------------|
1205
+ | `initialValue` | `unknown` | `undefined` | Initial value for the field |
1206
+ | `render` | `boolean` | `true` | Whether changes call `_queueRender()` automatically |
1207
+ | `onChange` | `(newValue, oldValue) => void` | -- | Callback fired on every change, before render is queued |
1208
+ | `equals` | `(a, b) => boolean` | `===` | Custom equality check to skip no-op assignments |
1209
+
1210
+ The `render: false` option is the escape hatch for custom decorators that want their own render strategy -- debouncing, throttling, conditional rendering.
1211
+
1212
+ ### addDecoratorEffect / addTeardown
1213
+
1214
+ These two functions handle **hot-reload compatibility**. When `Registry.evolve()` upgrades a live component, or `Registry.lazy()` loads a real implementation for a placeholder, Pandora needs to replay decorator behavior on instances that are already in the DOM. Without these, custom decorators would silently stop working after an evolve.
1215
+
1216
+ **`addDecoratorEffect(metadata, effectFn)`** -- Call this inside your decorator function (not inside `addInitializer`). The effect receives the instance and should install whatever behavior your decorator provides.
1217
+
1218
+ **`addTeardown(instance, cleanupFn)`** -- Call this inside `addInitializer`, or inside an effect. The cleanup runs before effects are replayed during evolve, so you don't end up with duplicate subscriptions or leaked listeners.
1219
+
1220
+ **Pattern:**
1221
+
1222
+ ```typescript
1223
+ function MyDecorator(config: string) {
1224
+ return function (_target: undefined, context: ClassFieldDecoratorContext) {
1225
+ const propertyKey = String(context.name);
1226
+
1227
+ const meta = context.metadata as Record<symbol, unknown>;
1228
+
1229
+ // 1. Register the effect for evolve/lazy replay
1230
+ addDecoratorEffect(meta, (instance) => {
1231
+ applyMyEffect(instance as Component, propertyKey, config);
1232
+ });
1233
+
1234
+ // 2. Apply the effect on first construction
1235
+ context.addInitializer(function (this: unknown) {
1236
+ applyMyEffect(this as Component, propertyKey, config);
953
1237
  });
1238
+ };
1239
+ }
954
1240
 
955
- // Bind click event using event helpers
956
- this.on('click', () => this.toggleTheme());
1241
+ function applyMyEffect(instance: Component, propertyKey: string, config: string) {
1242
+ // Set up the behavior (subscriptions, property descriptors, etc.)
1243
+ const subscription = someService.subscribe(config, (value) => {
1244
+ (instance as any)[propertyKey] = value;
1245
+ });
957
1246
 
958
- return Promise.resolve();
1247
+ // Register cleanup for evolve teardown
1248
+ addTeardown(instance as any, () => {
1249
+ subscription.unsubscribe();
1250
+ });
1251
+ }
1252
+ ```
1253
+
1254
+ ### didChange Hook
1255
+
1256
+ Components can override `didChange(property, oldValue, newValue, source?)` as a single interception point for every `@State`, `@Attribute`, `@Property`, and `@Subscribe` change. The `source` parameter tells you where the change came from (`'state'`, `'prop'`, `'prop-attribute'`, `'property'`, `'consumer'`, `'reactive'`):
1257
+
1258
+ ```typescript
1259
+ class TrackedComponent extends Component {
1260
+ @State() count = 0;
1261
+ @State() name = '';
1262
+ @Attribute() title = '';
1263
+ @Property() open = false;
1264
+
1265
+ didChange(property: string, oldValue: unknown, newValue: unknown, source?: string) {
1266
+ analytics.track('field_change', { property, oldValue, newValue, source });
959
1267
  }
1268
+ }
1269
+ ```
1270
+
1271
+ `didChange` fires synchronously after `@Watch` callbacks and before the render is queued.
1272
+
1273
+ ### Example: @LocalStorage
1274
+
1275
+ Persists a reactive field to `localStorage` and restores it on page load:
960
1276
 
961
- willUnmount() {
962
- // Clean up subscription
963
- if (this._unsubscribe) {
964
- this._unsubscribe();
1277
+ ```typescript
1278
+ import { reactive, addDecoratorEffect, addTeardown, Component } from '@aegis-framework/pandora';
1279
+
1280
+ function LocalStorage(storageKey: string) {
1281
+ return function (_target: undefined, context: ClassFieldDecoratorContext) {
1282
+ const propertyKey = String(context.name);
1283
+ const meta = context.metadata as Record<symbol, unknown>;
1284
+
1285
+ addDecoratorEffect(meta, (instance) => {
1286
+ applyLocalStorage(instance as Component, propertyKey, storageKey);
1287
+ });
1288
+
1289
+ context.addInitializer(function (this: unknown) {
1290
+ applyLocalStorage(this as Component, propertyKey, storageKey);
1291
+ });
1292
+ };
1293
+ }
1294
+
1295
+ function applyLocalStorage(instance: Component, propertyKey: string, storageKey: string) {
1296
+ const stored = localStorage.getItem(storageKey);
1297
+ const initial = stored !== null ? JSON.parse(stored) : undefined;
1298
+
1299
+ reactive(instance as any, propertyKey, {
1300
+ initialValue: initial,
1301
+ onChange(newVal) {
1302
+ localStorage.setItem(storageKey, JSON.stringify(newVal));
1303
+ }
1304
+ });
1305
+
1306
+ // Listen for changes from other tabs
1307
+ const handler = (e: StorageEvent) => {
1308
+ if (e.key === storageKey && e.newValue !== null) {
1309
+ (instance as any)[propertyKey] = JSON.parse(e.newValue);
965
1310
  }
966
- return Promise.resolve();
1311
+ };
1312
+ window.addEventListener('storage', handler);
1313
+ addTeardown(instance as any, () => window.removeEventListener('storage', handler));
1314
+ }
1315
+ ```
1316
+
1317
+ ```typescript
1318
+ @Register('settings-panel')
1319
+ class SettingsPanel extends Component {
1320
+ @LocalStorage('app.theme') theme = 'light';
1321
+
1322
+ render() {
1323
+ return html`
1324
+ <button @click=${() => { this.theme = this.theme === 'light' ? 'dark' : 'light'; }}>
1325
+ Current theme: ${this.theme}
1326
+ </button>
1327
+ `;
967
1328
  }
1329
+ }
1330
+ ```
968
1331
 
969
- toggleTheme() {
970
- const newTheme = this.state.theme === 'light' ? 'dark' : 'light';
971
- Registry.setState('theme', newTheme);
1332
+ The decorator is reactive (auto-renders), persists across page loads, syncs across tabs, and survives `Registry.evolve()` -- all from a few dozen lines.
1333
+
1334
+ ### Example: @DebouncedState
1335
+
1336
+ A reactive field that debounces its render trigger, useful for search inputs:
1337
+
1338
+ ```typescript
1339
+ import { reactive, Component } from '@aegis-framework/pandora';
1340
+
1341
+ function DebouncedState(ms: number = 300) {
1342
+ return function (_target: undefined, context: ClassFieldDecoratorContext) {
1343
+ const propertyKey = String(context.name);
1344
+ context.addInitializer(function (this: unknown) {
1345
+ const instance = this as Component;
1346
+ let timer: ReturnType<typeof setTimeout>;
1347
+ reactive(instance as any, propertyKey, {
1348
+ render: false,
1349
+ onChange() {
1350
+ clearTimeout(timer);
1351
+ timer = setTimeout(() => {
1352
+ (instance as any)._queueRender();
1353
+ }, ms);
1354
+ }
1355
+ });
1356
+ });
1357
+ };
1358
+ }
1359
+ ```
1360
+
1361
+ ```typescript
1362
+ @Register('search-bar')
1363
+ class SearchBar extends Component {
1364
+ @DebouncedState(250) query = '';
1365
+
1366
+ @Listen('input', { target: '.search-input' })
1367
+ onInput(e: Event) {
1368
+ this.query = (e.target as HTMLInputElement).value;
972
1369
  }
973
1370
 
974
1371
  render() {
975
- return `<button>Current: ${this.state.theme}</button>`;
1372
+ return html`
1373
+ <input class="search-input" placeholder="Search...">
1374
+ <div class="results">Searching for: ${this.query}</div>
1375
+ `;
976
1376
  }
977
1377
  }
978
1378
  ```
979
1379
 
980
- ## Styling
1380
+ The field itself updates immediately (so `@Watch` and `didChange` fire synchronously), but the template only re-renders after 250ms of inactivity.
981
1381
 
982
- Both `Component` and `ShadowComponent` use [Constructable Stylesheets](https://web.dev/constructable-stylesheets/) for optimal performance:
1382
+ ### Example: @MediaQuery
983
1383
 
984
- - **Shared across instances** - One stylesheet per component class, not per instance
985
- - **Fast updates** - Uses `replaceSync()` for synchronous style changes
986
- - **No DOM overhead** - No `<style>` element parsing
1384
+ A reactive boolean that tracks a CSS media query:
987
1385
 
988
- ### Regular Components
1386
+ ```typescript
1387
+ import { reactive, addDecoratorEffect, addTeardown, Component } from '@aegis-framework/pandora';
989
1388
 
990
- Styles are adopted into `document.adoptedStyleSheets` and automatically scoped using the component's tag name as a selector prefix:
1389
+ function MediaQuery(query: string) {
1390
+ return function (_target: undefined, context: ClassFieldDecoratorContext) {
1391
+ const propertyKey = String(context.name);
1392
+ const meta = context.metadata as Record<symbol, unknown>;
991
1393
 
992
- ```javascript
993
- element.setStyle({
994
- h2: {
995
- color: 'blue',
996
- fontSize: '24px'
997
- },
998
- '&:hover h2': {
999
- color: 'red'
1394
+ addDecoratorEffect(meta, (instance) => {
1395
+ applyMediaQuery(instance as Component, propertyKey, query);
1396
+ });
1397
+
1398
+ context.addInitializer(function (this: unknown) {
1399
+ applyMediaQuery(this as Component, propertyKey, query);
1400
+ });
1401
+ };
1402
+ }
1403
+
1404
+ function applyMediaQuery(instance: Component, propertyKey: string, query: string) {
1405
+ const mql = window.matchMedia(query);
1406
+ reactive(instance as any, propertyKey, { initialValue: mql.matches });
1407
+
1408
+ const handler = (e: MediaQueryListEvent) => {
1409
+ (instance as any)[propertyKey] = e.matches;
1410
+ };
1411
+ mql.addEventListener('change', handler);
1412
+ addTeardown(instance as any, () => mql.removeEventListener('change', handler));
1413
+ }
1414
+ ```
1415
+
1416
+ ```typescript
1417
+ @Register('responsive-layout')
1418
+ class ResponsiveLayout extends Component {
1419
+ @MediaQuery('(min-width: 768px)') isDesktop = false;
1420
+ @MediaQuery('(prefers-color-scheme: dark)') prefersDark = false;
1421
+
1422
+ render() {
1423
+ return html`
1424
+ <div class=${this.prefersDark ? 'dark' : 'light'}>
1425
+ ${this.isDesktop
1426
+ ? html`<div class="sidebar">...</div><div class="main">...</div>`
1427
+ : html`<div class="mobile-stack">...</div>`
1428
+ }
1429
+ </div>
1430
+ `;
1000
1431
  }
1001
- });
1002
- // Generates: my-element h2 { color: blue; ... }
1432
+ }
1003
1433
  ```
1004
1434
 
1005
- ### Shadow Components
1435
+ ### Example: @FetchData
1006
1436
 
1007
- Styles are adopted into the shadow root's `adoptedStyleSheets` and naturally scoped by Shadow DOM encapsulation:
1437
+ A reactive field that fetches data from a URL and auto-renders when the response arrives:
1008
1438
 
1009
- ```javascript
1010
- shadowElement.setStyle({
1011
- ':host': {
1012
- display: 'block'
1013
- },
1014
- h2: {
1015
- color: 'blue'
1016
- },
1017
- '@media (min-width: 768px)': {
1018
- h2: {
1019
- fontSize: '32px'
1020
- }
1439
+ ```typescript
1440
+ import { reactive, addDecoratorEffect, addTeardown, Component } from '@aegis-framework/pandora';
1441
+
1442
+ function FetchData(url: string) {
1443
+ return function (_target: undefined, context: ClassFieldDecoratorContext) {
1444
+ const propertyKey = String(context.name);
1445
+ const meta = context.metadata as Record<symbol, unknown>;
1446
+
1447
+ addDecoratorEffect(meta, (instance) => {
1448
+ applyFetchData(instance as Component, propertyKey, url);
1449
+ });
1450
+
1451
+ context.addInitializer(function (this: unknown) {
1452
+ applyFetchData(this as Component, propertyKey, url);
1453
+ });
1454
+ };
1455
+ }
1456
+
1457
+ function applyFetchData(instance: Component, propertyKey: string, url: string) {
1458
+ reactive(instance as any, propertyKey, { initialValue: null });
1459
+
1460
+ const controller = new AbortController();
1461
+ fetch(url, { signal: controller.signal })
1462
+ .then(r => r.json())
1463
+ .then(data => { (instance as any)[propertyKey] = data; })
1464
+ .catch(() => {});
1465
+
1466
+ addTeardown(instance as any, () => controller.abort());
1467
+ }
1468
+ ```
1469
+
1470
+ ```typescript
1471
+ @Register('user-profile')
1472
+ class UserProfile extends Component {
1473
+ @FetchData('/api/user') userData: any = null;
1474
+
1475
+ render() {
1476
+ if (!this.userData) return html`<p>Loading...</p>`;
1477
+ return html`<h2>${this.userData.name}</h2><p>${this.userData.email}</p>`;
1021
1478
  }
1479
+ }
1480
+ ```
1481
+
1482
+ ### What You Can Build
1483
+
1484
+ The extension API is meant to let you create decorators for any external data source or side effect:
1485
+
1486
+ | Pattern | Built with |
1487
+ |---------|-----------|
1488
+ | Persistent state (localStorage, IndexedDB) | `reactive()` + `onChange` |
1489
+ | Debounced/throttled fields | `reactive({ render: false })` + custom timer |
1490
+ | Media queries, resize observers | `reactive()` + `addTeardown()` for cleanup |
1491
+ | Data fetching | `reactive()` + `addTeardown()` for abort |
1492
+ | WebSocket bindings | `reactive()` + `addTeardown()` for disconnect |
1493
+ | Intersection observers | `reactive()` + `addTeardown()` for unobserve |
1494
+ | Animation state | `reactive({ render: false })` + requestAnimationFrame |
1495
+ | Form validation | `reactive()` + `onChange` for validation logic |
1496
+ | Feature flags | `reactive()` + external service subscription |
1497
+ | Analytics/telemetry | `didChange()` hook or `onChange` callback |
1498
+ | Type-safe shared state | `createState<T>()` + `@Subscribe` |
1499
+ | Class-based visual state | `@ClassList` decorator |
1500
+
1501
+ All of these plug straight into Pandora's render cycle, `@Watch`, `didChange()`, and `Registry.evolve()` -- no extra wiring needed.
1502
+
1503
+ ## Styling
1504
+
1505
+ ### setStyle()
1506
+
1507
+ `setStyle()` uses [Constructable Stylesheets](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/CSSStyleSheet) -- one stylesheet per component class, shared across every instance. Updates go through `replaceSync()`, so nothing adds `<style>` elements to the DOM.
1508
+
1509
+ ```typescript
1510
+ // CSS object (keys are selectors, values are property objects)
1511
+ this.setStyle({
1512
+ h2: { color: 'blue', fontSize: '24px' },
1513
+ '.active': { fontWeight: 'bold' },
1514
+ '&:hover': { opacity: '0.9' } // & is replaced with the tag name
1022
1515
  });
1516
+
1517
+ // CSS string
1518
+ this.setStyle('h2 { color: blue; }');
1519
+
1520
+ // Second argument true = replace instead of merge
1521
+ this.setStyle({ h2: { color: 'red' } }, true);
1522
+ ```
1523
+
1524
+ For `Component` (light DOM), selectors are prefixed with the component's tag name for you. For `ShadowComponent`, Shadow DOM provides natural encapsulation on its own.
1525
+
1526
+ ### @Style Decorator
1527
+
1528
+ `@Style` is the declarative equivalent -- styles are applied once on first mount:
1529
+
1530
+ ```typescript
1531
+ @Register('stat-card')
1532
+ @Style({
1533
+ ':host': { display: 'block', borderRadius: '8px', padding: '16px' },
1534
+ 'h4': { margin: '0 0 8px', fontSize: '14px', color: '#666' },
1535
+ '.value': { fontSize: '32px', fontWeight: 'bold' }
1536
+ })
1537
+ class StatCard extends Component { /* ... */ }
1538
+ ```
1539
+
1540
+ ## lit-html Integration
1541
+
1542
+ Pandora bundles and re-exports lit-html, so you don't need to install it separately.
1543
+
1544
+ ```typescript
1545
+ import {
1546
+ html, // HTML template tag
1547
+ svg, // SVG template tag
1548
+ nothing, // renders nothing (replaces previous content)
1549
+ noChange, // skip updating a binding
1550
+ render, // manual render (rarely needed)
1551
+ type TemplateResult,
1552
+ type SVGTemplateResult,
1553
+ type RenderOptions
1554
+ } from '@aegis-framework/pandora';
1555
+ ```
1556
+
1557
+ ### String vs lit-html Templates
1558
+
1559
+ Both rendering modes work inside the same component. Reach for whichever fits the situation:
1560
+
1561
+ ```typescript
1562
+ // String template -- simple, no build-time processing needed
1563
+ render() {
1564
+ return `<p>Hello, ${this.name}</p>`;
1565
+ }
1566
+
1567
+ // lit-html -- efficient updates, event binding, property binding
1568
+ render() {
1569
+ return html`
1570
+ <p>Hello, ${this.name}</p>
1571
+ <button @click=${() => this.handleClick()}>Go</button>
1572
+ <input .value=${this.query} ?disabled=${this.loading}>
1573
+ ${this.items.map(item => html`<li>${item}</li>`)}
1574
+ ${this.error ? html`<p class="error">${this.error}</p>` : nothing}
1575
+ `;
1576
+ }
1577
+
1578
+ // Async render -- component awaits the promise before updating the DOM
1579
+ async render() {
1580
+ const data = await fetchUserProfile(this.userId);
1581
+ return html`<div>${data.name}</div>`;
1582
+ }
1583
+ ```
1584
+
1585
+ ### Static Template
1586
+
1587
+ Set a template on the class directly -- handy for external templates or programmatic overrides. Every mounted instance re-renders automatically when the template changes:
1588
+
1589
+ ```typescript
1590
+ // Function template (self is the component instance)
1591
+ MyComponent.template = (self) => html`<div>${self.title}</div>`;
1592
+
1593
+ // Defined in the class body
1594
+ class MyComponent extends Component {
1595
+ static template = (self: MyComponent) => html`<h1>${self.title}</h1>`;
1596
+ }
1597
+ ```
1598
+
1599
+ An HTML `<template>` element with a matching `id` is also picked up on first mount:
1600
+
1601
+ ```html
1602
+ <template id="my-component">
1603
+ <div class="wrapper">Static HTML content</div>
1604
+ </template>
1023
1605
  ```
1024
1606
 
1025
- ### CSS String
1607
+ ## Non-Decorator Usage
1608
+
1609
+ **Best experience: modern TypeScript with decorators.** The decorator path gives you auto-rendering, attribute sync, event binding, and lifecycle management with no boilerplate.
1026
1610
 
1027
- You can also pass raw CSS strings:
1611
+ **Fallback: plain JavaScript with manual `forceRender()`.** For environments without build tools or decorator support, you can write components as plain classes. It works, but expect a bit more manual wiring.
1028
1612
 
1029
1613
  ```javascript
1030
- element.setStyle(`
1031
- h2 {
1032
- color: blue;
1033
- font-size: 24px;
1614
+ import { Component, Registry, html } from '@aegis-framework/pandora';
1615
+
1616
+ class CounterElement extends Component {
1617
+ count = 0;
1618
+
1619
+ didMount() {
1620
+ this.on('click', () => {
1621
+ this.count++;
1622
+ this.forceRender(); // plain fields are not reactive -- call forceRender() manually
1623
+ });
1624
+ }
1625
+
1626
+ render() {
1627
+ return html`<button>Count: ${this.count}</button>`;
1034
1628
  }
1035
- `);
1629
+ }
1630
+
1631
+ Registry.register('counter-element', CounterElement);
1632
+ ```
1633
+
1634
+ Plain class fields are not reactive. Without `@State` or `@Attribute`, changes don't trigger renders on their own -- you have to call `forceRender()` after every mutation. Lifecycle hooks (`willMount`, `didMount`, `willUnmount`, `didUnmount`, `didReconnect`) work the same way in both paths.
1635
+
1636
+ ## Test Utilities
1637
+
1638
+ Pandora ships a `testing` namespace with helpers for unit and component tests. Import it straight from the main package:
1639
+
1640
+ ```typescript
1641
+ import { testing } from '@aegis-framework/pandora';
1642
+ ```
1643
+
1644
+ | Function | Signature | Description |
1645
+ |----------|-----------|-------------|
1646
+ | `testing.flush()` | `() => Promise<void>` | Resolve all pending microtask renders. Call after state changes before asserting DOM state. |
1647
+ | `testing.whenReady(element, timeout?)` | `(Element, number?) => Promise<void>` | Wait until `element.isReady` is true. Resolves immediately if already ready. Rejects after `timeout` ms (default 5000). |
1648
+ | `testing.resetRegistry()` | `() => void` | Clear all global state, subscriptions, and middleware. Call in `beforeEach` / `afterEach` to isolate tests. |
1649
+ | `testing.mount(tagName, container?, innerHTML?)` | `(string, Element?, string?) => Promise<Component>` | Create the element, append it to `container` (default `document.body`), wait until ready, and return it. |
1650
+
1651
+ ```typescript
1652
+ import { testing } from '@aegis-framework/pandora';
1653
+ import { MyCounter } from './MyCounter';
1654
+
1655
+ beforeEach(() => {
1656
+ testing.resetRegistry();
1657
+ });
1658
+
1659
+ it('increments on click', async () => {
1660
+ const el = await testing.mount('my-counter') as MyCounter;
1661
+
1662
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
1663
+ await testing.flush();
1664
+
1665
+ expect(el.shadowRoot?.textContent).toContain('1');
1666
+ });
1667
+
1668
+ it('accepts initial innerHTML', async () => {
1669
+ const el = await testing.mount('my-counter', document.body, '<span slot="label">Clicks</span>');
1670
+ expect(el.isReady).toBe(true);
1671
+ });
1036
1672
  ```
1037
1673
 
1674
+ `testing.flush()` performs two microtask yields: the first drains any `_queueRender` microtasks, and the second drains any microtasks queued during the render itself. That's enough for all standard reactive updates.
1675
+
1038
1676
  ## Browser Usage
1039
1677
 
1040
- For direct browser usage without a bundler:
1678
+ Pandora ships a pre-bundled browser file you can drop in without a bundler:
1041
1679
 
1042
1680
  ```html
1043
- <script src="path/to/pandora.browser.js"></script>
1681
+ <script src="node_modules/@aegis-framework/pandora/dist/pandora.browser.js"></script>
1044
1682
  <script>
1045
- const { Component, ShadowComponent, Registry, html } = Pandora;
1683
+ const { Component, Registry, html } = Pandora;
1046
1684
 
1047
1685
  class CounterElement extends Component {
1048
- constructor() {
1049
- super();
1050
- this.state = { count: 0 };
1051
- }
1686
+ count = 0;
1052
1687
 
1053
1688
  didMount() {
1054
1689
  this.on('click', () => {
1055
- this.setState({ count: this.state.count + 1 });
1690
+ this.count++;
1691
+ this.forceRender();
1056
1692
  });
1057
- return Promise.resolve();
1058
1693
  }
1059
1694
 
1060
1695
  render() {
1061
- return html`<button>Count: ${this.state.count}</button>`;
1696
+ return html`<button>Count: ${this.count}</button>`;
1062
1697
  }
1063
1698
  }
1064
1699
 
@@ -1068,6 +1703,38 @@ For direct browser usage without a bundler:
1068
1703
  <counter-element></counter-element>
1069
1704
  ```
1070
1705
 
1706
+ Decorators aren't available in no-build browser usage. Use `Registry.register()` and `forceRender()` as shown above.
1707
+
1708
+ ## Migration Guide
1709
+
1710
+ Migrating from pre-0.6 Pandora to the new decorator-first API:
1711
+
1712
+ | Before (pre-0.6) | After (0.6) |
1713
+ |-------------------|-------------|
1714
+ | `this.state = { count: 0 }` | `@State() count = 0` |
1715
+ | `this.setState({ count: 1 })` | `this.count = 1` |
1716
+ | `this.props = { title: '' }` | `@Attribute() title = ''` |
1717
+ | `this.setProps({ title: 'Hi' })` | `this.title = 'Hi'` |
1718
+ | `onStateUpdate() { this.forceRender(); }` | Automatic -- `@State` fields queue renders on change |
1719
+ | `onPropsUpdate() { this.forceRender(); }` | Automatic -- `@Attribute` fields queue renders on change |
1720
+ | `willUpdate()` / `didUpdate()` | `@Watch('field')` or `didChange()` |
1721
+ | `update()` | `@Watch('field')` |
1722
+ | `unmount()` | `willUnmount()` / `didUnmount()` |
1723
+ | `MyComponent.template(fn)` | `MyComponent.template = fn` |
1724
+ | `this.dom` | `this` (Component is itself an `HTMLElement`) |
1725
+ | `this.static.tag` | Removed -- use `(this.constructor as typeof Component).tag` |
1726
+ | `this.width` / `this.height` | Use `getComputedStyle(this)` directly |
1727
+ | `this.ready(callback)` | Use `didMount()` |
1728
+ | `Component<Props, State>` generics | Typed class fields with decorators |
1729
+ | Untyped `Registry.setState` / `Registry.getState` for shared values | `createState<T>(key, default)` for type-safe global state |
1730
+
1731
+ **Key behavioral changes:**
1732
+
1733
+ - **Auto-rendering is the default.** You no longer need `onStateUpdate() { this.forceRender(); }`. Any assignment to a `@State` or `@Attribute` field queues a render for you.
1734
+ - **No more state / props bags.** Each piece of state is its own decorated class field, which gives you TypeScript types for free and makes the intent of each field explicit.
1735
+ - **`forceRender()` is the escape hatch now, not the norm.** You only need it when you're working with plain (non-decorated) fields, or when you need an immediate synchronous render.
1736
+ - **Lifecycle hooks are simpler.** The old update lifecycle (`willUpdate`, `update`, `didUpdate`, `onStateUpdate`, `onPropsUpdate`, `updateCallback`) is entirely replaced by `@Watch` and `didChange`.
1737
+
1071
1738
  ## License
1072
1739
 
1073
- This library is released under a [MIT License](./LICENSE).
1740
+ Released under the [MIT License](./LICENSE).