import { useState , useEffect } from 'react' ; import { useTheme } from '@twilio-paste/theme' ; import { findIndex , debounce } from 'lodash' ; interface WindowSizeState { width : number | undefined ; height : number | undefined ; breakpointIndex : number | undefined ; } function useWindowSize ( ) { const [ windowSize , setWindowSize ] = useState < WindowSizeState > ( { width : undefined , height : undefined , breakpointIndex : undefined , } ) ; const { breakpoints } = useTheme ( ) ; const breakpointNumbers = breakpoints . map ( ( bp ) : number => Number . parseInt ( bp . replace ( /\D+/g , '' ) , 10 ) ) ; useEffect ( ( ) => { const getBreakpointIndex = ( windowWidth ) : number => { const index = findIndex ( breakpointNumbers , ( bp ) : boolean => windowWidth < bp ) ; if ( index === - 1 ) { return breakpointNumbers . length - 1 ; } return index ; } ; const handleResize = debounce ( ( ) => { setWindowSize ( { width : window . innerWidth , height : window . innerHeight , breakpointIndex : getBreakpointIndex ( window . innerWidth ) , } ) ; } , 50 , { leading : false , trailing : true , maxWait : 150 } ) ; window . addEventListener ( 'resize' , handleResize ) ; handleResize ( ) ; return ( ) => window . removeEventListener ( 'resize' , handleResize ) ; } , [ ] ) ; return windowSize ; } export { useWindowSize } ;