import { EuiFilterButton, EuiFilterGroup, EuiIcon, EuiInputPopover, EuiPopover, EuiPopoverProps, EuiPopoverTitle, EuiSelectable, EuiSelectableOption, EuiSelectableOptionsListProps, EuiSelectableProps, EuiText, useEuiI18n, useEuiTheme, } from "@elastic/eui" import { ReactNode, useMemo, useState } from "react" import { SelectOptionList } from "./SelectOptionList" import { useUpdateEffect } from "rooks" const DEFAULT_EMPTY_VALUE = () => undefined const SELECT_ALL_KEY = "$$$__SELECT_ALL__&&&" export type SelectOption = { value: T label: string searchableLabel?: string disabled?: boolean inputDisplay?: ReactNode dropdownDisplay?: ReactNode append?: ReactNode prepend?: ReactNode isGroupLabel?: boolean } export type SelectProps = { id?: string options: SelectOption[] label?: ReactNode placeholder?: string searchable?: boolean popoverMode?: "attached" | "detached" popoverProps?: Partial & { anchorPosition?: "downLeft" | "downRight" | "downCenter" } emptyValue?: () => T | null | undefined hasDividers?: boolean fullWidth?: boolean style?: React.CSSProperties className?: string searchListProps?: Partial onBlur?: () => void isDisabled?: boolean isLoading?: boolean isClearable?: boolean renderSearchOption?: (opt: SelectOption, searchValue: string) => ReactNode selectAll?: string onSelectAll?: (isSelectAllChecked: boolean) => void getIsSelectedAll?: ( selectedOptions: SelectOption[], allOptions: SelectOption[] ) => boolean updateValueOnOptionsChange?: boolean } & ( | { multiple?: false value?: T onChange?: (value: T | undefined) => void } | { multiple: true value?: T[] onChange?: (values: T[]) => void } ) function defaultGetIsSelectedAll( selectedOptions: SelectOption[], allOptions: SelectOption[] ) { // Don't consider options with isGroupLabel true return ( selectedOptions.filter((o) => !o.isGroupLabel).length === allOptions.filter((o) => !o.isGroupLabel).length ) } export const Select = (props: SelectProps) => { const { id, options, label, placeholder, searchable, popoverMode = props.searchable ? "detached" : "attached", popoverProps, multiple, value, emptyValue = DEFAULT_EMPTY_VALUE, hasDividers, fullWidth, style, className, searchListProps, renderSearchOption, onChange, onBlur, isDisabled, isLoading, isClearable = false, selectAll, onSelectAll, getIsSelectedAll = defaultGetIsSelectedAll, updateValueOnOptionsChange = false, } = props const [isPopoverOpen, setPopoverOpen] = useState(false) const hasSelectAll = multiple && selectAll ? true : false const togglePopover = () => setPopoverOpen((val) => !val) const closePopover = () => { setPopoverOpen(false) onBlur?.() } // options keys const selectOptionKeys = useMemo(() => { return options.map((o) => JSON.stringify(o.value)) }, [options]) // selected options const selectedOptions = useMemo(() => { if (multiple) { return options.filter( (o) => Array.isArray(value) && value.includes && value.includes(o.value) ) } else { return options.find((o) => value === o.value) } }, [options, value, multiple]) // select option list options const selectOptionsListOptions = useMemo(() => { if (hasSelectAll && selectAll) { const selectAllOption: SelectOption = { label: selectAll, value: SELECT_ALL_KEY, } return [selectAllOption, ...options] } else { return options } }, [options, hasSelectAll, selectAll]) const isSelectedAll = useMemo(() => { if (hasSelectAll) { if (Array.isArray(selectedOptions)) { return getIsSelectedAll(selectedOptions, options) } } return false }, [hasSelectAll, selectedOptions, options, getIsSelectedAll]) // options for EuiSelectable const selectableOptions = useMemo(() => { const opts = options.map((o, index) => { const isChecked = Array.isArray(value) ? value.includes(o.value) : value === o.value const opt: EuiSelectableOption = { key: selectOptionKeys[index], label: o.label, searchableLabel: o.searchableLabel, disabled: o.disabled, checked: isChecked ? "on" : undefined, append: o.append, prepend: o.prepend, isGroupLabel: o.isGroupLabel, data: { __original: o, }, } return opt }) if (hasSelectAll && selectAll) { opts.splice(0, 0, { key: SELECT_ALL_KEY, label: selectAll, checked: isSelectedAll ? "on" : undefined, }) } return opts }, [options, value, selectOptionKeys, hasSelectAll, selectAll, isSelectedAll]) const onChangeSafe = ( valueOrValues: T | (T | null | undefined)[] | null | undefined ) => { // Cast to any because TS cannot understand that if not `multiple` then `onChange` should accept a single item onChange?.(valueOrValues as any) } const defaultOnSelectAll = (isSelectedAllChecked: boolean) => { onChangeSafe(isSelectedAllChecked ? options.map((o) => o.value) : []) } const handleSelectAll = onSelectAll ?? defaultOnSelectAll // selected option values const selectedOptionValues = useMemo(() => { let values: T[] = [] if (Array.isArray(selectedOptions)) { values = selectedOptions.map((o) => o.value) } else if (selectedOptions != null) { values = [selectedOptions.value] } else { values = [] } if (hasSelectAll && isSelectedAll) { values.push(SELECT_ALL_KEY as T) } return values }, [selectedOptions, hasSelectAll, isSelectedAll]) // Update value on options change if the currently selected value(s) is not present in the new options list useUpdateEffect(() => { if (!updateValueOnOptionsChange || isLoading) { return } const shouldUpdateValueOnOptionsChange = () => { if (multiple) { return ( Array.isArray(value) && value.some((v) => !options.some((o) => o.value === v)) ) } else { return value != null && !options.some((o) => o.value === value) } } if (shouldUpdateValueOnOptionsChange()) { if (multiple) { const newValue = Array.isArray(value) ? value.filter((v) => options.some((o) => o.value === v)) : [] onChangeSafe(newValue) } else { const newValue = options.some((o) => o.value === value) ? value : emptyValue() onChangeSafe(newValue) } } }, [options, updateValueOnOptionsChange, isLoading]) const keyToOptionValue = (key: string) => { const index = selectOptionKeys.indexOf(key) const value = index !== -1 ? options[index].value : emptyValue() return value } const handleSelectableChange = (nextOptions: EuiSelectableOption[]) => { if (props.multiple) { const wasSelectedAllChecked = !isSelectedAll && nextOptions.find((o) => o.key === SELECT_ALL_KEY)?.checked === "on" const wasSelectedAllUnchecked = isSelectedAll && nextOptions.find((o) => o.key === SELECT_ALL_KEY)?.checked !== "on" if (wasSelectedAllChecked) { return handleSelectAll(true) } else if (wasSelectedAllUnchecked) { return handleSelectAll(false) } else { const newValue = nextOptions .filter((o) => o.checked === "on" && o.key !== SELECT_ALL_KEY) .map((o) => keyToOptionValue(o.key!)) onChangeSafe(newValue) } } else { const selectedKey = nextOptions.find((o) => o.checked === "on")?.key const newValue = selectedKey != null ? keyToOptionValue(selectedKey) : emptyValue() onChangeSafe(newValue) closePopover() } } const handleOptionChange = (option: SelectOption, selected: boolean) => { if (multiple) { let newValue = Array.isArray(value) ? [...value] : [] const wasSelectedAllChecked = option.value === SELECT_ALL_KEY && selected const wasSelectedAllUnchecked = option.value === SELECT_ALL_KEY && !selected if (wasSelectedAllChecked) { return handleSelectAll(true) } else if (wasSelectedAllUnchecked) { return handleSelectAll(false) } else if (selected) { newValue = [...newValue, option.value] } else { newValue = newValue.filter((o) => o !== option.value) } onChangeSafe(newValue) } else { onChangeSafe(selected ? option.value : emptyValue()) closePopover() } } const hasValue = Array.isArray(selectedOptions) ? selectedOptions.length > 0 : selectedOptions != null const showClearButton = isClearable && hasValue && !isDisabled && !isLoading const handleClear = () => { onChangeSafe(multiple ? [] : emptyValue()) onBlur?.() } function renderSelectedOption(option: SelectOption) { const { label, inputDisplay } = option return inputDisplay || label } function renderButton() { const button = renderFilterButton() if (!isClearable) { return button } // Always wrap when clearable, so that the button is not remounted when the value changes return (
{button} {showClearButton && }
) } function renderFilterButton() { if (Array.isArray(selectedOptions)) { const isActive = selectedOptions.length > 0 return ( {label} ) } else { return ( {selectedOptions ? ( renderSelectedOption(selectedOptions) ) : ( {placeholder} )} ) } } function renderContent() { if (searchable) { const renderOption: EuiSelectableProps["renderOption"] = renderSearchOption ? (opt, searchValue) => { const oOpt = opt.data?.__original ?? (opt as any).__original return oOpt ? renderSearchOption(oOpt, searchValue) : opt.label } : undefined return ( {(list, search) => ( <> {search} {list} )} ) } else { return ( ) } } if (popoverMode === "attached") { return ( {renderContent()} ) } else { return ( {renderContent()} ) } } // Replicates EuiFormControlLayoutClearButton (used by EuiComboBox), which is not exported by EUI const SelectClearButton = ({ onClick }: { onClick: () => void }) => { const { euiTheme, colorMode } = useEuiTheme() const ariaLabel = useEuiI18n("euiFormControlLayoutClearButton.label", "Clear input") return ( ) }