fix(dropdown): preserve selected value in input when reopening

This commit is contained in:
amanape 2025-12-19 20:56:41 +04:00
parent abecc156a4
commit d6fc553ad9
2 changed files with 29 additions and 2 deletions

View File

@ -154,6 +154,30 @@ describe("Dropdown", () => {
const selectedOption = screen.getByRole("option", { name: "Option 1" });
expect(selectedOption).toHaveAttribute("aria-selected", "true");
});
it("should preserve selected value in input and show all options when reopening dropdown", async () => {
const user = userEvent.setup();
render(<Dropdown options={mockOptions} />);
const trigger = screen.getByTestId("dropdown-trigger");
await user.click(trigger);
await user.click(screen.getByRole("option", { name: "Option 1" }));
// Reopen the dropdown
await user.click(trigger);
const input = screen.getByRole("combobox");
expect(input).toHaveValue("Option 1");
expect(
screen.getByRole("option", { name: "Option 1" }),
).toBeInTheDocument();
expect(
screen.getByRole("option", { name: "Option 2" }),
).toBeInTheDocument();
expect(
screen.getByRole("option", { name: "Option 3" }),
).toBeInTheDocument();
});
});
describe("Clear button", () => {

View File

@ -32,9 +32,10 @@ export function Dropdown({
testId,
}: DropdownProps) {
const [inputValue, setInputValue] = useState(defaultValue?.label ?? "");
const [searchTerm, setSearchTerm] = useState("");
const filteredOptions = options.filter((option) =>
option.label.toLowerCase().includes(inputValue.toLowerCase()),
option.label.toLowerCase().includes(searchTerm.toLowerCase()),
);
const {
@ -51,6 +52,7 @@ export function Dropdown({
inputValue,
onInputValueChange: ({ inputValue: newValue }) => {
setInputValue(newValue ?? "");
setSearchTerm(newValue ?? "");
},
defaultSelectedItem: defaultValue,
onSelectedItemChange: ({ selectedItem: newSelectedItem }) => {
@ -61,9 +63,10 @@ export function Dropdown({
selectedItem: currentSelectedItem,
}) => {
if (newIsOpen) {
setInputValue("");
setSearchTerm("");
} else {
setInputValue(currentSelectedItem?.label ?? "");
setSearchTerm("");
}
},
});