Skip to content

Commit b2ce3f7

Browse files
committed
fix: mouse leave does not clear highlight
1 parent 5767fbf commit b2ce3f7

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

packages/listbox/src/listbox.test.tsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,4 +335,18 @@ describe('listbox primitives', () => {
335335

336336
expect(screen.getByRole('listbox', { name: 'External team label' })).toBeTruthy()
337337
})
338+
339+
it('clears highlighted option when mouse leaves an option', async () => {
340+
const user = userEvent.setup()
341+
const { listbox } = renderSingleListbox()
342+
343+
await user.hover(getOption('Banana'))
344+
345+
expect(getOption('Banana').getAttribute('data-highlighted')).toBe('')
346+
expect(getActiveOption(listbox).textContent).toBe('Banana')
347+
348+
await user.unhover(getOption('Banana'))
349+
350+
expect(getOption('Banana').hasAttribute('data-highlighted')).toBeFalsy()
351+
})
338352
})

packages/listbox/src/listbox.tsx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,12 +518,18 @@ function useItemBehavior(optionValue: string, disabled: boolean) {
518518
setActiveValue(optionValue)
519519
}, [isItemDisabled, optionValue, setActiveValue])
520520

521+
const handleMouseLeave = useCallback(() => {
522+
if (!isItemDisabled && activeValue === optionValue)
523+
setActiveValue(null)
524+
}, [isItemDisabled, setActiveValue, optionValue, activeValue])
525+
521526
return {
522527
isHighlighted,
523528
isItemDisabled,
524529
isSelected,
525530
handleMouseMove,
526531
selectItem,
532+
handleMouseLeave,
527533
}
528534
}
529535

@@ -539,6 +545,7 @@ export function ListboxItem({
539545
asChild = false,
540546
onClick,
541547
onMouseMove,
548+
onMouseLeave,
542549
id: idProp,
543550
...props
544551
}: ItemProps & { ref?: Ref<HTMLDivElement> }) {
@@ -550,6 +557,7 @@ export function ListboxItem({
550557
isSelected,
551558
handleMouseMove,
552559
selectItem,
560+
handleMouseLeave,
553561
} = useItemBehavior(optionValue, disabled)
554562

555563
const itemData = useMemo(() => ({
@@ -572,6 +580,7 @@ export function ListboxItem({
572580
'aria-disabled': isItemDisabled || undefined,
573581
'onMouseMove': composeEventHandlers(onMouseMove, handleMouseMove),
574582
'onClick': composeEventHandlers(onClick, handleClick),
583+
'onMouseLeave': composeEventHandlers(onMouseLeave, handleMouseLeave),
575584
'data-state': isSelected ? 'checked' : 'unchecked',
576585
'data-highlighted': isHighlighted ? '' : undefined,
577586
'data-disabled': isItemDisabled ? '' : undefined,

0 commit comments

Comments
 (0)