import { clsx } from 'clsx'; import { useIntl } from 'react-intl'; import { CommonProps, AriaLabelProperty } from '../common'; import Chip from './Chip'; import messages from './Chips.messages'; export type ChipValue = string | number; export type Chip = { value: ChipValue; label: string; }; export type ChipsProps = CommonProps & AriaLabelProperty & { /** List of chips with string labels and string/number values */ chips: readonly Chip[]; /** Callback which is invoked when a chip is selected or deselected */ onChange: ({ isEnabled, selectedValue, }: { isEnabled: boolean; selectedValue: ChipValue; }) => void; /** Used to manage which chips are selected */ selected: ChipValue | readonly ChipValue[]; /** True turns on Filter-mode, False is Choice */ multiple?: boolean; }; const Chips = ({ chips, onChange, selected, 'aria-label': ariaLabel, className, multiple, }: ChipsProps) => { const intl = useIntl(); const isSelected = (value: ChipValue) => Array.isArray(selected) ? selected.includes(value) : selected === value; const handleOnChange = (selectedValue: ChipValue, isCurrentlyEnabled: boolean) => { onChange({ isEnabled: !isCurrentlyEnabled, selectedValue }); }; return (
{chips.map((chip) => { const chipSelected = isSelected(chip.value); return ( handleOnChange(chip.value, chipSelected), } : { onClick: () => handleOnChange(chip.value, chipSelected), onKeyPress: () => handleOnChange(chip.value, chipSelected), })} /> ); })}
); }; export default Chips;