Skip to content

Commit

Permalink
LG-3955: Combobox shows incorrect highlight after making selection (#…
Browse files Browse the repository at this point in the history
…2679)

* Fix

* changeset
  • Loading branch information
tsck authored Feb 4, 2025
1 parent b39486c commit 7485a00
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/cold-tables-jam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@leafygreen-ui/combobox': patch
---

Fix option highlighting on re-open after selection
31 changes: 31 additions & 0 deletions packages/combobox/src/Combobox/Combobox.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,37 @@ describe('packages/combobox', () => {
expect(optionElements).toHaveLength(defaultOptions.length);
});

test('First item is highlighted when re-opened after selection is made', async () => {
const initialValue = 'banana'; // Select an option that is not the first one
const { comboboxEl, getMenuElements } = renderCombobox('single', {
initialValue,
});

// Open the combobox
userEvent.click(comboboxEl);
let { optionElements } = getMenuElements();
expect(optionElements).toHaveLength(defaultOptions.length);

// Verify that the first item is highlighted
expect(
(optionElements as HTMLCollectionOf<HTMLLIElement>)[0],
).toHaveAttribute('aria-selected', 'true');

// Click the same option again to close the menu
userEvent.click(
(optionElements as HTMLCollectionOf<HTMLLIElement>)[1], // Click the second option
);

// Open the combobox again
userEvent.click(comboboxEl);
optionElements = getMenuElements().optionElements;

// Verify that the first item is highlighted again
expect(
(optionElements as HTMLCollectionOf<HTMLLIElement>)[0],
).toHaveAttribute('aria-selected', 'true');
});

describe('Clickaway', () => {
test('Menu closes on click-away', async () => {
const { containerEl, openMenu } = renderCombobox(select);
Expand Down
7 changes: 3 additions & 4 deletions packages/combobox/src/Combobox/Combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -609,13 +609,12 @@ export function Combobox<M extends boolean>({
],
);

// When the input value changes (or when the menu opens)
// Update the focused option
// Reset the highlighted option when the menu closes so that it opens to the first option
useEffect(() => {
if (inputValue !== prevValue) {
if (!isOpen) {
updateHighlightedOption('first');
}
}, [inputValue, isOpen, prevValue, updateHighlightedOption]);
}, [isOpen, updateHighlightedOption]);

// When the focused option changes, update the menu scroll if necessary
useAutoScroll(
Expand Down

0 comments on commit 7485a00

Please sign in to comment.