@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.
@@ -1,347 +1,920 @@
1
1
  import { TemplateResult, nothing } from 'lit-html';
2
- import { Properties, Style, ReadyCallback } from './Types';
2
+ import type { SubscribeHandler } from './Types';
3
+ import { Style, TemplateValue, TemplateFunction } from './Types';
3
4
  /**
4
- * A component represents a custom HTML element, and has all of its functionality
5
- * as well as its general structure and representation self contained on it.
5
+ * The base class every Pandora component extends.
6
6
  *
7
- * @template P - The type of the component's props (defaults to Properties)
8
- * @template S - The type of the component's state (defaults to Properties)
7
+ * `Component` is a thin layer over the native `HTMLElement` that wires up
8
+ * Pandora's reactive lifecycle: subclasses declare state with decorators like
9
+ * `@State`, `@Attribute`, and `@Property`, and the base class takes care of
10
+ * registering the tag, batching state changes into microtask-scheduled
11
+ * renders, managing attributes, and running mount and unmount hooks. Most of
12
+ * the time you only implement `render()` and let the decorators do the rest.
13
+ *
14
+ * Rendering is batched on the microtask queue. Multiple synchronous property
15
+ * updates in the same tick coalesce into a single `render()` call. If you
16
+ * need a synchronous render, call `forceRender()`; if you need to group
17
+ * changes explicitly, wrap them in `batch()`.
18
+ *
19
+ * @example
20
+ * import { Component, Register, State, html } from '@aegis-framework/pandora';
21
+ *
22
+ * @Register('my-greeting')
23
+ * class MyGreeting extends Component {
24
+ * @State() name = 'world';
25
+ *
26
+ * render() {
27
+ * return html`<p>Hello, ${this.name}.</p>`;
28
+ * }
29
+ * }
30
+ *
31
+ * // <my-greeting></my-greeting>
9
32
  */
10
- declare class Component<P extends Properties = Properties, S extends Properties = Properties> extends HTMLElement {
11
- _children: string;
12
- _state: S;
13
- _props: P;
14
- _ready: ReadyCallback[];
15
- _connected: boolean;
16
- _isReady: boolean;
17
- _style: Style;
18
- _updatingProps: boolean;
19
- _renderId: number;
20
- _propsProxy: P | null;
21
- _stateProxy: S | null;
22
- _hasBeenMounted: boolean;
23
- static _tag?: string;
24
- static _template?: string | ((context: any) => string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing>);
25
- static _observedAttributes: string[];
33
+ declare class Component extends HTMLElement {
34
+ /**
35
+ * The inner HTML the component was mounted with, captured before the first
36
+ * render runs. Exposed publicly as `slotContent`.
37
+ *
38
+ * @internal
39
+ */
40
+ protected _children: string;
41
+ /**
42
+ * Tracks whether the element is currently in the DOM. Flipped in
43
+ * `connectedCallback` / `disconnectedCallback` and surfaced publicly as
44
+ * `isConnected`.
45
+ *
46
+ * @internal
47
+ */
48
+ protected _connected: boolean;
49
+ /**
50
+ * Flips to `true` once the first mount (including `didMount` and the initial
51
+ * render) has finished. Surfaced publicly as `isReady`.
52
+ *
53
+ * @internal
54
+ */
55
+ protected _isReady: boolean;
56
+ /**
57
+ * Remembers whether this instance has ever been mounted. We flip it on
58
+ * after `didMount` so `isFirstMount` stays `true` for the duration of that
59
+ * hook and only becomes `false` on later reconnects.
60
+ *
61
+ * @internal
62
+ */
63
+ protected _hasBeenMounted: boolean;
64
+ /**
65
+ * Gates decorator-driven re-renders so that field initializer assignments
66
+ * during construction don't queue a render. Set to `true` after the first
67
+ * render completes, so subsequent `@State` / `@Attribute` writes during
68
+ * `didMount` and later hooks can schedule renders.
69
+ *
70
+ * @internal
71
+ */
72
+ protected _initRenderDone: boolean;
73
+ /**
74
+ * Bumps on every render, letting queued microtask renders detect that they
75
+ * have been superseded and bail out before writing to the DOM.
76
+ *
77
+ * @internal
78
+ */
79
+ protected _renderId: number;
80
+ /**
81
+ * Tracks whether a microtask render is already queued, so repeated
82
+ * `_queueRender` calls in the same tick coalesce into a single render.
83
+ *
84
+ * @internal
85
+ */
86
+ protected _renderQueued: boolean;
87
+ /**
88
+ * The object-form style currently applied through `setStyle`. Persisted so
89
+ * that merge-mode updates can layer new rules on top of previous ones.
90
+ *
91
+ * @internal
92
+ */
93
+ protected _style: Style;
94
+ /**
95
+ * `true` while a `batch()` callback is executing. Used by the reactive
96
+ * setters to defer watcher and render scheduling until the batch flushes.
97
+ *
98
+ * @internal
99
+ */
100
+ protected _batching: boolean;
101
+ /**
102
+ * Records reactive changes while a `batch()` is open so watchers and
103
+ * `didChange` don't observe intermediate state. Flushed once at the end of
104
+ * the batch with first and last values per property.
105
+ *
106
+ * @internal
107
+ */
108
+ protected _batchedChanges: Array<{
109
+ property: string;
110
+ oldValue: unknown;
111
+ newValue: unknown;
112
+ shouldRender: boolean;
113
+ source: string;
114
+ }>;
115
+ /**
116
+ * Backing storage for the custom element tag this class registers under.
117
+ * Populated lazily by the `tag` getter (kebab-casing the class name) or
118
+ * eagerly by `@Register` and the `tag` setter.
119
+ *
120
+ * @internal
121
+ */
122
+ protected static _tag?: string;
123
+ /**
124
+ * Backing storage for a class-level template (string or function). Takes
125
+ * precedence over instance `render()` when set. Read and written through
126
+ * the public `template` accessors.
127
+ *
128
+ * @internal
129
+ */
130
+ protected static _template?: string | TemplateFunction;
131
+ /**
132
+ * Backing storage for attributes registered manually through the
133
+ * `observedAttributes` setter. Merged with `@Attribute` / `@Property`
134
+ * metadata in the getter.
135
+ *
136
+ * @internal
137
+ */
138
+ protected static _observedAttributes: string[];
139
+ /**
140
+ * The adopted `CSSStyleSheet` shared across every instance of this tag.
141
+ * We keep one per class so `setStyle` on one instance styles them all.
142
+ *
143
+ * @internal
144
+ */
145
+ protected static _styleSheet: CSSStyleSheet | null;
146
+ /**
147
+ * Object-form style declarations shared across every instance of this tag.
148
+ * `setStyle()` writes to this class-level store because the stylesheet itself
149
+ * is class-wide.
150
+ *
151
+ * @internal
152
+ */
153
+ protected static _sharedStyle: Style;
154
+ /**
155
+ * Set by `Registry._init` to notify the registry whenever an instance
156
+ * finishes `connectedCallback`. Left unset when the registry isn't loaded.
157
+ *
158
+ * @internal
159
+ */
26
160
  static _onMount?: (component: Component, tag: string) => void;
161
+ /**
162
+ * Set by `Registry._init` to notify the registry after
163
+ * `disconnectedCallback` finishes tearing an instance down.
164
+ *
165
+ * @internal
166
+ */
27
167
  static _onUnmount?: (component: Component, tag: string) => void;
168
+ /**
169
+ * Set by `Registry._init` to route lifecycle errors through the registry's
170
+ * error handler. When unset, errors rethrow from the lifecycle method.
171
+ *
172
+ * @internal
173
+ */
28
174
  static _onError?: (error: Error, component: Component, tag: string, lifecycle: string) => void;
29
- static _applyMiddleware?: (type: string, component: Component, value: any, renderType?: 'string' | 'lit') => any;
175
+ /**
176
+ * Set by `Registry._init` so the registry can transform values flowing
177
+ * through reactive setters and render output (currently `render` middleware).
178
+ *
179
+ * @internal
180
+ */
181
+ static _applyMiddleware?: (type: string, component: Component, value: unknown, renderType?: 'string' | 'lit') => unknown;
182
+ /**
183
+ * Set by `Registry._init`. Lets `Component` cheaply skip the middleware
184
+ * bridge when no middleware of a given type is registered.
185
+ *
186
+ * @internal
187
+ */
30
188
  static _hasMiddleware?: (type: string) => boolean;
31
189
  /**
32
- * Returns the list of attributes to observe for changes.
33
- * Override this in subclasses to specify which attributes should trigger attributeChangedCallback.
190
+ * Set by `Registry._init`. Subscribes an instance to a global state key
191
+ * and returns an unsubscribe function. Used to wire up `@Subscribe`
192
+ * handlers on mount.
193
+ *
194
+ * @internal
195
+ */
196
+ static _subscribe?: (stateKey: string, callback: (newVal: unknown, oldVal: unknown) => void) => () => void;
197
+ /**
198
+ * Set by `Registry._init`. Reads the current value for a global state key
199
+ * so `@Subscribe` fields can seed themselves on activation.
200
+ *
201
+ * @internal
202
+ */
203
+ static _getGlobalState?: (stateKey: string) => unknown;
204
+ /**
205
+ * Set by `Registry._init`. Applies the current implementation registered
206
+ * with `Registry.evolve()` so that instances created after `evolve` pick up
207
+ * the latest behavior.
208
+ *
209
+ * @internal
210
+ */
211
+ static _applyCurrentImplementation?: (instance: Component, tag: string) => void;
212
+ /**
213
+ * Activates a single `@Subscribe` handler on an instance, hooking it into
214
+ * the registry's global state so the field tracks the chosen state key.
215
+ * Safe to call more than once — any prior subscription in the handler's
216
+ * slot is torn down first.
217
+ *
218
+ * @internal
219
+ */
220
+ static _activateSubscription(instance: Component, handler: SubscribeHandler): void;
221
+ /**
222
+ * The list of attributes the browser will notify Pandora about.
223
+ *
224
+ * This is the standard custom-elements introspection hook. It merges any
225
+ * attributes you registered manually with the ones declared through
226
+ * `@Attribute` and `@Property({ attribute })` decorators, so you rarely need
227
+ * to set it by hand.
228
+ *
229
+ * @returns The tag names of observed attributes, with duplicates removed.
230
+ *
231
+ * @example
232
+ * class MyButton extends Component {
233
+ * @Attribute() disabled = false;
234
+ * }
34
235
  *
35
- * @returns {string[]} - Array of attribute names to observe
236
+ * MyButton.observedAttributes; // ['disabled']
36
237
  */
37
238
  static get observedAttributes(): string[];
38
239
  /**
39
- * Sets the list of attributes to observe for changes.
240
+ * Overrides the list of observed attributes for this class.
40
241
  *
41
- * @param value - The new list of attributes to observe
242
+ * Prefer `@Attribute` / `@Property({ attribute })` instead — they keep the
243
+ * attribute list and the reactive field in sync automatically. Setting
244
+ * this by hand is an escape hatch for integrations that need to declare
245
+ * attributes without decorators.
246
+ *
247
+ * @param value - The attribute names the component should react to.
42
248
  */
43
249
  static set observedAttributes(value: string[]);
250
+ /**
251
+ * The custom element tag this component registers under.
252
+ *
253
+ * If you used `@Register('my-tag')` the tag is whatever you passed in. If
254
+ * you didn't, Pandora derives one from the class name by converting it to
255
+ * kebab-case (`MyGreeting` becomes `my-greeting`).
256
+ *
257
+ * @returns The tag name the component is known by in the DOM.
258
+ *
259
+ * @example
260
+ * @Register('user-avatar')
261
+ * class UserAvatar extends Component {}
262
+ * UserAvatar.tag; // 'user-avatar'
263
+ *
264
+ * class ThemeToggle extends Component {}
265
+ * ThemeToggle.tag; // 'theme-toggle' — derived from the class name
266
+ */
44
267
  static get tag(): string;
268
+ /**
269
+ * Overrides the tag name this component registers under.
270
+ *
271
+ * `@Register('my-tag')` is the preferred way to set this. Use the setter
272
+ * when you need to assign a tag programmatically before calling
273
+ * `register()` yourself.
274
+ *
275
+ * @param value - The custom element tag (must contain a hyphen).
276
+ */
45
277
  static set tag(value: string);
46
278
  /**
47
- * Set or get the static template for this component class.
279
+ * The class-level template used in place of `render()` when defined.
280
+ *
281
+ * Pandora picks this up automatically from an HTML `<template id="my-tag">`
282
+ * on first mount, or you can assign a string or a function that returns
283
+ * one. When set, it takes precedence over the instance `render()` method.
284
+ *
285
+ * @returns The template, or `undefined` if the component renders through
286
+ * `render()`.
287
+ *
288
+ * @example
289
+ * MyGreeting.template = (self) => `<p>Hello, ${self.name}.</p>`;
290
+ */
291
+ static get template(): string | TemplateFunction | undefined;
292
+ /**
293
+ * Replaces the class-level template and refreshes every mounted instance.
48
294
  *
49
- * Templates can be:
50
- * - A string: `'<div>Hello</div>'`
51
- * - A function returning string: `(ctx) => \`<div>\${ctx.props.name}</div>\``
52
- * - A function returning lit-html: `(ctx) => html\`<div>\${ctx.props.name}</div>\``
53
- * - An async function: `async (ctx) => { const data = await fetch(); return html\`...\`; }`
295
+ * Assigning a new template triggers `forceRender()` on every live element
296
+ * of this tag, so the UI picks up the new markup immediately. Pass a
297
+ * string for static markup, or a function `(self) => string` when you need
298
+ * access to the instance.
54
299
  *
55
- * @param html - The template to set, or null to get the current template result
56
- * @param context - The context to use when calling template functions (usually the component instance)
57
- * @returns The rendered template when getting, void when setting
300
+ * @param value - The new template, or `undefined` to clear it.
301
+ *
302
+ * @example
303
+ * // Swap the greeting template at runtime.
304
+ * MyGreeting.template = '<p>Welcome back.</p>';
58
305
  */
59
- static template(html?: string | ((context: any) => string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing>) | null, context?: any): string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing> | undefined | void;
60
- constructor();
61
- get width(): number;
62
- set width(value: number | string);
63
- get height(): number;
64
- set height(value: number | string);
65
- get static(): typeof Component;
66
- set static(value: typeof Component);
67
- get props(): P;
68
- set props(value: P);
69
- get state(): S;
70
- set state(value: S);
71
- get dom(): HTMLElement;
72
- set dom(value: HTMLElement);
73
- /**
74
- * Returns the original innerHTML content that was present before the component rendered.
75
- *
76
- * This is an alias for `_children`
77
- *
78
- * @example
79
- * // String template
80
- * render() {
81
- * return `<div class="wrapper">${this.slotContent}</div>`;
306
+ static set template(value: string | TemplateFunction | undefined);
307
+ /**
308
+ * Initializes a component instance.
309
+ *
310
+ * The browser calls this for you when the element is created — either
311
+ * through `document.createElement('my-tag')`, `new MyTag()`, or when the
312
+ * parser encounters the tag in HTML. Subclasses rarely need to override
313
+ * it; reach for `willMount()` or `didMount()` for setup work. If you do
314
+ * override, remember to call `super()` first.
315
+ *
316
+ * @example
317
+ * class MyCounter extends Component {
318
+ * constructor() {
319
+ * super();
320
+ * // your own setup here
321
+ * }
82
322
  * }
323
+ */
324
+ constructor();
325
+ /**
326
+ * The original inner HTML the component was mounted with.
327
+ *
328
+ * Pandora captures whatever markup lived between the opening and closing
329
+ * tags on first mount, before any render runs. Use this when you want to
330
+ * project user-provided content into your template — it is the string-
331
+ * render equivalent of a light-DOM `<slot>`.
332
+ *
333
+ * @returns The trimmed inner HTML at mount time.
83
334
  *
84
335
  * @example
85
- * // lit-html template
86
- * render() {
87
- * return html`<div class="wrapper">${this.slotContent}</div>`;
336
+ * class MyCard extends Component {
337
+ * render() {
338
+ * return `<div class="card">${this.slotContent}</div>`;
339
+ * }
88
340
  * }
341
+ *
342
+ * // <my-card>Hello</my-card> → <div class="card">Hello</div>
89
343
  */
90
344
  get slotContent(): string;
91
345
  /**
92
- * Returns whether the component is currently connected to the DOM.
346
+ * Whether the component is currently attached to the DOM.
347
+ *
348
+ * Flips to `true` inside `connectedCallback()` and back to `false` during
349
+ * `disconnectedCallback()`. Useful if you're running async work that
350
+ * should stop once the element is removed.
351
+ *
352
+ * @returns `true` while the element is in the document.
353
+ *
354
+ * @example
355
+ * async loadData() {
356
+ * const data = await fetch('/api/posts').then(r => r.json());
357
+ * if (!this.isConnected) return; // bail out if the user navigated away
358
+ * this.items = data;
359
+ * }
93
360
  */
94
361
  get isConnected(): boolean;
95
362
  /**
96
- * Returns whether the component has completed its initial mount cycle.
363
+ * Whether the first mount lifecycle (including the initial render) has
364
+ * finished.
365
+ *
366
+ * Prefer `ready()` when you want to run code once the component is ready;
367
+ * this getter is handy when you need a synchronous check — for example
368
+ * inside a parent component that wants to talk to a freshly inserted
369
+ * child.
370
+ *
371
+ * @returns `true` after `didMount()` and the initial render have run.
372
+ *
373
+ * @example
374
+ * if (avatar.isReady) {
375
+ * avatar.focus();
376
+ * } else {
377
+ * avatar.ready(() => avatar.focus());
378
+ * }
97
379
  */
98
380
  get isReady(): boolean;
99
381
  /**
100
- * Returns whether this is the first time the component is being mounted.
101
- * Useful in didMount() to avoid adding duplicate event listeners on reconnect.
382
+ * Whether this is the component's first time being mounted.
383
+ *
384
+ * `true` during the initial `connectedCallback()` / `didMount()`, `false`
385
+ * on subsequent reconnects (for example if the element is detached and
386
+ * re-attached, or moved in the DOM). Use it to separate first-time setup
387
+ * from re-connect behavior inside lifecycle hooks.
388
+ *
389
+ * @returns `true` until the first mount completes.
390
+ *
391
+ * @example
392
+ * async didMount() {
393
+ * if (this.isFirstMount) {
394
+ * await this.loadInitialData();
395
+ * }
396
+ * }
102
397
  */
103
398
  get isFirstMount(): boolean;
104
399
  /**
105
- * register - Register the component as a custom HTML element
106
- * using the component's tag as the actual element tag.
107
- *
108
- * This action cannot be reverted nor the controller class for
109
- * the element can be changed.
110
- */
400
+ * Set eagerly at `Registry` module load (not by `_init` like the other
401
+ * hooks) so that `Component.register()` delegates to the registry as soon
402
+ * as the registry module is imported, regardless of init ordering.
403
+ *
404
+ * @internal
405
+ */
406
+ static _registryRegister?: (tag: string, component: typeof Component) => void;
407
+ /**
408
+ * Registers this class as a custom element so the browser will recognise
409
+ * its tag in the DOM.
410
+ *
411
+ * `@Register('my-tag')` is the preferred path — it sets the tag and calls
412
+ * this for you. Call `register()` directly when you're wiring things up
413
+ * without decorators, or when you configured the tag manually through the
414
+ * `tag` setter.
415
+ *
416
+ * @example
417
+ * class MyCounter extends Component {
418
+ * static tag = 'my-counter';
419
+ * render() { return `<p>count</p>`; }
420
+ * }
421
+ * MyCounter.register();
422
+ */
111
423
  static register(): void;
112
424
  /**
113
- * Instance method to set or get the template.
114
- * Delegates to the static template() method with this instance as context.
425
+ * Whether the component is currently inside a `batch()` call.
426
+ *
427
+ * Mostly useful for code paths that branch on whether an update is part
428
+ * of a larger batched change — for example deciding whether to defer side
429
+ * effects until the batch completes.
430
+ *
431
+ * @returns `true` while a `batch()` callback is running.
432
+ *
433
+ * @example
434
+ * if (!this.isBatching) {
435
+ * this.logAudit(change);
436
+ * }
437
+ */
438
+ get isBatching(): boolean;
439
+ /**
440
+ * Groups several state changes into a single render.
441
+ *
442
+ * Every reactive property assignment you do inside `fn` is collected and
443
+ * replayed after it returns. `@Watch` callbacks and `didChange()` run
444
+ * once each, with the first and last values seen during the batch, and
445
+ * Pandora queues just one render at the end. Net no-ops (setting `A`
446
+ * back to its original value within the same batch) are skipped entirely.
447
+ *
448
+ * @param fn - A synchronous function that performs the property changes.
449
+ *
450
+ * @example
451
+ * class MyCounter extends Component {
452
+ * @State() count = 0;
453
+ * @State() label = 'clicks';
454
+ *
455
+ * reset() {
456
+ * this.batch(() => {
457
+ * this.count = 0;
458
+ * this.label = 'reset';
459
+ * });
460
+ * // Only one render runs for both changes.
461
+ * }
462
+ * }
463
+ */
464
+ batch(fn: () => void): void;
465
+ /**
466
+ * Schedules a render on the microtask queue. Multiple calls in the same
467
+ * tick coalesce into one render, and errors inside the render surface
468
+ * through the registry error handler (or console as a fallback).
469
+ *
470
+ * @internal
471
+ */
472
+ protected _queueRender(): void;
473
+ /**
474
+ * Renders the component immediately, skipping microtask batching.
475
+ *
476
+ * Normally you don't need this — property changes schedule a render on
477
+ * the microtask queue automatically. Reach for `forceRender()` when you
478
+ * need the DOM to reflect the latest state right now, for example before
479
+ * measuring an element or taking a screenshot in a test.
480
+ *
481
+ * @returns A promise that resolves once the render (including async
482
+ * `render()` returns and `didRender()`) has completed.
483
+ *
484
+ * @example
485
+ * this.count = 42;
486
+ * await this.forceRender();
487
+ * // the counter has the new value painted at this point
488
+ */
489
+ forceRender(): Promise<void>;
490
+ /**
491
+ * Produces the markup for this component.
115
492
  *
116
- * @param html - The template to set, or null to get the current template result
117
- * @returns The rendered template when getting, void when setting
493
+ * Override this in your subclass. You can return a lit-html `TemplateResult`
494
+ * (from the `html` tagged template), a plain HTML string, `lit-html`'s
495
+ * `nothing` sentinel to render no content, or an empty string `''` to clear
496
+ * the host. Returning nothing (the default) leaves any HTML-defined
497
+ * children untouched, which is what container components rely on.
498
+ *
499
+ * Pandora calls this for you on mount and whenever a reactive property
500
+ * changes — you rarely invoke it yourself. The return may be synchronous
501
+ * or a promise.
502
+ *
503
+ * @returns The markup to render, or `void` to preserve existing content.
504
+ *
505
+ * @example
506
+ * import { html } from '@aegis-framework/pandora';
507
+ *
508
+ * class MyGreeting extends Component {
509
+ * @State() name = 'friend';
510
+ *
511
+ * render() {
512
+ * return html`<p>Hello, ${this.name}.</p>`;
513
+ * }
514
+ * }
515
+ */
516
+ render(): TemplateValue | Promise<TemplateValue>;
517
+ /**
518
+ * Applies a lit-html template result to the host. We clear and stamp the
519
+ * `data-lit-rendered` marker on first use so pre-existing children don't
520
+ * interfere with lit's reconciliation, then delegate to `litRender`.
521
+ *
522
+ * @internal
523
+ */
524
+ protected _applyLitRender(result: TemplateResult | typeof nothing): void;
525
+ /**
526
+ * Applies a string render result. Honours `<slot>` as the injection point
527
+ * when one is present, otherwise sets `innerHTML` directly and re-appends
528
+ * the captured `slotContent` if the new markup didn't already include it.
529
+ *
530
+ * @internal
531
+ */
532
+ protected _applyStringRender(html: string): void;
533
+ /**
534
+ * Runs a single render cycle: resolves the template, applies middleware,
535
+ * writes to the DOM, and re-attaches `@Listen` handlers. Bumps `_renderId`
536
+ * up front so any concurrent render that awaited through ours detects it
537
+ * has been superseded and bails before touching the DOM.
538
+ *
539
+ * @internal
118
540
  */
119
- template(html?: string | ((context: any) => string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing>) | null): string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing> | undefined | void;
120
- static _styleSheet: CSSStyleSheet | null;
541
+ protected _render(): Promise<void>;
121
542
  /**
122
- * Sets the component style. For normal components, styles are scoped to the
123
- * component's tag name as a selector prefix and shared across all instances
124
- * of the same component class.
543
+ * Applies styles to the component via an adopted stylesheet.
125
544
  *
126
- * @param style - CSS object or string to apply
127
- * @param reset - If true, replaces all styles; if false, merges with existing
128
- * @returns The current style object
545
+ * Pass a `Style` object to describe your rules declaratively, or a raw
546
+ * CSS string if you already have text. By default the styles are merged
547
+ * with anything previously applied to the component; pass `reset: true`
548
+ * to replace the stylesheet instead. The stylesheet is shared across
549
+ * every instance of the tag, so setting it once styles them all.
550
+ *
551
+ * @param style - A `Style` object or a CSS string.
552
+ * @param reset - When `true`, replace the existing styles instead of
553
+ * merging on top.
554
+ * @returns The current object-form style after the update (useful when
555
+ * you want to read back the merged state).
556
+ *
557
+ * @example
558
+ * class ThemeToggle extends Component {
559
+ * async didMount() {
560
+ * this.setStyle({
561
+ * ':host': { display: 'inline-block', cursor: 'pointer' },
562
+ * 'button': { padding: '0.5rem 1rem' }
563
+ * });
564
+ * }
565
+ * }
566
+ *
567
+ * // Or with a raw CSS string:
568
+ * this.setStyle(':host { color: rebeccapurple; }');
129
569
  */
130
570
  setStyle(style: Style | string, reset?: boolean): Style;
131
- setState(state: Partial<S>): void;
132
- setProps(props: Partial<P>): void;
133
- _setPropAttributes(update?: boolean): void;
134
571
  /**
135
- * Adds an event listener to the component.
572
+ * Attaches an event listener to the component.
573
+ *
574
+ * A thin, chainable wrapper around `addEventListener` scoped to the host
575
+ * element. Prefer the `@Listen` decorator for anything that should live
576
+ * for the lifetime of the component — `on()` is handy for one-offs and
577
+ * for ad-hoc wiring from outside the class.
136
578
  *
137
- * @param event - The event type to listen for
138
- * @param callback - The callback function to execute when the event occurs
139
- * @param options - Optional event listener options
140
- * @returns The component instance for chaining
579
+ * @param event - The event name to listen for.
580
+ * @param callback - The handler to run when the event fires.
581
+ * @param options - Standard `addEventListener` options.
582
+ * @returns The component, for chaining.
583
+ *
584
+ * @example
585
+ * const button = document.querySelector('my-button');
586
+ * button.on('click', () => console.log('clicked'));
141
587
  */
142
588
  on<K extends keyof HTMLElementEventMap>(event: K, callback: (this: this, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): this;
143
589
  on(event: string, callback: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): this;
144
590
  /**
145
- * Removes an event listener from the component.
591
+ * Removes a previously attached event listener from the component.
146
592
  *
147
- * @param event - The event type to remove the listener for
148
- * @param callback - The callback function to remove
149
- * @param options - Optional event listener options
150
- * @returns The component instance for chaining
593
+ * Pass the same event name, callback reference, and options you used in
594
+ * `on()` / `once()` — the underlying `removeEventListener` only matches
595
+ * exact triples.
596
+ *
597
+ * @param event - The event name.
598
+ * @param callback - The handler reference to remove.
599
+ * @param options - The options the listener was registered with.
600
+ * @returns The component, for chaining.
601
+ *
602
+ * @example
603
+ * const onClick = () => console.log('clicked');
604
+ * button.on('click', onClick);
605
+ * // later...
606
+ * button.off('click', onClick);
151
607
  */
152
608
  off<K extends keyof HTMLElementEventMap>(event: K, callback: (this: this, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): this;
153
609
  off(event: string, callback: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): this;
154
610
  /**
155
- * Adds a one-time event listener that removes itself after the first trigger.
611
+ * Attaches a one-shot event listener to the component.
612
+ *
613
+ * Like `on()`, but the listener is automatically removed after it fires
614
+ * once. Useful for reacting to things like the first click or the next
615
+ * transition end.
156
616
  *
157
- * @param event - The event type to listen for
158
- * @param callback - The callback function to execute when the event occurs
159
- * @param options - Optional event listener options
160
- * @returns The component instance for chaining
617
+ * @param event - The event name to listen for.
618
+ * @param callback - The handler to run the first time the event fires.
619
+ * @param options - Standard `addEventListener` options; `once` is forced
620
+ * to `true`.
621
+ * @returns The component, for chaining.
622
+ *
623
+ * @example
624
+ * modal.once('animationend', () => modal.remove());
161
625
  */
162
626
  once<K extends keyof HTMLElementEventMap>(event: K, callback: (this: this, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): this;
163
627
  once(event: string, callback: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): this;
164
628
  /**
165
- * Emits a custom event from the component.
629
+ * Dispatches a `CustomEvent` from the component.
630
+ *
631
+ * By default the event bubbles up through the DOM, is composed (so it
632
+ * crosses shadow-root boundaries), and is cancellable. Pass any of those
633
+ * as `options` to override them. Anything you put in `detail` is
634
+ * delivered to listeners as `event.detail`.
635
+ *
636
+ * @param event - The event name.
637
+ * @param detail - The payload to attach to `event.detail`.
638
+ * @param options - Overrides for `bubbles`, `cancelable`, `composed`, etc.
639
+ * @returns `false` if a listener called `preventDefault()`, otherwise
640
+ * `true`.
166
641
  *
167
- * @param event - The event name to emit
168
- * @param detail - Optional data to include with the event
169
- * @param options - Optional CustomEvent init options (bubbles, cancelable, composed)
170
- * @returns Whether the event was not cancelled
642
+ * @example
643
+ * class MyButton extends Component {
644
+ * @Listen('click')
645
+ * onClick() {
646
+ * this.emit('button-pressed', { id: this.id, at: Date.now() });
647
+ * }
648
+ * }
649
+ *
650
+ * // parent listens:
651
+ * myButton.on('button-pressed', (e) => console.log(e.detail.id));
171
652
  */
172
653
  emit<T = unknown>(event: string, detail?: T, options?: Omit<CustomEventInit<T>, 'detail'>): boolean;
173
654
  /**
174
- * Queries for a single element within the component's DOM.
655
+ * Finds the first descendant matching the given CSS selector.
656
+ *
657
+ * A shortcut for `querySelector` scoped to the component's own subtree.
658
+ * Handy inside `didMount()` or `didRender()` when you need to grab a
659
+ * rendered element. Subclasses like `ShadowComponent` scope the search
660
+ * to the shadow root instead.
175
661
  *
176
- * @param selector - CSS selector to query for
177
- * @returns The first matching element or null
662
+ * @param selector - Any valid CSS selector.
663
+ * @returns The first matching element, or `null` if nothing matched.
664
+ *
665
+ * @example
666
+ * async didMount() {
667
+ * this.query('input')?.focus();
668
+ * }
178
669
  */
179
670
  query<E extends Element = Element>(selector: string): E | null;
180
671
  /**
181
- * Queries for all matching elements within the component's DOM.
672
+ * Finds every descendant matching the given CSS selector.
673
+ *
674
+ * A shortcut for `querySelectorAll` scoped to the component's own
675
+ * subtree. Subclasses like `ShadowComponent` scope the search to the
676
+ * shadow root instead.
182
677
  *
183
- * @param selector - CSS selector to query for
184
- * @returns A NodeList of all matching elements
678
+ * @param selector - Any valid CSS selector.
679
+ * @returns A `NodeList` of matching elements (possibly empty).
680
+ *
681
+ * @example
682
+ * for (const item of this.queryAll('li.item')) {
683
+ * item.classList.add('ready');
684
+ * }
185
685
  */
186
686
  queryAll<E extends Element = Element>(selector: string): NodeListOf<E>;
187
687
  /**
188
- * Called before the component updates due to state or props changes.
189
- * Override this method to perform actions before an update occurs.
688
+ * Queue of callbacks registered through `ready()` before the component
689
+ * finished its first mount. Drained in order once `_isReady` flips to
690
+ * `true`, then discarded.
190
691
  *
191
- * @param origin - Whether the update was triggered by 'state' or 'props'
192
- * @param property - The name of the property that changed
193
- * @param oldValue - The previous value of the property
194
- * @param newValue - The new value of the property
195
- * @param oldObject - The previous state/props object
196
- * @param newObject - The new state/props object
197
- * @returns A promise that resolves when the pre-update logic completes
692
+ * @internal
198
693
  */
199
- willUpdate(_origin: string, _property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
694
+ private _readyCallbacks?;
200
695
  /**
201
- * Called when the component updates due to state or props changes.
202
- * Override this method to perform actions during an update.
696
+ * Queues a callback to run once the component has finished its first
697
+ * mount and initial render.
203
698
  *
204
- * @param origin - Whether the update was triggered by 'state' or 'props'
205
- * @param property - The name of the property that changed
206
- * @param oldValue - The previous value of the property
207
- * @param newValue - The new value of the property
208
- * @param oldObject - The previous state/props object
209
- * @param newObject - The new state/props object
210
- * @returns A promise that resolves when the update logic completes
211
- */
212
- update(_origin: string, _property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
213
- /**
214
- * Called after the component updates due to state or props changes.
215
- * Override this method to perform actions after an update completes.
699
+ * If the component is already ready, the callback runs on the next
700
+ * microtask. If not, it's queued and fired in order after `didMount()`
701
+ * and the first render. Typical use is deferring DOM work that depends on
702
+ * the rendered markup — focusing an input, measuring size, wiring up a
703
+ * library.
216
704
  *
217
- * @param origin - Whether the update was triggered by 'state' or 'props'
218
- * @param property - The name of the property that changed
219
- * @param oldValue - The previous value of the property
220
- * @param newValue - The new value of the property
221
- * @param oldObject - The previous state/props object
222
- * @param newObject - The new state/props object
223
- * @returns A promise that resolves when the post-update logic completes
224
- */
225
- didUpdate(_origin: string, _property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
226
- /**
227
- * Called when the component's state updates.
228
- * Override this method to react specifically to state changes.
705
+ * @param callback - The function to run when the component is ready.
229
706
  *
230
- * @param property - The name of the state property that changed
231
- * @param oldValue - The previous value of the property
232
- * @param newValue - The new value of the property
233
- * @param oldObject - The previous state object
234
- * @param newObject - The new state object
235
- * @returns A promise that resolves when the state update logic completes
707
+ * @example
708
+ * class UserAvatar extends Component {
709
+ * render() {
710
+ * return html`<input name="handle" />`;
711
+ * }
712
+ *
713
+ * constructor() {
714
+ * super();
715
+ * this.ready(() => this.query('input')?.focus());
716
+ * }
717
+ * }
236
718
  */
237
- onStateUpdate(_property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
719
+ ready(callback: () => void): void;
238
720
  /**
239
- * Called when the component's props update.
240
- * Override this method to react specifically to props changes.
721
+ * Runs just before the component's first render.
241
722
  *
242
- * @param property - The name of the prop that changed
243
- * @param oldValue - The previous value of the property
244
- * @param newValue - The new value of the property
245
- * @param oldObject - The previous props object
246
- * @param newObject - The new props object
247
- * @returns A promise that resolves when the props update logic completes
248
- */
249
- onPropsUpdate(_property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
250
- /**
251
- * Called before the component is mounted to the DOM.
252
- * Override this method to perform setup before rendering.
723
+ * Override this to do async setup that should finish before users see
724
+ * anything — fetch data, load a dependency, subscribe to a store. The
725
+ * render is awaited on your returned promise, so returning a pending
726
+ * fetch will delay the first paint.
253
727
  *
254
- * @returns A promise that resolves when the pre-mount logic completes
728
+ * @example
729
+ * async willMount() {
730
+ * this.data = await fetch('/api/profile').then(r => r.json());
731
+ * }
255
732
  */
256
733
  willMount(): Promise<void>;
257
734
  /**
258
- * Called after the component is mounted to the DOM for the first time.
259
- * Use this for one-time setup: event listeners, subscriptions, intervals, etc.
260
- * This will NOT be called on reconnect — use didReconnect() for that.
735
+ * Runs after the component's first mount completes.
736
+ *
737
+ * By this point the initial render has happened, `isReady` is `true`,
738
+ * and the component is in the DOM. Use it for post-render setup that
739
+ * needs to inspect the rendered markup, or for things you only want to
740
+ * do on the very first connection (use `isFirstMount` if you override
741
+ * `didReconnect` too).
261
742
  *
262
- * @returns A promise that resolves when the post-mount logic completes
743
+ * @example
744
+ * async didMount() {
745
+ * this.query('input')?.focus();
746
+ * }
263
747
  */
264
748
  didMount(): Promise<void>;
265
749
  /**
266
- * Called after the component is re-inserted into the DOM (not on first mount).
267
- * Use this for reconnect-specific logic: refreshing data, re-syncing state, etc.
750
+ * Runs after every render cycle.
268
751
  *
269
- * @returns A promise that resolves when the reconnect logic completes
752
+ * Fires on the initial mount render, on re-renders triggered by
753
+ * reactive state changes, and on every `forceRender()` call. Use it
754
+ * to grab references to freshly rendered elements or to re-apply
755
+ * imperative setup — `didMount()` only runs once, while this runs
756
+ * each time the DOM content is replaced.
757
+ *
758
+ * @example
759
+ * async didRender() {
760
+ * this._chart?.destroy();
761
+ * this._chart = createChart(this.query('canvas'));
762
+ * }
270
763
  */
271
- didReconnect(): Promise<void>;
764
+ didRender(): Promise<void>;
272
765
  /**
273
- * Called before the component is removed from the DOM.
274
- * Override this method to perform cleanup before unmounting.
766
+ * Runs when the component is re-attached to the DOM after being
767
+ * disconnected.
275
768
  *
276
- * @returns A promise that resolves when the pre-unmount logic completes
769
+ * This is the counterpart to `didMount()` for the second and later
770
+ * connection. Use it to re-subscribe to streams or re-start timers
771
+ * that you shut down in `willUnmount()` / `didUnmount()`.
772
+ *
773
+ * @example
774
+ * async didReconnect() {
775
+ * this._timer = setInterval(() => this.tick(), 1000);
776
+ * }
277
777
  */
278
- willUnmount(): Promise<void>;
778
+ didReconnect(): Promise<void>;
279
779
  /**
280
- * Called when the component is being removed from the DOM.
281
- * Override this method to perform cleanup during unmounting.
780
+ * Runs just before the component is removed from the DOM.
781
+ *
782
+ * Override to tear down anything that can't wait: cancel pending
783
+ * fetches, clear timers, close sockets. The returned promise is
784
+ * awaited before `didUnmount()` runs.
282
785
  *
283
- * @returns A promise that resolves when the unmount logic completes
786
+ * @example
787
+ * async willUnmount() {
788
+ * this._abort.abort();
789
+ * }
284
790
  */
285
- unmount(): Promise<void>;
791
+ willUnmount(): Promise<void>;
286
792
  /**
287
- * Called after the component is removed from the DOM.
288
- * Override this method to perform final cleanup after unmounting.
793
+ * Runs after the component has been removed from the DOM.
794
+ *
795
+ * By this point the element is no longer in the document. Use it for
796
+ * final cleanup — releasing references, logging, telemetry.
289
797
  *
290
- * @returns A promise that resolves when the post-unmount logic completes
798
+ * @example
799
+ * async didUnmount() {
800
+ * analytics.track('card-removed', { id: this.id });
801
+ * }
291
802
  */
292
803
  didUnmount(): Promise<void>;
293
804
  /**
294
- * Forces the component to be rendered again.
805
+ * Runs every time one of the component's reactive fields changes.
295
806
  *
296
- * @returns A promise that resolves when rendering is complete
807
+ * Override this for a single place to observe state changes across all
808
+ * `@State`, `@Attribute`, `@Property`, and `@Subscribe` fields. It fires
809
+ * synchronously in the setter, after any matching `@Watch` callbacks and
810
+ * before the queued render. Great for logging, audit trails, analytics,
811
+ * or cross-cutting validation.
812
+ *
813
+ * @param property - The name of the field that changed.
814
+ * @param oldValue - The previous value.
815
+ * @param newValue - The new value.
816
+ * @param source - A short label describing where the change came from,
817
+ * such as `'state'`, `'prop'`, `'prop-attribute'`, `'property'`,
818
+ * `'consumer'`, or `'reactive'`.
819
+ *
820
+ * @example
821
+ * class MyCounter extends Component {
822
+ * @State() count = 0;
823
+ *
824
+ * didChange(property, oldValue, newValue, source) {
825
+ * console.log(`[${source}] ${property}: ${oldValue} -> ${newValue}`);
826
+ * }
827
+ * }
297
828
  */
298
- forceRender(): Promise<void>;
829
+ didChange(_property: string, _oldValue: unknown, _newValue: unknown, _source?: string): void;
299
830
  /**
300
- * Returns the content for the component.
301
- * Override this method to define the component's template.
831
+ * The standard custom-elements hook Pandora uses to drive mounting.
302
832
  *
303
- * You can return either:
304
- * - A string (traditional HTML string)
305
- * - A lit-html TemplateResult (for efficient DOM diffing)
306
- * - `nothing` from lit-html (to render nothing)
307
- * - A Promise resolving to any of the above (for async data fetching)
833
+ * Pandora runs `@Subscribe` activation, picks up `@Style` metadata, calls
834
+ * `willMount()`, performs the first render, then calls either
835
+ * `didMount()` (on the first connection) or `didReconnect()` (on a later
836
+ * one), and finally fires any pending `ready()` callbacks. Subclasses
837
+ * normally reach for `willMount()`, `didMount()`, or `ready()` instead of
838
+ * overriding this. If you do override it, call `super.connectedCallback()`
839
+ * so the lifecycle keeps working.
308
840
  *
309
841
  * @example
310
- * // String-based rendering
311
- * render() {
312
- * return `<div>Hello ${this.state.name}</div>`;
842
+ * async connectedCallback() {
843
+ * await super.connectedCallback();
844
+ * // extra work that needs to run after the standard mount
313
845
  * }
846
+ */
847
+ connectedCallback(): Promise<void>;
848
+ /**
849
+ * The standard custom-elements hook Pandora uses to drive unmounting.
850
+ *
851
+ * Pandora tears down `@Subscribe` subscriptions and `@Listen` handlers,
852
+ * then calls `willUnmount()` and `didUnmount()` before flipping the
853
+ * component's ready and connected flags back to `false`. Override the
854
+ * lifecycle methods in preference to this hook; if you do override,
855
+ * remember to call `super.disconnectedCallback()`.
314
856
  *
315
857
  * @example
316
- * // lit-html rendering
317
- * render() {
318
- * return html`<div>Hello ${this.state.name}</div>`;
858
+ * async disconnectedCallback() {
859
+ * await super.disconnectedCallback();
860
+ * this.releaseExternalResource();
319
861
  * }
862
+ */
863
+ disconnectedCallback(): Promise<void>;
864
+ /**
865
+ * The standard custom-elements hook that tracks attribute changes.
866
+ *
867
+ * Pandora routes attribute updates into the fields you declared with
868
+ * `@Attribute` / `@Property({ attribute })`, parses values for you (so
869
+ * `"42"` arrives as a number, `"true"` as a boolean), fires `@Watch`
870
+ * callbacks and `didChange()`, and schedules a render. Prefer those
871
+ * decorators over overriding this hook — but if you must, call
872
+ * `super.attributeChangedCallback(...)` first so the reactive plumbing
873
+ * still runs.
874
+ *
875
+ * The browser only calls this hook for attributes named in
876
+ * `observedAttributes`. Fields declared with `@Attribute` or
877
+ * `@Property({ attribute: true })` register themselves in that list
878
+ * automatically.
879
+ *
880
+ * @param property - The attribute name that changed.
881
+ * @param oldValue - The previous attribute value, or `null` if unset.
882
+ * @param newValue - The new attribute value, or `null` if removed.
320
883
  *
321
884
  * @example
322
- * // Async rendering
323
- * async render() {
324
- * const data = await fetchData();
325
- * return html`<div>${data.name}</div>`;
885
+ * class MyButton extends Component {
886
+ * @Attribute() disabled = false;
887
+ * // Pandora keeps `disabled` in sync with the DOM attribute for you.
326
888
  * }
889
+ */
890
+ attributeChangedCallback(property: string, _oldValue: string | null, newValue: string | null): void;
891
+ /**
892
+ * The set of `@Listen` bindings currently wired up on this instance.
893
+ * We track them explicitly so `_detachListeners` can remove the exact
894
+ * `(target, event, handler, options)` triples we registered — this matters
895
+ * on disconnect and between renders, when listener targets may have been
896
+ * replaced.
327
897
  *
328
- * @returns The HTML string, lit-html TemplateResult, or Promise resolving to either
898
+ * @internal
329
899
  */
330
- render(): string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing>;
331
- _render(): Promise<void>;
332
- connectedCallback(): Promise<void>;
333
- ready(callback: ReadyCallback): void;
334
- disconnectedCallback(): Promise<void>;
335
- updateCallback(property: string, oldValue: unknown, newValue: unknown, origin?: 'props' | 'state' | 'attribute', oldObject?: P | S, newObject?: P | S): Promise<void>;
900
+ private _activeListeners;
901
+ /**
902
+ * Walks `@Listen` metadata and wires up the described listeners against
903
+ * their resolved targets. We resolve selectors at attach time (not at
904
+ * decoration time) because the target nodes may only exist after a render
905
+ * has populated the component's subtree.
906
+ *
907
+ * @internal
908
+ */
909
+ protected _attachListeners(): void;
336
910
  /**
337
- * Called when an observed attribute changes.
338
- * This is a Web Components lifecycle callback.
911
+ * Removes every listener currently recorded in `_activeListeners` and
912
+ * clears the tracking array. Called on disconnect and between renders so
913
+ * stale bindings never outlive the nodes they pointed at.
339
914
  *
340
- * @param property - The name of the attribute that changed
341
- * @param oldValue - The previous value of the attribute
342
- * @param newValue - The new value of the attribute
915
+ * @internal
343
916
  */
344
- attributeChangedCallback(property: string, oldValue: string | null, newValue: string | null): void;
917
+ protected _detachListeners(): void;
345
918
  }
346
919
  export default Component;
347
920
  //# sourceMappingURL=Component.d.ts.map