UNPKG

@twobirds/microcomponents

Version:

Micro Components Organization Class

1 lines 15.6 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.microcomponents=t():e.microcomponents=t()}(this,(()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function r(e){return e&&e.constructor&&e.constructor===Object}function n(e){let t={};return[...Object.keys(e)].sort().forEach((o=>{r(e[o])?t[o]=n(e[o]):t[o]=e[o]})),t}function o(e,t=!0){let r={};return[...Object.getOwnPropertyNames(e)].forEach((t=>{if(e[t]&&e[t].constructor&&e[t].constructor===Object){const n=o(e[t],!1);for(const e in n)r[t+"."+e]=n[e]}else r[t]=e[t]})),t?n(r):r}function c(e,t){return JSON.stringify(o(e))===JSON.stringify(o(t))}function s(e,t={}){let r=e.constructor===String?e.split("."):e;if(t&&r[0]&&t[r[0]])return t[r[0]].constructor===Object&&r.length>1?s(r.splice(1),t[r[0]]):t[r[0]];console.warn("ns",r[0],"not in",t)}function a(e,t){var n=Array.from(arguments);if(n.length>2){for(;n.length>1;)n[0]=a(n[0],n[1]),n.splice(1,1);return n[0]}if("string"==typeof e)e.match(/\{[^\{\}]*\}/g)?.forEach((function(r){var n=s(r.substring(1,r.length-1),t);void 0!==n&&(e=e.replace(r,n))}));else if(r(e))switch(e.constructor){case Object:Object.keys(e).forEach((function(r){e.hasOwnProperty(r)&&(e[r]=a(e[r],t))}));break;case Array:e.forEach((function(r,n,o){o[n]=a(e[n],t)}))}return e}function i(e){return e.split("-").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join("")}function l(e,t){let r;return()=>{clearTimeout(r),r=setTimeout((function(){e(...arguments)}),t)}}function u(e){let t=document.createElement("template");return e=e.replace(/<([A-Za-z0-9\-]*)([^>\/]*)(\/>)/gi,"<$1$2></$1>"),t.innerHTML=e,t.content.normalize(),Array.from(t.content.childNodes)}function d(e,t){const r=Object.getOwnPropertyDescriptors(e);for(const[e,n]of Object.entries(r))("get"in n||"set"in n)&&Object.defineProperty(t,e,n)}e.r(t),e.d(t,{DC:()=>k,MC:()=>C,McBase:()=>S,McEvent:()=>p,addListener:()=>v,autoload:()=>D,copyGettersSetters:()=>d,debounce:()=>l,deepEqual:()=>c,defineCE:()=>q,flattenObject:()=>o,formValues:()=>X,getCE:()=>$,htmlToElements:()=>u,isNativeObject:()=>r,kebabToPascal:()=>i,nameSpace:()=>s,observe:()=>Z,parse:()=>a,removeListener:()=>E,sortObject:()=>n});var f=new Function("try {return this===window;}catch(e){ return false;}");let m=new Set;f()&&Object.keys(HTMLElement.prototype).filter((e=>/^on/.test(e))).forEach((e=>m.add(e)));class p{#e;#t=!1;#r=!1;constructor(e,t={},r="l"){this.#e=e,this.data=t,this.bubble=r}get type(){return this.#e}get stopped(){return this.#t}get immediateStopped(){return this.#r}stopPropagation(){this.#t=!0}stopImmediatePropagation(){this.stopPropagation(),this.#r=!0}}var b=new Function("try {return this===window;}catch(e){ return false;}");let g=new Set;function h(e,t){let r=[];return e.forEach((e=>{if(e&&e instanceof HTMLElement){const n=e?._mc;!t&&n?r=r.concat(Object.values(e._mc)):t&&n&&n[t]&&r.push(n[t])}})),r}function y(e,t,r=!0){let n=[];for(;e;){if(e._mc&&(t?t&&e._mc[t]&&n.push(e._mc[t]):n=n.concat(Object.values(e._mc)),r))return n;e=e.parentNode}return n}function O(e){return e&&e instanceof HTMLElement}function v(e,t,r,n=!1,o=!1){let c={once:!1};n&&(c.capture=n),o&&(c.once=o),e.addEventListener(t,r,c)}function E(e,t,r){e.removeEventListener(t,r)}function w(e,t,r={}){let n=e;if(!n._mc){let t=k?.debug;k.debug=!1,n._mc=new k(e),k.debug=t,delete n._mc._mc}const o=n._mc;return t.length&&!o[t]&&(o[t]=r,e instanceof HTMLElement&&!e.getAttribute("_mc")&&e.setAttribute("_mc","")),r}function A(e,t){if(!t)return;const r=e?._mc||{};r&&r[t]&&delete r[t],!Object.keys(r).length&&e instanceof HTMLElement&&e.hasAttribute("_mc")&&e.removeAttribute("_mc")}function j(e,t,r={},n="l"){let o=e?._mc;if(!o)return;let c=t instanceof p?new p(t.type,t.data,"l"):new p(t,r,"l"),s="string"!=typeof t?t:new p(t,r,n);[...Object.values(o)].forEach((e=>{e?.trigger&&"function"==typeof e?.trigger&&e?.trigger(c)})),/[ud]/.test(s.bubble)&&_(e,s)}function _(e,t){/[ud]/.test(t.bubble)&&setTimeout((()=>{if(-1===t.bubble.indexOf("l")&&(t.bubble+="l"),t.bubble.indexOf("u")>-1){let r=y(e,"",!0)?.[0].target;r&&k.trigger(r,t)}t.bubble.indexOf("d")>-1&&new Set(e._mc.children().map((e=>e?.target))).forEach((e=>{e&&k.trigger(e,t)}))}),0)}b()&&Object.keys(HTMLElement.prototype).filter((e=>/^on/.test(e))).forEach((e=>g.add(e)));class S{#n;constructor(e,t=!1){var r;this.#n=new WeakRef(e||{}),(r=this).constructor!==k&&setTimeout((()=>{r.trigger("Init")}),0),function(e){if(!b()||e.constructor===k)return;const t=e.target;if(t instanceof HTMLElement){let r=e;Object.getOwnPropertyNames(r.constructor.prototype).filter((e=>/^on[A-Z]|one[A-Z]/.test(e)&&"function"==typeof r.constructor.prototype[e])).forEach((n=>{let o=/^one/.test(n),c=n.replace(/^on[e]{0,1}/,""),s=c.toLowerCase();o&&Object.defineProperty(e,"on"+c,{configurable:!0,enumerable:!1,writable:!0,value:e=>{r.constructor.prototype[n].bind(r)(e)}}),g.has("on"+s)&&v(t,s,(e=>{r.trigger(c,e)}),!1,o)}))}}(this)}get target(){return this.#n.deref()}}class C extends S{_mc={};constructor(e){super(e)}static trigger=j;trigger(e,t={},r="l"){let n=this;if(n.constructor===C||n.constructor===k){let o=e instanceof p?new p(e.type,e.data,"l"):new p(e,t,"l"),c="string"!=typeof e?e:new p(e,t,r);return[...Object.getOwnPropertyNames(n)].forEach((e=>{n[e]?.trigger&&"function"==typeof n[e]?.trigger&&n[e]?.trigger(o)})),void(/[ud]/.test(c.bubble)&&_(n.target,c))}if(n instanceof C||n instanceof k){const n=this,o="string"!=typeof e?e:new p(e,t,r),c="on"+o.type[0].toUpperCase()+o.type.slice(1);if(o.bubble.indexOf("l")>-1&&(o.immediateStopped||"function"!=typeof n[c]||(n[c](o),n.hasOwnProperty(c)&&delete n[c])),o.stopped||"l"===o.bubble)return n;/[ud]/.test(o.bubble)&&_(n.target,o)}}}class k extends S{_mc={};constructor(e,t=!1){super(e)}static add=w;static remove=A;static trigger=j;trigger(e,t={},r){C.prototype.trigger.call(this,e,t,r)}parent(e=""){let t=this.target;return O(t)?y(t.parentNode,e,!0):[]}ancestors(e=""){let t=this?.target;return O(t)?y(this.target.parentNode,e,!1):[]}children(e=""){let t=this?.target;if(!O(t))return[];const r=Math.random().toString().replace(".",""),n='[_mc]:not([temp_id="'+r+'"] [_mc] [_mc])';t.setAttribute("temp_id",r);const o=h([...t.querySelectorAll(n)],e);return t.removeAttribute("temp_id"),o}descendants(e=""){let t=this?.target;return O(t)?h([...t.querySelectorAll("*[_mc]")],e):[]}}const T=new Map,N=new Map;function L(e){const t="./"+e.split("-").join("/")+".js",r=document.createElement("script");return r.setAttribute("src",t),r.setAttribute("blocking","render"),r.async=!0,r.setAttribute("type","module"),r.setAttribute("name",e),r.setAttribute("loading",""),v(r,"load",(e=>{r.removeAttribute("loading"),r.setAttribute("loaded","")})),v(r,"error",(e=>{console.error("could not load Custom Element code from",t)})),r}function M(){[...document.querySelectorAll(":not(:defined)")].filter((e=>!!e&&!customElements.get(e.tagName.toLowerCase())&&!T.has(e.tagName.toLowerCase()))).forEach((e=>{const t=e.tagName.toLowerCase(),r=(t.split("-").join("/"),L(t));v(r,"load",(()=>{T.set(t,customElements.get(e.tagName.toLowerCase()))})),T.set(t,"loading"),document.head.append(r)})),[...document.querySelectorAll('[_mc]:not([_mc=""]')].filter((e=>!!e)).forEach((e=>{const t=e.getAttribute("_mc")?.split(" ").filter((e=>!!e))||[],r=t.filter((e=>!N.has(e)));r?.forEach((e=>{const t=L(e);v(t,"load",(()=>{return t=document.head.querySelector(`script[name="${e}"]`),void setTimeout((function(){const e=t.getAttribute("src"),r=t.getAttribute("name"),n=document.createElement("script");n.async=!0,n.setAttribute("type","module");const o=`\n\n\t\t\timport _ from "${e}";\n\t\t\timport { DC } from "./microcomponents.js";\n\n\t\t\tconst elements = Array.from(document.querySelectorAll('[_mc*="${r}"]')).filter( element => element instanceof HTMLElement );\n\n\t\t\telements.forEach((element) => {\n\t\t\t\t// add class to MCs repository\n\t\t\t\tautoload.state.MCs.set( '${r}', _ );\n\t\t\t\t// add instance to HTMLElement \n\t\t\t\tDC.add(element, _.name, new _(element));\n\t\t\t\t// remove instance name from elements "_mc" attribute\n\t\t\t\telement.setAttribute('_mc', element.getAttribute('_mc').replace('${r}', '').replace( /ww/g, ' ').trim()); \n\t\t\t});\n\n\t\t\tsetTimeout( () => {\n\t\t\t\tdocument.body.querySelector('script[name="${r}]"')?.remove();\n\t\t\t},0);\n\n\t\t`;n.innerHTML=o,document.body.append(n)}),0);var t})),N.set(e,"loading"),document.head.append(t)}));const n=t.filter((e=>N.has(e)&&!N.get(e).length));n?.forEach((t=>{setTimeout((()=>{k.add(e,t,new(D.state.MCs.get(t))(e)),e.getAttribute("_mc").replace("${elementName}","").replace(/\w\w/g," ").trim(),e.setAttribute("_mc")}),5)}))}))}let x=!1,P=null;function D(e=!0){return e?(x=e,P=new MutationObserver(M),setTimeout((()=>{P.observe(document.body,{childList:!0,subtree:!0}),M()}),5),window.autoload=window.autoload||D,x):(P?.disconnect(),P=null,x)}D.state={CEs:T,MCs:N};class H extends HTMLElement{constructor(){super()}connectedCallback(){k.trigger(this,"Connected")}disconnectedCallback(){k.trigger(this,"Disconnected")}adoptedCallback(){k.trigger(this,"Adopted")}attributeChangedCallback(e,t,r){k.trigger(this,"AttributeChanged",{name:e,oldValue:t,newValue:r})}}function q(e,t,r=[]){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 n=i(e);customElements.define(e,function(e,t){return Object.defineProperty(t,"name",{value:e})}(n,class extends H{instance;constructor(e){super();let r=new t(this,e);k.add(this,n,r)}static get observedAttributes(){return r}}))}function $(e){return customElements.get(e)}function I(e){return null!=e&&"object"==typeof e}function V(e){let t=new Set,r=/\{[^\{\}]*\}/g;return e.getAttributeNames().filter((t=>e.getAttribute(t)?.match(r))).forEach((n=>{new Set(e.getAttribute(n)?.match(r)).forEach((e=>t.add(e.replace(/[\{\}]/g,""))))})),[...e.childNodes].filter((e=>3===e.nodeType&&(e.nodeValue||"").match(r))).forEach((e=>{(e.nodeValue||"").match(r).forEach((e=>{t.add(e.replace(/[\{\}]/g,""))}))})),[...t].map((e=>e.replace(/[\{\}]/g,"")))}const F=[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement];class G extends k{data={};oldDisplay="";constructor(e){super(e);let t=this;V(e).forEach((e=>t.data[e]="")),Z(t),t.#o(),delete t._mc}#o(){let e=this,t=e.target,r=!1;t.getAttributeNames().filter((e=>t.getAttribute(e)?.match(/\{[^\{\}]*\}/g))).forEach((r=>{let n=new Set(t.getAttribute(r)?.match(/\{[^\{\}]*\}/g));var o;e.data.observe((o=t.getAttribute(r),e=>{let c=o;n.forEach((t=>{c=c.replace(t,e[t.replace(/[\{\}]/g,"")])})),t.setAttribute(r,c)}))})),[...t.childNodes].filter((e=>3===e.nodeType&&(e.nodeValue||"").match(/\{[^\{\}]*\}/g))).forEach((n=>{r=!0;let o=new Set(n.nodeValue.match(/\{[^\{\}]*\}/g));var c;e.data.observe((c=n.nodeValue,r=>{let s=c;o.forEach((e=>{s=s.replace(e,r[e.replace(/[\{\}]/g,"")])})),Object.keys(r).some((e=>!!r[e]))&&(e.oldDisplay?t.style=e.oldDisplay:t.removeAttribute("style"),delete e.oldDisplay),n.nodeValue=s})),e.oldDisplay=t.getAttribute("style)")||"",r&&!F.includes(t.constructor)&&"FIELDSET"!==t.tagName&&(t.style.display="none")}))}onData(e){let t=this,r={};Object.keys(e.data).forEach((n=>{t.data.hasOwnProperty(n)&&(r[n]=e.data[n])})),JSON.stringify(r)!==JSON.stringify(t.data)&&Object.assign(t.data,r)}}const J={};function R(e){let t=e.constructor.name;return J[t]||function(e){const t=e.constructor,r=t.name;let n=class extends t{#c=!0;#s=[];constructor(e){super(e),this.constructor.callbacks=[],I(e)&&Object.getOwnPropertyNames(e).forEach((t=>{this[t]=e[t]}))}get callbacks(){return this.#s}set callbacks(e){this.#s=e}observe(e){return this.#s.push(e),this}bind(e){const t=this;if(I(t.valueOf())){!function(e){var t;(t=e,(t instanceof HTMLElement?[t]:[]).concat([...t.querySelectorAll("*")]).filter((e=>!!V(e).length)).filter((e=>"STYLE"!==e.tagName))).forEach((e=>{e?._mc?._placeholders||k.add(e,"_placeholders",new G(e))}))}(e);const r=[...e.querySelectorAll("[_mc]")].filter((e=>!!e?._mc?._placeholders)),n=function(e){let t=o(e);r.forEach((e=>{e&&e._mc.trigger("data",t)}))};t.#s.push(n),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,r=I(t.valueOf())&&t.valueOf()instanceof Array==0?structuredClone(Object.assign({},t)):t.valueOf();return void 0!==e&&(t.#c=e),t.#s.forEach((e=>{e(r)})),t}};return J[r]=n,n}(e)}const Z=(e,t)=>((t?[t]:[...Object.getOwnPropertyNames(e)]).forEach((t=>{if(e.hasOwnProperty(t)&&"function"!=typeof e[t]&&!e?.[t]?.constructor?.prototype?.observe){if("_"===t[0]||void 0===e?.[t])return e;let r=e[t],n=new(R(r))(r);Object.defineProperty(e,t,{enumerable:!0,get(){if(I(n.valueOf())){let e=structuredClone(Object.assign({},n));setTimeout(l((function(){c(structuredClone(Object.assign({},n)),e)||n.notify()}),0),0)}return n},set(e){if(typeof e==typeof n.valueOf())if(I(n.valueOf())&&n.valueOf()instanceof Array==0){let t=structuredClone(Object.assign({},n));void 0===n?.constructor?.prototype?.observe&&(n=new(R(e))(structuredClone(Object.assign({},e))),d(e,n),n.seal()),Object.assign(n,e),setTimeout(l((function(){c(structuredClone(Object.assign({},n)),t)||n.notify()}),0),0)}else{let t=n.valueOf(),r=n.callbacks;e!==t&&(n=new(R(e))(e),n.callbacks=r,n.notify())}else console.warn("IGNORED - cannot change observable types, IS:",typeof n.valueOf(),n,"- CANNOT BECOME:",typeof e)}}),e[t]=r}})),e);class z{constructor(e){}}class B extends z{#a;constructor(e){super(e),this.#a=e}get val(){return new FormData(this.#a.form).get(this.#a.name)}set val(e){[...this.#a.form.querySelectorAll(`input[type="radio"][name="${this.#a.name}"]`)].filter((t=>t.getAttribute("value")===e)).shift().checked=!0}}class U extends z{#a;constructor(e){super(e),this.#a=e}get val(){return this.#a.checked}set val(e){this.#a.checked=e}}class W extends z{#a;constructor(e){super(e),this.#a=e}get val(){return this.#a.value}set val(e){this.#a.value=e}}class Y extends z{#a;#i=!1;constructor(e){super(e),this.#a=e,this.#i=e.multiple}get val(){const e=[];return[...this.#a.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.#a.querySelectorAll("option")].forEach((t=>{e.indexOf(t.value)>-1?t.selected=!0:t.selected=!1}))}}class K extends z{#a;constructor(e){super(e),this.#a=e}get val(){return this.#a.value||""}set val(e){this.#a.value=e}}const Q=e=>{let t=[...(e||document).querySelectorAll("input,select,textarea")],r={};return t.forEach((e=>{const t=e.getAttribute("name");if(t){let n=!1;switch((e=>e.tagName.toLowerCase())(e)){case"input":switch(e.type){case"radio":n=new B(e);break;case"checkbox":n=new U(e);break;default:n=new W(e)}break;case"select":n=new Y(e);break;case"textarea":n=new K(e);break;default:console.warn("handler missing:",t,"for",e.tagName.toLowerCase(),e)}n&&(k.add(e,t,n),Object.defineProperty(r,t,{enumerable:!0,configurable:!0,get:()=>n.val,set:e=>{n.val!==e&&(n.val=e)}}))}})),r};function X(e,t,r){let n=Q(r);e[t]=Object.assign({},n),Z(e,t),d(n,e[t]),[...r.querySelectorAll("input, textarea, select")].forEach((r=>{v(r,"input",(r=>{e[t].notify()}))}))}return t})()));