@atlaskit/popup
Version:
A popup displays brief content in an overlay.
263 lines (253 loc) • 11.5 kB
JavaScript
/* popup-top-layer.tsx generated by @compiled/babel-plugin v3.0.4 */
import _extends from "@babel/runtime/helpers/extends";
import * as React from 'react';
import { ax, ix } from "@compiled/react/runtime";
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 { PopupContentRenderer } from './internal/popup-content-renderer';
import { useRoleProps } from './internal/top-layer-bridge';
// Top-layer positioning is handled by CSS Anchor Positioning, not inline styles.
const EMPTY_STYLE = {};
/**
* 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 const PopupTopLayer = /*#__PURE__*/memo(function PopupTopLayer({
xcss,
isOpen,
id: providedId,
offset: offsetProp,
testId,
UNSAFE__disableInitialAutoFocus,
trigger,
content,
onClose: providedOnClose,
mode = 'auto',
placement = 'auto',
fallbackPlacements: _fallbackPlacements,
shouldFlip: _shouldFlip = true,
popupComponent: PopupContainer,
// top-layer: initial focus follows `role`. No-op.
// eslint-disable-next-line -eslint/no-unused-vars
autoFocus: _autoFocus = true,
shouldFitContainer = false,
// top-layer: focus returns as the platform returns it (`Popover` with `mode="manual"`), and
// `false` does not stop it. No-op. To focus another element, focus it in `onClose`.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
shouldReturnFocus: _shouldReturnFocus = true,
role,
label,
titleId,
// No-op props.
// These props are accepted for API compatibility but have no effect
// in the top-layer path. Each is documented with why it is unnecessary.
// top-layer: stacking managed by browser top layer. zIndex is a no-op.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
zIndex: _zIndex,
// top-layer: always renders in top layer. shouldRenderToParent is a no-op.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
shouldRenderToParent: _shouldRenderToParent,
// top-layer: CSS Anchor Positioning replaces Popper strategy. No-op.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
strategy: _strategy,
// top-layer: Popper.js modifiers not applicable. No-op.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
modifiers: _modifiers,
// top-layer: viewport is the natural boundary. No-op.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
boundary: _boundary,
// top-layer: viewport is the natural boundary. No-op.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
rootBoundary: _rootBoundary,
// top-layer: `useManualLightDismiss` replaces the capture-phase click handler. It listens in the
// capture phase, and a press must start and end outside.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
shouldUseCaptureOnOutsideClick: _shouldUseCaptureOnOutsideClick,
// top-layer: focus trapping is role-based. shouldDisableFocusLock is a no-op.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
shouldDisableFocusLock: _shouldDisableFocusLock,
// top-layer: maps onto `'max-available'`, capping the popup to the space
// between the trigger and the viewport edge. `PopoverSurface` already owns
// `overflow: auto`, so the capped surface scrolls.
//
// Keep the explicit `false`: `undefined` previously reached an
// `isEnabled = true` default and silently enabled fitting for every popup
// that omitted the prop.
shouldFitViewport = false,
// top-layer: appearance is accepted but UNSAFE_modal-below-sm is not yet implemented.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
appearance: _appearance
}) {
const onClose = providedOnClose !== null && providedOnClose !== void 0 ? providedOnClose : noop;
const triggerRef = useRef(null);
// Stable, so the trigger ref is not detached and attached again on every render.
const setTriggerRef = useCallback(node => {
triggerRef.current = node;
}, []);
const 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`.
*/
const consumerInitialFocusRef = useRef(null);
const setInitialFocusRef = useCallback(value => {
consumerInitialFocusRef.current = typeof value === 'function' ? value(consumerInitialFocusRef.current) : value;
}, []);
const 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.
const topLayerPlacement = useMemo(() => fromLegacyPlacement({
legacy: placement,
offset: offsetProp
}), [placement, offsetProp]);
useAnchoredPopover({
anchorRef: triggerRef,
popoverRef,
placement: topLayerPlacement,
isOpen,
...getPopupAxisSizes({
shouldFitContainer,
shouldFitViewport
})
});
// onClose bridge.
// Translates top-layer's { reason: TPopoverCloseReason } into legacy
// onClose(event, currentLevel?) by synthesizing DOM events.
//
// Focus return: `Popover` returns focus to the opener as the popup hides after Escape or a
// close from `isOpen`, as the browser does for an `auto` popover. An outside press leaves focus
// where the user pressed. No manual triggerRef.current?.focus() is needed.
const handleOnClose = useCallback(({
reason
}) => {
onClose(createPopoverCloseEvent({
reason
}));
}, [onClose]);
/**
* **Ask first, close second**
*
* Both modes render a `manual` popover, so the browser never closes it. An outside press or Escape
* asks `onClose`, and the popup hides only when `isOpen` becomes `false`, as legacy `Popup` did. A
* press on the trigger does not ask: the trigger's own click decides.
* See `@atlaskit/top-layer` `notes/decisions/wrappers-ask-first-close.md`.
*/
const isManual = mode === 'manual';
// A `manual` popup without `onClose` stays open until `isOpen` changes, and takes no Escape.
const isClosable = !isManual || Boolean(providedOnClose);
const triggerRefs = useMemo(() => [triggerRef], []);
useManualLightDismiss({
isOpen: isOpen && isClosable,
popoverRef,
additionalInsideElementRefs: triggerRefs,
onClose: handleOnClose
});
// 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.
const contentProps = useMemo(() => ({
isOpen,
update: noop,
onClose,
setInitialFocusRef
}), [isOpen, onClose, setInitialFocusRef]);
// Role mapping.
// Build the role/label props for Popover.
// Roles requiring accessible names must have label or labelledBy.
const roleProps = useRoleProps({
role,
label,
titleId,
initialFocusRef: consumerInitialFocusRef
});
const resolvedPopoverId = providedId !== null && providedId !== void 0 ? providedId : popoverId;
const ariaAttributes = getAriaForTrigger({
role: getTriggerRole({
role: roleProps.role
}),
isOpen,
popoverId: resolvedPopoverId
});
// Narrow to ForwardRefExoticComponent so JSX accepts the ref prop.
// All popupComponent implementations use forwardRef per the PopupComponentProps contract.
const Container = PopupContainer;
// Map to legacy TriggerProps.
const triggerProps = {
ref: setTriggerRef,
'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__disableInitialAutoFocus: UNSAFE__disableInitialAutoFocus,
isOpen: isOpen,
mode: "manual"
// Without it, `requestClosePopovers()` cannot close the popup.
,
onClose: isClosable ? handleOnClose : undefined,
shouldAnimate: true,
placement: topLayerPlacement,
testId: testId && `${testId}--container`
}), Container ? /*#__PURE__*/React.createElement(Container
// No `id`: the `Popover` host has it, and the trigger's `aria-controls` points at
// the host. Passing it here too would put the same `id` on two elements.
, {
style: EMPTY_STYLE,
"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, /*#__PURE__*/React.createElement(PopupContentRenderer, {
render: content,
contentProps: 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, /*#__PURE__*/React.createElement(PopupContentRenderer, {
render: content,
contentProps: contentProps
}))))));
});