page_live.ex 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. defmodule ToyWeb.PageLive do
  2. use ToyWeb, :live_view
  3. @impl true
  4. def mount(_params, _session, socket) do
  5. {:ok, assign(socket, query: "", results: %{})}
  6. end
  7. @impl true
  8. def handle_event("suggest", %{"q" => query}, socket) do
  9. {:noreply, assign(socket, results: search(query), query: query)}
  10. end
  11. @impl true
  12. def handle_event("search", %{"q" => query}, socket) do
  13. case search(query) do
  14. %{^query => vsn} ->
  15. {:noreply, redirect(socket, external: "https://hexdocs.pm/#{query}/#{vsn}")}
  16. _ ->
  17. {:noreply,
  18. socket
  19. |> put_flash(:error, "No dependencies found matching \"#{query}\"")
  20. |> assign(results: %{}, query: query)}
  21. end
  22. end
  23. defp search(query) do
  24. if not ToyWeb.Endpoint.config(:code_reloader) do
  25. raise "action disabled when not in development"
  26. end
  27. for {app, desc, vsn} <- Application.started_applications(),
  28. app = to_string(app),
  29. String.starts_with?(app, query) and not List.starts_with?(desc, ~c"ERTS"),
  30. into: %{},
  31. do: {app, vsn}
  32. end
  33. end