Skip to content

Multiselect dropdown closes unexpectedly when deselecting last selected item #1634

@joshhunt

Description

@joshhunt

We are using useMultipleSelection with useCombobox to create a multiselect dropdown that keeps selected items visible in the menu.

When clicking an item in the menu that's already selected, and that item is last in the selectedItems list, the dropdown unexpectedly closes. This appears to be caused by the focus management logic in useMultipleSelection which seems to be built with the assumption that you can only remove items via the selected item 'pills'?

It looks like the relevant code is

case stateChangeTypes.FunctionRemoveSelectedItem: {
let newActiveIndex = activeIndex
const selectedItemIndex = selectedItems.findIndex(
item => props.itemToKey(item) === props.itemToKey(selectedItem),
)
if (selectedItemIndex < 0) {
break
}
if (selectedItems.length === 1) {
newActiveIndex = -1
} else if (selectedItemIndex === selectedItems.length - 1) {
newActiveIndex = selectedItems.length - 2
}

and

if (activeIndex === -1 && dropdownRef.current) {
dropdownRef.current.focus()
} else if (selectedItemRefs.current[activeIndex]) {
selectedItemRefs.current[activeIndex].focus()
}

I don't yet have a minimal standalone reproduction, but our component is here https://github.com/grafana/grafana/blob/cf631d0c9f5f8cb07f2988bc3de3b713adee1c58/packages/grafana-ui/src/components/Combobox/MultiCombobox.tsx

If a standlone reproduction would help, let me know and ill try and get one up on stackblitz or something.

I'm happy to contribute a fix, but I don't completely understand the downshift code i linked to, or understand exactly what causes the problem, so I would need some pointers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions