UNPKG

bitandblack-rows

Version:

A small and simple CSS gutter to create rows and cells using the flexbox model.

134 lines (114 loc) 3.13 kB
/** * Bit&Black Rows * * @copyright Copyright (c) Bit&Black * @author Tobias Köngeter <hello@bitandblack.com> * @link https://www.bitandblack.com */ /** * Tracking the viewport and viewport changes. */ class Viewport { /** * @private */ private readonly viewports: Array<string> = [ "phone", "tablet-portrait", "tablet-landscape", "desktop", "desktop-big" ]; /** * @private */ private resizeTimeout: NodeJS.Timeout; /** * @param viewportName */ private callback = (viewportName: string) => {}; /** * @private */ private readonly mainSelector = "bb-rows-js"; /** * @private */ private viewportName: string; /** * Constructor. */ constructor() { window.addEventListener("resize", this.onWindowResize.bind(this)); this.init(); } /** * @private */ private onWindowResize() { clearTimeout(this.resizeTimeout); this.resizeTimeout = setTimeout( this.resize.bind(this), 250 ); } /** * @private */ private init(): Viewport { const divMainExisting = document.querySelector(`.${this.mainSelector}`) if (!divMainExisting) { const divMain = document.createElement("div"); divMain.classList.add(this.mainSelector); const body = document.querySelector("body"); body.appendChild(divMain); this.viewports.forEach((viewport: string) => { const divViewport = document.createElement("div"); divViewport.classList.add(`${this.mainSelector}__viewport`); divViewport.classList.add(`${this.mainSelector}__viewport--${viewport}`); divViewport.dataset.bbRowViewportName = viewport; divMain.appendChild(divViewport); }); } window.dispatchEvent(new Event("resize")); return this; } /** * @private */ private resize(): void { const elements: NodeListOf<HTMLElement> = document.querySelectorAll(`.${this.mainSelector}__viewport`); const isHidden = (element) => { const style = window.getComputedStyle(element); return "none" === style.display; }; for (const element of elements as any) { const viewport = element.dataset.bbRowViewportName; if (!isHidden(element)) { this.viewportName = viewport; this.callback(viewport); return; } } this.viewportName = "phone"; this.callback("phone"); } /** * Sets the resize callback. * * @param customCallback */ public onResize = (customCallback): Viewport => { this.callback = customCallback; return this; }; /** * Returns the name of the current viewport. * * @return string */ public getViewportName = (): string => this.viewportName; } export { Viewport };