UNPKG

x-widget

Version:

Adds the ability to define reusable Widgets (WebComponents) using Alpinejs.

2 lines (1 loc) 1.28 kB
var c=e=>e.replace(/[a-z][A-Z]/g,i=>i[0]+"-"+i[1].toLowerCase());function w(e){let i=this,p=Object.entries(Object.getOwnPropertyDescriptors(e));return(b,a)=>{let n=O(b);console.assert(n,"widget not found");let l=Array.from(n.attributes).filter(t=>t.name.startsWith("x-prop:")).map(({name:t})=>t.substr(7)),f=new MutationObserver(t=>{t.forEach(({attributeName:r,target:o})=>{u(r,o.getAttribute(r))})});f.observe(n,{attributes:!0,attributeFilter:Object.keys(e).map(c),attributeOldValue:!1});let d=Object.fromEntries(p.filter(([t])=>!l.includes(t))),s=i.reactive(Object.assign(Object.create(Object.getPrototypeOf(e),d),{destroy(){f.disconnect()}})),g=[...n.attributes];for(let t of Object.getOwnPropertyNames(e)){let r=g.find(o=>o.name.match(new RegExp(`^((x-(bind|prop))?:)?${c(t)}$`)));!r||(r.name.startsWith("x-prop:")?Object.defineProperty(s,t,{configurable:!0,enumerable:!0,get(){return a[t]},set(o){a[t]=o}}):u(t,n.getAttribute(c(t))))}function u(t,r){let o=e[t];if(typeof o=="boolean")r===""?s[t]=!0:r==="false"?s[t]=!1:s[t]=!!r;else if(typeof o=="number")s[t]=parseFloat(r);else if(typeof o=="string")s[t]=r;else throw new Error("unsupported static attribute: "+t)}return s}}function O(e){for(;e&&!e.tagName.includes("-");)e=e.parentElement;return e}export{w as xWidgetData};