@aegis-framework/pandora 0.5.0 → 0.6.0

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