@twobirds/microcomponents 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/dev.d.ts +3 -1
- package/dist/cli/dev.d.ts.map +1 -1
- package/dist/cli/dispatch.d.ts +2 -0
- package/dist/cli/dispatch.d.ts.map +1 -1
- package/dist/cli/index.js +110 -18
- package/dist/cli/preview.d.ts +3 -1
- package/dist/cli/preview.d.ts.map +1 -1
- package/dist/docs/cli.d.ts +1 -1
- package/dist/helpers.min.js +1 -0
- package/dist/mcp/api.json +28 -2
- package/dist/mcp/concepts/mc-types.md +15 -8
- package/dist/microcomponents.d.ts +1 -0
- package/dist/microcomponents.d.ts.map +1 -1
- package/dist/microcomponents.js +1 -1
- package/dist/microcomponents.min.js +1 -1
- package/dist/placeholders.min.js +1 -0
- package/dist/state/index.d.ts +2 -0
- package/dist/state/index.d.ts.map +1 -1
- package/dist/state/placeholders.js +1980 -0
- package/dist/utils/autoload.js +1451 -0
- package/dist/utils/events.d.ts +1 -1
- package/dist/utils/events.d.ts.map +1 -1
- package/dist/utils/helpers.js +693 -0
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/package.json +21 -5
|
@@ -0,0 +1,1451 @@
|
|
|
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
|
+
* Converts a PascalCase string to kebab-case.
|
|
276
|
+
* Example: 'MyComponentName' -> 'my-component-name'
|
|
277
|
+
* @param str - The PascalCase string to convert.
|
|
278
|
+
* @returns The converted kebab-case string.
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* ```ts
|
|
282
|
+
* console.log(pascalToKebab('MyElement'));
|
|
283
|
+
* ```
|
|
284
|
+
*/
|
|
285
|
+
function pascalToKebab(str) {
|
|
286
|
+
return str.replace(/[A-Z]/g, (m, i) => (i ? "-" : "") + m.toLowerCase());
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Injects a CSS string into the given scope (document or shadow root) as an adopted stylesheet.
|
|
290
|
+
* Enables css-in-js so that every custom element is self-contained and importable.
|
|
291
|
+
*
|
|
292
|
+
* @hidden
|
|
293
|
+
* @param target - The scope to inject styles into: `document` for global styles, or a `ShadowRoot` for encapsulated component internals.
|
|
294
|
+
* @param css - The CSS string to inject.
|
|
295
|
+
* @returns The created `CSSStyleSheet` instance that was adopted into the target scope.
|
|
296
|
+
*
|
|
297
|
+
* 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.
|
|
298
|
+
* When targeting **shadowRoot**: use `:host` for the custom element itself, standard selectors (`.inner`, `#id`) for internal structure, and `::slotted()` for projected light-DOM content.
|
|
299
|
+
*
|
|
300
|
+
* @example Inject global styles into the document:
|
|
301
|
+
* ```ts
|
|
302
|
+
* import { injectCSS } from '@twobirds/mc/utils/helpers';
|
|
303
|
+
* injectCSS(document, 'body { display: block; }');
|
|
304
|
+
* ```
|
|
305
|
+
*
|
|
306
|
+
* @example Inject global styles for a micro component into the document:
|
|
307
|
+
* ```ts
|
|
308
|
+
* import { injectCSS } from '@twobirds/mc/utils/helpers';
|
|
309
|
+
* injectCSS(document, 'my-microcomponent { display: block; }');
|
|
310
|
+
* ```
|
|
311
|
+
*
|
|
312
|
+
* @example Inject scoped styles into a shadow root:
|
|
313
|
+
* ```ts
|
|
314
|
+
* const shadow = element.attachShadow({ mode: 'open' });
|
|
315
|
+
* injectCSS(shadow, ':host { color: var(--text); } .inner { padding: 8px; }');
|
|
316
|
+
* ```
|
|
317
|
+
* Styles can also be added using a compound innerHTML statement: `shadow.innerHTML = \`<style>${style}</style>${template}\``
|
|
318
|
+
*/
|
|
319
|
+
var _injectedCSS = /* @__PURE__ */ new WeakMap();
|
|
320
|
+
function injectCSS(target, css) {
|
|
321
|
+
const injected = _injectedCSS.get(target) ?? /* @__PURE__ */ new Set();
|
|
322
|
+
if (injected.has(css)) return target.adoptedStyleSheets[0];
|
|
323
|
+
injected.add(css);
|
|
324
|
+
_injectedCSS.set(target, injected);
|
|
325
|
+
const sheet = new CSSStyleSheet();
|
|
326
|
+
sheet.replaceSync(css);
|
|
327
|
+
target.adoptedStyleSheets.push(sheet);
|
|
328
|
+
return sheet;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Processes a record of asset strings and applies them to the given target element.
|
|
332
|
+
* Supports injecting CSS into document or shadow root, and setting innerHTML for
|
|
333
|
+
* both target and shadow DOM. Automatically attaches a shadow root if any key starts
|
|
334
|
+
* with `'shadow'`.
|
|
335
|
+
*
|
|
336
|
+
* Recognized keys: `'css'`, `'targetCss'` (document-level styles), `'shadowCss'`
|
|
337
|
+
* (shadow-root styles), `'shadowHtml'` (shadow innerHTML), `'targetHtml'` (target innerHTML).
|
|
338
|
+
*
|
|
339
|
+
* @param instance - The micro component to apply assets onto.
|
|
340
|
+
* @param assets - A record mapping asset type keys to their string content.
|
|
341
|
+
*
|
|
342
|
+
* @example
|
|
343
|
+
* ```ts
|
|
344
|
+
* processAssets(this, {
|
|
345
|
+
* css: 'body { margin: 0; }',
|
|
346
|
+
* shadowCss: ':host { display: block; }',
|
|
347
|
+
* shadowHtml: '<slot></slot>'
|
|
348
|
+
* });
|
|
349
|
+
* ```
|
|
350
|
+
*/
|
|
351
|
+
function processAssets(instance, assets) {
|
|
352
|
+
const target = instance.target;
|
|
353
|
+
let shadow = target.shadowRoot;
|
|
354
|
+
if (!shadow && Object.keys(assets).some((key) => key.indexOf("shadow") === 0)) shadow = target.attachShadow({ mode: "open" });
|
|
355
|
+
Object.keys(assets).forEach((key) => {
|
|
356
|
+
switch (key) {
|
|
357
|
+
case "css":
|
|
358
|
+
injectCSS(document, assets[key]);
|
|
359
|
+
break;
|
|
360
|
+
case "targetCss":
|
|
361
|
+
injectCSS(document, assets[key]);
|
|
362
|
+
break;
|
|
363
|
+
case "shadowCss":
|
|
364
|
+
injectCSS(shadow, assets[key]);
|
|
365
|
+
break;
|
|
366
|
+
case "shadowHtml":
|
|
367
|
+
shadow.innerHTML = assets[key];
|
|
368
|
+
bindTemplateEvents(shadow, instance);
|
|
369
|
+
break;
|
|
370
|
+
case "targetHtml":
|
|
371
|
+
target.innerHTML = assets[key];
|
|
372
|
+
bindTemplateEvents(target, instance);
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Loads companion asset files (CSS, HTML) for a given component basename from the server.
|
|
379
|
+
*
|
|
380
|
+
* Each entry in `assets` encodes an optional variant and extension in camelCase, e.g. `'shadowCss'` → `{name}.shadow.css`,
|
|
381
|
+
* `'targetHtml'` → `{name}.target.html`. Plain entries like `'css'` or `'html'` resolve to
|
|
382
|
+
* `{name}.css` / `{name}.html`.
|
|
383
|
+
*
|
|
384
|
+
* In bundled mode the Vite plugin replaces this call with an inline array literal, so `.then()`
|
|
385
|
+
* fires synchronously — no async overhead.
|
|
386
|
+
*
|
|
387
|
+
* @hidden
|
|
388
|
+
* @param name - The component basename (e.g. `'shop-catalog'`).
|
|
389
|
+
* @param assets - Array of asset descriptors such as `'shadowCss'`, `'targetHtml'`, `'shadowHtml'`, `'css'`, `'html'`.
|
|
390
|
+
* @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`.
|
|
391
|
+
*
|
|
392
|
+
* @example
|
|
393
|
+
* ```ts
|
|
394
|
+
* export const MyComponent = loadAssets('my-component', ['shadowCss', 'shadowHtml']).then(([shadowCss, shadowHtml]) => {
|
|
395
|
+
* class _MyComponent extends DC { ... }
|
|
396
|
+
* defineCE('my-component', _MyComponent);
|
|
397
|
+
* return _MyComponent;
|
|
398
|
+
* });
|
|
399
|
+
* ```
|
|
400
|
+
*/
|
|
401
|
+
function loadAssets(name, assets) {
|
|
402
|
+
const parseAsset = (asset) => {
|
|
403
|
+
const m = asset.match(/^([a-z]+)([A-Z][a-z]*)$/);
|
|
404
|
+
if (m) return `./${name.replace(/-/g, "/")}.${m[1]}.${m[2].toLowerCase()}`;
|
|
405
|
+
return `./${name.replace(/-/g, "/")}.${asset.toLowerCase()}`;
|
|
406
|
+
};
|
|
407
|
+
return Promise.all(assets.map(async (asset) => {
|
|
408
|
+
const filename = parseAsset(asset);
|
|
409
|
+
try {
|
|
410
|
+
const resp = await fetch(filename);
|
|
411
|
+
if (!resp.ok) return `file not found: ${filename}`;
|
|
412
|
+
if (filename.endsWith("json")) {
|
|
413
|
+
const text = await resp.text();
|
|
414
|
+
try {
|
|
415
|
+
return JSON.parse(text);
|
|
416
|
+
} catch {
|
|
417
|
+
console.error(`could not JSON.parse() asset '${asset}' from ${filename}:\n`, text);
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return resp.text();
|
|
422
|
+
} catch {
|
|
423
|
+
return `file not found: ${filename}`;
|
|
424
|
+
}
|
|
425
|
+
}));
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Binds declarative event attributes in a template fragment to microcomponent triggers.
|
|
429
|
+
*
|
|
430
|
+
* Scans all elements under `root` for attributes whose names correspond to native DOM
|
|
431
|
+
* events (e.g. `click`, `submit`, `change`). The attribute value encodes the target and
|
|
432
|
+
* handler method in the form `target|methodName`:
|
|
433
|
+
*
|
|
434
|
+
* - `this|myHandler` — triggers locally on the component attached to this element.
|
|
435
|
+
* - `other-comp|submit` — resolves elements via `querySelectorAll('other-comp')` and
|
|
436
|
+
* triggers the event on each matched host's `_mc`.
|
|
437
|
+
*
|
|
438
|
+
* An optional sibling `payload` attribute supplies the data argument for `trigger()`.
|
|
439
|
+
* After binding, both the event attribute and the payload attribute are removed from the DOM.
|
|
440
|
+
*
|
|
441
|
+
* @param rootElement - The container element whose descendants should be scanned for bindings.
|
|
442
|
+
* @param instance - The instance to trigger events on.
|
|
443
|
+
*
|
|
444
|
+
* @example
|
|
445
|
+
* ```html
|
|
446
|
+
* <button click='this|onSubmit|{"action":"go"}'>Submit</button>
|
|
447
|
+
* <input change="|cart-form|refresh">
|
|
448
|
+
* ```
|
|
449
|
+
*/
|
|
450
|
+
function bindTemplateEvents(rootElement, instance) {
|
|
451
|
+
const allElements = [...rootElement.querySelectorAll("*")];
|
|
452
|
+
for (const el of allElements) {
|
|
453
|
+
if (!(el instanceof HTMLElement)) continue;
|
|
454
|
+
const attrs = [...el.attributes];
|
|
455
|
+
for (const attr of attrs) {
|
|
456
|
+
const lowerName = attr.name.toLowerCase();
|
|
457
|
+
if (!("on" + lowerName in el)) continue;
|
|
458
|
+
const parts = attr.value.trim().split("|");
|
|
459
|
+
if (parts.length < 2) continue;
|
|
460
|
+
const [selector, event, payload] = parts;
|
|
461
|
+
el.removeAttribute(attr.name);
|
|
462
|
+
let payloadData;
|
|
463
|
+
if (payload) try {
|
|
464
|
+
payloadData = JSON.parse(payload);
|
|
465
|
+
} catch {
|
|
466
|
+
payloadData = payload;
|
|
467
|
+
}
|
|
468
|
+
if (selector === "this" || selector === "") on(el, lowerName, () => instance.trigger(event, payloadData));
|
|
469
|
+
else on(el, lowerName, () => trigger(selector, event, payloadData));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region src/core/mcGuards.ts
|
|
475
|
+
function isMcHost(element, key) {
|
|
476
|
+
if (typeof HTMLElement === "undefined" || !(element instanceof HTMLElement)) return false;
|
|
477
|
+
if (!("_mc" in element)) return false;
|
|
478
|
+
if (key === void 0) return true;
|
|
479
|
+
const mc = element._mc;
|
|
480
|
+
if (typeof mc !== "object" || mc === null) return false;
|
|
481
|
+
return key in mc;
|
|
482
|
+
}
|
|
483
|
+
//#endregion
|
|
484
|
+
//#region src/core/MC.ts
|
|
485
|
+
function add(targetHTMLElement, key, element = {}) {
|
|
486
|
+
const node = targetHTMLElement;
|
|
487
|
+
if (!("_mc" in targetHTMLElement)) node._mc = new DC(targetHTMLElement);
|
|
488
|
+
const _mc = node._mc;
|
|
489
|
+
if (key.length) {
|
|
490
|
+
_mc[key] = element;
|
|
491
|
+
if (targetHTMLElement instanceof HTMLElement && !targetHTMLElement.getAttribute("data-mc")) targetHTMLElement.setAttribute("data-mc", "");
|
|
492
|
+
}
|
|
493
|
+
return node;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
Removes a named microcomponent from the internal `_mc` collection of a target DOM node.
|
|
497
|
+
|
|
498
|
+
This function deletes the specified key from the element's `_mc` hash object and, if the
|
|
499
|
+
collection becomes empty, removes the `data-mc` attribute from the DOM node.
|
|
500
|
+
|
|
501
|
+
The bare poisoned value (`el._mc.gone` without member access) is `never`,
|
|
502
|
+
which is assignable to anything — only member/method use of a removed entry is caught.
|
|
503
|
+
|
|
504
|
+
@template T - A plain or already-enhanced element type.
|
|
505
|
+
@template K - The literal registration key; its entry is poisoned in the registry type.
|
|
506
|
+
@param target - The DOM element whose microcomponent should be removed.
|
|
507
|
+
@param key - The property name/key corresponding to the microcomponent to remove.
|
|
508
|
+
*/
|
|
509
|
+
function remove(target, key) {
|
|
510
|
+
if (!key) return;
|
|
511
|
+
const _mc = target._mc;
|
|
512
|
+
if (!_mc) return;
|
|
513
|
+
if (_mc[key]) delete _mc[key];
|
|
514
|
+
if (!Object.keys(_mc).length && target instanceof HTMLElement && target.hasAttribute("data-mc")) target.removeAttribute("data-mc");
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
Runs the "Init" lifecycle event on a DOM microcomponent instance.
|
|
518
|
+
|
|
519
|
+
This function schedules the `trigger('Init')` call in a microtask, ensuring
|
|
520
|
+
that all synchronous initialization is complete before the lifecycle hook
|
|
521
|
+
executes. The {@link DC} constructor calls it once the declared assets are in
|
|
522
|
+
place — synchronously in a bundled build, after the fetch resolves in a
|
|
523
|
+
dev/autoload build — so `oneInit()` always sees the loaded assets. Only `DC`
|
|
524
|
+
instances have an Init lifecycle — the `DC` constructor calls this exclusively,
|
|
525
|
+
so the signature encodes that invariant instead of re-checking it at runtime.
|
|
526
|
+
|
|
527
|
+
@param element - The DOM microcomponent instance on which to trigger the Init event.
|
|
528
|
+
*/
|
|
529
|
+
function init(element) {
|
|
530
|
+
queueMicrotask(() => {
|
|
531
|
+
element.trigger("Init", null);
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
Attaches event listeners to DOM elements based on method naming conventions.
|
|
536
|
+
|
|
537
|
+
Scans the prototype of the provided element and attaches listeners for methods
|
|
538
|
+
prefixed with `on` or `one`, corresponding to either native HTML events (e.g.,
|
|
539
|
+
'onclick') or microcomponent-prefixed custom events (e.g., '_mcUpdate').
|
|
540
|
+
|
|
541
|
+
@param element - The instance whose prototype should be scanned for event handlers.
|
|
542
|
+
*/
|
|
543
|
+
function autoAttachListeners(element) {
|
|
544
|
+
const sourceTarget = element.target;
|
|
545
|
+
const prototype = Object.getPrototypeOf(element);
|
|
546
|
+
const sourceElement = element;
|
|
547
|
+
const definedEventHandlerNames = Object.getOwnPropertyNames(prototype).filter((key) => /^(on[A-Z]|one[A-Z])/.test(key) && typeof prototype[key] === "function");
|
|
548
|
+
for (const eventHandlerName of definedEventHandlerNames) {
|
|
549
|
+
const once = /^one/.test(eventHandlerName);
|
|
550
|
+
const eventName = eventHandlerName.replace(/^one?/, "");
|
|
551
|
+
const listener = (ev) => sourceElement[eventHandlerName](ev);
|
|
552
|
+
on(sourceTarget, eventName, listener, once);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
Retrieves immediate child microcomponents of a DOM node.
|
|
557
|
+
|
|
558
|
+
Queries the DOM for descendant elements marked with `data-mc` that are direct
|
|
559
|
+
children of the provided element and returns their associated `_mc` instances.
|
|
560
|
+
|
|
561
|
+
@param domNode - The DOM element whose child microcomponents to find.
|
|
562
|
+
@returns An array of child microcomponent instances.
|
|
563
|
+
*/
|
|
564
|
+
function getMcChildNodes(domNode) {
|
|
565
|
+
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);
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
Walks up the DOM from `from`, returning the `_mc` controller of the nearest
|
|
569
|
+
`data-mc` ancestor — restricted, when `key` is given, to hosts whose registry
|
|
570
|
+
actually carries that key. Hosts marked `data-mc` but not (yet) carrying an
|
|
571
|
+
`_mc` record (e.g. autoload pending) are skipped rather than returned.
|
|
572
|
+
|
|
573
|
+
@param from - The element whose ancestors to search (exclusive).
|
|
574
|
+
@param key - Optional registry key the ancestor's `_mc` must contain.
|
|
575
|
+
@returns The nearest matching controller, or null.
|
|
576
|
+
*/
|
|
577
|
+
function findMcAncestor(from, key) {
|
|
578
|
+
let el = from.parentElement?.closest("[data-mc]");
|
|
579
|
+
while (el instanceof HTMLElement) {
|
|
580
|
+
/* v8 ignore next */
|
|
581
|
+
if ("_mc" in el) {
|
|
582
|
+
const mc = el._mc;
|
|
583
|
+
if (key === void 0 || key in mc) return mc;
|
|
584
|
+
}
|
|
585
|
+
el = el.parentElement?.closest("[data-mc]");
|
|
586
|
+
}
|
|
587
|
+
return null;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
The base class for all microcomponents — shared root of both {@link MC} and {@link DC}.
|
|
591
|
+
|
|
592
|
+
Holds a `WeakRef` to the target (a DOM element for `DC`, or any plain object for `MC`)
|
|
593
|
+
to avoid circular references. It starts loading any `static assets` for `MC` and `DC`
|
|
594
|
+
alike (shared per class through `_assetsPromise`), read through the {@link McBase.assets}
|
|
595
|
+
getter. For `DC` subclasses it bootstraps one automatic behaviour:
|
|
596
|
+
|
|
597
|
+
1. **Event listener auto-attachment** — methods whose names start with `on` or `one`
|
|
598
|
+
(e.g. `onClick`, `oneInit`) are wired to the target element via {@link on} / {@link one}.
|
|
599
|
+
|
|
600
|
+
The **"Init" lifecycle event** and the DOM attach of auto-attached assets are dispatched
|
|
601
|
+
by the {@link DC} constructor — after the declared assets are in place — so that
|
|
602
|
+
`oneInit()` runs once the instance is fully constructed and its assets are loaded. Plain
|
|
603
|
+
`MC` instances fetch their assets server-side with no DOM attach and no `Init` lifecycle,
|
|
604
|
+
keeping server-side usage lightweight.
|
|
605
|
+
|
|
606
|
+
### Plugin extension points
|
|
607
|
+
|
|
608
|
+
The prototype of `McBase` is the attachment point for optional plugins that curry
|
|
609
|
+
additional instance methods onto every microcomponent. Two built-in plugins modify
|
|
610
|
+
this class at runtime:
|
|
611
|
+
|
|
612
|
+
- **{@link State.observePlugin}** — adds `notify()`, `subscribe()`, and `bind()` so that
|
|
613
|
+
observable properties can be controlled directly on the component instance with
|
|
614
|
+
fluent chaining. Call `observePlugin(DC)` once at module level to activate.
|
|
615
|
+
|
|
616
|
+
- **{@link State.formValuePlugin}** — adds `formValues()` for two-way binding between DOM
|
|
617
|
+
form controls and an observable property. Also pulls in all methods from
|
|
618
|
+
{@link State.observePlugin}, so you can chain `.subscribe()` and `.bind()` after
|
|
619
|
+
`.formValues()`. Call `formValuePlugin(DC)` once at module level to activate.
|
|
620
|
+
|
|
621
|
+
Both plugins are idempotent — calling them multiple times has no side effects. They
|
|
622
|
+
work by assigning methods onto `McBase.prototype` (reached via
|
|
623
|
+
`Object.getPrototypeOf(Class.prototype)`) and use TypeScript module augmentation
|
|
624
|
+
(`declare module`) so the added signatures appear in type-checking automatically.
|
|
625
|
+
|
|
626
|
+
@template TTarget - The concrete type of the wrapped target; preserved by the
|
|
627
|
+
{@link McBase.target} getter.
|
|
628
|
+
|
|
629
|
+
@example Extending with plugins at runtime
|
|
630
|
+
|
|
631
|
+
```ts
|
|
632
|
+
import { DC, observePlugin, formValuePlugin } from '@twobirds/microcomponents';
|
|
633
|
+
|
|
634
|
+
observePlugin(DC);
|
|
635
|
+
formValuePlugin(DC);
|
|
636
|
+
|
|
637
|
+
class MyForm extends DC {
|
|
638
|
+
data = { name: '' };
|
|
639
|
+
|
|
640
|
+
oneInit() {
|
|
641
|
+
this
|
|
642
|
+
.formValues(this.target, 'data')
|
|
643
|
+
.subscribe('data', (v) => console.log(v))
|
|
644
|
+
.bind('data', this.target);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
```
|
|
648
|
+
|
|
649
|
+
`observePlugin(DC)` adds `notify()`, `subscribe()`, `bind()` to `McBase.prototype`;
|
|
650
|
+
`formValuePlugin(DC)` adds `formValues()` and re-runs `observePlugin`. `oneInit()`
|
|
651
|
+
runs once after the constructor.
|
|
652
|
+
@group Micro Components
|
|
653
|
+
*/
|
|
654
|
+
var McBase = class {
|
|
655
|
+
#target;
|
|
656
|
+
/**
|
|
657
|
+
* Loaded asset cache, keyed by camelCase descriptor (`'targetHtml'` → `.target.html`).
|
|
658
|
+
* Inlined by the bundler in a bundled build, filled by `loadAssets()` in dev/autoload.
|
|
659
|
+
* Read through the {@link McBase.assets} getter.
|
|
660
|
+
*/
|
|
661
|
+
static _assets = {};
|
|
662
|
+
/**
|
|
663
|
+
* Declares companion files for auto-loading by convention (e.g. `['targetHtml', 'json']`).
|
|
664
|
+
* Asset names are camelCase and translated into file extensions: `'targetHtml'` → `.target.html`.
|
|
665
|
+
*/
|
|
666
|
+
static assets = [];
|
|
667
|
+
/**
|
|
668
|
+
* In-flight asset request, cached per class so that instances constructed while
|
|
669
|
+
* the first fetch is still pending (e.g. in a loop) share a single request
|
|
670
|
+
* instead of each triggering their own. Resolves to the freshly loaded assets.
|
|
671
|
+
*/
|
|
672
|
+
static _assetsPromise;
|
|
673
|
+
/**
|
|
674
|
+
The constructor for the base `McBase` class.
|
|
675
|
+
|
|
676
|
+
Initializes a weak reference to the target, auto-attaches listeners for `DC`
|
|
677
|
+
subclasses, and starts loading any `static assets` for `MC` and `DC` alike —
|
|
678
|
+
a server-side `MC` fetches them with no DOM, a `DC` gets them attached by its
|
|
679
|
+
own constructor. The load is shared per class through `_assetsPromise`.
|
|
680
|
+
|
|
681
|
+
@param target - The object or element this microcomponent represents.
|
|
682
|
+
*/
|
|
683
|
+
constructor(target) {
|
|
684
|
+
this.#target = new WeakRef(target || {});
|
|
685
|
+
const ctor = this.constructor;
|
|
686
|
+
if (this instanceof DC && this.constructor !== DC) autoAttachListeners(this);
|
|
687
|
+
const remaining = (ctor.assets ?? []).filter((key) => !ctor._assets[key]);
|
|
688
|
+
if (remaining.length && !ctor._assetsPromise) ctor._assetsPromise = loadAssets(ctor._originalTag || (this instanceof DC ? this.target.tagName.toLowerCase() : pascalToKebab(ctor.name)), remaining).then((res) => {
|
|
689
|
+
const loadedAssets = {};
|
|
690
|
+
remaining.forEach((key, i) => {
|
|
691
|
+
loadedAssets[key] = res[i];
|
|
692
|
+
});
|
|
693
|
+
ctor._assets = Object.assign({}, ctor._assets, loadedAssets);
|
|
694
|
+
return loadedAssets;
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
Returns the current target object (DOM node or other data) referenced by this microcomponent.
|
|
699
|
+
|
|
700
|
+
Uses a `WeakRef` internally to avoid circular references, and safely dereferences it here.
|
|
701
|
+
|
|
702
|
+
The dereference is asserted non-null: the controller is stored on its target
|
|
703
|
+
(`element._mc`), so any code that can reach the controller through the element is
|
|
704
|
+
holding the target alive. Only a controller retained independently after its element
|
|
705
|
+
was garbage-collected could observe a stale reference — do not cache controllers
|
|
706
|
+
detached from their elements.
|
|
707
|
+
|
|
708
|
+
@returns The target object.
|
|
709
|
+
*/
|
|
710
|
+
get target() {
|
|
711
|
+
return this.#target.deref();
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
The loaded assets for this component instance.
|
|
715
|
+
|
|
716
|
+
`static assets` are loaded before `oneInit()` fires on a `DC`, so this getter is
|
|
717
|
+
ready inside the `oneInit()` callback. A server-side `MC` fills it from `loadAssets()`;
|
|
718
|
+
await `MC._assetsPromise` before reading it. It returns the merged asset record keyed
|
|
719
|
+
by descriptor: `css` / `targetCss` / `shadowCss` / `shadowHtml` / `targetHtml` arrive
|
|
720
|
+
as strings, `*Json` entries arrive parsed, and a plain `html` template is returned as a
|
|
721
|
+
string for `parse()`. An empty object when no assets are declared.
|
|
722
|
+
|
|
723
|
+
@returns A record mapping asset keys to their content.
|
|
724
|
+
*/
|
|
725
|
+
get assets() {
|
|
726
|
+
return this.constructor._assets || {};
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
/**
|
|
730
|
+
@class DC
|
|
731
|
+
---
|
|
732
|
+
|
|
733
|
+
A DOM-centric microcomponent that operates on a specific HTML element.
|
|
734
|
+
|
|
735
|
+
Extends {@link McBase} and associates itself with an actual DOM node via the
|
|
736
|
+
`_target` reference. Provides methods for event handling, DOM traversal,
|
|
737
|
+
and interaction with sibling or ancestor microcomponents.
|
|
738
|
+
|
|
739
|
+
---
|
|
740
|
+
|
|
741
|
+
## Static Configuration Properties
|
|
742
|
+
|
|
743
|
+
DC classes support three static properties that configure custom elements
|
|
744
|
+
before any instance is constructed:
|
|
745
|
+
|
|
746
|
+
### `static tag?: string`
|
|
747
|
+
|
|
748
|
+
Replaces the default target element with a semantic HTML element, or removes it entirely.
|
|
749
|
+
|
|
750
|
+
- **Non-empty string** (e.g., `'header'`) — the original custom element is replaced
|
|
751
|
+
with the specified built-in element. The original tag name is added as a CSS class.
|
|
752
|
+
- **Empty string `''`** — the target element is removed from the DOM entirely.
|
|
753
|
+
Useful for components that only inject global styles or act as style containers.
|
|
754
|
+
|
|
755
|
+
@example static tag — replace with semantic element
|
|
756
|
+
|
|
757
|
+
```ts
|
|
758
|
+
class ShopHeader extends DC {
|
|
759
|
+
static tag = 'header';
|
|
760
|
+
}
|
|
761
|
+
defineCE('shop-header', ShopHeader);
|
|
762
|
+
```
|
|
763
|
+
|
|
764
|
+
Produces `<header class="shop-header">` instead of `<shop-header>`.
|
|
765
|
+
|
|
766
|
+
@example static tag — remove element entirely
|
|
767
|
+
|
|
768
|
+
```ts
|
|
769
|
+
class GlobalStyles extends DC {
|
|
770
|
+
static tag = '';
|
|
771
|
+
}
|
|
772
|
+
defineCE('global-styles', GlobalStyles);
|
|
773
|
+
```
|
|
774
|
+
|
|
775
|
+
The element self-destructs; only side effects (e.g., injected styles) remain.
|
|
776
|
+
|
|
777
|
+
### `static assets: string[]`
|
|
778
|
+
|
|
779
|
+
Declares companion files for auto-loading by convention. Asset names are camelCase
|
|
780
|
+
and translated into file extensions: `'targetHtml'` → `.target.html`, `'json'` → `.json`.
|
|
781
|
+
|
|
782
|
+
The path is derived from the custom element tag segments, and the basename is the
|
|
783
|
+
last segment. For `<cart-container-checkout>`, assets load from `/cart/container/checkout.*`.
|
|
784
|
+
|
|
785
|
+
**Assets are loaded before `oneInit()` fires.** The constructor applies them to the
|
|
786
|
+
target, then dispatches the `Init` lifecycle event — synchronously in a bundled build
|
|
787
|
+
(assets inlined), after the fetch resolves in a dev/autoload build. Inside `oneInit()`
|
|
788
|
+
the loaded assets are read through the {@link DC.assets} getter. Everything ending in
|
|
789
|
+
`Json` arrives parsed; all other files arrive as text.
|
|
790
|
+
|
|
791
|
+
**Auto-attached assets**: `.css`, `.target.css`, `.shadow.css`, `.target.html` and
|
|
792
|
+
`.shadow.html` are attached automatically by `processAssets()` — CSS is injected into
|
|
793
|
+
the document or shadow scope, HTML is set as `target.innerHTML` / `shadowRoot.innerHTML`,
|
|
794
|
+
and native event handlers in the template (`<button click="this|go">`) are wired.
|
|
795
|
+
|
|
796
|
+
**Plain `.html` is NOT auto-attached.** It is a template held in {@link DC.assets} for
|
|
797
|
+
components created programmatically with a `data` parameter: in `oneInit()` you compile
|
|
798
|
+
the target markup from template + data with `parse()`.
|
|
799
|
+
|
|
800
|
+
**One-time global styles**: Assets named `'css'` and `'targetCss'` inject CSS into the
|
|
801
|
+
global document scope via `injectCSS(document, ...)`. Because these are idempotent
|
|
802
|
+
global side effects, they are processed only once — after the first instance loads them,
|
|
803
|
+
the entries are dropped from `static _assets`. Subsequent instances skip re-processing
|
|
804
|
+
them entirely.
|
|
805
|
+
|
|
806
|
+
**CSS file roles**:
|
|
807
|
+
|
|
808
|
+
- `.css` — design tokens only (CSS custom-property presets). Injected into the document
|
|
809
|
+
scope once, like `targetCss`.
|
|
810
|
+
- `.target.css` — layout rules for the light DOM. Also document-scoped and one-time.
|
|
811
|
+
- `.shadow.css` — layout rules for the shadow DOM. Injected per instance into the
|
|
812
|
+
component's own shadow root, so each instance gets its own copy.
|
|
813
|
+
|
|
814
|
+
Every declared asset — CSS, HTML, JSON — is inlined into `static _assets` at build time by
|
|
815
|
+
the bundler, which replaces the `static assets` declaration with `static _assets` (the
|
|
816
|
+
`static assets` line is deleted from the bundled `.js`) and collapses each inlined
|
|
817
|
+
`.[shadow/target].css` / `.html` to a single line, so a bundled build performs no fetches.
|
|
818
|
+
|
|
819
|
+
In a bundled build the plain `.css` files are additionally concatenated into a single
|
|
820
|
+
`bundle.css` by the bundling script. That file is a convenience listing of the available
|
|
821
|
+
variables: copy the ones you want to change into your own stylesheet and override them
|
|
822
|
+
there. It is not required at runtime, and it cannot drift from the inlined presets — both
|
|
823
|
+
are read from the same source files.
|
|
824
|
+
|
|
825
|
+
The runtime decides whether an asset still needs fetching with `!ctor._assets[key]`, so an
|
|
826
|
+
inlined entry must never be an empty string: that would trigger a re-fetch of a file that
|
|
827
|
+
does not exist in a bundled build.
|
|
828
|
+
|
|
829
|
+
@example static assets read in oneInit
|
|
830
|
+
|
|
831
|
+
```ts
|
|
832
|
+
class CartCheckout extends DC {
|
|
833
|
+
static assets = ['targetHtml', 'targetCss', 'configJson'];
|
|
834
|
+
|
|
835
|
+
oneInit() {
|
|
836
|
+
const { configJson } = this.assets;
|
|
837
|
+
console.log(configJson);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
defineCE('cart-checkout', CartCheckout);
|
|
841
|
+
```
|
|
842
|
+
|
|
843
|
+
`configJson` arrives already parsed into an object.
|
|
844
|
+
|
|
845
|
+
@example plain .html template compiled with data
|
|
846
|
+
|
|
847
|
+
```ts
|
|
848
|
+
class UserCard extends DC {
|
|
849
|
+
static assets = ['html', 'targetCss'];
|
|
850
|
+
|
|
851
|
+
constructor(target: HTMLElement, data: { name: string }) {
|
|
852
|
+
super(target);
|
|
853
|
+
this.data = data;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
oneInit() {
|
|
857
|
+
this.target.innerHTML = parse(this.assets.html, this.data);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
defineCE('user-card', UserCard);
|
|
861
|
+
```
|
|
862
|
+
|
|
863
|
+
`user-card.html` holds the `{name}` template; `parse()` fills it from `data`.
|
|
864
|
+
|
|
865
|
+
### `static attributes?: object`
|
|
866
|
+
|
|
867
|
+
Sets HTML attributes on every instance automatically.
|
|
868
|
+
|
|
869
|
+
@example static attributes
|
|
870
|
+
|
|
871
|
+
```ts
|
|
872
|
+
class ProductCard extends DC {
|
|
873
|
+
static attributes = { role: 'listitem' };
|
|
874
|
+
}
|
|
875
|
+
defineCE('product-card', ProductCard);
|
|
876
|
+
```
|
|
877
|
+
|
|
878
|
+
Every `<product-card>` carries `role="listitem"`.
|
|
879
|
+
|
|
880
|
+
### Combined usage
|
|
881
|
+
|
|
882
|
+
All three can be combined in one class:
|
|
883
|
+
|
|
884
|
+
@example All static properties together
|
|
885
|
+
|
|
886
|
+
```ts
|
|
887
|
+
class ShopCatalog extends DC {
|
|
888
|
+
static tag = 'section';
|
|
889
|
+
static attributes = { role: 'list', 'aria-label': 'products' };
|
|
890
|
+
static assets = ['targetHtml', 'targetCss'];
|
|
891
|
+
}
|
|
892
|
+
defineCE('shop-catalog', ShopCatalog);
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
Produces `<section role="list" aria-label="products">`.
|
|
896
|
+
|
|
897
|
+
---
|
|
898
|
+
|
|
899
|
+
## Event Handler Conventions
|
|
900
|
+
|
|
901
|
+
Methods whose names start with `on` or `one` are automatically wired as event listeners
|
|
902
|
+
on the target element. The prefix determines persistence:
|
|
903
|
+
|
|
904
|
+
- **`on<EventName>`** — persistent listener (fires every time)
|
|
905
|
+
- **`one<EventName>`** — one-time listener (fires once, then detaches)
|
|
906
|
+
|
|
907
|
+
### Web Component Lifecycle Events
|
|
908
|
+
|
|
909
|
+
When a DC is registered via {@link defineCE}, the custom element dispatches these
|
|
910
|
+
internal events that can be caught with handler methods:
|
|
911
|
+
|
|
912
|
+
| Method | When it fires |
|
|
913
|
+
|--------|---------------|
|
|
914
|
+
| `onConnected()` | Element was inserted into the DOM (`connectedCallback`) |
|
|
915
|
+
| `onDisconnected()` | Element was removed from the DOM (`disconnectedCallback`) |
|
|
916
|
+
| `onAdopted()` | Element was moved to a new document (`adoptedCallback`) |
|
|
917
|
+
| `onAttributeChanged()` | An observed attribute changed (`attributeChangedCallback`) |
|
|
918
|
+
| `oneInit()` | Constructor finished and declared assets loaded; read them via `this.assets` |
|
|
919
|
+
|
|
920
|
+
@example Event handlers in action
|
|
921
|
+
|
|
922
|
+
```ts
|
|
923
|
+
class MyElement extends DC {
|
|
924
|
+
onConnected() {
|
|
925
|
+
console.log('entered the DOM');
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
onDisconnected() {
|
|
929
|
+
console.log('left the DOM');
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
onClick() {
|
|
933
|
+
this.trigger('something', 'payload');
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
oneSomething(ev) {
|
|
937
|
+
console.log('first time only:', ev.detail.data);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
defineCE('my-element', MyElement);
|
|
941
|
+
```
|
|
942
|
+
|
|
943
|
+
---
|
|
944
|
+
|
|
945
|
+
## Construction Patterns
|
|
946
|
+
|
|
947
|
+
### Template usage (declarative)
|
|
948
|
+
|
|
949
|
+
```ts
|
|
950
|
+
class MyElement extends DC {}
|
|
951
|
+
defineCE('my-element', MyElement);
|
|
952
|
+
```
|
|
953
|
+
|
|
954
|
+
The registered element is then used in HTML as `<my-element></my-element>`.
|
|
955
|
+
|
|
956
|
+
### Programmatic construction with data
|
|
957
|
+
|
|
958
|
+
When constructing programmatically via {@link getCE}, pass only the `data` payload —
|
|
959
|
+
the target element is created automatically by the custom element constructor.
|
|
960
|
+
|
|
961
|
+
@example Programmatic construction
|
|
962
|
+
|
|
963
|
+
```ts
|
|
964
|
+
class MyElement extends DC {
|
|
965
|
+
data = {};
|
|
966
|
+
|
|
967
|
+
constructor(target, data) {
|
|
968
|
+
super(target);
|
|
969
|
+
this.data = data;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
defineCE('my-element', MyElement);
|
|
973
|
+
|
|
974
|
+
const Ctor = getCE('my-element');
|
|
975
|
+
document.body.append(new Ctor({ name: 'John' }));
|
|
976
|
+
```
|
|
977
|
+
|
|
978
|
+
### Data from HTML attributes
|
|
979
|
+
|
|
980
|
+
@example Reading data from an attribute
|
|
981
|
+
|
|
982
|
+
```ts
|
|
983
|
+
class MyElement extends DC {
|
|
984
|
+
data = {};
|
|
985
|
+
|
|
986
|
+
constructor(target) {
|
|
987
|
+
super(target);
|
|
988
|
+
this.data = JSON.parse(target.getAttribute('my-data'));
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
defineCE('my-element', MyElement);
|
|
992
|
+
```
|
|
993
|
+
|
|
994
|
+
Used in HTML as `<my-element my-data='{"name":"John"}'></my-element>`.
|
|
995
|
+
|
|
996
|
+
---
|
|
997
|
+
|
|
998
|
+
## Plugin Extension Points
|
|
999
|
+
|
|
1000
|
+
The prototype of `DC` (inherited from {@link McBase}) is extended at runtime by optional
|
|
1001
|
+
plugins. See the {@link McBase} documentation for details on {@link State.observePlugin} and
|
|
1002
|
+
{@link State.formValuePlugin}.
|
|
1003
|
+
|
|
1004
|
+
@template T - The concrete element type of the host element.
|
|
1005
|
+
@template EM - The component's custom event map (`event name → payload type`).
|
|
1006
|
+
Declaring it registers events on the type level: `trigger()` enforces the
|
|
1007
|
+
payload for registered names, and `on()`/`one()` handlers receive
|
|
1008
|
+
`CustomEvent<McDetail<Payload>>` with no annotation needed. Unregistered
|
|
1009
|
+
names keep the open `unknown`-payload behavior.
|
|
1010
|
+
|
|
1011
|
+
@example Typed event map
|
|
1012
|
+
|
|
1013
|
+
```ts
|
|
1014
|
+
class Cart extends DC<HTMLFormElement, { CartUpdate: { count: number } }> {
|
|
1015
|
+
checkout() {
|
|
1016
|
+
this.trigger('CartUpdate', { count: 2 }, 'u');
|
|
1017
|
+
this.on('CartUpdate', (ev) => ev.detail.data.count);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
```
|
|
1021
|
+
|
|
1022
|
+
`trigger()` checks the payload against the registered `CartUpdate` shape, and the `on()`
|
|
1023
|
+
handler receives a fully typed `ev`.
|
|
1024
|
+
@group Micro Components
|
|
1025
|
+
*/
|
|
1026
|
+
var DC = class DC extends McBase {
|
|
1027
|
+
/**
|
|
1028
|
+
* Replaces the target element with a semantic HTML tag, or removes it entirely.
|
|
1029
|
+
* Set to `'header'` to swap `<my-element>` for `<header>`, or `''` to self-destruct.
|
|
1030
|
+
*/
|
|
1031
|
+
static tag;
|
|
1032
|
+
/**
|
|
1033
|
+
* Sets HTML attributes on every instance automatically.
|
|
1034
|
+
* Example: `{ role: 'listitem', 'aria-label': 'nav' }`.
|
|
1035
|
+
*/
|
|
1036
|
+
static attributes = {};
|
|
1037
|
+
/**
|
|
1038
|
+
* Constructs a new DC instance and applies static configuration.
|
|
1039
|
+
*
|
|
1040
|
+
* The constructor performs these steps in order:
|
|
1041
|
+
* 1. Calls {@link McBase} to establish the target reference and auto-attach listeners.
|
|
1042
|
+
* 2. If `static tag` is set and differs from the current element, replaces the target
|
|
1043
|
+
* with a new built-in element (or removes it if `tag === ''`).
|
|
1044
|
+
* 3. Applies any `static attributes` to the target element.
|
|
1045
|
+
* 4. Loads `static assets` (inlined in a bundled build, fetched in dev/autoload),
|
|
1046
|
+
* applies the auto-attached ones to the target, then fires the `Init` lifecycle
|
|
1047
|
+
* event — so `oneInit()` runs with the assets loaded and readable via {@link DC.assets}.
|
|
1048
|
+
*
|
|
1049
|
+
* @param target - The host DOM element this component operates on.
|
|
1050
|
+
*/
|
|
1051
|
+
constructor(target) {
|
|
1052
|
+
super(target);
|
|
1053
|
+
const ctor = this.constructor;
|
|
1054
|
+
if (ctor === DC) return;
|
|
1055
|
+
const tagName = this.target.tagName.toLowerCase();
|
|
1056
|
+
if (ctor["tag"] !== void 0 && tagName !== ctor.tag && ctor.tag !== "") {
|
|
1057
|
+
const element = document.createElement(ctor.tag);
|
|
1058
|
+
element.classList.add(tagName);
|
|
1059
|
+
ctor._originalTag = tagName;
|
|
1060
|
+
DC.add(element, ctor.name, new ctor(element));
|
|
1061
|
+
delete ctor._originalTag;
|
|
1062
|
+
if (tagName.includes("-") && !this.target.isConnected) this.on("connected", () => this.target.replaceWith(element));
|
|
1063
|
+
else this.target.replaceWith(element);
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
const attributes = ctor.attributes;
|
|
1067
|
+
if (ctor.attributes) Object.keys(ctor.attributes).forEach((key) => {
|
|
1068
|
+
this.target.setAttribute(key, attributes[key]);
|
|
1069
|
+
});
|
|
1070
|
+
if (Object.keys(ctor._assets).length) {
|
|
1071
|
+
processAssets(this, ctor._assets);
|
|
1072
|
+
for (const onceKey of ["css", "targetCss"]) delete ctor._assets[onceKey];
|
|
1073
|
+
ctor.assets = ctor.assets.filter((key) => key !== "css" && key !== "targetCss");
|
|
1074
|
+
}
|
|
1075
|
+
if (ctor._assetsPromise) ctor._assetsPromise.then((loadedAssets) => {
|
|
1076
|
+
processAssets(this, loadedAssets);
|
|
1077
|
+
for (const onceKey of ["css", "targetCss"]) delete ctor._assets[onceKey];
|
|
1078
|
+
ctor.assets = ctor.assets.filter((key) => key !== "css" && key !== "targetCss");
|
|
1079
|
+
init(this);
|
|
1080
|
+
});
|
|
1081
|
+
else init(this);
|
|
1082
|
+
if (ctor.tag === "") {
|
|
1083
|
+
this.target.remove();
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
/**
|
|
1088
|
+
Static helper to attach a microcomponent instance to a DOM element.
|
|
1089
|
+
|
|
1090
|
+
Wrapper around the `add()` utility function, providing a class-level API
|
|
1091
|
+
for adding child microcomponents to a target node.
|
|
1092
|
+
|
|
1093
|
+
@template T - The concrete element type of the target; preserved in the return type.
|
|
1094
|
+
@template K - The literal registration key; becomes a known entry of the returned `_mc` registry.
|
|
1095
|
+
@template E - The type of the attached element; retrievable as `result._mc[key]`.
|
|
1096
|
+
@param target - The DOM element to which to attach the microcomponent.
|
|
1097
|
+
@param key - The property name/key under which to store the instance in `_mc`.
|
|
1098
|
+
@returns The target DOM element with the attached microcomponent.
|
|
1099
|
+
*/
|
|
1100
|
+
static add(target, key, element = {}) {
|
|
1101
|
+
return add(target, key, element);
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
Static helper to remove a named microcomponent from a DOM element.
|
|
1105
|
+
|
|
1106
|
+
Wrapper around the `remove()` utility function, providing a class-level API
|
|
1107
|
+
for removing child microcomponents.
|
|
1108
|
+
|
|
1109
|
+
@template T - A plain or already-enhanced element type.
|
|
1110
|
+
@template K - The literal registration key; its entry is poisoned in the registry type.
|
|
1111
|
+
@param target - The DOM element from which to remove the microcomponent.
|
|
1112
|
+
@param key - The property name/key corresponding to the microcomponent to remove.
|
|
1113
|
+
*/
|
|
1114
|
+
static remove(target, key) {
|
|
1115
|
+
remove(target, key);
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
Class-verified entry lookup: returns the component stored under `key` on the
|
|
1119
|
+
element's `_mc` record — but only if it is an instance of `Klass`.
|
|
1120
|
+
|
|
1121
|
+
This is the *sound* retrieval primitive: presence AND type identity are both
|
|
1122
|
+
proven at runtime (`instanceof`), so it needs no global `McRegistry`
|
|
1123
|
+
declaration and stays correct even when different elements use the same key
|
|
1124
|
+
name for different component types. Accepts any value (including
|
|
1125
|
+
`querySelector` results that may be null) — every failure mode returns
|
|
1126
|
+
`undefined`.
|
|
1127
|
+
|
|
1128
|
+
@template E - The component type, inferred from `Klass`.
|
|
1129
|
+
@param element - The value to look the entry up on; anything non-host yields undefined.
|
|
1130
|
+
@param key - The registry key name to look under.
|
|
1131
|
+
@param elementMcClass - The class the entry must be an instance of.
|
|
1132
|
+
@returns The verified instance, or undefined.
|
|
1133
|
+
@example
|
|
1134
|
+
```ts
|
|
1135
|
+
const cart = DC.get(document.querySelector('form'), 'cart', Cart);
|
|
1136
|
+
cart?.addItem(item);
|
|
1137
|
+
```
|
|
1138
|
+
|
|
1139
|
+
`cart` is `Cart | undefined` — presence and type identity are both proven by the
|
|
1140
|
+
`instanceof` check inside `get()`, with no global declaration involved.
|
|
1141
|
+
*/
|
|
1142
|
+
static get(element, key, elementMcClass) {
|
|
1143
|
+
if (!isMcHost(element)) return void 0;
|
|
1144
|
+
const entry = element._mc[key];
|
|
1145
|
+
return entry instanceof elementMcClass ? entry : void 0;
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
Detaches an event listener from the DOM node.
|
|
1149
|
+
|
|
1150
|
+
This is an instance method wrapper for `off()`, using the internal `_target` DOM reference.
|
|
1151
|
+
|
|
1152
|
+
@param eventName - The name of the event (e.g., 'click', 'update').
|
|
1153
|
+
@param handler - The previously attached callback function or object to remove.
|
|
1154
|
+
*/
|
|
1155
|
+
off(eventName, handler) {
|
|
1156
|
+
off(this.target, eventName, handler);
|
|
1157
|
+
}
|
|
1158
|
+
/**
|
|
1159
|
+
Attaches a persistent event listener to the DOM node.
|
|
1160
|
+
|
|
1161
|
+
This is an instance method wrapper for `on()`, using the internal `_target` DOM reference.
|
|
1162
|
+
|
|
1163
|
+
The handler receives a `CustomEvent<McDetail<Payload>>`. For event names
|
|
1164
|
+
registered in the component's event map `EM` the payload is resolved from the
|
|
1165
|
+
map — an unannotated arrow handler is fully typed. For unregistered names the
|
|
1166
|
+
payload defaults to `unknown` and can be pinned via the type argument
|
|
1167
|
+
(`on<Payload>('Name', handler)`) or the handler's own annotation.
|
|
1168
|
+
|
|
1169
|
+
@param eventName - The name of the event (e.g., 'click', 'update').
|
|
1170
|
+
@param handler - The callback function or object to invoke.
|
|
1171
|
+
@returns The attached handler reference, unchanged — usable directly with {@link off}.
|
|
1172
|
+
*/
|
|
1173
|
+
on(eventName, handler) {
|
|
1174
|
+
return on(this.target, eventName, handler);
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
Attaches a one-time event listener to the DOM node.
|
|
1178
|
+
|
|
1179
|
+
This is an instance method wrapper for `one()`, using the internal `_target` DOM reference.
|
|
1180
|
+
Payload typing follows the same rules as {@link DC.on}.
|
|
1181
|
+
|
|
1182
|
+
@param eventName - The name of the event (e.g., 'click', 'update').
|
|
1183
|
+
@param handler - The callback function or object to invoke once.
|
|
1184
|
+
@returns The attached one-time handler reference, unchanged — usable directly with {@link off}.
|
|
1185
|
+
*/
|
|
1186
|
+
one(eventName, handler) {
|
|
1187
|
+
return one(this.target, eventName, handler);
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
Triggers a custom event on the DOM node and optionally bubbles it.
|
|
1191
|
+
|
|
1192
|
+
This is an instance method wrapper for `trigger()`, using the internal `_target` DOM reference.
|
|
1193
|
+
|
|
1194
|
+
For event names registered in the component's event map `EM` the payload type
|
|
1195
|
+
is enforced; unregistered names accept any payload (typed via inference or an
|
|
1196
|
+
explicit `trigger<Payload>(...)` argument).
|
|
1197
|
+
|
|
1198
|
+
@param eventName - The name of the event (will be prefixed if needed).
|
|
1199
|
+
@param data - Additional data payload attached to `event.detail.data`.
|
|
1200
|
+
@param bubble - Bubbling direction ('l', 'u', 'd' or combinations).
|
|
1201
|
+
@param controller - Optional controller for managing bubbling behavior.
|
|
1202
|
+
*/
|
|
1203
|
+
trigger(eventName, data = {}, bubble = "l", controller) {
|
|
1204
|
+
trigger(this.target, eventName, data, bubble, controller);
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
Returns an array of all ancestor microcomponents up the DOM tree.
|
|
1208
|
+
|
|
1209
|
+
Traverses upward from this element's target, collecting the `_mc` instances
|
|
1210
|
+
of ancestor elements marked with `data-mc`. The keyed form only collects
|
|
1211
|
+
hosts whose registry carries `key`, typed from the global {@link McRegistry}
|
|
1212
|
+
binding — non-optional, since presence is checked during the walk.
|
|
1213
|
+
|
|
1214
|
+
@template R - Known registry entries of the results; pass a record to assert
|
|
1215
|
+
a site-specific shape: `ancestors<{ cart: Cart }>()`. Defaults to none.
|
|
1216
|
+
@returns An array of ancestor microcomponent instances (empty if none found).
|
|
1217
|
+
*/
|
|
1218
|
+
ancestors(key) {
|
|
1219
|
+
const result = [];
|
|
1220
|
+
let current = findMcAncestor(this.target, key);
|
|
1221
|
+
while (current) {
|
|
1222
|
+
result.push(current);
|
|
1223
|
+
current = findMcAncestor(current.target, key);
|
|
1224
|
+
}
|
|
1225
|
+
return result;
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
Returns the closest ancestor microcomponent or null if none found.
|
|
1229
|
+
|
|
1230
|
+
This method is equivalent to calling `ancestors()[0]`, but more concise.
|
|
1231
|
+
The keyed form walks up to the nearest host whose registry carries `key`,
|
|
1232
|
+
typed from the global {@link McRegistry} binding — non-optional, since
|
|
1233
|
+
presence is checked during the walk.
|
|
1234
|
+
|
|
1235
|
+
@template R - Known registry entries of the result; pass a record to assert
|
|
1236
|
+
a site-specific shape: `closest<{ cart: Cart }>()?.cart.addItem(...)`.
|
|
1237
|
+
Defaults to none.
|
|
1238
|
+
@returns The nearest matching ancestor's `_mc`, or null if not found.
|
|
1239
|
+
*/
|
|
1240
|
+
closest(key) {
|
|
1241
|
+
return findMcAncestor(this.target, key);
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
Returns an array of direct child microcomponents.
|
|
1245
|
+
|
|
1246
|
+
Calls `getMcChildNodes()` internally to find immediate descendants only,
|
|
1247
|
+
excluding nested grandchildren and deeper levels. The keyed form filters to
|
|
1248
|
+
hosts whose registry carries `key`; see {@link DC.closest}.
|
|
1249
|
+
|
|
1250
|
+
@template R - Known registry entries of the results; see {@link DC.closest}.
|
|
1251
|
+
@returns An array of child microcomponent instances (empty if none found).
|
|
1252
|
+
*/
|
|
1253
|
+
children(key) {
|
|
1254
|
+
const kids = getMcChildNodes(this.target);
|
|
1255
|
+
return key === void 0 ? kids : kids.filter((mc) => key in mc);
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
Returns an array of all descendant microcomponents recursively.
|
|
1259
|
+
|
|
1260
|
+
Uses a `querySelectorAll` query to collect every nested element marked with
|
|
1261
|
+
`data-mc`, returning their associated `_mc` instances. The keyed form
|
|
1262
|
+
filters to hosts whose registry carries `key`; see {@link DC.closest}.
|
|
1263
|
+
|
|
1264
|
+
@template R - Known registry entries of the results; see {@link DC.closest}.
|
|
1265
|
+
@returns An array of descendant microcomponent instances (empty if none found).
|
|
1266
|
+
*/
|
|
1267
|
+
descendants(key) {
|
|
1268
|
+
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);
|
|
1269
|
+
}
|
|
1270
|
+
};
|
|
1271
|
+
//#endregion
|
|
1272
|
+
//#region src/utils/resolveComponentPath.ts
|
|
1273
|
+
/**
|
|
1274
|
+
@module Autoload
|
|
1275
|
+
|
|
1276
|
+
Single source of truth for the tag-to-file convention: hyphens become path
|
|
1277
|
+
separators, so `my-card` resolves to `./my/card.js`. Imported by the runtime
|
|
1278
|
+
autoload loader and by build-time tooling so both agree on the path without
|
|
1279
|
+
either duplicating the rule.
|
|
1280
|
+
*/
|
|
1281
|
+
/**
|
|
1282
|
+
The tag-to-path primitive: hyphens become path separators, with no prefix or
|
|
1283
|
+
extension. `my-card` → `my/card`. The single source of truth for the
|
|
1284
|
+
convention; {@link resolveComponentPath} and build-time tooling both derive
|
|
1285
|
+
their paths from it so neither duplicates the rule.
|
|
1286
|
+
|
|
1287
|
+
@example Returns `'my/card'` for `my-card`, and `'app/header'` for `app-header`.
|
|
1288
|
+
```ts
|
|
1289
|
+
tagPath('my-card');
|
|
1290
|
+
tagPath('app-header');
|
|
1291
|
+
```
|
|
1292
|
+
@hidden
|
|
1293
|
+
@group Autoload
|
|
1294
|
+
*/
|
|
1295
|
+
function tagPath(tag) {
|
|
1296
|
+
return tag.split("-").join("/");
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
Resolves a microcomponent tag name to its autoload module path by prefixing and
|
|
1300
|
+
suffixing {@link tagPath}: `my-card` → `./my/card.js`.
|
|
1301
|
+
|
|
1302
|
+
@example Returns `'./my/card.js'` for `my-card`, and `'./app/header.js'` for `app-header`.
|
|
1303
|
+
```ts
|
|
1304
|
+
resolveComponentPath('my-card');
|
|
1305
|
+
resolveComponentPath('app-header');
|
|
1306
|
+
```
|
|
1307
|
+
@group Autoload
|
|
1308
|
+
*/
|
|
1309
|
+
function resolveComponentPath(tag) {
|
|
1310
|
+
return "./" + tagPath(tag) + ".js";
|
|
1311
|
+
}
|
|
1312
|
+
//#endregion
|
|
1313
|
+
//#region src/utils/autoload.ts
|
|
1314
|
+
/**
|
|
1315
|
+
@module Autoload
|
|
1316
|
+
|
|
1317
|
+
The {@linkcode autoload} function enables automatic detection and instantiation of microcomponents in the DOM via a `MutationObserver`. When enabled, newly added elements with undefined custom tags or `data-mc` references will trigger dynamic script loading and component attachment.
|
|
1318
|
+
|
|
1319
|
+
Kept in its own module so the core controller classes in MC.ts stay free of
|
|
1320
|
+
side-effect-bearing DOM machinery (`MutationObserver`, script injection):
|
|
1321
|
+
importing `DC`/`MC` never pulls a DOM observer into the bundle unless
|
|
1322
|
+
{@link autoload} itself is imported.
|
|
1323
|
+
*/
|
|
1324
|
+
var loadingDCs = /* @__PURE__ */ new Set();
|
|
1325
|
+
/**
|
|
1326
|
+
Creates a closure that attaches DOM elements with the specified tag name to
|
|
1327
|
+
their corresponding microcomponent instances.
|
|
1328
|
+
|
|
1329
|
+
Used internally by `makeLoadScript()` when dynamically loading external
|
|
1330
|
+
custom element definitions. The returned function is invoked after the
|
|
1331
|
+
element definition becomes available, and performs:
|
|
1332
|
+
- Querying of all matching elements in the DOM
|
|
1333
|
+
- Instantiation of new `DC` instances
|
|
1334
|
+
- Attachment to each DOM node via `DC.add()`
|
|
1335
|
+
|
|
1336
|
+
@param element - The tag name (custom element name) of the microcomponent to instantiate.
|
|
1337
|
+
@returns A closure that performs the attachment logic when invoked.
|
|
1338
|
+
@group Autoload
|
|
1339
|
+
*/
|
|
1340
|
+
function attachDC(element) {
|
|
1341
|
+
return () => {
|
|
1342
|
+
const elements = Array.from(document.querySelectorAll(`[data-mc~="${element}"]`)).filter((e) => e instanceof HTMLElement);
|
|
1343
|
+
if (elements.length === 0) return;
|
|
1344
|
+
const customElementClass = customElements.get(element);
|
|
1345
|
+
for (let node of elements) {
|
|
1346
|
+
try {
|
|
1347
|
+
DC.add(node, customElementClass.name, new customElementClass(node));
|
|
1348
|
+
} catch (error) {
|
|
1349
|
+
/* v8 ignore start */
|
|
1350
|
+
if ("create" in customElementClass && typeof customElementClass.create === "function") {
|
|
1351
|
+
const customElement = customElementClass.create(node);
|
|
1352
|
+
if (!isMcHost(customElement)) throw `create() of Class ${customElementClass.name} did not return a McHost.`;
|
|
1353
|
+
customElement.setAttribute("data-mc", node.getAttribute("data-mc") ?? "");
|
|
1354
|
+
node.replaceWith(customElement);
|
|
1355
|
+
node = customElement;
|
|
1356
|
+
} else throw `Class ${customElementClass.name} doesn't have a callable constructor AND class doesn't have a static .create() method.`;
|
|
1357
|
+
}
|
|
1358
|
+
const newMcName = node.getAttribute("data-mc").split(" ").filter((name) => name !== element && name !== "").join(" ").trim();
|
|
1359
|
+
node.setAttribute("data-mc", newMcName);
|
|
1360
|
+
}
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
Dynamically loads and registers a custom element definition from an external JS file.
|
|
1365
|
+
|
|
1366
|
+
Constructs the script URL based on kebab-case naming (e.g., `my-element` → `./my/element.js`).
|
|
1367
|
+
Registers a handler to be executed once the element is defined, then appends the
|
|
1368
|
+
`<script>` tag to `<head>`. Handles both successful loading and error cases.
|
|
1369
|
+
|
|
1370
|
+
@param element - The custom element tag name (e.g., 'mc-button', 'my-widget').
|
|
1371
|
+
*/
|
|
1372
|
+
function makeLoadScript(element) {
|
|
1373
|
+
/* v8 ignore next */
|
|
1374
|
+
if (loadingDCs.has(element)) return;
|
|
1375
|
+
loadingDCs.add(element);
|
|
1376
|
+
const fileName = resolveComponentPath(element);
|
|
1377
|
+
const scriptElement = document.createElement("script");
|
|
1378
|
+
scriptElement.setAttribute("src", fileName);
|
|
1379
|
+
scriptElement.setAttribute("blocking", "render");
|
|
1380
|
+
scriptElement.async = true;
|
|
1381
|
+
scriptElement.setAttribute("type", "module");
|
|
1382
|
+
scriptElement.setAttribute("data-name", element);
|
|
1383
|
+
scriptElement.setAttribute("loading", "");
|
|
1384
|
+
customElements.whenDefined(element).then(attachDC(element));
|
|
1385
|
+
scriptElement.addEventListener("load", (ev) => {
|
|
1386
|
+
loadingDCs.delete(element);
|
|
1387
|
+
document.head.querySelector(`script[data-name="${element}"]`)?.remove();
|
|
1388
|
+
});
|
|
1389
|
+
scriptElement.addEventListener("error", (ev) => {
|
|
1390
|
+
console.error("could not load DC code from", fileName);
|
|
1391
|
+
loadingDCs.delete(element);
|
|
1392
|
+
});
|
|
1393
|
+
document.head.append(scriptElement);
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
Scans the DOM for undefined custom elements and pending microcomponents,
|
|
1397
|
+
then loads their definitions if necessary.
|
|
1398
|
+
|
|
1399
|
+
This is the main driver function for the autoload mechanism. It performs:
|
|
1400
|
+
1. Finds all undefined custom elements in the document
|
|
1401
|
+
2. Checks whether they are already loading or defined
|
|
1402
|
+
3. Calls `makeLoadScript()` to fetch missing definitions
|
|
1403
|
+
4. Invokes `attachDC()` where element definitions exist but haven't been attached yet
|
|
1404
|
+
|
|
1405
|
+
It is called both immediately after enabling autoload and on each DOM mutation.
|
|
1406
|
+
*/
|
|
1407
|
+
function loadUndefinedMCs() {
|
|
1408
|
+
[...document.querySelectorAll(":not(:defined)")].filter((element) => !!element && !customElements.get(element.tagName.toLowerCase()) && !loadingDCs.has(element.tagName.toLowerCase())).forEach((el) => {
|
|
1409
|
+
makeLoadScript(el.tagName.toLowerCase());
|
|
1410
|
+
});
|
|
1411
|
+
[...document.querySelectorAll("[data-mc]:not([data-mc=\"\"]")].filter((element) => !!element).forEach((el) => {
|
|
1412
|
+
(el.getAttribute("data-mc")?.split(" ").filter((name) => name !== ""))?.forEach((element) => {
|
|
1413
|
+
const isDefined = customElements.get(element);
|
|
1414
|
+
if (!loadingDCs.has(element) && !isDefined) makeLoadScript(element);
|
|
1415
|
+
else if (isDefined) attachDC(element)();
|
|
1416
|
+
});
|
|
1417
|
+
});
|
|
1418
|
+
}
|
|
1419
|
+
var observer = null;
|
|
1420
|
+
var armTimer = null;
|
|
1421
|
+
function autoload(enable = true) {
|
|
1422
|
+
if (!enable) {
|
|
1423
|
+
if (armTimer) {
|
|
1424
|
+
clearTimeout(armTimer);
|
|
1425
|
+
armTimer = null;
|
|
1426
|
+
}
|
|
1427
|
+
if (observer) {
|
|
1428
|
+
observer.disconnect();
|
|
1429
|
+
observer = null;
|
|
1430
|
+
}
|
|
1431
|
+
loadingDCs.clear();
|
|
1432
|
+
return false;
|
|
1433
|
+
}
|
|
1434
|
+
if (!!observer) return true;
|
|
1435
|
+
observer = new MutationObserver(loadUndefinedMCs);
|
|
1436
|
+
armTimer = setTimeout(() => {
|
|
1437
|
+
armTimer = null;
|
|
1438
|
+
/* v8 ignore next */
|
|
1439
|
+
if (!observer) return;
|
|
1440
|
+
observer.observe(document.body, {
|
|
1441
|
+
childList: true,
|
|
1442
|
+
subtree: true
|
|
1443
|
+
});
|
|
1444
|
+
loadUndefinedMCs();
|
|
1445
|
+
}, 5);
|
|
1446
|
+
window.autoload ??= autoload;
|
|
1447
|
+
return true;
|
|
1448
|
+
}
|
|
1449
|
+
autoload.state = loadingDCs;
|
|
1450
|
+
//#endregion
|
|
1451
|
+
export { autoload };
|