From 117310c83822e245a0d83643ca6c776eda4b24fe Mon Sep 17 00:00:00 2001 From: WK Wong Date: Sun, 29 Dec 2024 22:15:39 +0800 Subject: [PATCH] fix(autocomplete): clear autocomplete value when pressing clear button --- .changeset/nice-books-yell.md | 5 +++ .../__tests__/autocomplete.test.tsx | 43 +++++++++++++++++++ .../autocomplete/src/use-autocomplete.ts | 6 +-- 3 files changed, 49 insertions(+), 5 deletions(-) create mode 100644 .changeset/nice-books-yell.md diff --git a/.changeset/nice-books-yell.md b/.changeset/nice-books-yell.md new file mode 100644 index 0000000000..4d95c78535 --- /dev/null +++ b/.changeset/nice-books-yell.md @@ -0,0 +1,5 @@ +--- +"@nextui-org/autocomplete": patch +--- + +clear autocomplete value when pressing clear button (#4402) diff --git a/packages/components/autocomplete/__tests__/autocomplete.test.tsx b/packages/components/autocomplete/__tests__/autocomplete.test.tsx index 55a050d64c..bc06f15d5c 100644 --- a/packages/components/autocomplete/__tests__/autocomplete.test.tsx +++ b/packages/components/autocomplete/__tests__/autocomplete.test.tsx @@ -235,6 +235,49 @@ describe("Autocomplete", () => { expect(autocomplete).toHaveFocus(); }); + it("should clear arbitrary value after clicking clear button", async () => { + const wrapper = render( + + + Penguin + + + Zebra + + + Shark + + , + ); + + const autocomplete = wrapper.getByTestId("autocomplete"); + + // open the select listbox + await user.click(autocomplete); + + // assert that the autocomplete listbox is open + expect(autocomplete).toHaveAttribute("aria-expanded", "true"); + + await user.keyboard("pe"); + + const {container} = wrapper; + + const clearButton = container.querySelector( + "[data-slot='inner-wrapper'] button:nth-of-type(1)", + )!; + + expect(clearButton).not.toBeNull(); + + // click the clear button + await user.click(clearButton); + + // assert that the input has empty value + expect(autocomplete).toHaveValue(""); + + // assert that input is focused + expect(autocomplete).toHaveFocus(); + }); + it("should keep the ListBox open after clicking clear button", async () => { const wrapper = render( diff --git a/packages/components/autocomplete/src/use-autocomplete.ts b/packages/components/autocomplete/src/use-autocomplete.ts index 381809b85b..5b8337b1d4 100644 --- a/packages/components/autocomplete/src/use-autocomplete.ts +++ b/packages/components/autocomplete/src/use-autocomplete.ts @@ -418,13 +418,9 @@ export function useAutocomplete(originalProps: UseAutocomplete onPress: (e: PressEvent) => { slotsProps.clearButtonProps?.onPress?.(e); if (state.selectedItem) { - state.setInputValue(""); state.setSelectedKey(null); - } else { - if (allowsCustomValue) { - state.setInputValue(""); - } } + state.setInputValue(""); state.open(); }, "data-visible": !!state.selectedItem || state.inputValue?.length > 0,