Skip to content

Commit

Permalink
next: gracefully handle deselect on single listbox
Browse files Browse the repository at this point in the history
  • Loading branch information
huntabyte committed Oct 2, 2024
1 parent e6e4afd commit db021fc
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
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 db021fc

Please sign in to comment.