UNPKG

@studiometa/js-toolkit

Version:

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

83 lines (82 loc) • 2.55 kB
import { useResize } from "../services/index.js"; import { isDev, isArray } from "../utils/index.js"; function testBreakpoints(breakpoints) { const { breakpoint } = useResize().props(); for (const [breakpointKeys, instance] of breakpoints) { if (breakpointKeys.includes(breakpoint) && !instance.$isMounted) { setTimeout(() => instance.$mount(), 0); } else if (!breakpointKeys.includes(breakpoint) && instance.$isMounted) { instance.$destroy(); } } } function mountComponents(instance, breakpoints) { return breakpoints.map(([bk, ComponentClass]) => { const child = new ComponentClass(instance.$el); Object.defineProperty(child, "$parent", { get: () => instance.$parent }); return [bk.split(" "), child]; }); } const instances = /* @__PURE__ */ new WeakMap(); function withBreakpointManager(BaseClass, breakpoints) { if (!isArray(breakpoints)) { if (isDev) { throw new Error("[withBreakpointManager] The `breakpoints` parameter must be an array."); } return BaseClass; } if (breakpoints.length < 2) { if (isDev) { throw new Error("[withBreakpointManager] You must define at least 2 breakpoints."); } return BaseClass; } const { add, props } = useResize(); if (!props().breakpoint) { if (isDev) { throw new Error("The `BreakpointManager` class requires breakpoints to be defined."); } return BaseClass; } class WithBreakpointManager extends BaseClass { /** * Watch for the document resize to test the breakpoints. */ constructor(element) { super(element); if (!instances.has(this)) { instances.set(this, mountComponents(this, breakpoints)); } add(`BreakpointManager-${this.$id}`, () => { testBreakpoints(instances.get(this)); }); } /** * Override the default $mount method to prevent component's from being * mounted when they should not. */ async $mount() { await super.$mount(); testBreakpoints(instances.get(this)); return this; } /** * Destroy all instances when the main one is destroyed. */ async $destroy() { const promises = []; if (isArray(instances.get(this))) { for (const [, instance] of instances.get(this)) { promises.push(instance.$destroy()); } } await Promise.all(promises); return super.$destroy(); } } return WithBreakpointManager; } export { withBreakpointManager }; //# sourceMappingURL=withBreakpointManager.js.map