@twobirds/microcomponents 0.0.58 → 0.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/assets/test.html +1 -1
  2. package/dist/MC.d.ts +1 -1
  3. package/dist/MC.d.ts.map +1 -1
  4. package/dist/MC.min.js +71 -26
  5. package/dist/MC.ts +136 -34
  6. package/dist/elements.min.js +1 -1
  7. package/dist/formvValues.min.js +1 -1
  8. package/dist/microcomponents.min.js +1 -1
  9. package/dist/observables.min.js +1 -1
  10. package/dist/selectors.min.js +1 -1
  11. package/dist/test.ts +17 -1
  12. package/package.json +3 -3
  13. package/public/MC.js +71 -26
  14. package/public/MC.js.map +1 -1
  15. package/public/MC.min.js +71 -26
  16. package/public/documentation/observables.md +1 -1
  17. package/public/elements.min.js +1 -1
  18. package/public/formvValues.min.js +1 -1
  19. package/public/microcomponents.min.js +1 -1
  20. package/public/observables.min.js +1 -1
  21. package/public/selectors.min.js +1 -1
  22. package/public/src/MC.ts +136 -34
  23. package/public/src/test.ts +17 -1
  24. package/public/test/child.js +15 -0
  25. package/public/test/child.js.map +1 -0
  26. package/public/test/grandchild.js +15 -0
  27. package/public/test/grandchild.js.map +1 -0
  28. package/public/test/grandparent.js +15 -1
  29. package/public/test/grandparent.js.map +1 -0
  30. package/public/test/greatgrandchild.js +29 -0
  31. package/public/test/greatgrandchild.js.map +1 -0
  32. package/public/test/parent.js +15 -0
  33. package/public/test/parent.js.map +1 -0
  34. package/public/test/testform.js +141 -1
  35. package/public/test/testform.js.map +1 -0
  36. package/public/test/testmc.js +10 -0
  37. package/public/test/testmc.js.map +1 -0
  38. package/public/test.html +1 -1
  39. package/public/test.js +4 -1
  40. package/public/test.js.map +1 -1
  41. package/src/MC.ts +136 -34
  42. package/src/test/testmc.ts +11 -0
  43. package/src/test.ts +17 -1
  44. package/webpack.config.js +39 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parent.js","sourceRoot":"","sources":["../../src/test/parent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,QAAQ,CACP,aAAa,EAEb,MAAM,MAAO,SAAQ,EAAE;IACtB,YAAY,MAAmB;QAC9B,KAAK,CAAC,MAAM,CAAC,CAAC;IACf,CAAC;IAED,WAAW;QACV,IAAI,IAAI,GAAG,IAAI,CAAC;QAEhB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,KAAM,EAAE,CAAC,CAAC;QAClC,CAAC;IACF,CAAC;CACD,CACD,CAAC;AAEF,MAAM,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC"}
@@ -1 +1,141 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.TestTestform=t():e.TestTestform=t()}(self,(()=>(()=>{"use strict";var e=new Function("try {return this===window;}catch(e){ return false;}");let t=new Set;e()&&Object.keys(HTMLElement.prototype).filter((e=>/^on/.test(e))).forEach((e=>t.add(e)));class n{#e;#t=!1;#n=!1;constructor(e,t={},n="l"){this.#e=e,this.data=t,this.bubble=n}get type(){return this.#e}get stopped(){return this.#t}get immediateStopped(){return this.#n}stopPropagation(){this.#t=!0}stopImmediatePropagation(){this.stopPropagation(),this.#n=!0}}var a=new Function("try {return this===window;}catch(e){ return false;}");let l=new Set;function r(e,t){let n=[];return e.forEach((e=>{if(e&&e instanceof HTMLElement){const a=e?._mc;!t&&a?n=n.concat(Object.values(e._mc)):t&&a&&a[t]&&n.push(a[t])}})),n}function o(e,t,n=!0){let a=[];for(;e;){if(e._mc&&(t?t&&e._mc[t]&&a.push(e._mc[t]):a=a.concat(Object.values(e._mc)),n))return a;e=e.parentNode}return a}function i(e){return e&&e instanceof HTMLElement}function s(e,t,n,a=!1,l=!1){let r={once:!1};a&&(r.capture=a),l&&(r.once=l),e.addEventListener(t,n,r)}function c(e,t,n={}){let a=e;if(!a._mc){let t=m?.debug;m.debug=!1,a._mc=new m(e),m.debug=t,delete a._mc._mc}const l=a._mc;return t.length&&!l[t]&&(l[t]=n,e instanceof HTMLElement&&e.setAttribute("_mc","")),n}function u(e,t){if(!t)return;const n=e?._mc||{};n&&n[t]&&delete n[t],!Object.keys(n).length&&e instanceof HTMLElement&&e.hasAttribute("_mc")&&e.removeAttribute("_mc")}function p(e,t,a={},l="l"){let r=e?._mc;if(!r)return;let o=t instanceof n?new n(t.type,t.data,"l"):new n(t,a,"l"),i="string"!=typeof t?t:new n(t,a,l);[...Object.values(r)].forEach((e=>{e?.trigger&&"function"==typeof e?.trigger&&e?.trigger(o)})),/[ud]/.test(i.bubble)&&d(e,i)}function d(e,t){/[ud]/.test(t.bubble)&&setTimeout((()=>{if(-1===t.bubble.indexOf("l")&&(t.bubble+="l"),t.bubble.indexOf("u")>-1){let n=o(e,"",!0)?.[0].target;n&&m.trigger(n,t)}t.bubble.indexOf("d")>-1&&new Set(e._mc.children().map((e=>e?.target))).forEach((e=>{e&&m.trigger(e,t)}))}),0)}a()&&Object.keys(HTMLElement.prototype).filter((e=>/^on/.test(e))).forEach((e=>l.add(e)));class b{#a;constructor(e,t=!1){var n;this.#a=new WeakRef(e||{}),(n=this).constructor!==m&&setTimeout((()=>{n.trigger("Init")}),0),function(e){if(!a()||e.constructor===m)return;const t=e.target;if(t instanceof HTMLElement){let n=e;Object.getOwnPropertyNames(n.constructor.prototype).filter((e=>/^on[A-Z]|one[A-Z]/.test(e)&&"function"==typeof n.constructor.prototype[e])).forEach((a=>{let r=/^one/.test(a),o=a.replace(/^on[e]{0,1}/,""),i=o.toLowerCase();r&&Object.defineProperty(e,"on"+o,{configurable:!0,enumerable:!1,writable:!0,value:e=>{n.constructor.prototype[a].bind(n)(e)}}),l.has("on"+i)&&s(t,i,(e=>{n.trigger(o,e)}),!1,r)}))}}(this)}get target(){return this.#a.deref()}}class f extends b{_mc={};constructor(e){super(e)}static trigger=p;trigger(e,t={},a="l"){let l=this;if(l.constructor===f||l.constructor===m){let r=e instanceof n?new n(e.type,e.data,"l"):new n(e,t,"l"),o="string"!=typeof e?e:new n(e,t,a);return[...Object.getOwnPropertyNames(l)].forEach((e=>{l[e]?.trigger&&"function"==typeof l[e]?.trigger&&l[e]?.trigger(r)})),void(/[ud]/.test(o.bubble)&&d(l.target,o))}if(l instanceof f||l instanceof m){const l=this,r="string"!=typeof e?e:new n(e,t,a),o="on"+r.type[0].toUpperCase()+r.type.slice(1);if(r.bubble.indexOf("l")>-1&&(r.immediateStopped||"function"!=typeof l[o]||(l[o](r),l.hasOwnProperty(o)&&delete l[o])),r.stopped||"l"===r.bubble)return l;/[ud]/.test(r.bubble)&&d(l.target,r)}}}class m extends b{_mc={};constructor(e,t=!1){super(e)}static add=c;static remove=u;static trigger=p;trigger(e,t={},n){f.prototype.trigger.call(this,e,t,n)}parent(e=""){let t=this.target;return i(t)?o(t.parentNode,e,!0):[]}ancestors(e=""){let t=this?.target;return i(t)?o(this.target.parentNode,e,!1):[]}children(e=""){let t=this?.target;if(!i(t))return[];const n=Math.random().toString().replace(".",""),a='[_mc]:not([temp_id="'+n+'"] [_mc] [_mc])';t.setAttribute("temp_id",n);const l=r([...t.querySelectorAll(a)],e);return t.removeAttribute("temp_id"),l}descendants(e=""){let t=this?.target;return i(t)?r([...t.querySelectorAll("*[_mc]")],e):[]}}function g(e){let t={};return[...Object.keys(e)].sort().forEach((n=>{var a;(a=e[n])&&a.constructor&&a.constructor===Object?t[n]=g(e[n]):t[n]=e[n]})),t}function h(e,t=!0){let n={};return[...Object.getOwnPropertyNames(e)].forEach((t=>{if(e[t]&&e[t].constructor&&e[t].constructor===Object){const a=h(e[t],!1);for(const e in a)n[t+"."+e]=a[e]}else n[t]=e[t]})),t?g(n):n}function y(e,t){return JSON.stringify(h(e))===JSON.stringify(h(t))}function v(e,t){let n;return()=>{clearTimeout(n),n=setTimeout((function(){e(...arguments)}),t)}}function O(e,t){const n=Object.getOwnPropertyDescriptors(e);for(const[e,a]of Object.entries(n))("get"in a||"set"in a)&&Object.defineProperty(t,e,a)}new Map;class w extends HTMLElement{constructor(){super()}connectedCallback(){m.trigger(this,"Connected")}disconnectedCallback(){m.trigger(this,"Disconnected")}adoptedCallback(){m.trigger(this,"Adopted")}attributeChangedCallback(e,t,n){m.trigger(this,"AttributeChanged",{name:e,oldValue:t,newValue:n})}}function x(e){return null!=e&&"object"==typeof e}function E(e){let t=new Set,n=/\{[^\{\}]*\}/g;return e.getAttributeNames().filter((t=>e.getAttribute(t)?.match(n))).forEach((a=>{new Set(e.getAttribute(a)?.match(n)).forEach((e=>t.add(e.replace(/[\{\}]/g,""))))})),[...e.childNodes].filter((e=>3===e.nodeType&&(e.nodeValue||"").match(n))).forEach((e=>{(e.nodeValue||"").match(n).forEach((e=>{t.add(e.replace(/[\{\}]/g,""))}))})),[...t].map((e=>e.replace(/[\{\}]/g,"")))}const k=[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement];class A extends m{data={};oldDisplay="";constructor(e){super(e);let t=this;E(e).forEach((e=>t.data[e]="")),j(t),t.#l(),delete t._mc}#l(){let e=this,t=e.target,n=!1;t.getAttributeNames().filter((e=>t.getAttribute(e)?.match(/\{[^\{\}]*\}/g))).forEach((n=>{let a=new Set(t.getAttribute(n)?.match(/\{[^\{\}]*\}/g));var l;e.data.observe((l=t.getAttribute(n),e=>{let r=l;a.forEach((t=>{r=r.replace(t,e[t.replace(/[\{\}]/g,"")])})),t.setAttribute(n,r)}))})),[...t.childNodes].filter((e=>3===e.nodeType&&(e.nodeValue||"").match(/\{[^\{\}]*\}/g))).forEach((a=>{n=!0;let l=new Set(a.nodeValue.match(/\{[^\{\}]*\}/g));var r;e.data.observe((r=a.nodeValue,n=>{let o=r;l.forEach((e=>{o=o.replace(e,n[e.replace(/[\{\}]/g,"")])})),Object.keys(n).some((e=>!!n[e]))&&(e.oldDisplay?t.style=e.oldDisplay:t.removeAttribute("style"),delete e.oldDisplay),a.nodeValue=o})),e.oldDisplay=t.getAttribute("style)")||"",n&&!k.includes(t.constructor)&&"FIELDSET"!==t.tagName&&(t.style.display="none")}))}onData(e){let t=this,n={};Object.keys(e.data).forEach((a=>{t.data.hasOwnProperty(a)&&(n[a]=e.data[a])})),JSON.stringify(n)!==JSON.stringify(t.data)&&Object.assign(t.data,n)}}const j=(e,t)=>((t?[t]:[...Object.getOwnPropertyNames(e)]).forEach((t=>{if("_"===t[0]||void 0===e?.[t])return e;let n,a=e[t];if(!a.prototype)switch(typeof a){case"string":n=String;break;case"number":n=Number;break;case"boolean":n=Boolean;break;case"object":n=a instanceof Array?Array:Object;break;default:return}let l=class extends n{#r=!0;constructor(e){super(e),this.constructor.callbacks=[],x(e)&&Object.getOwnPropertyNames(e).forEach((t=>{this[t]=e[t]}))}observe(e){return this.constructor.callbacks.push(e),this}bind(e){const t=this;if(x(t.valueOf())){!function(e){var t;(t=e,(t instanceof HTMLElement?[t]:[]).concat([...t.querySelectorAll("*")]).filter((e=>!!E(e).length)).filter((e=>"STYLE"!==e.tagName))).forEach((e=>{e?._mc?._placeholders||m.add(e,"_placeholders",new A(e))}))}(e);const n=[...e.querySelectorAll("[_mc]")].filter((e=>!!e?._mc?._placeholders)),a=function(e){let t=h(e);n.forEach((e=>{e&&e._mc.trigger("data",t)}))};t.constructor.callbacks.push(a),t.notify()}else console.warn("IGNORED - cannot bind a non-Object to the dom, IS:",typeof t.valueOf(),t);return this}notify(e){let t=this,n=x(t.valueOf())&&t.valueOf()instanceof Array==0?structuredClone(Object.assign({},t)):t.valueOf();return void 0!==e&&(t.#r=e),t.constructor.callbacks.forEach((e=>{e(n)})),t}},r=new l(a);Object.defineProperty(e,t,{enumerable:!0,get(){if(x(r.valueOf())){let e=structuredClone(Object.assign({},r));setTimeout(v((function(){y(structuredClone(Object.assign({},r)),e)||r.notify()}),0),0)}return r},set(e){if(typeof e==typeof r.valueOf())if(x(r.valueOf())&&r.valueOf()instanceof Array==0){let t=structuredClone(Object.assign({},r));r instanceof l==0&&(r=new l(structuredClone(Object.assign({},e))),O(e,r),r.seal()),Object.assign(r,e),setTimeout(v((function(){y(structuredClone(Object.assign({},r)),t)||r.notify()}),0),0)}else{let t=r.valueOf(),n=r.constructor.callbacks;r=new l(e),r.constructor.callbacks=n,e!==t&&r.notify()}else console.warn("IGNORED - cannot change observable types, IS:",typeof r.valueOf(),r,"- CANNOT BECOME:",typeof e)}}),e[t]=a})),e);class S{constructor(e){}}class _ extends S{#o;constructor(e){super(e),this.#o=e}get val(){return new FormData(this.#o.form).get(this.#o.name)}set val(e){[...this.#o.form.querySelectorAll(`input[type="radio"][name="${this.#o.name}"]`)].filter((t=>t.getAttribute("value")===e)).shift().checked=!0}}class T extends S{#o;constructor(e){super(e),this.#o=e}get val(){return this.#o.checked}set val(e){this.#o.checked=e}}class N extends S{#o;constructor(e){super(e),this.#o=e}get val(){return this.#o.value}set val(e){this.#o.value=e}}class C extends S{#o;#i=!1;constructor(e){super(e),this.#o=e,this.#i=e.multiple}get val(){const e=[];return[...this.#o.querySelectorAll("option")].filter((e=>e.selected)).forEach((t=>{e.push(t.value)})),this.#i?e:e.length?e[0]:""}set val(e){e="string"==typeof e?[e]:e,[...this.#o.querySelectorAll("option")].forEach((t=>{e.indexOf(t.value)>-1?t.selected=!0:t.selected=!1}))}}class I extends S{#o;constructor(e){super(e),this.#o=e}get val(){return this.#o.value||""}set val(e){this.#o.value=e}}return function(e,t,n=[]){if(customElements.get(e))return void console.warn(`IGNORED: Custom element "${e}" is already defined!`);if(!e.includes("-"))throw new Error('createCustomElement: tagName must contain at least one hyphen ("-").');let a=e.split("-").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join("");customElements.define(e,function(e,t){return Object.defineProperty(t,"name",{value:e})}(a,class extends w{instance;constructor(e){super();let n=new t(this,e);m.add(this,a,n)}static get observedAttributes(){return n}}))}("test-testform",class extends m{data;constructor(e){super(e);const t=this;delete t._mc;let n=t.target.attachShadow({mode:"open"});n.innerHTML=`<style>${t.css}</style>${t.template}`,function(e,t,n){let a=(e=>{let t=[...(e||document).querySelectorAll("input,select,textarea")],n={};return t.forEach((e=>{const t=e.getAttribute("name");if(t){let a=!1;switch((e=>e.tagName.toLowerCase())(e)){case"input":switch(e.type){case"radio":a=new _(e);break;case"checkbox":a=new T(e);break;default:a=new N(e)}break;case"select":a=new C(e);break;case"textarea":a=new I(e);break;default:console.warn("handler missing:",t,"for",e.tagName.toLowerCase(),e)}a&&(m.add(e,t,a),Object.defineProperty(n,t,{enumerable:!0,configurable:!0,get:()=>a.val,set:e=>{a.val!==e&&(a.val=e)}}))}})),n})(n);e[t]=Object.assign({},a),j(e,t),O(a,e[t]),[...n.querySelectorAll("input, textarea, select")].forEach((n=>{s(n,"keyup",(n=>{e[t].notify()})),s(n,"change",(n=>{e[t].notify()})),s(n,"select",(n=>{e[t].notify()}))}))}(t,"data",n),t.data.bind(n)}get template(){return'\n <form>\n \x3c!-- sample form to start with --\x3e\n <fieldset>\n <legend>Inputs</legend>\n <label>text</label><input type="text" name="textInput" value="Hallo" />&nbsp;<strong>2wB:&nbsp;</strong>{textInput}\n <label>color</label><input type="color" name="colorInput" value="" />\n <label>date</label><input type="date" name="dateInput" value="" />\n <label>datetime-local</label><input type="datetime-local" name="dtlInput" value="" />\n <label>email</label><input type="email" name="email" value="" />\n <label>file</label><input type="file" name="fileInput" value="" />\n <label>hidden</label><input type="hidden" name="hiddenInput" value="hiddenVal" />\n <label>month</label><input type="month" name="month" value="" />\n <label>number</label><input type="number" name="number" value="" />\n <label>password</label><input type="password" name="passInput" value="" />\n <label>range</label><input type="range" name="rangeInput" value="" />\n <label>search</label><input type="search" name="searchInput" value="" />\n <label>tel</label><input type="tel" name="telInput" value="" />\n <label>time</label><input type="time" name="timeInput" value="" />\n <label>url</label><input type="url" name="urlInput" value="" />\n <label>week</label><input type="week" name="weekInput" value="" />\n </fieldset>\n\n <fieldset>\n <legend>Selects</legend>\n\n <label>singleSelect</label>\n <select name="singleSelect">\n <option disabled selected value> -- select -- </option>\n <option value="1">Option 1</option>\n <option value="2">Option 2</option>\n <option value="3">Option 3</option>\n <option value="4">Option 4</option>\n </select>\n\n <label>multiSelect</label>\n <select name="multiSelect" multiple="multiple" type="select-multiple">\n <option value="1">Option 1</option>\n <option value="2" selected=true>Option 2</option>\n <option value="3">Option 3</option>\n <option value="4" selected=true>Option 4</option>\n </select>\n\n </fieldset>\n\n <fieldset>\n <legend>Radiobuttons&nbsp;<strong>2wB:&nbsp;</strong><span>{myRadio}</span></legend>\n\n <label>radio1</label><input type="radio" name="myRadio" value="radio1">\n <label>radio2</label><input type="radio" name="myRadio" value="radio2">\n <label>radio3</label><input type="radio" name="myRadio" value="radio3">\n\n </fieldset>\n\n <fieldset>\n <legend>Checkboxes</legend>\n <label>cb1</label><input type="checkbox" name="cb1">\n <label>cb2</label><input type="checkbox" name="cb2">\n <label>cb3</label><input type="checkbox" name="cb3">\n <label>cb4</label><input type="checkbox" name="cb4">\n <label>cb5</label><input type="checkbox" name="cb5">\n\n </fieldset>\n\n <fieldset>\n <legend>TextArea</legend>\n <label>textArea</label>\n <textarea name="textArea">abc</textarea>\n </fieldset>\n\n </form>\n '}get css(){return"\nlegend {\n display: inherit;\n margin: inherit;\n vertical-align: inherit;\n}\n\nlabel {\n display: inline;\n margin-top: 5px;\n margin-left: 5px;\n vertical-align: top;\n width: 10em;\n text-align: right;\n}\n\nlabel::before {\n content: ' ';\n display: block;\n}\n\nform input,\nform select,\nform textarea {\n margin-left: 5px;\n margin-top: 0px;\n display: inline;\n}\n\nform label + textarea {\n display: inline-block;\n margin-top: 3px;\n}\n\nform input + label {\n width: inherit;\n margin-top: 3px;\n text-align: left;\n}\n\nbody > form {\n display: block;\n}\n\nform fieldset {\n border: 1px solid darkslategrey;\n border-radius: 3px;\n margin: 0.5em 0;\n}\n "}}),{}})()));
1
+ 'use strict';
2
+ import { DC, defineCE, formValues } from '.././microcomponents.js';
3
+ defineCE('test-testform', class TestTestForm extends DC {
4
+ data;
5
+ constructor(target) {
6
+ super(target);
7
+ const that = this;
8
+ delete that._mc;
9
+ let shadow = that.target.attachShadow({ mode: 'open' });
10
+ shadow.innerHTML = `<style>${that.css}</style>${that.template}`;
11
+ formValues(that, 'data', shadow);
12
+ that.data.bind(shadow);
13
+ }
14
+ get template() {
15
+ return `
16
+ <form>
17
+ <!-- sample form to start with -->
18
+ <fieldset>
19
+ <legend>Inputs</legend>
20
+ <label>text</label><input type="text" name="textInput" value="Hallo" />&nbsp;<strong>2wB:&nbsp;</strong>{textInput}
21
+ <label>color</label><input type="color" name="colorInput" value="" />
22
+ <label>date</label><input type="date" name="dateInput" value="" />
23
+ <label>datetime-local</label><input type="datetime-local" name="dtlInput" value="" />
24
+ <label>email</label><input type="email" name="email" value="" />
25
+ <label>file</label><input type="file" name="fileInput" value="" />
26
+ <label>hidden</label><input type="hidden" name="hiddenInput" value="hiddenVal" />
27
+ <label>month</label><input type="month" name="month" value="" />
28
+ <label>number</label><input type="number" name="number" value="" />
29
+ <label>password</label><input type="password" name="passInput" value="" />
30
+ <label>range</label><input type="range" name="rangeInput" value="" />
31
+ <label>search</label><input type="search" name="searchInput" value="" />
32
+ <label>tel</label><input type="tel" name="telInput" value="" />
33
+ <label>time</label><input type="time" name="timeInput" value="" />
34
+ <label>url</label><input type="url" name="urlInput" value="" />
35
+ <label>week</label><input type="week" name="weekInput" value="" />
36
+ </fieldset>
37
+
38
+ <fieldset>
39
+ <legend>Selects</legend>
40
+
41
+ <label>singleSelect</label>
42
+ <select name="singleSelect">
43
+ <option disabled selected value> -- select -- </option>
44
+ <option value="1">Option 1</option>
45
+ <option value="2">Option 2</option>
46
+ <option value="3">Option 3</option>
47
+ <option value="4">Option 4</option>
48
+ </select>
49
+
50
+ <label>multiSelect</label>
51
+ <select name="multiSelect" multiple="multiple" type="select-multiple">
52
+ <option value="1">Option 1</option>
53
+ <option value="2" selected=true>Option 2</option>
54
+ <option value="3">Option 3</option>
55
+ <option value="4" selected=true>Option 4</option>
56
+ </select>
57
+
58
+ </fieldset>
59
+
60
+ <fieldset>
61
+ <legend>Radiobuttons&nbsp;<strong>2wB:&nbsp;</strong><span>{myRadio}</span></legend>
62
+
63
+ <label>radio1</label><input type="radio" name="myRadio" value="radio1">
64
+ <label>radio2</label><input type="radio" name="myRadio" value="radio2">
65
+ <label>radio3</label><input type="radio" name="myRadio" value="radio3">
66
+
67
+ </fieldset>
68
+
69
+ <fieldset>
70
+ <legend>Checkboxes</legend>
71
+ <label>cb1</label><input type="checkbox" name="cb1">
72
+ <label>cb2</label><input type="checkbox" name="cb2">
73
+ <label>cb3</label><input type="checkbox" name="cb3">
74
+ <label>cb4</label><input type="checkbox" name="cb4">
75
+ <label>cb5</label><input type="checkbox" name="cb5">
76
+
77
+ </fieldset>
78
+
79
+ <fieldset>
80
+ <legend>TextArea</legend>
81
+ <label>textArea</label>
82
+ <textarea name="textArea">abc</textarea>
83
+ </fieldset>
84
+
85
+ </form>
86
+ `;
87
+ }
88
+ get css() {
89
+ return `
90
+ legend {
91
+ display: inherit;
92
+ margin: inherit;
93
+ vertical-align: inherit;
94
+ }
95
+
96
+ label {
97
+ display: inline;
98
+ margin-top: 5px;
99
+ margin-left: 5px;
100
+ vertical-align: top;
101
+ width: 10em;
102
+ text-align: right;
103
+ }
104
+
105
+ label::before {
106
+ content: ' ';
107
+ display: block;
108
+ }
109
+
110
+ form input,
111
+ form select,
112
+ form textarea {
113
+ margin-left: 5px;
114
+ margin-top: 0px;
115
+ display: inline;
116
+ }
117
+
118
+ form label + textarea {
119
+ display: inline-block;
120
+ margin-top: 3px;
121
+ }
122
+
123
+ form input + label {
124
+ width: inherit;
125
+ margin-top: 3px;
126
+ text-align: left;
127
+ }
128
+
129
+ body > form {
130
+ display: block;
131
+ }
132
+
133
+ form fieldset {
134
+ border: 1px solid darkslategrey;
135
+ border-radius: 3px;
136
+ margin: 0.5em 0;
137
+ }
138
+ `;
139
+ }
140
+ });
141
+ //# sourceMappingURL=testform.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testform.js","sourceRoot":"","sources":["../../src/test/testform.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO,EAAE,EAAE,EAAE,QAAQ,EAAc,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAE/E,QAAQ,CACP,eAAe,EAEf,MAAM,YAAa,SAAQ,EAAE;IAC5B,IAAI,CAAU;IAEd,YAAY,MAAmB;QAC9B,KAAK,CAAC,MAAM,CAAC,CAAC;QAEd,MAAM,IAAI,GAAG,IAAI,CAAC;QAElB,OAAO,IAAI,CAAC,GAAG,CAAC;QAEhB,IAAI,MAAM,GAAI,IAAW,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;QAChE,MAAM,CAAC,SAAS,GAAG,UAAU,IAAI,CAAC,GAAG,WAAW,IAAI,CAAC,QAAQ,EAAE,CAAC;QAEhE,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAEhC,IAAI,CAAC,IAAmB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACxC,CAAC;IAED,IAAI,QAAQ;QACX,OAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAuEN,CAAC;IACZ,CAAC;IAED,IAAI,GAAG;QACN,OAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAiDL,CAAC;IACZ,CAAC;CACD,CACD,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { DC } from '../microcomponents.js';
2
+ export default class testmc extends DC {
3
+ constructor(target) {
4
+ super(target);
5
+ }
6
+ oneInit() {
7
+ console.log('testmc connected to DOM');
8
+ }
9
+ }
10
+ //# sourceMappingURL=testmc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testmc.js","sourceRoot":"","sources":["../../src/test/testmc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAE3C,MAAM,CAAC,OAAO,OAAO,MAAO,SAAQ,EAAE;IAClC,YAAY,MAAmB;QAC3B,KAAK,CAAC,MAAM,CAAC,CAAC;IAClB,CAAC;IAED,OAAO;QACH,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAC3C,CAAC;CACJ"}
package/public/test.html CHANGED
@@ -21,7 +21,7 @@
21
21
  </head>
22
22
  <body>
23
23
  <test-grandparent></test-grandparent>
24
- <test-testform></test-testform>
24
+ <test-testform _mc="test-testmc"></test-testform>
25
25
  Open the debugger, read console, then:<br />
26
26
  </body>
27
27
  </html>
package/public/test.js CHANGED
@@ -72,7 +72,10 @@ document.body.appendChild(fragment);
72
72
  setTimeout(() => {
73
73
  console.log('%c \n\nStress Test:\n\n %cInstancing %s web components (%s classes): %c %s ms.', 'font-weight: bold; color: black;', 'font-weight: normal;', max, max * 3, 'font-weight: bold; color: blue;', end - start);
74
74
  let element = document.querySelector('my-tag');
75
- console.log("\n\n%cInspect this tag:%c \n( ...to see the inner structure in the '._mc' property )\n\n %O %c %s", 'font-weight: bold;', 'font-weight: normal;', element, 'font-weight: bold;', '\n\nLook up code in the debugger: test.js\n\n');
75
+ console.log("\n\n%cInspect this tag:%c \n( ...to see the inner structure in the '._mc' property )\n\n %O %c %s", 'font-weight: bold;', 'font-weight: normal;', element, 'font-weight: bold;', '\n\nLook up code in the debugger: test.js\n');
76
+ let form = document.querySelector('test-testform');
77
+ let formData = form._mc.TestTestform.data;
78
+ console.log("\n\n%cRight-click this object and store it as a global variable:%c \n\n %O %c %s %c %s %c %s", 'font-weight: bold;', 'font-weight: normal;', formData, 'font-weight: bold;', '\n\nYou can then use e.g. \n\n', 'font-weight: normal;', ' temp0.textInput = "whatever"', 'font-weight: bold;', '\n\nto change the form contents.\n');
76
79
  DC.trigger(element, 'doSomething');
77
80
  }, 500);
78
81
  //# sourceMappingURL=test.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"test.js","sourceRoot":"","sources":["../src/test.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAEN,EAAE,EAEF,QAAQ,EACR,KAAK,EACL,OAAO,GAEP,MAAM,sBAAsB,CAAC;AAE9B,MAAM,UAAW,SAAQ,EAAE;IAC1B,aAAa,GAAgB,EAAE,CAAC;IAEhC,QAAQ,GAAY,IAAI,CAAC;IACzB,WAAW,GAAY,EAAE,CAAC;IAE1B,YACC,MAAmD,EACnD,YAAyB,EACzB,uBAAoC;QAEpC,KAAK,CAAC,MAAqB,CAAC,CAAC;QAC7B,IAAI,IAAI,GAAG,IAAI,CAAC;QAGhB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;QAEtB,OAAO,CAAC,IAAI,CAAC,CAAC;QAGd,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAGjC,IAAI,CAAC,QAAuB,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;YAC9C,IAAI,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC7C,IAAI,CAAC,WAAW,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;YACvD,CAAC;QACF,CAAC,CAAC,CAAC;QAEF,IAAI,CAAC,WAA0B,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAE/D,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAE1C,IAAI,CAAC,QAAuB,CAAC,MAAM,EAAE,CAAC;QAEvC,OAAO,IAAI,CAAC,GAAG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,CACV,8FAA8F,EAC9F,oBAAoB,EACpB,sBAAsB,EACtB,QAAQ,EACR,oBAAoB,EACpB,gCAAgC,EAChC,sBAAsB,EACtB,gCAAgC,EAChC,oBAAoB,EACpB,oCAAoC,CACpC,CAAC;IAGH,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;AACpC,CAAC,EAAE,GAAG,CAAC,CAAC"}
package/src/MC.ts CHANGED
@@ -111,7 +111,7 @@ function add(target: HTMLElement, key: string, element = {}): any {
111
111
  if (key.length && !_mc[key]) {
112
112
  _mc[key] = element;
113
113
  // add attribute if HTMLElement
114
- if (target instanceof HTMLElement) {
114
+ if (target instanceof HTMLElement && ! target.getAttribute('_mc') ) {
115
115
  target.setAttribute('_mc', '');
116
116
  }
117
117
  }
@@ -410,46 +410,145 @@ class DC extends McBase {
410
410
  }
411
411
  }
412
412
 
413
- export { addListener, removeListener, McBase, MC, DC, McEvent };
414
-
415
413
  let observer: MutationObserver | null = null;
416
- const unresolved = new Map();
417
414
 
418
- function loadit() {
419
- document
420
- .querySelectorAll(':not(:defined),[_mc]:not([_mc=""])')
415
+ /*
416
+ unresolvedCEs (code below this comment):
417
+
418
+ a repository (a hashmap) of undefined custom elements:
419
+ the name is the tagname of the micro component (like "my-custom-component")
420
+ if they are loading, the value is a script element
421
+ if they are loaded, the entry is deleted and the browser instanciates it automatically
422
+ if they cannot be loaded, the browser will throw an error
423
+
424
+ If the custom element ( defined by its tagname, like "my-custom-component") is not defined, it will be on-demand loaded:
425
+ The file name is assumed to be "/my/custom/component.js"
426
+ The file must define a custom element via the defineCE() function included in the "elements" module.
427
+ This function is a wrapper for customElementRegistry.define(), which you can also use directly in the imported code.
428
+
429
+ In general this behaves like a custom runtime import for custom elements in the browser.
430
+ The only difference is that the micro component is loaded only when needed, and not on page load.
431
+ */
432
+
433
+ const unresolvedCEs = new Map();
434
+
435
+ /*
436
+ MCs (code below this comment):
437
+ a repository (a hashmap) of micro components:
438
+ the name is the name of the micro component (like "my-mc")
439
+ if they are loading, the value is a script element
440
+ if they are loaded, the value is the micro component class itself
441
+
442
+ This is mostly used for old style progressive enhancement:
443
+ If the micro component ( defined in the HTMLElements "_mc" attribute, like "my-mc") is not defined, it will be on-demand loaded:
444
+ The file name is assumed to be "/my/mc.js"
445
+ The file needs to have a default export, and it should be a class that extends the DC class ( since it is in a HTMLElements attribute )
446
+
447
+ In general this behaves like a custom runtime import for classes in the browser.
448
+ The only difference is that the micro component is loaded only when needed, and not on page load.
449
+ */
450
+ const MCs = new Map();
451
+
452
+ function makeLoadScript( element: string ): HTMLScriptElement {
453
+
454
+ const fileName: string = '/' + element.split('-').join('/')+'.js';
455
+
456
+ const se: HTMLScriptElement = document.createElement('script');
457
+
458
+ se.setAttribute('src', fileName);
459
+ se.setAttribute('blocking', 'render');
460
+ se.async = true;
461
+ se.setAttribute('type', 'module');
462
+ se.setAttribute( 'name', element);
463
+ se.setAttribute( 'loading', '');
464
+
465
+ addListener( se, 'load', (ev) => {
466
+ // console.info('loaded MC', elementName);
467
+ se.removeAttribute( 'loading' );
468
+ se.setAttribute( 'loaded', '');
469
+ });
470
+
471
+ addListener( se, 'error', (ev) => {
472
+ console.error('could not load Custom Element code from', fileName);
473
+ });
474
+
475
+ return se;
476
+ }
477
+
478
+ function onLoadCallback( script: HTMLScriptElement ) {
479
+ // create callback script tag
480
+ setTimeout( function(){
481
+ // create callback script tag
482
+ const importFileName = script.getAttribute('src');
483
+ const elementName = script.getAttribute('name');
484
+
485
+ const se: HTMLScriptElement = document.createElement('script');
486
+
487
+ se.async = true;
488
+ se.setAttribute( 'type', 'module');
489
+
490
+ const code = /*javascript*/`
491
+ import _ from "${importFileName}";
492
+ import {DC} from "./microcomponents.js";
493
+
494
+ const elements = Array.from(document.querySelectorAll('[_mc*="${elementName}"]')).filter( element => element instanceof HTMLElement );
495
+
496
+ // console.log('elements', elements);
497
+ elements.forEach((element) => {
498
+ // console.log('DC, element,class', DC, element, _);
499
+ DC.add(element, _.name, new _(element));
500
+ element.setAttribute('_mc', element.getAttribute('_mc').replace('${elementName}', '').replace( /\w\w/g, ' ').trim());
501
+ });
502
+ setTimeout( () => {
503
+ // console.log('remove callback script tag', '${elementName}');
504
+ document.body.querySelector('script[name="${elementName}]"')?.remove();
505
+ },0);`;
506
+
507
+ se.innerHTML = code;
508
+ document.body.append(se);
509
+ }, 0);
510
+ }
511
+
512
+
513
+ function loadUndefinedMicroComponents() {
514
+
515
+ // load unresolved custom eleents
516
+ [ ...document.querySelectorAll(':not(:defined)') ] // undefined custom elements
517
+ .filter( (element) => !!element && !document.head.querySelector(`script[name="${element.tagName.toLowerCase()}"]`) )
421
518
  .forEach((el) => {
422
- const load: string[] = el.tagName.includes('-')
423
- ? [el.tagName.toLowerCase()]
424
- : el.getAttribute('_mc')!.trim().split(' ');
519
+ const elementName = el.tagName.toLowerCase(),
520
+ fileName: string = '/'+elementName.split('-').join('/')+'.js';
425
521
 
426
- load.forEach((elementName) => {
427
- let fileName: any = elementName.toLowerCase().split('-');
428
- fileName = fileName.join('/') + '.js';
522
+ const se: HTMLScriptElement = makeLoadScript( elementName );
429
523
 
430
- // autoload web components
431
- // TBD: _mc components
432
- if (
433
- el.tagName.includes('-') &&
434
- !unresolved.has(el.tagName.toLowerCase())
435
- ) {
436
- const se: HTMLScriptElement = document.createElement('script');
524
+ document.head.append(se);
437
525
 
438
- unresolved.set(elementName, fileName);
526
+ // instanciation of the micro component will be handled by the browser automatically
527
+ // module code must define the micro component class and add it to the customElementRegistry
528
+ });
439
529
 
440
- se.setAttribute('src', fileName);
441
- se.setAttribute('blocking', 'render');
442
- se.setAttribute('type', 'module');
443
- se.onload = () => {
444
- // console.info('loaded', s);
445
- unresolved.delete(elementName);
446
- //console.log(unresolved);
447
- };
530
+ [ ...document.querySelectorAll('[_mc]:not([_mc=""]') ] // undefined DOM components
531
+ .filter( (element) => !!element )
532
+ .forEach((el) => {
533
+ const elements = el.getAttribute('_mc')?.split(' ').filter( m => !!m ) || [];
534
+ const elementsToBeLoaded = elements.filter( m => !document.head.querySelector(`script[name="${m}"]`) );
535
+ const elementsAlreadyLoaded = elements.filter( m => !!document.head.querySelector(`script[name="${m}"][loaded]`) );
448
536
 
449
- document.head.append(se);
450
- }
537
+ // load MC components that do not exist yet
538
+ elementsToBeLoaded?.forEach( elementName => {
539
+ const se: HTMLScriptElement = makeLoadScript( elementName );
540
+
541
+ addListener( se, 'load', () => onLoadCallback( document.head.querySelector(`script[name="${elementName}"]`) as HTMLScriptElement) );
542
+
543
+ document.head.append(se);
544
+ });
545
+
546
+ // loading MC components already have callbacks attached
547
+
548
+ // MCs that are already loaded will trigger the onLoadCallback manually
549
+ elementsAlreadyLoaded?.forEach( elementName => {
550
+ onLoadCallback( document.head.querySelector(`script[name="${elementName}"]`) as HTMLScriptElement);
451
551
  });
452
- //console.log(unresolved);
453
552
  });
454
553
  }
455
554
 
@@ -463,12 +562,15 @@ export function autoload(enable: boolean = true): boolean {
463
562
  }
464
563
 
465
564
  autoloadEnabled = enable;
466
- observer = new MutationObserver(loadit);
565
+ observer = new MutationObserver(loadUndefinedMicroComponents);
467
566
 
468
567
  setTimeout(() => {
469
568
  observer!.observe(document.body, { childList: true, subtree: true });
470
- loadit();
569
+ loadUndefinedMicroComponents();
471
570
  }, 5);
472
571
 
473
572
  return autoloadEnabled;
474
573
  }
574
+
575
+ export { addListener, removeListener, McBase, MC, DC, McEvent };
576
+
@@ -0,0 +1,11 @@
1
+ import { DC } from '../microcomponents.js';
2
+
3
+ export default class testmc extends DC {
4
+ constructor(target: HTMLElement) {
5
+ super(target);
6
+ }
7
+
8
+ oneInit() {
9
+ console.log('testmc connected to DOM');
10
+ }
11
+ }
package/src/test.ts CHANGED
@@ -169,9 +169,25 @@ setTimeout(() => {
169
169
  'font-weight: normal;',
170
170
  element,
171
171
  'font-weight: bold;',
172
- '\n\nLook up code in the debugger: test.js\n\n'
172
+ '\n\nLook up code in the debugger: test.js\n'
173
173
  );
174
174
 
175
+ let form = ( document.querySelector('test-testform') as any);
176
+ let formData = form._mc.TestTestform.data;
177
+
178
+ console.log(
179
+ "\n\n%cRight-click this object and store it as a global variable:%c \n\n %O %c %s %c %s %c %s",
180
+ 'font-weight: bold;',
181
+ 'font-weight: normal;',
182
+ formData,
183
+ 'font-weight: bold;',
184
+ '\n\nYou can then use e.g. \n\n',
185
+ 'font-weight: normal;',
186
+ ' temp0.textInput = "whatever"',
187
+ 'font-weight: bold;',
188
+ '\n\nto change the form contents.\n'
189
+ );
190
+
175
191
  // will trigger the event on all micro components contained in <my-tag>
176
192
  DC.trigger(element, 'doSomething');
177
193
  }, 500);
package/webpack.config.js CHANGED
@@ -304,4 +304,43 @@ module.exports = [
304
304
  minimize: true, // Enable minification
305
305
  },
306
306
  },
307
+ /*
308
+ {
309
+ entry: './build/test/default.js',
310
+ mode: 'production',
311
+ output: {
312
+ path: path.resolve(__dirname, 'public/test'),
313
+ filename: 'default.js',
314
+ libraryTarget: 'umd',
315
+ library: 'default',
316
+ },
317
+ module: {
318
+ rules: [
319
+ {
320
+ // test: /\.tsx?$/,
321
+ use: [
322
+ {
323
+ loader: 'ts-loader',
324
+ options: {
325
+ transpileOnly: true, // Avoid type checking during webpack build
326
+ compilerOptions: {
327
+ declaration: false, // Generate .d.ts files
328
+ declarationMap: false, // Generate .d.ts.map files
329
+ outDir: 'build/types', // Output .d.ts and .d.ts.map to a different directory
330
+ },
331
+ },
332
+ },
333
+ ],
334
+ exclude: /node_modules/,
335
+ },
336
+ ],
337
+ },
338
+ resolve: {
339
+ extensions: ['.tsx', '.ts', '.js'],
340
+ },
341
+ optimization: {
342
+ minimize: true, // Enable minification
343
+ },
344
+ },
345
+ */
307
346
  ];