|
| 1 | +import { useState, Fragment } from 'react' |
| 2 | +import { Combobox } from '@headlessui/react' |
| 3 | + |
| 4 | +function XIcon ({ className, onClick }) { |
| 5 | + return ( |
| 6 | + <svg className={className} onClick={onClick} xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='currentColor' strokeWidth={2}> |
| 7 | + <path strokeLinecap='round' strokeLinejoin='round' d='M6 18L18 6M6 6l12 12' /> |
| 8 | + </svg> |
| 9 | + ) |
| 10 | +} |
| 11 | +export default function AutocompleteInput ({ items, selectedItems, setSelectedItems }) { |
| 12 | + const [query, setQuery] = useState('') |
| 13 | + |
| 14 | + function removeSelectedItem (itemId) { |
| 15 | + const newSelectedItems = selectedItems.filter(item => item.id !== itemId) |
| 16 | + setSelectedItems(newSelectedItems) |
| 17 | + } |
| 18 | + |
| 19 | + const filteredItems = |
| 20 | + query === '' |
| 21 | + ? items |
| 22 | + : items.filter(({ name }) => name.toLowerCase().includes(query.toLowerCase())) |
| 23 | + |
| 24 | + return ( |
| 25 | + <Combobox value={selectedItems} onChange={setSelectedItems} multiple> |
| 26 | + <Combobox.Input |
| 27 | + onChange={(event) => setQuery(event.target.value)} |
| 28 | + displayValue={(item) => item.name} |
| 29 | + className='block w-full rounded-md border-gray-300' |
| 30 | + /> |
| 31 | + {selectedItems.length > 0 && ( |
| 32 | + <div className='flex mt-1'> |
| 33 | + {selectedItems.map(({ id, name }) => ( |
| 34 | + <div key={id} className='flex p-1 border-solid border-2 border-gray-300 rounded-md mr-2'> |
| 35 | + {name} <XIcon className='w-4 ml-3' onClick={() => removeSelectedItem(id)} /> |
| 36 | + </div> |
| 37 | + ))} |
| 38 | + </div> |
| 39 | + )} |
| 40 | + <Combobox.Options className='border-solid border-2 border-gray-300 rounded-md'> |
| 41 | + {filteredItems.map((item) => ( |
| 42 | + /* Use the `active` state to conditionally style the active option. */ |
| 43 | + <Combobox.Option key={item.id} value={item} as={Fragment}> |
| 44 | + {({ active }) => ( |
| 45 | + <li |
| 46 | + className={`px-4 py-2 ${ |
| 47 | + active ? 'bg-kernel-green-dark text-white' : 'bg-white text-black' |
| 48 | + }`} |
| 49 | + > |
| 50 | + {item.name} |
| 51 | + </li> |
| 52 | + )} |
| 53 | + </Combobox.Option> |
| 54 | + ))} |
| 55 | + </Combobox.Options> |
| 56 | + </Combobox> |
| 57 | + ) |
| 58 | +} |
0 commit comments