Hide creatable option when input matches suggestion (#3217)

This commit fixes a bug where the `Create "apple"` combo box option
would show up even when `apple` was in the suggestions list.
This commit is contained in:
Vini Brasil 2023-08-01 19:41:56 +01:00 committed by GitHub
parent 232bdd34a1
commit 06305cce95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View File

@ -164,7 +164,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
/>
<.option
:if={@creatable && String.length(@display_value) > 0}
:if={display_creatable_option?(assigns)}
idx={length(@suggestions)}
submit_value={@display_value}
display_value={@display_value}
@ -287,4 +287,13 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
defp suggestions_limit(assigns) do
Map.get(assigns, :suggestions_limit, @default_suggestions_limit)
end
defp display_creatable_option?(assigns) do
empty_input? = String.length(assigns.display_value) == 0
input_matches_suggestion? =
Enum.any?(assigns.suggestions, fn {suggestion, _} -> assigns.display_value == suggestion end)
assigns.creatable && not empty_input? && not input_matches_suggestion?
end
end

View File

@ -240,6 +240,14 @@ defmodule PlausibleWeb.Live.Components.ComboBoxTest do
~s(Create "my new option")
end
test "does not suggest creating value when input exact matches a suggestion", %{conn: conn} do
{:ok, lv, _html} = live_isolated(conn, CreatableView, session: %{})
assert lv
|> type_into_combo("test-creatable-component", "Option 1")
|> text_of_element("li#dropdown-test-creatable-component-option-0 a") == ~s(Option 1)
end
test "stores new value by clicking on the dropdown custom option", %{conn: conn} do
{:ok, lv, _html} = live_isolated(conn, CreatableView, session: %{})
type_into_combo(lv, "test-creatable-component", "my new option")