UNPKG

@hhgtech/hhg-components

Version:
47 lines (44 loc) 1.97 kB
import React__default, { createContext, useState, useEffect, useMemo } from 'react'; import throttle from 'lodash/throttle'; import { B as Breakpoints } from './utils-cb7242c7.js'; const ScreenSizeContext = createContext({ isInit: true, }); const getWidthValue = (manualWidth) => typeof manualWidth === 'number' ? manualWidth : (typeof window !== 'undefined' && window.innerWidth) || 0; // get from width passed in, else get from window.innerWidth const getWindowSizeGroups = (manualWidth) => { const width = getWidthValue(manualWidth); return { smallMobile: width < Breakpoints.BREAK_POINT_SMALL_MOBILE, mobile: width >= Breakpoints.BREAK_POINT_SMALL_MOBILE && width < Breakpoints.BREAK_POINT_MOBILE, tablet: width >= Breakpoints.BREAK_POINT_MOBILE && width < Breakpoints.BREAK_POINT_TABLET, pc: width >= Breakpoints.BREAK_POINT_TABLET && width < Breakpoints.BREAK_POINT_PC, xl: width >= Breakpoints.BREAK_POINT_PC, }; }; const ScreenSizeContextProvider = ({ children, }) => { const [screenSize, setScreenSize] = useState(() => ({ isInit: true, })); useEffect(() => { const handleResize = throttle(() => { setScreenSize({ width: window.innerWidth, height: window.innerHeight, isInit: false, }); }, 200); window.addEventListener('resize', handleResize, { passive: true }); return () => { window.removeEventListener('resize', handleResize); }; }, []); const sizeGroups = useMemo(() => getWindowSizeGroups(screenSize.width), [screenSize.width]); return (React__default.createElement(ScreenSizeContext.Provider, { value: Object.assign(Object.assign({}, screenSize), { sizeGroups }) }, children)); }; export { ScreenSizeContext, ScreenSizeContextProvider, getWindowSizeGroups };