UNPKG

media-query-manager

Version:

Used to manage media query break points and listen for changes.

61 lines (56 loc) 1.7 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var empxrem = require('empxrem'); class MediaQueryManager extends EventTarget { _watchers = []; _active = 0; _breaks = []; _baseFontSize; _handler = () => { for (let i = 0; i < this._watchers.length; i++) { if (this._watchers[i].matches) { this._active = this._breaks[i]; break; } } this._changed(); }; init() { for (const pt of this._breaks) { const dim = empxrem.ensureNotPxEm(pt, this._baseFontSize); const query = `(max-width: ${dim})`; const watcher = window.matchMedia(query); watcher.addEventListener('change', this._handler); this._watchers.push(watcher); } this._handler(); } constructor(breaks, { baseFontSize = 16, delayInit = false } = {}) { super(); this._baseFontSize = baseFontSize; this._breaks = [...breaks, 99999]; if (!delayInit) { this.init(); } } updateBaseFont() { const node = document.querySelector('html'); if (node) { node.style.fontSize = `${this._baseFontSize / 16 * 100}%`; } } _changed() { const event = new CustomEvent('change', { detail: { active: this.active } }); this.dispatchEvent(event); } destroy() { this._watchers.forEach(e => e.removeEventListener('change', this._handler)); } get breaks() { return this._breaks; } get active() { return this._active; } } exports.MediaQueryManager = MediaQueryManager;