@aegis-framework/pandora 0.5.0 → 0.6.1
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 +1395 -755
- package/dist/pandora.browser.js +16 -15
- package/dist/pandora.browser.js.map +11 -9
- package/dist/pandora.js +16 -15
- package/dist/pandora.js.map +10 -8
- package/dist/types/Component.d.ts +795 -222
- package/dist/types/Component.d.ts.map +1 -1
- package/dist/types/Decorators.d.ts +378 -35
- package/dist/types/Decorators.d.ts.map +1 -1
- package/dist/types/Registry.d.ts +479 -105
- package/dist/types/Registry.d.ts.map +1 -1
- package/dist/types/ShadowComponent.d.ts +133 -23
- package/dist/types/ShadowComponent.d.ts.map +1 -1
- package/dist/types/Testing.d.ts +74 -0
- package/dist/types/Testing.d.ts.map +1 -0
- package/dist/types/TypedState.d.ts +51 -0
- package/dist/types/TypedState.d.ts.map +1 -0
- package/dist/types/Types.d.ts +92 -2
- package/dist/types/Types.d.ts.map +1 -1
- package/dist/types/Util.d.ts +134 -15
- package/dist/types/Util.d.ts.map +1 -1
- package/dist/types/browser.d.ts +14 -0
- package/dist/types/browser.d.ts.map +1 -1
- package/dist/types/index.d.ts +20 -8
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +9 -5
package/README.md
CHANGED
|
@@ -1,1091 +1,1699 @@
|
|
|
1
1
|
# Pandora
|
|
2
2
|
|
|
3
|
-
Pandora is a lightweight
|
|
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
|
+
|
|
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.
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
import { Component, Register, State, Listen, html } from '@aegis-framework/pandora';
|
|
9
|
+
|
|
10
|
+
@Register('my-counter')
|
|
11
|
+
class MyCounter extends Component {
|
|
12
|
+
@State() count = 0;
|
|
13
|
+
|
|
14
|
+
@Listen('click')
|
|
15
|
+
increment() {
|
|
16
|
+
this.count++; // auto-renders
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
render() {
|
|
20
|
+
return html`<button>Count: ${this.count}</button>`;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
```
|
|
4
24
|
|
|
5
25
|
## Installation
|
|
6
26
|
|
|
7
27
|
```bash
|
|
8
|
-
#
|
|
28
|
+
# npm
|
|
9
29
|
npm install @aegis-framework/pandora
|
|
10
30
|
|
|
11
|
-
#
|
|
31
|
+
# yarn
|
|
12
32
|
yarn add @aegis-framework/pandora
|
|
13
33
|
|
|
14
|
-
#
|
|
34
|
+
# bun
|
|
15
35
|
bun add @aegis-framework/pandora
|
|
16
36
|
```
|
|
17
37
|
|
|
18
38
|
## Quick Start
|
|
19
39
|
|
|
20
|
-
|
|
40
|
+
The simplest component you can build: a prop that auto-renders on change.
|
|
21
41
|
|
|
22
|
-
```
|
|
23
|
-
import { Component } from '@aegis-framework/pandora';
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
this.props = {
|
|
29
|
-
text: ''
|
|
30
|
-
};
|
|
31
|
-
}
|
|
42
|
+
```typescript
|
|
43
|
+
import { Component, Register, Attribute, html } from '@aegis-framework/pandora';
|
|
44
|
+
|
|
45
|
+
@Register('my-greeting')
|
|
46
|
+
class MyGreeting extends Component {
|
|
47
|
+
@Attribute() name = 'World';
|
|
32
48
|
|
|
33
49
|
render() {
|
|
34
|
-
return `<
|
|
50
|
+
return html`<h1>Hello, ${this.name}!</h1>`;
|
|
35
51
|
}
|
|
36
52
|
}
|
|
53
|
+
```
|
|
37
54
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
// Register the custom element
|
|
41
|
-
window.customElements.define(CustomElement.tag, CustomElement);
|
|
55
|
+
```html
|
|
56
|
+
<my-greeting name="Alice"></my-greeting>
|
|
42
57
|
```
|
|
43
58
|
|
|
44
|
-
|
|
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.
|
|
45
60
|
|
|
46
|
-
|
|
61
|
+
## Decorators Reference
|
|
47
62
|
|
|
48
|
-
|
|
49
|
-
import { Component, html } from '@aegis-framework/pandora';
|
|
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).
|
|
50
64
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
this.props = { text: '' };
|
|
55
|
-
}
|
|
65
|
+
### @Register(tagName)
|
|
66
|
+
|
|
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.
|
|
56
68
|
|
|
69
|
+
```typescript
|
|
70
|
+
@Register('my-button')
|
|
71
|
+
class MyButton extends Component {
|
|
57
72
|
render() {
|
|
58
|
-
return html`<
|
|
73
|
+
return html`<button>${this.slotContent}</button>`;
|
|
59
74
|
}
|
|
60
75
|
}
|
|
61
76
|
```
|
|
62
77
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
```html
|
|
66
|
-
<custom-element text="Hello World!"></custom-element>
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
### TypeScript Support
|
|
78
|
+
### @State(options?)
|
|
70
79
|
|
|
71
|
-
|
|
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.
|
|
72
81
|
|
|
73
82
|
```typescript
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
name: string;
|
|
78
|
-
count: number;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
interface MyState {
|
|
82
|
-
active: boolean;
|
|
83
|
-
}
|
|
84
|
-
|
|
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
|
-
}
|
|
83
|
+
@Register('my-toggle')
|
|
84
|
+
class MyToggle extends Component {
|
|
85
|
+
@State() open = false;
|
|
96
86
|
|
|
97
87
|
render() {
|
|
98
88
|
return html`
|
|
99
|
-
<
|
|
100
|
-
|
|
101
|
-
<span>Count: ${this.props.count}</span>
|
|
102
|
-
</div>
|
|
89
|
+
<button @click=${() => { this.open = !this.open; }}>Toggle</button>
|
|
90
|
+
${this.open ? html`<div class="panel">Content</div>` : nothing}
|
|
103
91
|
`;
|
|
104
92
|
}
|
|
105
93
|
}
|
|
106
94
|
```
|
|
107
95
|
|
|
108
|
-
|
|
96
|
+
**Options:**
|
|
109
97
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
import { Component, Register, Consumer, Prop, html } from '@aegis-framework/pandora';
|
|
98
|
+
| Option | Type | Default | Description |
|
|
99
|
+
|--------|------|---------|-------------|
|
|
100
|
+
| `render` | `boolean` | `true` | Whether changes queue a re-render |
|
|
114
101
|
|
|
115
|
-
|
|
116
|
-
class MyCounter extends Component {
|
|
117
|
-
@Prop()
|
|
118
|
-
initialCount: number = 0;
|
|
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`:
|
|
119
103
|
|
|
120
|
-
|
|
121
|
-
|
|
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
|
|
122
109
|
|
|
123
|
-
|
|
124
|
-
super();
|
|
125
|
-
this.state = { count: 0 };
|
|
126
|
-
}
|
|
110
|
+
@Query('.time-display') timeDisplay!: HTMLSpanElement;
|
|
127
111
|
|
|
128
|
-
|
|
129
|
-
|
|
112
|
+
@Watch('currentTime')
|
|
113
|
+
onTimeUpdate(newVal: number) {
|
|
114
|
+
if (this.isReady) {
|
|
115
|
+
this.timeDisplay.textContent = `${newVal.toFixed(1)}s`;
|
|
116
|
+
}
|
|
130
117
|
}
|
|
131
118
|
|
|
132
119
|
render() {
|
|
133
120
|
return html`
|
|
134
|
-
<div
|
|
135
|
-
|
|
136
|
-
</div>
|
|
121
|
+
<div>Now playing: ${this.track}</div>
|
|
122
|
+
<span class="time-display">0.0s</span>
|
|
137
123
|
`;
|
|
138
124
|
}
|
|
139
125
|
}
|
|
140
126
|
```
|
|
141
127
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
### Component
|
|
145
|
-
|
|
146
|
-
The base class for creating custom elements.
|
|
128
|
+
When to use `render: false`:
|
|
147
129
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
super();
|
|
152
|
-
|
|
153
|
-
// Define props with default values
|
|
154
|
-
this.props = {
|
|
155
|
-
title: '',
|
|
156
|
-
visible: true
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
// Define internal state
|
|
160
|
-
this.state = {
|
|
161
|
-
count: 0
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
render() {
|
|
166
|
-
return `<div>${this.props.title}: ${this.state.count}</div>`;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
```
|
|
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)
|
|
170
133
|
|
|
171
|
-
|
|
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.
|
|
172
135
|
|
|
173
|
-
|
|
136
|
+
### @Property(options?)
|
|
174
137
|
|
|
175
|
-
|
|
176
|
-
import { ShadowComponent, html } from '@aegis-framework/pandora';
|
|
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.
|
|
177
139
|
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
}
|
|
140
|
+
```typescript
|
|
141
|
+
@Register('game-screen')
|
|
142
|
+
class GameScreen extends Component {
|
|
143
|
+
@Property() open = false;
|
|
183
144
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
this.
|
|
187
|
-
':host': { display: 'block' },
|
|
188
|
-
h2: { color: 'blue' }
|
|
189
|
-
});
|
|
145
|
+
@Watch('open')
|
|
146
|
+
onOpenChange() {
|
|
147
|
+
this.classList.toggle('active', this.open);
|
|
190
148
|
}
|
|
191
149
|
|
|
192
|
-
render() {
|
|
193
|
-
//
|
|
194
|
-
return html`<h2>${this.props.text}</h2>`;
|
|
150
|
+
render(): void {
|
|
151
|
+
// void = preserve HTML children
|
|
195
152
|
}
|
|
196
153
|
}
|
|
197
154
|
```
|
|
198
155
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
## API Reference
|
|
202
|
-
|
|
203
|
-
### Static Properties
|
|
156
|
+
**Options:**
|
|
204
157
|
|
|
205
|
-
|
|
|
206
|
-
|
|
207
|
-
| `
|
|
208
|
-
| `
|
|
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 |
|
|
209
162
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
| Property | Type | Description |
|
|
213
|
-
|----------|------|-------------|
|
|
214
|
-
| `props` | `object` | Component properties (read via proxy, set via `setProps()`) |
|
|
215
|
-
| `state` | `object` | Internal component state (set via `setState()`) |
|
|
216
|
-
| `dom` | `HTMLElement` | Reference to the component's DOM element |
|
|
217
|
-
| `slotContent` | `string` | Original innerHTML content before rendering (for content projection) |
|
|
218
|
-
| `width` | `number` | Computed width in pixels |
|
|
219
|
-
| `height` | `number` | Computed height in pixels |
|
|
220
|
-
| `isConnected` | `boolean` | Whether the component is connected to the DOM |
|
|
221
|
-
| `isReady` | `boolean` | Whether the component has completed its initial mount |
|
|
222
|
-
| `isFirstMount` | `boolean` | Whether this is the first time the component is being mounted (as opposed to a reconnect) |
|
|
163
|
+
**When to use @Property vs @State:**
|
|
223
164
|
|
|
224
|
-
|
|
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 |
|
|
225
171
|
|
|
226
|
-
|
|
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.
|
|
227
173
|
|
|
228
|
-
|
|
174
|
+
### @Attribute(attributeNameOrOptions?)
|
|
229
175
|
|
|
230
|
-
|
|
231
|
-
// Update props (triggers update cycle)
|
|
232
|
-
element.setProps({ title: 'New Title' });
|
|
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.
|
|
233
177
|
|
|
234
|
-
|
|
235
|
-
element.setState({ count: 5 });
|
|
178
|
+
**String shorthand** -- custom attribute name:
|
|
236
179
|
|
|
237
|
-
|
|
238
|
-
|
|
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;
|
|
239
186
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
}
|
|
187
|
+
render() {
|
|
188
|
+
return html`
|
|
189
|
+
<input
|
|
190
|
+
placeholder=${this.placeholder}
|
|
191
|
+
maxlength=${this.maxLength}
|
|
192
|
+
?disabled=${this.disabled}
|
|
193
|
+
>
|
|
194
|
+
`;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
244
197
|
```
|
|
245
198
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
```javascript
|
|
249
|
-
// Add event listener (chainable)
|
|
250
|
-
element.on('click', (e) => console.log('Clicked!'));
|
|
251
|
-
|
|
252
|
-
// Add one-time event listener (auto-removes after first trigger)
|
|
253
|
-
element.once('click', (e) => console.log('Only fires once!'));
|
|
254
|
-
|
|
255
|
-
// Remove event listener (chainable)
|
|
256
|
-
element.off('click', handler);
|
|
257
|
-
|
|
258
|
-
// Emit custom event
|
|
259
|
-
element.emit('custom-event', { data: 'value' });
|
|
199
|
+
```html
|
|
200
|
+
<my-input placeholder="Enter text" max-length="50" disabled></my-input>
|
|
260
201
|
```
|
|
261
202
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
```javascript
|
|
265
|
-
// Query single element within component
|
|
266
|
-
const button = element.query('button');
|
|
203
|
+
Attribute values are coerced for you: `''` and `'true'` become `true`, `'false'` becomes `false`, numeric strings become numbers, and everything else stays a string.
|
|
267
204
|
|
|
268
|
-
|
|
269
|
-
const items = element.queryAll('.item');
|
|
270
|
-
```
|
|
205
|
+
**Property-only mode** -- use `@Property()`:
|
|
271
206
|
|
|
272
|
-
|
|
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.
|
|
273
208
|
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
|
|
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;
|
|
277
216
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
+
}
|
|
282
233
|
```
|
|
283
234
|
|
|
284
|
-
> **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.
|
|
285
|
-
|
|
286
|
-
### Lifecycle Hooks
|
|
287
|
-
|
|
288
|
-
Override these methods to hook into the component lifecycle. All lifecycle hooks are async.
|
|
289
|
-
|
|
290
|
-
#### Mount Cycle
|
|
291
|
-
|
|
292
|
-
- `willMount()` - Called before the component is rendered (runs on every mount and reconnect)
|
|
293
|
-
- `didMount()` - Called after the component is rendered **for the first time only**
|
|
294
|
-
- `didReconnect()` - Called after the component is re-inserted into the DOM (not on first mount)
|
|
295
|
-
|
|
296
|
-
#### Update Cycle
|
|
297
|
-
|
|
298
|
-
- `willUpdate(origin, property, oldValue, newValue, oldObject, newObject)` - Called before an update
|
|
299
|
-
- `update(origin, property, oldValue, newValue, oldObject, newObject)` - Called during an update
|
|
300
|
-
- `didUpdate(origin, property, oldValue, newValue, oldObject, newObject)` - Called after an update
|
|
301
|
-
- `onStateUpdate(property, oldValue, newValue, oldObject, newObject)` - Called when state changes
|
|
302
|
-
- `onPropsUpdate(property, oldValue, newValue, oldObject, newObject)` - Called when props change
|
|
303
|
-
|
|
304
|
-
The `origin` parameter can be `'props'`, `'state'`, or `'attribute'` depending on what triggered the update.
|
|
305
|
-
|
|
306
|
-
#### Unmount Cycle
|
|
307
|
-
|
|
308
|
-
- `willUnmount()` - Called before the component is removed
|
|
309
|
-
- `unmount()` - Called when the component is being removed
|
|
310
|
-
- `didUnmount()` - Called after the component is removed
|
|
311
|
-
|
|
312
235
|
```javascript
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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);
|
|
240
|
+
```
|
|
318
241
|
|
|
319
|
-
|
|
320
|
-
// Only runs once — safe for listeners, subscriptions, intervals
|
|
321
|
-
this.on('click', () => this.handleClick());
|
|
322
|
-
console.log('Mounted for the first time!');
|
|
323
|
-
}
|
|
242
|
+
### @Watch(property)
|
|
324
243
|
|
|
325
|
-
|
|
326
|
-
// Runs when re-inserted into the DOM (e.g., after being moved)
|
|
327
|
-
console.log('Reconnected — refreshing data');
|
|
328
|
-
await this.refreshData();
|
|
329
|
-
}
|
|
244
|
+
Method decorator. Runs the decorated method synchronously when a `@State` or `@Attribute` field changes, before the queued render. The method receives `(newValue, oldValue)`.
|
|
330
245
|
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
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);
|
|
334
255
|
}
|
|
335
256
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
this.forceRender();
|
|
257
|
+
render() {
|
|
258
|
+
return html`<input .value=${this.query}>`;
|
|
339
259
|
}
|
|
340
260
|
}
|
|
341
261
|
```
|
|
342
262
|
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
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.
|
|
346
264
|
|
|
347
|
-
|
|
348
|
-
class MyComponent extends Component {
|
|
349
|
-
static observedAttributes = ['title', 'count', 'disabled'];
|
|
265
|
+
Multiple methods can watch the same property, and one method can watch multiple properties by stacking decorators:
|
|
350
266
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
}
|
|
267
|
+
```typescript
|
|
268
|
+
@Watch('width')
|
|
269
|
+
@Watch('height')
|
|
270
|
+
onDimensionChange(newVal: number) {
|
|
271
|
+
this.recalculateLayout();
|
|
357
272
|
}
|
|
358
273
|
```
|
|
359
274
|
|
|
360
|
-
|
|
275
|
+
### @Computed(...dependencies)
|
|
361
276
|
|
|
362
|
-
|
|
277
|
+
Getter decorator. Caches the return value and only recalculates when one of its dependencies (`@State`, `@Attribute`, `@Property`) changes. List dependencies by property name.
|
|
363
278
|
|
|
364
|
-
```
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
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
|
+
}
|
|
373
290
|
|
|
374
|
-
|
|
291
|
+
@Computed('tasks')
|
|
292
|
+
get completedCount() {
|
|
293
|
+
return this.tasks.filter(t => t.done).length;
|
|
294
|
+
}
|
|
375
295
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
<h2>${context.props.title}</h2>
|
|
384
|
-
</div>
|
|
385
|
-
`);
|
|
386
|
-
|
|
387
|
-
// Function returning lit-html (recommended for dynamic content)
|
|
388
|
-
import { html } from '@aegis-framework/pandora';
|
|
389
|
-
|
|
390
|
-
MyComponent.template((context) => html`
|
|
391
|
-
<div class="wrapper">
|
|
392
|
-
<h2>${context.props.title}</h2>
|
|
393
|
-
<button @click=${() => context.handleClick()}>Click me</button>
|
|
394
|
-
</div>
|
|
395
|
-
`);
|
|
396
|
-
|
|
397
|
-
// Async function (for data fetching)
|
|
398
|
-
MyComponent.template(async (context) => {
|
|
399
|
-
const data = await fetchData(context.props.id);
|
|
400
|
-
return html`<div>${data.content}</div>`;
|
|
401
|
-
});
|
|
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
|
+
}
|
|
402
303
|
```
|
|
403
304
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
## lit-html Integration
|
|
407
|
-
|
|
408
|
-
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.
|
|
409
|
-
|
|
410
|
-
### Exports
|
|
411
|
-
|
|
412
|
-
```javascript
|
|
413
|
-
import {
|
|
414
|
-
// Tagged template functions
|
|
415
|
-
html, // For HTML templates
|
|
416
|
-
svg, // For SVG templates
|
|
417
|
-
|
|
418
|
-
// Special values
|
|
419
|
-
nothing, // Render nothing
|
|
420
|
-
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.
|
|
421
306
|
|
|
422
|
-
|
|
423
|
-
render,
|
|
307
|
+
### @Subscribe(stateKey)
|
|
424
308
|
|
|
425
|
-
|
|
426
|
-
TemplateResult,
|
|
427
|
-
SVGTemplateResult,
|
|
428
|
-
RenderOptions
|
|
429
|
-
} from '@aegis-framework/pandora';
|
|
430
|
-
```
|
|
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.
|
|
431
310
|
|
|
432
|
-
|
|
311
|
+
```typescript
|
|
312
|
+
Registry.setState('app.theme', 'light');
|
|
433
313
|
|
|
434
|
-
|
|
314
|
+
@Register('themed-card')
|
|
315
|
+
class ThemedCard extends Component {
|
|
316
|
+
@Subscribe('app.theme') theme!: string;
|
|
435
317
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
return `<div>${this.props.name}</div>`;
|
|
318
|
+
render() {
|
|
319
|
+
return html`<div class="card theme-${this.theme}">...</div>`;
|
|
320
|
+
}
|
|
440
321
|
}
|
|
441
322
|
|
|
442
|
-
//
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
<div>
|
|
446
|
-
${this.props.name}
|
|
447
|
-
<button @click=${() => this.handleClick()}>Click</button>
|
|
448
|
-
</div>
|
|
449
|
-
`;
|
|
450
|
-
}
|
|
323
|
+
// All ThemedCard instances re-render automatically
|
|
324
|
+
Registry.setState('app.theme', 'dark');
|
|
325
|
+
```
|
|
451
326
|
|
|
452
|
-
|
|
453
|
-
// Can use async/await OR return a Promise directly
|
|
454
|
-
async render() {
|
|
455
|
-
const data = await fetchUserData();
|
|
456
|
-
return html`<div>Hello, ${data.name}!</div>`;
|
|
457
|
-
}
|
|
327
|
+
Setting the property from inside the component also updates the global state, so every other consumer sees the change too.
|
|
458
328
|
|
|
459
|
-
|
|
460
|
-
render() {
|
|
461
|
-
return fetchUserData().then(data =>
|
|
462
|
-
html`<div>Hello, ${data.name}!</div>`
|
|
463
|
-
);
|
|
464
|
-
}
|
|
465
|
-
```
|
|
329
|
+
### @Query(selector) / @QueryAll(selector)
|
|
466
330
|
|
|
467
|
-
|
|
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.
|
|
468
332
|
|
|
469
|
-
|
|
333
|
+
```typescript
|
|
334
|
+
@Register('my-form')
|
|
335
|
+
class MyForm extends Component {
|
|
336
|
+
@Query('.submit-btn') submitButton!: HTMLButtonElement;
|
|
337
|
+
@QueryAll('.field') fields!: NodeListOf<HTMLInputElement>;
|
|
470
338
|
|
|
471
|
-
|
|
472
|
-
|
|
339
|
+
async didMount() {
|
|
340
|
+
this.submitButton.focus();
|
|
341
|
+
}
|
|
473
342
|
|
|
474
|
-
class MyComponent extends Component {
|
|
475
343
|
render() {
|
|
476
344
|
return html`
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
<!-- List rendering -->
|
|
481
|
-
<ul>
|
|
482
|
-
${this.state.items.map(item => html`<li>${item}</li>`)}
|
|
483
|
-
</ul>
|
|
484
|
-
|
|
485
|
-
<!-- Event binding -->
|
|
486
|
-
<button @click=${(e) => this.handleClick(e)}>Click</button>
|
|
487
|
-
|
|
488
|
-
<!-- Property binding -->
|
|
489
|
-
<input .value=${this.state.name}>
|
|
490
|
-
|
|
491
|
-
<!-- Boolean attributes -->
|
|
492
|
-
<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>
|
|
493
348
|
`;
|
|
494
349
|
}
|
|
495
350
|
}
|
|
496
351
|
```
|
|
497
352
|
|
|
498
|
-
###
|
|
353
|
+
### @Slot(name?)
|
|
499
354
|
|
|
500
|
-
|
|
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.
|
|
501
356
|
|
|
502
|
-
```
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
</my-card>
|
|
508
|
-
```
|
|
357
|
+
```typescript
|
|
358
|
+
@Register('card-layout')
|
|
359
|
+
class CardLayout extends ShadowComponent {
|
|
360
|
+
@Slot() defaultSlot!: HTMLSlotElement;
|
|
361
|
+
@Slot('header') headerSlot!: HTMLSlotElement;
|
|
509
362
|
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
return `
|
|
515
|
-
<div class="card">
|
|
516
|
-
<div class="card-body">
|
|
517
|
-
${this.slotContent}
|
|
518
|
-
</div>
|
|
519
|
-
</div>
|
|
520
|
-
`;
|
|
363
|
+
async didMount() {
|
|
364
|
+
this.headerSlot?.addEventListener('slotchange', () => {
|
|
365
|
+
console.log('Header slot changed');
|
|
366
|
+
});
|
|
521
367
|
}
|
|
522
|
-
}
|
|
523
368
|
|
|
524
|
-
// Or with lit-html
|
|
525
|
-
class MyCard extends Component {
|
|
526
369
|
render() {
|
|
527
370
|
return html`
|
|
528
|
-
<div class="
|
|
529
|
-
|
|
530
|
-
${this.slotContent}
|
|
531
|
-
</div>
|
|
532
|
-
</div>
|
|
371
|
+
<div class="header"><slot name="header"></slot></div>
|
|
372
|
+
<div class="body"><slot></slot></div>
|
|
533
373
|
`;
|
|
534
374
|
}
|
|
535
375
|
}
|
|
536
376
|
```
|
|
537
377
|
|
|
538
|
-
|
|
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.
|
|
539
379
|
|
|
540
|
-
|
|
380
|
+
### @Listen(event, options?)
|
|
541
381
|
|
|
542
|
-
|
|
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.
|
|
543
383
|
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
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
|
+
}
|
|
547
393
|
|
|
548
|
-
|
|
394
|
+
@Listen('resize', { target: 'window' })
|
|
395
|
+
handleResize() {
|
|
396
|
+
this.recalculatePosition();
|
|
397
|
+
}
|
|
549
398
|
|
|
550
|
-
|
|
551
|
-
|
|
399
|
+
@Listen('keydown', { target: 'document', capture: true })
|
|
400
|
+
handleKeydown(e: KeyboardEvent) {
|
|
401
|
+
if (e.key === 'Escape') this.close();
|
|
402
|
+
}
|
|
552
403
|
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
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();
|
|
557
408
|
}
|
|
558
409
|
}
|
|
559
|
-
|
|
560
|
-
// No need for: Registry.register('my-button', MyButton);
|
|
561
410
|
```
|
|
562
411
|
|
|
563
|
-
|
|
412
|
+
**Options:**
|
|
564
413
|
|
|
565
|
-
|
|
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 |
|
|
566
421
|
|
|
567
|
-
|
|
568
|
-
import { Component, Register, Consumer, html } from '@aegis-framework/pandora';
|
|
569
|
-
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.
|
|
570
423
|
|
|
571
|
-
|
|
572
|
-
Registry.setState('user.theme', 'light');
|
|
573
|
-
Registry.setState('user.name', 'Guest');
|
|
424
|
+
### @Emitter(eventName)
|
|
574
425
|
|
|
575
|
-
|
|
576
|
-
class UserGreeting extends Component {
|
|
577
|
-
@Consumer('user.theme')
|
|
578
|
-
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.
|
|
579
427
|
|
|
580
|
-
|
|
581
|
-
|
|
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
|
+
}
|
|
582
442
|
|
|
583
443
|
render() {
|
|
584
|
-
return html
|
|
585
|
-
<div class="theme-${this.theme}">
|
|
586
|
-
Hello, ${this.name}!
|
|
587
|
-
</div>
|
|
588
|
-
`;
|
|
444
|
+
return html`<input type="file" @change=${this.handleChange.bind(this)}>`;
|
|
589
445
|
}
|
|
590
446
|
}
|
|
591
|
-
|
|
592
|
-
// Later, updating state automatically updates all @Consumer properties
|
|
593
|
-
Registry.setState('user.name', 'Alice'); // All UserGreeting instances re-render
|
|
594
447
|
```
|
|
595
448
|
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
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
|
+
```
|
|
599
455
|
|
|
600
|
-
|
|
601
|
-
import { Component, Register, Prop, html } from '@aegis-framework/pandora';
|
|
456
|
+
### @Style(css)
|
|
602
457
|
|
|
603
|
-
|
|
604
|
-
class MyInput extends Component {
|
|
605
|
-
@Prop()
|
|
606
|
-
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.
|
|
607
459
|
|
|
608
|
-
|
|
609
|
-
maxLength: number = 100;
|
|
460
|
+
**Object form:**
|
|
610
461
|
|
|
611
|
-
|
|
612
|
-
|
|
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 = '';
|
|
613
471
|
|
|
614
472
|
render() {
|
|
615
473
|
return html`
|
|
616
|
-
<
|
|
617
|
-
|
|
618
|
-
maxlength=${this.maxLength}
|
|
619
|
-
?disabled=${this.disabled}
|
|
620
|
-
>
|
|
474
|
+
<h3>${this.title}</h3>
|
|
475
|
+
<div class="body">${this.slotContent}</div>
|
|
621
476
|
`;
|
|
622
477
|
}
|
|
623
478
|
}
|
|
624
479
|
```
|
|
625
480
|
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
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 { /* ... */ }
|
|
629
490
|
```
|
|
630
491
|
|
|
631
|
-
|
|
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.
|
|
632
493
|
|
|
633
|
-
|
|
494
|
+
### @ClassList(map)
|
|
634
495
|
|
|
635
|
-
|
|
636
|
-
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:
|
|
637
497
|
|
|
638
|
-
|
|
639
|
-
|
|
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).
|
|
640
500
|
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
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 {}
|
|
644
512
|
}
|
|
645
|
-
|
|
646
|
-
// Get the component class
|
|
647
|
-
const MyComponentClass = Registry.get('my-tag');
|
|
648
|
-
|
|
649
|
-
// Evolve an existing component (hot reload)
|
|
650
|
-
Registry.evolve('my-tag', UpdatedComponent);
|
|
651
|
-
|
|
652
|
-
// Evolve and re-render all existing instances
|
|
653
|
-
Registry.evolve('my-tag', UpdatedComponent, true);
|
|
654
|
-
|
|
655
|
-
// Get all instances of a component
|
|
656
|
-
const instances = Registry.instances('my-tag');
|
|
657
|
-
|
|
658
|
-
// Execute callback on all instances
|
|
659
|
-
Registry.instances('my-tag', (instance) => {
|
|
660
|
-
instance.setProps({ updated: true });
|
|
661
|
-
});
|
|
662
|
-
|
|
663
|
-
// Create new instance with props
|
|
664
|
-
const element = Registry.instantiate('my-tag', { title: 'Hello' });
|
|
665
513
|
```
|
|
666
514
|
|
|
667
|
-
|
|
515
|
+
Initial classes are applied on `connectedCallback`, and subsequent updates react to field changes automatically. You can mix both forms in the same map.
|
|
668
516
|
|
|
669
|
-
|
|
517
|
+
## Component API
|
|
670
518
|
|
|
671
|
-
|
|
672
|
-
|--------|-------------|
|
|
673
|
-
| `register(tag, component)` | Register a new component with the custom elements registry |
|
|
674
|
-
| `has(tag)` | Check if a component is registered |
|
|
675
|
-
| `get(tag)` | Get the component class by tag name |
|
|
676
|
-
| `evolve(tag, component, rerender?)` | Update an existing component's implementation (optionally re-render instances) |
|
|
677
|
-
| `instances(tag, callback?)` | Get all instances or execute callback on each |
|
|
678
|
-
| `instantiate(tag, props)` | Create a new instance with the given props |
|
|
519
|
+
### Status Getters
|
|
679
520
|
|
|
680
|
-
|
|
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 |
|
|
681
527
|
|
|
682
|
-
|
|
683
|
-
|-----------------|-------------|
|
|
684
|
-
| `debug` | Boolean property - enable/disable debug logging |
|
|
685
|
-
| `log(message, data?)` | Log a debug message (only when debug is enabled) |
|
|
686
|
-
| `list()` | Get array of all registered component tags |
|
|
687
|
-
| `stats(tag?)` | Get stats for one or all components (instanceCount, isRegistered, isLazy) |
|
|
528
|
+
### Rendering
|
|
688
529
|
|
|
689
|
-
|
|
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 |
|
|
690
537
|
|
|
691
|
-
|
|
692
|
-
|--------|-------------|
|
|
693
|
-
| `onMount(callback)` | Register callback for when any component mounts (returns unsubscribe) |
|
|
694
|
-
| `onUnmount(callback)` | Register callback for when any component unmounts (returns unsubscribe) |
|
|
538
|
+
### Styles
|
|
695
539
|
|
|
696
|
-
|
|
540
|
+
| Method | Signature | Description |
|
|
541
|
+
|--------|-----------|-------------|
|
|
542
|
+
| `setStyle(style, reset?)` | `(Style \| string, boolean?) => Style` | Apply styles; `reset=true` replaces instead of merging |
|
|
697
543
|
|
|
698
|
-
|
|
699
|
-
|--------|-------------|
|
|
700
|
-
| `onError(callback)` | Register global error handler for component errors (returns unsubscribe) |
|
|
544
|
+
### Events
|
|
701
545
|
|
|
702
|
-
|
|
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) |
|
|
703
552
|
|
|
704
|
-
|
|
705
|
-
|--------|-------------|
|
|
706
|
-
| `alias(aliasTag, originalTag)` | Create an alias tag name for an existing component |
|
|
707
|
-
| `isAlias(tag)` | Check if a tag is an alias |
|
|
708
|
-
| `getOriginalTag(aliasTag)` | Get the original tag name for an alias |
|
|
553
|
+
### DOM Helpers
|
|
709
554
|
|
|
710
|
-
|
|
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 |
|
|
711
559
|
|
|
712
|
-
|
|
713
|
-
|--------|-------------|
|
|
714
|
-
| `lazy(tag, loader)` | Register a component to be loaded on first use |
|
|
715
|
-
| `isLazy(tag)` | Check if a component is registered as lazy |
|
|
716
|
-
| `preload(tag)` | Preload a lazy component without mounting |
|
|
560
|
+
For `ShadowComponent`, `query` and `queryAll` search within the shadow root.
|
|
717
561
|
|
|
718
|
-
|
|
562
|
+
### Registration
|
|
719
563
|
|
|
720
|
-
| Method | Description |
|
|
721
|
-
|
|
722
|
-
| `
|
|
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`) |
|
|
723
568
|
|
|
724
|
-
|
|
569
|
+
## Lifecycle
|
|
725
570
|
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
| `deleteState(key)` | Delete a state value |
|
|
732
|
-
| `subscribe(key, callback)` | Subscribe to state changes (returns unsubscribe function) |
|
|
733
|
-
| `unsubscribe(key, callback)` | Unsubscribe from state changes |
|
|
734
|
-
| `getAllState()` | Get a copy of all global state |
|
|
735
|
-
| `clearState()` | Clear all global state |
|
|
571
|
+
```
|
|
572
|
+
Mount: willMount -> render -> didMount (first time) / didReconnect (subsequent)
|
|
573
|
+
Unmount: willUnmount -> didUnmount
|
|
574
|
+
Changes: @Watch callbacks -> didChange -> queued microtask render
|
|
575
|
+
```
|
|
736
576
|
|
|
737
|
-
|
|
577
|
+
All lifecycle hooks are async. Override only the hooks you need.
|
|
738
578
|
|
|
739
|
-
|
|
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 |
|
|
740
586
|
|
|
741
|
-
|
|
742
|
-
import { Registry } from '@aegis-framework/pandora';
|
|
587
|
+
### Lifecycle Events
|
|
743
588
|
|
|
744
|
-
|
|
745
|
-
Registry.setState('theme', 'dark');
|
|
746
|
-
Registry.setState('user', { name: 'John', id: 123 });
|
|
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.
|
|
747
590
|
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
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 }` |
|
|
751
595
|
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
}
|
|
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
|
+
});
|
|
756
601
|
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
console.log(`Theme changed from ${oldValue} to ${newValue}`);
|
|
602
|
+
document.addEventListener('pandora:unmount', (e) => {
|
|
603
|
+
console.log(`<${e.detail.tag}> is unmounting`);
|
|
760
604
|
});
|
|
605
|
+
```
|
|
761
606
|
|
|
762
|
-
|
|
763
|
-
Registry.setState('theme', 'light'); // Logs: "Theme changed from dark to light"
|
|
607
|
+
In lit-html templates or HTML event binding:
|
|
764
608
|
|
|
765
|
-
|
|
766
|
-
|
|
609
|
+
```html
|
|
610
|
+
<game-screen @pandora:ready="onScreenReady"></game-screen>
|
|
611
|
+
```
|
|
767
612
|
|
|
768
|
-
|
|
769
|
-
Registry.deleteState('theme');
|
|
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.
|
|
770
614
|
|
|
771
|
-
|
|
772
|
-
const allState = Registry.getAllState();
|
|
615
|
+
### didChange(property, oldValue, newValue, source?)
|
|
773
616
|
|
|
774
|
-
|
|
775
|
-
Registry.clearState();
|
|
776
|
-
```
|
|
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.
|
|
777
618
|
|
|
778
|
-
|
|
619
|
+
**Timing:** fires synchronously in the setter, after `@Watch` callbacks, before the queued render.
|
|
779
620
|
|
|
780
|
-
|
|
621
|
+
**Source values:**
|
|
781
622
|
|
|
782
|
-
|
|
783
|
-
|
|
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 |
|
|
631
|
+
|
|
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
|
+
}
|
|
643
|
+
|
|
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
|
+
}
|
|
651
|
+
```
|
|
652
|
+
|
|
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.
|
|
784
654
|
|
|
785
|
-
|
|
786
|
-
Registry.debug = true;
|
|
655
|
+
### Lifecycle Example
|
|
787
656
|
|
|
788
|
-
|
|
789
|
-
|
|
657
|
+
```typescript
|
|
658
|
+
@Register('data-list')
|
|
659
|
+
class DataList extends Component {
|
|
660
|
+
@State() items: string[] = [];
|
|
661
|
+
private _pollInterval: number | undefined;
|
|
790
662
|
|
|
791
|
-
|
|
792
|
-
|
|
663
|
+
async willMount() {
|
|
664
|
+
// Runs on every connect -- safe for synchronous setup
|
|
665
|
+
}
|
|
793
666
|
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
667
|
+
async didMount() {
|
|
668
|
+
// Runs once -- safe for subscriptions and timers
|
|
669
|
+
this._pollInterval = setInterval(() => this.refresh(), 5000);
|
|
670
|
+
await this.refresh();
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
async didReconnect() {
|
|
674
|
+
// Component was re-inserted (e.g., moved in the DOM)
|
|
675
|
+
await this.refresh();
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
async willUnmount() {
|
|
679
|
+
clearInterval(this._pollInterval);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
async refresh() {
|
|
683
|
+
this.items = await fetchItems();
|
|
684
|
+
}
|
|
797
685
|
|
|
798
|
-
|
|
799
|
-
|
|
686
|
+
render() {
|
|
687
|
+
return html`<ul>${this.items.map(i => html`<li>${i}</li>`)}</ul>`;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
800
690
|
```
|
|
801
691
|
|
|
802
|
-
##
|
|
692
|
+
## Decorator Inheritance
|
|
803
693
|
|
|
804
|
-
|
|
694
|
+
When you subclass a decorated component, it helps to know how decorators interact with inheritance:
|
|
805
695
|
|
|
806
|
-
|
|
807
|
-
import { Registry } from '@aegis-framework/pandora';
|
|
696
|
+
### @Watch and Method Overrides
|
|
808
697
|
|
|
809
|
-
|
|
810
|
-
const unsubscribeMount = Registry.onMount((component, tag) => {
|
|
811
|
-
console.log(`Component <${tag}> mounted`, component);
|
|
812
|
-
});
|
|
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`:
|
|
813
699
|
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
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
|
+
}
|
|
709
|
+
|
|
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
|
+
}
|
|
818
728
|
|
|
819
|
-
//
|
|
820
|
-
|
|
821
|
-
|
|
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
|
+
}
|
|
822
736
|
```
|
|
823
737
|
|
|
824
|
-
|
|
738
|
+
**Rules:**
|
|
825
739
|
|
|
826
|
-
|
|
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.
|
|
827
744
|
|
|
828
|
-
|
|
829
|
-
import { Registry } from '@aegis-framework/pandora';
|
|
745
|
+
### @State and @Attribute Inheritance
|
|
830
746
|
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
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;
|
|
835
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.
|
|
836
830
|
|
|
837
|
-
|
|
838
|
-
|
|
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);
|
|
839
843
|
```
|
|
840
844
|
|
|
841
|
-
|
|
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:
|
|
842
850
|
|
|
843
|
-
|
|
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
|
+
}
|
|
884
|
+
```
|
|
885
|
+
|
|
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.
|
|
889
|
+
|
|
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:**
|
|
844
905
|
|
|
845
906
|
```javascript
|
|
846
|
-
|
|
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
|
+
```
|
|
847
914
|
|
|
848
|
-
|
|
849
|
-
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.
|
|
850
916
|
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
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';
|
|
854
928
|
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
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';
|
|
858
936
|
|
|
859
|
-
|
|
860
|
-
|
|
937
|
+
render() {
|
|
938
|
+
return html`
|
|
939
|
+
<button class="btn-${this.variant}">
|
|
940
|
+
<slot></slot>
|
|
941
|
+
</button>
|
|
942
|
+
`;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
861
945
|
```
|
|
862
946
|
|
|
863
947
|
```html
|
|
864
|
-
|
|
865
|
-
<my-button>Click me</my-button>
|
|
866
|
-
<app-button>Click me</app-button>
|
|
867
|
-
<custom-button>Click me</custom-button>
|
|
948
|
+
<fancy-button variant="secondary">Click me</fancy-button>
|
|
868
949
|
```
|
|
869
950
|
|
|
870
|
-
|
|
951
|
+
Access the shadow root via `element.shadowRoot`.
|
|
952
|
+
|
|
953
|
+
## Registry
|
|
871
954
|
|
|
872
|
-
|
|
955
|
+
The Registry is Pandora's central hub for component management, global state, and cross-cutting concerns.
|
|
873
956
|
|
|
874
|
-
|
|
957
|
+
### Component Management
|
|
958
|
+
|
|
959
|
+
```typescript
|
|
875
960
|
import { Registry } from '@aegis-framework/pandora';
|
|
876
961
|
|
|
877
|
-
// Register
|
|
878
|
-
Registry.
|
|
962
|
+
// Register (usually handled by @Register decorator)
|
|
963
|
+
Registry.register('my-tag', MyComponent);
|
|
879
964
|
|
|
880
|
-
//
|
|
881
|
-
//
|
|
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
|
+
```
|
|
882
991
|
|
|
883
|
-
|
|
884
|
-
Registry.isLazy('heavy-chart'); // true (before loaded), false (after loaded)
|
|
992
|
+
### Lazy Loading
|
|
885
993
|
|
|
886
|
-
|
|
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'));
|
|
998
|
+
|
|
999
|
+
// Check status
|
|
1000
|
+
Registry.isLazy('heavy-chart') // true before loaded
|
|
1001
|
+
|
|
1002
|
+
// Preload eagerly (e.g., on route anticipation)
|
|
887
1003
|
await Registry.preload('heavy-chart');
|
|
888
1004
|
```
|
|
889
1005
|
|
|
890
|
-
###
|
|
1006
|
+
### Aliases
|
|
891
1007
|
|
|
892
|
-
|
|
893
|
-
// Components are loaded only when first mounted
|
|
894
|
-
Registry.lazy('data-table', async () => {
|
|
895
|
-
const module = await import('./components/DataTable.js');
|
|
896
|
-
return module.default;
|
|
897
|
-
});
|
|
1008
|
+
Create alternative tag names for an existing component:
|
|
898
1009
|
|
|
899
|
-
|
|
1010
|
+
```typescript
|
|
1011
|
+
Registry.register('my-button', MyButton);
|
|
1012
|
+
Registry.alias('app-button', 'my-button');
|
|
1013
|
+
Registry.alias('ui-button', 'my-button');
|
|
1014
|
+
|
|
1015
|
+
Registry.isAlias('app-button') // true
|
|
1016
|
+
Registry.getOriginalTag('app-button') // 'my-button'
|
|
900
1017
|
```
|
|
901
1018
|
|
|
902
|
-
|
|
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
|
+
```
|
|
903
1025
|
|
|
904
|
-
|
|
1026
|
+
### Lifecycle Hooks
|
|
905
1027
|
|
|
906
|
-
|
|
907
|
-
import { Registry } from '@aegis-framework/pandora';
|
|
1028
|
+
Listen to mount and unmount events across all registered components:
|
|
908
1029
|
|
|
909
|
-
|
|
910
|
-
const
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
};
|
|
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`);
|
|
916
1037
|
});
|
|
917
1038
|
|
|
918
|
-
//
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
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 });
|
|
923
1052
|
});
|
|
1053
|
+
```
|
|
1054
|
+
|
|
1055
|
+
### Middleware
|
|
1056
|
+
|
|
1057
|
+
Intercept and transform render output across all components:
|
|
924
1058
|
|
|
925
|
-
|
|
926
|
-
//
|
|
927
|
-
|
|
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) => {
|
|
928
1063
|
if (renderType === 'string') {
|
|
929
|
-
|
|
930
|
-
return value.replace('{{timestamp}}', Date.now());
|
|
1064
|
+
return value.replace(/{{version}}/g, '1.0.0');
|
|
931
1065
|
}
|
|
932
|
-
// lit-html
|
|
933
|
-
return value;
|
|
1066
|
+
return value; // pass lit-html results through unchanged
|
|
934
1067
|
});
|
|
935
1068
|
|
|
936
|
-
//
|
|
937
|
-
|
|
938
|
-
unsubscribeState();
|
|
939
|
-
unsubscribeRender();
|
|
1069
|
+
// Remove middleware
|
|
1070
|
+
off();
|
|
940
1071
|
```
|
|
941
1072
|
|
|
942
|
-
###
|
|
1073
|
+
### Debug Mode
|
|
943
1074
|
|
|
944
|
-
```
|
|
945
|
-
|
|
946
|
-
// Log all state changes
|
|
947
|
-
Registry.use('state', (component, state) => {
|
|
948
|
-
console.log(`[${component.static.tag}] setState:`, state);
|
|
949
|
-
return state;
|
|
950
|
-
});
|
|
1075
|
+
```typescript
|
|
1076
|
+
Registry.debug = true; // enables [Pandora] console logs for all lifecycle events
|
|
951
1077
|
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
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
|
+
}
|
|
961
1118
|
}
|
|
1119
|
+
|
|
1120
|
+
// All DateDisplay instances re-render automatically
|
|
1121
|
+
Registry.setState('app.locale', 'fr');
|
|
962
1122
|
```
|
|
963
1123
|
|
|
964
|
-
###
|
|
1124
|
+
### Typed State
|
|
965
1125
|
|
|
966
|
-
|
|
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')
|
|
967
1150
|
class ThemeToggle extends Component {
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
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
|
+
`;
|
|
973
1159
|
}
|
|
1160
|
+
}
|
|
1161
|
+
```
|
|
974
1162
|
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
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);
|
|
980
1232
|
});
|
|
981
1233
|
|
|
982
|
-
|
|
1234
|
+
// 2. Apply the effect on first construction
|
|
1235
|
+
context.addInitializer(function (this: unknown) {
|
|
1236
|
+
applyMyEffect(this as Component, propertyKey, config);
|
|
1237
|
+
});
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
|
|
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
|
+
});
|
|
1246
|
+
|
|
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 });
|
|
983
1267
|
}
|
|
1268
|
+
}
|
|
1269
|
+
```
|
|
984
1270
|
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
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:
|
|
1276
|
+
|
|
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));
|
|
989
1303
|
}
|
|
990
|
-
}
|
|
1304
|
+
});
|
|
991
1305
|
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
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);
|
|
1310
|
+
}
|
|
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
|
+
`;
|
|
995
1328
|
}
|
|
1329
|
+
}
|
|
1330
|
+
```
|
|
1331
|
+
|
|
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:
|
|
996
1337
|
|
|
997
|
-
|
|
998
|
-
|
|
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;
|
|
999
1369
|
}
|
|
1000
1370
|
|
|
1001
1371
|
render() {
|
|
1002
|
-
return
|
|
1372
|
+
return html`
|
|
1373
|
+
<input class="search-input" placeholder="Search...">
|
|
1374
|
+
<div class="results">Searching for: ${this.query}</div>
|
|
1375
|
+
`;
|
|
1003
1376
|
}
|
|
1004
1377
|
}
|
|
1005
1378
|
```
|
|
1006
1379
|
|
|
1007
|
-
|
|
1380
|
+
The field itself updates immediately (so `@Watch` and `didChange` fire synchronously), but the template only re-renders after 250ms of inactivity.
|
|
1008
1381
|
|
|
1009
|
-
|
|
1382
|
+
### Example: @MediaQuery
|
|
1010
1383
|
|
|
1011
|
-
|
|
1012
|
-
- **Fast updates** - Uses `replaceSync()` for synchronous style changes
|
|
1013
|
-
- **No DOM overhead** - No `<style>` element parsing
|
|
1384
|
+
A reactive boolean that tracks a CSS media query:
|
|
1014
1385
|
|
|
1015
|
-
|
|
1386
|
+
```typescript
|
|
1387
|
+
import { reactive, addDecoratorEffect, addTeardown, Component } from '@aegis-framework/pandora';
|
|
1016
1388
|
|
|
1017
|
-
|
|
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>;
|
|
1018
1393
|
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
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
|
+
`;
|
|
1027
1431
|
}
|
|
1028
|
-
}
|
|
1029
|
-
// Generates: my-element h2 { color: blue; ... }
|
|
1432
|
+
}
|
|
1030
1433
|
```
|
|
1031
1434
|
|
|
1032
|
-
###
|
|
1435
|
+
### Example: @FetchData
|
|
1033
1436
|
|
|
1034
|
-
|
|
1437
|
+
A reactive field that fetches data from a URL and auto-renders when the response arrives:
|
|
1035
1438
|
|
|
1036
|
-
```
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
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>`;
|
|
1048
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
|
|
1049
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
|
+
}
|
|
1050
1597
|
```
|
|
1051
1598
|
|
|
1052
|
-
|
|
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>
|
|
1605
|
+
```
|
|
1053
1606
|
|
|
1054
|
-
|
|
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.
|
|
1610
|
+
|
|
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.
|
|
1055
1612
|
|
|
1056
1613
|
```javascript
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
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
|
+
});
|
|
1061
1624
|
}
|
|
1062
|
-
|
|
1625
|
+
|
|
1626
|
+
render() {
|
|
1627
|
+
return html`<button>Count: ${this.count}</button>`;
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
Registry.register('counter-element', CounterElement);
|
|
1063
1632
|
```
|
|
1064
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
|
+
});
|
|
1672
|
+
```
|
|
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
|
+
|
|
1065
1676
|
## Browser Usage
|
|
1066
1677
|
|
|
1067
|
-
|
|
1678
|
+
Pandora ships a pre-bundled browser file you can drop in without a bundler:
|
|
1068
1679
|
|
|
1069
1680
|
```html
|
|
1070
|
-
<script src="
|
|
1681
|
+
<script src="node_modules/@aegis-framework/pandora/dist/pandora.browser.js"></script>
|
|
1071
1682
|
<script>
|
|
1072
|
-
const { Component,
|
|
1683
|
+
const { Component, Registry, html } = Pandora;
|
|
1073
1684
|
|
|
1074
1685
|
class CounterElement extends Component {
|
|
1075
|
-
|
|
1076
|
-
super();
|
|
1077
|
-
this.state = { count: 0 };
|
|
1078
|
-
}
|
|
1686
|
+
count = 0;
|
|
1079
1687
|
|
|
1080
1688
|
didMount() {
|
|
1081
1689
|
this.on('click', () => {
|
|
1082
|
-
this.
|
|
1690
|
+
this.count++;
|
|
1083
1691
|
this.forceRender();
|
|
1084
1692
|
});
|
|
1085
1693
|
}
|
|
1086
1694
|
|
|
1087
1695
|
render() {
|
|
1088
|
-
return html`<button>Count: ${this.
|
|
1696
|
+
return html`<button>Count: ${this.count}</button>`;
|
|
1089
1697
|
}
|
|
1090
1698
|
}
|
|
1091
1699
|
|
|
@@ -1095,6 +1703,38 @@ For direct browser usage without a bundler:
|
|
|
1095
1703
|
<counter-element></counter-element>
|
|
1096
1704
|
```
|
|
1097
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
|
+
|
|
1098
1738
|
## License
|
|
1099
1739
|
|
|
1100
|
-
|
|
1740
|
+
Released under the [MIT License](./LICENSE).
|