@wordpress/components
Version:
UI components for WordPress.
332 lines (331 loc) • 12.3 kB
JavaScript
import clsx from "clsx";
import { arrow, autoUpdate, flip, limitShift, offset, shift, size, useFloating } from "@floating-ui/react-dom";
import { motion } from "framer-motion";
import { createPortal, forwardRef, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from "@wordpress/element";
import { __experimentalUseDialog, useMergeRefs, useReducedMotion, useViewportMatch } from "@wordpress/compose";
import { close } from "@wordpress/icons";
import deprecated from "@wordpress/deprecated";
import { Path, SVG } from "@wordpress/primitives";
import { __ } from "@wordpress/i18n";
import Button from "../button/index.mjs";
import ScrollLock from "../scroll-lock/index.mjs";
import { Fill, Slot, useSlot } from "../slot-fill/index.mjs";
import { computePopoverPosition, getReferenceElement, placementToMotionAnimationProps, positionToPlacement } from "./utils.mjs";
import { contextConnect, useContextSystem } from "../context/index.mjs";
import { overlayMiddlewares } from "./overlay-middlewares.mjs";
import { StyleProvider } from "../style-provider/index.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { slotNameContext } from "./context.mjs";
// packages/components/src/popover/index.tsx
/**
* Name of slot in which popover should fill.
*
* @type {string}
*/
const SLOT_NAME = "Popover";
/**
* Virtual padding to account for overflow boundaries.
*
* @type {number}
*/
const OVERFLOW_PADDING = 8;
/**
* How long to wait after the last position update before dropping the
* `will-change` hint.
*
* @type {number}
*/
const WILL_CHANGE_IDLE_TIMEOUT = 200;
const ArrowTriangle = () => /* @__PURE__ */ jsxs(SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 100 100",
className: "components-popover__triangle",
role: "presentation",
children: [/* @__PURE__ */ jsx(Path, {
className: "components-popover__triangle-bg",
d: "M 0 0 L 50 50 L 100 0"
}), /* @__PURE__ */ jsx(Path, {
className: "components-popover__triangle-border",
d: "M 0 0 L 50 50 L 100 0",
vectorEffect: "non-scaling-stroke"
})]
});
const fallbackContainerClassname = "components-popover__fallback-container";
const getPopoverFallbackContainer = () => {
let container = document.body.querySelector("." + fallbackContainerClassname);
if (!container) {
container = document.createElement("div");
container.className = fallbackContainerClassname;
document.body.append(container);
}
return container;
};
const UnforwardedPopover = (props, forwardedRef) => {
const { animate = true, headerTitle, constrainTabbing, onClose, children, className, noArrow = true, position, placement: placementProp = "bottom-start", offset: offsetProp = 0, focusOnMount = "firstElement", anchor, expandOnMobile, onFocusOutside, __unstableSlotName = SLOT_NAME, flip: flip$1 = true, resize = true, shift: shift$1 = false, inline = false, variant, style: contentStyle, __unstableForcePosition, anchorRef, anchorRect, getAnchorRect, isAlternate, onKeyDown, ...contentProps } = useContextSystem(props, "Popover");
let computedFlipProp = flip$1;
let computedResizeProp = resize;
if (__unstableForcePosition !== void 0) {
deprecated("`__unstableForcePosition` prop in wp.components.Popover", {
since: "6.1",
version: "6.3",
alternative: "`flip={ false }` and `resize={ false }`"
});
computedFlipProp = !__unstableForcePosition;
computedResizeProp = !__unstableForcePosition;
}
if (anchorRef !== void 0) deprecated("`anchorRef` prop in wp.components.Popover", {
since: "6.1",
alternative: "`anchor` prop"
});
if (anchorRect !== void 0) deprecated("`anchorRect` prop in wp.components.Popover", {
since: "6.1",
alternative: "`anchor` prop"
});
if (getAnchorRect !== void 0) deprecated("`getAnchorRect` prop in wp.components.Popover", {
since: "6.1",
alternative: "`anchor` prop"
});
const computedVariant = isAlternate ? "toolbar" : variant;
if (isAlternate !== void 0) deprecated("`isAlternate` prop in wp.components.Popover", {
since: "6.2",
alternative: "`variant` prop with the `'toolbar'` value"
});
const arrowRef = useRef(null);
const [fallbackReferenceElement, setFallbackReferenceElement] = useState(null);
const anchorRefFallback = useCallback((node) => {
setFallbackReferenceElement(node);
}, []);
const isMobileViewport = useViewportMatch("medium", "<");
const isExpanded = expandOnMobile && isMobileViewport;
const hasArrow = !isExpanded && !noArrow;
const normalizedPlacementFromProps = position ? positionToPlacement(position) : placementProp;
const middleware = [
...placementProp === "overlay" ? overlayMiddlewares() : [],
offset(offsetProp),
computedFlipProp && flip(),
computedResizeProp && size({
padding: OVERFLOW_PADDING,
apply(sizeProps) {
const { firstElementChild } = refs.floating.current ?? {};
if (!(firstElementChild instanceof HTMLElement)) return;
Object.assign(firstElementChild.style, {
maxHeight: `${Math.max(0, sizeProps.availableHeight)}px`,
overflow: "auto"
});
}
}),
shift$1 && shift({
crossAxis: true,
limiter: limitShift(),
padding: 1
}),
arrow({ element: arrowRef })
];
const slotName = useContext(slotNameContext) || __unstableSlotName;
const slot = useSlot(slotName);
let onDialogClose;
if (onClose || onFocusOutside) onDialogClose = (type, event) => {
if (type === "focus-outside") {
const blurTarget = event?.target;
const referenceElement = refs.reference.current;
const floatingElement = refs.floating.current;
const isBlurFromThisPopover = referenceElement && "contains" in referenceElement && referenceElement.contains(blurTarget) || floatingElement?.contains(blurTarget);
const ownerDocument = floatingElement?.ownerDocument;
if (!isBlurFromThisPopover && !("relatedTarget" in event && event.relatedTarget) && ownerDocument?.activeElement === ownerDocument?.body) return;
const relatedTarget = "relatedTarget" in event ? event.relatedTarget : null;
if (relatedTarget instanceof Element && relatedTarget.closest("[data-wp-compat-overlay-slot]")) return;
if (floatingElement && ownerDocument?.activeElement instanceof Element && floatingElement.contains(ownerDocument.activeElement)) return;
if (onFocusOutside) onFocusOutside(event);
else if (onClose) onClose();
} else if (onClose) onClose();
};
const [dialogRef, dialogProps] = __experimentalUseDialog({
constrainTabbing,
focusOnMount,
onKeyDown,
__unstableOnClose: onDialogClose,
onClose: onDialogClose
});
const { x, y, refs, elements, strategy, update, placement: computedPlacement, middlewareData: { arrow: arrowData } } = useFloating({
placement: normalizedPlacementFromProps === "overlay" ? void 0 : normalizedPlacementFromProps,
middleware,
whileElementsMounted: (referenceParam, floatingParam, updateParam) => autoUpdate(referenceParam, floatingParam, updateParam, {
layoutShift: false,
animationFrame: true
})
});
const arrowCallbackRef = useCallback((node) => {
arrowRef.current = node;
update();
}, [update]);
const anchorRefTop = anchorRef?.top;
const anchorRefBottom = anchorRef?.bottom;
const anchorRefStartContainer = anchorRef?.startContainer;
const anchorRefCurrent = anchorRef?.current;
useLayoutEffect(() => {
const resultingReferenceElement = getReferenceElement({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement
});
refs.setReference(resultingReferenceElement);
}, [
anchor,
anchorRef,
anchorRefTop,
anchorRefBottom,
anchorRefStartContainer,
anchorRefCurrent,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
refs
]);
const popoverElementRef = useRef(null);
const mergedFloatingRef = useMergeRefs([
refs.setFloating,
dialogRef,
popoverElementRef,
forwardedRef
]);
useLayoutEffect(() => {
const popoverElement = popoverElementRef.current;
if (!popoverElement) return;
popoverElement.style.willChange = "transform";
const timeoutId = setTimeout(() => {
popoverElement.style.willChange = "auto";
}, WILL_CHANGE_IDLE_TIMEOUT);
return () => clearTimeout(timeoutId);
}, [
x,
y,
elements.floating
]);
const style = isExpanded ? void 0 : {
position: strategy,
top: 0,
left: 0,
x: computePopoverPosition(x),
y: computePopoverPosition(y)
};
const shouldReduceMotion = useReducedMotion();
const shouldAnimate = animate && !isExpanded && !shouldReduceMotion;
const [animationFinished, setAnimationFinished] = useState(false);
const { style: motionInlineStyles, ...otherMotionProps } = useMemo(() => placementToMotionAnimationProps(computedPlacement), [computedPlacement]);
const animationProps = shouldAnimate ? {
style: {
...contentStyle,
...motionInlineStyles,
...style
},
onAnimationComplete: () => setAnimationFinished(true),
...otherMotionProps
} : {
animate: false,
style: {
...contentStyle,
...style
}
};
const isPositioned = (!shouldAnimate || animationFinished) && x !== null && y !== null;
let content = /* @__PURE__ */ jsxs(motion.div, {
className: clsx(className, {
"is-expanded": isExpanded,
"is-positioned": isPositioned,
[`is-${computedVariant === "toolbar" ? "alternate" : computedVariant}`]: computedVariant
}),
...animationProps,
...contentProps,
ref: mergedFloatingRef,
...dialogProps,
tabIndex: -1,
children: [
isExpanded && /* @__PURE__ */ jsx(ScrollLock, {}),
isExpanded && /* @__PURE__ */ jsxs("div", {
className: "components-popover__header",
children: [/* @__PURE__ */ jsx("span", {
className: "components-popover__header-title",
children: headerTitle
}), /* @__PURE__ */ jsx(Button, {
className: "components-popover__close",
size: "small",
icon: close,
onClick: onClose,
label: __("Close")
})]
}),
/* @__PURE__ */ jsx("div", {
className: "components-popover__content",
children
}),
hasArrow && /* @__PURE__ */ jsx("div", {
ref: arrowCallbackRef,
className: ["components-popover__arrow", `is-${computedPlacement.split("-")[0]}`].join(" "),
style: {
left: typeof arrowData?.x !== "undefined" && Number.isFinite(arrowData.x) ? `${arrowData.x}px` : "",
top: typeof arrowData?.y !== "undefined" && Number.isFinite(arrowData.y) ? `${arrowData.y}px` : ""
},
children: /* @__PURE__ */ jsx(ArrowTriangle, {})
})
]
});
const shouldRenderWithinSlot = slot.ref && !inline;
const hasAnchor = anchorRef || anchorRect || anchor;
if (shouldRenderWithinSlot) content = /* @__PURE__ */ jsx(Fill, {
name: slotName,
children: content
});
else if (!inline) content = createPortal(/* @__PURE__ */ jsx(StyleProvider, {
document,
children: content
}), getPopoverFallbackContainer());
if (hasAnchor) return content;
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", { ref: anchorRefFallback }), content] });
};
const PopoverSlot = forwardRef(({ name = SLOT_NAME }, ref) => {
return /* @__PURE__ */ jsx(Slot, {
bubblesVirtually: true,
name,
className: "popover-slot",
ref
});
});
/**
* `Popover` renders its content in a floating modal. If no explicit anchor is passed via props, it anchors to its parent element by default.
*
* ```jsx
* import { Button, Popover } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyPopover = () => {
* const [ isVisible, setIsVisible ] = useState( false );
* const toggleVisible = () => {
* setIsVisible( ( state ) => ! state );
* };
*
* return (
* <Button variant="secondary" onClick={ toggleVisible }>
* Toggle Popover!
* { isVisible && <Popover>Popover is toggled!</Popover> }
* </Button>
* );
* };
* ```
*
*/
const Popover = Object.assign(contextConnect(UnforwardedPopover, "Popover"), {
/**
* Renders a slot that is used internally by Popover for rendering content.
*/
Slot: Object.assign(PopoverSlot, { displayName: "Popover.Slot" }),
/**
* Provides a context to manage popover slot names.
*
* This is marked as unstable and should not be used directly.
*/
__unstableSlotNameProvider: Object.assign(slotNameContext.Provider, { displayName: "Popover.__unstableSlotNameProvider" })
});
export { Popover, Popover as default, PopoverSlot, SLOT_NAME };
//# sourceMappingURL=index.mjs.map