UNPKG

x-widget

Version:

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

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