@aegis-framework/pandora 0.6.2 → 0.7.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 +226 -27
- 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 +226 -30
- package/dist/types/Component.d.ts.map +1 -1
- package/dist/types/Decorators.d.ts +47 -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 +15 -3
- package/dist/types/ShadowComponent.d.ts.map +1 -1
- package/dist/types/Testing.d.ts +12 -9
- 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 +119 -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')
|
|
@@ -467,11 +533,11 @@ Class decorator. Declaratively applies styles at component definition time. Acce
|
|
|
467
533
|
'.body': { marginTop: '8px' }
|
|
468
534
|
})
|
|
469
535
|
class MyCard extends Component {
|
|
470
|
-
@Attribute()
|
|
536
|
+
@Attribute() heading = '';
|
|
471
537
|
|
|
472
538
|
render() {
|
|
473
539
|
return html`
|
|
474
|
-
<h3>${this.
|
|
540
|
+
<h3>${this.heading}</h3>
|
|
475
541
|
<div class="body">${this.slotContent}</div>
|
|
476
542
|
`;
|
|
477
543
|
}
|
|
@@ -520,8 +586,8 @@ Initial classes are applied on `connectedCallback`, and subsequent updates react
|
|
|
520
586
|
|
|
521
587
|
| Property | Type | Description |
|
|
522
588
|
|----------|------|-------------|
|
|
523
|
-
| `isConnected` | `boolean` | True when in the DOM |
|
|
524
|
-
| `isReady` | `boolean` | True
|
|
589
|
+
| `isConnected` | `boolean` | True when in the DOM. Flips as soon as the element is inserted or removed, like the native property. |
|
|
590
|
+
| `isReady` | `boolean` | True once the render and `didMount` / `didReconnect` of the current connection complete; false again as soon as the element is removed |
|
|
525
591
|
| `isFirstMount` | `boolean` | True until first mount completes |
|
|
526
592
|
| `slotContent` | `string` | Original `innerHTML` captured before first render |
|
|
527
593
|
|
|
@@ -534,6 +600,7 @@ Initial classes are applied on `connectedCallback`, and subsequent updates react
|
|
|
534
600
|
| `batch(fn)` | `(() => void) => void` | Group state changes; `@Watch`/`didChange` deferred until batch completes, one render queued |
|
|
535
601
|
| `ready(callback)` | `(() => void) => void` | Call after component is mounted. Fires immediately (via microtask) if already mounted. |
|
|
536
602
|
| `static template` | `string \| ((self) => TemplateValue)` | External template; setting it auto-re-renders mounted instances |
|
|
603
|
+
| `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
604
|
|
|
538
605
|
### Styles
|
|
539
606
|
|
|
@@ -566,6 +633,28 @@ For `ShadowComponent`, `query` and `queryAll` search within the shadow root.
|
|
|
566
633
|
| `static register()` | Manual registration (equivalent to `@Register`) |
|
|
567
634
|
| `static tag` | Tag name (auto-derived from class name, or set by `@Register`) |
|
|
568
635
|
|
|
636
|
+
### Instances
|
|
637
|
+
|
|
638
|
+
| Method | Signature | Description |
|
|
639
|
+
|--------|-----------|-------------|
|
|
640
|
+
| `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 |
|
|
641
|
+
|
|
642
|
+
```typescript
|
|
643
|
+
@Register('toast-message')
|
|
644
|
+
class ToastMessage extends Component {
|
|
645
|
+
dismiss() {
|
|
646
|
+
this.remove();
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Close every toast on the page, without searching the DOM.
|
|
651
|
+
for (const toast of [...ToastMessage.connectedInstances()]) {
|
|
652
|
+
toast.dismiss();
|
|
653
|
+
}
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
`Registry.instances(tag)` still searches the document, so it doesn't see instances inside shadow roots.
|
|
657
|
+
|
|
569
658
|
## Lifecycle
|
|
570
659
|
|
|
571
660
|
```
|
|
@@ -574,11 +663,11 @@ Unmount: willUnmount -> didUnmount
|
|
|
574
663
|
Changes: @Watch callbacks -> didChange -> queued microtask render
|
|
575
664
|
```
|
|
576
665
|
|
|
577
|
-
|
|
666
|
+
Lifecycle hooks can be sync or `async` -- Pandora awaits whatever they return before moving on. Override only the hooks you need.
|
|
578
667
|
|
|
579
668
|
| Hook | When it runs | Common use |
|
|
580
669
|
|------|-------------|------------|
|
|
581
|
-
| `willMount()` |
|
|
670
|
+
| `willMount()` | On every connect, before that connection's first render | Setup that must run before the DOM is ready |
|
|
582
671
|
| `didMount()` | After the first render only | One-time subscriptions, timers, third-party init |
|
|
583
672
|
| `didReconnect()` | After re-insertion (not first mount) | Refresh data, re-sync state |
|
|
584
673
|
| `willUnmount()` | Before removal | Save state, cancel pending requests |
|
|
@@ -590,7 +679,7 @@ Components dispatch DOM events after mount completes and before teardown, which
|
|
|
590
679
|
|
|
591
680
|
| Event | When | `event.detail` |
|
|
592
681
|
|-------|------|----------------|
|
|
593
|
-
| `pandora:ready` | After `didMount`
|
|
682
|
+
| `pandora:ready` | After `didMount` (first mount) or `didReconnect` (later connects) completes | `{ firstMount: boolean, tag: string }` |
|
|
594
683
|
| `pandora:unmount` | Before `willUnmount` runs | `{ tag: string }` |
|
|
595
684
|
|
|
596
685
|
```javascript
|
|
@@ -604,10 +693,12 @@ document.addEventListener('pandora:unmount', (e) => {
|
|
|
604
693
|
});
|
|
605
694
|
```
|
|
606
695
|
|
|
607
|
-
In lit-html
|
|
696
|
+
In a lit-html template:
|
|
608
697
|
|
|
609
|
-
```
|
|
610
|
-
|
|
698
|
+
```typescript
|
|
699
|
+
render() {
|
|
700
|
+
return html`<game-screen @pandora:ready=${(event: CustomEvent) => this.onScreenReady(event)}></game-screen>`;
|
|
701
|
+
}
|
|
611
702
|
```
|
|
612
703
|
|
|
613
704
|
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 +725,7 @@ A generic change observer that fires whenever any `@State`, `@Attribute`, `@Prop
|
|
|
634
725
|
class AuditForm extends Component {
|
|
635
726
|
@State() name = '';
|
|
636
727
|
@State() email = '';
|
|
637
|
-
@Attribute()
|
|
728
|
+
@Attribute() access = 'user';
|
|
638
729
|
|
|
639
730
|
didChange(property: string, oldValue: unknown, newValue: unknown, source?: string) {
|
|
640
731
|
console.log(`[${source}:${property}] ${oldValue} -> ${newValue}`);
|
|
@@ -895,6 +986,8 @@ class StopwatchElement extends Component {
|
|
|
895
986
|
| `object` / `array` | `@Property()` | Property-only -- no attribute sync, no render |
|
|
896
987
|
| `function` | `@Property()` | Property-only -- no attribute sync, no render |
|
|
897
988
|
|
|
989
|
+
Numeric coercion covers ordinary decimal spellings, including a leading sign and trailing zeroes -- so `42`, `+1`, `-3.14`, and `1.0` all arrive as numbers. Strings with leading zeros (`007`), scientific or hex notation (`1e3`, `0xFF`), or non-finite words (`Infinity`) are preserved as strings, so significant values like ids and zip codes survive the round trip intact.
|
|
990
|
+
|
|
898
991
|
**Setting attribute-friendly props from HTML:**
|
|
899
992
|
|
|
900
993
|
```html
|
|
@@ -914,6 +1007,34 @@ document.body.appendChild(table);
|
|
|
914
1007
|
|
|
915
1008
|
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.
|
|
916
1009
|
|
|
1010
|
+
## Elements Created Early or From Code
|
|
1011
|
+
|
|
1012
|
+
**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:
|
|
1013
|
+
|
|
1014
|
+
```typescript
|
|
1015
|
+
const card = document.querySelector('user-card');
|
|
1016
|
+
card.user = { name: 'Ada' }; // before UserCard is defined
|
|
1017
|
+
|
|
1018
|
+
@Register('user-card')
|
|
1019
|
+
class UserCard extends Component {
|
|
1020
|
+
@Property() user = { name: 'Guest' };
|
|
1021
|
+
|
|
1022
|
+
render() {
|
|
1023
|
+
return html`<p>${this.user.name}</p>`; // renders "Ada"
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
```
|
|
1027
|
+
|
|
1028
|
+
A value that can't be assigned again (a getter without a setter) is reported on the console.
|
|
1029
|
+
|
|
1030
|
+
**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:
|
|
1031
|
+
|
|
1032
|
+
```typescript
|
|
1033
|
+
const badge = document.createElement('status-badge'); // fine, even with @Attribute() level = 1
|
|
1034
|
+
badge.setAttribute('level', '3');
|
|
1035
|
+
document.body.append(badge); // level stays "3"
|
|
1036
|
+
```
|
|
1037
|
+
|
|
917
1038
|
## ShadowComponent
|
|
918
1039
|
|
|
919
1040
|
`ShadowComponent` extends `Component` with an open shadow root. The API is identical -- every decorator works the same way. The differences:
|
|
@@ -1078,6 +1199,8 @@ Registry.debug = true; // enables [Pandora] console logs for all lifecycle even
|
|
|
1078
1199
|
Registry.log('custom message', { extra: 'data' }); // only logs when debug is true
|
|
1079
1200
|
```
|
|
1080
1201
|
|
|
1202
|
+
`VERSION` tells you which Pandora is running (`import { VERSION } from '@aegis-framework/pandora'`, or `Pandora.VERSION` with the browser bundle).
|
|
1203
|
+
|
|
1081
1204
|
## Global State
|
|
1082
1205
|
|
|
1083
1206
|
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.
|
|
@@ -1167,15 +1290,18 @@ Pandora exposes its reactive primitives as a public API, so you can build your o
|
|
|
1167
1290
|
### Public Extension API
|
|
1168
1291
|
|
|
1169
1292
|
```typescript
|
|
1170
|
-
import { reactive, addDecoratorEffect, addTeardown } from '@aegis-framework/pandora';
|
|
1293
|
+
import { reactive, reactiveFields, addDecoratorEffect, addTeardown } from '@aegis-framework/pandora';
|
|
1171
1294
|
```
|
|
1172
1295
|
|
|
1173
1296
|
| Export | Purpose |
|
|
1174
1297
|
|--------|---------|
|
|
1175
1298
|
| `reactive(instance, propertyKey, options?)` | Make a field reactive: installs getter/setter, auto-renders on change, fires `onChange` callback |
|
|
1299
|
+
| `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 |
|
|
1176
1300
|
| `addDecoratorEffect(metadata, effectFn)` | Register a function to replay when `Registry.evolve()` or `Registry.lazy()` upgrades a live instance |
|
|
1177
1301
|
| `addTeardown(instance, cleanupFn)` | Register a cleanup function that runs before decorator effects are replayed (unsubscribe, remove listeners, etc.) |
|
|
1178
1302
|
|
|
1303
|
+
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.
|
|
1304
|
+
|
|
1179
1305
|
Additionally, the `Util` namespace export gives access to metadata symbols if you need to read or extend decorator metadata directly:
|
|
1180
1306
|
|
|
1181
1307
|
```typescript
|
|
@@ -1184,6 +1310,7 @@ import { Util } from '@aegis-framework/pandora';
|
|
|
1184
1310
|
// Available symbols:
|
|
1185
1311
|
Util.PROP_ATTRIBUTES // string[] of observed attribute names
|
|
1186
1312
|
Util.WATCH_HANDLERS // @Watch registrations: { property, methodName }[]
|
|
1313
|
+
Util.REACTIVE_FIELDS // Set of @State / @Property / @Attribute field names (or call reactiveFields())
|
|
1187
1314
|
Util.LISTEN_HANDLERS // @Listen registrations: { event, methodName, options }[]
|
|
1188
1315
|
Util.STYLE_METADATA // @Style CSS data (object or string)
|
|
1189
1316
|
Util.DECORATOR_EFFECTS // effect functions for evolve/lazy replay
|
|
@@ -1202,12 +1329,12 @@ reactive(instance, propertyKey, options?);
|
|
|
1202
1329
|
|
|
1203
1330
|
| Option | Type | Default | Description |
|
|
1204
1331
|
|--------|------|---------|-------------|
|
|
1205
|
-
| `initialValue` | `unknown` | `undefined` |
|
|
1332
|
+
| `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). |
|
|
1206
1333
|
| `render` | `boolean` | `true` | Whether changes call `_queueRender()` automatically |
|
|
1207
|
-
| `onChange` | `(newValue, oldValue) => void` | -- | Callback fired on every change, before render is queued |
|
|
1334
|
+
| `onChange` | `(newValue, oldValue) => void` | -- | Callback fired on every change, before render is queued -- immediately, even inside `batch()` |
|
|
1208
1335
|
| `equals` | `(a, b) => boolean` | `===` | Custom equality check to skip no-op assignments |
|
|
1209
1336
|
|
|
1210
|
-
The `render: false` option is the escape hatch for custom decorators that want their own render strategy -- debouncing, throttling, conditional rendering.
|
|
1337
|
+
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.
|
|
1211
1338
|
|
|
1212
1339
|
### addDecoratorEffect / addTeardown
|
|
1213
1340
|
|
|
@@ -1259,7 +1386,7 @@ Components can override `didChange(property, oldValue, newValue, source?)` as a
|
|
|
1259
1386
|
class TrackedComponent extends Component {
|
|
1260
1387
|
@State() count = 0;
|
|
1261
1388
|
@State() name = '';
|
|
1262
|
-
@Attribute()
|
|
1389
|
+
@Attribute() heading = '';
|
|
1263
1390
|
@Property() open = false;
|
|
1264
1391
|
|
|
1265
1392
|
didChange(property: string, oldValue: unknown, newValue: unknown, source?: string) {
|
|
@@ -1582,6 +1709,32 @@ async render() {
|
|
|
1582
1709
|
}
|
|
1583
1710
|
```
|
|
1584
1711
|
|
|
1712
|
+
### Focus and Scroll in String Renders
|
|
1713
|
+
|
|
1714
|
+
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:
|
|
1715
|
+
|
|
1716
|
+
- 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;
|
|
1717
|
+
- every element that had been scrolled is scrolled back to the same place.
|
|
1718
|
+
|
|
1719
|
+
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`:
|
|
1720
|
+
|
|
1721
|
+
```typescript
|
|
1722
|
+
@Register('choice-list')
|
|
1723
|
+
class ChoiceList extends Component {
|
|
1724
|
+
static override keepFocusAndScroll = true;
|
|
1725
|
+
|
|
1726
|
+
@State() choices: string[] = [];
|
|
1727
|
+
|
|
1728
|
+
render() {
|
|
1729
|
+
return this.choices.map((choice) => `<button data-key="${choice}">${choice}</button>`).join('');
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
```
|
|
1733
|
+
|
|
1734
|
+
lit-html renders update the elements they already have, so they keep focus and scroll on their own.
|
|
1735
|
+
|
|
1736
|
+
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.
|
|
1737
|
+
|
|
1585
1738
|
### Static Template
|
|
1586
1739
|
|
|
1587
1740
|
Set a template on the class directly -- handy for external templates or programmatic overrides. Every mounted instance re-renders automatically when the template changes:
|
|
@@ -1633,6 +1786,33 @@ Registry.register('counter-element', CounterElement);
|
|
|
1633
1786
|
|
|
1634
1787
|
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
1788
|
|
|
1789
|
+
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:
|
|
1790
|
+
|
|
1791
|
+
```javascript
|
|
1792
|
+
import { Component, Registry, reactive, html } from '@aegis-framework/pandora';
|
|
1793
|
+
|
|
1794
|
+
class CounterElement extends Component {
|
|
1795
|
+
count = 0;
|
|
1796
|
+
|
|
1797
|
+
constructor() {
|
|
1798
|
+
super();
|
|
1799
|
+
reactive(this, 'count');
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
didMount() {
|
|
1803
|
+
this.on('click', () => {
|
|
1804
|
+
this.count++; // re-renders on its own
|
|
1805
|
+
});
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
render() {
|
|
1809
|
+
return html`<button>Count: ${this.count}</button>`;
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
Registry.register('counter-element', CounterElement);
|
|
1814
|
+
```
|
|
1815
|
+
|
|
1636
1816
|
## Test Utilities
|
|
1637
1817
|
|
|
1638
1818
|
Pandora ships a `testing` namespace with helpers for unit and component tests. Import it straight from the main package:
|
|
@@ -1646,7 +1826,7 @@ import { testing } from '@aegis-framework/pandora';
|
|
|
1646
1826
|
| `testing.flush()` | `() => Promise<void>` | Resolve all pending microtask renders. Call after state changes before asserting DOM state. |
|
|
1647
1827
|
| `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
1828
|
| `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<
|
|
1829
|
+
| `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`). |
|
|
1650
1830
|
|
|
1651
1831
|
```typescript
|
|
1652
1832
|
import { testing } from '@aegis-framework/pandora';
|
|
@@ -1657,7 +1837,7 @@ beforeEach(() => {
|
|
|
1657
1837
|
});
|
|
1658
1838
|
|
|
1659
1839
|
it('increments on click', async () => {
|
|
1660
|
-
const el = await testing.mount('my-counter')
|
|
1840
|
+
const el = await testing.mount<MyCounter>('my-counter');
|
|
1661
1841
|
|
|
1662
1842
|
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
1663
1843
|
await testing.flush();
|
|
@@ -1703,7 +1883,22 @@ Pandora ships a pre-bundled browser file you can drop in without a bundler:
|
|
|
1703
1883
|
<counter-element></counter-element>
|
|
1704
1884
|
```
|
|
1705
1885
|
|
|
1706
|
-
Decorators aren't available in no-build browser usage. Use `Registry.register()`
|
|
1886
|
+
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.
|
|
1887
|
+
|
|
1888
|
+
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.
|
|
1889
|
+
|
|
1890
|
+
## Troubleshooting
|
|
1891
|
+
|
|
1892
|
+
Pandora reports common mistakes on the console, prefixed with `[Pandora]`:
|
|
1893
|
+
|
|
1894
|
+
| Message | What it means | What to do |
|
|
1895
|
+
|---------|---------------|------------|
|
|
1896
|
+
| `@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) |
|
|
1897
|
+
| `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`) |
|
|
1898
|
+
| `<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}` `` |
|
|
1899
|
+
| `<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 |
|
|
1900
|
+
| `@Watch('count') … is not reactive` | The watched field isn't declared with a reactive decorator | Add `@State`, `@Attribute`, `@Property` or `@Subscribe` to it |
|
|
1901
|
+
| `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 |
|
|
1707
1902
|
|
|
1708
1903
|
## Migration Guide
|
|
1709
1904
|
|
|
@@ -1713,8 +1908,8 @@ Migrating from pre-0.6 Pandora to the new decorator-first API:
|
|
|
1713
1908
|
|-------------------|-------------|
|
|
1714
1909
|
| `this.state = { count: 0 }` | `@State() count = 0` |
|
|
1715
1910
|
| `this.setState({ count: 1 })` | `this.count = 1` |
|
|
1716
|
-
| `this.props = {
|
|
1717
|
-
| `this.setProps({
|
|
1911
|
+
| `this.props = { heading: '' }` | `@Attribute() heading = ''` |
|
|
1912
|
+
| `this.setProps({ heading: 'Hi' })` | `this.heading = 'Hi'` |
|
|
1718
1913
|
| `onStateUpdate() { this.forceRender(); }` | Automatic -- `@State` fields queue renders on change |
|
|
1719
1914
|
| `onPropsUpdate() { this.forceRender(); }` | Automatic -- `@Attribute` fields queue renders on change |
|
|
1720
1915
|
| `willUpdate()` / `didUpdate()` | `@Watch('field')` or `didChange()` |
|
|
@@ -1724,7 +1919,7 @@ Migrating from pre-0.6 Pandora to the new decorator-first API:
|
|
|
1724
1919
|
| `this.dom` | `this` (Component is itself an `HTMLElement`) |
|
|
1725
1920
|
| `this.static.tag` | Removed -- use `(this.constructor as typeof Component).tag` |
|
|
1726
1921
|
| `this.width` / `this.height` | Use `getComputedStyle(this)` directly |
|
|
1727
|
-
| `this.ready(callback)` |
|
|
1922
|
+
| `this.ready(callback)` | Unchanged -- or override `didMount()` for setup inside the class |
|
|
1728
1923
|
| `Component<Props, State>` generics | Typed class fields with decorators |
|
|
1729
1924
|
| Untyped `Registry.setState` / `Registry.getState` for shared values | `createState<T>(key, default)` for type-safe global state |
|
|
1730
1925
|
|
|
@@ -1735,6 +1930,10 @@ Migrating from pre-0.6 Pandora to the new decorator-first API:
|
|
|
1735
1930
|
- **`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
1931
|
- **Lifecycle hooks are simpler.** The old update lifecycle (`willUpdate`, `update`, `didUpdate`, `onStateUpdate`, `onPropsUpdate`, `updateCallback`) is entirely replaced by `@Watch` and `didChange`.
|
|
1737
1932
|
|
|
1933
|
+
## Contributing
|
|
1934
|
+
|
|
1935
|
+
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.
|
|
1936
|
+
|
|
1738
1937
|
## License
|
|
1739
1938
|
|
|
1740
1939
|
Released under the [MIT License](./LICENSE).
|