UNPKG

@wordpress/components

Version:
48 lines (47 loc) • 1.94 kB
"use strict"; Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); let _wordpress_element = require("@wordpress/element"); // packages/components/src/utils/use-responsive-value.ts const breakpoints = [ "40em", "52em", "64em" ]; const useBreakpointIndex = (options = {}) => { const { defaultIndex = 0, enabled = true } = options; if (typeof defaultIndex !== "number") throw new TypeError(`Default breakpoint index should be a number. Got: ${defaultIndex}, ${typeof defaultIndex}`); else if (defaultIndex < 0 || defaultIndex > breakpoints.length - 1) throw new RangeError(`Default breakpoint index out of range. Theme has ${breakpoints.length} breakpoints, got index ${defaultIndex}`); const [value, setValue] = (0, _wordpress_element.useState)(defaultIndex); (0, _wordpress_element.useEffect)(() => { if (!enabled) return; const getIndex = () => breakpoints.filter((bp) => { return typeof window !== "undefined" ? window.matchMedia(`screen and (min-width: ${bp})`).matches : false; }).length; const onResize = () => { const newValue = getIndex(); if (value !== newValue) setValue(newValue); }; onResize(); if (typeof window !== "undefined") window.addEventListener("resize", onResize); return () => { if (typeof window !== "undefined") window.removeEventListener("resize", onResize); }; }, [value, enabled]); return value; }; function useResponsiveValue(values, options = {}) { const isResponsive = Array.isArray(values) && values.length > 1; const index = useBreakpointIndex({ ...options, enabled: isResponsive }); if (!Array.isArray(values) && typeof values !== "function") return values; const array = values || []; return array[index >= array.length ? array.length - 1 : index]; } exports.useBreakpointIndex = useBreakpointIndex; exports.useResponsiveValue = useResponsiveValue; //# sourceMappingURL=use-responsive-value.cjs.map