diff --git a/.changeset/whole-eels-poke.md b/.changeset/whole-eels-poke.md new file mode 100644 index 0000000000..64f6a98969 --- /dev/null +++ b/.changeset/whole-eels-poke.md @@ -0,0 +1,6 @@ +--- +"@gradio/dropdown": patch +"gradio": patch +--- + +fix:Update the selected indices in `Dropdown` when value changes programmatically diff --git a/js/dropdown/dropdown.test.ts b/js/dropdown/dropdown.test.ts index ddf4167f47..c5cebcc69e 100644 --- a/js/dropdown/dropdown.test.ts +++ b/js/dropdown/dropdown.test.ts @@ -326,4 +326,43 @@ describe("Dropdown", () => { await item.blur(); expect(item.value).toBe("applepie"); }); + + test("setting a value should update the displayed value and selected indices", async () => { + const { getByLabelText, getAllByTestId, component } = await render( + Dropdown, + { + show_label: true, + loading_status, + value: "", + allow_custom_value: false, + label: "Dropdown", + choices: [ + ["apple", "apple"], + ["zebra", "zebra"], + ["pony", "pony"] + ], + filterable: true, + interactive: true + } + ); + + const item: HTMLInputElement = getByLabelText( + "Dropdown" + ) as HTMLInputElement; + + expect(item.value).toBe("apple"); + await item.focus(); + let options = getAllByTestId("dropdown-option"); + expect(options[0]).toHaveClass("selected"); + + await component.$set({ value: "zebra" }); + expect(item.value).toBe("zebra"); + options = getAllByTestId("dropdown-option"); + expect(options[0]).toHaveClass("selected"); + + await component.$set({ value: undefined }); + expect(item.value).toBe(""); + options = getAllByTestId("dropdown-option"); + expect(options[0]).not.toHaveClass("selected"); + }); }); diff --git a/js/dropdown/shared/Dropdown.svelte b/js/dropdown/shared/Dropdown.svelte index e917b670e6..0dd7df6c14 100644 --- a/js/dropdown/shared/Dropdown.svelte +++ b/js/dropdown/shared/Dropdown.svelte @@ -105,12 +105,16 @@ function set_input_text(): void { if (value === undefined) { input_text = ""; + selected_index = null; } else if (choices_values.includes(value as string)) { input_text = choices_names[choices_values.indexOf(value as string)]; + selected_index = choices_values.indexOf(value as string); } else if (allow_custom_value) { input_text = value as string; + selected_index = null; } else { input_text = ""; + selected_index = null; } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8306033573..f38a285edb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,4 +1,4 @@ -lockfileVersion: '6.0' +lockfileVersion: '6.1' settings: autoInstallPeers: true