@wordpress/components
Version:
UI components for WordPress.
55 lines (54 loc) • 1.78 kB
JavaScript
// packages/components/src/utils/use-responsive-value.ts
import { useEffect, useState } from "@wordpress/element";
var breakpoints = ["40em", "52em", "64em"];
var useBreakpointIndex = (options = {}) => {
const {
defaultIndex = 0
} = 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] = useState(defaultIndex);
useEffect(() => {
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]);
return value;
};
function useResponsiveValue(values, options = {}) {
const index = useBreakpointIndex(options);
if (!Array.isArray(values) && typeof values !== "function") {
return values;
}
const array = values || [];
return (
/** @type {T[]} */
array[
/* eslint-enable jsdoc/no-undefined-types */
index >= array.length ? array.length - 1 : index
]
);
}
export {
useBreakpointIndex,
useResponsiveValue
};
//# sourceMappingURL=use-responsive-value.js.map