@atlaskit/select
Version:
Select allows users to make a single selection or multiple selections from a list of options.
436 lines (420 loc) • 18.7 kB
JavaScript
/* popup-select-top-layer.tsx generated by @compiled/babel-plugin v3.0.4 */
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["closeMenuOnSelect", "shouldCloseMenuOnTab", "footer", "searchThreshold", "maxMenuWidth", "minMenuWidth", "maxMenuHeight", "target", "label", "placeholder", "testId", "isOpen", "defaultIsOpen", "options", "isSearchable", "components", "styles", "onChange", "onKeyDown", "onOpen", "onClose", "onMenuOpen", "onMenuClose", "popperProps", "shouldPreventEscapePropagation"];
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, forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { bind } from 'bind-event-listener';
import { mergeStyles } from '@atlaskit/react-select/styles';
import { fromLegacyPlacement } from '@atlaskit/top-layer/placement-map/index';
import { PopoverSurface } from '@atlaskit/top-layer/popover-surface';
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 Select from '../select';
import { defaultComponents } from './components';
import { DummyControl } from './dummy-control';
/**
* The `[along, away]` offset the legacy popper gave for `popperProps.modifiers`.
*
* Legacy PopupSelect spreads `popperProps` over its defaults, so a consumer `modifiers` value
* replaces the default list, with its `[0, 8]` offset. Only a consumer offset modifier then sets
* the offset. Popper ignores a popper v1 `modifiers` object, so that gives `[0, 0]` too.
*
* Exported for tests only.
*/
export function getLegacyOffset(_ref) {
var _find;
var modifiers = _ref.modifiers;
if (modifiers == null) {
return [0, 8];
}
var value = Array.isArray(modifiers) ? (_find = modifiers.find(function (modifier) {
return (modifier === null || modifier === void 0 ? void 0 : modifier.name) === 'offset';
})) === null || _find === void 0 || (_find = _find.options) === null || _find === void 0 ? void 0 : _find.offset : undefined;
if (Array.isArray(value) && value.length === 2) {
return [Number(value[0]) || 0, Number(value[1]) || 0];
}
return [0, 0];
}
/**
* Top-layer implementation of PopupSelect.
*
* Replaces the legacy PopupSelect rendering pipeline
* (react-popper + createPortal + react-focus-lock + @atlaskit/layering + z-index)
* with the native Popover API + CSS Anchor Positioning via @atlaskit/top-layer.
*
* Gated behind the `platform-dst-top-layer` feature flag.
*/
function PopupSelectTopLayerInner(_ref2, forwardedRef) {
var _popperProps$placemen, _getLabel;
var _ref2$closeMenuOnSele = _ref2.closeMenuOnSelect,
closeMenuOnSelect = _ref2$closeMenuOnSele === void 0 ? true : _ref2$closeMenuOnSele,
_ref2$shouldCloseMenu = _ref2.shouldCloseMenuOnTab,
shouldCloseMenuOnTab = _ref2$shouldCloseMenu === void 0 ? true : _ref2$shouldCloseMenu,
footer = _ref2.footer,
_ref2$searchThreshold = _ref2.searchThreshold,
searchThreshold = _ref2$searchThreshold === void 0 ? 5 : _ref2$searchThreshold,
_ref2$maxMenuWidth = _ref2.maxMenuWidth,
maxMenuWidth = _ref2$maxMenuWidth === void 0 ? 440 : _ref2$maxMenuWidth,
_ref2$minMenuWidth = _ref2.minMenuWidth,
minMenuWidth = _ref2$minMenuWidth === void 0 ? 220 : _ref2$minMenuWidth,
_ref2$maxMenuHeight = _ref2.maxMenuHeight,
maxMenuHeight = _ref2$maxMenuHeight === void 0 ? 300 : _ref2$maxMenuHeight,
target = _ref2.target,
label = _ref2.label,
placeholder = _ref2.placeholder,
testId = _ref2.testId,
isOpenProp = _ref2.isOpen,
defaultIsOpen = _ref2.defaultIsOpen,
_ref2$options = _ref2.options,
options = _ref2$options === void 0 ? [] : _ref2$options,
_ref2$isSearchable = _ref2.isSearchable,
isSearchable = _ref2$isSearchable === void 0 ? true : _ref2$isSearchable,
consumerComponents = _ref2.components,
consumerStyles = _ref2.styles,
onChange = _ref2.onChange,
onKeyDown = _ref2.onKeyDown,
onOpen = _ref2.onOpen,
onClose = _ref2.onClose,
onMenuOpen = _ref2.onMenuOpen,
onMenuClose = _ref2.onMenuClose,
popperProps = _ref2.popperProps,
_shouldPreventEscapePropagation = _ref2.shouldPreventEscapePropagation,
selectProps = _objectWithoutProperties(_ref2, _excluded);
// State.
// As on the legacy path, whether `isOpen` is controlled is decided once, at mount, and a new
// `true` or `false` is copied into the open state (a new `undefined` keeps it). A controlled
// popup does not close itself: an outside press and Escape ask through `onClose`, and a pick and
// Tab leave it to the consumer (for example a multi-value picker stays open). A consumer that
// passes `isOpen` only while open is not controlled: a pick, Tab, Escape and an outside press
// close it.
var _useState = useState(isOpenProp !== undefined),
_useState2 = _slicedToArray(_useState, 1),
isControlledAtMount = _useState2[0];
var _useState3 = useState(isOpenProp !== null && isOpenProp !== void 0 ? isOpenProp : Boolean(defaultIsOpen)),
_useState4 = _slicedToArray(_useState3, 2),
isOpen = _useState4[0],
setIsOpen = _useState4[1];
var _useState5 = useState(isOpenProp),
_useState6 = _slicedToArray(_useState5, 2),
lastIsOpenProp = _useState6[0],
setLastIsOpenProp = _useState6[1];
if (isOpenProp !== lastIsOpenProp) {
setLastIsOpenProp(isOpenProp);
if (isOpenProp !== undefined) {
setIsOpen(isOpenProp);
}
}
var selectRef = useRef(null);
var triggerRef = useRef(null);
var menuRef = useRef(null);
var popoverRef = useRef(null);
var popoverId = usePopoverId();
// Placement.
var legacyPlacement = (_popperProps$placemen = popperProps === null || popperProps === void 0 ? void 0 : popperProps.placement) !== null && _popperProps$placemen !== void 0 ? _popperProps$placemen : 'bottom-start';
var legacyOffset = useMemo(function () {
return getLegacyOffset({
modifiers: popperProps === null || popperProps === void 0 ? void 0 : popperProps.modifiers
});
}, [popperProps === null || popperProps === void 0 ? void 0 : popperProps.modifiers]);
var topLayerPlacement = useMemo(function () {
return fromLegacyPlacement({
legacy: legacyPlacement,
offset: legacyOffset
});
}, [legacyPlacement, legacyOffset]);
useAnchoredPopover({
anchorRef: triggerRef,
popoverRef: popoverRef,
placement: topLayerPlacement,
isOpen: isOpen
});
// Merged components.
var mergedComponents = useMemo(function () {
return _objectSpread(_objectSpread({}, defaultComponents), consumerComponents);
}, [consumerComponents]);
// Default styles.
var defaultStyles = useMemo(function () {
return {
groupHeading: function groupHeading(provided) {
return _objectSpread(_objectSpread({}, provided), {}, {
color: "var(--ds-text-subtlest, #6B6E76)"
});
}
};
}, []);
// Utils.
var getItemCount = useCallback(function () {
return options.reduce(function (count, groupOrOption) {
var group = groupOrOption;
if (group.options) {
return count + group.options.length;
}
return count + 1;
}, 0);
}, [options]);
var showSearchControl = isSearchable && getItemCount() > searchThreshold;
var getMaxHeight = useCallback(function () {
var _selectRef$current$se;
if (!selectRef.current) {
return maxMenuHeight;
}
var controlRef = (_selectRef$current$se = selectRef.current.select) === null || _selectRef$current$se === void 0 ? void 0 : _selectRef$current$se.controlRef;
var offsetHeight = showSearchControl && controlRef ? controlRef.offsetHeight : 0;
return maxMenuHeight - offsetHeight;
}, [maxMenuHeight, showSearchControl]);
var getLabel = useCallback(function () {
if (label) {
return label;
}
if (typeof placeholder === 'string') {
return placeholder;
}
return undefined;
}, [label, placeholder]);
// Open / Close.
var open = useCallback(function () {
if (!isControlledAtMount) {
setIsOpen(true);
}
onOpen === null || onOpen === void 0 || onOpen();
onMenuOpen === null || onMenuOpen === void 0 || onMenuOpen();
}, [isControlledAtMount, onOpen, onMenuOpen]);
var close = useCallback(function () {
if (!isControlledAtMount) {
setIsOpen(false);
}
onClose === null || onClose === void 0 || onClose();
onMenuClose === null || onMenuClose === void 0 || onMenuClose();
}, [isControlledAtMount, onClose, onMenuClose]);
/**
* For backwards compatibility
*/
useImperativeHandle(forwardedRef, function () {
return {
open: open,
close: close,
get selectRef() {
return selectRef.current;
},
get menuRef() {
return menuRef.current;
},
get targetRef() {
return triggerRef.current;
}
};
}, [close, open]);
// Call the open or close callbacks when `isOpen` is `true` or `false` (at mount, and on a change).
useEffect(function () {
if (isOpenProp === undefined) {
return;
}
if (isOpenProp) {
onOpen === null || onOpen === void 0 || onOpen();
onMenuOpen === null || onMenuOpen === void 0 || onMenuOpen();
} else {
onClose === null || onClose === void 0 || onClose();
onMenuClose === null || onMenuClose === void 0 || onMenuClose();
}
// Only react to changes in the `isOpen` prop
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpenProp]);
// Open the react-select menu when isOpen becomes true.
useEffect(function () {
if (isOpen && selectRef.current) {
var _selectRef$current$se2;
(_selectRef$current$se2 = selectRef.current.select) === null || _selectRef$current$se2 === void 0 || _selectRef$current$se2.openMenu('first');
}
}, [isOpen]);
// Event Handlers.
var handleTargetKeyDown = useCallback(function (event) {
if (event.key === 'ArrowDown') {
open();
}
}, [open]);
// Open the menu when the trigger is clicked. Mirrors the legacy
// `PopupSelect` global-click listener: consumers are not required to
// spread an `onClick`, so we walk up from the event target to the
// trigger ref instead.
useEffect(function () {
if (typeof window === 'undefined') {
return;
}
return bind(window, {
type: 'click',
listener: function listener(event) {
var target = event.target;
if (!(target instanceof Element)) {
return;
}
var trigger = triggerRef.current;
if (!trigger || !trigger.contains(target)) {
return;
}
if (isOpen) {
close();
return;
}
open();
},
options: {
capture: true
}
});
}, [isOpen, open, close]);
// 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.
var handleOnClose = useCallback(function (_args) {
if (isControlledAtMount) {
// For controlled mode, notify consumer but do not change internal state
onClose === null || onClose === void 0 || onClose();
onMenuClose === null || onMenuClose === void 0 || onMenuClose();
return;
}
close();
}, [close, isControlledAtMount, onClose, onMenuClose]);
/**
* **Ask first, close second**
*
* A `manual` popover, so the browser never closes it. An outside press or Escape asks to close
* (with a controlled `isOpen`, through `onClose`), and the popup hides only when `isOpen` becomes
* `false`. A press on the trigger does not ask: the trigger click toggles the popup, as on the
* legacy path. See `@atlaskit/top-layer` `notes/decisions/wrappers-ask-first-close.md`.
*/
var triggerRefs = useMemo(function () {
return [triggerRef];
}, []);
useManualLightDismiss({
isOpen: isOpen,
popoverRef: popoverRef,
additionalInsideElementRefs: triggerRefs,
onClose: handleOnClose
});
// Counts the picks that leave a controlled popup to the consumer. It changes in the same commit as
// the consumer's answer, so the effect below sees whether `onChange` closed the popup.
var _useState7 = useState(0),
_useState8 = _slicedToArray(_useState7, 2),
controlledPickCount = _useState8[0],
setControlledPickCount = _useState8[1];
var handleSelectChange = useCallback(function (value, actionMeta) {
if (closeMenuOnSelect && actionMeta.action !== 'clear') {
if (isControlledAtMount) {
setControlledPickCount(function (count) {
return count + 1;
});
} else {
var _triggerRef$current;
close();
// Return focus to trigger after selection
(_triggerRef$current = triggerRef.current) === null || _triggerRef$current === void 0 || _triggerRef$current.focus();
}
}
onChange === null || onChange === void 0 || onChange(value, actionMeta);
}, [closeMenuOnSelect, close, onChange, isControlledAtMount]);
// When `onChange` closes a controlled popup, focus goes to the trigger, as after an uncontrolled
// pick and on the legacy path. The `Popover` focus return is not enough: on a touch-capable device
// `react-select` blurs the input on a pick, so no focus is left in the popup. Only the commit of a
// pick acts, so a later close (for example an outside press) moves no focus.
var handledPickCountRef = useRef(0);
useEffect(function () {
if (controlledPickCount === handledPickCountRef.current) {
return;
}
handledPickCountRef.current = controlledPickCount;
if (!isOpen) {
var _triggerRef$current2;
(_triggerRef$current2 = triggerRef.current) === null || _triggerRef$current2 === void 0 || _triggerRef$current2.focus();
}
}, [controlledPickCount, isOpen]);
var handleKeyDown = useCallback(function (event) {
var tabEvent = event.key === 'Tab';
if (shouldCloseMenuOnTab && tabEvent && !isControlledAtMount) {
var _triggerRef$current3;
close();
(_triggerRef$current3 = triggerRef.current) === null || _triggerRef$current3 === void 0 || _triggerRef$current3.focus();
}
onKeyDown === null || onKeyDown === void 0 || onKeyDown(event);
}, [shouldCloseMenuOnTab, close, onKeyDown, isControlledAtMount]);
// Select components.
// Type assertion needed because defaultComponents uses concrete OptionType/boolean
// but Select expects the generic Option/IsMulti parameters. The components are
// structurally compatible regardless of the generic parameters.
var selectComponentsMerged = useMemo(function () {
return _objectSpread(_objectSpread({}, mergedComponents), {}, {
Control: showSearchControl ? mergedComponents.Control : DummyControl
});
}, [mergedComponents, showSearchControl]);
var getSelectRef = useCallback(function (ref) {
selectRef.current = ref;
}, []);
var triggerProps = {
ref: function ref(node) {
triggerRef.current = node;
},
// No `onClick` on `triggerProps`: the trigger click is observed via
// the capture-phase global `click` listener in the effect above,
// matching the legacy `PopupSelect` contract for consumers that do
// not spread `triggerProps` onto their target.
onKeyDown: handleTargetKeyDown,
// Maintain existing aria attribute format for backwards compatibility.
// Should technically be 'dialog' instead of 'true', but preserving
// legacy behavior. See go/DSP-22283
'aria-haspopup': 'true',
'aria-expanded': isOpen,
// The popover host is in the DOM only while open, so `aria-controls` is set only then.
// Matches `getAriaForTrigger` (see
// `top-layer/notes/decisions/aria-controls-trigger-contract.md`) and the legacy path.
'aria-controls': isOpen ? popoverId : undefined,
isOpen: isOpen
};
return /*#__PURE__*/React.createElement(Fragment, null, target === null || target === void 0 ? void 0 : target(triggerProps), /*#__PURE__*/React.createElement(Popover, {
ref: popoverRef,
id: popoverId,
role: "dialog",
label: (_getLabel = getLabel()) !== null && _getLabel !== void 0 ? _getLabel : 'Popup select',
isOpen: isOpen,
mode: "manual",
onClose: handleOnClose,
shouldAnimate: true,
placement: topLayerPlacement,
testId: testId && "".concat(testId, "--content")
}, /*#__PURE__*/React.createElement(PopoverSurface, null, /*#__PURE__*/React.createElement("div", {
ref: menuRef
// eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop
,
style: {
maxWidth: maxMenuWidth,
minWidth: minMenuWidth
},
"data-testid": testId && "".concat(testId, "--menu")
}, /*#__PURE__*/React.createElement(Select, _extends({
label: getLabel(),
backspaceRemovesValue: false,
controlShouldRenderValue: false,
isClearable: false,
tabSelectsValue: false,
placeholder: placeholder,
ref: getSelectRef
// eslint-disable-next-line @repo/internal/react/no-unsafe-spread-props -- preserving legacy PopupSelect API during migration
}, selectProps, {
menuRenderMode: "inline",
options: options,
isSearchable: showSearchControl,
styles: mergeStyles(defaultStyles, consumerStyles || {}),
maxMenuHeight: getMaxHeight(),
components: selectComponentsMerged,
onChange: handleSelectChange,
onKeyDown: handleKeyDown,
testId: testId
})), footer))));
}
export var PopupSelectTopLayer = /*#__PURE__*/forwardRef(PopupSelectTopLayerInner);