Skip to content

Commit 5d62565

Browse files
authored
fix(Command): allow selection of initial value (#1837)
1 parent 630e7b6 commit 5d62565

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

.changeset/eight-lamps-stop.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"bits-ui": patch
3+
---
4+
5+
fix(Command): allow selection of the initial value when passed as the `value` prop

packages/bits-ui/src/lib/bits/command/command.svelte.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,11 @@ export class CommandRootState {
189189
*/
190190
#sort(): void {
191191
if (!this._commandState.search || this.opts.shouldFilter.current === false) {
192-
// If no search and no selection yet, select first item
193-
this.#selectFirstItem();
192+
// if no search and no initial value set or when clearing search,
193+
// we select the first item.
194+
if (!this._commandState.value || !this.#isInitialMount) {
195+
this.#selectFirstItem();
196+
}
194197
return;
195198
}
196199

tests/src/tests/command/command.browser.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,22 @@ it("should allow forcing the selected value", async () => {
3636
await expect.element(page.getByText("Introduction")).toHaveAttribute("data-selected");
3737
});
3838

39+
it("should respect initial value when it's not the first item", async () => {
40+
setup({ value: "Radio Group" });
41+
42+
// ensure the initial value is selected, not the first item
43+
await expect.element(page.getByText("Radio Group")).toHaveAttribute("data-selected");
44+
await expect.element(page.getByText("Introduction")).not.toHaveAttribute("data-selected");
45+
});
46+
47+
it("should respect initial value for items in the first group", async () => {
48+
setup({ value: "Styling" });
49+
50+
// ensure the provided value is selected, not the first item
51+
await expect.element(page.getByText("Styling")).toHaveAttribute("data-selected");
52+
await expect.element(page.getByText("Introduction")).not.toHaveAttribute("data-selected");
53+
});
54+
3955
it("should render the separator when search is empty and remove it when search is not empty", async () => {
4056
const t = setup();
4157

0 commit comments

Comments
 (0)