@webjsdev/core 0.7.50 → 0.7.51

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.
Files changed (57) hide show
  1. package/dist/webjs-core-browser.js +5 -5
  2. package/dist/webjs-core-browser.js.map +3 -3
  3. package/dist/webjs-core-testing.js +20 -20
  4. package/dist/webjs-core-testing.js.map +3 -3
  5. package/dist/webjs-core.js +7 -7
  6. package/dist/webjs-core.js.map +3 -3
  7. package/index-browser.js +1 -1
  8. package/index.d.ts +1 -1
  9. package/index.js +1 -1
  10. package/package.json +1 -1
  11. package/src/component/lifecycle.js +1481 -0
  12. package/src/component/reactive.js +171 -0
  13. package/src/component/server-element.js +248 -0
  14. package/src/component.js +2 -1896
  15. package/src/render-client/parts.js +2007 -0
  16. package/src/render-client/reconciler.js +388 -0
  17. package/src/render-client/template-compiler.js +525 -0
  18. package/src/render-client.js +1 -2938
  19. package/src/render-server/attrs.js +160 -0
  20. package/src/render-server/dsd.js +445 -0
  21. package/src/render-server/html-scan.js +402 -0
  22. package/src/render-server/slots.js +213 -0
  23. package/src/render-server/stream.js +163 -0
  24. package/src/render-server/template-renderer.js +923 -0
  25. package/src/render-server/text.js +163 -0
  26. package/src/render-server.js +6 -2405
  27. package/src/router-client/anchors.js +44 -0
  28. package/src/router-client/boundaries.js +221 -0
  29. package/src/router-client/constants.js +187 -0
  30. package/src/router-client/diagnostics.js +377 -0
  31. package/src/router-client/dom-differ.js +709 -0
  32. package/src/router-client/dom-parse.js +150 -0
  33. package/src/router-client/events.js +139 -0
  34. package/src/router-client/fetch-apply.js +387 -0
  35. package/src/router-client/form-encoder.js +135 -0
  36. package/src/router-client/frames.js +329 -0
  37. package/src/router-client/head-merge.js +344 -0
  38. package/src/router-client/nav-error.js +105 -0
  39. package/src/router-client/navigator.js +781 -0
  40. package/src/router-client/prefetch.js +824 -0
  41. package/src/router-client/scroll.js +259 -0
  42. package/src/router-client/snapshot-cache.js +97 -0
  43. package/src/router-client/state.js +92 -0
  44. package/src/router-client/stream.js +206 -0
  45. package/src/router-client/swap.js +451 -0
  46. package/src/router-client/upgrade.js +261 -0
  47. package/src/router-client/view-transition.js +223 -0
  48. package/src/router-client.d.ts +10 -1
  49. package/src/router-client.js +75 -5345
  50. package/src/slot/assignment.js +304 -0
  51. package/src/slot/interception.js +558 -0
  52. package/src/slot/polyfills.js +365 -0
  53. package/src/slot/project.js +432 -0
  54. package/src/slot/sensors.js +303 -0
  55. package/src/slot/state.js +245 -0
  56. package/src/slot/symbols.js +85 -0
  57. package/src/slot.js +7 -2199
package/src/component.js CHANGED
@@ -1,1896 +1,2 @@
1
- import { render as clientRender } from './render-client.js';
2
- import { readAttributeValue } from './attribute-reader.js';
3
- import { setActiveActionSignal } from './action-abort-client.js';
4
- import { carriesFunction } from './form-action.js';
5
- import { isCSS, adoptStyles } from './css.js';
6
- import { register, tagOf } from './registry.js';
7
- import { parse as deserializeProp } from './serialize.js';
8
- import { Signal } from './signal.js';
9
- import { resolveAttributeProperty } from './attribute-reader.js';
10
- import {
11
- captureAuthoredChildren,
12
- adoptSSRAssignments,
13
- ensureSlotState,
14
- hasSlotState,
15
- hasFrameworkRenderedSubtree,
16
- installSlotInterception,
17
- installSlotSensors,
18
- teardownSlotSensors,
19
- reconnectSweep,
20
- } from './slot.js';
21
-
22
- const isBrowser = typeof window !== 'undefined' && typeof HTMLElement !== 'undefined';
23
-
24
- /**
25
- * @typedef {Object} ReactiveController
26
- * A controller is a reusable piece of lifecycle logic that plugs into a
27
- * WebComponent host. Controllers let you extract cross-cutting concerns
28
- * (timers, intersection observers, media queries, form validation, fetch
29
- * caching) out of the component class and share them across unrelated
30
- * components.
31
- *
32
- * **When to use:** any time two or more components need the same
33
- * `connectedCallback` / `disconnectedCallback` / pre-render / post-render
34
- * behaviour. Instead of a mixin or base-class hierarchy, attach a controller.
35
- *
36
- * **Why it exists:** mirrors Lit's `ReactiveController` protocol so
37
- * ecosystem controllers are interoperable.
38
- *
39
- * @property {() => void} [hostConnected]
40
- * Called when the host element is inserted into the DOM
41
- * (`connectedCallback`). Use for subscriptions, observers, timers.
42
- * @property {() => void} [hostDisconnected]
43
- * Called when the host element is removed from the DOM
44
- * (`disconnectedCallback`). Use for cleanup: unsubscribe, disconnect
45
- * observers, clear timers.
46
- * @property {() => void} [hostUpdate]
47
- * Called just before the host renders (inside `_performRender`, after
48
- * `willUpdate` but before `render()`). Use for reading layout or
49
- * preparing data that the render depends on.
50
- * @property {() => void} [hostUpdated]
51
- * Called after the host has rendered and the DOM is up to date. Use for
52
- * post-render side effects that depend on the new DOM (measuring,
53
- * focusing, scrolling).
54
- */
55
-
56
- /**
57
- * @typedef {Object} PropertyDeclaration
58
- * Declares how a single reactive property behaves. Used inside
59
- * `static properties = { propName: { …declaration } }`.
60
- *
61
- * @property {Function} [type]
62
- * Constructor used for attribute → property coercion.
63
- * Supported built-ins: `String`, `Number`, `Boolean`, `Object`, `Array`.
64
- * Default: `String`.
65
- *
66
- * @property {boolean} [reflect]
67
- * When `true`, writing to the property also sets the corresponding
68
- * HTML attribute on the element (kebab-cased). Useful when you want
69
- * CSS attribute selectors like `my-el[mode="dark"]` to work.
70
- *
71
- * @property {boolean} [state]
72
- * When `true`, the property is *internal-only*: it is NOT exposed as an
73
- * HTML attribute (excluded from `observedAttributes`) and never reflects.
74
- * It still triggers a re-render when changed via the generated setter.
75
- * Use for private reactive state that shouldn't leak into the DOM.
76
- *
77
- * @property {(newValue: unknown, oldValue: unknown) => boolean} [hasChanged]
78
- * Custom dirty-check function. Called by the generated setter before
79
- * scheduling an update. Return `true` to trigger a re-render, `false`
80
- * to skip. Default: strict inequality `(a, b) => a !== b`.
81
- *
82
- * Note: this fires on the FIRST assignment too, with `oldValue` set
83
- * to `undefined`. Numeric comparators that subtract against undefined
84
- * produce `NaN`, which evaluates to `false`, silently rejecting the
85
- * constructor's initial assignment. Treat `oldValue === undefined` as
86
- * "always changed" in custom comparators so the initial value lands.
87
- *
88
- * @property {{ fromAttribute: (value: string|null, type?: Function) => unknown, toAttribute: (value: unknown, type?: Function) => string|null }} [converter]
89
- * Custom serialization/deserialization pair for the HTML attribute.
90
- * `fromAttribute` is called by BOTH attribute readers through the shared
91
- * `readAttributeValue` in `attribute-reader.js`: the client
92
- * `attributeChangedCallback` and the SSR
93
- * `applyAttrsToInstance` in `render-server.js` (#1340). So it runs
94
- * server-side too, and must not touch browser globals.
95
- * `toAttribute` is called when reflecting back to the attribute.
96
- * If omitted, the built-in type-based coercion is used.
97
- */
98
-
99
- /**
100
- * Default change detection: strict inequality.
101
- * @param {unknown} a
102
- * @param {unknown} b
103
- * @returns {boolean}
104
- */
105
- function defaultHasChanged(a, b) {
106
- return a !== b;
107
- }
108
-
109
-
110
- /**
111
- * `String(v)` that cannot itself throw.
112
- *
113
- * A rejection reason is whatever the author rejected with, and not every value
114
- * converts to a primitive: `Object.create(null)` has no `toString`, and a
115
- * revoked Proxy throws on any operation. Coercing one in an error-reporting
116
- * path turned a reportable failure into a second, unreported one.
117
- *
118
- * @param {unknown} v
119
- * @returns {string}
120
- */
121
- function safeString(v) {
122
- try {
123
- return String(v);
124
- } catch {
125
- return Object.prototype.toString.call(v);
126
- }
127
- }
128
-
129
- /**
130
- * Warn that a function value was dropped rather than reflected (#1169).
131
- *
132
- * A silently missing attribute is its own confusion, so say what went and why.
133
- * The message deliberately does NOT include the value: printing the source is
134
- * the leak this guard exists to prevent, and a server log is not always a
135
- * private place.
136
- *
137
- * UNCONDITIONAL, matching the `.prop=${fn}` unserializable-value drop in
138
- * `render-server.js`, which is the sibling path this guard mirrors. Two
139
- * reasons not to gate it on a dev flag. It fires only on a genuine mistake (a
140
- * function is never a meaningful attribute value), so there is no volume to
141
- * suppress, and reflection runs per assignment rather than per frame.
142
- *
143
- * More decisively, a `NODE_ENV` gate does not survive the dist build.
144
- * `scripts/build-framework-dist.js` runs esbuild with `platform: 'browser'`
145
- * and `minify: true`, which substitutes `process.env.NODE_ENV` with
146
- * `"production"` and folds the check to a constant. The SSR half of the
147
- * warning would then be unreachable in every published build, which is how
148
- * every installed app runs, and SSR is the half that matters most, since that
149
- * is where the leaked source reached visitors.
150
- *
151
- * @param {{ constructor: unknown, tagName?: string }} host
152
- * @param {string} propName
153
- * @param {string} attrName
154
- */
155
- function warnFunctionReflection(host, propName, attrName) {
156
- if (typeof console === 'undefined' || !console.warn) return;
157
- const tag = tagOf(/** @type any */ (host.constructor)) || host.tagName?.toLowerCase() || 'unknown';
158
- console.warn(
159
- `[webjs] reflect:true property "${propName}" on <${tag}> holds a function `
160
- + `(or an array carrying one), which has no HTML attribute representation. `
161
- + `Removing "${attrName}" instead of stringifying it (a stringified function `
162
- + `writes its source into the page, so a server action's body would ship to `
163
- + `the browser). Pass a string, or drop reflect on this property.`
164
- );
165
- }
166
-
167
- /**
168
- * Warn that a value with no JSON representation was dropped rather than
169
- * reflected (#1253).
170
- *
171
- * `JSON.stringify` throws for three reasons an app hits in practice: a cycle,
172
- * a `BigInt`, and an author `toJSON()` that throws. All three mean the same
173
- * thing here, that there is no string to put in the attribute, so all three
174
- * get the same answer as a function does.
175
- *
176
- * The caught message IS included, unlike `warnFunctionReflection`, which
177
- * withholds its value on purpose. A function's string form is its source,
178
- * which is the leak that guard exists to prevent; `JSON.stringify`'s own
179
- * message names the property path rather than a value, and the sibling
180
- * `.prop=${val}` SSR drop in `render-server.js` already ends the same way.
181
- *
182
- * UNCONDITIONAL, for the reason recorded on `warnFunctionReflection` above: a
183
- * `NODE_ENV` gate is folded to a constant by the dist build, which would make
184
- * the SSR half unreachable in every published build, and the SSR half is where
185
- * the component silently vanishes.
186
- *
187
- * @param {{ constructor: unknown, tagName?: string }} host
188
- * @param {string} propName
189
- * @param {string} attrName
190
- * @param {string} [detail] the message `JSON.stringify` threw
191
- */
192
- function warnUnserializableReflection(host, propName, attrName, detail) {
193
- if (typeof console === 'undefined' || !console.warn) return;
194
- const tag = tagOf(/** @type any */ (host.constructor)) || host.tagName?.toLowerCase() || 'unknown';
195
- console.warn(
196
- `[webjs] reflect:true property "${propName}" on <${tag}> holds a value `
197
- + `JSON.stringify cannot serialize (a cycle, a BigInt, or a throwing `
198
- + `toJSON), so it has no HTML attribute representation. Removing `
199
- + `"${attrName}" instead. Detail: ${detail}`
200
- );
201
- }
202
-
203
- /**
204
- * A minimal base for HTML Custom Elements that mirrors Lit's ergonomics
205
- * while staying JSDoc-only and no-build.
206
- *
207
- * Subclasses declare:
208
- * - `static properties`: attribute/property declarations with type info,
209
- * reflection, custom converters, and internal-state mode
210
- * - `static styles`: CSSResult or array thereof (only meaningful with
211
- * `static shadow = true`; light-DOM components inherit global CSS)
212
- * - `static shadow`: set `true` to opt in to shadow DOM (default: `false`
213
- * → light DOM, so Tailwind / global CSS apply directly)
214
- * - `render()`: returns a TemplateResult
215
- *
216
- * The tag name is not a static field: pass it to `.register('tag-name')`
217
- * at the bottom of the file. Tag must contain a hyphen (HTML spec).
218
- *
219
- * Lifecycle (lit-aligned, called in order during each update cycle):
220
- * 1. `shouldUpdate(changedProperties)`. Skip update if false.
221
- * 2. `willUpdate(changedProperties)`. Safe to set properties; folds into this cycle.
222
- * 3. controllers' `hostUpdate()`
223
- * 4. `update(changedProperties)`. Default impl calls `render()` + commits.
224
- * 5. controllers' `hostUpdated()`
225
- * 6. `firstUpdated(changedProperties)`: once, on the first render only
226
- * 7. `updated(changedProperties)`: every render commit
227
- * 8. `updateComplete` promise resolves
228
- *
229
- * `changedProperties` is a `Map<string, unknown>` where each entry maps
230
- * a property name to its previous value.
231
- *
232
- * MAINTAINER NOTE. Adding a new overridable lifecycle hook here means
233
- * the display-only component elision analyser must learn about it too,
234
- * or it will wrongly elide a component that now does client work. Add
235
- * the hook name to `CLIENT_LIFECYCLE_HOOKS` in
236
- * `packages/server/src/component-elision.js`. The guard test at
237
- * `packages/server/test/elision/lifecycle-coverage.test.js` introspects
238
- * this prototype and fails until you do.
239
- *
240
- * Usage:
241
- * ```js
242
- * import { signal } from '@webjsdev/core';
243
- *
244
- * const count = signal(0);
245
- *
246
- * class MyCounter extends WebComponent {
247
- * render() {
248
- * return html`<button @click=${() => count.set(count.get() + 1)}>${count.get()}</button>`;
249
- * }
250
- * }
251
- * MyCounter.register('my-counter');
252
- * ```
253
- */
254
-
255
- /**
256
- * Inert `ElementInternals`-shaped object returned by the server shim's
257
- * `attachInternals()`. Modeled on `@lit-labs/ssr-dom-shim`'s
258
- * `ElementInternalsShim` (lit repo, `packages/labs/ssr-dom-shim/src/lib/
259
- * element-internals.ts`): form-association, validity, and custom-state
260
- * calls are no-ops at SSR (no form, no constraint validation, no `:state()`
261
- * matching server-side), so a component that calls `this.attachInternals()`
262
- * in its constructor renders instead of crashing. The browser runs the real
263
- * `attachInternals()` on hydration.
264
- *
265
- * Deliberate deviation from lit: lit's `checkValidity` / `reportValidity`
266
- * THROW on the server. WebJs returns `true` instead, to keep SSR
267
- * progressive-enhancement-safe (a stray validity call in a constructor must
268
- * not 500 the page); the browser does the real validation.
269
- * @returns {any}
270
- */
271
- function makeServerInternals() {
272
- return {
273
- states: new Set(),
274
- shadowRoot: null,
275
- form: null,
276
- labels: [],
277
- role: '',
278
- willValidate: true,
279
- validity: /** @type {any} */ ({}),
280
- validationMessage: '',
281
- setFormValue() {},
282
- setValidity() {},
283
- checkValidity() { return true; },
284
- reportValidity() { return true; },
285
- };
286
- }
287
-
288
- /**
289
- * Server-side stand-in for `HTMLElement`. The SSR pipeline constructs
290
- * component instances in Node, where `HTMLElement` does not exist, so the
291
- * base class is this shim. It is modeled on `@lit-labs/ssr-dom-shim`'s
292
- * `ElementShim` (lit repo, `packages/labs/ssr-dom-shim/src/index.ts`): the
293
- * attribute methods (`getAttribute` / `setAttribute` / `hasAttribute` /
294
- * `removeAttribute` / `toggleAttribute`, the `attributes` getter) are backed
295
- * by a Map, so lit muscle-memory patterns that read attributes in `render()`
296
- * or set them while deriving state work server-side; the SSR walker seeds
297
- * the Map from the element's source attributes and reads it back to surface
298
- * reflected/added attributes in the output. Event methods are no-ops (no
299
- * server event loop), and `attachInternals()` returns the inert object
300
- * above. The genuinely browser-only surface (`querySelector`, layout reads,
301
- * `attachShadow`, `focus`) is deliberately absent and still throws at SSR,
302
- * which the `no-browser-globals-in-render` rule and the SSR crash hint flag.
303
- *
304
- * Deliberate deviation from lit: this shim lowercases attribute names so
305
- * `getAttribute('Foo')` after `setAttribute('foo', x)` resolves, matching how
306
- * a real browser treats HTML attribute names as case-insensitive. lit's shim
307
- * keys the Map by the raw name (a known fidelity gap in lit-labs).
308
- */
309
- class ServerElement {
310
- constructor() {
311
- /**
312
- * Backing store for the attribute methods. Keys are lowercased
313
- * attribute names (HTML attributes are case-insensitive). Seeded by the
314
- * SSR walker from the element's source attributes.
315
- * @type {Map<string, string>}
316
- */
317
- this.__ssrAttrs = new Map();
318
- /** @type {any} */
319
- this.__internals = null;
320
- }
321
-
322
- /** Mirrors `Element.attributes`: an array of `{ name, value }`. */
323
- get attributes() {
324
- return [...this.__ssrAttrs].map(([name, value]) => ({ name, value }));
325
- }
326
-
327
- /** @param {string} name */
328
- getAttribute(name) {
329
- const v = this.__ssrAttrs.get(String(name).toLowerCase());
330
- return v === undefined ? null : v;
331
- }
332
-
333
- /** @param {string} name @param {unknown} value */
334
- setAttribute(name, value) {
335
- // Emulate the browser casting all values to string (lit does the same).
336
- this.__ssrAttrs.set(String(name).toLowerCase(), String(value));
337
- }
338
-
339
- /** @param {string} name */
340
- removeAttribute(name) {
341
- this.__ssrAttrs.delete(String(name).toLowerCase());
342
- }
343
-
344
- /** @param {string} name */
345
- hasAttribute(name) {
346
- return this.__ssrAttrs.has(String(name).toLowerCase());
347
- }
348
-
349
- /** @param {string} name @param {boolean} [force] */
350
- toggleAttribute(name, force) {
351
- // Steps mirror https://dom.spec.whatwg.org/#dom-element-toggleattribute
352
- const key = String(name).toLowerCase();
353
- const present = this.__ssrAttrs.has(key);
354
- const next = force === undefined ? !present : force;
355
- if (next) {
356
- this.__ssrAttrs.set(key, '');
357
- return true;
358
- }
359
- this.__ssrAttrs.delete(key);
360
- return false;
361
- }
362
-
363
- /** @returns {string[]} */
364
- getAttributeNames() {
365
- return [...this.__ssrAttrs.keys()];
366
- }
367
-
368
- /**
369
- * Minimal `Element.closest()` for SSR. The SSR walker threads the chain
370
- * of enclosing custom-element instances into each instance
371
- * (`__ssrAncestors`); this walks self-then-ancestors and returns the
372
- * nearest whose tag matches. Only bare tag-name selectors are supported
373
- * server-side (`closest('ui-tabs')`), which is what compound components
374
- * need to read parent state for a correct first paint; anything more
375
- * specific (class, attribute, or descendant selectors) returns null,
376
- * matching the pre-shim behaviour. The browser runs the real `closest()`
377
- * on hydration.
378
- * @param {string} selector
379
- * @returns {any}
380
- */
381
- closest(selector) {
382
- const sel = String(selector).trim().toLowerCase();
383
- // Tag-name selectors only at SSR; bail (null) on anything else.
384
- if (!/^[a-z][a-z0-9-]*$/.test(sel)) return null;
385
- if (this.__ssrTag === sel) return this;
386
- const chain = this.__ssrAncestors;
387
- if (!Array.isArray(chain)) return null;
388
- for (let i = chain.length - 1; i >= 0; i--) {
389
- if (chain[i] && chain[i].__ssrTag === sel) return chain[i];
390
- }
391
- return null;
392
- }
393
-
394
- /**
395
- * `HTMLElement.dataset`: a live view over the element's `data-*`
396
- * attributes, backed by the SSR attribute Map. Reading / writing
397
- * `el.dataset.fooBar` maps to the `data-foo-bar` attribute (camelCase
398
- * to kebab-case), so a `render()` that sets `this.dataset.state = 'on'`
399
- * surfaces `data-state="on"` in the SSR'd host tag instead of crashing
400
- * on an undefined `dataset`.
401
- * @returns {Record<string, string>}
402
- */
403
- get dataset() {
404
- if (this.__dataset) return this.__dataset;
405
- const el = this;
406
- const toAttr = (p) => 'data-' + String(p).replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
407
- this.__dataset = new Proxy(/** @type {Record<string,string>} */ ({}), {
408
- get(_t, prop) {
409
- if (typeof prop !== 'string') return undefined;
410
- const v = el.getAttribute(toAttr(prop));
411
- return v === null ? undefined : v;
412
- },
413
- set(_t, prop, value) {
414
- if (typeof prop === 'string') el.setAttribute(toAttr(prop), value);
415
- return true;
416
- },
417
- has(_t, prop) {
418
- return typeof prop === 'string' && el.hasAttribute(toAttr(prop));
419
- },
420
- deleteProperty(_t, prop) {
421
- if (typeof prop === 'string') el.removeAttribute(toAttr(prop));
422
- return true;
423
- },
424
- ownKeys() {
425
- return el.getAttributeNames()
426
- .filter((n) => n.startsWith('data-'))
427
- .map((n) => n.slice(5).replace(/-([a-z])/g, (_m, c) => c.toUpperCase()));
428
- },
429
- getOwnPropertyDescriptor(_t, prop) {
430
- if (typeof prop === 'string' && el.hasAttribute(toAttr(prop))) {
431
- return { enumerable: true, configurable: true, value: el.getAttribute(toAttr(prop)) };
432
- }
433
- return undefined;
434
- },
435
- });
436
- return this.__dataset;
437
- }
438
-
439
- // IDL properties that reflect to a content attribute. A render() that
440
- // mutates these on the host (a light-DOM compound-component pattern, e.g.
441
- // `this.className = ...`, `this.hidden = !active`) then surfaces the
442
- // matching attribute in the SSR'd host tag, matching the browser.
443
- get className() { return this.getAttribute('class') ?? ''; }
444
- set className(v) { this.setAttribute('class', v); }
445
- get hidden() { return this.hasAttribute('hidden'); }
446
- set hidden(v) { this.toggleAttribute('hidden', !!v); }
447
- get id() { return this.getAttribute('id') ?? ''; }
448
- set id(v) { this.setAttribute('id', v); }
449
- get title() { return this.getAttribute('title') ?? ''; }
450
- set title(v) { this.setAttribute('title', v); }
451
- get slot() { return this.getAttribute('slot') ?? ''; }
452
- set slot(v) { this.setAttribute('slot', v); }
453
- get role() { return this.getAttribute('role'); }
454
- set role(v) { v == null ? this.removeAttribute('role') : this.setAttribute('role', v); }
455
- get tabIndex() { const v = this.getAttribute('tabindex'); return v === null ? -1 : (Number.parseInt(v, 10) || 0); }
456
- set tabIndex(v) { this.setAttribute('tabindex', String(v)); }
457
-
458
- // No server event loop: listeners never fire at SSR. The no-op keeps a
459
- // constructor that wires delegated listeners (a common lit pattern) from
460
- // crashing; the browser re-runs the constructor on hydration where the
461
- // real HTMLElement methods apply.
462
- addEventListener() {}
463
- removeEventListener() {}
464
- dispatchEvent() { return true; }
465
-
466
- /** @returns {any} */
467
- attachInternals() {
468
- // Match the browser (and lit's shim): a second attach is an error.
469
- if (this.__internals !== null) {
470
- throw new Error(
471
- "Failed to execute 'attachInternals' on 'HTMLElement': " +
472
- 'ElementInternals for the specified element was already attached.',
473
- );
474
- }
475
- this.__internals = makeServerInternals();
476
- return this.__internals;
477
- }
478
- }
479
-
480
- // ARIAMixin IDL reflections (`el.ariaPressed = 'true'` writes aria-pressed).
481
- // A render() that sets ARIA state via the IDL properties then surfaces the
482
- // matching aria-* attribute in the SSR'd host tag, matching the browser. The
483
- // IDL name maps to the content attribute by lowercasing the part after
484
- // `aria` and prefixing `aria-` (ariaPressed -> aria-pressed).
485
- const ARIA_IDL_PROPS = [
486
- 'ariaAtomic', 'ariaAutoComplete', 'ariaBusy', 'ariaChecked', 'ariaColCount',
487
- 'ariaColIndex', 'ariaColSpan', 'ariaCurrent', 'ariaDescription', 'ariaDisabled',
488
- 'ariaExpanded', 'ariaHasPopup', 'ariaHidden', 'ariaInvalid', 'ariaKeyShortcuts',
489
- 'ariaLabel', 'ariaLevel', 'ariaLive', 'ariaModal', 'ariaMultiLine',
490
- 'ariaMultiSelectable', 'ariaOrientation', 'ariaPlaceholder', 'ariaPosInSet',
491
- 'ariaPressed', 'ariaReadOnly', 'ariaRequired', 'ariaRoleDescription',
492
- 'ariaRowCount', 'ariaRowIndex', 'ariaRowSpan', 'ariaSelected', 'ariaSetSize',
493
- 'ariaSort', 'ariaValueMax', 'ariaValueMin', 'ariaValueNow', 'ariaValueText',
494
- ];
495
- for (const idl of ARIA_IDL_PROPS) {
496
- const attr = 'aria-' + idl.slice(4).toLowerCase();
497
- Object.defineProperty(ServerElement.prototype, idl, {
498
- configurable: true,
499
- get() { return this.getAttribute(attr); },
500
- set(v) { v == null ? this.removeAttribute(attr) : this.setAttribute(attr, String(v)); },
501
- });
502
- }
503
-
504
- // Base class choice: real HTMLElement on the browser, the shim on the server.
505
- const Base = isBrowser ? HTMLElement : /** @type {any} */ (ServerElement);
506
-
507
- /**
508
- * Marker stamped on the anonymous subclass the `WebComponent({...})` factory
509
- * produces. It lets `_assertFactoryProperties` tell the framework's own
510
- * factory-generated `static properties` (allowed) apart from a `static
511
- * properties` a user wrote by hand in a class body (no longer allowed).
512
- */
513
- const FACTORY_PROPS = Symbol('webjs.factoryProps');
514
-
515
- // Per-class memo so the constructor-time enforcement walk runs once per class.
516
- const _propsChecked = new WeakSet();
517
-
518
- class WebComponentBase extends Base {
519
- /** Whether to use shadow DOM. Default: false (light DOM). @type {boolean} */
520
- static shadow = false;
521
-
522
- /**
523
- * Hydration strategy for this component.
524
- *
525
- * **AI hint:** Set `static hydrate = 'visible'` to defer client-side
526
- * hydration until the element scrolls into (or near) the viewport. The
527
- * server-rendered Declarative Shadow DOM content stays visible the whole
528
- * time: users see the SSR HTML immediately while JavaScript activation
529
- * is deferred. This is useful for below-the-fold components that don't
530
- * need interactivity right away.
531
- *
532
- * - `undefined` (default): hydrate immediately on `connectedCallback`.
533
- * - `'visible'`: hydrate when the element enters the viewport
534
- * (with a 200 px root margin).
535
- *
536
- * @type {'visible' | undefined}
537
- */
538
- static hydrate = undefined;
539
-
540
- /**
541
- * Attribute/property declarations.
542
- *
543
- * Each key is a property name; the value is a {@link PropertyDeclaration}.
544
- *
545
- * Properties declared here get auto-generated accessors (getter/setter)
546
- * that trigger re-renders on change, coerce attribute values by type,
547
- * and optionally reflect back to attributes.
548
- *
549
- * Properties with `state: true` are excluded from `observedAttributes`
550
- * and never reflect: they behave like private reactive state.
551
- *
552
- * @type {Record<string, PropertyDeclaration>}
553
- */
554
- static properties = {};
555
-
556
- /**
557
- * Styles to adopt into the shadow root.
558
- * @type {import('./css.js').CSSResult | import('./css.js').CSSResult[] | null}
559
- */
560
- static styles = null;
561
-
562
- /**
563
- * Register this class as a custom element under `tag`.
564
- *
565
- * class Counter extends WebComponent { … }
566
- * Counter.register('my-counter');
567
- *
568
- * Delegates to `customElements.define` (or the server-side shim) via the
569
- * internal registry. The module URL for `<link rel="modulepreload">`
570
- * hints is derived server-side by scanning the app tree: no need to
571
- * pass `import.meta.url`.
572
- *
573
- * @param {string} tag Must contain a hyphen (HTML spec).
574
- */
575
- static register(tag) {
576
- register(tag, this);
577
- }
578
-
579
- /**
580
- * Returns the list of attribute names the browser should observe.
581
- * Properties with `state: true` are excluded: they are internal-only
582
- * and do not correspond to any HTML attribute.
583
- *
584
- * @returns {string[]}
585
- */
586
- static get observedAttributes() {
587
- const props = this.properties || {};
588
- return Object.keys(props)
589
- .filter((k) => !(typeof props[k] === 'object' && props[k].state))
590
- .map((k) => (typeof props[k] === 'object' && props[k].attribute) || hyphenate(k));
591
- }
592
-
593
- constructor() {
594
- super();
595
- this._renderRoot = null;
596
- this._scheduled = false;
597
- this._connected = false;
598
-
599
- /**
600
- * Set of attached reactive controllers.
601
- * @type {Set<ReactiveController>}
602
- */
603
- this.__controllers = new Set();
604
-
605
- /**
606
- * Whether the component has completed its first render.
607
- * Used to gate the one-time `firstUpdated()` call.
608
- * @type {boolean}
609
- */
610
- this.__firstRendered = false;
611
-
612
- /**
613
- * Map of changed properties accumulated since the last render. Keys are
614
- * property names; values are the previous value before the change. Passed
615
- * to `shouldUpdate`, `willUpdate`,
616
- * `update`, `firstUpdated`, and `updated`. Cleared at the start of each
617
- * render cycle so accumulations during hooks queue for the next cycle.
618
- * @type {Map<string, unknown>}
619
- */
620
- this._changedProperties = new Map();
621
-
622
- /**
623
- * Resolver for the currently-pending updateComplete promise. `null` when
624
- * no update is pending.
625
- * @type {((value: boolean) => void) | null}
626
- * @private
627
- */
628
- this._updateResolve = null;
629
-
630
- /**
631
- * Promise that resolves after the next render commit. Resolves to `true`
632
- * when there are no further pending updates, `false` otherwise.
633
- * @type {Promise<boolean>}
634
- * @private
635
- */
636
- this._updatePromise = Promise.resolve(true);
637
-
638
- /**
639
- * Set while the component is inside the update phase (between
640
- * `shouldUpdate` and `updated`). Property assignments during this window
641
- * fold into the CURRENT `changedProperties` Map without scheduling a
642
- * new microtask render. Assignments during `updated()` (after the flag
643
- * clears) queue a fresh cycle.
644
- * @type {boolean}
645
- * @private
646
- */
647
- this._isUpdating = false;
648
-
649
- // Enforce the declare-free factory DX: a hand-written `static properties`
650
- // in a class body is a hard error (use `extends WebComponent({ … })`).
651
- this._assertFactoryProperties();
652
-
653
- // Install reactive property accessors for `static properties` declarations.
654
- this._initializeProperties();
655
- }
656
-
657
- /**
658
- * Throw if a class in this instance's constructor chain declares its own
659
- * `static properties`. Reactive properties must be declared via the
660
- * `extends WebComponent({ … })` factory, which stamps {@link FACTORY_PROPS}
661
- * on the subclass it generates; a `static properties` written by hand in a
662
- * class body carries no such marker and is rejected here (issue #598).
663
- *
664
- * The walk stops at {@link WebComponentBase} (whose `static properties = {}`
665
- * default is internal) and is memoized per class so it runs once.
666
- * @private
667
- */
668
- _assertFactoryProperties() {
669
- const Ctor = /** @type {any} */ (this.constructor);
670
- if (_propsChecked.has(Ctor)) return;
671
- let C = Ctor;
672
- while (C && C !== WebComponentBase) {
673
- if (Object.hasOwn(C, 'properties') && !Object.hasOwn(C, FACTORY_PROPS)) {
674
- const name = C.name || 'a component';
675
- throw new Error(
676
- `${name}: \`static properties\` is no longer supported. Declare reactive ` +
677
- `properties via the factory instead: \`class ${name} extends WebComponent({ ` +
678
- `count: Number })\`. Use the \`prop()\` helper for options ` +
679
- `(\`prop(Number, { reflect: true })\`) and set defaults in the ` +
680
- `constructor after \`super()\`. See https://webjs.dev/docs/components.`,
681
- );
682
- }
683
- C = Object.getPrototypeOf(C);
684
- }
685
- _propsChecked.add(Ctor);
686
- }
687
-
688
- /**
689
- * For every key in `static properties`, create a getter/setter pair on
690
- * the instance that coerces values, runs `hasChanged`, schedules updates,
691
- * and optionally reflects to the HTML attribute.
692
- *
693
- * This is called once from the constructor. The backing store is a plain
694
- * object (`this.__propValues`) so accessors don't collide with the
695
- * prototype.
696
- * @private
697
- */
698
- _initializeProperties() {
699
- const Ctor = /** @type {any} */ (this.constructor);
700
- const props = Ctor.properties;
701
- if (!props || typeof props !== 'object') return;
702
-
703
- /** @type {Record<string, unknown>} */
704
- this.__propValues = {};
705
-
706
- for (const [propName, decl] of Object.entries(props)) {
707
- const d = typeof decl === 'object' ? decl : { type: decl };
708
- // Capture any value set before the accessor was installed (e.g. via
709
- // attribute or property assignment before `super()` returns).
710
- const initial = /** @type {any} */ (this)[propName];
711
-
712
- Object.defineProperty(this, propName, {
713
- configurable: true,
714
- enumerable: true,
715
- get: () => this.__propValues[propName],
716
- set: (newVal) => {
717
- const oldVal = this.__propValues[propName];
718
- const changed = (d.hasChanged || defaultHasChanged)(newVal, oldVal);
719
- if (!changed) return;
720
- this.__propValues[propName] = newVal;
721
-
722
- // Reflect to attribute if requested (and not internal state).
723
- if (d.reflect && !d.state && this._connected) {
724
- this._reflectAttribute(propName, newVal, d);
725
- }
726
-
727
- // requestUpdate records the (name, oldValue) entry AND schedules
728
- // a render. When called during the update phase (willUpdate /
729
- // hostUpdate / update / hostUpdated), the scheduler short-circuits
730
- // and the entry folds into the current cycle's changedProperties.
731
- this.requestUpdate(propName, oldVal);
732
- },
733
- });
734
-
735
- if (initial !== undefined) {
736
- this.__propValues[propName] = initial;
737
- } else if (d.default !== undefined) {
738
- // Declarative `default` option (lit-parity). A function default is
739
- // CALLED per instance, so an object / array default is a fresh value
740
- // per element. Written straight to the backing store; an applied
741
- // attribute (attributeChangedCallback runs later) overrides it.
742
- this.__propValues[propName] =
743
- typeof d.default === 'function' ? d.default() : d.default;
744
- }
745
- }
746
- }
747
-
748
- /**
749
- * Write a property value back to its corresponding HTML attribute.
750
- * Uses a custom `converter.toAttribute` if provided, otherwise the
751
- * built-in type-based serialization.
752
- *
753
- * @param {string} propName
754
- * @param {unknown} value
755
- * @param {PropertyDeclaration} decl
756
- * @private
757
- */
758
- _reflectAttribute(propName, value, decl) {
759
- // A custom `attribute` option wins over the kebab-cased property name.
760
- const attrName = decl.attribute || hyphenate(propName);
761
- // Guard against re-entrant loops: attributeChangedCallback fires when
762
- // we call setAttribute, which would call the setter again.
763
- if (this.__reflectingAttribute) return;
764
- this.__reflectingAttribute = true;
765
- try {
766
- if (decl.converter && decl.converter.toAttribute) {
767
- const serialized = decl.converter.toAttribute(value, decl.type);
768
- if (serialized == null) this.removeAttribute(attrName);
769
- else this.setAttribute(attrName, serialized);
770
- } else if (typeof value === 'function') {
771
- // #1169: the value IS a function, and no branch below has a
772
- // meaningful serialization for one. `String(fn)` is the function's
773
- // SOURCE, so a reflected `'use server'` action would ship its whole
774
- // body, closure secrets included, to every visitor, and
775
- // `JSON.stringify(fn)` is `undefined`, which `setAttribute` writes as
776
- // the literal string "undefined". Treat it like `null` and remove the
777
- // attribute, matching what the `.prop=${fn}` SSR binding already does
778
- // for an unserializable value.
779
- //
780
- // Placed AFTER the converter branch on purpose: a custom
781
- // `toAttribute` is author-controlled, so its author has taken
782
- // responsibility for serializing whatever they are handed.
783
- this.removeAttribute(attrName);
784
- warnFunctionReflection(this, propName, attrName);
785
- } else if (decl.type === Boolean) {
786
- if (value) this.setAttribute(attrName, '');
787
- else this.removeAttribute(attrName);
788
- } else if (value == null) {
789
- this.removeAttribute(attrName);
790
- } else if (decl.type === Object || decl.type === Array) {
791
- // One rule about an unserializable reflected value, in two halves.
792
- //
793
- // A JSON-typed prop CARRYING a function is safe and stays whole:
794
- // `JSON.stringify` drops a function to `null` in an array and omits
795
- // the key in an object, so `[1, 2, fn]` serializes to `[1,2,null]`
796
- // with no source and no data loss. Refusing here would discard the
797
- // `1` and the `2` on a path that never leaked.
798
- //
799
- // A value `JSON.stringify` cannot serialize AT ALL is the other half
800
- // (#1253): a cycle, a `BigInt`, or an author `toJSON()` that throws.
801
- // The throw used to escape reflection entirely, so a property
802
- // assignment threw from the setter, a client upgrade threw out of
803
- // `connectedCallback` before the first render, and an SSR render was
804
- // swallowed by per-component isolation, which surfaces an error box in
805
- // dev and emits the component EMPTY at a 200 in PRODUCTION, where the
806
- // cause is only in the server log. There is no string to put in the
807
- // attribute, so the
808
- // attribute goes, exactly as it does for a function. The `catch` IS
809
- // the detection: `JSON.stringify` already walks the value, so its own
810
- // failure covers all three causes, where a cycle-only pre-walk would
811
- // miss the other two and pay a full traversal per reflection.
812
- let serialized;
813
- let serializable = true;
814
- try {
815
- serialized = JSON.stringify(value);
816
- } catch (e) {
817
- serializable = false;
818
- this.removeAttribute(attrName);
819
- warnUnserializableReflection(this, propName, attrName, e && e.message);
820
- }
821
- // Outside the `try` on purpose, so a genuine `setAttribute` failure
822
- // (an invalid attribute name) still surfaces instead of being folded
823
- // into the unserializable path.
824
- if (serializable) this.setAttribute(attrName, serialized);
825
- } else if (carriesFunction(value)) {
826
- // The string fall-through is the one place a CARRIED function still
827
- // leaks. `String([fn])` is `Array.prototype.join`, which runs
828
- // `String()` on every element, so `[serverAction]` writes the same
829
- // source `serverAction` does. Hence the recursive predicate the
830
- // form-action guard already uses, rather than a bare `typeof`, but
831
- // scoped to this branch rather than applied above, where JSON
832
- // handles the same shape losslessly.
833
- this.removeAttribute(attrName);
834
- warnFunctionReflection(this, propName, attrName);
835
- } else {
836
- this.setAttribute(attrName, String(value));
837
- }
838
- } finally {
839
- this.__reflectingAttribute = false;
840
- }
841
- }
842
-
843
- connectedCallback() {
844
- if (!isBrowser) return;
845
-
846
- // Apply any `data-webjs-prop-*` attributes emitted by SSR. The server
847
- // emits these for `.prop=${val}` bindings in parent templates so
848
- // rich-typed values (Array, Object, Date, Map, Set, BigInt, cycles)
849
- // round-trip through the rendered HTML. Once applied, the attributes
850
- // are stripped so the settled DOM matches what the user would expect
851
- // from the JS source: no framework artifacts left on the element.
852
- // One-time per element. Subsequent reconnections do nothing.
853
- if (!this.__webjsPropsHydrated) {
854
- this.__webjsPropsHydrated = true;
855
- this._hydratePropAttrs();
856
- }
857
-
858
- const Ctor = /** @type any */ (this.constructor);
859
-
860
- // Selective hydration: defer activation until the element scrolls into
861
- // (or near) the viewport. The DSD content from SSR stays visible the
862
- // whole time: the user sees the server-rendered HTML.
863
- if (
864
- Ctor.hydrate === 'visible' &&
865
- typeof IntersectionObserver !== 'undefined' &&
866
- !this.__hydrationActivated
867
- ) {
868
- this.__hydrationActivated = false;
869
- this.__hydrationObserver = new IntersectionObserver(
870
- (entries) => {
871
- for (const entry of entries) {
872
- if (entry.isIntersecting) {
873
- this.__hydrationObserver.unobserve(this);
874
- this.__hydrationObserver.disconnect();
875
- this.__hydrationObserver = null;
876
- this.__hydrationActivated = true;
877
- this._activate();
878
- return;
879
- }
880
- }
881
- },
882
- { rootMargin: '200px' }
883
- );
884
- this.__hydrationObserver.observe(this);
885
- return;
886
- }
887
-
888
- this._activate();
889
- }
890
-
891
- /**
892
- * Internal activation method that performs the actual connectedCallback
893
- * work: setting up the render root, adopting styles, notifying
894
- * controllers, and performing the first render.
895
- *
896
- * Called directly from `connectedCallback()` for normal components, or
897
- * deferred via IntersectionObserver when `static hydrate = 'visible'`.
898
- *
899
- * @private
900
- */
901
- /**
902
- * Read `data-webjs-prop-*` attributes (emitted by SSR for `.prop=${val}`
903
- * bindings in parent templates), decode each via the wire serializer,
904
- * assign the decoded value to the corresponding camelCase property on
905
- * this instance, and remove the attribute from the DOM. After this
906
- * runs, inspecting the element shows the same attributes the developer
907
- * would expect from the JS source.
908
- *
909
- * @private
910
- */
911
- _hydratePropAttrs() {
912
- /** @type {string[]} */
913
- const names = [];
914
- const attrs = this.attributes;
915
- for (let i = 0; i < attrs.length; i++) {
916
- const n = attrs[i].name;
917
- if (n.startsWith('data-webjs-prop-')) names.push(n);
918
- }
919
- for (const fullName of names) {
920
- const raw = this.getAttribute(fullName);
921
- this.removeAttribute(fullName);
922
- if (raw == null) continue;
923
- const propName = camelCase(fullName.slice('data-webjs-prop-'.length));
924
- try {
925
- /** @type any */ (this)[propName] = deserializeProp(raw);
926
- } catch (err) {
927
- console.warn(
928
- `[webjs] failed to decode ${fullName} on <${this.tagName.toLowerCase()}>: ${err && err.message}`
929
- );
930
- }
931
- }
932
- }
933
-
934
- _activate() {
935
- this._connected = true;
936
- // Reflect declared reflect:true properties from their current value now
937
- // that the element is connected. Constructor / willUpdate defaults were
938
- // set while disconnected (the setter skips reflection then), so this is
939
- // what makes a freshly-created client element carry the same reflected
940
- // attributes the SSR walker emitted. Same-value reflects are no-ops, so a
941
- // hydrated element (whose attribute already arrived from SSR) is unchanged.
942
- this._reflectDeclaredAttributes();
943
- const Ctor = /** @type any */ (this.constructor);
944
- // Mark LIGHT-DOM component hosts so the framework default host rule
945
- // (`@layer webjs-host { :where([data-wj-host]) { display: block } }`)
946
- // applies. SSR already stamps this on server-rendered light hosts
947
- // (idempotent here); this also covers a client-only light component (never
948
- // SSR'd) so it does not collapse. Shadow hosts are NOT marked: a document
949
- // rule would override the shadow author's own `:host { display: … }`, so
950
- // shadow components control their host display via `:host` in `static styles`.
951
- if (Ctor.shadow !== true && !this.hasAttribute('data-wj-host')) {
952
- this.setAttribute('data-wj-host', '');
953
- }
954
- if (Ctor.shadow === true) {
955
- const hadSSRShadow = !!this.shadowRoot;
956
- if (!this.shadowRoot) {
957
- /** @type any */ (this).attachShadow({ mode: 'open' });
958
- }
959
- this._renderRoot = this.shadowRoot;
960
- const styles = Ctor.styles;
961
- const list = Array.isArray(styles) ? styles : isCSS(styles) ? [styles] : [];
962
- if (list.length) {
963
- // If the shadow root came from Declarative Shadow DOM (SSR), it
964
- // contains an inline <style> tag. Remove it before switching to
965
- // adoptedStyleSheets to avoid duplicate styles.
966
- if (hadSSRShadow) {
967
- const ssrStyle = this.shadowRoot.querySelector('style');
968
- if (ssrStyle) ssrStyle.remove();
969
- }
970
- adoptStyles(this._renderRoot, list);
971
- }
972
- } else {
973
- this._renderRoot = this;
974
- // Light DOM: static styles is not supported (no shadow root for
975
- // adoptedStyleSheets). Warn if the developer set both.
976
- if (Ctor.styles) {
977
- console.warn(
978
- `[webjs] <${tagOf(Ctor) || this.tagName?.toLowerCase()}> has static shadow = false AND static styles. ` +
979
- `static styles only works with shadow DOM (adoptedStyleSheets). ` +
980
- `For light DOM, use global CSS or <style> in render().`
981
- );
982
- }
983
- // Light-DOM slot capture: ONCE per host lifetime (#1015). Three
984
- // sub-paths, all of which resolve to "the record is populated
985
- // exactly once and never re-captured":
986
- //
987
- // a. Reconnection. The record already exists from a prior mount.
988
- // The host still carries the rendered template DOM (plus
989
- // placed slot children) from before the disconnect. Skip
990
- // capture (would wrongly hoover up rendered nodes) and skip
991
- // SSR adoption. clientRender will see the existing INSTANCE
992
- // and updateInstance instead of recreating; the DOM stays.
993
- //
994
- // b. SSR hydration (first mount, <!--webjs-hydrate--> marker
995
- // present). Children are already inside their
996
- // <slot data-webjs-light data-projection="actual"> elements
997
- // (injectDSD placed them). Adopt those assignments BEFORE
998
- // _performRender so we retain references to the SSR'd nodes;
999
- // the renderer's createInstance().replaceChildren() will
1000
- // detach them, but the slot-apply step re-attaches the same
1001
- // Node refs into the freshly-cloned slot. DOM identity
1002
- // preserved through the hydration round-trip.
1003
- //
1004
- // c. First mount, no SSR. Partition authored children into the
1005
- // record before _performRender wipes the host.
1006
- //
1007
- // After capture, installSlotInterception + installSlotSensors below make
1008
- // native DOM writes on a mounted host live (appendChild, slot= flips,
1009
- // innerHTML, HTMLSlotElement.assign), so light-DOM slots match shadow DOM
1010
- // through the standard API.
1011
- if (hasSlotState(this)) {
1012
- // (a) Reconnection. Record already populated. Sweep any direct child
1013
- // added by a raw bypass write while the host was disconnected (no
1014
- // sensor was live to catch it), then re-arm the sensors below.
1015
- reconnectSweep(this);
1016
- } else if (
1017
- this.__isHydrating() ||
1018
- this.hasAttribute('data-wj-serialized') ||
1019
- hasFrameworkRenderedSubtree(this)
1020
- ) {
1021
- // (b) Framework-rendered markup, from any of three signals: boot-time
1022
- // SSR hydration (the webjs-hydrate marker), the router's
1023
- // data-wj-serialized stamp (applySwap marks every host in a parsed
1024
- // doc, covering a snapshot restore whose serialized shape has no
1025
- // projected slot to detect), or the structural detector (own
1026
- // data-webjs-light[data-projection] slots, attributes only the
1027
- // renderer / SSR stamps). Adopt-not-capture: capturing restored
1028
- // post-hydration HTML would hoover the rendered tree into the
1029
- // record and duplicate content on the next render (the #1006
1030
- // shape, on the restore path).
1031
- this.removeAttribute('data-wj-serialized');
1032
- ensureSlotState(this);
1033
- adoptSSRAssignments(this);
1034
- } else {
1035
- // (c) First mount with author-written children. Capture them.
1036
- captureAuthoredChildren(this);
1037
- }
1038
- // Install native-write interception AFTER capture (capture uses the
1039
- // host's still-native methods), then arm the sensors. Together they make
1040
- // appendChild / insertBefore / removeChild / innerHTML / slot= flips on a
1041
- // mounted light host drive the slot record, restoring full shadow-DOM
1042
- // parity through the standard DOM API. Interception installs once;
1043
- // sensors are armed on every connect and torn down on disconnect.
1044
- installSlotInterception(this);
1045
- installSlotSensors(this);
1046
- }
1047
-
1048
- // Notify all controllers that the host is connected.
1049
- for (const c of this.__controllers) {
1050
- if (c.hostConnected) c.hostConnected();
1051
- }
1052
-
1053
- // First render is deferred to a microtask, matching lit's
1054
- // performUpdate scheduling. The user's connectedCallback override
1055
- // body runs synchronously to completion BEFORE the first render,
1056
- // so subclass setup that needs to inspect attributes / state / etc.
1057
- // observes consistent timing whether SSR-hydrating or first mount.
1058
- // Render-root setup (shadow attachment, light-DOM SSR adoption,
1059
- // controller hostConnected, _connected=true) all stay synchronous
1060
- // above; only the template commit + post-commit slot observers
1061
- // defer. Authoring contract: post-render DOM setup goes in
1062
- // firstUpdated(), NOT connectedCallback().
1063
- //
1064
- // The scheduling matches `_scheduleUpdate`'s wrapper so lifecycle
1065
- // throws are surfaced as console errors instead of bricking the
1066
- // element.
1067
- if (this._updateResolve === null) {
1068
- this._updatePromise = new Promise((resolve) => {
1069
- this._updateResolve = resolve;
1070
- });
1071
- }
1072
- this._scheduled = true;
1073
- queueMicrotask(() => {
1074
- this._scheduled = false;
1075
- try {
1076
- this._performRender();
1077
- } catch (err) {
1078
- console.error(`[webjs] lifecycle hook threw during initial render:`, err);
1079
- }
1080
- // The renderer's slot parts place the record content as part of the
1081
- // commit; native DOM writes on the host (appendChild, slot= flips,
1082
- // innerHTML) drive the record live through the interception + sensors
1083
- // installed on connect. There is no WebJs-specific slot API.
1084
- });
1085
- }
1086
-
1087
- /**
1088
- * True when this host's first child is the framework's hydration
1089
- * marker, meaning the SSR pipeline already rendered the template's
1090
- * shape (including <slot data-webjs-light> elements with their
1091
- * projected children inside) and the client should bind events
1092
- * without re-creating DOM. Sets __hydratedAtActivate as a side
1093
- * effect so the post-render path picks up the SSR assignment table.
1094
- *
1095
- * @returns {boolean}
1096
- * @private
1097
- */
1098
- __isHydrating() {
1099
- const first = this.firstChild;
1100
- const isHydrate =
1101
- first != null &&
1102
- first.nodeType === 8 &&
1103
- /** @type {Comment} */ (first).data === 'webjs-hydrate';
1104
- if (isHydrate) this.__hydratedAtActivate = true;
1105
- return isHydrate;
1106
- }
1107
-
1108
-
1109
- /**
1110
- * Called when the element is removed from the DOM.
1111
- *
1112
- * Notifies all attached {@link ReactiveController}s so they can clean up
1113
- * subscriptions, timers, and observers. If you override this in a
1114
- * subclass, always call `super.disconnectedCallback()`.
1115
- */
1116
- disconnectedCallback() {
1117
- this._connected = false;
1118
- // Clean up the hydration observer if the element is removed before
1119
- // it became visible.
1120
- if (this.__hydrationObserver) {
1121
- this.__hydrationObserver.disconnect();
1122
- this.__hydrationObserver = null;
1123
- }
1124
- // Tear down the slot sensors, processing any queued records first (a bare
1125
- // disconnect() drops them). The per-host slot record + interception are
1126
- // preserved so a reconnection picks up where it left off (sensors re-arm in
1127
- // connectedCallback).
1128
- teardownSlotSensors(this);
1129
- // Dispose the signal watcher so dependency edges drop. Without
1130
- // this the element holds references to module-scope signals
1131
- // (and vice versa) forever.
1132
- if (this.__signalWatcher) {
1133
- this.__signalWatcher.dispose();
1134
- this.__signalWatcher = undefined;
1135
- }
1136
- for (const c of this.__controllers) {
1137
- if (c.hostDisconnected) c.hostDisconnected();
1138
- }
1139
- }
1140
-
1141
- /**
1142
- * @param {string} name Kebab-cased attribute name
1143
- * @param {string|null} _old
1144
- * @param {string|null} value
1145
- */
1146
- attributeChangedCallback(name, _old, value) {
1147
- // When we are reflecting a property back to an attribute, ignore the
1148
- // resulting attributeChangedCallback to avoid infinite loops.
1149
- if (this.__reflectingAttribute) return;
1150
-
1151
- // One name resolver for both sides (#1341). The browser only calls this for
1152
- // a name in `observedAttributes`, and it has already lowercased that name
1153
- // while parsing, so it passes straight through; the SSR caller lowercases
1154
- // its source name first. `resolveAttributeProperty` also normalises the
1155
- // declaration, so a bare-constructor shorthand (`count: Number`) and the
1156
- // long form (`{ type: Number, … }`) both arrive here as `{ type, … }`.
1157
- const resolved = resolveAttributeProperty(this.constructor, name);
1158
- if (resolved === undefined) return;
1159
- const { propName, def } = resolved;
1160
-
1161
- // One reader for both sides, in `attribute-reader.js`: this and
1162
- // `applyAttrsToInstance` in `render-server.js` call the same function, so
1163
- // precedence and every fallback are shared rather than mirrored (#1340).
1164
- // It takes an already-decoded value, which the DOM has done here and
1165
- // `decodeAttrEntities` does at the SSR call site (#1341).
1166
- const v = readAttributeValue(def, value);
1167
-
1168
- if (this[propName] !== v) {
1169
- this[propName] = v;
1170
- if (this._connected) this.requestUpdate();
1171
- }
1172
- }
1173
-
1174
- /**
1175
- * Schedule a re-render. Optionally record a property change in
1176
- * `changedProperties` so hooks can branch on what changed.
1177
- *
1178
- * @param {string} [name] Property name that changed
1179
- * @param {unknown} [oldValue] Previous value of the property
1180
- */
1181
- requestUpdate(name, oldValue) {
1182
- if (name !== undefined && !this._changedProperties.has(name)) {
1183
- this._changedProperties.set(name, oldValue);
1184
- }
1185
- this._scheduleUpdate();
1186
- }
1187
-
1188
- /**
1189
- * Internal scheduler driven by reactive-property setters, the signal
1190
- * watcher, and explicit `requestUpdate()` calls. Coalesces multiple
1191
- * changes in the same tick into a single microtask render.
1192
- * Manages the `updateComplete` promise lifecycle. Short-circuits when
1193
- * the component is mid-update (assignments during `willUpdate` / `update`
1194
- * fold into the current cycle's `changedProperties` Map).
1195
- * @private
1196
- */
1197
- _scheduleUpdate() {
1198
- if (this._updateResolve === null) {
1199
- this._updatePromise = new Promise((resolve) => {
1200
- this._updateResolve = resolve;
1201
- });
1202
- }
1203
- if (this._isUpdating) return;
1204
- if (this._scheduled || !this._connected) return;
1205
- this._scheduled = true;
1206
- queueMicrotask(() => {
1207
- this._scheduled = false;
1208
- try {
1209
- this._performRender();
1210
- } catch (err) {
1211
- // _performRender wraps the update phase in try/finally so this
1212
- // catches throws from shouldUpdate / willUpdate / hostUpdate /
1213
- // hostUpdated / firstUpdated / updated. The component is not
1214
- // left in a bad state (the finally blocks reset _isUpdating and
1215
- // resolve updateComplete). Surface the error for visibility.
1216
- console.error(`[webjs] lifecycle hook threw during update cycle:`, err);
1217
- }
1218
- });
1219
- }
1220
-
1221
- /**
1222
- * Core update cycle, lit-aligned:
1223
- * 1. Snapshot + clear `changedProperties`
1224
- * 2. `shouldUpdate(changedProperties)`. If false, resolve updateComplete and return.
1225
- * 3. `willUpdate(changedProperties)`. Safe to set properties without re-triggering.
1226
- * 4. Controllers' `hostUpdate()`
1227
- * 5. `update(changedProperties)`. Default impl calls `render()` + commits.
1228
- * Wrapped in error boundary that falls back to `renderError(error)`.
1229
- * 6. Controllers' `hostUpdated()`
1230
- * 7. `firstUpdated(changedProperties)` runs once, on the first render only
1231
- * 8. `updated(changedProperties)` runs after every commit
1232
- * 9. Resolve `updateComplete` promise
1233
- * @private
1234
- */
1235
- _performRender() {
1236
- if (!this._renderRoot) return;
1237
-
1238
- // Hold a stable reference to the current Map so all hooks see the same
1239
- // snapshot. During the update phase (steps 3-6) the Map is mutated in
1240
- // place when property setters fire, folding those changes into THIS
1241
- // cycle. The Map is replaced with a fresh empty one only after a
1242
- // successful commit so post-commit assignments queue the NEXT cycle.
1243
- // On `shouldUpdate=false` or hook errors, the Map is preserved so the
1244
- // accumulated changes survive into the next render.
1245
- const changedProperties = this._changedProperties;
1246
-
1247
- // --- 1. Mark we're inside an update cycle ---
1248
- this._isUpdating = true;
1249
- let didCommit = false;
1250
- // Set when render() was async: the DOM commit lands when this settles,
1251
- // so the post-commit half of the cycle defers until then (#469).
1252
- let pendingCommit = null;
1253
-
1254
- // --- 2-6. Update phase. Lifecycle-hook throws are logged and
1255
- // swallowed so the component is not left in a deadlocked state
1256
- // (`_isUpdating` stuck true, `updateComplete` never resolves).
1257
- try {
1258
- if (this.shouldUpdate(changedProperties)) {
1259
- // --- 3. willUpdate (may mutate properties; folds into this cycle) ---
1260
- this.willUpdate(changedProperties);
1261
-
1262
- // --- 4. controllers' hostUpdate ---
1263
- for (const c of this.__controllers) {
1264
- if (c.hostUpdate) c.hostUpdate();
1265
- }
1266
-
1267
- // --- 5. update + DOM commit (with render-error boundary) ---
1268
- // Stamp a fresh render token for THIS commit, sync or async. A later
1269
- // cycle that reaches here bumps it, so an in-flight async render whose
1270
- // token no longer matches drops its now-stale resolution. Stamping
1271
- // here (not inside _commitAsync) is what guards the async-superseded-
1272
- // by-sync case (#469); a shouldUpdate=false cycle never reaches here,
1273
- // so it does not invalidate an in-flight async render.
1274
- this.__renderToken = (this.__renderToken || 0) + 1;
1275
- // Abort the superseded render's in-flight action fetches (#492), start a
1276
- // fresh controller for this render, and bind it as the active signal so
1277
- // the RPC stub ties its fetches to this render. A superseded fetch's
1278
- // AbortError is dropped by the render-token guard in _commitAsync.
1279
- if (this.__renderAbort) this.__renderAbort.abort();
1280
- this.__renderAbort = typeof AbortController !== 'undefined' ? new AbortController() : null;
1281
- setActiveActionSignal(this.__renderAbort ? this.__renderAbort.signal : null);
1282
- try {
1283
- const r = this.update(changedProperties);
1284
- if (r && typeof r.then === 'function') pendingCommit = r;
1285
- } catch (error) {
1286
- this._handleRenderError(/** @type {Error} */ (error));
1287
- } finally {
1288
- // The synchronous portion of render() has run; actions invoked there
1289
- // already captured the signal. Clear it so a later event handler is
1290
- // not bound to a stale render's controller.
1291
- setActiveActionSignal(null);
1292
- }
1293
-
1294
- if (!pendingCommit) {
1295
- // --- 6. controllers' hostUpdated (sync commit) ---
1296
- for (const c of this.__controllers) {
1297
- if (c.hostUpdated) c.hostUpdated();
1298
- }
1299
- didCommit = true;
1300
- }
1301
- }
1302
- // shouldUpdate=false: preserve _changedProperties so the next
1303
- // requestUpdate keeps accumulating on top of the entries that
1304
- // didn't render this cycle.
1305
- } catch (preCommitError) {
1306
- console.error(`[webjs] lifecycle hook threw during update phase:`, preCommitError);
1307
- } finally {
1308
- this._isUpdating = false;
1309
- // The snapshot is consumed once the commit is DISPATCHED. For an async
1310
- // render it resets here too, so a property change during the in-flight
1311
- // fetch starts a fresh cycle (whose render token supersedes this one).
1312
- if (didCommit || pendingCommit) {
1313
- this._changedProperties = new Map();
1314
- }
1315
- }
1316
-
1317
- // --- Async render: finish the cycle when the pending commit settles. ---
1318
- if (pendingCommit) {
1319
- const token = this.__renderToken;
1320
- // Count this in-flight async commit so a non-committing cycle
1321
- // (shouldUpdate=false) running during the fetch does NOT resolve
1322
- // updateComplete early: the pending commit owns the resolution.
1323
- this.__pendingAsyncCommits = (this.__pendingAsyncCommits || 0) + 1;
1324
- const settle = () => {
1325
- // Always decrement first, even when superseded, so the in-flight
1326
- // count never leaks (a superseded cycle returns below without
1327
- // committing, but it is no longer pending).
1328
- this.__pendingAsyncCommits--;
1329
- // A newer render superseded this one; let the newer cycle finish.
1330
- if (token !== this.__renderToken) return;
1331
- // --- 6. controllers' hostUpdated (after the async commit) ---
1332
- for (const c of this.__controllers) {
1333
- if (c.hostUpdated) c.hostUpdated();
1334
- }
1335
- // --- 7-8 + updateComplete ---
1336
- this._postCommit(changedProperties);
1337
- };
1338
- // A rejection has to settle the cycle too, or the counter stays >= 1
1339
- // forever: that both wedges `updateComplete` for this instance and
1340
- // disables the `!this.__pendingAsyncCommits` escape below for every
1341
- // later non-committing cycle. `_commitAsync` is written not to reject,
1342
- // but it is not the only thenable that reaches here: `update()` is a
1343
- // documented override point and may return one, so the handler belongs
1344
- // at this site rather than only at the one implementation of it.
1345
- pendingCommit.then(settle, (error) => {
1346
- // The token check gates the DOM write, NOT the release. A superseded
1347
- // cycle rejecting late (a discarded fetch, or the #492 abort of its own
1348
- // in-flight action surfacing as an AbortError) must not commit its
1349
- // error state over the newer render that already replaced it, which is
1350
- // the same rule both handlers inside _commitAsync follow. `settle()`
1351
- // still runs either way: it does its own token check before touching
1352
- // anything, and the decrement it owns has to happen regardless or the
1353
- // counter wedges exactly as it did before this handler existed.
1354
- // `finally`, not a trailing statement: the release must survive
1355
- // anything the reporting path throws. `String(error)` is evaluated in
1356
- // the argument expression, OUTSIDE _handleRenderError's own try/catch,
1357
- // so a rejection reason that cannot be coerced (a null-prototype
1358
- // object, a revoked Proxy) threw a TypeError straight out of this
1359
- // handler and skipped the decrement, wedging the counter in exactly
1360
- // the way this handler exists to prevent.
1361
- try {
1362
- if (token === this.__renderToken) {
1363
- this._handleRenderError(error instanceof Error ? error : new Error(safeString(error)));
1364
- }
1365
- } finally {
1366
- settle();
1367
- }
1368
- });
1369
- return;
1370
- }
1371
-
1372
- // --- 7-8. Post-commit hooks (sync path). Errors are caught so the
1373
- // updateComplete promise always resolves.
1374
- if (didCommit) {
1375
- this._postCommit(changedProperties);
1376
- } else if (!this.__pendingAsyncCommits) {
1377
- // A non-committing cycle resolves updateComplete only when no async
1378
- // commit is in flight; otherwise the pending commit resolves it once it
1379
- // lands, so `await el.updateComplete` never returns before that DOM.
1380
- this._resolveUpdate();
1381
- }
1382
- }
1383
-
1384
- /**
1385
- * Resolve the pending updateComplete promise. Value reflects whether any
1386
- * further updates were queued during the current cycle: `true` means the
1387
- * component has settled, `false` means another render will run.
1388
- * @private
1389
- */
1390
- _resolveUpdate() {
1391
- if (this._updateResolve) {
1392
- const settled = this._changedProperties.size === 0;
1393
- this._updateResolve(settled);
1394
- this._updateResolve = null;
1395
- }
1396
- }
1397
-
1398
- /**
1399
- * Run the pre-render half of the update cycle synchronously for SSR.
1400
- *
1401
- * The SSR walker constructs the instance, applies attributes/props, then
1402
- * calls this BEFORE `render()`. It mirrors how lit drives the update
1403
- * lifecycle server-side: `willUpdate` runs so derived state computed there
1404
- * is correct in the SSR'd HTML, then reactive controllers' `hostUpdate`
1405
- * runs, then reflect:true properties are written to attributes so they
1406
- * appear in the serialized output. It deliberately does NOT run
1407
- * `shouldUpdate` (SSR always produces the first paint, there is no prior
1408
- * render to skip), `update` (the walker commits by calling `render`
1409
- * itself), or the post-commit hooks `firstUpdated` / `updated` (browser-only
1410
- * DOM work).
1411
- *
1412
- * `_isUpdating` is set so a property assignment inside `willUpdate` folds
1413
- * into the current `changedProperties` snapshot instead of scheduling a
1414
- * fresh cycle (the SSR scheduler short-circuits anyway, since the element
1415
- * is not connected). Hook throws propagate to the walker's per-component
1416
- * try/catch, which logs an actionable hint and skips DSD for that element,
1417
- * the same as a throwing `render()`.
1418
- */
1419
- performServerUpdate() {
1420
- const changedProperties = this._changedProperties;
1421
- this._isUpdating = true;
1422
- try {
1423
- this.willUpdate(changedProperties);
1424
- for (const c of this.__controllers) {
1425
- if (c.hostUpdate) c.hostUpdate();
1426
- }
1427
- this._reflectDeclaredAttributes();
1428
- } finally {
1429
- this._isUpdating = false;
1430
- }
1431
- }
1432
-
1433
- /**
1434
- * Reflect every reflect:true (non-state) property to its attribute from its
1435
- * CURRENT value, regardless of whether the value arrived via the setter.
1436
- *
1437
- * The property setter only reflects on a connected change, so a value set
1438
- * in the constructor (a default) or in `willUpdate` is not reflected by the
1439
- * setter alone. This syncs those: the SSR walker calls it in
1440
- * `performServerUpdate` (writing into the server attribute shim, which the
1441
- * walker reads back into the rendered HTML), and `_activate` calls it on
1442
- * the client's first connected render. Running it on both sides is what
1443
- * keeps a server-rendered element and a freshly-created client element
1444
- * agree on their reflected attributes (matching lit, which reflects during
1445
- * the first update). `_reflectAttribute`'s re-entrancy guard makes a
1446
- * same-value reflect a no-op, so re-reflecting an attribute that already
1447
- * arrived from SSR does not churn.
1448
- * @private
1449
- */
1450
- _reflectDeclaredAttributes() {
1451
- const props = /** @type {any} */ (this.constructor).properties || {};
1452
- for (const name of Object.keys(props)) {
1453
- const decl = props[name];
1454
- if (!decl || !decl.reflect || decl.state) continue;
1455
- this._reflectAttribute(name, this[name], decl);
1456
- }
1457
- }
1458
-
1459
- // ---------------------------------------------------------------------------
1460
- // Lifecycle hooks: override in subclasses
1461
- // ---------------------------------------------------------------------------
1462
-
1463
- /**
1464
- * Decide whether the component should render in response to a queued
1465
- * update. Default implementation returns `true` (always render).
1466
- *
1467
- * **When to use:** override to skip an update when the relevant inputs
1468
- * haven't changed, e.g. an expensive component that only depends on a
1469
- * subset of its reactive properties.
1470
- *
1471
- * ```js
1472
- * shouldUpdate(changedProperties) {
1473
- * return changedProperties.has('itemCount') || changedProperties.has('mode');
1474
- * }
1475
- * ```
1476
- *
1477
- * @param {Map<string, unknown>} _changedProperties
1478
- * @returns {boolean}
1479
- */
1480
- shouldUpdate(_changedProperties) {
1481
- return true;
1482
- }
1483
-
1484
- /**
1485
- * Run immediately before `update()`. Safe to set reactive properties
1486
- * here without triggering another update cycle: assignments made inside
1487
- * `willUpdate` are folded into the current `changedProperties` snapshot
1488
- * and rendered in the same pass.
1489
- *
1490
- * **When to use:** computing derived values from changed inputs before
1491
- * `render()` reads them. Lit users typically migrate `shouldUpdate`
1492
- * heuristics that mutate state into `willUpdate`.
1493
- *
1494
- * ```js
1495
- * willUpdate(changedProperties) {
1496
- * if (changedProperties.has('items')) {
1497
- * this.totalCount = this.items.length;
1498
- * }
1499
- * }
1500
- * ```
1501
- *
1502
- * @param {Map<string, unknown>} _changedProperties
1503
- */
1504
- willUpdate(_changedProperties) {}
1505
-
1506
- /**
1507
- * The render-and-commit step. Default impl calls `render()` and commits
1508
- * the returned `TemplateResult` to the render root.
1509
- *
1510
- * **When to use:** rarely. Override only when you need to wrap or
1511
- * short-circuit the commit. Most users override `render()` instead.
1512
- * If you do override, you MUST commit something to `this._renderRoot`
1513
- * (or call `super.update(changedProperties)`).
1514
- *
1515
- * @param {Map<string, unknown>} _changedProperties
1516
- */
1517
- update(_changedProperties) {
1518
- // Track signal reads during render so the component re-renders when
1519
- // any of them change. The watcher is lazy-allocated on first
1520
- // render and disposed in disconnectedCallback. observe() clears
1521
- // prior dep edges before fn(), so each render re-records its own
1522
- // (possibly different) read set.
1523
- if (!this.__signalWatcher) {
1524
- this.__signalWatcher = new Signal.subtle.Watcher(() => {
1525
- if (this._connected) this.requestUpdate();
1526
- });
1527
- }
1528
- let tpl;
1529
- this.__signalWatcher.observe(() => { tpl = this.render(); });
1530
- // Bare-await async render (#469): render() returned a promise. Use
1531
- // stale-while-revalidate: keep the current DOM (the SSR first paint on
1532
- // hydration, or the prior content on a re-fetch) visible until the new
1533
- // template resolves, then commit it. Returns the pending promise so
1534
- // _performRender defers the post-commit half of the cycle (hostUpdated,
1535
- // firstUpdated/updated, updateComplete) until the real commit lands.
1536
- // (Note: only signal reads BEFORE the first `await` are tracked; reads
1537
- // after a suspension point do not establish reactive dependencies.)
1538
- if (tpl && typeof (/** @type any */ (tpl).then) === 'function') {
1539
- return this._commitAsync(/** @type {Promise<unknown>} */ (tpl));
1540
- }
1541
- clientRender(tpl, this._renderRoot);
1542
- return undefined;
1543
- }
1544
-
1545
- /**
1546
- * Commit a promise-returning render() with stale-while-revalidate
1547
- * semantics (#469). The current DOM stays untouched until the template
1548
- * resolves; on a client RE-FETCH an author-defined renderFallback()
1549
- * optionally swaps in a loading state first. The cycle's render token
1550
- * (stamped by _performRender before update() ran) drops a superseded
1551
- * resolution so an out-of-order fetch never commits stale DOM, INCLUDING
1552
- * when the superseding render is synchronous (a later cycle re-stamps the
1553
- * token whether or not it is async). A rejection routes to the
1554
- * renderError() boundary, isolated to this component. Returns a promise
1555
- * that settles once the commit (or its error / fallback) has been applied.
1556
- *
1557
- * @param {Promise<unknown>} pending
1558
- * @returns {Promise<void>}
1559
- * @private
1560
- */
1561
- _commitAsync(pending) {
1562
- const token = this.__renderToken;
1563
- // First paint (hydration): keep the SSR DOM, never a fallback, so
1564
- // first-paint data stays visible with no skeleton flash. Re-fetch: an
1565
- // author-defined renderFallback() overrides the stale-while-revalidate
1566
- // default with an explicit loading state.
1567
- if (this.__firstRendered && this._overridesRenderFallback()) {
1568
- try {
1569
- const fb = this.renderFallback();
1570
- if (fb !== undefined) clientRender(fb, this._renderRoot);
1571
- } catch (e) {
1572
- console.error(`[webjs] renderFallback() threw:`, e);
1573
- }
1574
- }
1575
- return Promise.resolve(pending).then(
1576
- (tpl) => {
1577
- if (token !== this.__renderToken) return; // superseded by a newer render
1578
- // The COMMIT throws too, not just the fetch, and a sibling rejection
1579
- // handler cannot see it: `.then(onFulfil, onRejected)` never routes
1580
- // onFulfil's own throw to onRejected. Left uncaught, the returned
1581
- // promise rejected and _performRender's `.then` had no rejection
1582
- // handler, so the error escaped as an unhandled rejection,
1583
- // renderError() never ran, __pendingAsyncCommits never decremented
1584
- // (wedging it >= 1 forever, which also disables the non-committing
1585
- // cycle's _resolveUpdate escape), and updateComplete never settled.
1586
- // The sync path routes an identical throw to the same boundary, so
1587
- // this is what makes the two paths agree.
1588
- try {
1589
- clientRender(tpl, this._renderRoot);
1590
- } catch (commitError) {
1591
- this._handleRenderError(
1592
- commitError instanceof Error ? commitError : new Error(String(commitError)),
1593
- );
1594
- }
1595
- },
1596
- (error) => {
1597
- if (token !== this.__renderToken) return;
1598
- this._handleRenderError(error instanceof Error ? error : new Error(String(error)));
1599
- },
1600
- );
1601
- }
1602
-
1603
- /**
1604
- * Whether the subclass overrides renderFallback() (vs the inert default).
1605
- * @returns {boolean}
1606
- * @private
1607
- */
1608
- _overridesRenderFallback() {
1609
- return this.renderFallback !== WebComponent.prototype.renderFallback;
1610
- }
1611
-
1612
- /**
1613
- * Client-side render-error boundary, shared by the sync and async commit
1614
- * paths. Logs, then commits renderError()'s output (if any) so one broken
1615
- * component does not crash the page.
1616
- * @param {Error} error
1617
- * @private
1618
- */
1619
- _handleRenderError(error) {
1620
- console.error(
1621
- `[webjs] render error in <${tagOf(/** @type any */ (this.constructor)) || this.tagName?.toLowerCase()}>:`,
1622
- error,
1623
- );
1624
- try {
1625
- const fallback = this.renderError(error);
1626
- if (fallback !== undefined) clientRender(fallback, this._renderRoot);
1627
- } catch (fallbackError) {
1628
- console.error(`[webjs] renderError() also threw:`, fallbackError);
1629
- }
1630
- }
1631
-
1632
- /**
1633
- * Post-commit half of the update cycle (steps 7-8 + updateComplete),
1634
- * shared by the sync path and the async (post-resolution) path.
1635
- * @param {Map<string, unknown>} changedProperties
1636
- * @private
1637
- */
1638
- _postCommit(changedProperties) {
1639
- try {
1640
- if (!this.__firstRendered) {
1641
- this.__firstRendered = true;
1642
- this.firstUpdated(changedProperties);
1643
- }
1644
- this.updated(changedProperties);
1645
- } catch (postCommitError) {
1646
- console.error(`[webjs] lifecycle hook threw during post-commit phase:`, postCommitError);
1647
- } finally {
1648
- this._resolveUpdate();
1649
- }
1650
- }
1651
-
1652
- /**
1653
- * Called after every render commit (both the first and all subsequent
1654
- * renders). Receives the `changedProperties` Map so you can branch on
1655
- * what changed this cycle.
1656
- *
1657
- * **When to use:** post-render DOM work that depends on the new DOM,
1658
- * triggered by specific property changes. This is the lit-aligned
1659
- * replacement for ad-hoc `requestAnimationFrame` shims that components
1660
- * historically used to defer DOM work after `render()`.
1661
- *
1662
- * ```js
1663
- * updated(changedProperties) {
1664
- * if (changedProperties.has('open') && this.open) {
1665
- * this.querySelector('input')?.focus();
1666
- * }
1667
- * }
1668
- * ```
1669
- *
1670
- * @param {Map<string, unknown>} _changedProperties
1671
- */
1672
- updated(_changedProperties) {}
1673
-
1674
- /**
1675
- * Called exactly once, after the component's very first render completes
1676
- * and the DOM is live. Receives the same `changedProperties` Map that
1677
- * `updated()` does for the first render; entries reflect the initial
1678
- * values of reactive properties (old values are `undefined`).
1679
- *
1680
- * **When to use:** one-time post-render setup that requires DOM access.
1681
- * Auto-focusing an input, measuring layout, initializing a third-party
1682
- * library on a DOM node. `connectedCallback` fires before the first
1683
- * render, so querying shadow children there yields nothing.
1684
- *
1685
- * ```js
1686
- * firstUpdated(changedProperties) {
1687
- * this.shadowRoot.querySelector('input')?.focus();
1688
- * }
1689
- * ```
1690
- *
1691
- * @param {Map<string, unknown>} _changedProperties
1692
- */
1693
- firstUpdated(_changedProperties) {}
1694
-
1695
- /**
1696
- * A Promise that resolves after the next render commit. Resolves to
1697
- * `true` when the component has settled (no further updates queued),
1698
- * `false` if another render is already scheduled.
1699
- *
1700
- * **When to use:** awaiting a re-render in tests, or in user code that
1701
- * needs to read the post-render DOM after triggering an update.
1702
- *
1703
- * ```js
1704
- * el.count = 5;
1705
- * await el.updateComplete;
1706
- * // DOM now reflects count = 5
1707
- * ```
1708
- *
1709
- * @returns {Promise<boolean>}
1710
- */
1711
- get updateComplete() {
1712
- return this.getUpdateComplete();
1713
- }
1714
-
1715
- /**
1716
- * Override point for `updateComplete`. Default returns the internal
1717
- * update promise. Override to await additional async work that should
1718
- * be considered part of the update cycle (e.g. lazy-loaded subcomponents).
1719
- *
1720
- * ```js
1721
- * async getUpdateComplete() {
1722
- * const result = await super.getUpdateComplete();
1723
- * await this._chart?.updateComplete;
1724
- * return result;
1725
- * }
1726
- * ```
1727
- *
1728
- * @returns {Promise<boolean>}
1729
- */
1730
- getUpdateComplete() {
1731
- return this._updatePromise;
1732
- }
1733
-
1734
- // ---------------------------------------------------------------------------
1735
- // Reactive controllers
1736
- // ---------------------------------------------------------------------------
1737
-
1738
- /**
1739
- * Register a {@link ReactiveController} with this component.
1740
- *
1741
- * **When to use:** call this from your controller's constructor (which
1742
- * typically receives the host as its first argument) or from the
1743
- * component's constructor / `connectedCallback`.
1744
- *
1745
- * **Why it exists:** controllers decouple reusable lifecycle behaviour
1746
- * from the class hierarchy. Instead of extending a base class or using
1747
- * a mixin, you compose controllers:
1748
- *
1749
- * ```js
1750
- * class MouseController {
1751
- * constructor(host) {
1752
- * this.host = host;
1753
- * host.addController(this);
1754
- * }
1755
- * hostConnected() { window.addEventListener('mousemove', this._onMove); }
1756
- * hostDisconnected() { window.removeEventListener('mousemove', this._onMove); }
1757
- * }
1758
- * ```
1759
- *
1760
- * If the host is already connected when the controller is added, the
1761
- * controller's `hostConnected()` is called immediately.
1762
- *
1763
- * @param {ReactiveController} controller
1764
- */
1765
- addController(controller) {
1766
- this.__controllers.add(controller);
1767
- if (this._connected && controller.hostConnected) {
1768
- controller.hostConnected();
1769
- }
1770
- }
1771
-
1772
- /**
1773
- * Unregister a previously added {@link ReactiveController}.
1774
- *
1775
- * **When to use:** call this when a controller's lifetime is shorter
1776
- * than the component's: e.g. a controller that tracks a specific
1777
- * resource and should be swapped out when the resource changes.
1778
- *
1779
- * The controller's `hostDisconnected()` is NOT called by `removeController`;
1780
- * if cleanup is needed, call it yourself before removing.
1781
- *
1782
- * @param {ReactiveController} controller
1783
- */
1784
- removeController(controller) {
1785
- this.__controllers.delete(controller);
1786
- }
1787
-
1788
- /**
1789
- * Override in subclasses to return a TemplateResult.
1790
- * @returns {unknown}
1791
- */
1792
- render() {
1793
- return '';
1794
- }
1795
-
1796
- /**
1797
- * Called when `render()` throws an error on the client side.
1798
- *
1799
- * **When to override (AI hint):** Override this to show a fallback UI
1800
- * when a component's render fails. Without this, the error is logged
1801
- * and the component renders nothing. The default implementation returns
1802
- * `undefined` (empty render).
1803
- *
1804
- * **Why it exists:** Client-side error boundary. Prevents one broken
1805
- * component from crashing the entire page. Similar to React's
1806
- * `componentDidCatch` / Error Boundaries.
1807
- *
1808
- * ```js
1809
- * renderError(error) {
1810
- * return html`<p style="color:red">Something went wrong: ${error.message}</p>`;
1811
- * }
1812
- * ```
1813
- *
1814
- * @param {Error} error The error thrown by render().
1815
- * @returns {unknown} A TemplateResult fallback, or undefined for empty.
1816
- */
1817
- renderError(error) {
1818
- return undefined;
1819
- }
1820
-
1821
- /**
1822
- * Optional loading UI for an async render() (#469), shown ONLY during a
1823
- * client RE-FETCH (a prop / dependency change re-runs `async render()`),
1824
- * NEVER on the first paint.
1825
- *
1826
- * **When to override (AI hint):** the client re-fetch default is
1827
- * stale-while-revalidate (the component keeps showing its current content
1828
- * until the new render resolves). Override `renderFallback()` only when you
1829
- * want a loading state (skeleton / spinner) shown during the re-fetch
1830
- * instead of the stale content, e.g. when stale data would mislead.
1831
- *
1832
- * **What it does NOT do:** it does not affect the first paint (SSR always
1833
- * blocks and bakes real data in), and it does NOT create a server-streaming
1834
- * boundary. To show a first-paint fallback for slow data, wrap the component
1835
- * in `<webjs-suspense .fallback=${...}>` instead. It is a prop-aware method,
1836
- * not a static field, so it can branch on the component's current state.
1837
- *
1838
- * ```js
1839
- * renderFallback() { return html`<div class="skeleton h-24"></div>`; }
1840
- * async render() { const u = await getUser(this.id); return html`<h3>${u.name}</h3>`; }
1841
- * ```
1842
- *
1843
- * @returns {unknown} A TemplateResult loading state, or undefined to keep
1844
- * the stale-while-revalidate default.
1845
- */
1846
- renderFallback() {
1847
- return undefined;
1848
- }
1849
- }
1850
-
1851
- /** @param {string} s */
1852
- function hyphenate(s) {
1853
- return s.replace(/([A-Z])/g, '-$1').toLowerCase();
1854
- }
1855
- /** @param {string} s */
1856
- function camelCase(s) {
1857
- return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1858
- }
1859
-
1860
- /**
1861
- * Dual-role WebComponent class and factory.
1862
- * Can be extended directly: `class X extends WebComponent`
1863
- * Or called as a class factory: `class X extends WebComponent({ count: Number })`
1864
- *
1865
- * @param {Record<string, any>} [properties]
1866
- * @returns {any}
1867
- */
1868
- export function WebComponent(properties) {
1869
- if (new.target) {
1870
- return Reflect.construct(WebComponentBase, arguments, new.target);
1871
- } else {
1872
- return class extends WebComponentBase {
1873
- static properties = properties;
1874
- static [FACTORY_PROPS] = true;
1875
- };
1876
- }
1877
- }
1878
-
1879
- // Ensure static inheritance and instanceof checks work
1880
- Object.setPrototypeOf(WebComponent, WebComponentBase);
1881
- WebComponent.prototype = WebComponentBase.prototype;
1882
-
1883
- /**
1884
- * Helper to define properties with custom options.
1885
- *
1886
- * @param {any} [type]
1887
- * @param {any} [opts]
1888
- * @returns {any}
1889
- */
1890
- export function prop(type, opts = {}) {
1891
- if (type && typeof type === 'object' && !('call' in type)) {
1892
- opts = type;
1893
- type = undefined;
1894
- }
1895
- return { ...(type ? { type } : {}), ...opts };
1896
- }
1
+ export { WebComponent } from './component/lifecycle.js';
2
+ export { prop } from './component/reactive.js';