@twobirds/microcomponents 0.0.80 → 0.0.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1115 +1,8 @@
1
- (function webpackUniversalModuleDefinition(root, factory) {
2
- if(typeof exports === 'object' && typeof module === 'object')
3
- module.exports = factory();
4
- else if(typeof define === 'function' && define.amd)
5
- define([], factory);
6
- else if(typeof exports === 'object')
7
- exports["microcomponents"] = factory();
8
- else
9
- root["microcomponents"] = factory();
10
- })(this, () => {
11
- return /******/ (() => { // webpackBootstrap
12
- /******/ "use strict";
13
- /******/ // The require scope
14
- /******/ var __webpack_require__ = {};
15
- /******/
16
- /************************************************************************/
17
- /******/ /* webpack/runtime/define property getters */
18
- /******/ (() => {
19
- /******/ // define getter functions for harmony exports
20
- /******/ __webpack_require__.d = (exports, definition) => {
21
- /******/ for(var key in definition) {
22
- /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
23
- /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
24
- /******/ }
25
- /******/ }
26
- /******/ };
27
- /******/ })();
28
- /******/
29
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
30
- /******/ (() => {
31
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
32
- /******/ })();
33
- /******/
34
- /******/ /* webpack/runtime/make namespace object */
35
- /******/ (() => {
36
- /******/ // define __esModule on exports
37
- /******/ __webpack_require__.r = (exports) => {
38
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
39
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
40
- /******/ }
41
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
42
- /******/ };
43
- /******/ })();
44
- /******/
45
- /************************************************************************/
46
- var __webpack_exports__ = {};
47
- // ESM COMPAT FLAG
48
- __webpack_require__.r(__webpack_exports__);
49
-
50
- // EXPORTS
51
- __webpack_require__.d(__webpack_exports__, {
52
- DC: () => (/* reexport */ DC),
53
- MC: () => (/* reexport */ MC),
54
- McBase: () => (/* reexport */ McBase),
55
- McEvent: () => (/* reexport */ McEvent),
56
- addListener: () => (/* reexport */ addListener),
57
- autoload: () => (/* reexport */ autoload),
58
- copyGettersSetters: () => (/* reexport */ copyGettersSetters),
59
- debounce: () => (/* reexport */ debounce),
60
- deepEqual: () => (/* reexport */ deepEqual),
61
- defineCE: () => (/* reexport */ defineCE),
62
- flattenObject: () => (/* reexport */ flattenObject),
63
- formValues: () => (/* reexport */ formValues),
64
- getCE: () => (/* reexport */ getCE),
65
- htmlToElements: () => (/* reexport */ htmlToElements),
66
- isNativeObject: () => (/* reexport */ isNativeObject),
67
- kebabToPascal: () => (/* reexport */ kebabToPascal),
68
- nameSpace: () => (/* reexport */ nameSpace),
69
- observe: () => (/* reexport */ observe),
70
- parse: () => (/* reexport */ parse),
71
- removeListener: () => (/* reexport */ removeListener),
72
- sortObject: () => (/* reexport */ sortObject)
73
- });
74
-
75
- ;// ./build/helpers.js
76
-
77
- function isNativeObject(value) {
78
- return value && value['constructor'] && value.constructor === Object;
79
- }
80
- function sortObject(o) {
81
- let result = {}, keys = [...Object.keys(o)].sort();
82
- keys.forEach((key) => {
83
- if (isNativeObject(o[key])) {
84
- result[key] = sortObject(o[key]);
85
- }
86
- else {
87
- result[key] = o[key];
88
- }
89
- });
90
- return result;
91
- }
92
- function flattenObject(o, doSort = true) {
93
- let result = {};
94
- [...Object.getOwnPropertyNames(o)].forEach((propName) => {
95
- if (o[propName] &&
96
- o[propName]['constructor'] &&
97
- o[propName].constructor === Object) {
98
- const temp = flattenObject(o[propName], false);
99
- for (const j in temp) {
100
- result[propName + '.' + j] = temp[j];
101
- }
102
- }
103
- else {
104
- result[propName] = o[propName];
105
- }
106
- });
107
- return doSort ? sortObject(result) : result;
108
- }
109
- function deepEqual(o1, o2) {
110
- return (JSON.stringify(flattenObject(o1)) === JSON.stringify(flattenObject(o2)));
111
- }
112
- function nameSpace(ns, obj = {}) {
113
- let nsa = ns.constructor === String ? ns.split('.') : ns;
114
- if (!obj || !nsa[0] || !obj[nsa[0]]) {
115
- console.warn('ns', nsa[0], 'not in', obj);
116
- return;
117
- }
118
- if (obj[nsa[0]].constructor === Object && nsa.length > 1) {
119
- return nameSpace(nsa.splice(1), obj[nsa[0]]);
120
- }
121
- return obj[nsa[0]];
122
- }
123
- function parse(what, parseThis) {
124
- var args = Array.from(arguments);
125
- if (args.length > 2) {
126
- while (args.length > 1) {
127
- args[0] = parse(args[0], args[1]);
128
- args.splice(1, 1);
129
- }
130
- return args[0];
131
- }
132
- if (typeof what === 'string') {
133
- what.match(/\{[^\{\}]*\}/g)?.forEach(function (pPropname) {
134
- var propname = pPropname.substring(1, pPropname.length - 1), value = nameSpace(propname, parseThis);
135
- if (typeof value !== 'undefined') {
136
- what = what.replace(pPropname, value);
137
- }
138
- });
139
- }
140
- else if (isNativeObject(what)) {
141
- switch (what.constructor) {
142
- case Object:
143
- Object.keys(what).forEach(function (pKey) {
144
- if (what.hasOwnProperty(pKey)) {
145
- what[pKey] = parse(what[pKey], parseThis);
146
- }
147
- });
148
- break;
149
- case Array:
150
- what.forEach(function (pValue, pKey, original) {
151
- original[pKey] = parse(what[pKey], parseThis);
152
- });
153
- break;
154
- }
155
- }
156
- return what;
157
- }
158
- function kebabToPascal(str) {
159
- return str
160
- .split('-')
161
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
162
- .join('');
163
- }
164
- function debounce(func, milliseconds) {
165
- let timeout;
166
- return () => {
167
- clearTimeout(timeout);
168
- timeout = setTimeout(function () {
169
- func(...arguments);
170
- }, milliseconds);
171
- };
172
- }
173
- function htmlToElements(html) {
174
- let template = document.createElement('template');
175
- html = html.replace(/<([A-Za-z0-9\-]*)([^>\/]*)(\/>)/gi, '<$1$2></$1>');
176
- template.innerHTML = html;
177
- template.content.normalize();
178
- return Array.from(template.content.childNodes);
179
- }
180
- function copyGettersSetters(source, target) {
181
- const descriptors = Object.getOwnPropertyDescriptors(source);
182
- for (const [key, descriptor] of Object.entries(descriptors)) {
183
- if ('get' in descriptor || 'set' in descriptor) {
184
- Object.defineProperty(target, key, descriptor);
185
- }
186
- }
187
- }
188
-
189
- ;// ./build/McEvent.js
190
-
191
- var isBrowser = new Function("try {return this===window;}catch(e){ return false;}");
192
- let nativeEventNames = new Set();
193
- if (isBrowser()) {
194
- Object.keys(HTMLElement.prototype).filter(key => /^on/.test(key)).forEach(eventName => nativeEventNames.add(eventName));
195
- }
196
- function isDOM(element) {
197
- return element && element instanceof HTMLElement;
198
- }
199
- class McEvent {
200
- #type;
201
- #stopped = false;
202
- #immediateStopped = false;
203
- constructor(type, data = {}, bubble = 'l') {
204
- this.#type = type;
205
- this.data = data;
206
- this.bubble = bubble;
207
- }
208
- get type() {
209
- return this.#type;
210
- }
211
- get stopped() {
212
- return this.#stopped;
213
- }
214
- get immediateStopped() {
215
- return this.#immediateStopped;
216
- }
217
- stopPropagation() {
218
- this.#stopped = true;
219
- }
220
- stopImmediatePropagation() {
221
- this.stopPropagation();
222
- this.#immediateStopped = true;
223
- }
224
- }
225
- function getMicroComponents(elements, search) {
226
- let mcValues = [];
227
- elements.forEach(e => {
228
- if (e) {
229
- if (e instanceof HTMLElement) {
230
- const _mc = e?._mc;
231
- if (!search && _mc) {
232
- mcValues = mcValues.concat(Object.values(e._mc));
233
- }
234
- else if (search && _mc && _mc[search]) {
235
- mcValues.push(_mc[search]);
236
- }
237
- }
238
- }
239
- });
240
- return mcValues;
241
- }
242
- function traverseNodes(node, search, firstonly = true) {
243
- let mcValues = [];
244
- while (node) {
245
- if (node._mc) {
246
- if (!search) {
247
- mcValues = mcValues.concat(Object.values(node._mc));
248
- }
249
- else if (search && node._mc[search]) {
250
- mcValues.push(node._mc[search]);
251
- }
252
- if (firstonly)
253
- return mcValues;
254
- }
255
- node = node.parentNode;
256
- }
257
- return mcValues;
258
- }
259
-
260
-
261
- ;// ./build/MC.js
262
-
263
-
264
- var MC_isBrowser = new Function('try {return this===window;}catch(e){ return false;}');
265
- let MC_nativeEventNames = new Set();
266
- if (MC_isBrowser()) {
267
- Object.keys(HTMLElement.prototype)
268
- .filter((key) => /^on/.test(key))
269
- .forEach((eventName) => MC_nativeEventNames.add(eventName));
270
- }
271
- function MC_getMicroComponents(elements, search) {
272
- let mcValues = [];
273
- elements.forEach((e) => {
274
- if (e) {
275
- if (e instanceof HTMLElement) {
276
- const _mc = e?._mc;
277
- if (!search && _mc) {
278
- mcValues = mcValues.concat(Object.values(e._mc));
279
- }
280
- else if (search && _mc && _mc[search]) {
281
- mcValues.push(_mc[search]);
282
- }
283
- }
284
- }
285
- });
286
- return mcValues;
287
- }
288
- function MC_traverseNodes(node, search, firstonly = true) {
289
- let mcValues = [];
290
- while (node) {
291
- if (node._mc) {
292
- if (!search) {
293
- mcValues = mcValues.concat(Object.values(node._mc));
294
- }
295
- else if (search && node._mc[search]) {
296
- mcValues.push(node._mc[search]);
297
- }
298
- if (firstonly)
299
- return mcValues;
300
- }
301
- node = node.parentNode;
302
- }
303
- return mcValues;
304
- }
305
- function MC_isDOM(element) {
306
- return element && element instanceof HTMLElement;
307
- }
308
- function addListener(domNode, eventName, handler, capture = false, once = false) {
309
- let options = { once: false };
310
- if (capture) {
311
- options.capture = capture;
312
- }
313
- if (once) {
314
- options.once = once;
315
- }
316
- domNode.addEventListener(eventName, handler, options);
317
- }
318
- function removeListener(domNode, eventName, handler) {
319
- domNode.removeEventListener(eventName, handler);
320
- }
321
- function add(target, key, element = {}) {
322
- let node = target;
323
- if (!node._mc) {
324
- let debug = DC?.debug;
325
- DC.debug = false;
326
- node._mc = new DC(target);
327
- DC.debug = debug;
328
- delete node._mc._mc;
329
- }
330
- const _mc = node._mc;
331
- if (key.length && !_mc[key]) {
332
- _mc[key] = element;
333
- if (target instanceof HTMLElement && !target.getAttribute('_mc')) {
334
- target.setAttribute('_mc', '');
335
- }
336
- }
337
- return element;
338
- }
339
- function remove(target, key) {
340
- if (!key)
341
- return;
342
- const _mc = target?._mc || {};
343
- if (_mc && _mc[key]) {
344
- delete _mc[key];
345
- }
346
- if (!Object.keys(_mc).length &&
347
- target instanceof HTMLElement &&
348
- target.hasAttribute('_mc')) {
349
- target.removeAttribute('_mc');
350
- }
351
- return;
352
- }
353
- function trigger(target, ev, data = {}, bubble = 'l') {
354
- let _mc = target?._mc;
355
- if (!_mc)
356
- return;
357
- let event = ev instanceof McEvent
358
- ? new McEvent(ev.type, ev.data, 'l')
359
- : new McEvent(ev, data, 'l'), mcEvent = typeof ev !== 'string' ? ev : new McEvent(ev, data, bubble);
360
- [...Object.values(_mc)].forEach((mc) => {
361
- if (mc?.trigger && typeof mc?.trigger === 'function') {
362
- mc?.trigger(event);
363
- }
364
- });
365
- if (/[ud]/.test(mcEvent.bubble)) {
366
- bubbleEvent(target, mcEvent);
367
- }
368
- return;
369
- }
370
- function init(element) {
371
- if (element.constructor === DC)
372
- return;
373
- setTimeout(() => {
374
- element.trigger('Init');
375
- }, 0);
376
- }
377
- function autoAttachListeners(element) {
378
- if (!MC_isBrowser() || element.constructor === DC)
379
- return;
380
- const target = element.target;
381
- if (target instanceof HTMLElement) {
382
- let that = element;
383
- Object.getOwnPropertyNames(that.constructor.prototype)
384
- .filter((key) => /^on[A-Z]|one[A-Z]/.test(key) &&
385
- typeof that.constructor.prototype[key] === 'function')
386
- .forEach((key) => {
387
- let once = /^one/.test(key), withoutOnOne = key.replace(/^on[e]{0,1}/, ''), nativeEventName = withoutOnOne.toLowerCase(), listener = (ev) => {
388
- that.trigger(withoutOnOne, ev);
389
- };
390
- if (once) {
391
- Object.defineProperty(element, 'on' + withoutOnOne, {
392
- configurable: true,
393
- enumerable: false,
394
- writable: true,
395
- value: (ev) => {
396
- that.constructor.prototype[key].bind(that)(ev);
397
- },
398
- });
399
- }
400
- if (MC_nativeEventNames.has('on' + nativeEventName)) {
401
- addListener(target, nativeEventName, listener, false, once);
402
- }
403
- });
404
- }
405
- }
406
- function bubbleEvent(target, ev) {
407
- if (/[ud]/.test(ev.bubble)) {
408
- setTimeout(() => {
409
- if (ev.bubble.indexOf('l') === -1) {
410
- ev.bubble += 'l';
411
- }
412
- if (ev.bubble.indexOf('u') > -1) {
413
- let parent = MC_traverseNodes(target, '', true)?.[0].target;
414
- if (parent)
415
- DC.trigger(parent, ev);
416
- }
417
- if (ev.bubble.indexOf('d') > -1) {
418
- let targets = new Set(target._mc
419
- .children()
420
- .map((c) => c?.target));
421
- targets.forEach((target) => {
422
- if (target)
423
- DC.trigger(target, ev);
424
- });
425
- }
426
- }, 0);
427
- }
428
- }
429
- class McBase {
430
- #target;
431
- constructor(target, debug = false) {
432
- let that = this, element = that;
433
- this.#target = new WeakRef(target || {});
434
- init(element);
435
- autoAttachListeners(element);
436
- }
437
- get target() {
438
- return this.#target.deref();
439
- }
440
- }
441
- class MC extends McBase {
442
- _mc = {};
443
- constructor(target) {
444
- super(target);
445
- }
446
- static trigger = trigger;
447
- trigger(ev, data = {}, bubble = 'l') {
448
- let that = this;
449
- if (that.constructor === MC || that.constructor === DC) {
450
- let event = ev instanceof McEvent
451
- ? new McEvent(ev.type, ev.data, 'l')
452
- : new McEvent(ev, data, 'l'), mcEvent = typeof ev !== 'string'
453
- ? ev
454
- : new McEvent(ev, data, bubble);
455
- [...Object.getOwnPropertyNames(that)].forEach((mc) => {
456
- if (that[mc]?.trigger &&
457
- typeof that[mc]?.trigger === 'function') {
458
- that[mc]?.trigger(event);
459
- }
460
- });
461
- if (/[ud]/.test(mcEvent.bubble)) {
462
- bubbleEvent(that.target, mcEvent);
463
- }
464
- return;
465
- }
466
- if (that instanceof MC || that instanceof DC) {
467
- const that = this, mcEvent = typeof ev !== 'string'
468
- ? ev
469
- : new McEvent(ev, data, bubble), handlerName = 'on' + mcEvent.type[0].toUpperCase() + mcEvent.type.slice(1);
470
- if (mcEvent.bubble.indexOf('l') > -1) {
471
- if (!mcEvent.immediateStopped &&
472
- typeof that[handlerName] === 'function') {
473
- that[handlerName](mcEvent);
474
- if (that.hasOwnProperty(handlerName)) {
475
- delete that[handlerName];
476
- }
477
- }
478
- }
479
- if (mcEvent.stopped || mcEvent.bubble === 'l') {
480
- return that;
481
- }
482
- if (/[ud]/.test(mcEvent.bubble)) {
483
- bubbleEvent(that.target, mcEvent);
484
- }
485
- }
486
- }
487
- }
488
- class DC extends McBase {
489
- _mc = {};
490
- constructor(target, debug = false) {
491
- super(target);
492
- }
493
- static add = add;
494
- static remove = remove;
495
- static trigger = trigger;
496
- trigger(ev, data = {}, bubble) {
497
- MC.prototype.trigger.call(this, ev, data, bubble);
498
- }
499
- parent(search = '') {
500
- let target = this.target;
501
- if (!MC_isDOM(target))
502
- return [];
503
- return MC_traverseNodes(target.parentNode, search, true);
504
- }
505
- ancestors(search = '') {
506
- let target = this?.target;
507
- if (!MC_isDOM(target))
508
- return [];
509
- return MC_traverseNodes(this.target.parentNode, search, false);
510
- }
511
- children(search = '') {
512
- let target = this?.target;
513
- if (!MC_isDOM(target))
514
- return [];
515
- const id = Math.random().toString().replace('.', '');
516
- const selector = '[_mc]:not([temp_id="' + id + '"] [_mc] [_mc])';
517
- target.setAttribute('temp_id', id);
518
- const myDomElements = target.querySelectorAll(selector);
519
- const mcValues = MC_getMicroComponents([...myDomElements], search);
520
- target.removeAttribute('temp_id');
521
- return mcValues;
522
- }
523
- descendants(search = '') {
524
- let target = this?.target;
525
- if (!MC_isDOM(target))
526
- return [];
527
- const myDomElements = target.querySelectorAll('*[_mc]');
528
- return MC_getMicroComponents([...myDomElements], search);
529
- }
530
- }
531
- const CEs = new Map();
532
- const MCs = new Map();
533
- function makeLoadScript(element) {
534
- const fileName = './' + element.split('-').join('/') + '.js';
535
- const se = document.createElement('script');
536
- se.setAttribute('src', fileName);
537
- se.setAttribute('blocking', 'render');
538
- se.async = true;
539
- se.setAttribute('type', 'module');
540
- se.setAttribute('name', element);
541
- se.setAttribute('loading', '');
542
- addListener(se, 'load', (ev) => {
543
- se.removeAttribute('loading');
544
- se.setAttribute('loaded', '');
545
- });
546
- addListener(se, 'error', (ev) => {
547
- console.error('could not load Custom Element code from', fileName);
548
- });
549
- return se;
550
- }
551
- function onLoadCallback(script) {
552
- setTimeout(function () {
553
- const importFileName = script.getAttribute('src');
554
- const elementName = script.getAttribute('name');
555
- const se = document.createElement('script');
556
- se.async = true;
557
- se.setAttribute('type', 'module');
558
- const code = `
559
-
560
- import _ from "${importFileName}";
561
- import { DC } from "./microcomponents.js";
562
-
563
- const elements = Array.from(document.querySelectorAll('[_mc*="${elementName}"]')).filter( element => element instanceof HTMLElement );
564
-
565
- elements.forEach((element) => {
566
- // add class to MCs repository
567
- autoload.state.MCs.set( '${elementName}', _ );
568
- // add instance to HTMLElement
569
- DC.add(element, _.name, new _(element));
570
- // remove instance name from elements "_mc" attribute
571
- element.setAttribute('_mc', element.getAttribute('_mc').replace('${elementName}', '').replace( /\w\w/g, ' ').trim());
572
- });
573
-
574
- setTimeout( () => {
575
- document.body.querySelector('script[name="${elementName}]"')?.remove();
576
- },0);
577
-
578
- `;
579
- se.innerHTML = code;
580
- document.body.append(se);
581
- }, 0);
582
- }
583
- function loadUndefinedMicroComponents() {
584
- [...document.querySelectorAll(':not(:defined)')]
585
- .filter((element) => !!element
586
- && !customElements.get(element.tagName.toLowerCase())
587
- && !CEs.has(element.tagName.toLowerCase()))
588
- .forEach((el) => {
589
- const elementName = el.tagName.toLowerCase(), fileName = './' + elementName.split('-').join('/') + '.js';
590
- const se = makeLoadScript(elementName);
591
- addListener(se, 'load', () => {
592
- CEs.set(elementName, customElements.get(el.tagName.toLowerCase()));
593
- });
594
- CEs.set(elementName, 'loading');
595
- document.head.append(se);
596
- });
597
- [...document.querySelectorAll('[_mc]:not([_mc=""]')]
598
- .filter((element) => !!element)
599
- .forEach((el) => {
600
- const elements = el.getAttribute('_mc')?.split(' ').filter(m => !!m) || [];
601
- const elementsToBeLoaded = elements.filter(m => !MCs.has(m));
602
- elementsToBeLoaded?.forEach(elementName => {
603
- const se = makeLoadScript(elementName);
604
- addListener(se, 'load', () => onLoadCallback(document.head.querySelector(`script[name="${elementName}"]`)));
605
- MCs.set(elementName, 'loading');
606
- document.head.append(se);
607
- });
608
- const elementsAlreadyLoaded = elements.filter(m => MCs.has(m) && !MCs.get(m).length);
609
- elementsAlreadyLoaded?.forEach(elementName => {
610
- setTimeout(() => {
611
- DC.add(el, elementName, new (autoload.state.MCs.get(elementName))(el));
612
- const newAttribute = el.getAttribute('_mc')
613
- .replace('${elementName}', '')
614
- .replace(/\w\w/g, ' ')
615
- .trim() || '_mc';
616
- el.setAttribute('_mc');
617
- }, 5);
618
- });
619
- });
620
- }
621
- let autoloadEnabled = false;
622
- let observer = null;
623
- function autoload(enable = true) {
624
- if (!enable) {
625
- observer?.disconnect();
626
- observer = null;
627
- return autoloadEnabled;
628
- }
629
- autoloadEnabled = enable;
630
- observer = new MutationObserver(loadUndefinedMicroComponents);
631
- setTimeout(() => {
632
- observer.observe(document.body, { childList: true, subtree: true });
633
- loadUndefinedMicroComponents();
634
- }, 5);
635
- window.autoload = window.autoload || autoload;
636
- return autoloadEnabled;
637
- }
638
- autoload.state = { CEs, MCs };
639
-
640
-
641
- ;// ./build/elements.js
642
-
643
-
644
-
645
- class CeBaseClass extends HTMLElement {
646
- constructor() {
647
- super();
648
- }
649
- connectedCallback() {
650
- DC.trigger(this, 'Connected');
651
- }
652
- disconnectedCallback() {
653
- DC.trigger(this, 'Disconnected');
654
- }
655
- adoptedCallback() {
656
- DC.trigger(this, 'Adopted');
657
- }
658
- attributeChangedCallback(name, oldValue, newValue) {
659
- DC.trigger(this, 'AttributeChanged', { name, oldValue, newValue });
660
- }
661
- }
662
- function createNamedClass(name, ClassBody) {
663
- return Object.defineProperty(ClassBody, 'name', { value: name });
664
- }
665
- function defineCE(tagName, DefinitionClass, observedAttributes = []) {
666
- if (customElements.get(tagName)) {
667
- console.warn(`IGNORED: Custom element "${tagName}" is already defined!`);
668
- return;
669
- }
670
- if (!tagName.includes('-')) {
671
- throw new Error('createCustomElement: tagName must contain at least one hyphen ("-").');
672
- }
673
- let name = kebabToPascal(tagName);
674
- customElements.define(tagName, createNamedClass(name, class extends CeBaseClass {
675
- instance;
676
- constructor(data) {
677
- super();
678
- let instance = new DefinitionClass(this, data);
679
- DC.add(this, name, instance);
680
- }
681
- static get observedAttributes() {
682
- return observedAttributes;
683
- }
684
- }));
685
- }
686
- function getCE(tagName) {
687
- return customElements.get(tagName);
688
- }
689
-
690
- ;// ./build/observables.js
691
-
692
-
693
-
694
- function isObservableObject(value) {
695
- return value != null && typeof value === 'object';
696
- }
697
- function getPlaceholders(target) {
698
- let placeholders = new Set(), regEx = /\{[^\{\}]*\}/g;
699
- target
700
- .getAttributeNames()
701
- .filter((attr) => target.getAttribute(attr)?.match(regEx))
702
- .forEach((attr) => {
703
- let phs = new Set(target.getAttribute(attr)?.match(regEx));
704
- phs.forEach((placeholder) => placeholders.add(placeholder.replace(/[\{\}]/g, '')));
705
- });
706
- [...target.childNodes]
707
- .filter((childNode) => {
708
- return (childNode.nodeType === 3 &&
709
- (childNode.nodeValue || '').match(regEx));
710
- })
711
- .forEach((childNode) => {
712
- (childNode.nodeValue || '')
713
- .match(regEx)
714
- .forEach((placeholder) => {
715
- placeholders.add(placeholder.replace(/[\{\}]/g, ''));
716
- });
717
- });
718
- return [...placeholders].map((placeholder) => placeholder.replace(/[\{\}]/g, ''));
719
- }
720
- const inputs = [HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement];
721
- class Placeholders extends DC {
722
- data = {};
723
- oldDisplay = '';
724
- constructor(target) {
725
- super(target);
726
- let that = this;
727
- getPlaceholders(target).forEach((property) => (that.data[property] = ''));
728
- observe(that);
729
- that.#attachCallbacks();
730
- delete that._mc;
731
- }
732
- #attachCallbacks() {
733
- let that = this, target = that.target, hide = false;
734
- target
735
- .getAttributeNames()
736
- .filter((attr) => target.getAttribute(attr)?.match(/\{[^\{\}]*\}/g))
737
- .forEach((attr) => {
738
- let phs = new Set(target.getAttribute(attr)?.match(/\{[^\{\}]*\}/g));
739
- that.data.observe(((template) => (data) => {
740
- let result = template;
741
- phs.forEach((placeholder) => {
742
- result = result.replace(placeholder, data[placeholder.replace(/[\{\}]/g, '')]);
743
- });
744
- target.setAttribute(attr, result);
745
- })(target.getAttribute(attr)));
746
- });
747
- [...target.childNodes]
748
- .filter((childNode) => {
749
- return (childNode.nodeType === 3 &&
750
- (childNode.nodeValue || '').match(/\{[^\{\}]*\}/g));
751
- })
752
- .forEach((childNode) => {
753
- hide = true;
754
- let phs = new Set(childNode.nodeValue.match(/\{[^\{\}]*\}/g));
755
- that.data.observe(((template) => (data) => {
756
- let result = template;
757
- phs.forEach((placeholder) => {
758
- result = result.replace(placeholder, data[placeholder.replace(/[\{\}]/g, '')]);
759
- });
760
- if (Object.keys(data).some((key) => {
761
- return !!data[key];
762
- })) {
763
- if (!!that.oldDisplay) {
764
- target.style = that.oldDisplay;
765
- }
766
- else {
767
- target.removeAttribute('style');
768
- }
769
- delete that.oldDisplay;
770
- }
771
- childNode.nodeValue = result;
772
- })(childNode.nodeValue));
773
- that.oldDisplay = target.getAttribute('style)') || '';
774
- if (hide &&
775
- !inputs.includes(target.constructor) &&
776
- target.tagName !== 'FIELDSET') {
777
- target.style.display = 'none';
778
- }
779
- });
780
- }
781
- onData(ev) {
782
- let that = this, data = {};
783
- Object.keys(ev.data).forEach((key) => {
784
- if (that.data.hasOwnProperty(key))
785
- data[key] = ev.data[key];
786
- });
787
- if (JSON.stringify(data) !== JSON.stringify(that.data))
788
- Object.assign(that.data, data);
789
- }
790
- }
791
- function getPlaceholderElements(target) {
792
- let elements = (target instanceof HTMLElement ? [target] : [])
793
- .concat([...target.querySelectorAll('*')])
794
- .filter((e) => !!getPlaceholders(e).length)
795
- .filter((e) => e.tagName !== 'STYLE');
796
- return elements;
797
- }
798
- function makePlaceholders(element) {
799
- getPlaceholderElements(element).forEach((e) => {
800
- if (e?._mc?._placeholders)
801
- return;
802
- DC.add(e, '_placeholders', new Placeholders(e));
803
- });
804
- }
805
- const classRepo = {};
806
- function makeObservable(val) {
807
- const Constructor = val.constructor, ConstructorName = Constructor.name;
808
- let ObservableClass = class extends Constructor {
809
- #notify = true;
810
- #callbacks = [];
811
- constructor(val) {
812
- super(val);
813
- this.constructor.callbacks = [];
814
- if (isObservableObject(val)) {
815
- Object.getOwnPropertyNames(val).forEach((key) => {
816
- this[key] = val[key];
817
- });
818
- }
819
- }
820
- get callbacks() {
821
- return this.#callbacks;
822
- }
823
- set callbacks(callbacks) {
824
- this.#callbacks = callbacks;
825
- }
826
- observe(f) {
827
- this.#callbacks.push(f);
828
- return this;
829
- }
830
- bind(target) {
831
- const that = this, iso = isObservableObject(that.valueOf());
832
- if (iso) {
833
- makePlaceholders(target);
834
- const placeholders = [
835
- ...target.querySelectorAll('[_mc]'),
836
- ].filter((e) => !!e?._mc?._placeholders);
837
- const func = function callback(data) {
838
- let d = flattenObject(data);
839
- placeholders.forEach((e) => {
840
- if (!e)
841
- return;
842
- e._mc.trigger('data', d);
843
- });
844
- };
845
- that.#callbacks.push(func);
846
- that.notify();
847
- }
848
- else {
849
- console.warn('IGNORED - cannot bind a non-Object to the dom, IS:', typeof that.valueOf(), that);
850
- }
851
- return this;
852
- }
853
- notify(notify) {
854
- let that = this, data = isObservableObject(that.valueOf()) &&
855
- that.valueOf() instanceof Array === false
856
- ? structuredClone(Object.assign({}, that))
857
- : that.valueOf();
858
- if (notify !== undefined) {
859
- that.#notify = notify;
860
- }
861
- that.#callbacks.forEach((f) => {
862
- f(data);
863
- });
864
- return that;
865
- }
866
- };
867
- classRepo[ConstructorName] = ObservableClass;
868
- return ObservableClass;
869
- }
870
- function getConstructor(val) {
871
- let key = val.constructor.name;
872
- return classRepo[key] || makeObservable(val);
873
- }
874
- const observe = (target, propertyName) => {
875
- let keys = !propertyName
876
- ? [...Object.getOwnPropertyNames(target)]
877
- : [propertyName];
878
- keys.forEach((key) => {
879
- if (target.hasOwnProperty(key)
880
- && typeof target[key] !== 'function'
881
- && !target?.[key]?.constructor?.prototype?.observe) {
882
- if (key[0] === '_' || target?.[key] === undefined)
883
- return target;
884
- let val = target[key];
885
- let o = new (getConstructor(val))(val);
886
- Object.defineProperty(target, key, {
887
- enumerable: true,
888
- get() {
889
- if (isObservableObject(o.valueOf())) {
890
- let check = structuredClone(Object.assign({}, o));
891
- setTimeout(debounce(function checkChanges() {
892
- let state = structuredClone(Object.assign({}, o));
893
- if (!deepEqual(state, check)) {
894
- o.notify();
895
- }
896
- }, 0), 0);
897
- }
898
- return o;
899
- },
900
- set(val) {
901
- if (typeof val === typeof o.valueOf()) {
902
- let iso = isObservableObject(o.valueOf()) &&
903
- o.valueOf() instanceof Array === false;
904
- if (iso) {
905
- let old = structuredClone(Object.assign({}, o));
906
- if (o?.constructor?.prototype?.observe === undefined) {
907
- o = new (getConstructor(val))(structuredClone(Object.assign({}, val)));
908
- copyGettersSetters(val, o);
909
- o.seal();
910
- }
911
- Object.assign(o, val);
912
- setTimeout(debounce(function checkChanges() {
913
- let state = structuredClone(Object.assign({}, o));
914
- if (!deepEqual(state, old)) {
915
- o.notify();
916
- }
917
- }, 0), 0);
918
- }
919
- else {
920
- let old = o.valueOf(), callbacks = o.callbacks;
921
- if (val !== old) {
922
- o = new (getConstructor(val))(val);
923
- o.callbacks = callbacks;
924
- o.notify();
925
- }
926
- }
927
- }
928
- else {
929
- console.warn('IGNORED - cannot change observable types, IS:', typeof o.valueOf(), o, '- CANNOT BECOME:', typeof val);
930
- }
931
- },
932
- });
933
- target[key] = val;
934
- }
935
- ;
936
- });
937
- return target;
938
- };
939
-
940
- ;// ./build/formValues.js
941
-
942
-
943
-
944
-
945
- const getInputName = (e) => {
946
- return e.tagName.toLowerCase();
947
- };
948
- class InputBase {
949
- constructor(e) { }
950
- }
951
- class RadioHandler extends InputBase {
952
- #e;
953
- constructor(e) {
954
- super(e);
955
- this.#e = e;
956
- }
957
- get val() {
958
- let ret = new FormData(this.#e.form).get(this.#e.name);
959
- return ret;
960
- }
961
- set val(value) {
962
- let arr = [
963
- ...this.#e.form.querySelectorAll(`input[type="radio"][name="${this.#e.name}"]`),
964
- ];
965
- arr
966
- .filter((e) => e.getAttribute('value') === value)
967
- .shift().checked = true;
968
- }
969
- }
970
- class CheckboxHandler extends InputBase {
971
- #e;
972
- constructor(e) {
973
- super(e);
974
- this.#e = e;
975
- }
976
- get val() {
977
- return this.#e.checked;
978
- }
979
- set val(value) {
980
- this.#e.checked = value;
981
- }
982
- }
983
- class InputHandler extends InputBase {
984
- #e;
985
- constructor(e) {
986
- super(e);
987
- this.#e = e;
988
- }
989
- get val() {
990
- return this.#e.value;
991
- }
992
- set val(value) {
993
- this.#e.value = value;
994
- }
995
- }
996
- class SelectHandler extends InputBase {
997
- #e;
998
- #multi = false;
999
- constructor(e) {
1000
- super(e);
1001
- this.#e = e;
1002
- this.#multi = e.multiple;
1003
- }
1004
- get val() {
1005
- const that = this, ret = [];
1006
- [...that.#e.querySelectorAll('option')]
1007
- .filter((o) => o.selected)
1008
- .forEach((o) => {
1009
- ret.push(o.value);
1010
- });
1011
- if (this.#multi)
1012
- return ret;
1013
- return ret.length ? ret[0] : '';
1014
- }
1015
- set val(value) {
1016
- const that = this;
1017
- value = typeof value === 'string' ? [value] : value;
1018
- [...that.#e.querySelectorAll('option')].forEach((o) => {
1019
- if (value.indexOf(o.value) > -1) {
1020
- o.selected = true;
1021
- }
1022
- else {
1023
- o.selected = false;
1024
- }
1025
- });
1026
- }
1027
- }
1028
- class TextAreaHandler extends InputBase {
1029
- #e;
1030
- constructor(e) {
1031
- super(e);
1032
- this.#e = e;
1033
- }
1034
- get val() {
1035
- return this.#e.value || '';
1036
- }
1037
- set val(value) {
1038
- this.#e.value = value;
1039
- }
1040
- }
1041
- const getInputHandlers = (e) => {
1042
- let inputList = [
1043
- ...(e || document).querySelectorAll('input,select,textarea'),
1044
- ], handlers = {};
1045
- inputList.forEach((i) => {
1046
- const name = i.getAttribute('name');
1047
- if (name) {
1048
- let handler = false;
1049
- switch (getInputName(i)) {
1050
- case 'input':
1051
- switch (i.type) {
1052
- case 'radio':
1053
- handler = new RadioHandler(i);
1054
- break;
1055
- case 'checkbox':
1056
- handler = new CheckboxHandler(i);
1057
- break;
1058
- default:
1059
- handler = new InputHandler(i);
1060
- }
1061
- break;
1062
- case 'select':
1063
- handler = new SelectHandler(i);
1064
- break;
1065
- case 'textarea':
1066
- handler = new TextAreaHandler(i);
1067
- break;
1068
- default:
1069
- console.warn('handler missing:', name, 'for', i.tagName.toLowerCase(), i);
1070
- break;
1071
- }
1072
- if (handler) {
1073
- DC.add(i, name, handler);
1074
- Object.defineProperty(handlers, name, {
1075
- enumerable: true,
1076
- configurable: true,
1077
- get: () => {
1078
- return handler.val;
1079
- },
1080
- set: (value) => {
1081
- if (handler.val !== value) {
1082
- handler.val = value;
1083
- }
1084
- },
1085
- });
1086
- }
1087
- }
1088
- });
1089
- return handlers;
1090
- };
1091
- function formValues(targetObject, propertyName, dom) {
1092
- let handlers = getInputHandlers(dom);
1093
- targetObject[propertyName] = Object.assign({}, handlers);
1094
- observe(targetObject, propertyName);
1095
- copyGettersSetters(handlers, targetObject[propertyName]);
1096
- [...dom.querySelectorAll('input, textarea, select')].forEach((input) => {
1097
- addListener(input, 'input', (ev) => {
1098
- targetObject[propertyName].notify();
1099
- });
1100
- });
1101
- }
1102
-
1103
- ;// ./build/microcomponents.js
1104
-
1105
-
1106
-
1107
-
1108
-
1109
-
1110
-
1111
-
1112
- /******/ return __webpack_exports__;
1113
- /******/ })()
1114
- ;
1115
- });
1
+ "use strict";
2
+ export * from './helpers.js';
3
+ export * from './MC.js';
4
+ export * from './McEvent.js';
5
+ export * from './elements.js';
6
+ export * from './observables.js';
7
+ export * from './formValues.js';
8
+ //# sourceMappingURL=microcomponents.js.map