Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure we reset the activeOptionIndex if the active option is unmounted #2274

Merged
merged 2 commits into from
Feb 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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