import { clsx } from 'clsx'; import { CommonProps, AriaLabelProperty } from '../common'; import Chip, { type ChipValue } from './Chip/Chip'; export type { ChipValue }; export type Chip = { value: T; 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: T }) => void; /** Used to manage which chips are selected */ selected: T | readonly T[]; /** True turns on Filter-mode, False is Choice */ multiple?: boolean; }; const Chips = ({ chips, onChange, selected, 'aria-label': ariaLabel, className, multiple, }: ChipsProps) => { const isSelected = (value: T) => Array.isArray(selected) ? selected.includes(value) : selected === value; const handleOnChange = (selectedValue: T, isCurrentlyEnabled: boolean) => { onChange({ isEnabled: !isCurrentlyEnabled, selectedValue }); }; return (
{chips.map((chip) => { const chipSelected = isSelected(chip.value); return ( key={chip.value} role={!multiple ? 'radio' : 'checkbox'} aria-checked={chipSelected} value={chip.value} label={chip.label} className={clsx({ 'np-chip--selected': chipSelected, })} onClick={() => handleOnChange(chip.value, chipSelected)} onKeyPress={(event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); handleOnChange(chip.value, chipSelected); } }} /> ); })}
); }; export default Chips;