avent-ui
Version:
The best UI library for Typescript and React
77 lines (74 loc) • 3.1 kB
JavaScript
import { useState, useEffect } from 'react';
const getInitialState = (mobileBreakPoint, tabletBreakPoint) => {
var _a, _b;
if (typeof window === 'undefined') {
return {
screenWidth: 1024,
screenHeight: 768,
devicePixelRatio: 1,
orientation: null,
isMobile: false,
isTablet: false,
isDesktop: true
};
}
const width = window.innerWidth;
return {
screenWidth: window.innerWidth,
screenHeight: window.innerHeight,
devicePixelRatio: window.devicePixelRatio || 1,
orientation: ((_b = (_a = window.screen) === null || _a === void 0 ? void 0 : _a.orientation) === null || _b === void 0 ? void 0 : _b.type) || null,
isMobile: width < mobileBreakPoint,
isTablet: width >= mobileBreakPoint && width < tabletBreakPoint,
isDesktop: width >= tabletBreakPoint
};
};
const useScreenDimensions = (options = {}) => {
const { debounceMs = 100, mobileBreakPoint = 768, tabletBreakPoint = 1024, } = options;
const initialState = getInitialState(mobileBreakPoint, tabletBreakPoint);
const [dimensions, setDimensions] = useState(initialState);
const updateDimensions = () => {
var _a, _b;
if (typeof window === 'undefined')
return;
const width = window.innerWidth;
setDimensions({
screenWidth: window.innerWidth,
screenHeight: window.innerHeight,
devicePixelRatio: window.devicePixelRatio || 1,
orientation: ((_b = (_a = window.screen) === null || _a === void 0 ? void 0 : _a.orientation) === null || _b === void 0 ? void 0 : _b.type) || null,
isMobile: width < mobileBreakPoint,
isTablet: width >= mobileBreakPoint && width < tabletBreakPoint,
isDesktop: width >= tabletBreakPoint
});
};
useEffect(() => {
var _a;
if (typeof window === 'undefined')
return;
let timeoutId;
const debouncedResize = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(updateDimensions, debounceMs);
};
const handleOrientationChange = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(updateDimensions, debounceMs);
};
window.addEventListener('resize', debouncedResize);
if ((_a = window.screen) === null || _a === void 0 ? void 0 : _a.orientation) {
window.screen.orientation.addEventListener('change', handleOrientationChange);
}
return () => {
var _a;
clearTimeout(timeoutId);
window.removeEventListener('resize', debouncedResize);
if ((_a = window.screen) === null || _a === void 0 ? void 0 : _a.orientation) {
window.screen.orientation.removeEventListener('change', handleOrientationChange);
}
};
}, [debounceMs]);
return { ...dimensions };
};
export { useScreenDimensions as default };
//# sourceMappingURL=useScreenDimensions.js.map