diff --git a/packages/eds-core-react/src/components/Autocomplete/Autocomplete.test.tsx b/packages/eds-core-react/src/components/Autocomplete/Autocomplete.test.tsx index 442b6aaf3a..04b9547325 100644 --- a/packages/eds-core-react/src/components/Autocomplete/Autocomplete.test.tsx +++ b/packages/eds-core-react/src/components/Autocomplete/Autocomplete.test.tsx @@ -209,6 +209,47 @@ describe('Autocomplete', () => { }) }) + it('Can deselect complex options', async () => { + const onChange = jest.fn() + const opts = [ + { label: 'Its', value: 'relationship' }, + { label: 'Complicated', value: 'status' }, + ] + render( + o.label} + itemCompare={(o1, o2) => o1.value === o2.value} + label={labelText} + options={opts} + data-testid="styled-autocomplete" + multiple={true} + onOptionsChange={onChange} + selectedOptions={[ + { + label: 'Its', + value: 'relationship', + }, + ]} + />, + ) + + const labeledNodes = await screen.findAllByLabelText(labelText) + const optionsList = labeledNodes[1] + + const buttonNode = await screen.findByLabelText('toggle options', { + selector: 'button', + }) + + fireEvent.click(buttonNode) + + const options = await within(optionsList).findAllByRole('option') + fireEvent.click(options[0]) + + await waitFor(() => { + expect(onChange).toHaveBeenCalledWith({ selectedItems: [] }) + }) + }) + it('Can open the options on button click', async () => { render() diff --git a/packages/eds-core-react/src/components/Autocomplete/Autocomplete.tsx b/packages/eds-core-react/src/components/Autocomplete/Autocomplete.tsx index 78865a4a99..03d8954dfe 100644 --- a/packages/eds-core-react/src/components/Autocomplete/Autocomplete.tsx +++ b/packages/eds-core-react/src/components/Autocomplete/Autocomplete.tsx @@ -610,9 +610,14 @@ function AutocompleteInner( if (selectedItem === AllSymbol) { toggleAllSelected() } else if (multiple) { - selectedItems.includes(selectedItem) - ? removeSelectedItem(selectedItem) - : addSelectedItem(selectedItem) + const shouldRemove = itemCompare + ? selectedItems.some((i) => itemCompare(selectedItem, i)) + : selectedItems.includes(selectedItem) + if (shouldRemove) { + removeSelectedItem(selectedItem) + } else { + addSelectedItem(selectedItem) + } } else { setSelectedItems([selectedItem]) }