UNPKG

@studiometa/js-toolkit

Version:

A set of useful little bits of JavaScript to boost your project! 🚀

63 lines (62 loc) • 1.66 kB
import { isDev } from "../utils/is.js"; function withMountOnMediaQuery(BaseClass, media) { class WithMountOnMediaQuery extends BaseClass { /** * Config. */ static config = { ...BaseClass.config, options: { media: String } }; /** * Is the media query matches? * * @private */ __matches = false; /** * Listen for media query changes when the class in instantiated. * * @param {HTMLElement} element The component's root element. */ constructor(element) { super(element); if (isDev && !this.$options.media && !media) { this.$warn( 'Missing either "$options.media" or "media" argument in withMountOnMediaQuery decorator.' ); return; } const mediaQueryList = window.matchMedia(this.$options.media || media); this.__matches = mediaQueryList.matches; const changeHandler = (event) => { this.__matches = event.matches; if (event.matches && !this.$isMounted) { this.$mount(); } else if (this.$isMounted) { setTimeout(() => this.$destroy()); } }; mediaQueryList.addEventListener("change", changeHandler); this.$on("terminated", () => { mediaQueryList.removeEventListener("change", changeHandler); }); } /** * Override the mounting of the component. */ async $mount() { if (this.__matches) { return super.$mount(); } return this; } } return WithMountOnMediaQuery; } export { withMountOnMediaQuery }; //# sourceMappingURL=withMountOnMediaQuery.js.map