UNPKG

@webreflection/ascii-grid

Version:

Probably the easiest way to define grids layouts

3 lines (2 loc) 2.32 kB
/*! (c) Andrea Giammarchi */ var t=t=>{const e=(t=>{let e,s=0;const o=/\S+/g,a=[],r=new Map([[".","."]]);for(const c of t.split(/[\r\n]+/)){const t=[];for(;e=o.exec(c);){const[o]=e;r.has(o)||r.set(o,"g"+s++),t.push(r.get(o))}t.length&&a.push(t)}return a})(t),s=e.flat().filter((t=>"."!==t));return t=e.map((t=>`"${t.join(" ")}"`)).join(" "),{applyTo(e){let o=0;const a=new Map,{children:r,style:c}=e;c.display="grid",c["grid-template-areas"]=t;for(const t of s)if(!a.has(t)){const e=r[o++];e.style["grid-area"]=t,a.set(t,e)}return e},cssFor(e){let o=0;const a=new Set,r=[`${e}{display:grid;grid-template-areas:${t}}`];for(const t of s)a.has(t)||(r.push(`${e}>*:nth-child(${++o}){grid-area:${t}}`),a.add(t));return r.join("\n")}}};if(!customElements.get("ascii-grid")){const{COMMENT_NODE:e,ELEMENT_NODE:s}=Node,{find:o}=Array.prototype,a=["cols","rows"],r=t=>t.nodeType===e&&t.data.startsWith("#"),c=(t,e,s)=>{switch(e){case"cols":t.style["grid-template-columns"]=s;break;case"rows":t.style["grid-template-rows"]=s}},i=new WeakMap,n=(t,e)=>{const s=new MutationObserver((()=>{o.call(t.childNodes,r)&&(s.disconnect(),i.delete(t),e.call(t,t))}));s.observe(t,{childList:!0}),i.set(t,s)};class l extends HTMLElement{static observedAttributes=a;attributeChangedCallback(t,e,s){c(this,t,s)}get structure(){const t=o.call(this.childNodes,r);return t?t.data.slice(1):""}set structure(e){let s=o.call(this.childNodes,r);s||(s=this.appendChild(document.createComment(""))),s.data="#"+e,t(e).applyTo(this)}connectedCallback(){const{structure:t}=this;t?this.structure=t:i.has(this)||n(this,this.connectedCallback)}}customElements.define("ascii-grid",l);const d=e=>{const s=o.call(e.childNodes,r);if(s){t(s.data.slice(1)).applyTo(e),p.observe(e,{attributeFilter:a});for(const t of a)c(e,t,e.getAttribute(t))}else i.has(e)||n(e,d)},h=t=>{for(const e of t.querySelectorAll(".ascii-grid"))d(e)},u=t=>(f.observe(t,{childList:!0,subtree:!0}),t),p=new MutationObserver((t=>{for(const{target:e,attributeName:s}of t)c(e,s,e.getAttribute(s))})),f=new MutationObserver((t=>{for(const{addedNodes:e}of t)for(const t of e)t.nodeType===s&&(t.classList.contains("ascii-grid")&&d(t),h(t))}));h(u(document));const{attachShadow:g}=Element.prototype;Element.prototype.attachShadow=function(){return u(g.apply(this,arguments))}}export{t as default};