UNPKG

x-widget

Version:

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

6 lines (3 loc) 5.58 kB
var v=Object.defineProperty;var N=t=>v(t,"__esModule",{value:!0});var C=(t,r)=>{N(t);for(var o in r)v(t,o,{get:r[o],enumerable:!0})};C(exports,{default:()=>L,slotsMagic:()=>E,xPropDirective:()=>S,xWidgetData:()=>x,xWidgetDirective:()=>O});var _=t=>t.replace(/[a-z][A-Z]/g,r=>r[0]+"-"+r[1].toLowerCase());function x(t){let r=this,o=Object.entries(Object.getOwnPropertyDescriptors(t));return(e,n)=>{let s=D(e);console.assert(s,"widget not found");let i=Array.from(s.attributes).filter(c=>c.name.startsWith("x-prop:")).map(({name:c})=>c.substr(7)),a=new MutationObserver(c=>{c.forEach(({attributeName:d,target:g})=>{p(d,g.getAttribute(d))})});a.observe(s,{attributes:!0,attributeFilter:Object.keys(t).map(_),attributeOldValue:!1});let u=Object.fromEntries(o.filter(([c])=>!i.includes(c))),l=r.reactive(Object.assign(Object.create(Object.getPrototypeOf(t),u),{destroy(){a.disconnect()}})),f=[...s.attributes];for(let c of Object.getOwnPropertyNames(t)){let d=f.find(g=>g.name.match(new RegExp(`^((x-(bind|prop))?:)?${_(c)}$`)));!d||(d.name.startsWith("x-prop:")?Object.defineProperty(l,c,{configurable:!0,enumerable:!0,get(){return n[c]},set(g){n[c]=g}}):p(c,s.getAttribute(_(c))))}function p(c,d){let g=t[c];if(typeof g=="boolean")d===""?l[c]=!0:d==="false"?l[c]=!1:l[c]=!!d;else if(typeof g=="number")l[c]=parseFloat(d);else if(typeof g=="string")l[c]=d;else throw new Error("unsupported static attribute: "+c)}return l}}function D(t){for(;t&&!t.tagName.includes("-");)t=t.parentElement;return t}function P(t,r,o){return t._x_dataStack=[r,...h(o||t)],()=>{t._x_dataStack=t._x_dataStack.filter(e=>e!==r)}}function h(t){return t._x_dataStack?t._x_dataStack:typeof ShadowRoot=="function"&&t instanceof ShadowRoot?h(t.host):t.parentNode?h(t.parentNode):[]}function y(t){let r=new Proxy({},{ownKeys:()=>Array.from(new Set(t.flatMap(o=>Object.keys(o)))),has:(o,e)=>t.some(n=>n.hasOwnProperty(e)),get:(o,e)=>(t.find(n=>{if(n.hasOwnProperty(e)){let s=Object.getOwnPropertyDescriptor(n,e);if(s.get&&s.get._x_alreadyBound||s.set&&s.set._x_alreadyBound)return!0;if((s.get||s.set)&&s.enumerable){let i=s.get,a=s.set,u=s;i=i&&i.bind(r),a=a&&a.bind(r),i&&(i._x_alreadyBound=!0),a&&(a._x_alreadyBound=!0),Object.defineProperty(n,e,{...u,get:i,set:a})}return!0}return!1})||{})[e],set:(o,e,n)=>{let s=t.find(i=>i.hasOwnProperty(e));return s?s[e]=n:t[t.length-1][e]=n,!0}});return r}function j(t,r,o,...e){try{return o(...e)}catch(n){m(n,t,r)}}function m(t,r,o=void 0){Object.assign(t,{el:r,expression:o}),console.warn(`Alpine Expression Error: ${t.message} ${o?'Expression: "'+o+`" `:""}`,r),setTimeout(()=>{throw t},0)}function b(t,r){let o=h(t),e=T(o,r,t);return j.bind(null,t,r,e)}function T(t,r,o){let e=A(r,o);return(n=()=>{},{scope:s={}}={})=>{e.result=void 0,e.finished=!1;let i=y([s,...t]);if(typeof e=="function"){let a=e(e,i).catch(u=>m(u,o,r));e.finished?(n(F(e.result,i)),e.result=void 0):a.then(u=>F(u,i)).catch(u=>m(u,o,r)).finally(()=>e.result=void 0)}}}function F(t,r){return typeof t=="function"?t.bind(r):t}var w={};function A(t,r){if(w[t])return w[t];let o=Object.getPrototypeOf(async function(){}).constructor,e=/^[\n\s]*if.*\(.*\)/.test(t)||/^(let|const)\s/.test(t)?`(() => { ${t} })()`:t,s=(()=>{try{return new o(["__self","scope"],`with (scope) { __self.result = ${e} }; __self.finished = true; return __self.result;`)}catch(i){return m(i,r,t),Promise.resolve()}})();return w[t]=s,s}var W=t=>t.replace(/-([a-zA-Z])/g,r=>r[1].toUpperCase()+r.substr(2));function S(t,{value:r,expression:o},{cleanup:e}){let n=W(r),s=b(o===n?t.parentElement:t,o),i,a=$(t,o)?b(t.parentElement,`${o} = __`):(f,{scope:{__:p}})=>i=p,u={};Object.defineProperty(u,n,{get(){let f;return typeof i!="undefined"?i:(s(p=>f=p),f)},set(f){n!=="value"&&(t[n]=f),a(()=>{},{scope:{__:f}})}}),n!=="value"&&(t[n]=u[n]);let l=P(t,u);e(()=>l())}function $(t,r){try{let o=y(h(t));return new Function("scope",`with(scope) {${r} = ${r}}`)(o),!0}catch{return!1}}function E(t){for(;t&&!t._x_slots;)t=t.parentElement;return t?._x_slots}function O(t,{expression:r,modifiers:o},{Alpine:e}){let n=r;if(window.customElements.get(n))return;if(o[0]){let i=document.createElement("style");i.innerHTML=`${n} { display: ${o[0]}}`,document.head.appendChild(i)}e._widgets?e._widgets.push(n):e._widgets=[n];let s=t.content.firstElementChild;window.customElements.define(n,class extends HTMLElement{constructor(){super();this._slotFills=null}connectedCallback(){let i;this._slotFills?i=this._slotFills:(i=M(this),this._slotFills=i);let a=s.cloneNode(!0);this._x_slots=Object.fromEntries([...i.entries()].map(([l,f])=>[l,f]));let u=k(a);for(let l of u){let f=l.name||"default",p=i.get(f);p?l.replaceWith(...p.map(c=>c.cloneNode(!0))):l.replaceWith(...l.childNodes)}requestAnimationFrame(()=>{for(;this.firstChild;)this.removeChild(this.firstChild);this.appendChild(a)}),this.dispatchEvent(new CustomEvent("x-widget:connected",{bubbles:!0}))}})}function k(t){let r=[...t.querySelectorAll("slot")];t.tagName==="SLOT"&&r.unshift(t);let o=t.querySelectorAll("template");for(let e of o)if(!e.getAttribute("x-widget"))for(let n of e.content.children)r.push(...k(n));return r}function M(t){let r=new Map;function o(e,n){r.has(e)?r.get(e).push(...n):r.set(e,n)}for(let e of t.childNodes)if(e.tagName==="TEMPLATE"){let n=e.getAttribute("slot"),s=!n&&(e.getAttribute("x-for")||e.getAttribute("x-if"));o(n||"default",s?[e]:[...e.content.childNodes])}else(e.nodeType!==Node.TEXT_NODE||e.textContent.trim())&&o("default",[e]);return r}function L(t){t.magic("slots",E),t.directive("widget",O),t.directive("prop",S),t.data("xWidget",x.bind(t))}