UNPKG

@zeix/ui-element

Version:

UIElement - a HTML-first library for reactive Web Components

4 lines (2 loc) 16.4 kB
var k,l=new Set,XH=0,QH=new Map,r,VH=()=>{r=void 0;let H=Array.from(QH.values());QH.clear();for(let K of H)K()},_H=()=>{if(r)cancelAnimationFrame(r);r=requestAnimationFrame(VH)};queueMicrotask(VH);var m=(H)=>{let K=new Set,B=H;return B.off=($)=>{K.add($)},B.cleanup=()=>{for(let $ of K)$();K.clear()},B},O=(H)=>{if(k&&!H.has(k)){let K=k;H.add(K),k.off(()=>{H.delete(K)})}},M=(H)=>{for(let K of H)if(XH)l.add(K);else K()},a=()=>{while(l.size){let H=Array.from(l);l.clear();for(let K of H)K()}},t=(H)=>{XH++;try{H()}finally{a(),XH--}},v=(H,K)=>{let B=k;k=K;try{H()}finally{k=B}},IH=(H,K)=>new Promise((B,$)=>{QH.set(K||Symbol(),()=>{try{B(H())}catch(Z){$(Z)}}),_H()});var z=(H)=>typeof H==="function",e=(H,K)=>Object.prototype.toString.call(H)===`[object ${K}]`,c=(H)=>H instanceof Error?H:Error(String(H));class f extends Error{constructor(H){super(`Circular dependency in ${H} detected`);this.name="CircularDependencyError"}}var YH="State",HH=(H)=>{let K=new Set,B=H,$={[Symbol.toStringTag]:YH,get:()=>{return O(K),B},set:(Z)=>{if(Object.is(B,Z))return;if(B=Z,M(K),V===B)K.clear()},update:(Z)=>{$.set(Z(B))}};return $},R=(H)=>e(H,YH);var V=Symbol(),_=(H)=>R(H)||g(H),D=(H)=>_(H)?H:yH(H)?KH(H):HH(H);var E="Computed",KH=(H)=>{let K=new Set,B=V,$,Z,L=!0,A=!1,J=!1,x=(G)=>{if(!Object.is(G,B))B=G,A=!0;$=void 0,L=!1},W=()=>{A=V!==B,B=V,$=void 0},X=(G)=>{let j=c(G);A=!$||j.name!==$.name||j.message!==$.message,B=V,$=j},Y=(G)=>(j)=>{if(J=!1,Z=void 0,G(j),A)M(K)},y=m(()=>{if(L=!0,Z?.abort("Aborted because source signal changed"),K.size)M(K);else y.cleanup()}),U=()=>v(()=>{if(J)throw new f("computed");if(A=!1,z(H)&&H.constructor.name==="AsyncFunction"){if(Z)return B;Z=new AbortController,Z.signal.addEventListener("abort",()=>{J=!1,Z=void 0,U()},{once:!0})}let G;J=!0;try{G=Z?H(Z.signal):H()}catch(j){if(j instanceof DOMException&&j.name==="AbortError")W();else X(j);J=!1;return}if(G instanceof Promise)G.then(Y(x),Y(X));else if(G==null||V===G)W();else x(G);J=!1},y);return{[Symbol.toStringTag]:E,get:()=>{if(O(K),a(),L)U();if($)throw $;return B}}},g=(H)=>e(H,E),yH=(H)=>z(H)&&H.length<2;function b(H){let{signals:K,ok:B,err:$=(J)=>{console.error(J)},nil:Z=()=>{}}=z(H)?{signals:[],ok:H}:H,L=!1,A=m(()=>v(()=>{if(L)throw new f("effect");L=!0;let J=[],x=!1,W=K.map((Y)=>{try{let y=Y.get();if(y===V)x=!0;return y}catch(y){return J.push(c(y)),V}}),X;try{X=x?Z():J.length?$(...J):B(...W)}catch(Y){X=$(c(Y))}finally{if(z(X))A.off(X)}L=!1},A));return A(),()=>A.cleanup()}var C=!1,UH="debug",DH="info",BH="warn",T="error",TH=(H)=>H?`#${H}`:"",wH=(H)=>H?.length?`.${Array.from(H).join(".")}`:"",u=(H)=>!!H&&typeof H==="object",w=(H)=>typeof H==="string",FH=(H,K)=>w(K)&&(K in H)&&z(H[K]),qH=(H)=>H.nodeType===Node.ELEMENT_NODE,i=(H)=>H.localName.includes("-");var Q=(H)=>H?`<${H.localName}${TH(H.id)}${wH(H.classList)}>`:"<unknown>",d=(H)=>w(H)?`"${H}"`:u(H)?JSON.stringify(H):String(H),$H=(H)=>{if(H===null)return"null";if(typeof H!=="object")return typeof H;if(Array.isArray(H))return"Array";if(Symbol.toStringTag in Object(H))return H[Symbol.toStringTag];return H.constructor?.name||"Object"},I=(H,K,B=UH)=>{if(C||[T,BH].includes(B))console[B](K,H);return H};class ZH extends Error{constructor(H,K){super(`Circular dependency detected in selection signal for component ${Q(H)} with selector "${K}"`);this.name="CircularMutationError"}}class LH extends Error{constructor(H){super(`Invalid component name "${H}". Custom element names must contain a hyphen, start with a lowercase letter, and contain only lowercase letters, numbers, and hyphens.`);this.name="InvalidComponentNameError"}}class o extends Error{constructor(H,K,B){super(`Invalid property name "${K}" for component <${H}>. ${B}`);this.name="InvalidPropertyNameError"}}class JH extends Error{constructor(H,K){super(`Invalid effects in component ${Q(H)}. Effects must be an array of effects, a single effect function, or a Promise that resolves to effects.`);if(this.name="InvalidEffectsError",K)this.cause=K}}class xH extends Error{constructor(H,K){super(`Expected signal as value for property "${String(K)}" in component ${Q(H)}.`);this.name="InvalidSignalError"}}class n extends Error{constructor(H,K,B){super(`Missing required element <${K}> in component ${Q(H)}. ${B}`);this.name="MissingElementError"}}class WH extends Error{constructor(H,K){super(`Timeout waiting for: [${K.join(", ")}] in component ${Q(H)}.`);this.name="DependencyTimeoutError"}}var N=Symbol("RESET"),p=(H,K,B=K)=>{try{if(H instanceof Promise)throw H;if(!Array.isArray(H))return H(K,B);let $=H.filter(z).map((Z)=>Z(K,B));return()=>{$.filter(z).forEach((Z)=>Z()),$.length=0}}catch($){if($ instanceof Promise)$.then(()=>p(H,K,B));else throw new JH(K,$ instanceof Error?$:new Error(String($)))}},h=(H,K,B,$)=>{try{return w(H)?K.getSignal(H).get():_(H)?H.get():z(H)?H(B):N}catch(Z){if($)I(Z,`Failed to resolve value of ${d(H)}${$?` for ${$}`:""} in ${Q(B)}${K!==B?` in ${Q(K)}`:""}`,T);return N}};var SH=(H)=>{let K=new Set;if(H.includes("."))K.add("class");if(H.includes("#"))K.add("id");if(H.includes("[")){let B=H.split("[");for(let $=1;$<B.length;$++){let Z=B[$];if(!Z.includes("]"))continue;let L=Z.split("=")[0].trim().replace(/[^a-zA-Z0-9_-]/g,"");if(L)K.add(L)}}return[...K]},NH=(H,K)=>{if(H.length!==K.length)return!1;let B=new Set(H);for(let $ of K)if(!B.has($))return!1;return!0},s=(H)=>z(H)&&H.length>=2,F=(H,K)=>z(K)?K(H):K,AH=(H,K)=>(B)=>{let $=B.shadowRoot??B,Z=(A,J)=>{let x=$.querySelector(A);if(!x)return;let W=J(x);if(W!=null)return W},L=void 0;for(let[A,J]of Object.entries(H))if(L=Z(A,J),L!=null)break;return w(L)&&s(K)?K(B,L):L??F(B,K)},CH=(H,K,B)=>{let $=new MutationObserver(B),Z={childList:!0,subtree:!0},L=SH(K);if(L.length)Z.attributes=!0,Z.attributeFilter=L;return $.observe(H,Z),$},PH=(H)=>{let K=H.shadowRoot??H,B=new Set;function $(J,x){let W=K.querySelector(J);if(x!=null&&!W)throw new n(H,J,x);if(W&&i(W)&&W.matches(":not(:defined)"))B.add(W.localName);return W}function Z(J,x){let W=K.querySelectorAll(J);if(x!=null&&!W.length)throw new n(H,J,x);if(W.length)W.forEach((X)=>{if(i(X)&&X.matches(":not(:defined)"))B.add(X.localName)});return Array.from(W)}return[{useElement:$,useElements:Z,first:(J,x,W)=>{let X=W!=null?$(J,W):$(J);return()=>{if(X)return p(x,H,X)}},all:(J,x,W)=>{let X=W!=null?Z(J,W):Z(J);return()=>{let Y=new Map,y=(j)=>{let q=p(x,H,j);if(q&&!Y.has(j))Y.set(j,q)},U=(j)=>{let q=Y.get(j);if(q)q();Y.delete(j)},P=(j)=>(q)=>{if(qH(q)){if(q.matches(J))j(q);q.querySelectorAll(J).forEach(j)}},G=CH(K,J,(j)=>{for(let q of j)q.addedNodes.forEach(P(y)),q.removedNodes.forEach(P(U))});if(X.length)X.forEach(y);return()=>{G.disconnect(),Y.forEach((j)=>j()),Y.clear()}}}},()=>Array.from(B)]};function kH(H){return(K)=>{let B=new Set,$=()=>Array.from((K.shadowRoot??K).querySelectorAll(H)),Z=V,L,A=0,J=2,x=()=>{Z=$(),L=CH(K,H,()=>{if(!B.size){L?.disconnect(),L=void 0;return}if(A++,A>J)throw L?.disconnect(),L=void 0,A=0,new ZH(K,H);try{let W=$();if(!NH(Z,W))Z=W,M(B)}finally{A--}})};return{[Symbol.toStringTag]:E,get(){if(O(B),!B.size)Z=$();else if(!L)x();return Z}}}}var EH=50,bH=new Set(["constructor","prototype"]),fH=new Set(["id","class","className","title","role","style","dataset","lang","dir","hidden","children","innerHTML","outerHTML","textContent","innerText"]),MH=(H)=>{if(bH.has(H))return`Property name "${H}" is a reserved word`;if(fH.has(H))return`Property name "${H}" conflicts with inherited HTMLElement property`;return null};function gH(H,K={},B){if(!H.includes("-")||!H.match(/^[a-z][a-z0-9-]*$/))throw new LH(H);for(let Z of Object.keys(K)){let L=MH(Z);if(L)throw new o(H,Z,L)}class $ extends HTMLElement{debug;#H={};#K;static observedAttributes=Object.entries(K)?.filter(([,Z])=>s(Z)).map(([Z])=>Z)??[];connectedCallback(){if(C){if(this.debug=this.hasAttribute("debug"),this.debug)I(this,"Connected")}for(let[W,X]of Object.entries(K)){if(X==null||W in this)continue;let Y=z(X)?X(this,null):X;if(Y!=null)this.setSignal(W,D(Y))}let[Z,L]=PH(this),A=B(this,Z),J=L(),x=()=>{let W=p(A,this);if(W)this.#K=W};if(J.length)Promise.race([Promise.all(J.map((W)=>customElements.whenDefined(W))),new Promise((W,X)=>{setTimeout(()=>{X(new WH(this,J.filter((Y)=>!customElements.get(Y))))},EH)})]).then(x).catch((W)=>{if(C)I(W,`Error during setup of <${H}>. Trying to run effects anyway.`,BH);x()});else x()}disconnectedCallback(){if(z(this.#K))this.#K();if(C&&this.debug)I(this,"Disconnected")}attributeChangedCallback(Z,L,A){if(A===L||g(this.#H[Z]))return;let J=K[Z];if(!s(J))return;let x=J(this,A,L);if(C&&this.debug)I(A,`Attribute "${String(Z)}" of ${Q(this)} changed from ${d(L)} to ${d(A)}, parsed as <${$H(x)}> ${d(x)}`);if(Z in this)this[Z]=x;else this.setSignal(Z,D(x))}getSignal(Z){let L=this.#H[Z];if(C&&this.debug)I(L,`Get ${$H(L)} "${String(Z)}" in ${Q(this)}`);return L}setSignal(Z,L){let A=MH(String(Z));if(A)throw new o(this.localName,Z,A);if(!_(L))throw new xH(this,Z);let J=this.#H[Z],x=R(L);if(this.#H[Z]=L,Object.defineProperty(this,Z,{get:L.get,set:x?L.set:void 0,enumerable:!0,configurable:x}),J&&R(J))J.set(V);if(C&&this.debug)I(L,`Set ${$H(L)} "${String(Z)} in ${Q(this)}`)}}customElements.define(H,$)}var GH="context-request";class OH extends Event{H;K;B;constructor(H,K,B=!1){super(GH,{bubbles:!0,composed:!0});this.context=H;this.callback=K;this.subscribe=B}}var dH=(H)=>(K)=>{let B=($)=>{let{context:Z,callback:L}=$;if(H.includes(Z)&&z(L))$.stopImmediatePropagation(),L(K.getSignal(String(Z)))};return K.addEventListener(GH,B),()=>K.removeEventListener(GH,B)},pH=(H,K)=>(B)=>{let $=D(F(B,K));return B.dispatchEvent(new OH(H,(Z)=>{$=Z})),$};var hH=(H,K,B)=>($)=>{let Z=new Set,L=F($,B),A=new Map,J,x=()=>{for(let[W,X]of Object.entries(K)){let Y=(y)=>{let U=y.target;if(!U)return;let P=U.closest(H);if(!P||!$.contains(P))return;y.stopPropagation();try{let G=X({event:y,host:$,target:P,value:L});if(G==null)return;if(!Object.is(G,L)){if(L=G,Z.size>0)M(Z);else if(J)J()}}catch(G){throw y.stopImmediatePropagation(),G}};A.set(W,Y),$.addEventListener(W,Y)}J=()=>{if(A.size){for(let[W,X]of A)$.removeEventListener(W,X);A.clear()}J=void 0}};return{[Symbol.toStringTag]:E,get(){if(O(Z),Z.size&&!A.size)x();return L}}},mH=(H,K,B=!1)=>($,Z)=>{let L=(A)=>{let J=K({host:$,target:Z,event:A});if(!u(J))return;t(()=>{for(let[x,W]of Object.entries(J))try{$[x]=W}catch(X){I(X,`Reactive property "${x}" on ${Q($)} from event ${H} on ${Q(Z)} could not be set, because it is read-only.`,T)}})};return Z.addEventListener(H,L,B),()=>Z.removeEventListener(H,L)},vH=(H,K)=>(B,$)=>b(()=>{let Z=h(K,B,$,`custom event "${H}" detail`);if(Z===N||Z===V)return;$.dispatchEvent(new CustomEvent(H,{detail:Z,bubbles:!0}))});var cH=(H,K="")=>{return{a:"attribute ",c:"class ",d:"dataset ",h:"inner HTML",m:"method call ",p:"property ",s:"style property ",t:"text content"}[H]+K},uH=(H)=>{if(/^(mailto|tel):/i.test(H))return!0;if(H.includes("://"))try{let K=new URL(H,window.location.origin);return["http:","https:","ftp:"].includes(K.protocol)}catch{return!1}return!0},iH=(H,K,B)=>{if(/^on/i.test(K))throw new Error(`Unsafe attribute: ${K}`);if(B=String(B).trim(),!uH(B))throw new Error(`Unsafe URL for ${K}: ${B}`);H.setAttribute(K,B)},S=(H,K)=>(B,$)=>{let{op:Z,name:L="",read:A,update:J}=K,x=A($),W=cH(Z,L),X=(y)=>()=>{if(C&&B.debug)I($,`${y} ${W} of ${Q($)} in ${Q(B)}`);K.resolve?.($)},Y=(y)=>(U)=>{I(U,`Failed to ${y} ${W} of ${Q($)} in ${Q(B)}`,T),K.reject?.(U)};return b(()=>{let y=h(H,B,$,W),U=y===N?x:y===V?K.delete?null:x:y;if(K.delete&&U===null)try{K.delete($),X("delete")()}catch(P){Y("delete")(P)}else if(U!=null){let P=A($);if(Object.is(U,P))return;try{J($,U),X("update")()}catch(G){Y("update")(G)}}})},oH=(H,K)=>(B,$)=>{let Z=(A)=>()=>{if(C&&B.debug)I($,`${A} element in ${Q($)} in ${Q(B)}`);if(z(K?.resolve))K.resolve($);else{let J=_(H)?H:w(H)?B.getSignal(H):void 0;if(R(J))J.set(0)}},L=(A)=>(J)=>{I(J,`Failed to ${A} element in ${Q($)} in ${Q(B)}`,T),K?.reject?.(J)};return b(()=>{let A=h(H,B,$,"insertion or deletion"),J=A===N?0:A;if(J>0){if(!K)throw new TypeError("No inserter provided");try{for(let x=0;x<J;x++){let W=K.create($);if(!W)continue;$.insertAdjacentElement(K.position??"beforeend",W)}Z("insert")()}catch(x){L("insert")(x)}}else if(J<0)try{if(K&&(K.position==="afterbegin"||K.position==="beforeend"))for(let x=0;x>J;x--)if(K.position==="afterbegin")$.firstElementChild?.remove();else $.lastElementChild?.remove();else $.remove();Z("remove")()}catch(x){L("remove")(x)}})},nH=(H)=>S(H,{op:"t",read:(K)=>K.textContent,update:(K,B)=>{Array.from(K.childNodes).filter(($)=>$.nodeType!==Node.COMMENT_NODE).forEach(($)=>$.remove()),K.append(document.createTextNode(B))}}),sH=(H,K=H)=>S(K,{op:"p",name:H,read:(B)=>(H in B)?B[H]:V,update:(B,$)=>{B[H]=$}}),lH=(H)=>S(H,{op:"p",name:"hidden",read:(K)=>!K.hidden,update:(K,B)=>{K.hidden=!B}});var rH=(H,K=H)=>S(K,{op:"a",name:H,read:(B)=>B.getAttribute(H),update:(B,$)=>{iH(B,H,$)},delete:(B)=>{B.removeAttribute(H)}}),aH=(H,K=H)=>S(K,{op:"a",name:H,read:(B)=>B.hasAttribute(H),update:(B,$)=>{B.toggleAttribute(H,$)}}),tH=(H,K=H)=>S(K,{op:"c",name:H,read:(B)=>B.classList.contains(H),update:(B,$)=>{B.classList.toggle(H,$)}}),eH=(H,K=H)=>S(K,{op:"s",name:H,read:(B)=>B.style.getPropertyValue(H),update:(B,$)=>{B.style.setProperty(H,$)},delete:(B)=>{B.style.removeProperty(H)}}),HK=(H,K={})=>S(H,{op:"h",read:(B)=>(B.shadowRoot||!K.shadowRootMode?B:null)?.innerHTML??"",update:(B,$)=>{let{shadowRootMode:Z,allowScripts:L}=K;if(!$){if(B.shadowRoot)B.shadowRoot.innerHTML="<slot></slot>";return""}if(Z&&!B.shadowRoot)B.attachShadow({mode:Z});let A=B.shadowRoot||B;if(A.innerHTML=$,!L)return"";return A.querySelectorAll("script").forEach((J)=>{let x=document.createElement("script");x.appendChild(document.createTextNode(J.textContent??"")),A.appendChild(x),J.remove()})," with scripts"}}),KK=(H)=>(K,B)=>{if(!u(H))throw new TypeError("Reactives must be an object of passed signals");if(!i(B))throw new TypeError(`Target ${Q(B)} is not a custom element`);if(!FH(B,"setSignal"))throw new TypeError(`Target ${Q(B)} is not a UIElement component`);for(let[$,Z]of Object.entries(H))B.setSignal($,w(Z)?K.getSignal(Z):D(Z))};var jH=()=>(H)=>H.textContent?.trim(),BK=(H)=>(K)=>{let B=K.getAttribute(H);return B?document.getElementById(B)?.textContent?.trim():void 0},$K=(H)=>(K)=>K[H],ZK=(H)=>(K)=>K.hasAttribute(H),RH=(H)=>(K)=>K.getAttribute(H),LK=(H)=>(K)=>K.classList.contains(H),JK=(H)=>(K)=>window.getComputedStyle(K).getPropertyValue(H),xK=(H)=>AH({".label":jH(),[H]:RH("aria-label")},""),WK=(H)=>AH({".description":jH(),[H]:BK("aria-describedby")},"");var zH=(H,K)=>{if(K==null)return;let B=H(K);return Number.isFinite(B)?B:void 0},AK=()=>(H,K)=>K!=null&&K!=="false",XK=(H=0)=>(K,B)=>{if(B==null)return F(K,H);let $=B.trim();if($.toLowerCase().startsWith("0x"))return zH((L)=>parseInt(L,16),$)??F(K,H);let Z=zH(parseFloat,B);return Z!=null?Math.trunc(Z):F(K,H)},QK=(H=0)=>(K,B)=>zH(parseFloat,B)??F(K,H),YK=(H="")=>(K,B)=>B??F(K,H),yK=(H)=>(K,B)=>{if(B==null)return H[0];let $=B.toLowerCase();return H.find((L)=>L.toLowerCase()===$)?B:H[0]},GK=(H)=>(K,B)=>{if((B??H)==null)throw new TypeError("asJSON: Value and fallback are both null or undefined");if(B==null)return F(K,H);if(B==="")throw new TypeError("Empty string is not valid JSON");let $;try{$=JSON.parse(B)}catch(Z){throw new SyntaxError(`Failed to parse JSON: ${String(Z)}`,{cause:Z})}return $??F(K,H)};export{S as updateElement,tH as toggleClass,aH as toggleAttribute,D as toSignal,HH as state,lH as show,nH as setText,eH as setStyle,sH as setProperty,rH as setAttribute,h as resolveReactive,dH as provideContexts,KK as pass,mH as on,I as log,R as isState,_ as isSignal,s as isParser,g as isComputed,oH as insertOrRemoveElement,LK as hasClass,ZK as hasAttribute,jH as getText,JK as getStyle,$K as getProperty,xK as getLabel,F as getFallback,WK as getDescription,RH as getAttribute,kH as fromSelector,hH as fromEvents,AH as fromDOM,pH as fromContext,IH as enqueue,vH as emitEvent,b as effect,HK as dangerouslySetInnerHTML,KH as computed,gH as component,t as batch,YK as asString,QK as asNumber,GK as asJSON,XK as asInteger,yK as asEnum,AK as asBoolean,V as UNSET,N as RESET,n as MissingElementError,BH as LOG_WARN,DH as LOG_INFO,T as LOG_ERROR,UH as LOG_DEBUG,xH as InvalidSignalError,o as InvalidPropertyNameError,JH as InvalidEffectsError,LH as InvalidComponentNameError,WH as DependencyTimeoutError,C as DEV_MODE,ZH as CircularMutationError}; //# debugId=E4E5A17B0DE9527164756E2164756E21