UNPKG

@wordpress/global-styles-ui

Version:
68 lines (67 loc) • 2.7 kB
import clsx from "clsx"; import { __unstableMotion } from "@wordpress/components"; import { useReducedMotion, useResizeObserver, useThrottle } from "@wordpress/compose"; import { useLayoutEffect, useState } from "@wordpress/element"; import { Skeleton } from "@wordpress/ui"; import { useStyle } from "./hooks.mjs"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; // packages/global-styles-ui/src/preview-wrapper.tsx const normalizedWidth = 248; const normalizedHeight = 152; const THROTTLE_OPTIONS = { leading: true, trailing: true }; function PreviewWrapper({ children, label, isFocused, withHoverView }) { const [backgroundColor = "white"] = useStyle("color.background"); const [gradientValue] = useStyle("color.gradient"); const disableMotion = useReducedMotion(); const [isHovered, setIsHovered] = useState(false); const [containerResizeListener, { width }] = useResizeObserver(); const [throttledWidth, setThrottledWidthState] = useState(width); const [ratioState, setRatioState] = useState(); const setThrottledWidth = useThrottle(setThrottledWidthState, 250, THROTTLE_OPTIONS); useLayoutEffect(() => { if (width) setThrottledWidth(width); }, [width, setThrottledWidth]); useLayoutEffect(() => { const newRatio = throttledWidth ? throttledWidth / normalizedWidth : 1; const ratioDiff = newRatio - (ratioState || 0); if (Math.abs(ratioDiff) > .1 || !ratioState) setRatioState(newRatio); }, [throttledWidth, ratioState]); const fallbackRatio = width ? width / normalizedWidth : 1; const ratio = ratioState ? ratioState : fallbackRatio; const isReady = !!width; return /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx("div", { style: { position: "relative" }, children: containerResizeListener }), !isReady && /* @__PURE__ */ jsx(Skeleton, { className: "global-styles-ui-preview__wrapper", style: { aspectRatio: normalizedWidth / normalizedHeight } }), isReady && /* @__PURE__ */ jsx("div", { className: clsx("global-styles-ui-preview__wrapper", { "is-hoverable": withHoverView }), style: { height: normalizedHeight * ratio }, onMouseEnter: () => setIsHovered(true), onMouseLeave: () => setIsHovered(false), tabIndex: -1, children: /* @__PURE__ */ jsx(__unstableMotion.div, { style: { height: normalizedHeight * ratio, width: "100%", background: gradientValue ?? backgroundColor }, initial: "start", animate: (isHovered || isFocused) && !disableMotion && label ? "hover" : "start", children: [].concat(children).map((child, key) => child({ ratio, key })) }) }) ] }); } export { PreviewWrapper as default }; //# sourceMappingURL=preview-wrapper.mjs.map