Skip to content

Commit

Permalink
next: gracefully handle deselect on single listbox/combobox (#713)
Browse files Browse the repository at this point in the history
  • Loading branch information
huntabyte authored Oct 2, 2024
1 parent e6e4afd commit 4fc8650
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/serious-shrimps-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"bits-ui": patch
---

Listbox/Combobox: gracefully handle deselect when `type="single"`
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@
}
}
value === undefined && (value = type === "single" ? "" : []);
useListboxRoot({
type,
value: box.with(
Expand Down
4 changes: 3 additions & 1 deletion packages/bits-ui/src/lib/bits/listbox/listbox.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -800,8 +800,10 @@ class ListboxItemState {
// prevent any default behavior
e.preventDefault();
if (this.disabled.current) return;
const isCurrentSelectedValue = this.value.current === this.root.value.current;
this.root.toggleItem(this.value.current, this.label.current);
if (!this.root.isMulti) {

if (!this.root.isMulti && !isCurrentSelectedValue) {
this.root.closeMenu();
}
};
Expand Down
13 changes: 13 additions & 0 deletions packages/bits-ui/src/tests/listbox/listbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,19 @@ describe("listbox - single", () => {
const content = getByTestId("content");
expect(content).toBeVisible();
});

it("should deselect the selected item when the user clicks on the selected item", async () => {
const { getByTestId, user, trigger } = await openSingle();
const [item0] = getItems(getByTestId);
await user.click(item0!);
expectSelected(item0!);
await user.click(trigger);

const [item0v2] = getItems(getByTestId);

await user.click(item0v2!);
expectNotSelected(item0v2!);
});
});

////////////////////////////////////
Expand Down

0 comments on commit 4fc8650

Please sign in to comment.