use-breakpoint-agent
Version:
A React hook to detect device type based on screen width
33 lines (32 loc) • 1.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBreakpointAgent = void 0;
const types_1 = require("../types/index.js");
const client_1 = require("../client.js");
const default_1 = require("../lib/default.js");
const getBreakpointAgent = (serverDevice = undefined, breakpoints) => {
const { mobile, tablet } = Object.assign(Object.assign({}, default_1.defaultBreakpoints), breakpoints);
const getSnapshot = () => {
var _a;
const w = window;
if (!w.__breakpointAgent) {
w.__breakpointAgent = { firstWidth: window.innerWidth, resize: false };
window.addEventListener("resize", () => {
var _a;
if (((_a = w.__breakpointAgent) === null || _a === void 0 ? void 0 : _a.firstWidth) !== window.innerWidth)
w.__breakpointAgent.resize = true;
});
}
if (!((_a = w.__breakpointAgent) === null || _a === void 0 ? void 0 : _a.resize))
return (0, client_1.getDeviceTypeFromString)(navigator.userAgent);
const width = window.innerWidth;
if (width <= mobile)
return types_1.DeviceEnum.MOBILE;
if (width < tablet)
return types_1.DeviceEnum.TABLET;
return types_1.DeviceEnum.DESKTOP;
};
const getServerSnapshot = () => serverDevice !== null && serverDevice !== void 0 ? serverDevice : null;
return typeof window === "undefined" ? getServerSnapshot() : getSnapshot();
};
exports.getBreakpointAgent = getBreakpointAgent;