UNPKG

@base-ui-components/react

Version:

Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.

57 lines (56 loc) 2.09 kB
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default; Object.defineProperty(exports, "__esModule", { value: true }); exports.useMediaQuery = useMediaQuery; var React = _interopRequireWildcard(require("react")); var _shim = require("use-sync-external-store/shim"); function useMediaQuery(query, options) { // Wait for jsdom to support the match media feature. // All the browsers Base UI support have this built-in. // This defensive check is here for simplicity. // Most of the time, the match media logic isn't central to people tests. const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; query = query.replace(/^@media( ?)/m, ''); const { defaultMatches = false, matchMedia = supportMatchMedia ? window.matchMedia : null, ssrMatchMedia = null, noSsr = false } = options; const getDefaultSnapshot = React.useCallback(() => defaultMatches, [defaultMatches]); const getServerSnapshot = React.useMemo(() => { if (noSsr && matchMedia) { return () => matchMedia(query).matches; } if (ssrMatchMedia !== null) { const { matches } = ssrMatchMedia(query); return () => matches; } return getDefaultSnapshot; }, [getDefaultSnapshot, query, ssrMatchMedia, noSsr, matchMedia]); const [getSnapshot, subscribe] = React.useMemo(() => { if (matchMedia === null) { return [getDefaultSnapshot, () => () => {}]; } const mediaQueryList = matchMedia(query); return [() => mediaQueryList.matches, notify => { mediaQueryList.addEventListener('change', notify); return () => { mediaQueryList.removeEventListener('change', notify); }; }]; }, [getDefaultSnapshot, matchMedia, query]); const match = (0, _shim.useSyncExternalStore)(subscribe, getSnapshot, getServerSnapshot); if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue({ query, match }); } return match; }