import { Fragment, useEffect, useRef } from 'react'; import { useId, useUncontrolled } from '@mantine/hooks'; import { BoxProps, ElementProps, extractStyleProps, Factory, genericFactory, MantineColor, Primitive, StylesApiProps, useProps, useResolvedStylesApi, useStyles, } from '../../core'; import { Combobox, ComboboxItem, ComboboxLikeProps, ComboboxLikeRenderOptionInput, ComboboxLikeStylesNames, ComboboxRenderPillInput, getOptionsLockup, getParsedComboboxData, OptionsDropdown, OptionsFilter, useCombobox, usePillsReorder, } from '../Combobox'; import { getComboboxLabelId } from '../Combobox/get-combobox-label-id/get-combobox-label-id'; import { getOptionByLabel } from '../Combobox/get-options-lockup/get-option-by-label'; import { isExternalInputChange } from '../Combobox/is-external-input-change/is-external-input-change'; import { __BaseInputProps, __InputStylesNames, ClearSectionMode, InputClearButtonProps, } from '../Input'; import { InputBase } from '../InputBase'; import { Pill } from '../Pill'; import { PillsInput } from '../PillsInput'; import { ScrollAreaProps } from '../ScrollArea'; import { filterPickedValues } from './filter-picked-values'; const clearSectionOffset: Record = { xs: 41, sm: 50, md: 60, lg: 72, xl: 89, }; export type MultiSelectStylesNames = | __InputStylesNames | ComboboxLikeStylesNames | 'pill' | 'pillsList' | 'inputField'; export interface MultiSelectProps extends BoxProps, __BaseInputProps, ComboboxLikeProps, StylesApiProps, ElementProps<'input', 'size' | 'value' | 'defaultValue' | 'onChange'> { /** Controlled component value */ value?: Value[]; /** Uncontrolled component default value */ defaultValue?: Value[]; /** Called when value changes */ onChange?: (value: Value[]) => void; /** Called with `value` of the removed item */ onRemove?: (value: Value) => void; /** Called when the clear button is clicked */ onClear?: () => void; /** Called when user attempts to select more values than allowed */ onMaxValues?: () => void; /** Controlled search value */ searchValue?: string; /** Default search value */ defaultSearchValue?: string; /** Called when search changes */ onSearchChange?: (value: string) => void; /** Maximum number of values, no limit if not set */ maxValues?: number; /** Allows searching through options by user input @default false */ searchable?: boolean; /** Message displayed when no options match the search query (when searchable is enabled) or when the data array is empty. If not set, the dropdown will be hidden instead. */ nothingFoundMessage?: React.ReactNode; /** If set, the check icon is displayed near the selected option label @default true */ withCheckIcon?: boolean; /** If set, unchecked labels are aligned with checked ones @default false */ withAlignedLabels?: boolean; /** Position of the checkmark icon shown next to selected options in the dropdown @default 'left' */ checkIconPosition?: 'left' | 'right'; /** When enabled, selected options are hidden from the dropdown list @default false */ hidePickedOptions?: boolean; /** When enabled, displays a clear button to remove all selected values (hidden when component is empty, disabled, or read-only) @default false */ clearable?: boolean; /** Determines how the clear button and rightSection are rendered @default 'both' */ clearSectionMode?: ClearSectionMode; /** Props passed down to the clear button */ clearButtonProps?: InputClearButtonProps; /** Props passed down to the hidden input */ hiddenInputProps?: Omit, 'value'>; /** Divider used to separate values in the hidden input `value` attribute @default ',' */ hiddenInputValuesDivider?: string; /** A function to render content of the option, replaces the default content of the option */ renderOption?: (item: ComboboxLikeRenderOptionInput>) => React.ReactNode; /** A function to render content of the pill */ renderPill?: (props: ComboboxRenderPillInput) => React.ReactNode; /** Props passed down to the underlying `ScrollArea` component in the dropdown */ scrollAreaProps?: ScrollAreaProps; /** Controls color of the default chevron */ chevronColor?: MantineColor; /** Clear search value when item is selected @default true */ clearSearchOnChange?: boolean; /** Controls whether dropdown opens when the input receives focus @default true */ openOnFocus?: boolean; /** If set, selected values can be reordered by dragging pills. Disabled when `disabled` or `readOnly` is set. @default false */ withPillsReorder?: boolean; } export type MultiSelectFactory = Factory<{ props: MultiSelectProps; ref: HTMLInputElement; stylesNames: MultiSelectStylesNames; signature: ( props: MultiSelectProps ) => React.JSX.Element; }>; const defaultProps = { maxValues: Infinity, withCheckIcon: true, checkIconPosition: 'left', hiddenInputValuesDivider: ',', clearSearchOnChange: true, openOnFocus: true, size: 'sm', } satisfies Partial; export const MultiSelect = genericFactory((_props) => { const props = useProps(['Input', 'InputWrapper', 'MultiSelect'], defaultProps, _props); const { classNames, className, style, styles, unstyled, vars, size, value, defaultValue, onChange, onKeyDown, variant, data, dropdownOpened, defaultDropdownOpened, onDropdownOpen, onDropdownClose, selectFirstOptionOnChange, selectFirstOptionOnDropdownOpen, onOptionSubmit, comboboxProps, filter, limit, withScrollArea, maxDropdownHeight, floatingHeight, searchValue, defaultSearchValue, onSearchChange, readOnly, disabled, onFocus, onBlur, radius, rightSection, rightSectionWidth, rightSectionPointerEvents, rightSectionProps, leftSection, leftSectionWidth, leftSectionPointerEvents, leftSectionProps, inputContainer, inputWrapperOrder, withAsterisk, labelProps, descriptionProps, errorProps, successProps, wrapperProps, description, label, error, success, maxValues, searchable, nothingFoundMessage, withCheckIcon, withAlignedLabels, checkIconPosition, hidePickedOptions, withErrorStyles, withSuccessStyles, name, form, id, clearable, clearSectionMode, clearButtonProps, hiddenInputProps, placeholder, hiddenInputValuesDivider, required, mod, renderOption, renderPill, onRemove, onClear, onMaxValues, scrollAreaProps, chevronColor, attributes, clearSearchOnChange, openOnFocus, loading, loadingPosition, loaderProps, withPillsReorder, ...others } = props; const _id = useId(id); const comboboxLabelId = getComboboxLabelId({ id: _id, label, labelProps, inputWrapperOrder, }); const parsedData = getParsedComboboxData(data); const optionsLockup = getOptionsLockup(parsedData); const retainedSelectedOptions = useRef>>({}); const combobox = useCombobox({ opened: dropdownOpened, defaultOpened: defaultDropdownOpened, onDropdownOpen: () => { onDropdownOpen?.(); if (selectFirstOptionOnDropdownOpen) { combobox.selectFirstOption(); } }, onDropdownClose: () => { onDropdownClose?.(); combobox.resetSelectedOption(); }, }); const { styleProps, rest: { type, autoComplete, ...rest }, } = extractStyleProps(others); const [_value, setValue] = useUncontrolled({ value, defaultValue, finalValue: [], onChange, }); const { getPillProps, getListProps, handleInputKeyDown } = usePillsReorder({ value: _value, onChange: setValue, enabled: withPillsReorder && !disabled && !readOnly, }); const [_searchValue, setSearchValue] = useUncontrolled({ value: searchValue, defaultValue: defaultSearchValue, finalValue: '', onChange: onSearchChange, }); const handleSearchChange = (value: string) => { setSearchValue(value); combobox.resetSelectedOption(); }; const getStyles = useStyles({ name: 'MultiSelect', classes: {} as any, props: props as any, classNames, styles, unstyled, attributes, }); const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi({ props, styles, classNames, }); const canInteract = !readOnly && !disabled; const handleInputKeydown = (event: React.KeyboardEvent) => { onKeyDown?.(event); if (event.defaultPrevented) { return; } if (event.key === ' ' && !searchable) { event.preventDefault(); canInteract && combobox.toggleDropdown(); } if ( event.key === 'Backspace' && _searchValue.length === 0 && _value.length > 0 && !event.nativeEvent.isComposing && !readOnly && !optionsLockup[`${_value[_value.length - 1]}`]?.disabled ) { onRemove?.(_value[_value.length - 1]); setValue(_value.slice(0, _value.length - 1)); } handleInputKeyDown(event); }; const values = _value.map((item, index) => { const optionData = optionsLockup[`${item}`] || retainedSelectedOptions.current[`${item}`]; const reorderProps = getPillProps(index); if (renderPill) { return ( {renderPill({ option: optionData, value: item, onRemove: () => { setValue(_value.filter((i) => item !== i)); onRemove?.(item); }, disabled, reorderProps, })} ); } return ( { setValue(_value.filter((i) => item !== i)); onRemove?.(item); }} unstyled={unstyled} disabled={disabled} {...getStyles('pill')} {...reorderProps} > {optionData?.label || item} ); }); useEffect(() => { if (selectFirstOptionOnChange) { combobox.selectFirstOption(); } }, [selectFirstOptionOnChange, _searchValue]); useEffect(() => { _value.forEach((val) => { if (`${val}` in optionsLockup) { retainedSelectedOptions.current[`${val}`] = optionsLockup[`${val}`]; } }); }, [optionsLockup, _value]); const clearButton = ( { onClear?.(); setValue([]); handleSearchChange(''); }} /> ); const filteredData = filterPickedValues({ data: parsedData, value: _value }); const _clearable = clearable && _value.length > 0 && !disabled && !readOnly; const pillsListStyle = _clearable ? { paddingInlineEnd: clearSectionOffset[size] ?? clearSectionOffset.sm } : undefined; return ( <> { onOptionSubmit?.(val as any); if (clearSearchOnChange) { handleSearchChange(''); } combobox.updateSelectedOptionIndex('selected'); if (_value.includes(optionsLockup[`${val}`].value as any)) { setValue(_value.filter((v) => v !== optionsLockup[`${val}`].value)); onRemove?.(optionsLockup[`${val}`].value as any); } else if (_value.length < maxValues) { setValue([..._value, optionsLockup[`${val}`].value] as any); } else { onMaxValues?.(); } }} {...comboboxProps} > } __clearSection={clearButton} __clearable={_clearable} __clearSectionMode={clearSectionMode} rightSection={rightSection} rightSectionPointerEvents={rightSectionPointerEvents || 'none'} rightSectionWidth={rightSectionWidth} rightSectionProps={rightSectionProps} leftSection={leftSection} leftSectionWidth={leftSectionWidth} leftSectionPointerEvents={leftSectionPointerEvents} leftSectionProps={leftSectionProps} loading={loading} loadingPosition={loadingPosition} loaderProps={loaderProps} inputContainer={inputContainer} inputWrapperOrder={inputWrapperOrder} withAsterisk={withAsterisk} labelProps={labelProps} descriptionProps={descriptionProps} errorProps={errorProps} successProps={successProps} wrapperProps={wrapperProps} description={description} label={label} error={error} success={success} withErrorStyles={withErrorStyles} withSuccessStyles={withSuccessStyles} __stylesApiProps={{ ...props, rightSectionPointerEvents: rightSectionPointerEvents || 'none', multiline: true, }} pointer={!searchable} onClick={() => { if (canInteract) { searchable ? combobox.openDropdown() : combobox.toggleDropdown(); } }} data-expanded={combobox.dropdownOpened || undefined} id={_id} required={required} mod={mod} attributes={attributes} > {values} { onFocus?.(event); openOnFocus && searchable && canInteract && combobox.openDropdown(); }} onBlur={(event) => { onBlur?.(event); combobox.closeDropdown(); handleSearchChange(''); }} onKeyDown={handleInputKeydown} value={_searchValue} onChange={(event) => { if (isExternalInputChange(event)) { if (!readOnly) { const externalOption = getOptionByLabel( optionsLockup, event.currentTarget.value ); if ( externalOption && !_value.includes(externalOption.value as any) && _value.length < maxValues ) { setValue([..._value, externalOption.value] as any); } } return; } handleSearchChange(event.currentTarget.value); searchable && combobox.openDropdown(); selectFirstOptionOnChange && combobox.selectFirstOption(); }} disabled={disabled} readOnly={readOnly || !searchable} pointer={!searchable} /> ); }); MultiSelect.classes = { ...InputBase.classes, ...Combobox.classes }; MultiSelect.displayName = '@mantine/core/MultiSelect'; export namespace MultiSelect { export type Props = MultiSelectProps; export type StylesNames = MultiSelectStylesNames; export type Factory = MultiSelectFactory; }