@kubit-ui-web/react-components
Version:
Kubit React Components is a customizable, accessible library of React web components, designed to enhance your application's user experience
73 lines • 3.32 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMediaDevice = void 0;
const react_1 = require("react");
const styled_components_1 = require("styled-components");
const breakpoints_1 = require("../../types/breakpoints/breakpoints");
const useMediaDevice = () => {
const mediaQueries = (0, styled_components_1.useTheme)().MEDIA_QUERIES.matchMedia;
const initialiceMedia = () => {
// Perhaps should return null by default
let deviceFound = breakpoints_1.DeviceBreakpointsType.DESKTOP;
if (typeof window !== 'undefined' && window?.matchMedia) {
const tableMatchMedia = window.matchMedia(mediaQueries.onlyTablet);
const mobileMatchMedia = window.matchMedia(mediaQueries.onlyMobile);
if (mobileMatchMedia.matches) {
deviceFound = breakpoints_1.DeviceBreakpointsType.MOBILE;
}
else if (tableMatchMedia.matches) {
deviceFound = breakpoints_1.DeviceBreakpointsType.TABLET;
}
else {
deviceFound = breakpoints_1.DeviceBreakpointsType.DESKTOP;
}
}
return deviceFound;
};
const [device, setDevice] = (0, react_1.useState)(initialiceMedia);
(0, react_1.useEffect)(() => {
let deviceFound = breakpoints_1.DeviceBreakpointsType.DESKTOP;
let desktopMatchMedia;
let tableMatchMedia;
let mobileMatchMedia;
const handleQueryListener = () => {
if (mobileMatchMedia?.matches) {
deviceFound = breakpoints_1.DeviceBreakpointsType.MOBILE;
}
else if (tableMatchMedia?.matches) {
deviceFound = breakpoints_1.DeviceBreakpointsType.TABLET;
}
else {
deviceFound = breakpoints_1.DeviceBreakpointsType.DESKTOP;
}
setDevice(deviceFound);
};
if (typeof window !== 'undefined' && window && window.matchMedia) {
desktopMatchMedia = window.matchMedia(mediaQueries.onlyDesktop);
tableMatchMedia = window.matchMedia(mediaQueries.onlyTablet);
mobileMatchMedia = window.matchMedia(mediaQueries.onlyMobile);
// Add listeners
desktopMatchMedia.addEventListener('change', handleQueryListener);
tableMatchMedia.addEventListener('change', handleQueryListener);
mobileMatchMedia.addEventListener('change', handleQueryListener);
if (mobileMatchMedia.matches) {
deviceFound = breakpoints_1.DeviceBreakpointsType.MOBILE;
}
else if (tableMatchMedia.matches) {
deviceFound = breakpoints_1.DeviceBreakpointsType.TABLET;
}
else {
deviceFound = breakpoints_1.DeviceBreakpointsType.DESKTOP;
}
}
setDevice(deviceFound);
return () => {
desktopMatchMedia?.removeEventListener('change', handleQueryListener);
tableMatchMedia?.removeEventListener('change', handleQueryListener);
mobileMatchMedia?.removeEventListener('change', handleQueryListener);
};
}, [mediaQueries]);
return device;
};
exports.useMediaDevice = useMediaDevice;
//# sourceMappingURL=useMediaDevice.js.map