@atlaskit/popup
Version:
A popup displays brief content in an overlay.
272 lines (263 loc) • 11.8 kB
JavaScript
/* popup-top-layer.tsx generated by @compiled/babel-plugin v3.0.2 */
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import * as React from 'react';
import { ax, ix } from "@compiled/react/runtime";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import { Fragment, memo, useCallback, useMemo, useRef } from 'react';
import noop from '@atlaskit/ds-lib/noop';
import MotionPresenceBoundary from '@atlaskit/motion/motion-presence-boundary';
import { getAriaForTrigger } from '@atlaskit/top-layer/get-aria-for-trigger';
import { fromLegacyPlacement } from '@atlaskit/top-layer/placement-map/index';
import { PopoverSurface } from '@atlaskit/top-layer/popover-surface';
import { createPopoverCloseEvent } from '@atlaskit/top-layer/popover/create-close-event';
import { Popover } from '@atlaskit/top-layer/popover/popover';
import { useAnchoredPopover } from '@atlaskit/top-layer/use-anchored-popover';
import { useManualLightDismiss } from '@atlaskit/top-layer/use-manual-light-dismiss';
import { usePopoverId } from '@atlaskit/top-layer/use-popover-id';
import { getPopupAxisSizes } from './internal/get-popup-axis-sizes';
import { getTriggerRole } from './internal/get-trigger-role';
import { useRoleProps } from './internal/top-layer-bridge';
// Top-layer positioning is handled by CSS Anchor Positioning, not inline styles.
var EMPTY_STYLE = {};
/**
* `Popover` props for `mode`. A manual popover gets `onClose` only when the consumer gave one, so
* without it `requestClosePopovers()` cannot close the popup.
*/
function getModeProps(_ref) {
var isManual = _ref.isManual,
hasOnClose = _ref.hasOnClose,
handleOnClose = _ref.handleOnClose;
if (!isManual) {
return {
mode: 'auto',
onClose: handleOnClose
};
}
if (!hasOnClose) {
return {
mode: 'manual'
};
}
return {
mode: 'manual',
onClose: handleOnClose
};
}
/**
* Top-layer implementation of Popup.
*
* Replaces the legacy @atlaskit/popup rendering pipeline
* (Popper.js + Portal + focus-trap + @atlaskit/layering)
* with the native Popover API + CSS Anchor Positioning via @atlaskit/top-layer.
*
* Gated behind the `platform-dst-top-layer` feature flag.
*/
export var PopupTopLayer = /*#__PURE__*/memo(function PopupTopLayer(_ref2) {
var xcss = _ref2.xcss,
isOpen = _ref2.isOpen,
providedId = _ref2.id,
offsetProp = _ref2.offset,
testId = _ref2.testId,
UNSAFE__disableAutoFocusForAsyncWrapper = _ref2.UNSAFE__disableAutoFocusForAsyncWrapper,
trigger = _ref2.trigger,
content = _ref2.content,
providedOnClose = _ref2.onClose,
_ref2$mode = _ref2.mode,
mode = _ref2$mode === void 0 ? 'auto' : _ref2$mode,
_ref2$placement = _ref2.placement,
placement = _ref2$placement === void 0 ? 'auto' : _ref2$placement,
_fallbackPlacements = _ref2.fallbackPlacements,
_ref2$shouldFlip = _ref2.shouldFlip,
_shouldFlip = _ref2$shouldFlip === void 0 ? true : _ref2$shouldFlip,
PopupContainer = _ref2.popupComponent,
_ref2$autoFocus = _ref2.autoFocus,
_autoFocus = _ref2$autoFocus === void 0 ? true : _ref2$autoFocus,
_ref2$shouldFitContai = _ref2.shouldFitContainer,
shouldFitContainer = _ref2$shouldFitContai === void 0 ? false : _ref2$shouldFitContai,
_ref2$shouldReturnFoc = _ref2.shouldReturnFocus,
_shouldReturnFocus = _ref2$shouldReturnFoc === void 0 ? true : _ref2$shouldReturnFoc,
role = _ref2.role,
label = _ref2.label,
titleId = _ref2.titleId,
_zIndex = _ref2.zIndex,
_shouldRenderToParent = _ref2.shouldRenderToParent,
_strategy = _ref2.strategy,
_modifiers = _ref2.modifiers,
_boundary = _ref2.boundary,
_rootBoundary = _ref2.rootBoundary,
_shouldUseCaptureOnOutsideClick = _ref2.shouldUseCaptureOnOutsideClick,
_shouldDisableFocusLock = _ref2.shouldDisableFocusLock,
_ref2$shouldFitViewpo = _ref2.shouldFitViewport,
shouldFitViewport = _ref2$shouldFitViewpo === void 0 ? false : _ref2$shouldFitViewpo,
_appearance = _ref2.appearance;
var onClose = providedOnClose !== null && providedOnClose !== void 0 ? providedOnClose : noop;
var triggerRef = useRef(null);
var popoverRef = useRef(null);
/**
* Consumer-chosen initial focus target.
*
* The legacy `Popup` surfaced `setInitialFocusRef` on the content
* render prop with a `Dispatch<SetStateAction<HTMLElement | null>>`
* signature so it could be passed as a React `ref` callback. We
* keep the same shape for API compatibility, but store the value in
* a ref. `Popover` reads it as `initialFocusRef` when it opens. For a
* role that moves focus, a target inside the popup takes focus instead
* of the role default, and focus moves once. Other roles ignore it. `autoFocus` has no effect here: role and focus go
* together. See `@atlaskit/top-layer` `notes/decisions/role-and-focus.md`.
*/
var consumerInitialFocusRef = useRef(null);
var setInitialFocusRef = useCallback(function (value) {
consumerInitialFocusRef.current = typeof value === 'function' ? value(consumerInitialFocusRef.current) : value;
}, []);
var popoverId = usePopoverId();
// Placement conversion.
// Legacy `offset` is the popper `[along, away]` tuple; `fromLegacyPlacement`
// folds it into the new `placement.offset` shape so it travels with placement.
var topLayerPlacement = useMemo(function () {
return fromLegacyPlacement({
legacy: placement,
offset: offsetProp
});
}, [placement, offsetProp]);
useAnchoredPopover(_objectSpread({
anchorRef: triggerRef,
popoverRef: popoverRef,
placement: topLayerPlacement,
isOpen: isOpen
}, getPopupAxisSizes({
shouldFitContainer: shouldFitContainer,
shouldFitViewport: shouldFitViewport
})));
// onClose bridge.
// Translates top-layer's { reason: TPopoverCloseReason } into legacy
// onClose(event, currentLevel?) by synthesizing DOM events.
//
// Focus restoration is handled natively by the Popover API:
// - Escape: browser restores focus to the trigger automatically
// - Click-outside: browser does NOT restore (correct behavior)
// No manual triggerRef.current?.focus() is needed.
var handleOnClose = useCallback(function (_ref3) {
var reason = _ref3.reason;
onClose(createPopoverCloseEvent({
reason: reason
}));
}, [onClose]);
/**
* Manual mode: the browser never light-dismisses the popover, so a press on the trigger does not
* close it. With `onClose`, an outside press or Escape calls it, as on an auto popup. The trigger
* is exempt.
*/
var isManual = mode === 'manual';
var triggerRefs = useMemo(function () {
return [triggerRef];
}, []);
var handleManualLightDismiss = useCallback(function (_ref4) {
var reason = _ref4.reason;
if (reason !== 'light-dismiss') {
handleOnClose({
reason: reason
});
return;
}
// Native light dismiss does not restore focus, but the consumer's programmatic close does
// when focus is inside the popover. The press usually moved focus out already. If not (for
// example an outside `mousedown` called `preventDefault()`), blur first, as an auto light
// dismiss would.
var popover = popoverRef.current;
var activeElement = popover === null || popover === void 0 ? void 0 : popover.ownerDocument.activeElement;
if (activeElement instanceof HTMLElement && popover !== null && popover !== void 0 && popover.contains(activeElement)) {
activeElement.blur();
}
handleOnClose({
reason: reason
});
}, [handleOnClose]);
useManualLightDismiss({
isOpen: isOpen && isManual && Boolean(providedOnClose),
popoverRef: popoverRef,
additionalInsideElementRefs: triggerRefs,
onClose: handleManualLightDismiss
});
// Content render-prop bridge.
// Legacy content() receives { isOpen, update, setInitialFocusRef, onClose }.
// update is a no-op because CSS Anchor Positioning self-updates.
// The args always hold the setter; the `TPopup` types decide who can see it.
var contentProps = useMemo(function () {
return {
isOpen: isOpen,
update: noop,
onClose: onClose,
setInitialFocusRef: setInitialFocusRef
};
}, [isOpen, onClose, setInitialFocusRef]);
// Role mapping.
// Build the role/label props for Popover.
// Roles requiring accessible names must have label or labelledBy.
var roleProps = useRoleProps({
role: role,
label: label,
titleId: titleId,
initialFocusRef: consumerInitialFocusRef
});
var resolvedPopoverId = providedId !== null && providedId !== void 0 ? providedId : popoverId;
var ariaAttributes = getAriaForTrigger({
role: getTriggerRole({
role: roleProps.role
}),
isOpen: isOpen,
popoverId: resolvedPopoverId
});
// Narrow to ForwardRefExoticComponent so JSX accepts the ref prop.
// All popupComponent implementations use forwardRef per the PopupComponentProps contract.
var Container = PopupContainer;
// Map to legacy TriggerProps.
var triggerProps = {
ref: function ref(node) {
triggerRef.current = node;
},
'aria-controls': ariaAttributes['aria-controls'],
// `aria-expanded` reflects current open state.
'aria-expanded': ariaAttributes['aria-expanded'],
'aria-haspopup': ariaAttributes['aria-haspopup']
};
return /*#__PURE__*/React.createElement(Fragment, null, trigger(triggerProps), /*#__PURE__*/React.createElement(Popover, _extends({
ref: popoverRef,
id: resolvedPopoverId
}, roleProps, {
UNSAFE__disableAutoFocusForAsyncWrapper: UNSAFE__disableAutoFocusForAsyncWrapper,
isOpen: isOpen
}, getModeProps({
isManual: isManual,
hasOnClose: Boolean(providedOnClose),
handleOnClose: handleOnClose
}), {
shouldAnimate: true,
placement: topLayerPlacement,
testId: testId && "".concat(testId, "--container")
}), Container ? /*#__PURE__*/React.createElement(Container, {
style: EMPTY_STYLE,
id: providedId,
"data-placement": placement,
"data-testid": testId,
tabIndex: -1,
xcss: xcss
// Forwarded because several in-tree containers key their own
// `overflow: auto` branch off it.
,
shouldFitViewport: shouldFitViewport
}, /*#__PURE__*/React.createElement(MotionPresenceBoundary, null, content(contentProps))) :
/*#__PURE__*/
// `PopoverSurface` owns `overflow: auto` and the `box-shadow` on the
// same element, so it is the scroll container. The wrapper exists only
// to carry the consumer's `xcss`: `PopoverSurface` exposes no
// `className` or `xcss` by design, so `xcss` lands on a CHILD of the
// surface. `width` works there; surface-level declarations apply one
// level in. Same shape as `compositional/popup-content-top-layer.tsx`.
React.createElement(PopoverSurface, null, /*#__PURE__*/React.createElement("div", {
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop
className: xcss,
"data-testid": testId
}, /*#__PURE__*/React.createElement(MotionPresenceBoundary, null, content(contentProps))))));
});