diff --git a/lib/bike_brigade_web/live/community_fridge_live/form_component.ex b/lib/bike_brigade_web/live/community_fridge_live/form_component.ex index e63130fd..3f821db7 100644 --- a/lib/bike_brigade_web/live/community_fridge_live/form_component.ex +++ b/lib/bike_brigade_web/live/community_fridge_live/form_component.ex @@ -1,7 +1,17 @@ defmodule BikeBrigadeWeb.CommunityFridgeLive.FormComponent do use BikeBrigadeWeb, :live_component - alias BikeBrigade.Locations + alias BikeBrigade.{Locations, MediaStorage} + + @impl true + def mount(socket) do + {:ok, + allow_upload(socket, :photo, + accept: ~w(.gif .png .jpg .jpeg), + max_entries: 1, + max_file_size: 10_000_000 + )} + end @impl true def update(%{community_fridge: community_fridge} = assigns, socket) do @@ -24,9 +34,35 @@ defmodule BikeBrigadeWeb.CommunityFridgeLive.FormComponent do end def handle_event("save", %{"community_fridge" => params}, socket) do + params = + case consume_uploaded_entries(socket, :photo, fn %{path: path}, + %{client_type: content_type} -> + {:ok, MediaStorage.upload_file!(path, content_type)} + end) do + [%{url: url}] -> Map.put(params, "photo", url) + [] -> Map.update(params, "photo", nil, &if(&1 == "", do: nil, else: &1)) + end + save_community_fridge(socket, socket.assigns.action, params) end + def handle_event("delete_photo", _params, socket) do + changeset = + socket.assigns.community_fridge + |> Locations.change_community_fridge(%{photo: nil}) + |> Map.put(:action, :validate) + + {:noreply, assign(socket, :changeset, changeset)} + end + + def handle_event("cancel_upload", %{"ref" => ref}, socket) do + {:noreply, cancel_upload(socket, :photo, ref)} + end + + defp error_to_string(:too_large), do: "Too large" + defp error_to_string(:too_many_files), do: "You have selected too many files" + defp error_to_string(:not_accepted), do: "You have selected an unacceptable file type" + defp save_community_fridge(socket, :edit, params) do case Locations.update_community_fridge(socket.assigns.community_fridge, params) do {:ok, _community_fridge} -> diff --git a/lib/bike_brigade_web/live/community_fridge_live/form_component.html.heex b/lib/bike_brigade_web/live/community_fridge_live/form_component.html.heex index 7741fd21..2c21fcfd 100644 --- a/lib/bike_brigade_web/live/community_fridge_live/form_component.html.heex +++ b/lib/bike_brigade_web/live/community_fridge_live/form_component.html.heex @@ -12,7 +12,63 @@ <.input type="textarea" field={f[:description]} label="Description" /> - <.input type="text" field={f[:photo]} label="Photo URL" /> +
or drag and drop
+PNG, JPG, GIF up to 10MB
++ {error_to_string(err)} +
+