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

Fix incorrect active option in the Listbox/Combobox component #1264

Merged
merged 3 commits into from
Mar 21, 2022
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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Improve Combobox Input value ([#1248](https://github.com/tailwindlabs/headlessui/pull/1248))
- Fix Tree-shaking support ([#1247](https://github.com/tailwindlabs/headlessui/pull/1247))
- Stop propagation on the Popover Button ([#1263](https://github.com/tailwindlabs/headlessui/pull/1263))
- Fix incorrect `active` option in the Listbox/Combobox component ([#1264](https://github.com/tailwindlabs/headlessui/pull/1264))

### Added

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4057,7 +4057,7 @@ describe('Mouse interactions', () => {
'should be possible to mouse leave an option and make it inactive',
suppressConsoleLogs(async () => {
render(
<Combobox value="test" onChange={console.log}>
<Combobox value="bob" onChange={console.log}>
<Combobox.Input onChange={NOOP} />
<Combobox.Button>Trigger</Combobox.Button>
<Combobox.Options>
Expand Down
75 changes: 40 additions & 35 deletions packages/@headlessui-react/src/components/combobox/combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ interface StateDefinition {

comboboxPropsRef: MutableRefObject<{
value: unknown
mode: ValueMode
onChange(value: unknown): void
__demoMode: boolean
}>
Expand Down Expand Up @@ -155,7 +156,25 @@ let reducers: {
[ActionTypes.OpenCombobox](state) {
if (state.disabled) return state
if (state.comboboxState === ComboboxStates.Open) return state
return { ...state, comboboxState: ComboboxStates.Open }

// Check if we have a selected value that we can make active
let activeOptionIndex = state.activeOptionIndex
let { value, mode } = state.comboboxPropsRef.current
let optionIdx = state.options.findIndex((option) => {
let optionValue = option.dataRef.current.value
let selected = match(mode, {
[ValueMode.Multi]: () => (value as unknown[]).includes(optionValue),
[ValueMode.Single]: () => value === optionValue,
})

return selected
})

if (optionIdx !== -1) {
activeOptionIndex = optionIdx
}

return { ...state, comboboxState: ComboboxStates.Open, activeOptionIndex }
},
[ActionTypes.SetDisabled](state, action) {
if (state.disabled === action.disabled) return state
Expand Down Expand Up @@ -187,9 +206,21 @@ let reducers: {
}
},
[ActionTypes.RegisterOption]: (state, action) => {
let adjustedState = adjustOrderedState(state, (options) => {
return [...options, { id: action.id, dataRef: action.dataRef }]
})
let option = { id: action.id, dataRef: action.dataRef }
let adjustedState = adjustOrderedState(state, (options) => [...options, option])

// Check if we need to make the newly registered option active.
if (state.activeOptionIndex === null) {
let { value, mode } = state.comboboxPropsRef.current
let optionValue = action.dataRef.current.value
let selected = match(mode, {
[ValueMode.Multi]: () => (value as unknown[]).includes(optionValue),
[ValueMode.Single]: () => value === optionValue,
})
if (selected) {
adjustedState.activeOptionIndex = adjustedState.options.indexOf(option)
}
}

let nextState = {
...state,
Expand Down Expand Up @@ -303,9 +334,14 @@ let ComboboxRoot = forwardRefWithAs(function Combobox<

let comboboxPropsRef = useRef<StateDefinition['comboboxPropsRef']['current']>({
value,
mode: Array.isArray(value) ? ValueMode.Multi : ValueMode.Single,
onChange,
__demoMode,
})

comboboxPropsRef.current.value = value
comboboxPropsRef.current.mode = Array.isArray(value) ? ValueMode.Multi : ValueMode.Single

let optionsPropsRef = useRef<StateDefinition['optionsPropsRef']['current']>({
static: false,
hold: false,
Expand Down Expand Up @@ -336,10 +372,6 @@ let ComboboxRoot = forwardRefWithAs(function Combobox<
[value]
)

useIsoMorphicEffect(() => {
comboboxPropsRef.current.value = value
}, [value])

useIsoMorphicEffect(() => {
comboboxPropsRef.current.onChange = (value: unknown) => {
return match(dataBag.mode, {
Expand Down Expand Up @@ -965,18 +997,6 @@ let Option = forwardRefWithAs(function Option<
[ValueMode.Multi]: () => (data.value as TType[]).includes(value),
[ValueMode.Single]: () => data.value === value,
})
let isFirstSelected = match(data.mode, {
[ValueMode.Multi]: () => {
let currentValues = data.value as TType[]

return (
state.options.find((option) =>
currentValues.includes(option.dataRef.current.value as TType)
)?.id === id
)
},
[ValueMode.Single]: () => selected,
})
let internalOptionRef = useRef<HTMLLIElement | null>(null)
let bag = useRef<ComboboxOptionDataRef['current']>({ disabled, value, domRef: internalOptionRef })
let optionRef = useSyncRefs(ref, internalOptionRef)
Expand All @@ -995,21 +1015,6 @@ let Option = forwardRefWithAs(function Option<

useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id])

useIsoMorphicEffect(() => {
if (state.comboboxState !== ComboboxStates.Open) return
if (!selected) return
if (state.activeOptionIndex !== null) return

match(data.mode, {
[ValueMode.Multi]: () => {
if (isFirstSelected) actions.goToOption(Focus.Specific, id)
},
[ValueMode.Single]: () => {
actions.goToOption(Focus.Specific, id)
},
})
}, [state.comboboxState, state.activeOptionIndex, selected, isFirstSelected, id, actions, data])

let enableScrollIntoView = useRef(state.comboboxPropsRef.current.__demoMode ? false : true)
useIsoMorphicEffect(() => {
if (!state.comboboxPropsRef.current.__demoMode) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3723,7 +3723,7 @@ describe('Mouse interactions', () => {
'should be possible to mouse leave an option and make it inactive',
suppressConsoleLogs(async () => {
render(
<Listbox value={undefined} onChange={console.log}>
<Listbox value="bob" onChange={console.log}>
<Listbox.Button>Trigger</Listbox.Button>
<Listbox.Options>
<Listbox.Option value="alice">alice</Listbox.Option>
Expand Down
66 changes: 34 additions & 32 deletions packages/@headlessui-react/src/components/listbox/listbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,25 @@ let reducers: {
[ActionTypes.OpenListbox](state) {
if (state.disabled) return state
if (state.listboxState === ListboxStates.Open) return state
return { ...state, listboxState: ListboxStates.Open }

// Check if we have a selected value that we can make active
let activeOptionIndex = state.activeOptionIndex
let { value, mode } = state.propsRef.current
let optionIdx = state.options.findIndex((option) => {
let optionValue = option.dataRef.current.value
let selected = match(mode, {
[ValueMode.Multi]: () => (value as unknown[]).includes(optionValue),
[ValueMode.Single]: () => value === optionValue,
})

return selected
})

if (optionIdx !== -1) {
activeOptionIndex = optionIdx
}

return { ...state, listboxState: ListboxStates.Open, activeOptionIndex }
},
[ActionTypes.SetDisabled](state, action) {
if (state.disabled === action.disabled) return state
Expand Down Expand Up @@ -220,10 +238,21 @@ let reducers: {
return { ...state, searchQuery: '' }
},
[ActionTypes.RegisterOption]: (state, action) => {
let adjustedState = adjustOrderedState(state, (options) => [
...options,
{ id: action.id, dataRef: action.dataRef },
])
let option = { id: action.id, dataRef: action.dataRef }
let adjustedState = adjustOrderedState(state, (options) => [...options, option])

// Check if we need to make the newly registered option active.
if (state.activeOptionIndex === null) {
let { value, mode } = state.propsRef.current
let optionValue = action.dataRef.current.value
let selected = match(mode, {
[ValueMode.Multi]: () => (value as unknown[]).includes(optionValue),
[ValueMode.Single]: () => value === optionValue,
})
if (selected) {
adjustedState.activeOptionIndex = adjustedState.options.indexOf(option)
}
}

return { ...state, ...adjustedState }
},
Expand Down Expand Up @@ -738,18 +767,6 @@ let Option = forwardRefWithAs(function Option<
[ValueMode.Multi]: () => (state.propsRef.current.value as TType[]).includes(value),
[ValueMode.Single]: () => state.propsRef.current.value === value,
})
let isFirstSelected = match(state.propsRef.current.mode, {
[ValueMode.Multi]: () => {
let currentValues = state.propsRef.current.value as TType[]

return (
state.options.find((option) =>
currentValues.includes(option.dataRef.current.value as TType)
)?.id === id
)
},
[ValueMode.Single]: () => selected,
})

let internalOptionRef = useRef<HTMLLIElement | null>(null)
let optionRef = useSyncRefs(ref, internalOptionRef)
Expand Down Expand Up @@ -784,21 +801,6 @@ let Option = forwardRefWithAs(function Option<
return () => dispatch({ type: ActionTypes.UnregisterOption, id })
}, [bag, id])

useIsoMorphicEffect(() => {
if (state.listboxState !== ListboxStates.Open) return
if (!selected) return
if (state.activeOptionIndex !== null) return

match(state.propsRef.current.mode, {
[ValueMode.Multi]: () => {
if (isFirstSelected) dispatch({ type: ActionTypes.GoToOption, focus: Focus.Specific, id })
},
[ValueMode.Single]: () => {
dispatch({ type: ActionTypes.GoToOption, focus: Focus.Specific, id })
},
})
}, [state.listboxState, state.activeOptionIndex, selected, isFirstSelected, state.propsRef.current.mode, id])

let handleClick = useCallback(
(event: { preventDefault: Function }) => {
if (disabled) return event.preventDefault()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4302,7 +4302,7 @@ describe('Mouse interactions', () => {
</ComboboxOptions>
</Combobox>
`,
setup: () => ({ value: ref(null) }),
setup: () => ({ value: ref('bob') }),
})

// Open combobox
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3862,7 +3862,7 @@ describe('Mouse interactions', () => {
</ListboxOptions>
</Listbox>
`,
setup: () => ({ value: ref(null) }),
setup: () => ({ value: ref('bob') }),
})

// Open listbox
Expand Down