@studiometa/js-toolkit
Version:
A set of useful little bits of JavaScript to boost your project! 🚀
71 lines (70 loc) • 2.03 kB
JavaScript
import { AbstractService } from "./AbstractService.js";
import { features } from "../Base/features.js";
import { debounce } from "../utils/debounce.js";
import { cache } from "../utils/cache.js";
class ResizeService extends AbstractService {
static config = [[() => window, [["resize"]]]];
breakpoints;
props = {
width: window.innerWidth,
height: window.innerHeight,
ratio: window.innerWidth / window.innerHeight,
orientation: "square",
get breakpoint() {
return Object.keys(this.activeBreakpoints).toReversed().find((name) => this.activeBreakpoints[name]);
},
get breakpoints() {
return Object.keys(this.activeBreakpoints);
},
activeBreakpoints: {}
};
constructor(breakpoints) {
super();
this.breakpoints = breakpoints;
Object.defineProperty(this.props, "activeBreakpoints", {
get: () => {
const activeBreakpoints = {};
for (const [name, breakpoint] of Object.entries(
this.breakpoints ?? features.get("breakpoints")
)) {
activeBreakpoints[name] = cache(
[this, window.innerWidth, window.innerHeight, breakpoint],
() => window.matchMedia(`(min-width: ${breakpoint})`).matches
);
}
return activeBreakpoints;
}
});
}
/**
* Update props.
*/
updateProps() {
const { props } = this;
props.width = window.innerWidth;
props.height = window.innerHeight;
props.ratio = window.innerWidth / window.innerHeight;
props.orientation = "square";
if (props.ratio > 1) {
props.orientation = "landscape";
}
if (props.ratio < 1) {
props.orientation = "portrait";
}
return props;
}
onResizeDebounce = debounce(() => {
this.trigger(this.updateProps());
}, 100);
handleEvent() {
this.onResizeDebounce();
}
}
function useResize(breakpoints) {
return ResizeService.getInstance([breakpoints], breakpoints);
}
export {
ResizeService,
useResize
};
//# sourceMappingURL=ResizeService.js.map