Skip to content

Commit

Permalink
Ensure we reset the activeOptionIndex if the active option is unmou…
Browse files Browse the repository at this point in the history
…nted (#2274)

* ensure we reset the `activeOptionIndex` if the active option is unmounted

Unmounting of the active option can happen when you are in a
multi-select Combobox, and you filter out all the selected values. This
means that the moment you press "Enter" on an active item, it becomes
the selected item and therefore will be filtered out.

* update changelog
  • Loading branch information
RobinMalfait committed Feb 10, 2023
1 parent b9af614 commit fcfd554
Show file tree
Hide file tree
Showing 6 changed files with 137 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/@headlessui-react/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Ensure we handle `null` dataRef values correctly ([#2258](https://github.com/tailwindlabs/headlessui/pull/2258))
- Move `aria-multiselectable` to `[role=listbox]` in the `Combobox` component ([#2271](https://github.com/tailwindlabs/headlessui/pull/2271))
- Re-focus `Combobox.Input` when a `Combobox.Option` is selected ([#2272](https://github.com/tailwindlabs/headlessui/pull/2272))
- Ensure we reset the `activeOptionIndex` if the active option is unmounted ([#2274](https://github.com/tailwindlabs/headlessui/pull/2274))

## [1.7.10] - 2023-02-06

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4400,6 +4400,10 @@ describe('Keyboard interactions', () => {

let options: ReturnType<typeof getComboboxOptions>

options = getComboboxOptions()
expect(options[0]).toHaveTextContent('person a')
assertActiveComboboxOption(options[0])

await press(Keys.ArrowDown)

// Person B should be active
Expand Down Expand Up @@ -5646,6 +5650,50 @@ describe('Multi-select', () => {
assertComboboxOption(options[2], { selected: true })
})
)

it(
'should reset the active option, if the active option gets unmounted',
suppressConsoleLogs(async () => {
let users = ['alice', 'bob', 'charlie']
function Example() {
let [value, setValue] = useState<string[]>([])

return (
<Combobox value={value} onChange={(value) => setValue(value)} multiple>
<Combobox.Input onChange={() => {}} />
<Combobox.Button>Trigger</Combobox.Button>
<Combobox.Options>
{users
.filter((user) => !value.includes(user))
.map((user) => (
<Combobox.Option key={user} value={user}>
{user}
</Combobox.Option>
))}
</Combobox.Options>
</Combobox>
)
}

render(<Example />)

// Open combobox
await click(getComboboxButton())
assertCombobox({ state: ComboboxState.Visible })

let options = getComboboxOptions()

// Go to the next option
await press(Keys.ArrowDown)
assertActiveComboboxOption(options[1])

// Select the option
await press(Keys.Enter)

// The active option is reset to the very first one
assertActiveComboboxOption(options[0])
})
)
})

describe('Form compatibility', () => {
Expand Down
28 changes: 27 additions & 1 deletion packages/@headlessui-react/src/components/combobox/combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,17 @@ function ComboboxFn<TValue, TTag extends ElementType = typeof DEFAULT_COMBOBOX_T
[value, defaultValue, disabled, multiple, nullable, __demoMode, state]
)

let lastActiveOption = useRef(
data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null
)
useEffect(() => {
let currentActiveOption =
data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null
if (lastActiveOption.current !== currentActiveOption) {
lastActiveOption.current = currentActiveOption
}
})

useIsoMorphicEffect(() => {
state.dataRef.current = data
}, [data])
Expand Down Expand Up @@ -553,7 +564,22 @@ function ComboboxFn<TValue, TTag extends ElementType = typeof DEFAULT_COMBOBOX_T

let registerOption = useEvent((id, dataRef) => {
dispatch({ type: ActionTypes.RegisterOption, id, dataRef })
return () => dispatch({ type: ActionTypes.UnregisterOption, id })
return () => {
// When we are unregistering the currently active option, then we also have to make sure to
// reset the `defaultToFirstOption` flag, so that visually something is selected and the next
// time you press a key on your keyboard it will go to the proper next or previous option in
// the list.
//
// Since this was the active option and it could have been anywhere in the list, resetting to
// the very first option seems like a fine default. We _could_ be smarter about this by going
// to the previous / next item in list if we know the direction of the keyboard navigation,
// but that might be too complex/confusing from an end users perspective.
if (lastActiveOption.current?.id === id) {
defaultToFirstOption.current = true
}

dispatch({ type: ActionTypes.UnregisterOption, id })
}
})

let registerLabel = useEvent((id) => {
Expand Down
1 change: 1 addition & 0 deletions packages/@headlessui-vue/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Don’t fire `afterLeave` event more than once for a given transition ([#2267](https://github.com/tailwindlabs/headlessui/pull/2267))
- Move `aria-multiselectable` to `[role=listbox]` in the `Combobox` component ([#2271](https://github.com/tailwindlabs/headlessui/pull/2271))
- Re-focus `Combobox.Input` when a `Combobox.Option` is selected ([#2272](https://github.com/tailwindlabs/headlessui/pull/2272))
- Ensure we reset the `activeOptionIndex` if the active option is unmounted ([#2274](https://github.com/tailwindlabs/headlessui/pull/2274))

## [1.7.9] - 2023-02-03

Expand Down
44 changes: 44 additions & 0 deletions packages/@headlessui-vue/src/components/combobox/combobox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5879,6 +5879,50 @@ describe('Multi-select', () => {
assertComboboxOption(options[2], { selected: true })
})
)

it(
'should reset the active option, if the active option gets unmounted',
suppressConsoleLogs(async () => {
renderTemplate({
template: html`
<Combobox v-model="value" multiple>
<ComboboxInput />
<ComboboxButton>Trigger</ComboboxButton>
<ComboboxOptions>
<ComboboxOption
v-for="user in users.filter(p => !value.includes(p))"
:key="user"
:value="user"
>{{ user }}</ComboboxOption
>
</ComboboxOptions>
</Combobox>
`,
setup: () => {
let users = ['alice', 'bob', 'charlie']

let value = ref([])
return { users, value }
},
})

// Open combobox
await click(getComboboxButton())
assertCombobox({ state: ComboboxState.Visible })

let options = getComboboxOptions()

// Go to the next option
await press(Keys.ArrowDown)
assertActiveComboboxOption(options[1])

// Select the option
await press(Keys.Enter)

// The active option is reset to the very first one
assertActiveComboboxOption(options[0])
})
)
})

describe('Form compatibility', () => {
Expand Down
16 changes: 16 additions & 0 deletions packages/@headlessui-vue/src/components/combobox/combobox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,22 @@ export let Combobox = defineComponent({
activationTrigger.value = ActivationTrigger.Other
},
unregisterOption(id: string) {
// When we are unregistering the currently active option, then we also have to make sure to
// reset the `defaultToFirstOption` flag, so that visually something is selected and the
// next time you press a key on your keyboard it will go to the proper next or previous
// option in the list.
//
// Since this was the active option and it could have been anywhere in the list, resetting
// to the very first option seems like a fine default. We _could_ be smarter about this by
// going to the previous / next item in list if we know the direction of the keyboard
// navigation, but that might be too complex/confusing from an end users perspective.
if (
api.activeOptionIndex.value !== null &&
api.options.value[api.activeOptionIndex.value]?.id === id
) {
defaultToFirstOption.value = true
}

let adjustedState = adjustOrderedState((options) => {
let idx = options.findIndex((a) => a.id === id)
if (idx !== -1) options.splice(idx, 1)
Expand Down

0 comments on commit fcfd554

Please sign in to comment.