@carbon/react
Version:
React components for the Carbon Design System
538 lines (524 loc) • 21.2 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
;
Object.defineProperty(exports, '__esModule', { value: true });
var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var Downshift = require('downshift');
var cx = require('classnames');
var PropTypes = require('prop-types');
var iconsReact = require('@carbon/icons-react');
var index$2 = require('../ListBox/index.js');
var mergeRefs = require('../../tools/mergeRefs.js');
var deprecate = require('../../prop-types/deprecate.js');
var usePrefix = require('../../internal/usePrefix.js');
require('../FluidForm/FluidForm.js');
var FormContext = require('../FluidForm/FormContext.js');
var useId = require('../../internal/useId.js');
var react = require('@floating-ui/react');
var index = require('../FeatureFlags/index.js');
var index$1 = require('../AILabel/index.js');
var utils = require('../../internal/utils.js');
var ListBoxPropTypes = require('../ListBox/ListBoxPropTypes.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var cx__default = /*#__PURE__*/_interopDefaultLegacy(cx);
var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes);
const {
ItemMouseMove,
MenuMouseLeave
} = Downshift.useSelect.stateChangeTypes;
const defaultItemToString = item => {
if (typeof item === 'string') {
return item;
}
if (typeof item === 'number') {
return `${item}`;
}
if (item !== null && typeof item === 'object' && 'label' in item && typeof item['label'] === 'string') {
return item['label'];
}
return '';
};
/**
* Custom state reducer for `useSelect` in Downshift, providing control over
* state changes.
*
* This function is called each time `useSelect` updates its internal state or
* triggers `onStateChange`. It allows for fine-grained control of state
* updates by modifying or overriding the default changes from Downshift's
* reducer.
* https://github.com/downshift-js/downshift/tree/master/src/hooks/useSelect#statereducer
*
* @param {Object} state - The current full state of the Downshift component.
* @param {Object} actionAndChanges - Contains the action type and proposed
* changes from the default Downshift reducer.
* @param {Object} actionAndChanges.changes - Suggested state changes.
* @param {string} actionAndChanges.type - The action type for the state
* change (e.g., item selection).
* @returns {Object} - The modified state based on custom logic or default
* changes if no custom logic applies.
*/
function stateReducer(state, actionAndChanges) {
const {
changes,
type
} = actionAndChanges;
switch (type) {
case ItemMouseMove:
case MenuMouseLeave:
if (changes.highlightedIndex === state.highlightedIndex) {
// Prevent state update if highlightedIndex hasn't changed
return state;
}
return changes;
default:
return changes;
}
}
const Dropdown = /*#__PURE__*/React__default["default"].forwardRef(({
autoAlign = false,
className: containerClassName,
decorator,
disabled = false,
direction = 'bottom',
items: itemsProp,
label,
['aria-label']: ariaLabel,
ariaLabel: deprecatedAriaLabel,
itemToString = defaultItemToString,
itemToElement = null,
renderSelectedItem,
type = 'default',
size,
onChange,
id,
titleText = '',
hideLabel,
helperText = '',
translateWithId,
light,
invalid,
invalidText,
warn,
warnText,
initialSelectedItem,
selectedItem: controlledSelectedItem,
downshiftProps,
readOnly,
slug,
...other
}, ref) => {
const enableFloatingStyles = index.useFeatureFlag('enable-v12-dynamic-floating-styles');
const {
refs,
floatingStyles,
middlewareData
} = react.useFloating(enableFloatingStyles || autoAlign ? {
placement: direction,
// The floating element is positioned relative to its nearest
// containing block (usually the viewport). It will in many cases also
// “break” the floating element out of a clipping ancestor.
// https://floating-ui.com/docs/misc#clipping
strategy: 'fixed',
// Middleware order matters, arrow should be last
middleware: [react.size({
apply({
rects,
elements
}) {
Object.assign(elements.floating.style, {
width: `${rects.reference.width}px`
});
}
}), autoAlign && react.flip(), autoAlign && react.hide()],
whileElementsMounted: react.autoUpdate
} : {}
// When autoAlign is turned off & the `enable-v12-dynamic-floating-styles` feature flag is not
// enabled, floating-ui will not be used
);
React.useEffect(() => {
if (enableFloatingStyles || autoAlign) {
const updatedFloatingStyles = {
...floatingStyles,
visibility: middlewareData.hide?.referenceHidden ? 'hidden' : 'visible'
};
Object.keys(updatedFloatingStyles).forEach(style => {
if (refs.floating.current) {
refs.floating.current.style[style] = updatedFloatingStyles[style];
}
});
}
}, [floatingStyles, autoAlign, refs.floating]);
const prefix = usePrefix.usePrefix();
const {
isFluid
} = React.useContext(FormContext.FormContext);
const onSelectedItemChange = React.useCallback(({
selectedItem
}) => {
if (onChange) {
onChange({
selectedItem: selectedItem ?? null
});
}
}, [onChange]);
const isItemDisabled = React.useCallback((item, _index) => {
const isObject = item !== null && typeof item === 'object';
return isObject && 'disabled' in item && item.disabled === true;
}, []);
const onHighlightedIndexChange = React.useCallback(changes => {
const {
highlightedIndex
} = changes;
if (highlightedIndex !== undefined && highlightedIndex > -1 && typeof window !== undefined) {
const itemArray = document.querySelectorAll(`li.${prefix}--list-box__menu-item[role="option"]`);
const highlightedItem = itemArray[highlightedIndex];
if (highlightedItem) {
highlightedItem.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
});
}
}
}, [prefix]);
const items = React.useMemo(() => itemsProp, [itemsProp]);
const selectProps = React.useMemo(() => ({
items,
itemToString,
initialSelectedItem,
onSelectedItemChange,
stateReducer,
isItemDisabled,
onHighlightedIndexChange,
...downshiftProps
}), [items, itemToString, initialSelectedItem, onSelectedItemChange, stateReducer, isItemDisabled, onHighlightedIndexChange, downshiftProps]);
const dropdownInstanceId = useId.useId();
// only set selectedItem if the prop is defined. Setting if it is undefined
// will overwrite default selected items from useSelect
if (controlledSelectedItem !== undefined) {
selectProps.selectedItem = controlledSelectedItem;
}
const {
isOpen,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getItemProps,
selectedItem,
highlightedIndex
} = Downshift.useSelect(selectProps);
const inline = type === 'inline';
const showWarning = !invalid && warn;
const [isFocused, setIsFocused] = React.useState(false);
const className = cx__default["default"](`${prefix}--dropdown`, {
[`${prefix}--dropdown--invalid`]: invalid,
[`${prefix}--dropdown--warning`]: showWarning,
[`${prefix}--dropdown--open`]: isOpen,
[`${prefix}--dropdown--focus`]: isFocused,
[`${prefix}--dropdown--inline`]: inline,
[`${prefix}--dropdown--disabled`]: disabled,
[`${prefix}--dropdown--light`]: light,
[`${prefix}--dropdown--readonly`]: readOnly,
[`${prefix}--dropdown--${size}`]: size,
[`${prefix}--list-box--up`]: direction === 'top',
[`${prefix}--autoalign`]: autoAlign
});
const titleClasses = cx__default["default"](`${prefix}--label`, {
[`${prefix}--label--disabled`]: disabled,
[`${prefix}--visually-hidden`]: hideLabel
});
const helperClasses = cx__default["default"](`${prefix}--form__helper-text`, {
[`${prefix}--form__helper-text--disabled`]: disabled
});
const wrapperClasses = cx__default["default"](`${prefix}--dropdown__wrapper`, `${prefix}--list-box__wrapper`, containerClassName, {
[`${prefix}--dropdown__wrapper--inline`]: inline,
[`${prefix}--list-box__wrapper--inline`]: inline,
[`${prefix}--dropdown__wrapper--inline--invalid`]: inline && invalid,
[`${prefix}--list-box__wrapper--inline--invalid`]: inline && invalid,
[`${prefix}--list-box__wrapper--fluid--invalid`]: isFluid && invalid,
[`${prefix}--list-box__wrapper--slug`]: slug,
[`${prefix}--list-box__wrapper--decorator`]: decorator
});
const helperId = !helperText ? undefined : `dropdown-helper-text-${dropdownInstanceId}`;
// needs to be Capitalized for react to render it correctly
const ItemToElement = itemToElement;
const toggleButtonProps = getToggleButtonProps({
'aria-label': ariaLabel || deprecatedAriaLabel
});
const helper = helperText && !isFluid ? /*#__PURE__*/React__default["default"].createElement("div", {
id: helperId,
className: helperClasses
}, helperText) : null;
const handleFocus = evt => {
setIsFocused(evt.type === 'focus' && !selectedItem ? true : false);
};
const mergedRef = mergeRefs["default"](toggleButtonProps.ref, ref);
const [currTimer, setCurrTimer] = React.useState();
const [isTyping, setIsTyping] = React.useState(false);
const onKeyDownHandler = React.useCallback(evt => {
if (evt.code !== 'Space' || !['ArrowDown', 'ArrowUp', ' ', 'Enter'].includes(evt.key)) {
setIsTyping(true);
}
if (isTyping && evt.code === 'Space' || !['ArrowDown', 'ArrowUp', ' ', 'Enter'].includes(evt.key)) {
if (currTimer) {
clearTimeout(currTimer);
}
setCurrTimer(setTimeout(() => {
setIsTyping(false);
}, 3000));
}
if (['ArrowDown'].includes(evt.key)) {
setIsFocused(false);
}
if (['Enter'].includes(evt.key) && !selectedItem && !isOpen) {
setIsFocused(true);
}
// For Dropdowns the arrow up key is only allowed if the Dropdown is open
if (toggleButtonProps.onKeyDown && (evt.key !== 'ArrowUp' || isOpen && evt.key === 'ArrowUp')) {
toggleButtonProps.onKeyDown(evt);
}
}, [isTyping, currTimer, toggleButtonProps]);
const readOnlyEventHandlers = React.useMemo(() => {
if (readOnly) {
return {
onClick: evt => {
// NOTE: does not prevent click
evt.preventDefault();
// focus on the element as per readonly input behavior
mergedRef?.current?.focus();
},
onKeyDown: evt => {
const selectAccessKeys = ['ArrowDown', 'ArrowUp', ' ', 'Enter'];
// This prevents the select from opening for the above keys
if (selectAccessKeys.includes(evt.key)) {
evt.preventDefault();
}
}
};
} else {
return {
onKeyDown: onKeyDownHandler
};
}
}, [readOnly, onKeyDownHandler]);
const menuProps = React.useMemo(() => getMenuProps({
ref: enableFloatingStyles || autoAlign ? refs.setFloating : null
}), [autoAlign, getMenuProps, refs.setFloating, enableFloatingStyles]);
// AILabel is always size `mini`
const candidate = slug ?? decorator;
const candidateIsAILabel = utils.isComponentElement(candidate, index$1.AILabel);
const normalizedDecorator = candidateIsAILabel ? /*#__PURE__*/React.cloneElement(candidate, {
size: 'mini'
}) : null;
const allLabelProps = getLabelProps();
const labelProps = /*#__PURE__*/React.isValidElement(titleText) ? {
id: allLabelProps.id
} : allLabelProps;
return /*#__PURE__*/React__default["default"].createElement("div", _rollupPluginBabelHelpers["extends"]({
className: wrapperClasses
}, other), titleText && /*#__PURE__*/React__default["default"].createElement("label", _rollupPluginBabelHelpers["extends"]({
className: titleClasses
}, labelProps), titleText), /*#__PURE__*/React__default["default"].createElement(index$2["default"], {
onFocus: handleFocus,
onBlur: handleFocus,
size: size,
className: className,
invalid: invalid,
invalidText: invalidText,
warn: warn,
warnText: warnText,
light: light,
isOpen: isOpen,
ref: enableFloatingStyles || autoAlign ? refs.setReference : null,
id: id
}, invalid && /*#__PURE__*/React__default["default"].createElement(iconsReact.WarningFilled, {
className: `${prefix}--list-box__invalid-icon`
}), showWarning && /*#__PURE__*/React__default["default"].createElement(iconsReact.WarningAltFilled, {
className: `${prefix}--list-box__invalid-icon ${prefix}--list-box__invalid-icon--warning`
}), /*#__PURE__*/React__default["default"].createElement("button", _rollupPluginBabelHelpers["extends"]({
type: "button"
// aria-expanded is already being passed through {...toggleButtonProps}
,
className: `${prefix}--list-box__field`,
disabled: disabled,
"aria-disabled": readOnly ? true : undefined // aria-disabled to remain focusable
,
"aria-describedby": !inline && !invalid && !warn && helper ? helperId : undefined,
title: selectedItem && itemToString !== undefined ? itemToString(selectedItem) : defaultItemToString(label)
}, toggleButtonProps, readOnlyEventHandlers, {
ref: mergedRef
}), /*#__PURE__*/React__default["default"].createElement("span", {
className: `${prefix}--list-box__label`
}, selectedItem ? renderSelectedItem ? renderSelectedItem(selectedItem) : itemToString(selectedItem) : label), /*#__PURE__*/React__default["default"].createElement(index$2["default"].MenuIcon, {
isOpen: isOpen,
translateWithId: translateWithId
})), slug ? normalizedDecorator : decorator ? /*#__PURE__*/React__default["default"].createElement("div", {
className: `${prefix}--list-box__inner-wrapper--decorator`
}, normalizedDecorator) : '', /*#__PURE__*/React__default["default"].createElement(index$2["default"].Menu, menuProps, isOpen && items.map((item, index) => {
const isObject = item !== null && typeof item === 'object';
const itemProps = getItemProps({
item,
index
});
const title = isObject && 'text' in item && itemToElement ? item.text : itemToString(item);
return /*#__PURE__*/React__default["default"].createElement(index$2["default"].MenuItem, _rollupPluginBabelHelpers["extends"]({
key: itemProps.id,
isActive: selectedItem === item,
isHighlighted: highlightedIndex === index,
title: title,
disabled: itemProps['aria-disabled']
}, itemProps), typeof item === 'object' && ItemToElement !== undefined && ItemToElement !== null ? /*#__PURE__*/React__default["default"].createElement(ItemToElement, _rollupPluginBabelHelpers["extends"]({
key: itemProps.id
}, item)) : itemToString(item), selectedItem === item && /*#__PURE__*/React__default["default"].createElement(iconsReact.Checkmark, {
className: `${prefix}--list-box__menu-item__selected-icon`
}));
}))), !inline && !invalid && !warn && helper);
});
// Workaround problems with forwardRef() and generics. In the long term, should stop using forwardRef().
// See https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref.
Dropdown.displayName = 'Dropdown';
Dropdown.propTypes = {
/**
* 'aria-label' of the ListBox component.
* Specify a label to be read by screen readers on the container node
*/
['aria-label']: PropTypes__default["default"].string,
/**
* Deprecated, please use `aria-label` instead.
* Specify a label to be read by screen readers on the container note.
*/
ariaLabel: deprecate["default"](PropTypes__default["default"].string, 'This prop syntax has been deprecated. Please use the new `aria-label`.'),
/**
* **Experimental**: Will attempt to automatically align the floating element to avoid collisions with the viewport and being clipped by ancestor elements.
*/
autoAlign: PropTypes__default["default"].bool,
/**
* Provide a custom className to be applied on the cds--dropdown node
*/
className: PropTypes__default["default"].string,
/**
* **Experimental**: Provide a `decorator` component to be rendered inside the `Dropdown` component
*/
decorator: PropTypes__default["default"].node,
/**
* Specify the direction of the dropdown. Can be either top or bottom.
*/
direction: PropTypes__default["default"].oneOf(['top', 'bottom']),
/**
* Disable the control
*/
disabled: PropTypes__default["default"].bool,
/**
* Additional props passed to Downshift.
*
* **Use with caution:** anything you define here overrides the components'
* internal handling of that prop. Downshift APIs and internals are subject to
* change, and in some cases they can not be shimmed by Carbon to shield you
* from potentially breaking changes.
*/
downshiftProps: PropTypes__default["default"].object,
/**
* Provide helper text that is used alongside the control label for
* additional help
*/
helperText: PropTypes__default["default"].node,
/**
* Specify whether the title text should be hidden or not
*/
hideLabel: PropTypes__default["default"].bool,
/**
* Specify a custom `id`
*/
id: PropTypes__default["default"].string.isRequired,
/**
* Allow users to pass in an arbitrary item or a string (in case their items are an array of strings)
* from their collection that are pre-selected
*/
initialSelectedItem: PropTypes__default["default"].oneOfType([PropTypes__default["default"].object, PropTypes__default["default"].string, PropTypes__default["default"].number]),
/**
* Specify if the currently selected value is invalid.
*/
invalid: PropTypes__default["default"].bool,
/**
* Message which is displayed if the value is invalid.
*/
invalidText: PropTypes__default["default"].node,
/**
* Function to render items as custom components instead of strings.
* Defaults to null and is overridden by a getter
*/
itemToElement: PropTypes__default["default"].func,
/**
* Helper function passed to downshift that allows the library to render a
* given item to a string label. By default, it extracts the `label` field
* from a given item to serve as the item label in the list.
*/
itemToString: PropTypes__default["default"].func,
/**
* We try to stay as generic as possible here to allow individuals to pass
* in a collection of whatever kind of data structure they prefer
*/
items: PropTypes__default["default"].array.isRequired,
/**
* Generic `label` that will be used as the textual representation of what
* this field is for
*/
label: PropTypes__default["default"].node.isRequired,
/**
* `true` to use the light version.
*/
light: deprecate["default"](PropTypes__default["default"].bool, 'The `light` prop for `Dropdown` has ' + 'been deprecated in favor of the new `Layer` component. It will be removed in the next major release.'),
/**
* `onChange` is a utility for this controlled component to communicate to a
* consuming component what kind of internal state changes are occurring.
*/
onChange: PropTypes__default["default"].func,
/**
* Whether or not the Dropdown is readonly
*/
readOnly: PropTypes__default["default"].bool,
/**
* An optional callback to render the currently selected item as a react element instead of only
* as a string.
*/
renderSelectedItem: PropTypes__default["default"].func,
/**
* In the case you want to control the dropdown selection entirely.
*/
selectedItem: PropTypes__default["default"].oneOfType([PropTypes__default["default"].object, PropTypes__default["default"].string, PropTypes__default["default"].number]),
/**
* Specify the size of the ListBox. Currently supports either `sm`, `md` or `lg` as an option.
*/
size: ListBoxPropTypes.ListBoxSizePropType,
/**
* **Experimental**: Provide a `Slug` component to be rendered inside the `Dropdown` component
*/
slug: deprecate["default"](PropTypes__default["default"].node, 'The `slug` prop for `Dropdown` has ' + 'been deprecated in favor of the new `decorator` prop. It will be removed in the next major release.'),
/**
* Provide the title text that will be read by a screen reader when
* visiting this control
*/
titleText: PropTypes__default["default"].node.isRequired,
/**
* Callback function for translating ListBoxMenuIcon SVG title
*/
translateWithId: PropTypes__default["default"].func,
/**
* The dropdown type, `default` or `inline`
*/
type: ListBoxPropTypes.ListBoxTypePropType,
/**
* Specify whether the control is currently in warning state
*/
warn: PropTypes__default["default"].bool,
/**
* Provide the text that is displayed when the control is in warning state
*/
warnText: PropTypes__default["default"].node
};
exports["default"] = Dropdown;