-
Notifications
You must be signed in to change notification settings - Fork 10
/
watched-box.min.js
1 lines (1 loc) · 2 KB
/
watched-box.min.js
1
export default class WatchedBox extends HTMLElement{constructor(){super();this.getPixels=(value=>{let test=document.createElement("div");Object.assign(test.style,{position:"absolute",width:value});this.appendChild(test);let pixels=test.offsetWidth;this.removeChild(test);return pixels});this.getPrefix=(()=>this.prefix?`${this.prefix}-`:"");this.toggleClasses=((watched,dimension,value,contentRect)=>{const length=dimension==="w"?contentRect.width:contentRect.height;const q=length<=this.getPixels(value);watched.target.classList.toggle(`${this.getPrefix()}${dimension}-lte-${value}`,q);watched.target.classList.toggle(`${this.getPrefix()}${dimension}-gt-${value}`,!q)});this.observe=(()=>{this.ro=new ResizeObserver(entries=>{const watched=entries[0];const contentRect=watched.contentRect;const widths=this.widthBreaks.replace(/ /g,"").split(",");widths.forEach(width=>{this.toggleClasses(watched,"w",width,contentRect)});const heights=this.heightBreaks.replace(/ /g,"").split(",");heights.forEach(height=>{this.toggleClasses(watched,"h",height,contentRect)});const ratio=contentRect.width/contentRect.height;watched.target.classList.toggle(`${this.getPrefix()}landscape`,ratio>1);watched.target.classList.toggle(`${this.getPrefix()}portrait`,ratio<1);watched.target.classList.toggle(`${this.getPrefix()}square`,ratio==1)});this.ro.observe(this)});this.unobserve=(()=>{this.ro.unobserve(this)})}get widthBreaks(){return this.getAttribute("widthBreaks")||"1024px"}set widthBreaks(val){return this.setAttribute("widthBreaks",val)}get heightBreaks(){return this.getAttribute("heightBreaks")||"768px"}set heightBreaks(val){return this.setAttribute("heightBreaks",val)}get prefix(){return this.getAttribute("prefix")||null}set prefix(val){return this.setAttribute("prefix",val)}static get observedAttributes(){return["widthBreaks","heightBreaks"]}connectedCallback(){this.observe()}attributeChangedCallback(){if(this.ro){this.unobserve()}this.observe()}};if(ResizeObserver&&"customElements"in window){customElements.define("watched-box",WatchedBox)}