UNPKG

@wordpress/components

Version:
401 lines (387 loc) 14.4 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.SLOT_NAME = exports.PopoverSlot = exports.Popover = void 0; var _clsx = _interopRequireDefault(require("clsx")); var _reactDom = require("@floating-ui/react-dom"); var _framerMotion = require("framer-motion"); var _element = require("@wordpress/element"); var _compose = require("@wordpress/compose"); var _icons = require("@wordpress/icons"); var _deprecated = _interopRequireDefault(require("@wordpress/deprecated")); var _primitives = require("@wordpress/primitives"); var _i18n = require("@wordpress/i18n"); var _button = _interopRequireDefault(require("../button")); var _scrollLock = _interopRequireDefault(require("../scroll-lock")); var _slotFill = require("../slot-fill"); var _utils = require("./utils"); var _context = require("../context"); var _overlayMiddlewares = require("./overlay-middlewares"); var _styleProvider = require("../style-provider"); var _jsxRuntime = require("react/jsx-runtime"); /** * External dependencies */ /** * WordPress dependencies */ /** * Internal dependencies */ /** * Name of slot in which popover should fill. * * @type {string} */ const SLOT_NAME = exports.SLOT_NAME = 'Popover'; /** * Virtual padding to account for overflow boundaries. * * @type {number} */ const OVERFLOW_PADDING = 8; // An SVG displaying a triangle facing down, filled with a solid // color and bordered in such a way to create an arrow-like effect. // Keeping the SVG's viewbox squared simplify the arrow positioning // calculations. const ArrowTriangle = () => /*#__PURE__*/(0, _jsxRuntime.jsxs)(_primitives.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 100 100", className: "components-popover__triangle", role: "presentation", children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_primitives.Path, { className: "components-popover__triangle-bg", d: "M 0 0 L 50 50 L 100 0" }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_primitives.Path, { className: "components-popover__triangle-border", d: "M 0 0 L 50 50 L 100 0", vectorEffect: "non-scaling-stroke" })] }); const slotNameContext = (0, _element.createContext)(undefined); 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 = true, resize = true, shift = false, inline = false, variant, style: contentStyle, // Deprecated props __unstableForcePosition, anchorRef, anchorRect, getAnchorRect, isAlternate, // Rest ...contentProps } = (0, _context.useContextSystem)(props, 'Popover'); let computedFlipProp = flip; let computedResizeProp = resize; if (__unstableForcePosition !== undefined) { (0, _deprecated.default)('`__unstableForcePosition` prop in wp.components.Popover', { since: '6.1', version: '6.3', alternative: '`flip={ false }` and `resize={ false }`' }); // Back-compat, set the `flip` and `resize` props // to `false` to replicate `__unstableForcePosition`. computedFlipProp = !__unstableForcePosition; computedResizeProp = !__unstableForcePosition; } if (anchorRef !== undefined) { (0, _deprecated.default)('`anchorRef` prop in wp.components.Popover', { since: '6.1', alternative: '`anchor` prop' }); } if (anchorRect !== undefined) { (0, _deprecated.default)('`anchorRect` prop in wp.components.Popover', { since: '6.1', alternative: '`anchor` prop' }); } if (getAnchorRect !== undefined) { (0, _deprecated.default)('`getAnchorRect` prop in wp.components.Popover', { since: '6.1', alternative: '`anchor` prop' }); } const computedVariant = isAlternate ? 'toolbar' : variant; if (isAlternate !== undefined) { (0, _deprecated.default)('`isAlternate` prop in wp.components.Popover', { since: '6.2', alternative: "`variant` prop with the `'toolbar'` value" }); } const arrowRef = (0, _element.useRef)(null); const [fallbackReferenceElement, setFallbackReferenceElement] = (0, _element.useState)(null); const anchorRefFallback = (0, _element.useCallback)(node => { setFallbackReferenceElement(node); }, []); const isMobileViewport = (0, _compose.useViewportMatch)('medium', '<'); const isExpanded = expandOnMobile && isMobileViewport; const hasArrow = !isExpanded && !noArrow; const normalizedPlacementFromProps = position ? (0, _utils.positionToPlacement)(position) : placementProp; const middleware = [...(placementProp === 'overlay' ? (0, _overlayMiddlewares.overlayMiddlewares)() : []), (0, _reactDom.offset)(offsetProp), computedFlipProp && (0, _reactDom.flip)(), computedResizeProp && (0, _reactDom.size)({ padding: OVERFLOW_PADDING, apply(sizeProps) { var _refs$floating$curren; const { firstElementChild } = (_refs$floating$curren = refs.floating.current) !== null && _refs$floating$curren !== void 0 ? _refs$floating$curren : {}; // Only HTMLElement instances have the `style` property. if (!(firstElementChild instanceof HTMLElement)) { return; } // Reduce the height of the popover to the available space. Object.assign(firstElementChild.style, { maxHeight: `${Math.max(0, sizeProps.availableHeight)}px`, overflow: 'auto' }); } }), shift && (0, _reactDom.shift)({ crossAxis: true, limiter: (0, _reactDom.limitShift)(), padding: 1 // Necessary to avoid flickering at the edge of the viewport. }), (0, _reactDom.arrow)({ element: arrowRef })]; const slotName = (0, _element.useContext)(slotNameContext) || __unstableSlotName; const slot = (0, _slotFill.useSlot)(slotName); let onDialogClose; if (onClose || onFocusOutside) { onDialogClose = (type, event) => { // Ideally the popover should have just a single onClose prop and // not three props that potentially do the same thing. if (type === 'focus-outside' && onFocusOutside) { onFocusOutside(event); } else if (onClose) { onClose(); } }; } const [dialogRef, dialogProps] = (0, _compose.__experimentalUseDialog)({ constrainTabbing, focusOnMount, __unstableOnClose: onDialogClose, // @ts-expect-error The __unstableOnClose property needs to be deprecated first (see https://github.com/WordPress/gutenberg/pull/27675) onClose: onDialogClose }); const { // Positioning coordinates x, y, // Object with "regular" refs to both "reference" and "floating" refs, // Type of CSS position property to use (absolute or fixed) strategy, update, placement: computedPlacement, middlewareData: { arrow: arrowData } } = (0, _reactDom.useFloating)({ placement: normalizedPlacementFromProps === 'overlay' ? undefined : normalizedPlacementFromProps, middleware, whileElementsMounted: (referenceParam, floatingParam, updateParam) => (0, _reactDom.autoUpdate)(referenceParam, floatingParam, updateParam, { layoutShift: false, animationFrame: true }) }); const arrowCallbackRef = (0, _element.useCallback)(node => { arrowRef.current = node; update(); }, [update]); // When any of the possible anchor "sources" change, // recompute the reference element (real or virtual) and its owner document. const anchorRefTop = anchorRef?.top; const anchorRefBottom = anchorRef?.bottom; const anchorRefStartContainer = anchorRef?.startContainer; const anchorRefCurrent = anchorRef?.current; (0, _element.useLayoutEffect)(() => { const resultingReferenceElement = (0, _utils.getReferenceElement)({ anchor, anchorRef, anchorRect, getAnchorRect, fallbackReferenceElement }); refs.setReference(resultingReferenceElement); }, [anchor, anchorRef, anchorRefTop, anchorRefBottom, anchorRefStartContainer, anchorRefCurrent, anchorRect, getAnchorRect, fallbackReferenceElement, refs]); const mergedFloatingRef = (0, _compose.useMergeRefs)([refs.setFloating, dialogRef, forwardedRef]); const style = isExpanded ? undefined : { position: strategy, top: 0, left: 0, // `x` and `y` are framer-motion specific props and are shorthands // for `translateX` and `translateY`. Currently it is not possible // to use `translateX` and `translateY` because those values would // be overridden by the return value of the // `placementToMotionAnimationProps` function. x: (0, _utils.computePopoverPosition)(x), y: (0, _utils.computePopoverPosition)(y) }; const shouldReduceMotion = (0, _compose.useReducedMotion)(); const shouldAnimate = animate && !isExpanded && !shouldReduceMotion; const [animationFinished, setAnimationFinished] = (0, _element.useState)(false); const { style: motionInlineStyles, ...otherMotionProps } = (0, _element.useMemo)(() => (0, _utils.placementToMotionAnimationProps)(computedPlacement), [computedPlacement]); const animationProps = shouldAnimate ? { style: { ...contentStyle, ...motionInlineStyles, ...style }, onAnimationComplete: () => setAnimationFinished(true), ...otherMotionProps } : { animate: false, style: { ...contentStyle, ...style } }; // When Floating UI has finished positioning and Framer Motion has finished animating // the popover, add the `is-positioned` class to signal that all transitions have finished. const isPositioned = (!shouldAnimate || animationFinished) && x !== null && y !== null; let content = /*#__PURE__*/(0, _jsxRuntime.jsxs)(_framerMotion.motion.div, { className: (0, _clsx.default)(className, { 'is-expanded': isExpanded, 'is-positioned': isPositioned, // Use the 'alternate' classname for 'toolbar' variant for back compat. [`is-${computedVariant === 'toolbar' ? 'alternate' : computedVariant}`]: computedVariant }), ...animationProps, ...contentProps, ref: mergedFloatingRef, ...dialogProps, tabIndex: -1, children: [isExpanded && /*#__PURE__*/(0, _jsxRuntime.jsx)(_scrollLock.default, {}), isExpanded && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", { className: "components-popover__header", children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", { className: "components-popover__header-title", children: headerTitle }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.default, { className: "components-popover__close", size: "small", icon: _icons.close, onClick: onClose, label: (0, _i18n.__)('Close') })] }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: "components-popover__content", children: children }), hasArrow && /*#__PURE__*/(0, _jsxRuntime.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__*/(0, _jsxRuntime.jsx)(ArrowTriangle, {}) })] }); const shouldRenderWithinSlot = slot.ref && !inline; const hasAnchor = anchorRef || anchorRect || anchor; if (shouldRenderWithinSlot) { content = /*#__PURE__*/(0, _jsxRuntime.jsx)(_slotFill.Fill, { name: slotName, children: content }); } else if (!inline) { content = (0, _element.createPortal)(/*#__PURE__*/(0, _jsxRuntime.jsx)(_styleProvider.StyleProvider, { document: document, children: content }), getPopoverFallbackContainer()); } if (hasAnchor) { return content; } return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, { children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", { ref: anchorRefFallback }), content] }); }; // Export the PopoverSlot individually to allow typescript to pick the types up. const PopoverSlot = exports.PopoverSlot = (0, _element.forwardRef)(({ name = SLOT_NAME }, ref) => { return /*#__PURE__*/(0, _jsxRuntime.jsx)(_slotFill.Slot, { bubblesVirtually: true, name: name, className: "popover-slot", ref: 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 = exports.Popover = Object.assign((0, _context.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' }) }); var _default = exports.default = Popover; //# sourceMappingURL=index.js.map