diff --git a/.changeset/sour-falcons-marry.md b/.changeset/sour-falcons-marry.md new file mode 100644 index 000000000000..06922ede7944 --- /dev/null +++ b/.changeset/sour-falcons-marry.md @@ -0,0 +1,6 @@ +--- +"@gradio/dropdown": patch +"gradio": patch +--- + +fix:Fixes dropdown breaking if a user types in invalid value and presses enter diff --git a/js/dropdown/dropdown.test.ts b/js/dropdown/dropdown.test.ts index 5938d8704989..cf896155779f 100644 --- a/js/dropdown/dropdown.test.ts +++ b/js/dropdown/dropdown.test.ts @@ -258,4 +258,62 @@ describe("Dropdown", () => { const options_new = getAllByTestId("dropdown-option"); expect(options_new).toHaveLength(3); }); + + test("setting a custom value when allow_custom_choice is false should revert to the first valid choice", 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 + } + ); + + const item: HTMLInputElement = getByLabelText( + "Dropdown" + ) as HTMLInputElement; + + await item.focus(); + await event.keyboard("pie"); + expect(item.value).toBe("applepie"); + await item.blur(); + expect(item.value).toBe("apple"); + }); + + test("setting a custom value when allow_custom_choice is true should keep the value", async () => { + const { getByLabelText, getAllByTestId, component } = await render( + Dropdown, + { + show_label: true, + loading_status, + value: "", + allow_custom_value: true, + label: "Dropdown", + choices: [ + ["apple", "apple"], + ["zebra", "zebra"], + ["pony", "pony"] + ], + filterable: true + } + ); + + const item: HTMLInputElement = getByLabelText( + "Dropdown" + ) as HTMLInputElement; + + await item.focus(); + await event.keyboard("pie"); + expect(item.value).toBe("applepie"); + await item.blur(); + expect(item.value).toBe("applepie"); + }); }); diff --git a/js/dropdown/shared/Dropdown.svelte b/js/dropdown/shared/Dropdown.svelte index 795d8506e38a..c770762eb5d7 100644 --- a/js/dropdown/shared/Dropdown.svelte +++ b/js/dropdown/shared/Dropdown.svelte @@ -74,7 +74,7 @@ dispatch("select", { index: selected_index, value: choices_values[selected_index], - selected: true, + selected: true }); } } @@ -97,7 +97,7 @@ filtered_indices = handle_filter(choices, input_text); old_choices = choices; old_input_text = input_text; - if (!allow_custom_value) { + if (!allow_custom_value && filtered_indices.length > 0) { active_index = filtered_indices[0]; } }