UNPKG

@gechiui/compose

Version:
88 lines (78 loc) 2.31 kB
/** * GeChiUI dependencies */ import { createContext, useContext } from '@gechiui/element'; /** * Internal dependencies */ import useMediaQuery from '../use-media-query'; /** * @typedef {"huge" | "wide" | "large" | "medium" | "small" | "mobile"} GCBreakpoint */ /** * Hash of breakpoint names with pixel width at which it becomes effective. * * @see _breakpoints.scss * * @type {Record<GCBreakpoint, number>} */ const BREAKPOINTS = { huge: 1440, wide: 1280, large: 960, medium: 782, small: 600, mobile: 480 }; /** * @typedef {">=" | "<"} GCViewportOperator */ /** * Object mapping media query operators to the condition to be used. * * @type {Record<GCViewportOperator, string>} */ const CONDITIONS = { '>=': 'min-width', '<': 'max-width' }; /** * Object mapping media query operators to a function that given a breakpointValue and a width evaluates if the operator matches the values. * * @type {Record<GCViewportOperator, (breakpointValue: number, width: number) => boolean>} */ const OPERATOR_EVALUATORS = { '>=': (breakpointValue, width) => width >= breakpointValue, '<': (breakpointValue, width) => width < breakpointValue }; const ViewportMatchWidthContext = createContext( /** @type {null | number} */ null); /** * Returns true if the viewport matches the given query, or false otherwise. * * @param {GCBreakpoint} breakpoint Breakpoint size name. * @param {GCViewportOperator} [operator=">="] Viewport operator. * * @example * * ```js * useViewportMatch( 'huge', '<' ); * useViewportMatch( 'medium' ); * ``` * * @return {boolean} Whether viewport matches query. */ const useViewportMatch = function (breakpoint) { let operator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '>='; const simulatedWidth = useContext(ViewportMatchWidthContext); const mediaQuery = !simulatedWidth && `(${CONDITIONS[operator]}: ${BREAKPOINTS[breakpoint]}px)`; const mediaQueryResult = useMediaQuery(mediaQuery || undefined); if (simulatedWidth) { return OPERATOR_EVALUATORS[operator](BREAKPOINTS[breakpoint], simulatedWidth); } return mediaQueryResult; }; useViewportMatch.__experimentalWidthProvider = ViewportMatchWidthContext.Provider; export default useViewportMatch; //# sourceMappingURL=index.js.map