import { useEffect , useState } from 'react' ; export const breakpoints = { DEFAULT : 0 , SMALL : 320 , MEDIUM : 600 , LARGE : 1136 , } as const ; export type BreakpointsType = keyof typeof breakpoints ; export type BreakpointsTypeWithoutFirst = Exclude < BreakpointsType , 'DEFAULT' > ; export type BreakpointsTypeWithoutLast = Exclude < BreakpointsType , 'LARGE' > ; const toEm = ( size ) => size / 16 + 'em' ; const getNextBreakpointName = ( name ) => { const names = Object . keys ( breakpoints ) as unknown as BreakpointsType ; return names [ names . indexOf ( name ) + 1 ] as BreakpointsTypeWithoutFirst ; } ; const getNextBreakpointValue = ( name ) => { const getNextName = getNextBreakpointName ( name ) ; return breakpoints [ getNextName ] - 0.02 ; } ; const getBreakpointValue = ( name ) => { return breakpoints [ name ] ; } ; const calcMinWidth = ( name ) => { return toEm ( getBreakpointValue ( name ) ) ; } ; const calcMaxWidth = ( name ) => { return toEm ( getNextBreakpointValue ( name ) ) ; } ; const withMinAndMaxMedia = ( x , y ) => `@media (min-width: ${ x }) and (max-width: ${ y })` ; example export const up = ( name ) => `@media (min-width: ${ calcMinWidth ( name ) })` ; example export const down = ( name ) => `@media (max-width: ${ calcMaxWidth ( name ) })` ; example export const between = ( min , max ) => withMinAndMaxMedia ( calcMinWidth ( min ) , calcMaxWidth ( max ) ) ; example export const only = ( name ) => withMinAndMaxMedia ( calcMinWidth ( name ) , calcMaxWidth ( name ) ) ; export const useBreakPoint = ( breakpoint ) => { const query = breakpoint . replace ( /^@media\s*/ , '' ) ; const [ isBreak , setIsBreak ] = useState < boolean | null > ( null ) ; useEffect ( ( ) => { const mq = window . matchMedia ( query ) ; const handleChange = ( event ) => { setIsBreak ( event . matches ) ; } ; setIsBreak ( mq . matches ) ; if ( ! mq . addEventListener ) { mq . addListener ( handleChange ) ; return ( ) => { mq . removeListener ( handleChange ) ; } ; } mq . addEventListener ( 'change' , handleChange ) ; return ( ) => { mq . removeEventListener ( 'change' , handleChange ) ; } ; } , [ query ] ) ; return isBreak ; } ; export const mediaQuery = ( name ) => { return `@media screen and (min-width: ${ getBreakpointValue ( name ) }px)` ; } ;