@twobirds/microcomponents 0.1.16 → 0.1.19

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/dist/MC.ts CHANGED
@@ -5,308 +5,307 @@ import { LooseObject } from './helpers.js';
5
5
  const isBrowser = new Function('try {return this===window;}catch(e){ return false;}');
6
6
 
7
7
  export interface HTMLMcElement extends HTMLElement {
8
- _mc: LooseObject;
8
+ _mc: LooseObject;
9
9
  }
10
10
 
11
11
  function isDOM(element: { [key: string]: any }) {
12
- return element && element instanceof HTMLElement;
12
+ return element && element instanceof HTMLElement;
13
13
  }
14
14
 
15
15
  // add a microcomponent to a target DOM node
16
16
  function add(target: HTMLElement, key: string, element: any = {}): HTMLMcElement {
17
- let node = target as HTMLMcElement;
17
+ let node = target as HTMLMcElement;
18
18
 
19
- // create the _mc property if necessary
20
- if (!node._mc) {
21
- node._mc = new (DC as any)(target);
22
- }
19
+ // create the _mc property if necessary
20
+ if (!node._mc) {
21
+ node._mc = new (DC as any)(target);
22
+ }
23
23
 
24
- const _mc = node._mc;
24
+ const _mc = node._mc;
25
25
 
26
- // add the element with the given property key to the _mc property
27
- if (key.length && !_mc[key]) {
28
- _mc[key] = element;
29
- // add attribute if HTMLElement
30
- if (target instanceof HTMLElement && !target.getAttribute('data-mc')) {
31
- target.setAttribute('data-mc', '');
32
- }
33
- }
26
+ // add the element with the given property key to the _mc property
27
+ if (key.length && !_mc[key]) {
28
+ _mc[key] = element;
29
+ // add attribute if HTMLElement
30
+ if (target instanceof HTMLElement && !target.getAttribute('data-mc')) {
31
+ target.setAttribute('data-mc', '');
32
+ }
33
+ }
34
34
 
35
- return node;
35
+ //console.warn('add() args: target, key, element', arguments, node);
36
+
37
+ return node;
36
38
  }
37
39
 
38
40
  // remove a micro component from the DOM
39
41
  function remove(target: HTMLElement, key: string) {
40
- if (!key) return; // silent fail
41
-
42
- const _mc = (target as unknown as HTMLMcElement)?._mc || {};
43
-
44
- // delete the property from the HTMLElement _mc collection
45
- if (_mc && _mc[key]) {
46
- delete _mc[key];
47
- }
48
-
49
- // remove the _mc attribute if the DOM collection is empty
50
- if (
51
- !Object.keys(_mc).length &&
52
- target instanceof HTMLElement &&
53
- target.hasAttribute('data-mc')
54
- ) {
55
- target.removeAttribute('data-mc');
56
- }
57
- return;
42
+ if (!key) return; // silent fail
43
+
44
+ const _mc = (target as unknown as HTMLMcElement)?._mc || {};
45
+
46
+ // delete the property from the HTMLElement _mc collection
47
+ if (_mc && _mc[key]) {
48
+ delete _mc[key];
49
+ }
50
+
51
+ // remove the _mc attribute if the DOM collection is empty
52
+ if (!Object.keys(_mc).length && target instanceof HTMLElement && target.hasAttribute('data-mc')) {
53
+ target.removeAttribute('data-mc');
54
+ }
55
+ return;
58
56
  }
59
57
 
60
58
  // run the "init" lifecycle event on the complete _mc structure
61
59
  function init(element: DC) {
62
- setTimeout(() => {
63
- if (element.constructor === DC) return;
64
- element.trigger('Init');
65
- }, 0);
60
+ //console.warn('init(): args', ...arguments);
61
+ setTimeout(() => {
62
+ if (element.constructor === DC) return;
63
+ element.trigger('Init');
64
+ }, 0);
66
65
  }
67
66
 
68
67
  // 'eventName' => '_mcEventName'
69
68
  function getMcEventName(eventName: string): string {
70
- return '_mc' + eventName[0].toUpperCase() + eventName.substring(1);
69
+ return '_mc' + eventName[0].toUpperCase() + eventName.substring(1);
71
70
  }
72
71
 
73
72
  /*
74
73
  CustomEvent Section...
75
74
  */
76
75
  function off(domNode: Node, eventName: string, handler: EventListenerOrEventListenerObject) {
77
- domNode.removeEventListener(getMcEventName(eventName), handler);
76
+ domNode.removeEventListener(getMcEventName(eventName), handler);
78
77
  }
79
78
 
80
79
  function on(
81
- domNode: Node,
82
- eventName: string,
83
- handler: EventListenerOrEventListenerObject,
84
- once: boolean = false
80
+ domNode: Node,
81
+ eventName: string,
82
+ handler: EventListenerOrEventListenerObject,
83
+ once: boolean = false
85
84
  ): EventListenerOrEventListenerObject {
86
- domNode.addEventListener(getMcEventName(eventName), handler, { capture: false, once });
87
- return handler;
85
+ domNode.addEventListener(getMcEventName(eventName), handler, { capture: false, once });
86
+ return handler;
88
87
  }
89
88
 
90
89
  function one(
91
- domNode: Node,
92
- eventName: string,
93
- handler: EventListenerOrEventListenerObject
90
+ domNode: Node,
91
+ eventName: string,
92
+ handler: EventListenerOrEventListenerObject
94
93
  ): EventListenerOrEventListenerObject {
95
- on(domNode, eventName, handler, true);
96
- return handler;
94
+ on(domNode, eventName, handler, true);
95
+ return handler;
97
96
  }
98
97
 
99
98
  class BubbleController {
100
- stopped = false;
101
- constructor() {}
102
- stop() {
103
- this.stopped = true;
104
- }
99
+ stopped = false;
100
+ constructor() {}
101
+ stop() {
102
+ this.stopped = true;
103
+ }
105
104
  }
106
105
 
107
106
  // create and dispatch custom event
108
107
  function trigger(
109
- domNode: HTMLElement,
110
- event: string,
111
- data: any = {},
112
- bubble: string = 'l', // direction of bubbling
113
- controller?: BubbleController
108
+ domNode: HTMLElement,
109
+ event: string,
110
+ data: any = {},
111
+ bubble: string = 'l', // direction of bubbling
112
+ controller?: BubbleController
114
113
  ) {
115
- const eventName = /^_mc/.test(event) ? event : getMcEventName(event),
116
- bubbleController = controller ? controller : new BubbleController(),
117
- ev = new CustomEvent(eventName, {
118
- detail: { data, control: bubbleController },
119
- bubbles: false,
120
- });
121
-
122
- if (bubbleController.stopped) return;
123
-
124
- if (/l/.test(bubble)) {
125
- domNode.dispatchEvent(ev);
126
- ev.stopImmediatePropagation();
127
-
128
- if (bubbleController.stopped) return;
129
- }
130
-
131
- // bubble if up or down is indicated
132
- if (/[ud]/.test(bubble)) {
133
- //console.log( 'bubble', bubble, domNode );
134
-
135
- // add missing 'l', or else no handlers are executed
136
- if (bubble.indexOf('l') === -1) {
137
- bubble += 'l';
138
- }
139
-
140
- setTimeout(() => {
141
- // bubble up towards document.body
142
- if (bubble.indexOf('u') > -1) {
143
- let parentMc: HTMLMcElement | null | undefined =
144
- domNode.parentElement?.closest('[data-mc]');
145
- if (parentMc) {
146
- parentMc?._mc.trigger(eventName, data, bubble, bubbleController);
147
- }
148
- }
149
-
150
- // bubble down towards DOM children
151
- if (bubble.indexOf('d') > -1) {
152
- let childNodes: DC[] | null = (domNode as HTMLMcElement)._mc.children();
153
- if (childNodes) {
154
- childNodes.forEach((_mc: DC) => _mc.trigger(eventName, data, bubble)); // event multiplex - dont carry bubble controller
155
- }
156
- }
157
- }, 0);
158
- }
114
+ //console.warn('trigger args', ...arguments);
115
+
116
+ const eventName = /^_mc/.test(event) ? event : getMcEventName(event),
117
+ bubbleController = controller ? controller : new BubbleController(),
118
+ ev = new CustomEvent(eventName, {
119
+ detail: { data, control: bubbleController },
120
+ bubbles: false,
121
+ });
122
+
123
+ if (bubbleController.stopped) return;
124
+
125
+ if (/l/.test(bubble)) {
126
+ domNode.dispatchEvent(ev);
127
+ ev.stopImmediatePropagation();
128
+
129
+ if (bubbleController.stopped) return;
130
+ }
131
+
132
+ // bubble if up or down is indicated
133
+ if (/[ud]/.test(bubble)) {
134
+ // add missing 'l', or else no handlers are executed
135
+ if (bubble.indexOf('l') === -1) {
136
+ bubble += 'l';
137
+ }
138
+
139
+ setTimeout(() => {
140
+ // bubble up towards document.body
141
+ if (bubble.indexOf('u') > -1) {
142
+ let parentMc: HTMLMcElement | null | undefined =
143
+ domNode.parentElement?.closest('[data-mc]');
144
+ if (parentMc) {
145
+ parentMc?._mc.trigger(eventName, data, bubble, bubbleController);
146
+ }
147
+ }
148
+
149
+ // bubble down towards DOM children
150
+ if (bubble.indexOf('d') > -1) {
151
+ let childNodes: DC[] | null = (domNode as HTMLMcElement)._mc.children();
152
+ if (childNodes) {
153
+ childNodes.forEach((_mc: DC) => _mc.trigger(eventName, data, bubble)); // event multiplex - dont carry bubble controller
154
+ }
155
+ }
156
+ }, 0);
157
+ }
159
158
  }
160
159
 
161
160
  function autoAttachListeners(element: MC | DC) {
162
- if (!isBrowser() || element.constructor === DC) return;
163
-
164
- const target = element.target;
165
-
166
- if (target instanceof HTMLElement) {
167
- let that: LooseObject = element;
168
- Object.getOwnPropertyNames(that.constructor.prototype)
169
- .filter(
170
- (key) =>
171
- /^(on[A-Z]|one[A-Z])/.test(key) &&
172
- typeof that.constructor.prototype[key] === 'function'
173
- )
174
- .forEach((key) => {
175
- let once = /^one/.test(key),
176
- withoutOnOne = key.replace(/^on[e]{0,1}/, ''), // preserves upper/lowercase for non-native events
177
- nativeEventName = withoutOnOne.toLowerCase(); // lowercase for native event names
178
-
179
- if ('on' + nativeEventName in target) {
180
- // it is a native HTML event
181
- let listener = (ev: Event) => {
182
- that[key](ev);
183
- };
184
- // console.log( 'AAL: attach native event listener', nativeEventName, 'to', target );
185
- target.addEventListener(nativeEventName, listener);
186
- } else {
187
- // it is a customEvent
188
- // console.log( 'AAL: attach custom event listener', '_mc' + withoutOnOne , 'to key', key, 'in', element );
189
- let listener = (ev: CustomEvent) => {
190
- that[key](ev);
191
- };
192
- on(target, withoutOnOne, listener as EventListenerOrEventListenerObject, once);
193
- }
194
- });
195
- }
161
+ if (!isBrowser() || element.constructor === DC) return;
162
+
163
+ const target = element.target;
164
+
165
+ if (target instanceof HTMLElement) {
166
+ let that: LooseObject = element;
167
+ Object.getOwnPropertyNames(that.constructor.prototype)
168
+ .filter(
169
+ (key) =>
170
+ /^(on[A-Z]|one[A-Z])/.test(key) && typeof that.constructor.prototype[key] === 'function'
171
+ )
172
+ .forEach((key) => {
173
+ let once = /^one/.test(key),
174
+ withoutOnOne = key.replace(/^on[e]{0,1}/, ''), // preserves upper/lowercase for non-native events
175
+ nativeEventName = withoutOnOne.toLowerCase(); // lowercase for native event names
176
+
177
+ if ('on' + nativeEventName in target) {
178
+ // it is a native HTML event
179
+ let listener = (ev: Event) => {
180
+ that[key](ev);
181
+ };
182
+ // console.log( 'AAL: attach native event listener', nativeEventName, 'to', target );
183
+ target.addEventListener(nativeEventName, listener);
184
+ } else {
185
+ // it is a customEvent
186
+ // console.log( 'AAL: attach custom event listener', '_mc' + withoutOnOne , 'to key', key, 'in', element );
187
+ let listener = (ev: CustomEvent) => {
188
+ that[key](ev);
189
+ };
190
+ on(target, withoutOnOne, listener as EventListenerOrEventListenerObject, once);
191
+ }
192
+ });
193
+ }
196
194
  }
197
195
 
198
196
  function getMcChildNodes(domNode: HTMLElement): DC[] | null {
199
- const id = Math.random().toString().replace('.', '');
200
- const selector = '[data-mc]:not([temp_id="' + id + '"] [data-mc] [data-mc])';
201
- domNode.setAttribute('temp_id', id);
202
- const mcArray: unknown[] = ([...domNode.querySelectorAll(selector)] as HTMLMcElement[])
203
- .filter((e) => !!e._mc)
204
- .map((e) => e._mc);
205
- domNode.removeAttribute('temp_id');
206
- return mcArray.length ? (mcArray as DC[]) : null;
197
+ const id = Math.random().toString().replace('.', '');
198
+ const selector = '[data-mc]:not([temp_id="' + id + '"] [data-mc] [data-mc])';
199
+ domNode.setAttribute('temp_id', id);
200
+ const mcArray: unknown[] = ([...domNode.querySelectorAll(selector)] as HTMLMcElement[])
201
+ .filter((e) => !!e._mc)
202
+ .map((e) => e._mc);
203
+ domNode.removeAttribute('temp_id');
204
+ return mcArray.length ? (mcArray as DC[]) : null;
207
205
  }
208
206
 
209
207
  class McBase {
210
- private _target: WeakRef<any>; // avoid circular reference
208
+ private _target: WeakRef<any>; // avoid circular reference
209
+
210
+ constructor(target?: { [key: string]: any }) {
211
+ let element = this as unknown as MC | DC;
211
212
 
212
- constructor(target?: { [key: string]: any }) {
213
- let element = this as unknown as MC | DC;
213
+ this._target = new WeakRef(target || {});
214
214
 
215
- this._target = new WeakRef(target || {});
215
+ //console.warn('McBase: this, element, args', target, this, element, arguments);
216
216
 
217
- autoAttachListeners(element);
217
+ autoAttachListeners(element);
218
218
 
219
- init(element as DC); // async lifecycle event
220
- }
219
+ init(element as DC); // async lifecycle event
220
+ }
221
221
 
222
- get target(): any {
223
- return this._target.deref();
224
- }
222
+ get target(): any {
223
+ return this._target.deref();
224
+ }
225
225
  }
226
226
 
227
227
  class MC extends McBase {
228
- constructor(target?: any) {
229
- super(target);
230
- }
228
+ constructor(target?: any) {
229
+ super(target);
230
+ }
231
231
  }
232
232
 
233
233
  class DC extends McBase {
234
- constructor(target: HTMLElement) {
235
- super(target);
236
- }
237
-
238
- static add(target: HTMLElement, key: string, element: any = {}): HTMLMcElement {
239
- return add(target, key, element);
240
- }
241
-
242
- static remove(target: HTMLElement, key: string) {
243
- remove(target, key);
244
- }
245
-
246
- /* event handling */
247
- off(eventName: string, handler: EventListenerOrEventListenerObject) {
248
- off(this.target, eventName, handler);
249
- }
250
-
251
- on(
252
- eventName: string,
253
- handler: EventListenerOrEventListenerObject
254
- ): EventListenerOrEventListenerObject {
255
- return on(this.target, eventName, handler);
256
- }
257
-
258
- one(
259
- eventName: string,
260
- handler: EventListenerOrEventListenerObject
261
- ): EventListenerOrEventListenerObject {
262
- return one(this.target, eventName, handler);
263
- }
264
-
265
- trigger(
266
- eventName: string,
267
- data: any = {},
268
- bubble: string = 'l',
269
- controller?: BubbleController
270
- ) {
271
- trigger(this.target, eventName, data, bubble, controller);
272
- }
273
-
274
- /* DOM traversal */
275
- ancestors(): DC[] | null {
276
- let currentNode: HTMLElement | null = (this as DC)?.target as HTMLMcElement,
277
- result: DC[] = [];
278
-
279
- if (!isDOM(currentNode)) return [];
280
-
281
- while ((currentNode = currentNode.closest('[data-mc]'))) {
282
- if ((currentNode as HTMLMcElement)?._mc) {
283
- result.push((currentNode as HTMLMcElement)?._mc as DC);
284
- }
285
- }
286
-
287
- return result.length ? result : null;
288
- }
289
-
290
- closest(): DC | null {
291
- let target: HTMLElement = (this as DC).target;
292
- if (!isDOM(target)) return null;
293
- return ((target.closest('[data-mc]') as HTMLMcElement)?._mc as DC) || null;
294
- }
295
-
296
- children(): DC[] | null {
297
- let target: any = (this as any)?.target;
298
- if (!isDOM(target)) return null;
299
- return getMcChildNodes(target);
300
- }
301
-
302
- descendants(): DC[] | null {
303
- const target: any = (this as DC)?.target;
304
- if (!isDOM(target)) return [];
305
- const mcArray: unknown[] = ([...target.querySelectorAll('[data-mc]')] as HTMLMcElement[])
306
- .filter((e) => !!e._mc)
307
- .map((e) => e._mc);
308
- return mcArray.length ? (mcArray as DC[]) : null;
309
- }
234
+ constructor(target: HTMLElement) {
235
+ super(target);
236
+ //console.warn('DC constructor:', arguments);
237
+ }
238
+
239
+ static add(target: HTMLElement, key: string, element: any = {}): HTMLMcElement {
240
+ //console.warn('static DC.add() args', arguments);
241
+ return add(target, key, element);
242
+ }
243
+
244
+ static remove(target: HTMLElement, key: string) {
245
+ remove(target, key);
246
+ }
247
+
248
+ /* event handling */
249
+ off(eventName: string, handler: EventListenerOrEventListenerObject) {
250
+ off(this.target, eventName, handler);
251
+ }
252
+
253
+ on(
254
+ eventName: string,
255
+ handler: EventListenerOrEventListenerObject
256
+ ): EventListenerOrEventListenerObject {
257
+ return on(this.target, eventName, handler);
258
+ }
259
+
260
+ one(
261
+ eventName: string,
262
+ handler: EventListenerOrEventListenerObject
263
+ ): EventListenerOrEventListenerObject {
264
+ return one(this.target, eventName, handler);
265
+ }
266
+
267
+ trigger(eventName: string, data: any = {}, bubble: string = 'l', controller?: BubbleController) {
268
+ //console.warn('MC.trigger args', ...arguments, this);
269
+
270
+ trigger(this.target, eventName, data, bubble, controller);
271
+ }
272
+
273
+ /* DOM traversal */
274
+ ancestors(): DC[] | null {
275
+ let currentNode: HTMLElement | null = (this as DC)?.target as HTMLMcElement,
276
+ result: DC[] = [];
277
+
278
+ if (!isDOM(currentNode)) return [];
279
+
280
+ while ((currentNode = currentNode.closest('[data-mc]'))) {
281
+ if ((currentNode as HTMLMcElement)?._mc) {
282
+ result.push((currentNode as HTMLMcElement)?._mc as DC);
283
+ }
284
+ }
285
+
286
+ return result.length ? result : null;
287
+ }
288
+
289
+ closest(): DC | null {
290
+ let target: HTMLElement = (this as DC).target;
291
+ if (!isDOM(target)) return null;
292
+ return ((target.closest('[data-mc]') as HTMLMcElement)?._mc as DC) || null;
293
+ }
294
+
295
+ children(): DC[] | null {
296
+ let target: any = (this as any)?.target;
297
+ if (!isDOM(target)) return null;
298
+ return getMcChildNodes(target);
299
+ }
300
+
301
+ descendants(): DC[] | null {
302
+ const target: any = (this as DC)?.target;
303
+ if (!isDOM(target)) return [];
304
+ const mcArray: unknown[] = ([...target.querySelectorAll('[data-mc]')] as HTMLMcElement[])
305
+ .filter((e) => !!e._mc)
306
+ .map((e) => e._mc);
307
+ return mcArray.length ? (mcArray as DC[]) : null;
308
+ }
310
309
  }
311
310
 
312
311
  /*
@@ -316,141 +315,141 @@ Autoload Section...
316
315
  const loadingDCs = new Set<string>();
317
316
 
318
317
  function attachDC(element: string): Function {
319
- //@ts-ignore
320
- return () => {
321
- const elements: HTMLElement[] = Array.from(
322
- document.querySelectorAll(`[data-mc*="${element}"]`)
323
- ).filter((element) => element instanceof HTMLElement);
324
-
325
- if (elements.length === 0) return;
326
-
327
- //console.log( 'loadedPromise elements', elements );
328
-
329
- const Klass = customElements.get(element);
330
-
331
- elements.forEach((node: HTMLElement) => {
332
- try {
333
- //console.log( 'add', klass!.name, 'to', node );
334
- DC.add(node, Klass!.name, new Klass!(node));
335
- } catch (error) {
336
- if ((Klass as LooseObject)['create']) {
337
- let element: HTMLMcElement = (Klass as LooseObject).create(node);
338
- element.setAttribute('data-mc', node.getAttribute('data-mc')!);
339
- node.replaceWith(element);
340
- node = element;
341
- } else {
342
- throw `Class ${(Klass as LooseObject).name} doesn't have a callable constructor AND class doesn't have a static .create() method.`;
343
- }
344
- }
345
-
346
- //@ts-ignore
347
- const new_mc = node
348
- .getAttribute('data-mc')
349
- .split(' ')
350
- .filter((name) => name !== element && name !== '')
351
- .join(' ')
352
- .trim();
353
-
354
- //@ts-ignore
355
- node.setAttribute(
356
- 'data-mc',
357
- //@ts-ignore
358
- new_mc
359
- );
360
- });
361
- };
318
+ //@ts-ignore
319
+ return () => {
320
+ const elements: HTMLElement[] = Array.from(
321
+ document.querySelectorAll(`[data-mc*="${element}"]`)
322
+ ).filter((element) => element instanceof HTMLElement);
323
+
324
+ if (elements.length === 0) return;
325
+
326
+ //console.log( 'loadedPromise elements', elements );
327
+
328
+ const Klass = customElements.get(element);
329
+
330
+ elements.forEach((node: HTMLElement) => {
331
+ try {
332
+ //console.log( 'add', klass!.name, 'to', node );
333
+ DC.add(node, Klass!.name, new Klass!(node));
334
+ } catch (error) {
335
+ if ((Klass as LooseObject)['create']) {
336
+ let element: HTMLMcElement = (Klass as LooseObject).create(node);
337
+ element.setAttribute('data-mc', node.getAttribute('data-mc')!);
338
+ node.replaceWith(element);
339
+ node = element;
340
+ } else {
341
+ throw `Class ${(Klass as LooseObject).name} doesn't have a callable constructor AND class doesn't have a static .create() method.`;
342
+ }
343
+ }
344
+
345
+ //@ts-ignore
346
+ const new_mc = node
347
+ .getAttribute('data-mc')
348
+ .split(' ')
349
+ .filter((name) => name !== element && name !== '')
350
+ .join(' ')
351
+ .trim();
352
+
353
+ //@ts-ignore
354
+ node.setAttribute(
355
+ 'data-mc',
356
+ //@ts-ignore
357
+ new_mc
358
+ );
359
+ });
360
+ };
362
361
  }
363
362
 
364
363
  function makeLoadScript(element: string) {
365
- if (loadingDCs.has(element)) return; // already loading
364
+ if (loadingDCs.has(element)) return; // already loading
366
365
 
367
- loadingDCs.add(element);
366
+ loadingDCs.add(element);
368
367
 
369
- //console.log( 'makeLoadScript:', element);
370
- const fileName: string = './' + element.split('-').join('/') + '.js';
368
+ //console.log( 'makeLoadScript:', element);
369
+ const fileName: string = './' + element.split('-').join('/') + '.js';
371
370
 
372
- const se: HTMLScriptElement = document.createElement('script');
371
+ const se: HTMLScriptElement = document.createElement('script');
373
372
 
374
- se.setAttribute('src', fileName);
375
- se.setAttribute('blocking', 'render');
376
- se.async = true;
377
- se.setAttribute('type', 'module');
378
- se.setAttribute('data-name', element);
379
- se.setAttribute('loading', '');
373
+ se.setAttribute('src', fileName);
374
+ se.setAttribute('blocking', 'render');
375
+ se.async = true;
376
+ se.setAttribute('type', 'module');
377
+ se.setAttribute('data-name', element);
378
+ se.setAttribute('loading', '');
380
379
 
381
- const loadedPromise = customElements.whenDefined(element);
380
+ const loadedPromise = customElements.whenDefined(element);
382
381
 
383
- //@ts-ignore
384
- loadedPromise.then(attachDC(element));
382
+ //@ts-ignore
383
+ loadedPromise.then(attachDC(element));
385
384
 
386
- se.addEventListener('load', (ev: Event) => {
387
- loadingDCs.delete(element);
385
+ se.addEventListener('load', (ev: Event) => {
386
+ loadingDCs.delete(element);
388
387
 
389
- document.head.querySelector(`script[data-name="${element}"]`)?.remove();
390
- });
388
+ document.head.querySelector(`script[data-name="${element}"]`)?.remove();
389
+ });
391
390
 
392
- se.addEventListener('error', (ev: Event) => {
393
- console.error('could not load DC code from', fileName);
394
- });
391
+ se.addEventListener('error', (ev: Event) => {
392
+ console.error('could not load DC code from', fileName);
393
+ });
395
394
 
396
- document.head.append(se);
395
+ document.head.append(se);
397
396
  }
398
397
 
399
398
  function loadUndefinedMCs() {
400
- // load unresolved custom elements
401
- [...document.querySelectorAll(':not(:defined)')]
402
- .filter(
403
- (element) =>
404
- !!element &&
405
- !customElements.get(element.tagName.toLowerCase()) && // not in CustomElementsRegistry
406
- !loadingDCs.has(element.tagName.toLowerCase()) // not in loading list
407
- )
408
- .forEach((el) => {
409
- //console.log( 'detected CE', el.tagName.toLowerCase() );
410
- makeLoadScript(el.tagName.toLowerCase()); // will automatically be instanciated
411
- });
412
-
413
- // if defined in _mc attribute: instanciate DCs, load if necessary
414
- [...document.querySelectorAll('[data-mc]:not([data-mc=""]')]
415
- .filter((element) => !!element)
416
- .forEach((el) => {
417
- const _mc = el
418
- .getAttribute('data-mc')
419
- ?.split(' ')
420
- .filter((name) => name !== '');
421
- _mc?.forEach((element) => {
422
- //console.log( 'detected DC', dc );
423
- const isDefined = customElements.get(element);
424
- if (!loadingDCs.has(element) && !isDefined) {
425
- makeLoadScript(element);
426
- } else if (isDefined) {
427
- attachDC(element)();
428
- }
429
- });
430
- });
399
+ // load unresolved custom elements
400
+ [...document.querySelectorAll(':not(:defined)')]
401
+ .filter(
402
+ (element) =>
403
+ !!element &&
404
+ !customElements.get(element.tagName.toLowerCase()) && // not in CustomElementsRegistry
405
+ !loadingDCs.has(element.tagName.toLowerCase()) // not in loading list
406
+ )
407
+ .forEach((el) => {
408
+ //console.log( 'detected CE', el.tagName.toLowerCase() );
409
+ makeLoadScript(el.tagName.toLowerCase()); // will automatically be instanciated
410
+ });
411
+
412
+ // if defined in _mc attribute: instanciate DCs, load if necessary
413
+ [...document.querySelectorAll('[data-mc]:not([data-mc=""]')]
414
+ .filter((element) => !!element)
415
+ .forEach((el) => {
416
+ const _mc = el
417
+ .getAttribute('data-mc')
418
+ ?.split(' ')
419
+ .filter((name) => name !== '');
420
+ _mc?.forEach((element) => {
421
+ //console.log( 'detected DC', dc );
422
+ const isDefined = customElements.get(element);
423
+ if (!loadingDCs.has(element) && !isDefined) {
424
+ makeLoadScript(element);
425
+ } else if (isDefined) {
426
+ attachDC(element)();
427
+ }
428
+ });
429
+ });
431
430
  }
432
431
 
433
432
  let autoloadEnabled: boolean = false;
434
433
  let observer: MutationObserver | null = null;
435
434
 
436
435
  function autoload(enable: boolean = true): boolean {
437
- if (!enable) {
438
- observer?.disconnect();
439
- observer = null;
440
- return autoloadEnabled;
441
- }
436
+ if (!enable) {
437
+ observer?.disconnect();
438
+ observer = null;
439
+ return autoloadEnabled;
440
+ }
442
441
 
443
- autoloadEnabled = enable;
444
- observer = new MutationObserver(loadUndefinedMCs);
442
+ autoloadEnabled = enable;
443
+ observer = new MutationObserver(loadUndefinedMCs);
445
444
 
446
- setTimeout(() => {
447
- observer!.observe(document.body, { childList: true, subtree: true });
448
- loadUndefinedMCs();
449
- }, 5);
445
+ setTimeout(() => {
446
+ observer!.observe(document.body, { childList: true, subtree: true });
447
+ loadUndefinedMCs();
448
+ }, 5);
450
449
 
451
- (window as LooseObject).autoload = (window as LooseObject).autoload || autoload;
450
+ (window as LooseObject).autoload = (window as LooseObject).autoload || autoload;
452
451
 
453
- return autoloadEnabled;
452
+ return autoloadEnabled;
454
453
  }
455
454
 
456
455
  (autoload as LooseObject).state = loadingDCs;