UNPKG

@crcong/wc-waterfall

Version:

wc-waterfall is a flow layout component written using web-component

2 lines (1 loc) 2.82 kB
"use strict";var L="wc-waterfall{position:relative;display:block;box-sizing:border-box!important;overflow:unset!important}wc-waterfall>*{position:absolute;box-sizing:border-box}";const H=t=>t.nodeType==1,_=t=>{const o=t();class e extends HTMLElement{constructor(){super(),this.$props=t();const s={};for(const a in this.$props)s[a]={get:()=>this.$props[a],set:i=>{this.$props[a]=O(o,a,i),this.render()}};Object.defineProperties(this,s)}static get observedAttributes(){return Object.keys(o).filter(s=>$(o[s]))}attributeChangedCallback(s,a,i){i=O(o,s,i),this.$props[s]!==i&&(this.$props[s]=i)}}return e},O=(t,o,e)=>{const n=t[o];return $(n)?{number:s=>Number(s),string:s=>String(s),boolean:s=>s!=null&&s!="false"}[typeof n](e):void 0},$=t=>{const o=typeof t;return o=="number"||o=="string"||o=="boolean"};function M(t){let o=0;for(let e=0;e<t.length;e++)o=t[o]<=t[e]?o:e;return o}function S(t,{getW:o,setW:e,getH:n,setH:s,getPad:a,setX:i,setY:u,getChildren:p},l){const{cols:r}=l,c=l["gap-x"],m=l["gap-y"],[x,A,v,w]=a(t),f=p(t),E=f.length;if(E){const W=(o(t)-c*(r-1)-(w+A))/r;Array.prototype.forEach.call(f,d=>e(d,W));const I=Array.prototype.map.call(f,d=>n(d)),h=Array(r).fill(x);for(let d=0;d<E;d++){const C=f[d],b=M(h);u(C,h[b]),i(C,w+(W+c)*b),h[b]+=I[d]+m}s(t,Math.max(...h)-m+v)}else s(t,x+v)}const g=Symbol(),y=Symbol();function T(t,o){let e,n,s;function a(){e=new ResizeObserver(l=>l.some(({target:r})=>r[y]!=r.offsetWidth||r[g]!=r.offsetHeight)&&p()),e.observe(t),Array.prototype.forEach.call(t.children,l=>e.observe(l)),n=new MutationObserver(l=>{l.forEach(r=>{r.addedNodes.forEach(c=>H(c)&&e.observe(c)),r.removedNodes.forEach(c=>H(c)&&e.unobserve(c))}),p()}),n.observe(t,{childList:!0,attributes:!1}),s=new MutationObserver(()=>p()),s.observe(t,{childList:!1,attributes:!0}),p()}function i(){e.disconnect(),n.disconnect(),s.disconnect()}let u=!1;function p(){u||(u=!0,requestAnimationFrame(()=>{o(),t[y]=t.offsetWidth,t[g]=t.offsetHeight,s.takeRecords(),u=!1}))}return{relayout:p,mount:a,unmount:i}}const j=(t,o)=>T(t,()=>{S(t,{getW:e=>e.offsetWidth,setW:(e,n)=>e.style.width=n+"px",getH:e=>(e[y]=e.offsetWidth,e[g]=e.offsetHeight),setH:(e,n)=>e.style.height=n+"px",getPad:e=>{const n=getComputedStyle(e);return[parseInt(n.paddingTop),parseInt(n.paddingRight),parseInt(n.paddingBottom),parseInt(n.paddingLeft)]},setX:(e,n)=>e.style.left=n+"px",setY:(e,n)=>e.style.top=n+"px",getChildren:e=>e.children},o)});document.head.appendChild(Object.assign(document.createElement("style"),{innerText:L}));const z=()=>({cols:2,"gap-x":4,"gap-y":4});class k extends _(z){constructor(){super()}connectedCallback(){this._layout=j(this,this),this._layout.mount()}disconnectedCallback(){this._layout.unmount()}render(){this.isConnected&&this._layout.relayout()}}customElements.define("wc-waterfall",k),exports.WaterfallElement=k;