@aegis-framework/pandora 0.6.3 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +236 -29
- package/dist/pandora.browser.js +15 -26
- package/dist/pandora.browser.js.map +38 -37
- package/dist/pandora.js +15 -26
- package/dist/pandora.js.map +37 -36
- package/dist/types/Component.d.ts +112 -18
- package/dist/types/Component.d.ts.map +1 -1
- package/dist/types/Decorators.d.ts +65 -33
- package/dist/types/Decorators.d.ts.map +1 -1
- package/dist/types/Registry.d.ts +51 -13
- package/dist/types/Registry.d.ts.map +1 -1
- package/dist/types/RenderState.d.ts +29 -0
- package/dist/types/RenderState.d.ts.map +1 -0
- package/dist/types/ShadowComponent.d.ts +8 -3
- package/dist/types/ShadowComponent.d.ts.map +1 -1
- package/dist/types/Testing.d.ts +6 -6
- package/dist/types/Testing.d.ts.map +1 -1
- package/dist/types/TypedState.d.ts +1 -1
- package/dist/types/TypedState.d.ts.map +1 -1
- package/dist/types/Types.d.ts +4 -2
- package/dist/types/Types.d.ts.map +1 -1
- package/dist/types/Util.d.ts +142 -62
- package/dist/types/Util.d.ts.map +1 -1
- package/dist/types/browser.d.ts +1 -1
- package/dist/types/browser.d.ts.map +1 -1
- package/dist/types/index.d.ts +20 -17
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +31 -24
package/README.md
CHANGED
|
@@ -35,6 +35,72 @@ yarn add @aegis-framework/pandora
|
|
|
35
35
|
bun add @aegis-framework/pandora
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
+
## Setup
|
|
39
|
+
|
|
40
|
+
Pandora's decorators are standard [TC39 decorators](https://github.com/tc39/proposal-decorators) with decorator metadata -- not TypeScript's legacy `experimentalDecorators`. No browser runs them natively yet, so your toolchain has to compile them.
|
|
41
|
+
|
|
42
|
+
**TypeScript 5.2 or newer**, with `experimentalDecorators` left off (it's off by default). Turning it on switches TypeScript, Bun, and esbuild to the legacy decorator semantics, and every Pandora decorator will break:
|
|
43
|
+
|
|
44
|
+
```jsonc
|
|
45
|
+
// tsconfig.json
|
|
46
|
+
{
|
|
47
|
+
"compilerOptions": {
|
|
48
|
+
"target": "ES2022", // or newer
|
|
49
|
+
"useDefineForClassFields": true // the default for ES2022+ targets
|
|
50
|
+
// no "experimentalDecorators"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Build tools:**
|
|
56
|
+
|
|
57
|
+
| Tool | Setup |
|
|
58
|
+
|------|-------|
|
|
59
|
+
| `tsc` 5.2+ | Works as-is |
|
|
60
|
+
| Bun 1.3+ (runtime and `bun build`) | Works as-is |
|
|
61
|
+
| esbuild 0.21+, Vite 5--7 | Works as-is |
|
|
62
|
+
| Vite 8+ | Needs the plugin below -- Vite 8 transforms TypeScript with Oxc, which only compiles legacy decorators |
|
|
63
|
+
|
|
64
|
+
On Vite 8 and later, run esbuild over your TypeScript first (`bun add -d esbuild`):
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
// vite.config.ts
|
|
68
|
+
import { defineConfig, type Plugin } from 'vite';
|
|
69
|
+
import { transform } from 'esbuild';
|
|
70
|
+
|
|
71
|
+
function lowerStandardDecorators(): Plugin {
|
|
72
|
+
return {
|
|
73
|
+
name: 'lower-standard-decorators',
|
|
74
|
+
enforce: 'pre',
|
|
75
|
+
async transform(code, id) {
|
|
76
|
+
const path = id.split('?')[0];
|
|
77
|
+
|
|
78
|
+
if (!/\.[cm]?tsx?$/.test(path) || !code.includes('@')) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const result = await transform(code, {
|
|
83
|
+
loader: path.endsWith('x') ? 'tsx' : 'ts',
|
|
84
|
+
target: 'es2024',
|
|
85
|
+
sourcefile: path,
|
|
86
|
+
sourcemap: true,
|
|
87
|
+
tsconfigRaw: { compilerOptions: { experimentalDecorators: false, useDefineForClassFields: true } },
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
return { code: result.code, map: result.map };
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export default defineConfig({
|
|
96
|
+
plugins: [lowerStandardDecorators()],
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
No build step at all? See [Browser Usage](#browser-usage) and [Non-Decorator Usage](#non-decorator-usage).
|
|
101
|
+
|
|
102
|
+
If a decorator does get compiled the legacy way, Pandora stops at once with `[Pandora] @State was called as a legacy decorator`, naming the setting to change, instead of failing later in a way that doesn't say why.
|
|
103
|
+
|
|
38
104
|
## Quick Start
|
|
39
105
|
|
|
40
106
|
The simplest component you can build: a prop that auto-renders on change.
|
|
@@ -60,7 +126,7 @@ That's all you need. No constructor, no `forceRender()`, no lifecycle boilerplat
|
|
|
60
126
|
|
|
61
127
|
## Decorators Reference
|
|
62
128
|
|
|
63
|
-
Pandora uses [TC39
|
|
129
|
+
Pandora uses standard [TC39 decorators](https://github.com/tc39/proposal-decorators) -- see [Setup](#setup) for the TypeScript and build tool configuration they need. For environments without decorator support, see [Non-Decorator Usage](#non-decorator-usage).
|
|
64
130
|
|
|
65
131
|
### @Register(tagName)
|
|
66
132
|
|
|
@@ -157,7 +223,7 @@ class GameScreen extends Component {
|
|
|
157
223
|
|
|
158
224
|
| Option | Type | Default | Description |
|
|
159
225
|
|--------|------|---------|-------------|
|
|
160
|
-
| `attribute` | `string \|
|
|
226
|
+
| `attribute` | `string \| boolean` | `false` | Mirror primitive values to an attribute: `true` uses the field name, a string names the attribute, `false` keeps it property-only |
|
|
161
227
|
| `equals` | `(a, b) => boolean` | `===` | Custom equality check |
|
|
162
228
|
|
|
163
229
|
**When to use @Property vs @State:**
|
|
@@ -209,14 +275,14 @@ For inputs that hold complex values (objects, arrays, functions), use `@Property
|
|
|
209
275
|
```typescript
|
|
210
276
|
@Register('data-table')
|
|
211
277
|
class DataTable extends Component {
|
|
212
|
-
@Attribute()
|
|
278
|
+
@Attribute() heading = '';
|
|
213
279
|
@Property() columns: string[] = [];
|
|
214
280
|
@Property() rows: Record<string, unknown>[] = [];
|
|
215
281
|
@Property() onRowClick?: (row: Record<string, unknown>) => void;
|
|
216
282
|
|
|
217
283
|
render() {
|
|
218
284
|
return html`
|
|
219
|
-
<h2>${this.
|
|
285
|
+
<h2>${this.heading}</h2>
|
|
220
286
|
<table>
|
|
221
287
|
<thead><tr>${this.columns.map(c => html`<th>${c}</th>`)}</tr></thead>
|
|
222
288
|
<tbody>
|
|
@@ -241,7 +307,7 @@ table.onRowClick = (row) => console.log('Clicked:', row);
|
|
|
241
307
|
|
|
242
308
|
### @Watch(property)
|
|
243
309
|
|
|
244
|
-
Method decorator. Runs the decorated method synchronously when a `@State
|
|
310
|
+
Method decorator. Runs the decorated method synchronously when a reactive field (`@State`, `@Attribute`, `@Property`, `@Subscribe`, or one made reactive with `reactive()`) changes, before the queued render. The method receives `(newValue, oldValue)`. Watching a field that isn't reactive logs a one-time warning, since the watcher could never fire.
|
|
245
311
|
|
|
246
312
|
```typescript
|
|
247
313
|
@Register('search-box')
|
|
@@ -406,6 +472,12 @@ class ModalDialog extends Component {
|
|
|
406
472
|
onSaveClick(e: Event) {
|
|
407
473
|
this.save();
|
|
408
474
|
}
|
|
475
|
+
|
|
476
|
+
// The element that matched comes second
|
|
477
|
+
@Listen('click', { delegate: '[data-remove]' })
|
|
478
|
+
onRemove(e: MouseEvent, button: HTMLButtonElement) {
|
|
479
|
+
this.remove(button.dataset.remove);
|
|
480
|
+
}
|
|
409
481
|
}
|
|
410
482
|
```
|
|
411
483
|
|
|
@@ -414,12 +486,16 @@ class ModalDialog extends Component {
|
|
|
414
486
|
| Option | Type | Default | Description |
|
|
415
487
|
|--------|------|---------|-------------|
|
|
416
488
|
| `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
|
|
489
|
+
| `delegate` | `string` | -- | CSS selector for event delegation. The handler only fires for an event that comes from an element matching it, and gets that element as its second argument. |
|
|
418
490
|
| `capture` | `boolean` | `false` | Use capture phase |
|
|
419
491
|
| `passive` | `boolean` | `false` | Mark as passive |
|
|
420
492
|
| `once` | `boolean` | `false` | Remove after first fire |
|
|
421
493
|
|
|
422
|
-
**Event delegation:** With `delegate` set, the listener attaches to the component (or `target`), but the handler only fires when the event originates from
|
|
494
|
+
**Event delegation:** With `delegate` set, the listener attaches to the component (or `target`), but the handler only fires when the event originates from an element 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.
|
|
495
|
+
|
|
496
|
+
- **The matched element comes second.** The handler gets `(event, matched)`, where `matched` is the element that fit the selector: the button, not the icon inside it that was clicked.
|
|
497
|
+
- **The search stops at the listening element.** It runs from where the event started up to the element the listener is on: the component, or the `target` element. That element may match itself, as with `closest()`, but nothing above it does, so a component placed inside a matching element doesn't fire for every event. With `target: 'document'` or `'window'`, the whole document is in range.
|
|
498
|
+
- **Shadow roots:** a listener on a `ShadowComponent` searches its own shadow root and the children slotted into it. It doesn't look inside another component's shadow root. Events that don't cross a shadow boundary (`change`, `submit` and other events that aren't `composed`) never reach the host, so listen for those with a `target` inside the shadow root.
|
|
423
499
|
|
|
424
500
|
### @Emitter(eventName)
|
|
425
501
|
|
|
@@ -467,11 +543,11 @@ Class decorator. Declaratively applies styles at component definition time. Acce
|
|
|
467
543
|
'.body': { marginTop: '8px' }
|
|
468
544
|
})
|
|
469
545
|
class MyCard extends Component {
|
|
470
|
-
@Attribute()
|
|
546
|
+
@Attribute() heading = '';
|
|
471
547
|
|
|
472
548
|
render() {
|
|
473
549
|
return html`
|
|
474
|
-
<h3>${this.
|
|
550
|
+
<h3>${this.heading}</h3>
|
|
475
551
|
<div class="body">${this.slotContent}</div>
|
|
476
552
|
`;
|
|
477
553
|
}
|
|
@@ -520,8 +596,8 @@ Initial classes are applied on `connectedCallback`, and subsequent updates react
|
|
|
520
596
|
|
|
521
597
|
| Property | Type | Description |
|
|
522
598
|
|----------|------|-------------|
|
|
523
|
-
| `isConnected` | `boolean` | True when in the DOM |
|
|
524
|
-
| `isReady` | `boolean` | True
|
|
599
|
+
| `isConnected` | `boolean` | True when in the DOM. Flips as soon as the element is inserted or removed, like the native property. |
|
|
600
|
+
| `isReady` | `boolean` | True once the render and `didMount` / `didReconnect` of the current connection complete; false again as soon as the element is removed |
|
|
525
601
|
| `isFirstMount` | `boolean` | True until first mount completes |
|
|
526
602
|
| `slotContent` | `string` | Original `innerHTML` captured before first render |
|
|
527
603
|
|
|
@@ -534,6 +610,7 @@ Initial classes are applied on `connectedCallback`, and subsequent updates react
|
|
|
534
610
|
| `batch(fn)` | `(() => void) => void` | Group state changes; `@Watch`/`didChange` deferred until batch completes, one render queued |
|
|
535
611
|
| `ready(callback)` | `(() => void) => void` | Call after component is mounted. Fires immediately (via microtask) if already mounted. |
|
|
536
612
|
| `static template` | `string \| ((self) => TemplateValue)` | External template; setting it auto-re-renders mounted instances |
|
|
613
|
+
| `static keepFocusAndScroll` | `boolean` (default `false`) | String renders give focus and scroll positions back to the new elements. See [Focus and Scroll in String Renders](#focus-and-scroll-in-string-renders) |
|
|
537
614
|
|
|
538
615
|
### Styles
|
|
539
616
|
|
|
@@ -566,6 +643,28 @@ For `ShadowComponent`, `query` and `queryAll` search within the shadow root.
|
|
|
566
643
|
| `static register()` | Manual registration (equivalent to `@Register`) |
|
|
567
644
|
| `static tag` | Tag name (auto-derived from class name, or set by `@Register`) |
|
|
568
645
|
|
|
646
|
+
### Instances
|
|
647
|
+
|
|
648
|
+
| Method | Signature | Description |
|
|
649
|
+
|--------|-----------|-------------|
|
|
650
|
+
| `static connectedInstances()` | `() => ReadonlySet<Instance>` | The instances of exactly this class that are in the document, in the order they connected, including ones inside shadow roots. Live: copy it before iterating if you add or remove components |
|
|
651
|
+
|
|
652
|
+
```typescript
|
|
653
|
+
@Register('toast-message')
|
|
654
|
+
class ToastMessage extends Component {
|
|
655
|
+
dismiss() {
|
|
656
|
+
this.remove();
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// Close every toast on the page, without searching the DOM.
|
|
661
|
+
for (const toast of [...ToastMessage.connectedInstances()]) {
|
|
662
|
+
toast.dismiss();
|
|
663
|
+
}
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
`Registry.instances(tag)` still searches the document, so it doesn't see instances inside shadow roots.
|
|
667
|
+
|
|
569
668
|
## Lifecycle
|
|
570
669
|
|
|
571
670
|
```
|
|
@@ -574,11 +673,11 @@ Unmount: willUnmount -> didUnmount
|
|
|
574
673
|
Changes: @Watch callbacks -> didChange -> queued microtask render
|
|
575
674
|
```
|
|
576
675
|
|
|
577
|
-
|
|
676
|
+
Lifecycle hooks can be sync or `async` -- Pandora awaits whatever they return before moving on. Override only the hooks you need.
|
|
578
677
|
|
|
579
678
|
| Hook | When it runs | Common use |
|
|
580
679
|
|------|-------------|------------|
|
|
581
|
-
| `willMount()` |
|
|
680
|
+
| `willMount()` | On every connect, before that connection's first render | Setup that must run before the DOM is ready |
|
|
582
681
|
| `didMount()` | After the first render only | One-time subscriptions, timers, third-party init |
|
|
583
682
|
| `didReconnect()` | After re-insertion (not first mount) | Refresh data, re-sync state |
|
|
584
683
|
| `willUnmount()` | Before removal | Save state, cancel pending requests |
|
|
@@ -590,7 +689,7 @@ Components dispatch DOM events after mount completes and before teardown, which
|
|
|
590
689
|
|
|
591
690
|
| Event | When | `event.detail` |
|
|
592
691
|
|-------|------|----------------|
|
|
593
|
-
| `pandora:ready` | After `didMount`
|
|
692
|
+
| `pandora:ready` | After `didMount` (first mount) or `didReconnect` (later connects) completes | `{ firstMount: boolean, tag: string }` |
|
|
594
693
|
| `pandora:unmount` | Before `willUnmount` runs | `{ tag: string }` |
|
|
595
694
|
|
|
596
695
|
```javascript
|
|
@@ -604,10 +703,12 @@ document.addEventListener('pandora:unmount', (e) => {
|
|
|
604
703
|
});
|
|
605
704
|
```
|
|
606
705
|
|
|
607
|
-
In lit-html
|
|
706
|
+
In a lit-html template:
|
|
608
707
|
|
|
609
|
-
```
|
|
610
|
-
|
|
708
|
+
```typescript
|
|
709
|
+
render() {
|
|
710
|
+
return html`<game-screen @pandora:ready=${(event: CustomEvent) => this.onScreenReady(event)}></game-screen>`;
|
|
711
|
+
}
|
|
611
712
|
```
|
|
612
713
|
|
|
613
714
|
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.
|
|
@@ -634,7 +735,7 @@ A generic change observer that fires whenever any `@State`, `@Attribute`, `@Prop
|
|
|
634
735
|
class AuditForm extends Component {
|
|
635
736
|
@State() name = '';
|
|
636
737
|
@State() email = '';
|
|
637
|
-
@Attribute()
|
|
738
|
+
@Attribute() access = 'user';
|
|
638
739
|
|
|
639
740
|
didChange(property: string, oldValue: unknown, newValue: unknown, source?: string) {
|
|
640
741
|
console.log(`[${source}:${property}] ${oldValue} -> ${newValue}`);
|
|
@@ -916,6 +1017,34 @@ document.body.appendChild(table);
|
|
|
916
1017
|
|
|
917
1018
|
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.
|
|
918
1019
|
|
|
1020
|
+
## Elements Created Early or From Code
|
|
1021
|
+
|
|
1022
|
+
**Values set before the element is defined are kept.** The parser can create `<user-card>` before the script that defines it has run, and code may set properties on it in the meantime (`card.user = { name: 'Ada' }`). Once the class is defined, Pandora assigns those values again, through your reactive fields and setters, before the first render:
|
|
1023
|
+
|
|
1024
|
+
```typescript
|
|
1025
|
+
const card = document.querySelector('user-card');
|
|
1026
|
+
card.user = { name: 'Ada' }; // before UserCard is defined
|
|
1027
|
+
|
|
1028
|
+
@Register('user-card')
|
|
1029
|
+
class UserCard extends Component {
|
|
1030
|
+
@Property() user = { name: 'Guest' };
|
|
1031
|
+
|
|
1032
|
+
render() {
|
|
1033
|
+
return html`<p>${this.user.name}</p>`; // renders "Ada"
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
```
|
|
1037
|
+
|
|
1038
|
+
A value that can't be assigned again (a getter without a setter) is reported on the console.
|
|
1039
|
+
|
|
1040
|
+
**Attribute defaults wait for the element to connect.** A new element must not have attributes while `document.createElement()` or `new` constructs it, so the defaults of `@Attribute` and `@Property({ attribute })` fields are written to their attributes when the element connects, before the first render. An attribute you set in the meantime wins:
|
|
1041
|
+
|
|
1042
|
+
```typescript
|
|
1043
|
+
const badge = document.createElement('status-badge'); // fine, even with @Attribute() level = 1
|
|
1044
|
+
badge.setAttribute('level', '3');
|
|
1045
|
+
document.body.append(badge); // level stays "3"
|
|
1046
|
+
```
|
|
1047
|
+
|
|
919
1048
|
## ShadowComponent
|
|
920
1049
|
|
|
921
1050
|
`ShadowComponent` extends `Component` with an open shadow root. The API is identical -- every decorator works the same way. The differences:
|
|
@@ -1080,6 +1209,8 @@ Registry.debug = true; // enables [Pandora] console logs for all lifecycle even
|
|
|
1080
1209
|
Registry.log('custom message', { extra: 'data' }); // only logs when debug is true
|
|
1081
1210
|
```
|
|
1082
1211
|
|
|
1212
|
+
`VERSION` tells you which Pandora is running (`import { VERSION } from '@aegis-framework/pandora'`, or `Pandora.VERSION` with the browser bundle).
|
|
1213
|
+
|
|
1083
1214
|
## Global State
|
|
1084
1215
|
|
|
1085
1216
|
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.
|
|
@@ -1169,15 +1300,18 @@ Pandora exposes its reactive primitives as a public API, so you can build your o
|
|
|
1169
1300
|
### Public Extension API
|
|
1170
1301
|
|
|
1171
1302
|
```typescript
|
|
1172
|
-
import { reactive, addDecoratorEffect, addTeardown } from '@aegis-framework/pandora';
|
|
1303
|
+
import { reactive, reactiveFields, addDecoratorEffect, addTeardown } from '@aegis-framework/pandora';
|
|
1173
1304
|
```
|
|
1174
1305
|
|
|
1175
1306
|
| Export | Purpose |
|
|
1176
1307
|
|--------|---------|
|
|
1177
1308
|
| `reactive(instance, propertyKey, options?)` | Make a field reactive: installs getter/setter, auto-renders on change, fires `onChange` callback |
|
|
1309
|
+
| `reactiveFields(componentClass)` | The names of a class's `@State`, `@Property` and `@Attribute` fields, inherited ones included, as a new `Set`. Useful to check a class against a contract before any instance exists |
|
|
1178
1310
|
| `addDecoratorEffect(metadata, effectFn)` | Register a function to replay when `Registry.evolve()` or `Registry.lazy()` upgrades a live instance |
|
|
1179
1311
|
| `addTeardown(instance, cleanupFn)` | Register a cleanup function that runs before decorator effects are replayed (unsubscribe, remove listeners, etc.) |
|
|
1180
1312
|
|
|
1313
|
+
Decorator options and Registry callbacks have exported types too (`StateOptions`, `PropertyOptions`, `AttributeOptions`, `ListenOptions`, `RegisterOptions`, `ClassListMap`, `ErrorCallback`, `LifecycleCallback`, `Middleware`, `ComponentStats`, ...), so wrappers around Pandora can stay fully typed.
|
|
1314
|
+
|
|
1181
1315
|
Additionally, the `Util` namespace export gives access to metadata symbols if you need to read or extend decorator metadata directly:
|
|
1182
1316
|
|
|
1183
1317
|
```typescript
|
|
@@ -1186,6 +1320,7 @@ import { Util } from '@aegis-framework/pandora';
|
|
|
1186
1320
|
// Available symbols:
|
|
1187
1321
|
Util.PROP_ATTRIBUTES // string[] of observed attribute names
|
|
1188
1322
|
Util.WATCH_HANDLERS // @Watch registrations: { property, methodName }[]
|
|
1323
|
+
Util.REACTIVE_FIELDS // Set of @State / @Property / @Attribute field names (or call reactiveFields())
|
|
1189
1324
|
Util.LISTEN_HANDLERS // @Listen registrations: { event, methodName, options }[]
|
|
1190
1325
|
Util.STYLE_METADATA // @Style CSS data (object or string)
|
|
1191
1326
|
Util.DECORATOR_EFFECTS // effect functions for evolve/lazy replay
|
|
@@ -1204,12 +1339,12 @@ reactive(instance, propertyKey, options?);
|
|
|
1204
1339
|
|
|
1205
1340
|
| Option | Type | Default | Description |
|
|
1206
1341
|
|--------|------|---------|-------------|
|
|
1207
|
-
| `initialValue` | `unknown` | `undefined` |
|
|
1342
|
+
| `initialValue` | `unknown` | `undefined` | Seeds the field when it has no value yet. Omit it to keep the field's current value (its class field initializer, say). |
|
|
1208
1343
|
| `render` | `boolean` | `true` | Whether changes call `_queueRender()` automatically |
|
|
1209
|
-
| `onChange` | `(newValue, oldValue) => void` | -- | Callback fired on every change, before render is queued |
|
|
1344
|
+
| `onChange` | `(newValue, oldValue) => void` | -- | Callback fired on every change, before render is queued -- immediately, even inside `batch()` |
|
|
1210
1345
|
| `equals` | `(a, b) => boolean` | `===` | Custom equality check to skip no-op assignments |
|
|
1211
1346
|
|
|
1212
|
-
The `render: false` option is the escape hatch for custom decorators that want their own render strategy -- debouncing, throttling, conditional rendering.
|
|
1347
|
+
The `render: false` option is the escape hatch for custom decorators that want their own render strategy -- debouncing, throttling, conditional rendering. Like decorated fields, `reactive()` fields defer `@Watch` and `didChange` until a surrounding `batch()` closes.
|
|
1213
1348
|
|
|
1214
1349
|
### addDecoratorEffect / addTeardown
|
|
1215
1350
|
|
|
@@ -1261,7 +1396,7 @@ Components can override `didChange(property, oldValue, newValue, source?)` as a
|
|
|
1261
1396
|
class TrackedComponent extends Component {
|
|
1262
1397
|
@State() count = 0;
|
|
1263
1398
|
@State() name = '';
|
|
1264
|
-
@Attribute()
|
|
1399
|
+
@Attribute() heading = '';
|
|
1265
1400
|
@Property() open = false;
|
|
1266
1401
|
|
|
1267
1402
|
didChange(property: string, oldValue: unknown, newValue: unknown, source?: string) {
|
|
@@ -1584,6 +1719,32 @@ async render() {
|
|
|
1584
1719
|
}
|
|
1585
1720
|
```
|
|
1586
1721
|
|
|
1722
|
+
### Focus and Scroll in String Renders
|
|
1723
|
+
|
|
1724
|
+
A `render()` that returns a string replaces every element inside the component, so the browser forgets which element had focus and how far each list was scrolled: typing in a field or scrolling a list jumps back after every render. Set `static keepFocusAndScroll = true` and Pandora notes them before each string render and gives them back to the new elements:
|
|
1725
|
+
|
|
1726
|
+
- the focused element gets its focus back (and a text field its selection), but only when the render took it: a render never takes focus from elsewhere on the page;
|
|
1727
|
+
- every element that had been scrolled is scrolled back to the same place.
|
|
1728
|
+
|
|
1729
|
+
It finds each new element by its `data-key` attribute, then its `id`, then its position among its parent's children. Give elements whose order can change a `data-key`:
|
|
1730
|
+
|
|
1731
|
+
```typescript
|
|
1732
|
+
@Register('choice-list')
|
|
1733
|
+
class ChoiceList extends Component {
|
|
1734
|
+
static override keepFocusAndScroll = true;
|
|
1735
|
+
|
|
1736
|
+
@State() choices: string[] = [];
|
|
1737
|
+
|
|
1738
|
+
render() {
|
|
1739
|
+
return this.choices.map((choice) => `<button data-key="${choice}">${choice}</button>`).join('');
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
```
|
|
1743
|
+
|
|
1744
|
+
lit-html renders update the elements they already have, so they keep focus and scroll on their own.
|
|
1745
|
+
|
|
1746
|
+
It's off by default because a component that already moves focus itself after a render (in `didRender()`) expects the render to have taken it.
|
|
1747
|
+
|
|
1587
1748
|
### Static Template
|
|
1588
1749
|
|
|
1589
1750
|
Set a template on the class directly -- handy for external templates or programmatic overrides. Every mounted instance re-renders automatically when the template changes:
|
|
@@ -1635,6 +1796,33 @@ Registry.register('counter-element', CounterElement);
|
|
|
1635
1796
|
|
|
1636
1797
|
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.
|
|
1637
1798
|
|
|
1799
|
+
To get auto-rendering without decorators, make the field reactive from the constructor with [`reactive()`](#reactiveinstance-propertykey-options). It keeps the field's initial value, and `@State`-style rendering, `didChange`, and `batch()` all work from there:
|
|
1800
|
+
|
|
1801
|
+
```javascript
|
|
1802
|
+
import { Component, Registry, reactive, html } from '@aegis-framework/pandora';
|
|
1803
|
+
|
|
1804
|
+
class CounterElement extends Component {
|
|
1805
|
+
count = 0;
|
|
1806
|
+
|
|
1807
|
+
constructor() {
|
|
1808
|
+
super();
|
|
1809
|
+
reactive(this, 'count');
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
didMount() {
|
|
1813
|
+
this.on('click', () => {
|
|
1814
|
+
this.count++; // re-renders on its own
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
render() {
|
|
1819
|
+
return html`<button>Count: ${this.count}</button>`;
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
Registry.register('counter-element', CounterElement);
|
|
1824
|
+
```
|
|
1825
|
+
|
|
1638
1826
|
## Test Utilities
|
|
1639
1827
|
|
|
1640
1828
|
Pandora ships a `testing` namespace with helpers for unit and component tests. Import it straight from the main package:
|
|
@@ -1648,7 +1836,7 @@ import { testing } from '@aegis-framework/pandora';
|
|
|
1648
1836
|
| `testing.flush()` | `() => Promise<void>` | Resolve all pending microtask renders. Call after state changes before asserting DOM state. |
|
|
1649
1837
|
| `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). |
|
|
1650
1838
|
| `testing.resetRegistry()` | `() => void` | Clear all global state, subscriptions, and middleware. Call in `beforeEach` / `afterEach` to isolate tests. |
|
|
1651
|
-
| `testing.mount(tagName, container?, innerHTML?)` | `(string, Element?, string?) => Promise<
|
|
1839
|
+
| `testing.mount<T>(tagName, container?, innerHTML?)` | `(string, Element?, string?) => Promise<T>` | Create the element, append it to `container` (default `document.body`), wait until ready, and return it typed as `T` (defaults to `Component`). |
|
|
1652
1840
|
|
|
1653
1841
|
```typescript
|
|
1654
1842
|
import { testing } from '@aegis-framework/pandora';
|
|
@@ -1659,7 +1847,7 @@ beforeEach(() => {
|
|
|
1659
1847
|
});
|
|
1660
1848
|
|
|
1661
1849
|
it('increments on click', async () => {
|
|
1662
|
-
const el = await testing.mount('my-counter')
|
|
1850
|
+
const el = await testing.mount<MyCounter>('my-counter');
|
|
1663
1851
|
|
|
1664
1852
|
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
1665
1853
|
await testing.flush();
|
|
@@ -1705,7 +1893,22 @@ Pandora ships a pre-bundled browser file you can drop in without a bundler:
|
|
|
1705
1893
|
<counter-element></counter-element>
|
|
1706
1894
|
```
|
|
1707
1895
|
|
|
1708
|
-
Decorators aren't available in no-build browser usage. Use `Registry.register()`
|
|
1896
|
+
Decorators aren't available in no-build browser usage. Use `Registry.register()` with `forceRender()` as shown above, or [`reactive()`](#non-decorator-usage) for auto-rendering fields.
|
|
1897
|
+
|
|
1898
|
+
The bundle is self-contained (lit-html included) and defines a single global, `window.Pandora`. From a module, `import '@aegis-framework/pandora/browser'` sets up the same global.
|
|
1899
|
+
|
|
1900
|
+
## Troubleshooting
|
|
1901
|
+
|
|
1902
|
+
Pandora reports common mistakes on the console, prefixed with `[Pandora]`:
|
|
1903
|
+
|
|
1904
|
+
| Message | What it means | What to do |
|
|
1905
|
+
|---------|---------------|------------|
|
|
1906
|
+
| `@State was called as a legacy decorator` | Your compiler uses TypeScript's legacy decorators | Remove `experimentalDecorators` from `tsconfig.json`; with Babel, use `@babel/plugin-proposal-decorators` with `{ version: "2023-11" }`. See [Setup](#setup) |
|
|
1907
|
+
| `Card: @Property() title has the name of the element's own title property` | The field replaces a property every element has (`title`, `hidden`, `id`, `ariaLabel`, `remove`…), so the browser's own behavior for it stops working | Rename the field (`heading` instead of `title`) |
|
|
1908
|
+
| `<my-list>'s render() returned a number` | `render()` returned something that isn't a string, a template, `nothing` or `undefined` | Return a string or an `` html`` `` template; put arrays inside a template: `` html`${items}` `` |
|
|
1909
|
+
| `<user-card> was given user before it was defined, and the value couldn't be kept` | A value set before the class was defined has nowhere to go (a getter without a setter) | Add a setter, or set the value after the element is defined |
|
|
1910
|
+
| `@Watch('count') … is not reactive` | The watched field isn't declared with a reactive decorator | Add `@State`, `@Attribute`, `@Property` or `@Subscribe` to it |
|
|
1911
|
+
| `Two copies of @aegis-framework/pandora are loaded` | The page runs two Pandoras, each with its own Registry, so components and state registered with one are unknown to the other | Install a single copy (`npm ls @aegis-framework/pandora`, then dedupe), import Pandora only by its package name, and don't load the browser bundle on a page that also bundles the package |
|
|
1709
1912
|
|
|
1710
1913
|
## Migration Guide
|
|
1711
1914
|
|
|
@@ -1715,8 +1918,8 @@ Migrating from pre-0.6 Pandora to the new decorator-first API:
|
|
|
1715
1918
|
|-------------------|-------------|
|
|
1716
1919
|
| `this.state = { count: 0 }` | `@State() count = 0` |
|
|
1717
1920
|
| `this.setState({ count: 1 })` | `this.count = 1` |
|
|
1718
|
-
| `this.props = {
|
|
1719
|
-
| `this.setProps({
|
|
1921
|
+
| `this.props = { heading: '' }` | `@Attribute() heading = ''` |
|
|
1922
|
+
| `this.setProps({ heading: 'Hi' })` | `this.heading = 'Hi'` |
|
|
1720
1923
|
| `onStateUpdate() { this.forceRender(); }` | Automatic -- `@State` fields queue renders on change |
|
|
1721
1924
|
| `onPropsUpdate() { this.forceRender(); }` | Automatic -- `@Attribute` fields queue renders on change |
|
|
1722
1925
|
| `willUpdate()` / `didUpdate()` | `@Watch('field')` or `didChange()` |
|
|
@@ -1726,7 +1929,7 @@ Migrating from pre-0.6 Pandora to the new decorator-first API:
|
|
|
1726
1929
|
| `this.dom` | `this` (Component is itself an `HTMLElement`) |
|
|
1727
1930
|
| `this.static.tag` | Removed -- use `(this.constructor as typeof Component).tag` |
|
|
1728
1931
|
| `this.width` / `this.height` | Use `getComputedStyle(this)` directly |
|
|
1729
|
-
| `this.ready(callback)` |
|
|
1932
|
+
| `this.ready(callback)` | Unchanged -- or override `didMount()` for setup inside the class |
|
|
1730
1933
|
| `Component<Props, State>` generics | Typed class fields with decorators |
|
|
1731
1934
|
| Untyped `Registry.setState` / `Registry.getState` for shared values | `createState<T>(key, default)` for type-safe global state |
|
|
1732
1935
|
|
|
@@ -1737,6 +1940,10 @@ Migrating from pre-0.6 Pandora to the new decorator-first API:
|
|
|
1737
1940
|
- **`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.
|
|
1738
1941
|
- **Lifecycle hooks are simpler.** The old update lifecycle (`willUpdate`, `update`, `didUpdate`, `onStateUpdate`, `onPropsUpdate`, `updateCallback`) is entirely replaced by `@Watch` and `didChange`.
|
|
1739
1942
|
|
|
1943
|
+
## Contributing
|
|
1944
|
+
|
|
1945
|
+
Bug reports and pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) explains how to set up the project, run the tests and check a change.
|
|
1946
|
+
|
|
1740
1947
|
## License
|
|
1741
1948
|
|
|
1742
1949
|
Released under the [MIT License](./LICENSE).
|