@aegis-framework/pandora 0.4.2 → 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,329 +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
- static _tag?: string;
19
- static _template?: string | ((context: any) => string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing>);
20
- 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
+ */
21
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
+ */
22
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
+ */
23
166
  static _onError?: (error: Error, component: Component, tag: string, lifecycle: string) => void;
24
- 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
+ */
25
180
  static _hasMiddleware?: (type: string) => boolean;
26
181
  /**
27
- * Returns the list of attributes to observe for changes.
28
- * 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.
29
185
  *
30
- * @returns {string[]} - Array of attribute names to observe
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
+ * }
227
+ *
228
+ * MyButton.observedAttributes; // ['disabled']
31
229
  */
32
230
  static get observedAttributes(): string[];
33
231
  /**
34
- * Sets the list of attributes to observe for changes.
232
+ * Overrides the list of observed attributes for this class.
233
+ *
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.
35
238
  *
36
- * @param value - The new list of attributes to observe
239
+ * @param value - The attribute names the component should react to.
37
240
  */
38
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
+ */
39
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
+ */
40
269
  static set tag(value: string);
41
270
  /**
42
- * Set or get the static template for this component class.
271
+ * The class-level template used in place of `render()` when defined.
272
+ *
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.
43
276
  *
44
- * Templates can be:
45
- * - A string: `'<div>Hello</div>'`
46
- * - A function returning string: `(ctx) => \`<div>\${ctx.props.name}</div>\``
47
- * - A function returning lit-html: `(ctx) => html\`<div>\${ctx.props.name}</div>\``
48
- * - An async function: `async (ctx) => { const data = await fetch(); return html\`...\`; }`
277
+ * @returns The template, or `undefined` if the component renders through
278
+ * `render()`.
49
279
  *
50
- * @param html - The template to set, or null to get the current template result
51
- * @param context - The context to use when calling template functions (usually the component instance)
52
- * @returns The rendered template when getting, void when setting
280
+ * @example
281
+ * MyGreeting.template = (self) => `<p>Hello, ${self.name}.</p>`;
53
282
  */
54
- 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;
55
- constructor();
56
- get width(): number;
57
- set width(value: number | string);
58
- get height(): number;
59
- set height(value: number | string);
60
- get static(): typeof Component;
61
- set static(value: typeof Component);
62
- get props(): P;
63
- set props(value: P);
64
- get state(): S;
65
- set state(value: S);
66
- get dom(): HTMLElement;
67
- set dom(value: HTMLElement);
68
- /**
69
- * Returns the original innerHTML content that was present before the component rendered.
70
- *
71
- * This is an alias for `_children`
72
- *
73
- * @example
74
- * // String template
75
- * render() {
76
- * 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
+ * }
77
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.
78
326
  *
79
327
  * @example
80
- * // lit-html template
81
- * render() {
82
- * return html`<div class="wrapper">${this.slotContent}</div>`;
328
+ * class MyCard extends Component {
329
+ * render() {
330
+ * return `<div class="card">${this.slotContent}</div>`;
331
+ * }
83
332
  * }
333
+ *
334
+ * // <my-card>Hello</my-card> → <div class="card">Hello</div>
84
335
  */
85
336
  get slotContent(): string;
86
337
  /**
87
- * 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
+ * }
88
352
  */
89
353
  get isConnected(): boolean;
90
354
  /**
91
- * 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
+ * }
92
371
  */
93
372
  get isReady(): boolean;
94
373
  /**
95
- * register - Register the component as a custom HTML element
96
- * using the component's tag as the actual element tag.
97
- *
98
- * This action cannot be reverted nor the controller class for
99
- * the element can be changed.
100
- */
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
+ * }
389
+ */
390
+ get isFirstMount(): boolean;
391
+ /**
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
+ */
101
415
  static register(): void;
102
416
  /**
103
- * Instance method to set or get the template.
104
- * 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).
105
461
  *
106
- * @param html - The template to set, or null to get the current template result
107
- * @returns The rendered template when getting, void when setting
462
+ * @internal
108
463
  */
109
- 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;
110
- static _styleSheet: CSSStyleSheet | null;
464
+ protected _queueRender(): void;
111
465
  /**
112
- * Sets the component style. For normal components, styles are scoped to the
113
- * component's tag name as a selector prefix and shared across all instances
114
- * 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.
472
+ *
473
+ * @returns A promise that resolves once the render (including async
474
+ * `render()` returns and `didRender()`) has completed.
115
475
  *
116
- * @param style - CSS object or string to apply
117
- * @param reset - If true, replaces all styles; if false, merges with existing
118
- * @returns The current style object
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; }');
119
561
  */
120
562
  setStyle(style: Style | string, reset?: boolean): Style;
121
- setState(state: Partial<S>): void;
122
- setProps(props: Partial<P>): void;
123
- _setPropAttributes(update?: boolean): void;
124
563
  /**
125
- * Adds an event listener to the component.
564
+ * Attaches an event listener to the component.
565
+ *
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.
126
570
  *
127
- * @param event - The event type to listen for
128
- * @param callback - The callback function to execute when the event occurs
129
- * @param options - Optional event listener options
130
- * @returns The component instance for chaining
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'));
131
579
  */
132
580
  on<K extends keyof HTMLElementEventMap>(event: K, callback: (this: this, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): this;
133
581
  on(event: string, callback: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): this;
134
582
  /**
135
- * Removes an event listener from the component.
583
+ * Removes a previously attached event listener from the component.
136
584
  *
137
- * @param event - The event type to remove the listener for
138
- * @param callback - The callback function to remove
139
- * @param options - Optional event listener options
140
- * @returns The component instance for chaining
585
+ * Pass the same event name, callback reference, and options you used in
586
+ * `on()` / `once()` — the underlying `removeEventListener` only matches
587
+ * exact triples.
588
+ *
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);
141
599
  */
142
600
  off<K extends keyof HTMLElementEventMap>(event: K, callback: (this: this, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): this;
143
601
  off(event: string, callback: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): this;
144
602
  /**
145
- * 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.
146
608
  *
147
- * @param event - The event type to listen for
148
- * @param callback - The callback function to execute when the event occurs
149
- * @param options - Optional event listener options
150
- * @returns The component instance for chaining
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.
614
+ *
615
+ * @example
616
+ * modal.once('animationend', () => modal.remove());
151
617
  */
152
618
  once<K extends keyof HTMLElementEventMap>(event: K, callback: (this: this, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): this;
153
619
  once(event: string, callback: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): this;
154
620
  /**
155
- * 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`.
156
627
  *
157
- * @param event - The event name to emit
158
- * @param detail - Optional data to include with the event
159
- * @param options - Optional CustomEvent init options (bubbles, cancelable, composed)
160
- * @returns Whether the event was not cancelled
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`.
633
+ *
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));
161
644
  */
162
645
  emit<T = unknown>(event: string, detail?: T, options?: Omit<CustomEventInit<T>, 'detail'>): boolean;
163
646
  /**
164
- * Queries for a single element within the component's DOM.
647
+ * Finds the first descendant matching the given CSS selector.
165
648
  *
166
- * @param selector - CSS selector to query for
167
- * @returns The first matching element or null
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.
653
+ *
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
+ * }
168
661
  */
169
662
  query<E extends Element = Element>(selector: string): E | null;
170
663
  /**
171
- * Queries for all matching elements within the component's DOM.
664
+ * Finds every descendant matching the given CSS selector.
172
665
  *
173
- * @param selector - CSS selector to query for
174
- * @returns A NodeList of all matching elements
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.
669
+ *
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
+ * }
175
677
  */
176
678
  queryAll<E extends Element = Element>(selector: string): NodeListOf<E>;
177
679
  /**
178
- * Called before the component updates due to state or props changes.
179
- * 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.
180
683
  *
181
- * @param origin - Whether the update was triggered by 'state' or 'props'
182
- * @param property - The name of the property that changed
183
- * @param oldValue - The previous value of the property
184
- * @param newValue - The new value of the property
185
- * @param oldObject - The previous state/props object
186
- * @param newObject - The new state/props object
187
- * @returns A promise that resolves when the pre-update logic completes
684
+ * @internal
188
685
  */
189
- willUpdate(_origin: string, _property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
686
+ private _readyCallbacks?;
190
687
  /**
191
- * Called when the component updates due to state or props changes.
192
- * 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.
193
690
  *
194
- * @param origin - Whether the update was triggered by 'state' or 'props'
195
- * @param property - The name of the property that changed
196
- * @param oldValue - The previous value of the property
197
- * @param newValue - The new value of the property
198
- * @param oldObject - The previous state/props object
199
- * @param newObject - The new state/props object
200
- * @returns A promise that resolves when the update logic completes
201
- */
202
- update(_origin: string, _property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
203
- /**
204
- * Called after the component updates due to state or props changes.
205
- * 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.
206
696
  *
207
- * @param origin - Whether the update was triggered by 'state' or 'props'
208
- * @param property - The name of the property that changed
209
- * @param oldValue - The previous value of the property
210
- * @param newValue - The new value of the property
211
- * @param oldObject - The previous state/props object
212
- * @param newObject - The new state/props object
213
- * @returns A promise that resolves when the post-update logic completes
697
+ * @param callback - The function to run when the component is ready.
698
+ *
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
+ * }
214
710
  */
215
- didUpdate(_origin: string, _property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
711
+ ready(callback: () => void): void;
216
712
  /**
217
- * Called when the component's state updates.
218
- * Override this method to react specifically to state changes.
713
+ * Runs just before the component's first render.
714
+ *
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.
219
719
  *
220
- * @param property - The name of the state property that changed
221
- * @param oldValue - The previous value of the property
222
- * @param newValue - The new value of the property
223
- * @param oldObject - The previous state object
224
- * @param newObject - The new state object
225
- * @returns A promise that resolves when the state update logic completes
720
+ * @example
721
+ * async willMount() {
722
+ * this.data = await fetch('/api/profile').then(r => r.json());
723
+ * }
226
724
  */
227
- onStateUpdate(_property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
725
+ willMount(): Promise<void>;
228
726
  /**
229
- * Called when the component's props update.
230
- * Override this method to react specifically to props changes.
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).
231
734
  *
232
- * @param property - The name of the prop that changed
233
- * @param oldValue - The previous value of the property
234
- * @param newValue - The new value of the property
235
- * @param oldObject - The previous props object
236
- * @param newObject - The new props object
237
- * @returns A promise that resolves when the props update logic completes
735
+ * @example
736
+ * async didMount() {
737
+ * this.query('input')?.focus();
738
+ * }
238
739
  */
239
- onPropsUpdate(_property: string, _oldValue: unknown, _newValue: unknown, _oldObject: unknown, _newObject: unknown): Promise<void>;
740
+ didMount(): Promise<void>;
240
741
  /**
241
- * Called before the component is mounted to the DOM.
242
- * Override this method to perform setup before rendering.
742
+ * Runs after every render cycle.
743
+ *
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.
243
749
  *
244
- * @returns A promise that resolves when the pre-mount logic completes
750
+ * @example
751
+ * async didRender() {
752
+ * this._chart?.destroy();
753
+ * this._chart = createChart(this.query('canvas'));
754
+ * }
245
755
  */
246
- willMount(): Promise<void>;
756
+ didRender(): Promise<void>;
247
757
  /**
248
- * Called after the component is mounted to the DOM.
249
- * Override this method to perform actions after the component is rendered.
758
+ * Runs when the component is re-attached to the DOM after being
759
+ * disconnected.
760
+ *
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()`.
250
764
  *
251
- * @returns A promise that resolves when the post-mount logic completes
765
+ * @example
766
+ * async didReconnect() {
767
+ * this._timer = setInterval(() => this.tick(), 1000);
768
+ * }
252
769
  */
253
- didMount(): Promise<void>;
770
+ didReconnect(): Promise<void>;
254
771
  /**
255
- * Called before the component is removed from the DOM.
256
- * Override this method to perform cleanup before 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.
257
777
  *
258
- * @returns A promise that resolves when the pre-unmount logic completes
778
+ * @example
779
+ * async willUnmount() {
780
+ * this._abort.abort();
781
+ * }
259
782
  */
260
783
  willUnmount(): Promise<void>;
261
784
  /**
262
- * Called when the component is being removed from the DOM.
263
- * Override this method to perform cleanup during unmounting.
785
+ * Runs after the component has been removed from the DOM.
264
786
  *
265
- * @returns A promise that resolves when the unmount logic completes
266
- */
267
- unmount(): Promise<void>;
268
- /**
269
- * Called after the component is removed from the DOM.
270
- * Override this method to perform final cleanup after unmounting.
787
+ * By this point the element is no longer in the document. Use it for
788
+ * final cleanup — releasing references, logging, telemetry.
271
789
  *
272
- * @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
+ * }
273
794
  */
274
795
  didUnmount(): Promise<void>;
275
796
  /**
276
- * Forces the component to be rendered again.
797
+ * Runs every time one of the component's reactive fields changes.
277
798
  *
278
- * @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
+ * }
279
820
  */
280
- forceRender(): Promise<void>;
821
+ didChange(_property: string, _oldValue: unknown, _newValue: unknown, _source?: string): void;
281
822
  /**
282
- * Returns the content for the component.
283
- * Override this method to define the component's template.
823
+ * The standard custom-elements hook Pandora uses to drive mounting.
284
824
  *
285
- * You can return either:
286
- * - A string (traditional HTML string)
287
- * - A lit-html TemplateResult (for efficient DOM diffing)
288
- * - `nothing` from lit-html (to render nothing)
289
- * - 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.
290
832
  *
291
833
  * @example
292
- * // String-based rendering
293
- * render() {
294
- * 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
295
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()`.
296
848
  *
297
849
  * @example
298
- * // lit-html rendering
299
- * render() {
300
- * return html`<div>Hello ${this.state.name}</div>`;
850
+ * async disconnectedCallback() {
851
+ * await super.disconnectedCallback();
852
+ * this.releaseExternalResource();
301
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.
302
875
  *
303
876
  * @example
304
- * // Async rendering
305
- * async render() {
306
- * const data = await fetchData();
307
- * 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.
308
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.
309
889
  *
310
- * @returns The HTML string, lit-html TemplateResult, or Promise resolving to either
890
+ * @internal
311
891
  */
312
- render(): string | TemplateResult | typeof nothing | Promise<string | TemplateResult | typeof nothing>;
313
- _render(): Promise<void>;
314
- connectedCallback(): Promise<void>;
315
- ready(callback: ReadyCallback): void;
316
- disconnectedCallback(): Promise<void>;
317
- 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;
318
902
  /**
319
- * Called when an observed attribute changes.
320
- * 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.
321
906
  *
322
- * @param property - The name of the attribute that changed
323
- * @param oldValue - The previous value of the attribute
324
- * @param newValue - The new value of the attribute
907
+ * @internal
325
908
  */
326
- attributeChangedCallback(property: string, oldValue: string | null, newValue: string | null): void;
909
+ protected _detachListeners(): void;
327
910
  }
328
911
  export default Component;
329
912
  //# sourceMappingURL=Component.d.ts.map