1 import React from 'react'
2 import {useTheme} from '@primer/react'
3
4 const getMatches = query => (typeof window !== 'undefined' ? window.matchMedia(query).matches : false)
5
6 // The MIT License (MIT)
7 // Copyright (c) 2020 Julien CARON
8 // https://github.com/juliencrn/usehooks-ts/blob/master/packages/usehooks-ts/src/useMediaQuery/useMediaQuery.ts
9 export function useMediaQuery(query) {
10 const [matches, setMatches] = React.useState(getMatches(query))
11 const handleChange = React.useCallback(() => setMatches(getMatches(query)), [query])
12
13 React.useEffect(() => {
14 handleChange()
15 const matchMedia = window.matchMedia(query)
16 matchMedia.addEventListener('change', handleChange)
17 return () => matchMedia.removeEventListener('change', handleChange)
18 }, [query, handleChange])
19
20 return matches
21 }
22
23 export function useBreakpoint(breakpoint, minMax = 'min') {
24 // Handle string values from themes with units at the end
25 const px = typeof breakpoint === 'string' ? parseInt(breakpoint, 10) : breakpoint
26 return useMediaQuery(`(${minMax}-width: ${px - (minMax === 'min' ? 0 : 1)}px)`)
27 }
28
29 // a common breakpoint where things change on mobile
30 export function useIsMobile() {
31 const {theme} = useTheme()
32 return useBreakpoint(theme.breakpoints[2], 'max')
33 }
34
35 export default useBreakpoint