Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: Add custom type for MediaQuery #624

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stupid-crabs-invite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"usehooks-ts": patch
---

feature: Add custom type for MediaQuery
9 changes: 9 additions & 0 deletions packages/usehooks-ts/src/types/length.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { AbsoluteUnit, RelativeUnit } from './unit'

export type AbsoluteLength = `${number}${AbsoluteUnit}`

export type RelativeLength = `${number}${RelativeUnit}`

export type CustomLength<T extends string> = `${number}${T}`

export type Length = AbsoluteLength | RelativeLength
43 changes: 43 additions & 0 deletions packages/usehooks-ts/src/types/mediaQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { CustomLength, Length } from './length'

export type MediaQuery =
| ['any-hover', 'hover' | 'none']
| ['any-pointer', 'none' | 'coarse' | 'fine']
| [
'aspect-ratio' | 'min-aspect-ratio' | 'max-aspect-ratio',
`${number}/${number}`,
]
| ['color' | 'min-color' | 'max-color', number]
| ['color-index' | 'min-color-index' | 'max-color-index', number]
| [
'display-mode',
(
| 'browser'
| 'fullscreen'
| 'minimal-ui'
| 'picture-in-picture'
| 'standalone'
| 'window-controls-overlay'
),
]
| ['dynamic-range', 'standard' | 'high']
| ['forced-colors', 'none' | 'active']
| ['grid', '0' | '1']
| ['height' | 'min-height' | 'max-height', Length]
| ['hover', 'hover' | 'none']
| ['inverted-colors', 'none' | 'inverted']
| ['orientation', 'portrait' | 'landscape']
| ['overflow-block', 'none' | 'scroll' | 'optional-paged' | 'paged']
| ['overflow-inline', 'none' | 'scroll']
| ['pointer', 'none' | 'coarse' | 'fine']
| ['prefers-color-scheme', 'light' | 'dark']
| ['prefers-contrast', 'no-preference' | 'more' | 'less' | 'custom']
| ['resolution', CustomLength<'dpi'>]
| [
'min-resolution',
CustomLength<'dpi'> | CustomLength<'dppx'> | CustomLength<'x'>,
]
| ['max-resolution', CustomLength<'dpi'> | CustomLength<'dpcm'>]
| ['update', 'none' | 'slow' | 'fast']
| ['video-dynamic-range', 'standard' | 'high']
| ['width' | 'min-width' | 'max-width', Length]
12 changes: 12 additions & 0 deletions packages/usehooks-ts/src/types/unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export type AbsoluteUnit = 'cm' | 'mm' | 'in' | 'px' | 'pt' | 'pc'

export type RelativeUnit =
| 'em'
| 'ex'
| 'ch'
| 'rem'
| 'vw'
| 'vh'
| 'vmin'
| 'vmax'
| '%'
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useMediaQuery } from './useMediaQuery'

export default function Component() {
const matches = useMediaQuery('(min-width: 768px)')
const matches = useMediaQuery(['min-width', '768px'])

return (
<div>
Expand Down
22 changes: 14 additions & 8 deletions packages/usehooks-ts/src/useMediaQuery/useMediaQuery.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useState } from 'react'

import type { MediaQuery } from 'src/types/mediaQuery'

import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'

/** Hook options. */
Expand All @@ -20,7 +22,7 @@ const IS_SERVER = typeof window === 'undefined'

/**
* Custom hook that tracks the state of a media query using the [`Match Media API`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia).
* @param {string} query - The media query to track.
* @param {MediaQuery | string} query - The media query to track. It might be a string (e.g. '(max-width: 600px)') or a tuple (e.g. '['max-width', '600px']') with autocomplete and strictness.
* @param {?UseMediaQueryOptions} [options] - The options for customizing the behavior of the hook (optional).
* @returns {boolean} The current state of the media query (true if the query matches, false otherwise).
* @public
Expand All @@ -31,34 +33,38 @@ const IS_SERVER = typeof window === 'undefined'
* // Use `isSmallScreen` to conditionally apply styles or logic based on the screen size.
* ```
*/

export function useMediaQuery(
query: string,
query: MediaQuery | string,
{
defaultValue = false,
initializeWithValue = true,
}: UseMediaQueryOptions = {},
): boolean {
const getMatches = (query: string): boolean => {
const _query =
typeof query === 'string' ? query : `(${query[0]}: ${query[1]})`

const getMatches = (_query: string): boolean => {
if (IS_SERVER) {
return defaultValue
}
return window.matchMedia(query).matches
return window.matchMedia(_query).matches
}

const [matches, setMatches] = useState<boolean>(() => {
if (initializeWithValue) {
return getMatches(query)
return getMatches(_query)
}
return defaultValue
})

// Handles the change event of the media query.
function handleChange() {
setMatches(getMatches(query))
setMatches(getMatches(_query))
}

useIsomorphicLayoutEffect(() => {
const matchMedia = window.matchMedia(query)
const matchMedia = window.matchMedia(_query)

// Triggered at the first client-side load and if query changes
handleChange()
Expand All @@ -77,7 +83,7 @@ export function useMediaQuery(
matchMedia.removeEventListener('change', handleChange)
}
}
}, [query])
}, [_query])

return matches
}