Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Combo box: prevent races between async suggestions and options rewrite (#6483)

Adam Rutkowski5b8d1e52a3f9
diff --git a/lib/plausible_web/live/components/combo_box.ex b/lib/plausible_web/live/components/combo_box.ex
index 37bf12667a..d450e6d222 100644
--- a/lib/plausible_web/live/components/combo_box.ex
+++ b/lib/plausible_web/live/components/combo_box.ex
@@ -54,7 +54,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
else
socket
end
- |> assign_suggestions(assigns[:suggestions])
+ |> assign_suggestions(assigns)
{:ok, socket}
end
@@ -325,7 +325,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
end
|> Enum.take(suggestions_limit(socket.assigns))
- {:noreply, assign(socket, %{suggestions: suggestions})}
+ {:noreply, assign(socket, %{suggestions: suggestions, searching?: input_len > 0})}
end
defp do_select(socket, submit_value, display_value) do
@@ -364,7 +364,17 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
end)
end
- defp assign_suggestions(socket, nil = _suggestions_from_update) do
+ defp assign_suggestions(socket, %{suggestions: _}), do: socket
+
+ # A background suggest_fun task delivered a result for a different key
+ # (namely, the initial options prefetch) - since the user has already
+ # searched, this stale result must not clobber the up-to-date suggestions.
+ defp assign_suggestions(%{assigns: %{searching?: true}} = socket, %{async_result?: true}),
+ do: socket
+
+ defp assign_suggestions(socket, _assigns), do: fill_suggestions_from_options(socket)
+
+ defp fill_suggestions_from_options(socket) do
suggestions =
socket.assigns
|> Map.get(:options, [])
@@ -373,10 +383,6 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
assign(socket, suggestions: suggestions)
end
- defp assign_suggestions(socket, _suggestions_from_update) do
- socket
- end
-
defp select_default(socket) do
case {socket.assigns[:selected], socket.assigns[:submit_value]} do
{{submit_value, display_value}, nil} ->
@@ -405,7 +411,8 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
__MODULE__,
Keyword.new([
{:id, id},
- {key_to_update, result}
+ {key_to_update, result},
+ {:async_result?, true}
])
)
end)
diff --git a/test/plausible_web/live/components/combo_box_test.exs b/test/plausible_web/live/components/combo_box_test.exs
index 051c86abd9..f3c8cf4fba 100644
--- a/test/plausible_web/live/components/combo_box_test.exs
+++ b/test/plausible_web/live/components/combo_box_test.exs
@@ -319,12 +319,12 @@ defmodule PlausibleWeb.Live.Components.ComboBoxTest do
defmodule SampleSuggest do
def suggest("", []) do
- :timer.sleep(500)
+ :timer.sleep(600)
[{1, "One"}, {2, "Two"}, {3, "Three"}]
end
def suggest("Echo me", _options) do
- :timer.sleep(500)
+ :timer.sleep(510)
[{1, "Echo me"}]
end
end