@carbon/react
Version:
React components for the Carbon Design System
464 lines (462 loc) • 18.3 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { usePrefix } from "../../internal/usePrefix.js";
import { ArrowDown, Delete, Enter, Escape, Space } from "../../internal/keyboard/keys.js";
import { match } from "../../internal/keyboard/match.js";
import useIsomorphicEffect from "../../internal/useIsomorphicEffect.js";
import { useId } from "../../internal/useId.js";
import { noopFn } from "../../internal/noopFn.js";
import { deprecate } from "../../prop-types/deprecate.js";
import { defaultItemToString } from "../../internal/defaultItemToString.js";
import { isComponentElement } from "../../internal/utils.js";
import { useFeatureFlag } from "../FeatureFlags/index.js";
import { useNormalizedInputProps } from "../../internal/useNormalizedInputProps.js";
import { AILabel } from "../AILabel/index.js";
import Checkbox_default from "../Checkbox/index.js";
import { ListBoxSizePropType, ListBoxTypePropType } from "../ListBox/ListBoxPropTypes.js";
import { FormContext } from "../FluidForm/FormContext.js";
import ListBox from "../ListBox/index.js";
import { mergeRefs } from "../../tools/mergeRefs.js";
import { sortingPropTypes } from "./MultiSelectPropTypes.js";
import { defaultCompareItems, defaultSortItems } from "./tools/sorting.js";
import { useSelection } from "../../internal/Selection.js";
import classNames from "classnames";
import React, { cloneElement, isValidElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import PropTypes from "prop-types";
import { jsx, jsxs } from "react/jsx-runtime";
import { WarningAltFilled, WarningFilled } from "@carbon/icons-react";
import { autoUpdate, flip, hide, size, useFloating } from "@floating-ui/react";
import { useSelect } from "downshift";
import isEqual from "react-fast-compare";
//#region src/components/MultiSelect/MultiSelect.tsx
/**
* Copyright IBM Corp. 2016, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const { ItemClick, ToggleButtonBlur, ToggleButtonKeyDownArrowDown, ToggleButtonKeyDownArrowUp, ToggleButtonKeyDownEnter, ToggleButtonKeyDownEscape, ToggleButtonKeyDownSpaceButton, ItemMouseMove, MenuMouseLeave, ToggleButtonClick, ToggleButtonKeyDownPageDown, ToggleButtonKeyDownPageUp, FunctionSetHighlightedIndex } = useSelect.stateChangeTypes;
const MultiSelect = React.forwardRef(({ autoAlign = false, className: containerClassName, decorator, id, items, itemToElement, itemToString = defaultItemToString, titleText = false, hideLabel, helperText, label, type = "default", size: size$1, disabled = false, initialSelectedItems = [], sortItems = defaultSortItems, compareItems = defaultCompareItems, clearSelectionText = "To clear selection, press Delete or Backspace", clearAnnouncement = "all items have been cleared", clearSelectionDescription = "Total items selected: ", light, invalid = false, invalidText, warn = false, warnText, useTitleInItem, translateWithId, downshiftProps, open = false, selectionFeedback = "top-after-reopen", onChange, onMenuChange, direction = "bottom", selectedItems: selected, readOnly, locale = "en", slug }, ref) => {
const filteredItems = useMemo(() => {
return items.filter((item) => {
if (typeof item === "object" && item !== null) {
for (const key in item) if (Object.hasOwn(item, key) && item[key] === void 0) return false;
}
return true;
});
}, [items]);
const selectAll = filteredItems.some((item) => item.isSelectAll);
const prefix = usePrefix();
const { isFluid } = useContext(FormContext);
const multiSelectInstanceId = useId();
const prevOpenPropRef = useRef(open);
const [inputFocused, setInputFocused] = useState(false);
const [isOpen, setIsOpen] = useState(open || false);
const [topItems, setTopItems] = useState([]);
const [itemsCleared, setItemsCleared] = useState(false);
const enableFloatingStyles = useFeatureFlag("enable-v12-dynamic-floating-styles") || autoAlign;
const { refs, floatingStyles, middlewareData } = useFloating(enableFloatingStyles ? {
placement: direction,
strategy: "fixed",
middleware: [
autoAlign && flip({ crossAxis: false }),
size({ apply({ rects, elements }) {
Object.assign(elements.floating.style, { width: `${rects.reference.width}px` });
} }),
autoAlign && hide()
],
whileElementsMounted: autoUpdate
} : {});
useIsomorphicEffect(() => {
if (enableFloatingStyles) {
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];
});
}
}, [
enableFloatingStyles,
floatingStyles,
refs.floating,
middlewareData,
open
]);
const { selectedItems: controlledSelectedItems, onItemChange, clearSelection } = useSelection({
disabled,
initialSelectedItems,
onChange,
selectedItems: selected,
selectAll,
filteredItems
});
const sortOptions = {
selectedItems: controlledSelectedItems,
itemToString,
compareItems,
locale
};
const { getToggleButtonProps, getLabelProps, getMenuProps, getItemProps, selectedItem, highlightedIndex, setHighlightedIndex } = useSelect({
stateReducer,
isOpen,
itemToString: (filteredItems) => {
return Array.isArray(filteredItems) && filteredItems.map((item) => {
return itemToString(item);
}).join(", ") || "";
},
selectedItem: controlledSelectedItems,
items: filteredItems,
isItemDisabled(item) {
return item?.disabled;
},
...downshiftProps
});
const toggleButtonProps = getToggleButtonProps({
onFocus: () => {
setInputFocused(true);
},
onBlur: () => {
setInputFocused(false);
},
onKeyDown: (e) => {
if (!disabled) {
if ((match(e, Delete) || match(e, Escape)) && !isOpen) {
clearSelection();
e.stopPropagation();
}
if (!isOpen && match(e, Delete) && selectedItems.length > 0) setItemsCleared(true);
if ((match(e, Space) || match(e, ArrowDown) || match(e, Enter)) && !isOpen) {
setHighlightedIndex(0);
setItemsCleared(false);
setIsOpenWrapper(true);
}
if (match(e, ArrowDown) && selectedItems.length === 0) setInputFocused(false);
if (match(e, Escape) && isOpen) setInputFocused(true);
if (match(e, Enter) && isOpen) setInputFocused(true);
}
}
});
const toggleButtonRef = useRef(null);
const mergedRef = mergeRefs(toggleButtonProps.ref, ref, toggleButtonRef);
const selectedItems = selectedItem;
/**
* wrapper function to forward changes to consumer
*/
const setIsOpenWrapper = (open) => {
setIsOpen(open);
if (onMenuChange) onMenuChange(open);
};
useEffect(() => {
if (prevOpenPropRef.current !== open) {
setIsOpen(open);
onMenuChange?.(open);
prevOpenPropRef.current = open;
}
}, [open, onMenuChange]);
const normalizedProps = useNormalizedInputProps({
id,
disabled,
readOnly,
invalid,
warn
});
const inline = type === "inline";
const showWarning = normalizedProps.warn;
const showHelperText = !normalizedProps.warn && !normalizedProps.invalid && helperText;
const wrapperClasses = classNames(`${prefix}--multi-select__wrapper`, `${prefix}--list-box__wrapper`, containerClassName, {
[`${prefix}--multi-select__wrapper--inline`]: inline,
[`${prefix}--list-box__wrapper--inline`]: inline,
[`${prefix}--multi-select__wrapper--inline--invalid`]: inline && normalizedProps.invalid,
[`${prefix}--list-box__wrapper--inline--invalid`]: inline && normalizedProps.invalid,
[`${prefix}--list-box__wrapper--fluid--invalid`]: isFluid && normalizedProps.invalid,
[`${prefix}--list-box__wrapper--slug`]: slug,
[`${prefix}--list-box__wrapper--decorator`]: decorator
});
const titleClasses = classNames(`${prefix}--label`, {
[`${prefix}--label--disabled`]: disabled,
[`${prefix}--visually-hidden`]: hideLabel
});
const helperId = !helperText ? void 0 : `multiselect-helper-text-${multiSelectInstanceId}`;
const fieldLabelId = `multiselect-field-label-${multiSelectInstanceId}`;
const helperClasses = classNames(`${prefix}--form__helper-text`, { [`${prefix}--form__helper-text--disabled`]: disabled });
const className = classNames(`${prefix}--multi-select`, {
[`${prefix}--multi-select--invalid`]: normalizedProps.invalid,
[`${prefix}--multi-select--invalid--focused`]: inputFocused && normalizedProps.invalid,
[`${prefix}--multi-select--warning`]: showWarning,
[`${prefix}--multi-select--inline`]: inline,
[`${prefix}--multi-select--selected`]: selectedItems && selectedItems.length > 0,
[`${prefix}--list-box--up`]: direction === "top",
[`${prefix}--multi-select--readonly`]: readOnly,
[`${prefix}--autoalign`]: enableFloatingStyles,
[`${prefix}--multi-select--selectall`]: selectAll
});
if (selectionFeedback === "fixed") sortOptions.selectedItems = [];
else if (selectionFeedback === "top-after-reopen") sortOptions.selectedItems = topItems;
function stateReducer(state, actionAndChanges) {
const { changes, props, type } = actionAndChanges;
const { highlightedIndex } = changes;
if (changes.isOpen && !isOpen) setTopItems(controlledSelectedItems);
switch (type) {
case ToggleButtonKeyDownSpaceButton:
case ToggleButtonKeyDownEnter:
if (changes.selectedItem === void 0) break;
if (Array.isArray(changes.selectedItem)) break;
onItemChange(changes.selectedItem);
return {
...changes,
highlightedIndex: state.highlightedIndex
};
case ToggleButtonBlur:
case ToggleButtonKeyDownEscape:
setIsOpenWrapper(false);
break;
case ToggleButtonClick:
setIsOpenWrapper(changes.isOpen || false);
return {
...changes,
highlightedIndex: controlledSelectedItems.length > 0 ? 0 : void 0
};
case ItemClick:
setHighlightedIndex(changes.selectedItem);
onItemChange(changes.selectedItem);
return {
...changes,
highlightedIndex: state.highlightedIndex
};
case MenuMouseLeave: return {
...changes,
highlightedIndex: state.highlightedIndex
};
case FunctionSetHighlightedIndex: if (!isOpen) return {
...changes,
highlightedIndex: 0
};
else return {
...changes,
highlightedIndex: filteredItems.indexOf(highlightedIndex)
};
case ToggleButtonKeyDownArrowDown:
case ToggleButtonKeyDownArrowUp:
case ToggleButtonKeyDownPageDown:
case ToggleButtonKeyDownPageUp:
if (highlightedIndex > -1) {
const itemArray = document.querySelectorAll(`li.${prefix}--list-box__menu-item[role="option"]`);
props.scrollIntoView(itemArray[highlightedIndex]);
}
if (highlightedIndex === -1) return {
...changes,
highlightedIndex: 0
};
return changes;
case ItemMouseMove: return {
...changes,
highlightedIndex: state.highlightedIndex
};
}
return changes;
}
const multiSelectFieldWrapperClasses = classNames(`${prefix}--list-box__field--wrapper`, { [`${prefix}--list-box__field--wrapper--input-focused`]: inputFocused });
const readOnlyEventHandlers = readOnly ? {
onClick: (evt) => {
evt.preventDefault();
if (toggleButtonRef.current) toggleButtonRef.current.focus();
},
onKeyDown: (evt) => {
if ([
"ArrowDown",
"ArrowUp",
" ",
"Enter"
].includes(evt.key)) evt.preventDefault();
}
} : {};
const candidate = slug ?? decorator;
const normalizedDecorator = isComponentElement(candidate, AILabel) ? cloneElement(candidate, { size: "mini" }) : candidate;
const itemsSelectedText = selectedItems.length > 0 && selectedItems.map((item) => item?.text);
const selectedItemsLength = selectAll ? selectedItems.filter((item) => !item.isSelectAll).length : selectedItems.length;
const menuProps = useMemo(() => getMenuProps({
ref: enableFloatingStyles ? refs.setFloating : null,
hidden: !isOpen
}), [
enableFloatingStyles,
getMenuProps,
isOpen,
refs.setFloating
]);
const allLabelProps = getLabelProps();
const labelProps = isValidElement(titleText) ? { id: allLabelProps.id } : allLabelProps;
const getSelectionStats = useCallback((selectedItems, filteredItems) => {
return {
hasIndividualSelections: selectedItems.some((selected) => !selected.isSelectAll),
nonSelectAllSelectedCount: selectedItems.filter((selected) => !selected.isSelectAll).length,
totalSelectableCount: filteredItems.filter((item) => !item.isSelectAll && !item.disabled).length
};
}, [selectedItems, filteredItems]);
return /* @__PURE__ */ jsxs("div", {
className: wrapperClasses,
children: [
/* @__PURE__ */ jsxs("label", {
className: titleClasses,
...labelProps,
children: [titleText && titleText, selectedItems.length > 0 && /* @__PURE__ */ jsxs("span", {
className: `${prefix}--visually-hidden`,
children: [
clearSelectionDescription,
" ",
selectedItems.length,
" ",
itemsSelectedText,
",",
clearSelectionText
]
})]
}),
/* @__PURE__ */ jsxs(ListBox, {
type,
size: size$1,
className,
disabled,
light,
invalid: normalizedProps.invalid,
invalidText,
warn: normalizedProps.warn,
warnText,
isOpen,
id,
children: [
normalizedProps.invalid && /* @__PURE__ */ jsx(WarningFilled, { className: `${prefix}--list-box__invalid-icon` }),
showWarning && /* @__PURE__ */ jsx(WarningAltFilled, { className: `${prefix}--list-box__invalid-icon ${prefix}--list-box__invalid-icon--warning` }),
/* @__PURE__ */ jsxs("div", {
className: multiSelectFieldWrapperClasses,
ref: enableFloatingStyles ? refs.setReference : null,
children: [
selectedItems.length > 0 && /* @__PURE__ */ jsx(ListBox.Selection, {
readOnly,
clearSelection: !disabled && !readOnly ? clearSelection : noopFn,
selectionCount: selectedItemsLength,
translateWithId,
disabled
}),
/* @__PURE__ */ jsxs("button", {
type: "button",
className: `${prefix}--list-box__field`,
disabled,
"aria-disabled": disabled || readOnly,
"aria-describedby": !inline && showHelperText ? helperId : void 0,
...toggleButtonProps,
ref: mergedRef,
...readOnlyEventHandlers,
children: [/* @__PURE__ */ jsx("span", {
id: fieldLabelId,
className: `${prefix}--list-box__label`,
children: label
}), /* @__PURE__ */ jsx(ListBox.MenuIcon, {
isOpen,
translateWithId
})]
}),
slug ? normalizedDecorator : decorator ? /* @__PURE__ */ jsx("div", {
className: `${prefix}--list-box__inner-wrapper--decorator`,
children: normalizedDecorator
}) : ""
]
}),
/* @__PURE__ */ jsx(ListBox.Menu, {
...menuProps,
children: isOpen && sortItems(filteredItems, sortOptions).map((item, index) => {
const { hasIndividualSelections, nonSelectAllSelectedCount, totalSelectableCount } = getSelectionStats(selectedItems, filteredItems);
const isChecked = item.isSelectAll ? nonSelectAllSelectedCount === totalSelectableCount && totalSelectableCount > 0 : selectedItems.some((selected) => isEqual(selected, item));
const isIndeterminate = item.isSelectAll && hasIndividualSelections && nonSelectAllSelectedCount < totalSelectableCount;
const itemProps = getItemProps({
item,
["aria-selected"]: isChecked
});
const itemText = itemToString(item);
return /* @__PURE__ */ jsx(ListBox.MenuItem, {
isActive: isChecked && !item["isSelectAll"],
"aria-label": itemText,
"aria-checked": isIndeterminate ? "mixed" : isChecked,
isHighlighted: highlightedIndex === index,
title: itemText,
disabled: itemProps["aria-disabled"],
...itemProps,
children: /* @__PURE__ */ jsx("div", {
className: `${prefix}--checkbox-wrapper`,
children: /* @__PURE__ */ jsx(Checkbox_default, {
id: `${itemProps.id}__checkbox`,
labelText: itemToElement ? itemToElement(item) : itemText,
checked: isChecked,
title: useTitleInItem ? itemText : void 0,
indeterminate: isIndeterminate,
disabled
})
})
}, itemProps.id);
})
}),
itemsCleared && /* @__PURE__ */ jsx("span", {
"aria-live": "assertive",
"aria-label": clearAnnouncement
})
]
}),
!inline && showHelperText && /* @__PURE__ */ jsx("div", {
id: helperId,
className: helperClasses,
children: helperText
})
]
});
});
MultiSelect.displayName = "MultiSelect";
MultiSelect.propTypes = {
...sortingPropTypes,
autoAlign: PropTypes.bool,
className: PropTypes.string,
clearSelectionDescription: PropTypes.string,
clearSelectionText: PropTypes.string,
compareItems: PropTypes.func,
decorator: PropTypes.node,
direction: PropTypes.oneOf(["top", "bottom"]),
disabled: PropTypes.bool,
downshiftProps: PropTypes.object,
helperText: PropTypes.node,
hideLabel: PropTypes.bool,
id: PropTypes.string.isRequired,
initialSelectedItems: PropTypes.array,
invalid: PropTypes.bool,
invalidText: PropTypes.node,
itemToElement: PropTypes.func,
itemToString: PropTypes.func,
items: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
light: deprecate(PropTypes.bool, "The `light` prop for `MultiSelect` has been deprecated in favor of the new `Layer` component. It will be removed in the next major release."),
locale: PropTypes.string,
onChange: PropTypes.func,
onMenuChange: PropTypes.func,
open: PropTypes.bool,
readOnly: PropTypes.bool,
selectedItems: PropTypes.array,
selectionFeedback: PropTypes.oneOf([
"top",
"fixed",
"top-after-reopen"
]),
size: ListBoxSizePropType,
slug: deprecate(PropTypes.node, "The `slug` prop has been deprecated and will be removed in the next major version. Use the decorator prop instead."),
sortItems: PropTypes.func,
titleText: PropTypes.node,
translateWithId: PropTypes.func,
type: ListBoxTypePropType,
useTitleInItem: PropTypes.bool,
warn: PropTypes.bool,
warnText: PropTypes.node
};
//#endregion
export { MultiSelect };