import { Field, Label, Listbox, ListboxButton, ListboxOption, ListboxOptions, } from '@headlessui/react'; import { CheckIcon, ChevronDownIcon } from '@heroicons/react/20/solid'; import { Chip } from '@mui/material'; import clsx from 'clsx'; import React, { useEffect, useState } from 'react'; import { GetCustomFieldType } from '../../../../../services/data'; type ListItem = { id: number; value: string; label?: string; }; type MultiSelectDropdownProps = { items: ListItem[]; title: string; placeholder?: string; setCurrentCustomFields: React.Dispatch< React.SetStateAction >; id: string; text: string[]; currentLanguage: string; }; const MultiSelectDropdownCustom: React.FC = ({ items, title, placeholder, setCurrentCustomFields, id, text, currentLanguage, }) => { const [selected, setSelected] = useState( items.filter(item => text.includes(item.value)), ); useEffect(() => { setSelected(items.filter(item => text.includes(item.value))); }, [items, text]); const onChange = (items: ListItem[]) => { const values = items.map(item => item.value); setCurrentCustomFields((prevFields: GetCustomFieldType[]) => { return prevFields.map((field: GetCustomFieldType) => field._id === id ? { ...field, text: field.text.map(itemIter => itemIter.locale === currentLanguage ? { locale: itemIter.locale, value: values, } : itemIter, ), } : field, ); }); }; const ids = items.map(item => item.id); const hasDuplicateIds = new Set(ids).size !== ids.length; if (hasDuplicateIds) { throw new Error('the item IDs must be unique.'); } const handleChange = (items: ListItem[]) => { onChange(items); }; const handleDeleteChip = (deletedItem: ListItem) => { handleChange(selected.filter(item => item !== deletedItem)); }; return ( {selected.length > 0 ? selected.map(s => ( handleDeleteChip(s)} variant="outlined" /> )) : placeholder} {items.map(item => ( s.id === item.id), invisible: !selected.some(s => s.id === item.id), })} />
{item.label ? item.label : item.value}
))}
); }; export default MultiSelectDropdownCustom;