@twobirds/microcomponents 0.8.0 → 0.10.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.
Files changed (44) hide show
  1. package/README.md +2 -16
  2. package/dist/cli/bundle.d.ts +106 -0
  3. package/dist/cli/bundle.d.ts.map +1 -0
  4. package/dist/cli/bundler.d.ts +44 -0
  5. package/dist/cli/bundler.d.ts.map +1 -0
  6. package/dist/cli/dev.d.ts +87 -0
  7. package/dist/cli/dev.d.ts.map +1 -0
  8. package/dist/cli/dispatch.d.ts +6 -2
  9. package/dist/cli/dispatch.d.ts.map +1 -1
  10. package/dist/cli/index.js +1807 -1
  11. package/dist/cli/inliner.d.ts +42 -0
  12. package/dist/cli/inliner.d.ts.map +1 -0
  13. package/dist/cli/preview.d.ts +48 -0
  14. package/dist/cli/preview.d.ts.map +1 -0
  15. package/dist/core/elements.js +1294 -75
  16. package/dist/core/mcGuards.js +5 -8
  17. package/dist/mcp/api.json +2 -17
  18. package/dist/mcp/concepts/project-layout.md +9 -8
  19. package/dist/mcp/index.js +450 -230
  20. package/dist/microcomponents.js +2882 -9
  21. package/dist/state/formValues.js +2236 -281
  22. package/dist/state/observables.js +1794 -342
  23. package/dist/utils/events.js +171 -197
  24. package/package.json +3 -7
  25. package/dist/cli/create.js +0 -568
  26. package/dist/cli/dispatch.js +0 -316
  27. package/dist/cli/scaffold.js +0 -109
  28. package/dist/cli/writeScaffold.js +0 -114
  29. package/dist/core/MC.js +0 -837
  30. package/dist/core/index.js +0 -72
  31. package/dist/state/index.js +0 -5
  32. package/dist/state/placeholders.js +0 -187
  33. package/dist/types/index.js +0 -1
  34. package/dist/types/mcTypes.js +0 -9
  35. package/dist/utils/autoload.js +0 -160
  36. package/dist/utils/helpers.js +0 -532
  37. package/dist/utils/index.js +0 -12
  38. package/dist/utils/resolveComponentPath.js +0 -39
  39. package/dist/vite/index.d.ts +0 -7
  40. package/dist/vite/index.d.ts.map +0 -1
  41. package/dist/vite/index.js +0 -6
  42. package/dist/vite/loadAssets.d.ts +0 -36
  43. package/dist/vite/loadAssets.d.ts.map +0 -1
  44. package/dist/vite/loadAssets.js +0 -221
@@ -1,3 +1,1981 @@
1
+ //#region src/utils/events.ts
2
+ /**
3
+ @module Events
4
+
5
+ This module provides event utilities for interfacing **between microcomponents and external
6
+ frameworks or native DOM/JS environments**. It is not intended for communication between
7
+ frontend microcomponents themselves — for that purpose, use the inherited methods
8
+ ( `.on()`, `.one()`, `.off()`, `.trigger()`) that exist when you extend `DC`.
9
+
10
+ Import this module when you need to exchange information with microcomponents from outside
11
+ the microcomponent system (e.g., vanilla JS, React via `useRef()`, or other frameworks).
12
+
13
+ The core feature is the ability to explicitly control event flow direction when using {@link trigger}:
14
+ - upward propagation to ancestor components ('u')
15
+ - local dispatch only ('l') [default]
16
+ - downward propagation to descendant components ('d').
17
+
18
+ @example
19
+ html:
20
+ ```html
21
+ <div class="grandparent">
22
+ <div class="parent">
23
+ <div class="child">
24
+ </div>
25
+ </div>
26
+ </div>
27
+ ```
28
+
29
+ javascript:
30
+ ```javascript
31
+ import { on, one, trigger, off } from '@twobirds/microcomponents/events';
32
+
33
+ const grandParent = document.querySelector('.grandparent');
34
+ const parent = document.querySelector('.parent');
35
+ const child = document.querySelector('.child');
36
+ if (!grandParent || !parent || !child) throw new Error('example markup missing');
37
+
38
+ const grandParentHandler = on(grandParent, 'dataReady', (ev) => console.log(ev.detail.data));
39
+
40
+ const parentHandler = on(parent, 'dataReady', (ev) => ev.detail.control.stop());
41
+
42
+ trigger(child, 'dataReady', { value: 42 }, 'u');
43
+
44
+ off(parent, 'dataReady', parentHandler);
45
+ off(grandParent, 'dataReady', grandParentHandler);
46
+ ```
47
+
48
+ The `dataReady` event bubbles upward from the innermost `div`, but `parentHandler`
49
+ calls `ev.detail.control.stop()`, so the `grandParent` handler is never reached.
50
+ Handlers are detached with `off()` once they are no longer needed.
51
+ */
52
+ /**
53
+ * Returns the correct event name to listen for on a DOM element.
54
+ *
55
+ * If `eventName` (case-insensitive) matches a native HTML event handler property
56
+ * (`'on' + eventName.toLowerCase()`) on the target, returns the lowercase native
57
+ * name so that standard DOM events like `'click'` are listened to correctly.
58
+ * Otherwise, prefixes with `_mc` for microcomponent custom events.
59
+ *
60
+ * @hidden
61
+ * @param target - The DOM element whose native event support is checked.
62
+ * @param eventName - The event name as provided by the caller (e.g., `'click'`, `'Update'`).
63
+ * @returns The resolved event name: lowercase native or `_mc`-prefixed custom.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const btn = document.createElement('button');
68
+ * console.log(trueEventName(btn, 'Click'));
69
+ * console.log(trueEventName(btn, 'Update'));
70
+ * ```
71
+ *
72
+ * `'Click'` resolves to the native `'click'` because the button has an `onclick` handler
73
+ * property; `'Update'` has no native counterpart, so it becomes the `_mc`-prefixed custom
74
+ * event name.
75
+ */
76
+ function trueEventName(target, eventName) {
77
+ const lower = eventName.toLowerCase();
78
+ if ("on" + lower in target) return lower;
79
+ return "_mc" + eventName[0].toUpperCase() + eventName.substring(1);
80
+ }
81
+ /**
82
+ Removes a previously attached event handler from the DOM node. See {@link on} and {@link one}.
83
+
84
+ Uses internal microcomponent-prefixed naming for event handlers.
85
+ This is primarily used to interface with external frameworks or vanilla JS environments.
86
+ For communication between frontend microcomponents, use the `DC.off()` method instead.
87
+
88
+ @param target - The DOM element from which to remove the listener.
89
+ @param eventName - The name of the event (e.g., 'click', 'update').
90
+ @param handler - The listener function or object to detach.
91
+
92
+ @example
93
+ ```ts
94
+ const handler = on(myElement, 'click', () => console.log('clicked'));
95
+ off(myElement, 'click', handler);
96
+ ```
97
+ @group Events
98
+ */
99
+ function off(target, eventName, handler) {
100
+ /* v8 ignore next */
101
+ if (!target) return;
102
+ if (typeof target === "string") {
103
+ document.querySelectorAll(target).forEach((el) => off(el, eventName, handler));
104
+ return;
105
+ }
106
+ target.removeEventListener(trueEventName(target, eventName), handler);
107
+ }
108
+ /**
109
+ Attaches a persistent event listener that will fire every time the specified event occurs.
110
+
111
+ This is primarily used to interface with external frameworks or vanilla JS environments.
112
+ For communication between frontend microcomponents, use the `DC.on()` method instead.
113
+
114
+ The handler receives a `CustomEvent<McDetail<D>>`: the payload sits under
115
+ `ev.detail.data`, the bubble-control handle under `ev.detail.control`.
116
+
117
+ @param target - The DOM element to attach the listener to.
118
+ @param eventName - The name of the event (e.g., 'click', 'update').
119
+ @param handler - The callback function or object to invoke on each event.
120
+ @param once - If true, remove the listener after first invocation.
121
+ @returns The attached handler reference. Useful for later deletion with {@link off}.
122
+
123
+ @example
124
+ ```ts
125
+ const handler = on<{ value: number }>(myElement, 'update', (ev) => {
126
+ console.log(ev.detail.data.value);
127
+ });
128
+ off(myElement, 'update', handler);
129
+ ```
130
+ @group Events
131
+ */
132
+ function on(target, eventName, handler, once = false) {
133
+ /* v8 ignore next */
134
+ if (!target) return;
135
+ if (typeof target === "string") {
136
+ document.querySelectorAll(target).forEach((el) => on(el, eventName, handler));
137
+ return;
138
+ }
139
+ target.addEventListener(trueEventName(target, eventName), handler, {
140
+ capture: false,
141
+ once
142
+ });
143
+ return handler;
144
+ }
145
+ /**
146
+ Attaches an event listener that will fire only once.
147
+
148
+ Internally calls {@link on} with the `once` flag set to true. The handler
149
+ is automatically removed after its first invocation.
150
+ This is primarily used to interface with external frameworks or vanilla JS environments.
151
+ For communication between frontend microcomponents, use the `DC.one()` method instead.
152
+
153
+ @param target - The DOM element to attach the listener to.
154
+ @param eventName - The name of the event (e.g., 'click', 'update').
155
+ @param handler - The callback function or object to invoke once.
156
+ @returns The attached one-time handler reference. Useful for later deletion with {@link off}.
157
+
158
+ @example
159
+ ```ts
160
+ one<{ ready: boolean }>(myElement, 'dataReady', (ev) => console.log('received:', ev.detail.data));
161
+ ```
162
+
163
+ The listener fires only once and detaches automatically.
164
+ @group Events
165
+ */
166
+ function one(target, eventName, handler) {
167
+ /* v8 ignore next */
168
+ if (!target) return;
169
+ if (typeof target === "string") {
170
+ document.querySelectorAll(target).forEach((el) => one(el, eventName, handler));
171
+ return;
172
+ }
173
+ on(target, eventName, handler, true);
174
+ return handler;
175
+ }
176
+ /**
177
+ * @hidden
178
+ * A controller object used to manage and potentially abort event bubbling.
179
+ *
180
+ * The `trigger()` function internally creates instance of this class,
181
+ * allowing the an eventual handler to call `ev.detail.control.stop()` to
182
+ * prevent further propagation in either direction (up/down).
183
+ *
184
+ * This is only used internally.
185
+ * @example
186
+ * ```ts
187
+ * trigger(myElement, 'update', { value: 42 }, 'u');
188
+ *
189
+ * onUpdate(ev) {
190
+ * ev.detail.control.stop();
191
+ * }
192
+ * ```
193
+ */
194
+ var BubbleController = class {
195
+ stopped = false;
196
+ constructor() {}
197
+ /**
198
+ * Signals that event bubbling should be halted.
199
+ *
200
+ * After calling this method, subsequent `trigger()` calls will abort
201
+ * before dispatching the event to any targets.
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * trigger(myElement, 'update', { value: 42 }, 'u');
206
+ *
207
+ * onUpdate(ev) {
208
+ * ev.detail.control.stop();
209
+ * }
210
+ * ```
211
+ */
212
+ stop() {
213
+ this.stopped = true;
214
+ }
215
+ };
216
+ /**
217
+ * Creates and dispatches a custom event on the specified DOM node.
218
+ *
219
+ * The event is namespaced with an `_mc` prefix by default, unless already prefixed.
220
+ * Supports bidirectional bubbling (up/down the DOM tree) based on the `bubble` parameter:
221
+ * - 'l': local dispatch only
222
+ * - 'u': bubble up towards ancestors
223
+ * - 'd': bubble down to descendants
224
+ *
225
+ * The dispatched event is a `CustomEvent<McDetail<D>>`: handlers find the payload
226
+ * under `ev.detail.data` and can call `ev.detail.control.stop()` to cancel bubbling.
227
+ *
228
+ * Prefer a direct target over bubbling: name the receiving element in `target` and keep the
229
+ * default `'l'`, so one `querySelectorAll` reaches it in a single step. Reserve `'u'`/`'d'`
230
+ * for receivers that cannot be named in advance, since they walk the tree and re-dispatch the
231
+ * event at every level. Pass a typed object as `data` rather than a bare string, so the
232
+ * handler reads named fields from `ev.detail.data` and the flow stays readable as it grows.
233
+ *
234
+ * @param target - The DOM element on which to trigger the event, or a querySelectorAll(selector) selector string.
235
+ * @param event - The name of the event (will be prefixed if needed).
236
+ * @param data - Additional data payload attached to `event.detail.data`.
237
+ * @param bubble - Bubbling direction ('l', 'u', 'd' or combinations).
238
+ * @param controller - Optional controller for managing bubbling behavior.
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * trigger(myElement, 'update', { value: 42 }, 'l');
243
+ * trigger(myElement, 'dataReady', { ready: true }, 'u');
244
+ * ```
245
+ *
246
+ * The first dispatch fires locally only; the second bubbles upward to ancestor components.
247
+ */
248
+ function trigger(target, event, data = {}, bubble = "l", controller) {
249
+ /* v8 ignore next */
250
+ if (!target) return;
251
+ if (typeof target === "string") {
252
+ document.querySelectorAll(target).forEach((el) => trigger(el, event, data, bubble));
253
+ return;
254
+ }
255
+ const eventName = /^_mc/.test(event) ? event : trueEventName(target, event), bubbleController = controller ? controller : new BubbleController(), ev = new CustomEvent(eventName, {
256
+ detail: {
257
+ data,
258
+ control: bubbleController
259
+ },
260
+ bubbles: false
261
+ });
262
+ if (bubbleController.stopped) return;
263
+ if (/l/.test(bubble)) {
264
+ target.dispatchEvent(ev);
265
+ if (bubbleController.stopped) return;
266
+ }
267
+ if (/[ud]/.test(bubble)) queueMicrotask(() => {
268
+ if (bubble.indexOf("u") > -1) trigger(target.parentElement, eventName, data, "lu", bubbleController);
269
+ if (bubble.indexOf("d") > -1) for (const child of target.children) trigger(child, eventName, data, "ld");
270
+ });
271
+ }
272
+ //#endregion
273
+ //#region src/utils/helpers.ts
274
+ /**
275
+ * Determines whether the current runtime environment is a web browser.
276
+ *
277
+ * This function works by attempting to access `this` within an anonymous function
278
+ * and checking if it refers to the global `window` object. It returns `true`
279
+ * when executed in a browser context, and `false` otherwise (e.g., Node.js).
280
+ *
281
+ * Note: While modern environments typically provide more reliable detection mechanisms,
282
+ * this fallback remains compatible across older runtimes where other detection techniques
283
+ * may be unreliable.
284
+ *
285
+ * @returns `true` if the code is running in a browser environment, `false` otherwise.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * if (isBrowser()) {
290
+ * console.log('Running in a browser');
291
+ * }
292
+ * ```
293
+ */
294
+ function isBrowser() {
295
+ return typeof window !== "undefined" && typeof window.document !== "undefined";
296
+ }
297
+ /**
298
+ * Checks if a value is a native JavaScript object (created via {} or new Object()).
299
+ * @param value - The value to check.
300
+ * @returns True if the value is a plain object, false otherwise.
301
+ *
302
+ * @example
303
+ * ```ts
304
+ * console.log(isNativeObject({}));
305
+ * console.log(isNativeObject(new Object()));
306
+ * console.log(isNativeObject([]));
307
+ * console.log(isNativeObject(null));
308
+ * ```
309
+ */
310
+ function isNativeObject(value) {
311
+ return typeof value === "object" && value !== null && value.constructor === Object;
312
+ }
313
+ /**
314
+ * Recursively sorts all keys in an object alphabetically, preserving nested structure.
315
+ * @param source - The object to sort.
316
+ * @returns A new object with sorted keys at all levels.
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * const obj = { z: 1, a: { y: 2, b: 3 } };
321
+ * console.log(JSON.stringify(sortObject(obj)));
322
+ * ```
323
+ */
324
+ function sortObject(source) {
325
+ const result = {}, keys = Object.keys(source).sort();
326
+ for (let i = 0; i < keys.length; i++) {
327
+ const key = keys[i], value = source[key];
328
+ if (isNativeObject(value)) result[key] = sortObject(value);
329
+ else result[key] = value;
330
+ }
331
+ return result;
332
+ }
333
+ /**
334
+ * Flattens a nested object into a single-level object with dot-separated keys.
335
+ * Optionally sorts the resulting flat keys alphabetically (default: true).
336
+ * @param source - The object to flatten.
337
+ * @param doSort - Whether to sort the resulting keys (default: true).
338
+ * @returns A flattened object with dot-notation keys.
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * const obj = { user: { name: 'Alice', age: 30 } };
343
+ * console.log(JSON.stringify(flattenObject(obj)));
344
+ * ```
345
+ */
346
+ function flattenObject(source, doSort = true) {
347
+ const result = {};
348
+ const record = source;
349
+ const names = Object.getOwnPropertyNames(source);
350
+ for (let i = 0; i < names.length; i++) {
351
+ const propName = names[i], value = record[propName];
352
+ if (value instanceof Object) {
353
+ const temp = flattenObject(value, false);
354
+ for (const j in temp) result[propName + "." + j] = temp[j];
355
+ } else result[propName] = value;
356
+ }
357
+ return doSort ? sortObject(result) : result;
358
+ }
359
+ /**
360
+ * Structural deep-equality using SameValueZero for primitives.
361
+ *
362
+ * See {@link https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero}.
363
+ *
364
+ * Note: `Map`/`Set` are not structurally compared.
365
+ *
366
+ * @param a - The first value to compare.
367
+ * @param b - The second value to compare.
368
+ * @returns True if the values are deeply equal, false otherwise.
369
+ *
370
+ * @example
371
+ * ```ts
372
+ * console.log(deepEqual({ a: 1 }, { a: 1 }));
373
+ * console.log(deepEqual({ a: { b: 2 } }, { a: {} }));
374
+ * console.log(deepEqual({ a: NaN }, { a: NaN }));
375
+ * console.log(deepEqual({ a: NaN }, { a: null }));
376
+ * ```
377
+ */
378
+ function deepEqual(a, b) {
379
+ if (a === b || a !== a && b !== b) return true;
380
+ /* v8 ignore start */
381
+ if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) return false;
382
+ if (a.constructor !== b.constructor) return false;
383
+ if (a instanceof Date) return a.getTime() === b.getTime();
384
+ if (a instanceof RegExp) return a.toString() === b.toString();
385
+ /* v8 ignore end */
386
+ if (Array.isArray(a)) {
387
+ const bArr = b;
388
+ /* v8 ignore next */
389
+ if (a.length !== bArr.length) return false;
390
+ for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], bArr[i])) return false;
391
+ return true;
392
+ }
393
+ const aObj = a, bObj = b, keys = Object.keys(aObj);
394
+ if (keys.length !== Object.keys(bObj).length) return false;
395
+ for (let i = 0; i < keys.length; i++) {
396
+ const key = keys[i];
397
+ if (!Object.prototype.hasOwnProperty.call(bObj, key) || !deepEqual(aObj[key], bObj[key])) return false;
398
+ }
399
+ return true;
400
+ }
401
+ /**
402
+ * Copies all getter and setter properties from a source object to a target object.
403
+ * Does not copy methods or regular data properties—only accessor properties (get/set).
404
+ * @hidden
405
+ * @param source - The source object with getters and/or setters to copy.
406
+ * @param target - The target object to which the accessors will be copied.
407
+ *
408
+ * @example
409
+ * ```ts
410
+ * const src = { get name() { return 'Alice'; } };
411
+ * const tgt = {};
412
+ * copyGettersSetters(src, tgt);
413
+ * console.log(tgt.name);
414
+ * ```
415
+ */
416
+ function copyGettersSetters(source, target) {
417
+ const descriptors = Object.getOwnPropertyDescriptors(source);
418
+ for (const [key, descriptor] of Object.entries(descriptors)) if ("get" in descriptor || "set" in descriptor) Object.defineProperty(target, key, descriptor);
419
+ }
420
+ /**
421
+ * Injects a CSS string into the given scope (document or shadow root) as an adopted stylesheet.
422
+ * Enables css-in-js so that every custom element is self-contained and importable.
423
+ *
424
+ * @hidden
425
+ * @param target - The scope to inject styles into: `document` for global styles, or a `ShadowRoot` for encapsulated component internals.
426
+ * @param css - The CSS string to inject.
427
+ * @returns The created `CSSStyleSheet` instance that was adopted into the target scope.
428
+ *
429
+ * When targeting **document**: selectors like `:host`, `::slotted()`, and shadow-internal classes are **not allowed** — they have no effect outside a shadow root. Use only global selectors, element tags, or layout presets.
430
+ * When targeting **shadowRoot**: use `:host` for the custom element itself, standard selectors (`.inner`, `#id`) for internal structure, and `::slotted()` for projected light-DOM content.
431
+ *
432
+ * @example Inject global styles into the document:
433
+ * ```ts
434
+ * import { injectCSS } from '@twobirds/mc/utils/helpers';
435
+ * injectCSS(document, 'body { display: block; }');
436
+ * ```
437
+ *
438
+ * @example Inject global styles for a micro component into the document:
439
+ * ```ts
440
+ * import { injectCSS } from '@twobirds/mc/utils/helpers';
441
+ * injectCSS(document, 'my-microcomponent { display: block; }');
442
+ * ```
443
+ *
444
+ * @example Inject scoped styles into a shadow root:
445
+ * ```ts
446
+ * const shadow = element.attachShadow({ mode: 'open' });
447
+ * injectCSS(shadow, ':host { color: var(--text); } .inner { padding: 8px; }');
448
+ * ```
449
+ * Styles can also be added using a compound innerHTML statement: `shadow.innerHTML = \`<style>${style}</style>${template}\``
450
+ */
451
+ var _injectedCSS = /* @__PURE__ */ new WeakMap();
452
+ function injectCSS(target, css) {
453
+ const injected = _injectedCSS.get(target) ?? /* @__PURE__ */ new Set();
454
+ if (injected.has(css)) return target.adoptedStyleSheets[0];
455
+ injected.add(css);
456
+ _injectedCSS.set(target, injected);
457
+ const sheet = new CSSStyleSheet();
458
+ sheet.replaceSync(css);
459
+ target.adoptedStyleSheets.push(sheet);
460
+ return sheet;
461
+ }
462
+ /**
463
+ * Processes a record of asset strings and applies them to the given target element.
464
+ * Supports injecting CSS into document or shadow root, and setting innerHTML for
465
+ * both target and shadow DOM. Automatically attaches a shadow root if any key starts
466
+ * with `'shadow'`.
467
+ *
468
+ * Recognized keys: `'css'`, `'targetCss'` (document-level styles), `'shadowCss'`
469
+ * (shadow-root styles), `'shadowHtml'` (shadow innerHTML), `'targetHtml'` (target innerHTML).
470
+ *
471
+ * @param instance - The micro component to apply assets onto.
472
+ * @param assets - A record mapping asset type keys to their string content.
473
+ *
474
+ * @example
475
+ * ```ts
476
+ * processAssets(this, {
477
+ * css: 'body { margin: 0; }',
478
+ * shadowCss: ':host { display: block; }',
479
+ * shadowHtml: '<slot></slot>'
480
+ * });
481
+ * ```
482
+ */
483
+ function processAssets(instance, assets) {
484
+ const target = instance.target;
485
+ let shadow = target.shadowRoot;
486
+ if (!shadow && Object.keys(assets).some((key) => key.indexOf("shadow") === 0)) shadow = target.attachShadow({ mode: "open" });
487
+ Object.keys(assets).forEach((key) => {
488
+ switch (key) {
489
+ case "css":
490
+ injectCSS(document, assets[key]);
491
+ break;
492
+ case "targetCss":
493
+ injectCSS(document, assets[key]);
494
+ break;
495
+ case "shadowCss":
496
+ injectCSS(shadow, assets[key]);
497
+ break;
498
+ case "shadowHtml":
499
+ shadow.innerHTML = assets[key];
500
+ bindTemplateEvents(shadow, instance);
501
+ break;
502
+ case "targetHtml":
503
+ target.innerHTML = assets[key];
504
+ bindTemplateEvents(target, instance);
505
+ break;
506
+ }
507
+ });
508
+ }
509
+ /**
510
+ * Loads companion asset files (CSS, HTML) for a given component basename from the server.
511
+ *
512
+ * Each entry in `assets` encodes an optional variant and extension in camelCase, e.g. `'shadowCss'` → `{name}.shadow.css`,
513
+ * `'targetHtml'` → `{name}.target.html`. Plain entries like `'css'` or `'html'` resolve to
514
+ * `{name}.css` / `{name}.html`.
515
+ *
516
+ * In bundled mode the Vite plugin replaces this call with an inline array literal, so `.then()`
517
+ * fires synchronously — no async overhead.
518
+ *
519
+ * @hidden
520
+ * @param name - The component basename (e.g. `'shop-catalog'`).
521
+ * @param assets - Array of asset descriptors such as `'shadowCss'`, `'targetHtml'`, `'shadowHtml'`, `'css'`, `'html'`.
522
+ * @returns A promise resolving to an array of file contents in the same order as `assets`. If a file is not found, the corresponding entry is `'file not found: ' + filename`.
523
+ *
524
+ * @example
525
+ * ```ts
526
+ * export const MyComponent = loadAssets('my-component', ['shadowCss', 'shadowHtml']).then(([shadowCss, shadowHtml]) => {
527
+ * class _MyComponent extends DC { ... }
528
+ * defineCE('my-component', _MyComponent);
529
+ * return _MyComponent;
530
+ * });
531
+ * ```
532
+ */
533
+ function loadAssets(name, assets) {
534
+ const parseAsset = (asset) => {
535
+ const m = asset.match(/^([a-z]+)([A-Z][a-z]*)$/);
536
+ if (m) return `./${name.replace(/-/g, "/")}.${m[1]}.${m[2].toLowerCase()}`;
537
+ return `./${name.replace(/-/g, "/")}.${asset.toLowerCase()}`;
538
+ };
539
+ return Promise.all(assets.map(async (asset) => {
540
+ const filename = parseAsset(asset);
541
+ try {
542
+ const resp = await fetch(filename);
543
+ if (!resp.ok) return `file not found: ${filename}`;
544
+ if (filename.endsWith("json")) {
545
+ const text = await resp.text();
546
+ try {
547
+ return JSON.parse(text);
548
+ } catch {
549
+ console.error(`could not JSON.parse() asset '${asset}' from ${filename}:\n`, text);
550
+ return null;
551
+ }
552
+ }
553
+ return resp.text();
554
+ } catch {
555
+ return `file not found: ${filename}`;
556
+ }
557
+ }));
558
+ }
559
+ /**
560
+ * Binds declarative event attributes in a template fragment to microcomponent triggers.
561
+ *
562
+ * Scans all elements under `root` for attributes whose names correspond to native DOM
563
+ * events (e.g. `click`, `submit`, `change`). The attribute value encodes the target and
564
+ * handler method in the form `target|methodName`:
565
+ *
566
+ * - `this|myHandler` — triggers locally on the component attached to this element.
567
+ * - `other-comp|submit` — resolves elements via `querySelectorAll('other-comp')` and
568
+ * triggers the event on each matched host's `_mc`.
569
+ *
570
+ * An optional sibling `payload` attribute supplies the data argument for `trigger()`.
571
+ * After binding, both the event attribute and the payload attribute are removed from the DOM.
572
+ *
573
+ * @param rootElement - The container element whose descendants should be scanned for bindings.
574
+ * @param instance - The instance to trigger events on.
575
+ *
576
+ * @example
577
+ * ```html
578
+ * <button click='this|onSubmit|{"action":"go"}'>Submit</button>
579
+ * <input change="|cart-form|refresh">
580
+ * ```
581
+ */
582
+ function bindTemplateEvents(rootElement, instance) {
583
+ const allElements = [...rootElement.querySelectorAll("*")];
584
+ for (const el of allElements) {
585
+ if (!(el instanceof HTMLElement)) continue;
586
+ const attrs = [...el.attributes];
587
+ for (const attr of attrs) {
588
+ const lowerName = attr.name.toLowerCase();
589
+ if (!("on" + lowerName in el)) continue;
590
+ const parts = attr.value.trim().split("|");
591
+ if (parts.length < 2) continue;
592
+ const [selector, event, payload] = parts;
593
+ el.removeAttribute(attr.name);
594
+ let payloadData;
595
+ if (payload) try {
596
+ payloadData = JSON.parse(payload);
597
+ } catch {
598
+ payloadData = payload;
599
+ }
600
+ if (selector === "this" || selector === "") on(el, lowerName, () => instance.trigger(event, payloadData));
601
+ else on(el, lowerName, () => trigger(selector, event, payloadData));
602
+ }
603
+ }
604
+ }
605
+ //#endregion
606
+ //#region src/core/mcGuards.ts
607
+ function isMcHost(element, key) {
608
+ return typeof HTMLElement !== "undefined" && element instanceof HTMLElement && "_mc" in element && (key === void 0 || key in element._mc);
609
+ }
610
+ //#endregion
611
+ //#region src/core/MC.ts
612
+ function add(targetHTMLElement, key, element = {}) {
613
+ const node = targetHTMLElement;
614
+ if (!("_mc" in targetHTMLElement)) node._mc = new DC(targetHTMLElement);
615
+ const _mc = node._mc;
616
+ if (key.length && !_mc[key]) {
617
+ _mc[key] = element;
618
+ if (targetHTMLElement instanceof HTMLElement && !targetHTMLElement.getAttribute("data-mc")) targetHTMLElement.setAttribute("data-mc", "");
619
+ }
620
+ return node;
621
+ }
622
+ /**
623
+ Removes a named microcomponent from the internal `_mc` collection of a target DOM node.
624
+
625
+ This function deletes the specified key from the element's `_mc` hash object and, if the
626
+ collection becomes empty, removes the `data-mc` attribute from the DOM node.
627
+
628
+ The bare poisoned value (`el._mc.gone` without member access) is `never`,
629
+ which is assignable to anything — only member/method use of a removed entry is caught.
630
+
631
+ @template T - A plain or already-enhanced element type.
632
+ @template K - The literal registration key; its entry is poisoned in the registry type.
633
+ @param target - The DOM element whose microcomponent should be removed.
634
+ @param key - The property name/key corresponding to the microcomponent to remove.
635
+ */
636
+ function remove(target, key) {
637
+ if (!key) return;
638
+ const _mc = target._mc;
639
+ if (!_mc) return;
640
+ if (_mc[key]) delete _mc[key];
641
+ if (!Object.keys(_mc).length && target instanceof HTMLElement && target.hasAttribute("data-mc")) target.removeAttribute("data-mc");
642
+ }
643
+ /**
644
+ Runs the "Init" lifecycle event on a DOM microcomponent instance asynchronously.
645
+
646
+ This function schedules the `trigger('Init')` call in a microtask, ensuring
647
+ that all synchronous initialization is complete before the lifecycle hook
648
+ executes. Only `DC` instances have an Init lifecycle — the `McBase`
649
+ constructor calls this exclusively behind an `instanceof DC` check, so the
650
+ signature encodes that invariant instead of re-checking it at runtime.
651
+
652
+ @param element - The DOM microcomponent instance on which to trigger the Init event.
653
+ */
654
+ function init(element) {
655
+ queueMicrotask(() => {
656
+ element.trigger("Init", null);
657
+ });
658
+ }
659
+ /**
660
+ Attaches event listeners to DOM elements based on method naming conventions.
661
+
662
+ Scans the prototype of the provided element and attaches listeners for methods
663
+ prefixed with `on` or `one`, corresponding to either native HTML events (e.g.,
664
+ 'onclick') or microcomponent-prefixed custom events (e.g., '_mcUpdate').
665
+
666
+ @param element - The instance whose prototype should be scanned for event handlers.
667
+ */
668
+ function autoAttachListeners(element) {
669
+ const sourceTarget = element.target;
670
+ const prototype = Object.getPrototypeOf(element);
671
+ const sourceElement = element;
672
+ const definedEventHandlerNames = Object.getOwnPropertyNames(prototype).filter((key) => /^(on[A-Z]|one[A-Z])/.test(key) && typeof prototype[key] === "function");
673
+ for (const eventHandlerName of definedEventHandlerNames) {
674
+ const once = /^one/.test(eventHandlerName);
675
+ const eventName = eventHandlerName.replace(/^one?/, "");
676
+ const listener = (ev) => sourceElement[eventHandlerName](ev);
677
+ on(sourceTarget, eventName, listener, once);
678
+ }
679
+ }
680
+ /**
681
+ Retrieves immediate child microcomponents of a DOM node.
682
+
683
+ Queries the DOM for descendant elements marked with `data-mc` that are direct
684
+ children of the provided element and returns their associated `_mc` instances.
685
+
686
+ @param domNode - The DOM element whose child microcomponents to find.
687
+ @returns An array of child microcomponent instances.
688
+ */
689
+ function getMcChildNodes(domNode) {
690
+ return Array.from(domNode.querySelectorAll("[data-mc]:not(:scope [data-mc] [data-mc])")).filter((e) => e instanceof HTMLElement && "_mc" in e).map((e) => e._mc);
691
+ }
692
+ /**
693
+ Walks up the DOM from `from`, returning the `_mc` controller of the nearest
694
+ `data-mc` ancestor — restricted, when `key` is given, to hosts whose registry
695
+ actually carries that key. Hosts marked `data-mc` but not (yet) carrying an
696
+ `_mc` record (e.g. autoload pending) are skipped rather than returned.
697
+
698
+ @param from - The element whose ancestors to search (exclusive).
699
+ @param key - Optional registry key the ancestor's `_mc` must contain.
700
+ @returns The nearest matching controller, or null.
701
+ */
702
+ function findMcAncestor(from, key) {
703
+ let el = from.parentElement?.closest("[data-mc]");
704
+ while (el instanceof HTMLElement) {
705
+ /* v8 ignore next */
706
+ if ("_mc" in el) {
707
+ const mc = el._mc;
708
+ if (key === void 0 || key in mc) return mc;
709
+ }
710
+ el = el.parentElement?.closest("[data-mc]");
711
+ }
712
+ return null;
713
+ }
714
+ /**
715
+ The base class for all microcomponents — shared root of both {@link MC} and {@link DC}.
716
+
717
+ Holds a `WeakRef` to the target (a DOM element for `DC`, or any plain object for `MC`)
718
+ to avoid circular references. For `DC` subclasses it also bootstraps two automatic
719
+ behaviours:
720
+
721
+ 1. **Event listener auto-attachment** — methods whose names start with `on` or `one`
722
+ (e.g. `onClick`, `oneInit`) are wired to the target element via {@link on} / {@link one}.
723
+ 2. **"Init" lifecycle event** — dispatched asynchronously in a microtask so that all
724
+ synchronous constructor work finishes first.
725
+
726
+ Both mechanisms run only when the instance is a `DC` (checked with `instanceof DC`).
727
+ Plain `MC` instances skip them entirely, keeping server-side usage lightweight.
728
+
729
+ ### Plugin extension points
730
+
731
+ The prototype of `McBase` is the attachment point for optional plugins that curry
732
+ additional instance methods onto every microcomponent. Two built-in plugins modify
733
+ this class at runtime:
734
+
735
+ - **{@link State.observePlugin}** — adds `notify()`, `subscribe()`, and `bind()` so that
736
+ observable properties can be controlled directly on the component instance with
737
+ fluent chaining. Call `observePlugin(DC)` once at module level to activate.
738
+
739
+ - **{@link State.formValuePlugin}** — adds `formValues()` for two-way binding between DOM
740
+ form controls and an observable property. Also pulls in all methods from
741
+ {@link State.observePlugin}, so you can chain `.subscribe()` and `.bind()` after
742
+ `.formValues()`. Call `formValuePlugin(DC)` once at module level to activate.
743
+
744
+ Both plugins are idempotent — calling them multiple times has no side effects. They
745
+ work by assigning methods onto `McBase.prototype` (reached via
746
+ `Object.getPrototypeOf(Class.prototype)`) and use TypeScript module augmentation
747
+ (`declare module`) so the added signatures appear in type-checking automatically.
748
+
749
+ @template TTarget - The concrete type of the wrapped target; preserved by the
750
+ {@link McBase.target} getter.
751
+
752
+ @example Extending with plugins at runtime
753
+
754
+ ```ts
755
+ import { DC, observePlugin, formValuePlugin } from '@twobirds/microcomponents';
756
+
757
+ observePlugin(DC);
758
+ formValuePlugin(DC);
759
+
760
+ class MyForm extends DC {
761
+ data = { name: '' };
762
+
763
+ oneInit() {
764
+ this
765
+ .formValues(this.target, 'data')
766
+ .subscribe('data', (v) => console.log(v))
767
+ .bind('data', this.target);
768
+ }
769
+ }
770
+ ```
771
+
772
+ `observePlugin(DC)` adds `notify()`, `subscribe()`, `bind()` to `McBase.prototype`;
773
+ `formValuePlugin(DC)` adds `formValues()` and re-runs `observePlugin`. `oneInit()`
774
+ runs once after the constructor.
775
+ @group Micro Components
776
+ */
777
+ var McBase = class {
778
+ _target;
779
+ /**
780
+ The constructor for the base `McBase` class.
781
+
782
+ Initializes a weak reference to the target and triggers auto-attachment
783
+ of listeners and initialization lifecycle events.
784
+
785
+ @param target - The object or element this microcomponent represents.
786
+ */
787
+ constructor(target) {
788
+ this._target = new WeakRef(target || {});
789
+ if (this instanceof DC && this.constructor !== DC) {
790
+ autoAttachListeners(this);
791
+ const tag = this.constructor.tag;
792
+ if (tag === void 0 || tag.toUpperCase() === this.target.tagName) init(this);
793
+ }
794
+ }
795
+ /**
796
+ Returns the current target object (DOM node or other data) referenced by this microcomponent.
797
+
798
+ Uses a `WeakRef` internally to avoid circular references, and safely dereferences it here.
799
+
800
+ The dereference is asserted non-null: the controller is stored on its target
801
+ (`element._mc`), so any code that can reach the controller through the element is
802
+ holding the target alive. Only a controller retained independently after its element
803
+ was garbage-collected could observe a stale reference — do not cache controllers
804
+ detached from their elements.
805
+
806
+ @returns The target object.
807
+ */
808
+ get target() {
809
+ return this._target.deref();
810
+ }
811
+ };
812
+ /**
813
+ @class DC
814
+ ---
815
+
816
+ A DOM-centric microcomponent that operates on a specific HTML element.
817
+
818
+ Extends {@link McBase} and associates itself with an actual DOM node via the
819
+ `_target` reference. Provides methods for event handling, DOM traversal,
820
+ and interaction with sibling or ancestor microcomponents.
821
+
822
+ ---
823
+
824
+ ## Static Configuration Properties
825
+
826
+ DC classes support three static properties that configure custom elements
827
+ before any instance is constructed:
828
+
829
+ ### `static tag?: string`
830
+
831
+ Replaces the default target element with a semantic HTML element, or removes it entirely.
832
+
833
+ - **Non-empty string** (e.g., `'header'`) — the original custom element is replaced
834
+ with the specified built-in element. The original tag name is added as a CSS class.
835
+ - **Empty string `''`** — the target element is removed from the DOM entirely.
836
+ Useful for components that only inject global styles or act as style containers.
837
+
838
+ @example static tag — replace with semantic element
839
+
840
+ ```ts
841
+ class ShopHeader extends DC {
842
+ static tag = 'header';
843
+ }
844
+ defineCE('shop-header', ShopHeader);
845
+ ```
846
+
847
+ Produces `<header class="shop-header">` instead of `<shop-header>`.
848
+
849
+ @example static tag — remove element entirely
850
+
851
+ ```ts
852
+ class GlobalStyles extends DC {
853
+ static tag = '';
854
+ }
855
+ defineCE('global-styles', GlobalStyles);
856
+ ```
857
+
858
+ The element self-destructs; only side effects (e.g., injected styles) remain.
859
+
860
+ ### `static assets: string[]`
861
+
862
+ Declares companion files for auto-loading by convention. Asset names are camelCase
863
+ and translated into file extensions: `'targetHtml'` → `.target.html`, `'json'` → `.json`.
864
+
865
+ The path is derived from the custom element tag segments, and the basename is the
866
+ last segment. For `<cart-container-checkout>`, assets load from `/cart/container/checkout.*`.
867
+
868
+ When assets finish loading, an `'assets'` event fires so that `oneAssets(ev)` can
869
+ process them. Everything ending in `Json` arrives parsed; all other files arrive as text.
870
+
871
+ **One-time global styles**: Assets named `'css'` and `'targetCss'` inject CSS into the
872
+ global document scope via `injectCSS(document, ...)`. Because these are idempotent
873
+ global side effects, they are processed only once — after the first instance loads them,
874
+ the entries are removed from both `static assets` and `static _assets`. Subsequent
875
+ instances skip loading and re-processing them entirely.
876
+
877
+ **CSS file roles**:
878
+
879
+ - `.css` — design tokens only (CSS custom-property presets). Injected into the document
880
+ scope once, like `targetCss`.
881
+ - `.target.css` — layout rules for the light DOM. Also document-scoped and one-time.
882
+ - `.shadow.css` — layout rules for the shadow DOM. Injected per instance into the
883
+ component's own shadow root, so each instance gets its own copy.
884
+
885
+ Every declared asset — CSS, HTML, JSON — is inlined into `static _assets` at build time by
886
+ the load-assets plugin, so a bundled build performs no fetches at all.
887
+
888
+ In a bundled build the plain `.css` files are additionally concatenated into a single
889
+ `bundle.css` by the bundling script. That file is a convenience listing of the available
890
+ variables: copy the ones you want to change into your own stylesheet and override them
891
+ there. It is not required at runtime, and it cannot drift from the inlined presets — both
892
+ are read from the same source files.
893
+
894
+ The runtime decides whether an asset still needs fetching with `!ctor._assets[key]`, so an
895
+ inlined entry must never be an empty string: that would trigger a re-fetch of a file that
896
+ does not exist in a bundled build.
897
+
898
+ @example static assets with autoload
899
+
900
+ ```ts
901
+ class CartCheckout extends DC {
902
+ static assets = ['targetHtml', 'targetCss', 'configJson'];
903
+
904
+ oneAssets(ev) {
905
+ const { configJson } = ev.detail.data;
906
+ console.log(configJson);
907
+ }
908
+ }
909
+ defineCE('cart-checkout', CartCheckout);
910
+ ```
911
+
912
+ `configJson` arrives already parsed into an object.
913
+
914
+ ### `static attributes?: object`
915
+
916
+ Sets HTML attributes on every instance automatically.
917
+
918
+ @example static attributes
919
+
920
+ ```ts
921
+ class ProductCard extends DC {
922
+ static attributes = { role: 'listitem' };
923
+ }
924
+ defineCE('product-card', ProductCard);
925
+ ```
926
+
927
+ Every `<product-card>` carries `role="listitem"`.
928
+
929
+ ### Combined usage
930
+
931
+ All three can be combined in one class:
932
+
933
+ @example All static properties together
934
+
935
+ ```ts
936
+ class ShopCatalog extends DC {
937
+ static tag = 'section';
938
+ static attributes = { role: 'list', 'aria-label': 'products' };
939
+ static assets = ['targetHtml', 'targetCss'];
940
+ }
941
+ defineCE('shop-catalog', ShopCatalog);
942
+ ```
943
+
944
+ Produces `<section role="list" aria-label="products">`.
945
+
946
+ ---
947
+
948
+ ## Event Handler Conventions
949
+
950
+ Methods whose names start with `on` or `one` are automatically wired as event listeners
951
+ on the target element. The prefix determines persistence:
952
+
953
+ - **`on<EventName>`** — persistent listener (fires every time)
954
+ - **`one<EventName>`** — one-time listener (fires once, then detaches)
955
+
956
+ ### Web Component Lifecycle Events
957
+
958
+ When a DC is registered via {@link defineCE}, the custom element dispatches these
959
+ internal events that can be caught with handler methods:
960
+
961
+ | Method | When it fires |
962
+ |--------|---------------|
963
+ | `onConnected()` | Element was inserted into the DOM (`connectedCallback`) |
964
+ | `onDisconnected()` | Element was removed from the DOM (`disconnectedCallback`) |
965
+ | `onAdopted()` | Element was moved to a new document (`adoptedCallback`) |
966
+ | `onAttributeChanged()` | An observed attribute changed (`attributeChangedCallback`) |
967
+ | `oneInit()` | Constructor finished; all synchronous setup complete (microtask) |
968
+ | `oneAssets()` | Constructor finished; all assets loaded and available; ev contains assets object |
969
+
970
+ @example Event handlers in action
971
+
972
+ ```ts
973
+ class MyElement extends DC {
974
+ onConnected() {
975
+ console.log('entered the DOM');
976
+ }
977
+
978
+ onDisconnected() {
979
+ console.log('left the DOM');
980
+ }
981
+
982
+ onClick() {
983
+ this.trigger('something', 'payload');
984
+ }
985
+
986
+ oneSomething(ev) {
987
+ console.log('first time only:', ev.detail.data);
988
+ }
989
+ }
990
+ defineCE('my-element', MyElement);
991
+ ```
992
+
993
+ ---
994
+
995
+ ## Construction Patterns
996
+
997
+ ### Template usage (declarative)
998
+
999
+ ```ts
1000
+ class MyElement extends DC {}
1001
+ defineCE('my-element', MyElement);
1002
+ ```
1003
+
1004
+ The registered element is then used in HTML as `<my-element></my-element>`.
1005
+
1006
+ ### Programmatic construction with data
1007
+
1008
+ When constructing programmatically via {@link getCE}, pass only the `data` payload —
1009
+ the target element is created automatically by the custom element constructor.
1010
+
1011
+ @example Programmatic construction
1012
+
1013
+ ```ts
1014
+ class MyElement extends DC {
1015
+ data = {};
1016
+
1017
+ constructor(target, data) {
1018
+ super(target);
1019
+ this.data = data;
1020
+ }
1021
+ }
1022
+ defineCE('my-element', MyElement);
1023
+
1024
+ const Ctor = getCE('my-element');
1025
+ document.body.append(new Ctor({ name: 'John' }));
1026
+ ```
1027
+
1028
+ ### Data from HTML attributes
1029
+
1030
+ @example Reading data from an attribute
1031
+
1032
+ ```ts
1033
+ class MyElement extends DC {
1034
+ data = {};
1035
+
1036
+ constructor(target) {
1037
+ super(target);
1038
+ this.data = JSON.parse(target.getAttribute('my-data'));
1039
+ }
1040
+ }
1041
+ defineCE('my-element', MyElement);
1042
+ ```
1043
+
1044
+ Used in HTML as `<my-element my-data='{"name":"John"}'></my-element>`.
1045
+
1046
+ ---
1047
+
1048
+ ## Plugin Extension Points
1049
+
1050
+ The prototype of `DC` (inherited from {@link McBase}) is extended at runtime by optional
1051
+ plugins. See the {@link McBase} documentation for details on {@link State.observePlugin} and
1052
+ {@link State.formValuePlugin}.
1053
+
1054
+ @template T - The concrete element type of the host element.
1055
+ @template EM - The component's custom event map (`event name → payload type`).
1056
+ Declaring it registers events on the type level: `trigger()` enforces the
1057
+ payload for registered names, and `on()`/`one()` handlers receive
1058
+ `CustomEvent<McDetail<Payload>>` with no annotation needed. Unregistered
1059
+ names keep the open `unknown`-payload behavior.
1060
+
1061
+ @example Typed event map
1062
+
1063
+ ```ts
1064
+ class Cart extends DC<HTMLFormElement, { CartUpdate: { count: number } }> {
1065
+ checkout() {
1066
+ this.trigger('CartUpdate', { count: 2 }, 'u');
1067
+ this.on('CartUpdate', (ev) => ev.detail.data.count);
1068
+ }
1069
+ }
1070
+ ```
1071
+
1072
+ `trigger()` checks the payload against the registered `CartUpdate` shape, and the `on()`
1073
+ handler receives a fully typed `ev`.
1074
+ @group Micro Components
1075
+ */
1076
+ var DC = class DC extends McBase {
1077
+ /**
1078
+ * Replaces the target element with a semantic HTML tag, or removes it entirely.
1079
+ * Set to `'header'` to swap `<my-element>` for `<header>`, or `''` to self-destruct.
1080
+ */
1081
+ static tag;
1082
+ /**
1083
+ * Result container for assets (e.g., `['targetHtml', 'json']`).
1084
+ * Asset names (keys) are camelCase and translated into file extensions: `'targetHtml'` → `.target.html`.
1085
+ */
1086
+ static _assets = {};
1087
+ /**
1088
+ * Declares companion files for auto-loading by convention (e.g., `['targetHtml', 'json']`).
1089
+ * Asset names are camelCase and translated into file extensions: `'targetHtml'` → `.target.html`.
1090
+ */
1091
+ static assets = [];
1092
+ /**
1093
+ * In-flight asset request, cached per class so that instances constructed while
1094
+ * the first fetch is still pending (e.g. in a loop) share a single request
1095
+ * instead of each triggering their own. Resolves to the freshly loaded assets.
1096
+ */
1097
+ static _assetsPromise;
1098
+ /**
1099
+ * Sets HTML attributes on every instance automatically.
1100
+ * Example: `{ role: 'listitem', 'aria-label': 'nav' }`.
1101
+ */
1102
+ static attributes = {};
1103
+ /**
1104
+ * Constructs a new DC instance and applies static configuration.
1105
+ *
1106
+ * The constructor performs these steps in order:
1107
+ * 1. Calls {@link McBase} to establish the target reference and auto-attach listeners.
1108
+ * 2. If `static tag` is set and differs from the current element, replaces the target
1109
+ * with a new built-in element (or removes it if `tag === ''`).
1110
+ * 3. If `static assets` has entries, initiates asynchronous loading, fires an `'assets'` event when complete handled by `oneAssets(ev)`.
1111
+ * 4. Applies any `static attributes` to the target element.
1112
+ *
1113
+ * @param target - The host DOM element this component operates on.
1114
+ */
1115
+ constructor(target) {
1116
+ super(target);
1117
+ const ctor = this.constructor;
1118
+ if (ctor === DC) return;
1119
+ const tagName = this.target.tagName.toLowerCase();
1120
+ if (ctor["tag"] !== void 0 && tagName !== ctor.tag && ctor.tag !== "") {
1121
+ const element = document.createElement(ctor.tag);
1122
+ element.classList.add(tagName);
1123
+ ctor._originalTag = tagName;
1124
+ DC.add(element, ctor.name, new ctor(element));
1125
+ delete ctor._originalTag;
1126
+ if (tagName.includes("-") && !this.target.isConnected) this.on("connected", () => this.target.replaceWith(element));
1127
+ else this.target.replaceWith(element);
1128
+ return;
1129
+ }
1130
+ const attributes = ctor.attributes;
1131
+ if (ctor.attributes) Object.keys(ctor.attributes).forEach((key) => {
1132
+ this.target.setAttribute(key, attributes[key]);
1133
+ });
1134
+ const that = this;
1135
+ const remainingAssets = ctor.assets.filter((key) => !ctor._assets[key]);
1136
+ if (Object.keys(ctor._assets).length) processAssets(this, ctor._assets);
1137
+ if (remainingAssets.length) {
1138
+ if (!ctor._assetsPromise) ctor._assetsPromise = loadAssets(ctor._originalTag || tagName, remainingAssets).then((res) => {
1139
+ const loadedAssets = {};
1140
+ remainingAssets.forEach((key, i) => {
1141
+ loadedAssets[key] = res[i];
1142
+ });
1143
+ ctor._assets = Object.assign({}, ctor._assets, loadedAssets);
1144
+ for (const onceKey of ["css", "targetCss"]) if (loadedAssets[onceKey] !== void 0) delete ctor._assets[onceKey];
1145
+ ctor.assets = ctor.assets.filter((key) => key !== "css" && key !== "targetCss");
1146
+ return loadedAssets;
1147
+ });
1148
+ ctor._assetsPromise.then((loadedAssets) => {
1149
+ processAssets(this, loadedAssets);
1150
+ that.trigger("assets", ctor._assets);
1151
+ });
1152
+ } else if ([...Object.keys(ctor._assets)].length) queueMicrotask(() => that.trigger("assets", ctor._assets));
1153
+ if (ctor.tag === "") {
1154
+ this.target.remove();
1155
+ return;
1156
+ }
1157
+ }
1158
+ /**
1159
+ Returns the loaded assets for this component instance.
1160
+
1161
+ Assets are loaded asynchronously when `static assets` is defined on the class.
1162
+ This method returns the resolved asset map keyed by filename, or `undefined`
1163
+ if assets have not yet been loaded.
1164
+
1165
+ @returns A record mapping asset keys to their content strings, or undefined.
1166
+ */
1167
+ getAssets() {
1168
+ return this.constructor._assets || {};
1169
+ }
1170
+ /**
1171
+ Static helper to attach a microcomponent instance to a DOM element.
1172
+
1173
+ Wrapper around the `add()` utility function, providing a class-level API
1174
+ for adding child microcomponents to a target node.
1175
+
1176
+ @template T - The concrete element type of the target; preserved in the return type.
1177
+ @template K - The literal registration key; becomes a known entry of the returned `_mc` registry.
1178
+ @template E - The type of the attached element; retrievable as `result._mc[key]`.
1179
+ @param target - The DOM element to which to attach the microcomponent.
1180
+ @param key - The property name/key under which to store the instance in `_mc`.
1181
+ @returns The target DOM element with the attached microcomponent.
1182
+ */
1183
+ static add(target, key, element = {}) {
1184
+ return add(target, key, element);
1185
+ }
1186
+ /**
1187
+ Static helper to remove a named microcomponent from a DOM element.
1188
+
1189
+ Wrapper around the `remove()` utility function, providing a class-level API
1190
+ for removing child microcomponents.
1191
+
1192
+ @template T - A plain or already-enhanced element type.
1193
+ @template K - The literal registration key; its entry is poisoned in the registry type.
1194
+ @param target - The DOM element from which to remove the microcomponent.
1195
+ @param key - The property name/key corresponding to the microcomponent to remove.
1196
+ */
1197
+ static remove(target, key) {
1198
+ remove(target, key);
1199
+ }
1200
+ /**
1201
+ Class-verified entry lookup: returns the component stored under `key` on the
1202
+ element's `_mc` record — but only if it is an instance of `Klass`.
1203
+
1204
+ This is the *sound* retrieval primitive: presence AND type identity are both
1205
+ proven at runtime (`instanceof`), so it needs no global `McRegistry`
1206
+ declaration and stays correct even when different elements use the same key
1207
+ name for different component types. Accepts any value (including
1208
+ `querySelector` results that may be null) — every failure mode returns
1209
+ `undefined`.
1210
+
1211
+ @template E - The component type, inferred from `Klass`.
1212
+ @param element - The value to look the entry up on; anything non-host yields undefined.
1213
+ @param key - The registry key name to look under.
1214
+ @param elementMcClass - The class the entry must be an instance of.
1215
+ @returns The verified instance, or undefined.
1216
+ @example
1217
+ ```ts
1218
+ const cart = DC.get(document.querySelector('form'), 'cart', Cart);
1219
+ cart?.addItem(item);
1220
+ ```
1221
+
1222
+ `cart` is `Cart | undefined` — presence and type identity are both proven by the
1223
+ `instanceof` check inside `get()`, with no global declaration involved.
1224
+ */
1225
+ static get(element, key, elementMcClass) {
1226
+ if (!isMcHost(element)) return void 0;
1227
+ const entry = element._mc[key];
1228
+ return entry instanceof elementMcClass ? entry : void 0;
1229
+ }
1230
+ /**
1231
+ Detaches an event listener from the DOM node.
1232
+
1233
+ This is an instance method wrapper for `off()`, using the internal `_target` DOM reference.
1234
+
1235
+ @param eventName - The name of the event (e.g., 'click', 'update').
1236
+ @param handler - The previously attached callback function or object to remove.
1237
+ */
1238
+ off(eventName, handler) {
1239
+ off(this.target, eventName, handler);
1240
+ }
1241
+ /**
1242
+ Attaches a persistent event listener to the DOM node.
1243
+
1244
+ This is an instance method wrapper for `on()`, using the internal `_target` DOM reference.
1245
+
1246
+ The handler receives a `CustomEvent<McDetail<Payload>>`. For event names
1247
+ registered in the component's event map `EM` the payload is resolved from the
1248
+ map — an unannotated arrow handler is fully typed. For unregistered names the
1249
+ payload defaults to `unknown` and can be pinned via the type argument
1250
+ (`on<Payload>('Name', handler)`) or the handler's own annotation.
1251
+
1252
+ @param eventName - The name of the event (e.g., 'click', 'update').
1253
+ @param handler - The callback function or object to invoke.
1254
+ @returns The attached handler reference, unchanged — usable directly with {@link off}.
1255
+ */
1256
+ on(eventName, handler) {
1257
+ return on(this.target, eventName, handler);
1258
+ }
1259
+ /**
1260
+ Attaches a one-time event listener to the DOM node.
1261
+
1262
+ This is an instance method wrapper for `one()`, using the internal `_target` DOM reference.
1263
+ Payload typing follows the same rules as {@link DC.on}.
1264
+
1265
+ @param eventName - The name of the event (e.g., 'click', 'update').
1266
+ @param handler - The callback function or object to invoke once.
1267
+ @returns The attached one-time handler reference, unchanged — usable directly with {@link off}.
1268
+ */
1269
+ one(eventName, handler) {
1270
+ return one(this.target, eventName, handler);
1271
+ }
1272
+ /**
1273
+ Triggers a custom event on the DOM node and optionally bubbles it.
1274
+
1275
+ This is an instance method wrapper for `trigger()`, using the internal `_target` DOM reference.
1276
+
1277
+ For event names registered in the component's event map `EM` the payload type
1278
+ is enforced; unregistered names accept any payload (typed via inference or an
1279
+ explicit `trigger<Payload>(...)` argument).
1280
+
1281
+ @param eventName - The name of the event (will be prefixed if needed).
1282
+ @param data - Additional data payload attached to `event.detail.data`.
1283
+ @param bubble - Bubbling direction ('l', 'u', 'd' or combinations).
1284
+ @param controller - Optional controller for managing bubbling behavior.
1285
+ */
1286
+ trigger(eventName, data = {}, bubble = "l", controller) {
1287
+ trigger(this.target, eventName, data, bubble, controller);
1288
+ }
1289
+ /**
1290
+ Returns an array of all ancestor microcomponents up the DOM tree.
1291
+
1292
+ Traverses upward from this element's target, collecting the `_mc` instances
1293
+ of ancestor elements marked with `data-mc`. The keyed form only collects
1294
+ hosts whose registry carries `key`, typed from the global {@link McRegistry}
1295
+ binding — non-optional, since presence is checked during the walk.
1296
+
1297
+ @template R - Known registry entries of the results; pass a record to assert
1298
+ a site-specific shape: `ancestors<{ cart: Cart }>()`. Defaults to none.
1299
+ @returns An array of ancestor microcomponent instances (empty if none found).
1300
+ */
1301
+ ancestors(key) {
1302
+ const result = [];
1303
+ let current = findMcAncestor(this.target, key);
1304
+ while (current) {
1305
+ result.push(current);
1306
+ current = findMcAncestor(current.target, key);
1307
+ }
1308
+ return result;
1309
+ }
1310
+ /**
1311
+ Returns the closest ancestor microcomponent or null if none found.
1312
+
1313
+ This method is equivalent to calling `ancestors()[0]`, but more concise.
1314
+ The keyed form walks up to the nearest host whose registry carries `key`,
1315
+ typed from the global {@link McRegistry} binding — non-optional, since
1316
+ presence is checked during the walk.
1317
+
1318
+ @template R - Known registry entries of the result; pass a record to assert
1319
+ a site-specific shape: `closest<{ cart: Cart }>()?.cart.addItem(...)`.
1320
+ Defaults to none.
1321
+ @returns The nearest matching ancestor's `_mc`, or null if not found.
1322
+ */
1323
+ closest(key) {
1324
+ return findMcAncestor(this.target, key);
1325
+ }
1326
+ /**
1327
+ Returns an array of direct child microcomponents.
1328
+
1329
+ Calls `getMcChildNodes()` internally to find immediate descendants only,
1330
+ excluding nested grandchildren and deeper levels. The keyed form filters to
1331
+ hosts whose registry carries `key`; see {@link DC.closest}.
1332
+
1333
+ @template R - Known registry entries of the results; see {@link DC.closest}.
1334
+ @returns An array of child microcomponent instances (empty if none found).
1335
+ */
1336
+ children(key) {
1337
+ const kids = getMcChildNodes(this.target);
1338
+ return key === void 0 ? kids : kids.filter((mc) => key in mc);
1339
+ }
1340
+ /**
1341
+ Returns an array of all descendant microcomponents recursively.
1342
+
1343
+ Uses a `querySelectorAll` query to collect every nested element marked with
1344
+ `data-mc`, returning their associated `_mc` instances. The keyed form
1345
+ filters to hosts whose registry carries `key`; see {@link DC.closest}.
1346
+
1347
+ @template R - Known registry entries of the results; see {@link DC.closest}.
1348
+ @returns An array of descendant microcomponent instances (empty if none found).
1349
+ */
1350
+ descendants(key) {
1351
+ return Array.from(this.target.querySelectorAll("[data-mc]")).filter((e) => e instanceof HTMLElement && "_mc" in e).map((e) => e._mc).filter((mc) => key === void 0 || key in mc);
1352
+ }
1353
+ };
1354
+ //#endregion
1355
+ //#region src/state/placeholders.ts
1356
+ /**
1357
+ @hidden
1358
+ DOM placeholder binding: `{name}` templates in attributes and text nodes,
1359
+ kept up to date from observable data.
1360
+
1361
+ Split from observables.ts so the pure observable machinery carries no DOM
1362
+ scanning/decoration code. The two modules reference each other only inside
1363
+ function bodies (`Placeholders` calls `observe(this)`; `bind()` calls
1364
+ {@link makePlaceholders}), never during module evaluation, so the circular
1365
+ import is benign under ESM live bindings.
1366
+ */
1367
+ /**
1368
+ Extracts placeholder names from an HTML element's attributes and text content.
1369
+
1370
+ Placeholders are strings enclosed in curly braces `{}`. This function scans
1371
+ all attributes and direct child text nodes of the target element for placeholders
1372
+ and returns them as an array of unique names (without braces).
1373
+
1374
+ @param target - The HTMLElement to scan for placeholders.
1375
+ @returns An array of placeholder names found within the element's attributes and text content.
1376
+ */
1377
+ function getPlaceholders(target) {
1378
+ const placeholders = /* @__PURE__ */ new Set(), regEx = /\{[^\{\}]*\}/g;
1379
+ (target.getAttributeNames ? target.getAttributeNames() : []).filter((attr) => target.getAttribute(attr)?.match(regEx)).forEach((attr) => {
1380
+ new Set(target.getAttribute(attr)?.match(regEx)).forEach((attrPlaceholder) => placeholders.add(attrPlaceholder.replace(/[\{\}]/g, "")));
1381
+ });
1382
+ [...target.childNodes].filter((childNode) => {
1383
+ return childNode.nodeType === 3 && (childNode.nodeValue || "").match(regEx);
1384
+ }).forEach((childNode) => {
1385
+ (childNode?.nodeValue || "").match(regEx).forEach((textNodePlaceholder) => placeholders.add(textNodePlaceholder.replace(/[\{\}]/g, "")));
1386
+ });
1387
+ return [...placeholders];
1388
+ }
1389
+ var inputTags = [
1390
+ "INPUT",
1391
+ "SELECT",
1392
+ "TEXTAREA"
1393
+ ];
1394
+ /**
1395
+ A class that manages placeholders within an HTML element and updates them dynamically.
1396
+
1397
+ This class extends `DC` (Data Controller) and processes the target element to identify
1398
+ placeholder patterns in attributes and text nodes. It then observes changes on its internal
1399
+ data object and updates the corresponding DOM locations when notified of changes.
1400
+ */
1401
+ var Placeholders = class extends DC {
1402
+ data = {};
1403
+ oldDisplay = "";
1404
+ /**
1405
+ Creates a new `Placeholders` instance for the given HTML element.
1406
+
1407
+ Initializes the internal data with empty strings for each placeholder
1408
+ found in the target and starts observing the data object. Attaches
1409
+ callbacks to update placeholders as needed.
1410
+
1411
+ @param target - The HTMLElement to process for placeholders.
1412
+ */
1413
+ constructor(target) {
1414
+ super(target);
1415
+ getPlaceholders(target).forEach((property) => this.data[property] = "");
1416
+ observe(this);
1417
+ this.#attachCallbacks();
1418
+ }
1419
+ #attachCallbacks() {
1420
+ const target = this.target;
1421
+ let hide = false;
1422
+ (target.getAttributeNames ? target.getAttributeNames() : []).filter((attr) => target.getAttribute(attr)?.match(/\{[^\{\}]*\}/g)).forEach((attr) => {
1423
+ const placeholders = new Set(target.getAttribute(attr)?.match(/\{[^\{\}]*\}/g));
1424
+ /* v8 ignore next -- attr passed the filter above, so its value is a non-null string */
1425
+ const attrTemplate = target.getAttribute(attr) ?? "";
1426
+ this.data.subscribe(((template) => (data) => {
1427
+ let result = template;
1428
+ placeholders.forEach((placeholder) => {
1429
+ result = result.replace(placeholder, String(data[placeholder.replace(/[\{\}]/g, "")]));
1430
+ });
1431
+ target.setAttribute(attr, result);
1432
+ })(attrTemplate));
1433
+ });
1434
+ [...target.childNodes].filter((childNode) => {
1435
+ return childNode.nodeType === 3 && (childNode.nodeValue || "").match(/\{[^\{\}]*\}/g);
1436
+ }).forEach((childNode) => {
1437
+ hide = true;
1438
+ /* v8 ignore next -- the filter above only admits text nodes with a non-empty
1439
+ nodeValue, so the ?? fallback is unreachable */
1440
+ const textTemplate = childNode.nodeValue ?? "";
1441
+ const placeholders = new Set(textTemplate.match(/\{[^\{\}]*\}/g));
1442
+ this.data.subscribe(((template) => (data) => {
1443
+ let result = template;
1444
+ placeholders.forEach((placeholder) => {
1445
+ result = result.replace(placeholder, String(data[placeholder.replace(/[\{\}]/g, "")]));
1446
+ });
1447
+ if (this.oldDisplay) target.style = this.oldDisplay;
1448
+ else target.removeAttribute("style");
1449
+ delete this.oldDisplay;
1450
+ childNode.nodeValue = result;
1451
+ })(textTemplate));
1452
+ this.oldDisplay = target.getAttribute("style") || "";
1453
+ if (hide && !inputTags.includes(target.tagName) && target.tagName !== "FIELDSET") target.style.display = "none";
1454
+ });
1455
+ }
1456
+ /**
1457
+ Handles a `data` custom event to update the internal placeholder data.
1458
+
1459
+ Extracts matching keys from the event's detail data and updates only those
1460
+ properties in the internal `data` object that were previously defined as placeholders.
1461
+
1462
+ @param ev - The CustomEvent containing new data to merge into the placeholders.
1463
+ */
1464
+ onData(ev) {
1465
+ const data = {};
1466
+ Object.keys(ev.detail.data).forEach((key) => {
1467
+ if (this.data.hasOwnProperty(key)) data[key] = ev.detail.data[key];
1468
+ });
1469
+ if (JSON.stringify(data) !== JSON.stringify(this.data)) Object.assign(this.data, data);
1470
+ }
1471
+ };
1472
+ /**
1473
+ Finds all elements within a given scope that contain placeholders.
1474
+
1475
+ @param target - The HTMLElement, DocumentFragment, or ShadowRoot to search.
1476
+ @returns An array of HTMLElements containing placeholder patterns.
1477
+ */
1478
+ function getPlaceholderElements(target) {
1479
+ return [target].concat([...target.querySelectorAll("*")]).filter((e) => !!getPlaceholders(e).length).filter((e) => e?.tagName !== "STYLE").reverse();
1480
+ }
1481
+ /**
1482
+ Applies placeholder support to an element and its descendants.
1483
+
1484
+ This function scans the provided target for elements containing placeholders
1485
+ and attaches a `Placeholders` controller instance to each one if not already present.
1486
+
1487
+ @param element - The HTMLElement, DocumentFragment, or ShadowRoot to process.
1488
+ */
1489
+ function makePlaceholders(element) {
1490
+ getPlaceholderElements(element).forEach((e) => {
1491
+ if (e?._mc?._placeholders) return;
1492
+ DC.add(e, "_placeholders", new Placeholders(e));
1493
+ });
1494
+ }
1495
+ //#endregion
1496
+ //#region src/state/observables.ts
1497
+ /**
1498
+ Reactive data binding via observables — object properties trigger callbacks and update
1499
+ DOM placeholders automatically when their values change. Supports primitives, nested objects,
1500
+ and deep-change detection with debounced notifications.
1501
+
1502
+ @module Observables
1503
+
1504
+ Two APIs are provided for different contexts:
1505
+
1506
+ - **`observe()`** — standalone function for general usage outside the MC ecosystem.
1507
+ Call it on any plain object to make its properties observable. You manage the resulting
1508
+ data object yourself (subscribe, bind, notify).
1509
+
1510
+ - **`observePlugin()`** — used inside MC custom elements (classes extending `DC`).
1511
+ It attaches `.notify()`, `.subscribe()`, and `.bind()` as chainable instance methods
1512
+ that implicitly create the observable wrapper for you. Just declare a plain data property
1513
+ on your component and call `this.subscribe('data', …)` — the observable is generated on demand.
1514
+
1515
+ > **Note:** `.bind()` only works with objects because their properties become the placeholder
1516
+ > names in HTML (e.g., `{name}`, `{count}`). Binding primitives to the DOM is silently ignored.
1517
+
1518
+ @example Plugin — inside an MC custom element (recommended within DC classes)
1519
+ ```ts
1520
+ import { DC, defineCE, observePlugin } from '@twobirds/microcomponents';
1521
+
1522
+ observePlugin(DC);
1523
+
1524
+ class Counter extends DC {
1525
+ data = { clicks: 1 };
1526
+
1527
+ oneAssets() {
1528
+ this
1529
+ .subscribe('data', (v) => console.log('data →', v))
1530
+ .bind('data', this.target);
1531
+ }
1532
+ }
1533
+
1534
+ defineCE('mc-counter', Counter);
1535
+ ```
1536
+
1537
+ @example Standalone — outside the MC ecosystem (plain objects, vanilla JS, etc.)
1538
+ ```ts
1539
+ import { observe } from '@twobirds/microcomponents';
1540
+
1541
+ const state = observe({ count: 0, label: 'hi' });
1542
+ state.count.subscribe((v) => console.log('count is now', v));
1543
+ state.count++;
1544
+ ```
1545
+
1546
+ Incrementing `state.count` triggers the subscribed callback.
1547
+
1548
+ @example Deep change detection on a nested property
1549
+ ```ts
1550
+ import { observe } from '@twobirds/microcomponents';
1551
+
1552
+ const state = observe({ data: { name: 'John', age: 30 } });
1553
+ state.data.subscribe((d) => console.log('data changed:', d));
1554
+ state.data.name = 'Jane';
1555
+ ```
1556
+
1557
+ Writing into a nested property triggers the callback with the updated object.
1558
+
1559
+ @example DOM binding — only observable properties that hold objects can be bound
1560
+ ```ts
1561
+ import { observe } from '@twobirds/microcomponents';
1562
+
1563
+ const state = observe({ user: { name: 'Alice', count: 0 } });
1564
+ state.user.bind(document.querySelector('.model'));
1565
+ ```
1566
+
1567
+ Inside the bound model, `<span>{name}</span>` and `<span>{count}</span>` update
1568
+ automatically on every change.
1569
+
1570
+ */
1571
+ /**
1572
+ @hidden
1573
+ Determines if a value is an observable object.
1574
+
1575
+ @param value - The value to check.
1576
+ @returns `true` if the value is a non-null object, otherwise `false`.
1577
+ */
1578
+ function isObservableObject(value) {
1579
+ return value != null && typeof value === "object";
1580
+ }
1581
+ var classRepo = {};
1582
+ /**
1583
+ @hidden
1584
+ Creates a new observable wrapper class for the given value's constructor.
1585
+
1586
+ Returns a subclass of the original constructor that implements the Observable interface,
1587
+ allowing observation and notification of changes. The new class is cached in `classRepo`.
1588
+
1589
+ @param val - The value whose constructor should be wrapped with observable behavior.
1590
+ @returns A new Observable class that wraps the original constructor.
1591
+ */
1592
+ function makeObservable(val) {
1593
+ const Constructor = val.constructor, ConstructorName = Constructor.name;
1594
+ const ObservableClass = class extends Constructor {
1595
+ #notify = true;
1596
+ #callbacks = [];
1597
+ constructor(valArg) {
1598
+ super(valArg);
1599
+ const ctor = this.constructor;
1600
+ ctor.callbacks = [];
1601
+ if (isObservableObject(valArg)) Object.getOwnPropertyNames(valArg).forEach((key) => {
1602
+ this[key] = valArg[key];
1603
+ });
1604
+ }
1605
+ get callbacks() {
1606
+ return this.#callbacks;
1607
+ }
1608
+ set callbacks(callbacks) {
1609
+ this.#callbacks = callbacks;
1610
+ }
1611
+ /**
1612
+ Coerces the observable to its underlying primitive value when used in
1613
+ arithmetic, string interpolation, or other contexts requiring a primitive.
1614
+
1615
+ This allows `observable + 1` or `` `${observable}` `` to work naturally
1616
+ while still exposing `.subscribe()`, `.notify()`, etc. as methods on the object.
1617
+
1618
+ @param hint - The coercion context: 'number', 'string', or 'default'.
1619
+ @returns The underlying primitive value coerced to the requested type.
1620
+
1621
+ @example
1622
+ ```ts
1623
+ const state = observe({ count: 42 });
1624
+ console.log(state.count + 10);
1625
+ console.log(`${state.count}`);
1626
+ state.count.subscribe((v) => console.log('changed to', v));
1627
+ ```
1628
+
1629
+ Arithmetic coerces with `hint === 'number'` (logs `52`), interpolation with
1630
+ `hint === 'string'` (logs `"42"`), and `.subscribe()` stays callable on the
1631
+ wrapper.
1632
+ */
1633
+ [Symbol.toPrimitive](hint) {
1634
+ const value = this.valueOf();
1635
+ if (hint === "string") return String(value);
1636
+ if (hint === "number") return Number(value);
1637
+ return value;
1638
+ }
1639
+ /**
1640
+ Registers a callback function to be invoked when the observable object is notified.
1641
+
1642
+ @param callback - The function to invoke on notification.
1643
+ @returns This instance for chaining.
1644
+
1645
+ @example
1646
+ ```ts
1647
+ const state = observe({ count: 0 });
1648
+ state.count.subscribe((v) => console.log('count changed to', v));
1649
+ state.count++;
1650
+ ```
1651
+
1652
+ The increment fires the callback, logging `count changed to 1`.
1653
+ */
1654
+ subscribe(callback) {
1655
+ this.#callbacks.push(callback);
1656
+ return this;
1657
+ }
1658
+ /**
1659
+ Removes a previously registered callback so it no longer fires on notify.
1660
+
1661
+ Detaching by the same function reference that was passed to `subscribe()` —
1662
+ unknown callbacks are a silent no-op. Long-lived subscribers should call
1663
+ this when they are done to avoid leaking callbacks.
1664
+
1665
+ @param callback - The exact callback reference to remove.
1666
+ @returns This instance for chaining.
1667
+
1668
+ @example
1669
+ ```ts
1670
+ const state = observe({ count: 0 });
1671
+ const log = (v) => console.log(v);
1672
+ state.count.subscribe(log);
1673
+ state.count.unsubscribe(log);
1674
+ ```
1675
+
1676
+ After `unsubscribe(log)`, the callback no longer fires on changes.
1677
+ */
1678
+ unsubscribe(callback) {
1679
+ this.#callbacks = this.#callbacks.filter((registered) => registered !== callback);
1680
+ return this;
1681
+ }
1682
+ /**
1683
+ Binds the observable to a DOM target, setting up placeholder updates and
1684
+ triggering initial callbacks.
1685
+
1686
+ Scans the target and its descendants for placeholders and registers handlers
1687
+ to update them with flattened data on notification. Only works in browser environments.
1688
+
1689
+ @param target - The HTMLElement, DocumentFragment, or ShadowRoot to bind.
1690
+ @returns This instance for chaining.
1691
+
1692
+ @example
1693
+ ```ts
1694
+ const state = observe({ user: { name: 'Alice', count: 0 } });
1695
+ state.user.bind(document.querySelector('.model'));
1696
+ ```
1697
+
1698
+ Only object-valued observables can be bound: inside the model, `{name}` and
1699
+ `{count}` placeholders update on every change.
1700
+ */
1701
+ bind(target) {
1702
+ if (!isBrowser()) return;
1703
+ if (isObservableObject(this.valueOf())) {
1704
+ makePlaceholders(target);
1705
+ const placeholders = [target, ...target.querySelectorAll("[data-mc]")].filter((e) => {
1706
+ return !!e?._mc?._placeholders;
1707
+ });
1708
+ this.#callbacks.push(function callback(data) {
1709
+ const flattenedData = flattenObject(data);
1710
+ placeholders.forEach((node) => {
1711
+ /* v8 ignore next */
1712
+ if (!node) return;
1713
+ trigger(node, "data", flattenedData);
1714
+ });
1715
+ });
1716
+ this.notify();
1717
+ } else console.warn("IGNORED - cannot bind a non-Object to the dom, IS:", typeof this.valueOf(), this);
1718
+ return this;
1719
+ }
1720
+ /**
1721
+ Notifies registered callbacks with the current observable data.
1722
+
1723
+ Clones the internal value (if it's an object and not an array) before passing
1724
+ to callbacks. Respects the internal `#notify` flag that can suppress notifications.
1725
+
1726
+ @param notify - Optional boolean override for the notification state.
1727
+ @returns This instance for chaining.
1728
+
1729
+ @example
1730
+ ```ts
1731
+ const state = observe({ count: 0 });
1732
+ state.count.subscribe((v) => console.log('notified:', v));
1733
+ state.count.notify();
1734
+ ```
1735
+
1736
+ The manual `notify()` call pushes the current value to subscribers, logging
1737
+ `notified: 0`.
1738
+ */
1739
+ notify(notify) {
1740
+ const data = isObservableObject(this.valueOf()) && this.valueOf() instanceof Array === false ? structuredClone(Object.assign({}, this)) : this.valueOf();
1741
+ if (notify !== void 0) this.#notify = notify;
1742
+ if (this.#notify) this.#callbacks.forEach((f) => {
1743
+ f(data);
1744
+ });
1745
+ return this;
1746
+ }
1747
+ };
1748
+ classRepo[ConstructorName] = ObservableClass;
1749
+ return ObservableClass;
1750
+ }
1751
+ /**
1752
+ Retrieves or creates an observable wrapper class for the given value.
1753
+
1754
+ @param val - The value whose constructor should be wrapped with observable behavior.
1755
+ @returns A class that wraps the original constructor and implements observable functionality.
1756
+ */
1757
+ function getConstructor(val) {
1758
+ return classRepo[val.constructor.name] || makeObservable(val);
1759
+ }
1760
+ /**
1761
+ @hidden
1762
+ Whether a value is already an observable wrapper — `subscribe` is reachable on its prototype chain.
1763
+ Used by {@link observe} to skip re-wrapping and to detect the "not yet observed" state on reassignment.
1764
+
1765
+ @example
1766
+ ```ts
1767
+ const state = observe({ count: 0 });
1768
+ console.log(isAlreadyObserved(state.count));
1769
+ console.log(isAlreadyObserved(42));
1770
+ ```
1771
+
1772
+ The wrapped property reports `true`, a plain primitive reports `false`.
1773
+ */
1774
+ function isAlreadyObserved(value) {
1775
+ return (typeof value === "object" || typeof value === "function") && value !== null && "subscribe" in value;
1776
+ }
1777
+ /**
1778
+ @hidden
1779
+ Makes a target object's properties observable by replacing them with wrapped values.
1780
+
1781
+ Wraps each property of `target` that is not already observable (and meets criteria)
1782
+ in an observable wrapper. Also sets up deep change detection for objects and
1783
+ debounced notifications when the data changes.
1784
+
1785
+ There are two sides to using it — pick per call site:
1786
+
1787
+ **Declarative (typed class fields).** Declare the field as `Observable<T>` up
1788
+ front, then let `observe(this, 'field')` install the live wrapper in the
1789
+ constructor. The declaration needs the double cast once (`0 as unknown as
1790
+ Observable<number>`): the field starts life as a plain value and only becomes
1791
+ the wrapper when `observe()` runs. In exchange, every later use is fully typed —
1792
+ arithmetic, `subscribe`, `bind` — with no casts anywhere else.
1793
+
1794
+ **Imperative (wrapping existing data).** Hand any object to `observe()` after
1795
+ the fact — no declarations, the return type is inferred: every property comes
1796
+ back as `Observable<PropertyType>`.
1797
+
1798
+ @param target - The object whose properties should be made observable.
1799
+ @param propertyName - Optional specific property name to make one property observable instead of all properties.
1800
+ @returns The original target object, now with observable properties.
1801
+
1802
+ @example Imperative usage — wrap an existing plain object:
1803
+ ```ts
1804
+ const state = observe({ count: 0, label: 'hi' });
1805
+ state.count.subscribe((v) => console.log('count is now', v));
1806
+ state.count++;
1807
+ ```
1808
+
1809
+ Incrementing `state.count` triggers the subscribed callback.
1810
+
1811
+ @example Declarative usage — typed class field with double cast:
1812
+ ```ts
1813
+ class Counter {
1814
+ clicks: Observable<number> = 0 as unknown as Observable<number>;
1815
+
1816
+ constructor() {
1817
+ observe(this, 'clicks');
1818
+ }
1819
+
1820
+ bump() {
1821
+ this.clicks++;
1822
+ }
1823
+ }
1824
+ ```
1825
+
1826
+ Plain arithmetic compiles because the declaration carries the observable type.
1827
+
1828
+ @example Schema-first usage — divergent read/write types via hand-declared interface:
1829
+ ```ts
1830
+ interface CounterState {
1831
+ get count(): Observable<number>;
1832
+ set count(v: number);
1833
+ }
1834
+
1835
+ const state = observe<CounterState>({ count: 0 });
1836
+ state.count.subscribe((v) => console.log(v));
1837
+ state.count = 5;
1838
+ ```
1839
+
1840
+ The seed object is validated against the schema, the subscription callback is fully
1841
+ typed, and plain assignment is legal because the declared setter type permits it.
1842
+ */
1843
+ function observe(target, propertyName) {
1844
+ const source = target;
1845
+ (propertyName ? [propertyName] : [...Object.getOwnPropertyNames(target)]).forEach((key) => {
1846
+ const current = source[key];
1847
+ if (Object.prototype.hasOwnProperty.call(target, key) && typeof current !== "function" && !isAlreadyObserved(current)) {
1848
+ if (key[0] === "_" || current === void 0) return;
1849
+ const wrappedVal = current;
1850
+ let o = new (getConstructor(wrappedVal))(wrappedVal);
1851
+ const debouncedNotify = function() {
1852
+ queueMicrotask(function() {
1853
+ o.notify();
1854
+ });
1855
+ };
1856
+ Object.defineProperty(target, key, {
1857
+ enumerable: true,
1858
+ get() {
1859
+ if (isObservableObject(o.valueOf())) {
1860
+ const snapshot = structuredClone(Object.assign({}, o));
1861
+ queueMicrotask(function checkChanges() {
1862
+ if (!deepEqual(structuredClone(Object.assign({}, o)), snapshot)) debouncedNotify();
1863
+ });
1864
+ }
1865
+ return o;
1866
+ },
1867
+ set(val) {
1868
+ if (typeof val === typeof o.valueOf()) if (isObservableObject(o.valueOf()) && o.valueOf() instanceof Array === false) {
1869
+ /* v8 ignore next */
1870
+ if (!isAlreadyObserved(o)) {
1871
+ /* v8 ignore next */
1872
+ o = new (getConstructor(val))(structuredClone(Object.assign({}, val)));
1873
+ /* v8 ignore next */
1874
+ copyGettersSetters(val, o);
1875
+ }
1876
+ Object.assign(o, val);
1877
+ o.notify();
1878
+ } else {
1879
+ const old = o.valueOf(), callbacks = o.callbacks;
1880
+ if (val !== old) {
1881
+ o = new (getConstructor(val))(val);
1882
+ o.callbacks = callbacks;
1883
+ debouncedNotify();
1884
+ }
1885
+ }
1886
+ else console.warn("IGNORED - cannot change observable types, IS:", typeof o.valueOf(), o, "- CANNOT BECOME:", typeof val);
1887
+ }
1888
+ });
1889
+ source[key] = wrappedVal;
1890
+ }
1891
+ });
1892
+ return target;
1893
+ }
1894
+ /**
1895
+ Attaches convenience methods `notify()`, `subscribe()`, and `bind()` to the prototype of a
1896
+ microcomponent class so that observable properties can be controlled directly on the instance.
1897
+
1898
+ All three methods return the component instance, so you can chain them fluently.
1899
+
1900
+ Call it once at module level before defining any component classes. The plugin is idempotent —
1901
+ subsequent calls are no-ops.
1902
+
1903
+ @param Class - A constructor function whose prototype chain includes {@link Core.McBase}.
1904
+
1905
+ @example
1906
+ ```ts
1907
+ class Counter extends DC {
1908
+ data = { clicks: 1 };
1909
+
1910
+ oneAssets() {
1911
+ this
1912
+ .subscribe('data', (v) => console.log('data →', v))
1913
+ .bind('data', this.target);
1914
+ }
1915
+ }
1916
+ ```
1917
+ */
1918
+ function observePlugin(Class) {
1919
+ const McBaseProto = Object.getPrototypeOf(Class.prototype);
1920
+ function makePropObservable(obj, propName) {
1921
+ const obs = obj[propName];
1922
+ if (!isAlreadyObserved(obs)) observe(obj, propName);
1923
+ }
1924
+ if (!Object.hasOwn(McBaseProto, "notify")) Object.assign(McBaseProto, {
1925
+ /**
1926
+ * Manually trigger a notification on an observable property.
1927
+ * Ensures the property is observed first if it hasn't been yet.
1928
+ * @param propName - The name of the observable property to notify.
1929
+ * @returns This instance for chaining.
1930
+
1931
+ @example
1932
+ ```ts
1933
+ this.notify('count');
1934
+ ```
1935
+ */
1936
+ notify: function(propName) {
1937
+ makePropObservable(this, propName);
1938
+ this[propName].notify();
1939
+ return this;
1940
+ },
1941
+ /**
1942
+ * Subscribe a callback to changes on an observable property.
1943
+ * Ensures the property is observed first if it hasn't been yet.
1944
+ * @param propName - The name of the observable property.
1945
+ * @param callback - Function invoked with the new value on every change.
1946
+ * @returns This instance for chaining.
1947
+
1948
+ @example
1949
+ ```ts
1950
+ this.subscribe('count', (v) => console.log('count →', v));
1951
+ ```
1952
+ */
1953
+ subscribe: function(propName, callback) {
1954
+ makePropObservable(this, propName);
1955
+ this[propName].subscribe(callback);
1956
+ return this;
1957
+ },
1958
+ /**
1959
+ * Bind an observable property to a DOM target so that `{placeholder}` tokens are updated live.
1960
+ * Ensures the property is observed first if it hasn't been yet.
1961
+ * @param propName - The name of the observable property.
1962
+ * @param target - HTMLElement, ShadowRoot, or DocumentFragment containing placeholders.
1963
+ * @returns This instance for chaining.
1964
+
1965
+ @example
1966
+ ```ts
1967
+ this.bind('data', this.target);
1968
+ ```
1969
+ */
1970
+ bind: function(propName, target) {
1971
+ makePropObservable(this, propName);
1972
+ this[propName].bind(target);
1973
+ return this;
1974
+ }
1975
+ });
1976
+ }
1977
+ //#endregion
1978
+ //#region src/state/formValues.ts
1
1979
  /**
2
1980
  Two-way binding between DOM form controls (`input`, `select`, `textarea`) and an observable
3
1981
  object property. Reads reflect live DOM values; writes update the controls synchronously.
@@ -7,14 +1985,14 @@ object property. Reads reflect live DOM values; writes update the controls synch
7
1985
  Two APIs are provided for different contexts:
8
1986
 
9
1987
  - **`formValues()`** — standalone function for general usage outside the MC ecosystem.
10
- Call it on any plain object to bind form controls to a new observable property. You manage
11
- subscriptions and bindings manually on the resulting data object.
1988
+ Call it on any plain object to bind form controls to a new observable property. You manage
1989
+ subscriptions and bindings manually on the resulting data object.
12
1990
 
13
1991
  - **`formValuePlugin()`** — used inside MC custom elements (classes extending `DC`).
14
- It attaches `.formValues()` as a chainable instance method that implicitly creates both the
15
- form-values binding and the underlying observable wrapper. Just call
16
- `this.formValues(this.target, 'formData')` and chain `.subscribe()` / `.bind()` — everything
17
- is set up for you automatically.
1992
+ It attaches `.formValues()` as a chainable instance method that implicitly creates both the
1993
+ form-values binding and the underlying observable wrapper. Just call
1994
+ `this.formValues(this.target, 'formData')` and chain `.subscribe()` / `.bind()` — everything
1995
+ is set up for you automatically.
18
1996
 
19
1997
  @example Plugin — inside an MC custom element (recommended within DC classes)
20
1998
  ```ts
@@ -23,14 +2001,14 @@ import { DC, defineCE, formValuePlugin } from '@twobirds/microcomponents';
23
2001
  formValuePlugin(DC);
24
2002
 
25
2003
  class CheckoutForm extends DC {
26
- static assets = ['targetHtml'];
2004
+ static assets = ['targetHtml'];
27
2005
 
28
- oneAssets() {
29
- this
30
- .formValues(this.target, 'formData')
31
- .subscribe('formData', (data) => console.log(data))
32
- .bind('formData', this.target);
33
- }
2006
+ oneAssets() {
2007
+ this
2008
+ .formValues(this.target, 'formData')
2009
+ .subscribe('formData', (data) => console.log(data))
2010
+ .bind('formData', this.target);
2011
+ }
34
2012
  }
35
2013
 
36
2014
  defineCE('checkout-form', CheckoutForm);
@@ -49,254 +2027,235 @@ state.formData.role = 'admin';
49
2027
  Reading `state.formData.username` reflects the live `<input name="username">` value;
50
2028
  assigning `state.formData.role` writes straight back to the `<select>` control.
51
2029
  */
52
- import { DC } from '../core/MC.js';
53
- import { copyGettersSetters, isBrowser } from '../utils/helpers.js';
54
- import { observe, observePlugin } from './observables.js';
55
2030
  observePlugin(DC);
56
2031
  /**
57
2032
  Extracts the lowercase tag name of an element (e.g., 'input', 'select', 'textarea').
58
2033
  @param inputElement - The HTML element to extract the tag name from.
59
2034
  @returns The lowercase tag name string.
60
2035
  */
61
- const getInputName = (inputElement) => {
62
- return inputElement.tagName.toLowerCase();
2036
+ var getInputName = (inputElement) => {
2037
+ return inputElement.tagName.toLowerCase();
63
2038
  };
64
2039
  /**
65
2040
  Abstract base class for form input value handlers.
66
2041
  Defines the interface that all handler classes must implement.
67
2042
  */
68
- class InputBase {
69
- /**
70
- Creates a new InputBase instance.
71
- @param e - The HTML element being handled (input, select, or textarea).
72
- */
73
- constructor(e) { }
74
- }
2043
+ var InputBase = class {
2044
+ /**
2045
+ Creates a new InputBase instance.
2046
+ @param e - The HTML element being handled (input, select, or textarea).
2047
+ */
2048
+ constructor(e) {}
2049
+ };
75
2050
  /**
76
2051
  Handler class specifically for radio button groups.
77
2052
  Provides synchronized access to the selected value in a group of related radio buttons.
78
2053
  */
79
- class RadioHandler extends InputBase {
80
- #e;
81
- /**
82
- Creates a new RadioHandler instance.
83
- @param e - The first radio button element in the group (used to determine name and form scope).
84
- */
85
- constructor(e) {
86
- super(e);
87
- this.#e = e;
88
- }
89
- /**
90
- Gets the currently selected value of the radio button group using FormData API.
91
- @returns The string value of the selected radio button, or null if none is selected.
92
- */
93
- get val() {
94
- if (!this.#e.form)
95
- return null;
96
- const ret = new FormData(this.#e.form).get(this.#e.name);
97
- return ret ?? null;
98
- }
99
- /**
100
- Sets the selected radio button by value.
101
- Finds and checks the first radio input matching the specified value within the same group.
102
- @param value - The value to match against radio inputs in this group.
103
- */
104
- set val(value) {
105
- /* v8 ignore next */
106
- const arr = [
107
- ...(this.#e.form?.querySelectorAll(`input[type="radio"][name="${this.#e.name}"]`) ?? []),
108
- ];
109
- arr.filter((e) => e.getAttribute('value') === value).shift().checked =
110
- true;
111
- }
112
- }
113
- /**
114
- * Handler class for checkbhox inputs.
115
- * Provides synchronized get/set access to the checked state of a single checkbox.
116
- */
117
- class CheckboxHandler extends InputBase {
118
- #e;
119
- /**
120
- Creates a new CheckboxHandler instance.
121
- @param e - The checkbox element to handle.
122
- */
123
- constructor(e) {
124
- super(e);
125
- this.#e = e;
126
- }
127
- /**
128
- Gets the checked state of the checkbox.
129
- @returns True if the checkbox is checked, false otherwise.
130
- */
131
- get val() {
132
- return this.#e.checked;
133
- }
134
- /**
135
- Sets the checked state of the checkbox.
136
- @param value - The boolean value to assign as the new checked state.
137
- */
138
- set val(value) {
139
- this.#e.checked = value;
140
- }
141
- }
2054
+ var RadioHandler = class extends InputBase {
2055
+ #e;
2056
+ /**
2057
+ Creates a new RadioHandler instance.
2058
+ @param e - The first radio button element in the group (used to determine name and form scope).
2059
+ */
2060
+ constructor(e) {
2061
+ super(e);
2062
+ this.#e = e;
2063
+ }
2064
+ /**
2065
+ Gets the currently selected value of the radio button group using FormData API.
2066
+ @returns The string value of the selected radio button, or null if none is selected.
2067
+ */
2068
+ get val() {
2069
+ if (!this.#e.form) return null;
2070
+ return new FormData(this.#e.form).get(this.#e.name) ?? null;
2071
+ }
2072
+ /**
2073
+ Sets the selected radio button by value.
2074
+ Finds and checks the first radio input matching the specified value within the same group.
2075
+ @param value - The value to match against radio inputs in this group.
2076
+ */
2077
+ set val(value) {
2078
+ /* v8 ignore next */
2079
+ const arr = [...this.#e.form?.querySelectorAll(`input[type="radio"][name="${this.#e.name}"]`) ?? []];
2080
+ arr.filter((e) => e.getAttribute("value") === value).shift().checked = true;
2081
+ }
2082
+ };
2083
+ /**
2084
+ * Handler class for checkbhox inputs.
2085
+ * Provides synchronized get/set access to the checked state of a single checkbox.
2086
+ */
2087
+ var CheckboxHandler = class extends InputBase {
2088
+ #e;
2089
+ /**
2090
+ Creates a new CheckboxHandler instance.
2091
+ @param e - The checkbox element to handle.
2092
+ */
2093
+ constructor(e) {
2094
+ super(e);
2095
+ this.#e = e;
2096
+ }
2097
+ /**
2098
+ Gets the checked state of the checkbox.
2099
+ @returns True if the checkbox is checked, false otherwise.
2100
+ */
2101
+ get val() {
2102
+ return this.#e.checked;
2103
+ }
2104
+ /**
2105
+ Sets the checked state of the checkbox.
2106
+ @param value - The boolean value to assign as the new checked state.
2107
+ */
2108
+ set val(value) {
2109
+ this.#e.checked = value;
2110
+ }
2111
+ };
142
2112
  /**
143
2113
  Handler class for standard single-line input fields (text, password, email, etc.).
144
2114
  Provides synchronized get/set access to the value of an input field.
145
2115
  */
146
- class InputHandler extends InputBase {
147
- #e;
148
- /**
149
- * Creates a new InputHandler instance.
150
- * @param e - The HTML input element to handle.
151
- */
152
- constructor(e) {
153
- super(e);
154
- this.#e = e;
155
- }
156
- /**
157
- * Gets the current value of the input field.
158
- * @returns The string content of the input element.
159
- */
160
- get val() {
161
- return this.#e.value;
162
- }
163
- /**
164
- * Sets the value of the input field.
165
- * @param value - The new string value for the input element.
166
- */
167
- set val(value) {
168
- this.#e.value = value;
169
- }
170
- }
2116
+ var InputHandler = class extends InputBase {
2117
+ #e;
2118
+ /**
2119
+ * Creates a new InputHandler instance.
2120
+ * @param e - The HTML input element to handle.
2121
+ */
2122
+ constructor(e) {
2123
+ super(e);
2124
+ this.#e = e;
2125
+ }
2126
+ /**
2127
+ * Gets the current value of the input field.
2128
+ * @returns The string content of the input element.
2129
+ */
2130
+ get val() {
2131
+ return this.#e.value;
2132
+ }
2133
+ /**
2134
+ * Sets the value of the input field.
2135
+ * @param value - The new string value for the input element.
2136
+ */
2137
+ set val(value) {
2138
+ this.#e.value = value;
2139
+ }
2140
+ };
171
2141
  /**
172
2142
  Handler class for select dropdown elements, supporting both single and multiple selection modes.
173
2143
  Provides synchronized get/set access to selected option values.
174
2144
  */
175
- class SelectHandler extends InputBase {
176
- #e;
177
- #multi = false;
178
- /**
179
- * Creates a new SelectHandler instance.
180
- * @param e - The select element to handle.
181
- */
182
- constructor(e) {
183
- super(e);
184
- this.#e = e;
185
- this.#multi = e.multiple;
186
- }
187
- /**
188
- * Gets the currently selected option value(s).
189
- * For single selection, returns a string. For multiple selection, returns an json.stringify()'ied array of strings.
190
- * @returns A string or JSON.stringify array of strings representing selected values.
191
- */
192
- get val() {
193
- const ret = [];
194
- // get all options
195
- [...this.#e.querySelectorAll('option')]
196
- .filter((o) => o.selected)
197
- .forEach((o) => {
198
- ret.push(o.value);
199
- });
200
- return this.#multi ? ret : ret[0];
201
- }
202
- /**
203
- * Sets the selected option(s) by value.
204
- * @param value - A string or array of strings representing values to select.
205
- */
206
- set val(value) {
207
- value = typeof value === 'string' ? [value] : value;
208
- // set all options /* v8 ignore next */
209
- [...this.#e.querySelectorAll('option')].forEach((o) => {
210
- if (value.indexOf(o.value) > -1) {
211
- o.selected = true;
212
- }
213
- else {
214
- o.selected = false;
215
- }
216
- });
217
- }
218
- }
2145
+ var SelectHandler = class extends InputBase {
2146
+ #e;
2147
+ #multi = false;
2148
+ /**
2149
+ * Creates a new SelectHandler instance.
2150
+ * @param e - The select element to handle.
2151
+ */
2152
+ constructor(e) {
2153
+ super(e);
2154
+ this.#e = e;
2155
+ this.#multi = e.multiple;
2156
+ }
2157
+ /**
2158
+ * Gets the currently selected option value(s).
2159
+ * For single selection, returns a string. For multiple selection, returns an json.stringify()'ied array of strings.
2160
+ * @returns A string or JSON.stringify array of strings representing selected values.
2161
+ */
2162
+ get val() {
2163
+ const ret = [];
2164
+ [...this.#e.querySelectorAll("option")].filter((o) => o.selected).forEach((o) => {
2165
+ ret.push(o.value);
2166
+ });
2167
+ return this.#multi ? ret : ret[0];
2168
+ }
2169
+ /**
2170
+ * Sets the selected option(s) by value.
2171
+ * @param value - A string or array of strings representing values to select.
2172
+ */
2173
+ set val(value) {
2174
+ value = typeof value === "string" ? [value] : value;
2175
+ [...this.#e.querySelectorAll("option")].forEach((o) => {
2176
+ if (value.indexOf(o.value) > -1) o.selected = true;
2177
+ else o.selected = false;
2178
+ });
2179
+ }
2180
+ };
219
2181
  /**
220
2182
  Handler class for textarea elements.
221
2183
  Provides synchronized get/set access to the multi-line text content of a textarea.
222
2184
  */
223
- class TextAreaHandler extends InputBase {
224
- #e;
225
- /**
226
- * Creates a new TextAreaHandler instance.
227
- * @param e - The textarea element to handle.
228
- */
229
- constructor(e) {
230
- super(e);
231
- this.#e = e;
232
- }
233
- /**
234
- * Gets the current value of the textarea (defaults to empty string if null/undefined).
235
- * @returns The string content of the textarea element.
236
- */
237
- get val() {
238
- return this.#e.value || '';
239
- }
240
- /**
241
- * Sets the value of the textarea.
242
- * @param value - The new string value for the textarea element.
243
- */
244
- set val(value) {
245
- this.#e.value = value;
246
- }
247
- }
2185
+ var TextAreaHandler = class extends InputBase {
2186
+ #e;
2187
+ /**
2188
+ * Creates a new TextAreaHandler instance.
2189
+ * @param e - The textarea element to handle.
2190
+ */
2191
+ constructor(e) {
2192
+ super(e);
2193
+ this.#e = e;
2194
+ }
2195
+ /**
2196
+ * Gets the current value of the textarea (defaults to empty string if null/undefined).
2197
+ * @returns The string content of the textarea element.
2198
+ */
2199
+ get val() {
2200
+ return this.#e.value || "";
2201
+ }
2202
+ /**
2203
+ * Sets the value of the textarea.
2204
+ * @param value - The new string value for the textarea element.
2205
+ */
2206
+ set val(value) {
2207
+ this.#e.value = value;
2208
+ }
2209
+ };
248
2210
  /**
249
2211
  Collects all form controls within a given DOM scope and creates handler objects
250
2212
  that provide synchronized get/set access to their values.
251
2213
 
252
2214
  @param e - Optional root DOM element or shadow root to search within; defaults to document if omitted.
253
2215
  @returns An object where each key is the name attribute of an input, select, or textarea,
254
- and each value is a proxy-like accessor object with `val` getter/setter methods.
255
- */
256
- const getInputHandlers = (e) => {
257
- const inputList = [...(e || document).querySelectorAll('input,select,textarea')], handlers = {};
258
- inputList.forEach((input) => {
259
- const name = input.getAttribute('name');
260
- if (name) {
261
- let handler = false;
262
- switch (getInputName(input)) {
263
- case 'input':
264
- switch (input.type) {
265
- case 'radio':
266
- handler = new RadioHandler(input);
267
- break;
268
- case 'checkbox':
269
- handler = new CheckboxHandler(input);
270
- break;
271
- default:
272
- handler = new InputHandler(input);
273
- }
274
- break;
275
- case 'select':
276
- handler = new SelectHandler(input);
277
- break;
278
- case 'textarea':
279
- handler = new TextAreaHandler(input);
280
- break;
281
- }
282
- /* v8 ignore next */
283
- if (handler) {
284
- const h = handler;
285
- DC.add(input, name, h);
286
- Object.defineProperty(handlers, name, {
287
- enumerable: true,
288
- configurable: true,
289
- get: () => h.val,
290
- set: (value) => {
291
- if (h.val !== value) {
292
- h.val = value;
293
- }
294
- },
295
- });
296
- }
297
- }
298
- });
299
- return handlers;
2216
+ and each value is a proxy-like accessor object with `val` getter/setter methods.
2217
+ */
2218
+ var getInputHandlers = (e) => {
2219
+ const inputList = [...(e || document).querySelectorAll("input,select,textarea")], handlers = {};
2220
+ inputList.forEach((input) => {
2221
+ const name = input.getAttribute("name");
2222
+ if (name) {
2223
+ let handler = false;
2224
+ switch (getInputName(input)) {
2225
+ case "input":
2226
+ switch (input.type) {
2227
+ case "radio":
2228
+ handler = new RadioHandler(input);
2229
+ break;
2230
+ case "checkbox":
2231
+ handler = new CheckboxHandler(input);
2232
+ break;
2233
+ default: handler = new InputHandler(input);
2234
+ }
2235
+ break;
2236
+ case "select":
2237
+ handler = new SelectHandler(input);
2238
+ break;
2239
+ case "textarea":
2240
+ handler = new TextAreaHandler(input);
2241
+ break;
2242
+ }
2243
+ /* v8 ignore next */
2244
+ if (handler) {
2245
+ const h = handler;
2246
+ DC.add(input, name, h);
2247
+ Object.defineProperty(handlers, name, {
2248
+ enumerable: true,
2249
+ configurable: true,
2250
+ get: () => h.val,
2251
+ set: (value) => {
2252
+ if (h.val !== value) h.val = value;
2253
+ }
2254
+ });
2255
+ }
2256
+ }
2257
+ });
2258
+ return handlers;
300
2259
  };
301
2260
  /**
302
2261
  @hidden
@@ -330,34 +2289,31 @@ assigning `state.formData.role` writes straight back to the `<select>` control.
330
2289
  import { DC, defineCE, formValues } from '@twobirds/microcomponents';
331
2290
 
332
2291
  class MyForm extends DC {
333
- static assets = ['targetHtml'];
2292
+ static assets = ['targetHtml'];
334
2293
 
335
- oneAssets() {
336
- formValues(this, 'formData', this.target);
337
- this.formData.subscribe((data) => console.log('form changed:', data));
338
- }
2294
+ oneAssets() {
2295
+ formValues(this, 'formData', this.target);
2296
+ this.formData.subscribe((data) => console.log('form changed:', data));
2297
+ }
339
2298
  }
340
2299
 
341
2300
  defineCE('my-form', MyForm);
342
2301
  ```
343
2302
  */
344
- export function formValues(targetObject, propertyName, dom) {
345
- /* v8 ignore next */
346
- if (!isBrowser())
347
- return; // DOM does not exist on the server side
348
- const handlers = getInputHandlers(dom);
349
- const source = targetObject;
350
- source[propertyName] = Object.assign({}, handlers);
351
- observe(targetObject, propertyName);
352
- // After observe(), the property getter returns the live observable wrapper.
353
- const observable = source[propertyName];
354
- copyGettersSetters(handlers, observable);
355
- //Object.seal(source[propertyName]); // object structure may not be changed from now on
356
- [...dom.querySelectorAll('input, textarea, select')].forEach((input) => {
357
- input.addEventListener('input', () => {
358
- observable.notify();
359
- });
360
- });
2303
+ function formValues(targetObject, propertyName, dom) {
2304
+ /* v8 ignore next */
2305
+ if (!isBrowser()) return;
2306
+ const handlers = getInputHandlers(dom);
2307
+ const source = targetObject;
2308
+ source[propertyName] = Object.assign({}, handlers);
2309
+ observe(targetObject, propertyName);
2310
+ const observable = source[propertyName];
2311
+ copyGettersSetters(handlers, observable);
2312
+ [...dom.querySelectorAll("input, textarea, select")].forEach((input) => {
2313
+ input.addEventListener("input", () => {
2314
+ observable.notify();
2315
+ });
2316
+ });
361
2317
  }
362
2318
  /**
363
2319
  Attaches a convenience method `formValues()` to the prototype of a microcomponent class so that
@@ -378,41 +2334,40 @@ import { DC, defineCE, formValuePlugin } from '@twobirds/microcomponents';
378
2334
  formValuePlugin(DC);
379
2335
 
380
2336
  class CheckoutForm extends DC {
381
- static assets = ['targetHtml'];
2337
+ static assets = ['targetHtml'];
382
2338
 
383
- oneAssets() {
384
- this
385
- .formValues(this.target, 'formData')
386
- .subscribe('formData', (data) => console.log(data))
387
- .bind('formData', this.target);
388
- }
2339
+ oneAssets() {
2340
+ this
2341
+ .formValues(this.target, 'formData')
2342
+ .subscribe('formData', (data) => console.log(data))
2343
+ .bind('formData', this.target);
2344
+ }
389
2345
  }
390
2346
 
391
2347
  defineCE('checkout-form', CheckoutForm);
392
2348
  ```
393
2349
  */
394
- export function formValuePlugin(Class) {
395
- const McBaseProto = Object.getPrototypeOf(Class.prototype);
396
- if (!Object.hasOwn(McBaseProto, 'formValues')) {
397
- Object.assign(McBaseProto, {
398
- /**
399
- * Bind all named form controls inside a DOM subtree to an observable property on this instance.
400
- * Ensures the property becomes observable and stays in sync with input changes.
401
- * @param target - HTMLElement or ShadowRoot containing the form controls.
402
- * @param propName - The name of the property that will hold the bound form data.
403
- * @returns This instance for chaining.
404
-
405
- @example
406
- ```ts
407
- this.formValues(this.target, 'formData');
408
- ```
409
-
410
- After this call, `this.formData.username` reflects the live `<input name="username">` value.
411
- */
412
- formValues: function (target, propName) {
413
- formValues(this, propName, target);
414
- return this; // chainable
415
- },
416
- });
417
- }
2350
+ function formValuePlugin(Class) {
2351
+ const McBaseProto = Object.getPrototypeOf(Class.prototype);
2352
+ if (!Object.hasOwn(McBaseProto, "formValues")) Object.assign(McBaseProto, {
2353
+ /**
2354
+ * Bind all named form controls inside a DOM subtree to an observable property on this instance.
2355
+ * Ensures the property becomes observable and stays in sync with input changes.
2356
+ * @param target - HTMLElement or ShadowRoot containing the form controls.
2357
+ * @param propName - The name of the property that will hold the bound form data.
2358
+ * @returns This instance for chaining.
2359
+
2360
+ @example
2361
+ ```ts
2362
+ this.formValues(this.target, 'formData');
2363
+ ```
2364
+
2365
+ After this call, `this.formData.username` reflects the live `<input name="username">` value.
2366
+ */
2367
+ formValues: function(target, propName) {
2368
+ formValues(this, propName, target);
2369
+ return this;
2370
+ } });
418
2371
  }
2372
+ //#endregion
2373
+ export { formValuePlugin, formValues };