18.5 KiB · text History e569b6d
defmodule CartosnapAppWeb.PhotoLive.Index do
  @moduledoc """
  The photo stream: everything you've uploaded, newest first, as a grid or a
  table. Thumbnails appear as the image pipeline finishes them.

  Select mode picks photos out of the grid (one by one, or all of them) to
  promote, unpromote, add to a trip or delete together.

  The filter bar narrows it by camera details (camera, lens, aperture,
  focal length, ISO, shutter; see `CartosnapApp.Photos.Facets`). Filters
  live in the URL (`/photos?camera=…&f=2.8`), so they can be linked to,
  and each choice narrows what the others offer.
  """
  use CartosnapAppWeb, :live_view

  import CartosnapAppWeb.PhotoComponents

  alias CartosnapApp.Photos
  alias CartosnapApp.Photos.Facets
  alias CartosnapApp.Trips

  @impl true
  def mount(_params, _session, socket) do
    if connected?(socket), do: Photos.subscribe(socket.assigns.current_scope)

    {:ok,
     socket
     |> assign(:page_title, "Photos")
     |> assign(:view_mode, :grid)
     |> assign(:promoted_only, false)
     |> assign(:selecting, false)
     |> assign(:selected, MapSet.new())
     |> assign(:trip_options, Trips.trip_options(socket.assigns.current_scope))
     |> assign(:bulk_trip_form, to_form(%{"trip_id" => ""}, as: :bulk))
     |> assign(:filters, [])}
  end

  @impl true
  def handle_params(params, _url, socket) do
    filters = Facets.from_params(params)

    {:noreply,
     socket
     |> assign(:filters, filters)
     |> assign(:filter_form, to_form(Facets.to_params(filters), as: :filter))
     |> assign(:selected, MapSet.new())
     |> load_photos()}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:photos}>
      <.header>
        Photos
        <:subtitle>
          {@count} {if @count == 1, do: "photo", else: "photos"}{if @promoted_only, do: " promoted"}{if @filters !=
                                                                                                          [],
                                                                                                        do:
                                                                                                          " matching"}
        </:subtitle>
        <:actions>
          <div class="flex items-center gap-2">
            <button
              :if={@count > 0}
              type="button"
              id="toggle-selecting"
              phx-click="toggle-selecting"
              aria-pressed={to_string(@selecting)}
              class={["btn btn-sm gap-1.5", if(@selecting, do: "btn-primary", else: "btn-ghost")]}
            >
              <.icon name="hero-check-circle-micro" class="size-4" />
              {if @selecting, do: "Done", else: "Select"}
            </button>
            <button
              type="button"
              id="toggle-promoted"
              phx-click="toggle-promoted"
              aria-pressed={to_string(@promoted_only)}
              class={["btn btn-sm gap-1.5", if(@promoted_only, do: "btn-warning", else: "btn-ghost")]}
            >
              <.icon
                name={if @promoted_only, do: "hero-star-solid", else: "hero-star"}
                class="size-4"
              /> Promoted
            </button>
            <div class="join" role="group" aria-label="Layout">
              <button
                type="button"
                id="layout-grid"
                phx-click="view-mode"
                phx-value-mode="grid"
                class={["btn btn-sm join-item", @view_mode == :grid && "btn-active"]}
                aria-label="Grid"
              >
                <.icon name="hero-squares-2x2-micro" class="size-4" />
              </button>
              <button
                type="button"
                id="layout-table"
                phx-click="view-mode"
                phx-value-mode="table"
                class={["btn btn-sm join-item", @view_mode == :table && "btn-active"]}
                aria-label="Table"
              >
                <.icon name="hero-list-bullet-micro" class="size-4" />
              </button>
            </div>
          </div>
        </:actions>
      </.header>

      <.form
        :if={@filters != [] or Enum.any?(@facets, fn {_key, values} -> values != [] end)}
        for={@filter_form}
        id="photo-filters"
        phx-change="filter"
        class="mb-4 flex flex-wrap items-center gap-2"
      >
        <.icon name="hero-camera-micro" class="size-4 text-base-content/50" />
        <%= for facet <- Facets.all(), options = facet_options(@facets, @filters, facet.key), options != [] do %>
          <select
            name={@filter_form[facet.param].name}
            id={"filter-#{facet.param}"}
            aria-label={facet.label}
            class={[
              "select select-sm w-auto max-w-56 transition",
              Keyword.has_key?(@filters, facet.key) && "select-primary font-medium"
            ]}
          >
            <option value="">{facet.label}: any</option>
            <option
              :for={{value, count} <- options}
              value={Facets.param_value(value)}
              selected={@filters[facet.key] == value}
            >
              {Facets.format(facet.key, value)} ({count})
            </option>
          </select>
        <% end %>
        <.link
          :if={@filters != []}
          patch={~p"/photos"}
          id="clear-filters"
          class="btn btn-ghost btn-sm gap-1"
        >
          <.icon name="hero-x-mark-micro" class="size-4" /> Clear
        </.link>
      </.form>

      <div
        :if={@count == 0 and @filters != []}
        id="photos-no-match"
        class="rounded-box border border-dashed border-base-300 py-16 text-center"
      >
        <.icon name="hero-funnel" class="mx-auto size-10 text-base-content/30" />
        <p class="mt-3 font-medium">No photos match those camera details</p>
        <.link patch={~p"/photos"} class="btn btn-ghost btn-sm mt-4">Clear the filters</.link>
      </div>

      <div
        :if={@count == 0 and @filters == []}
        id="photos-empty"
        class="rounded-box border border-dashed border-base-300 py-16 text-center"
      >
        <.icon name="hero-photo" class="mx-auto size-10 text-base-content/30" />
        <p class="mt-3 font-medium">
          {if @promoted_only, do: "No promoted photos yet", else: "No photos yet"}
        </p>
        <.link :if={!@promoted_only} navigate={~p"/upload"} class="btn btn-primary btn-sm mt-4">
          <.icon name="hero-arrow-up-tray-micro" class="size-4" /> Upload some
        </.link>
      </div>

      <div
        :if={@view_mode == :grid}
        id="photos"
        phx-update="stream"
        class="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6"
      >
        <.link
          :for={{dom_id, photo} <- @streams.photos}
          id={dom_id}
          navigate={!@selecting && ~p"/photos/#{photo}"}
          phx-click={@selecting && JS.push("select-photo", value: %{id: photo.id})}
          aria-pressed={@selecting && to_string(MapSet.member?(@selected, photo.id))}
          class={[
            "group relative block overflow-hidden rounded-box focus-visible:outline-2 focus-visible:outline-primary",
            @selecting && "cursor-pointer",
            MapSet.member?(@selected, photo.id) &&
              "ring-4 ring-primary ring-offset-2 ring-offset-base-100"
          ]}
        >
          <span
            :if={@selecting}
            class={[
              "absolute left-1.5 top-1.5 z-10 grid size-6 place-items-center rounded-full border-2 shadow transition",
              if(MapSet.member?(@selected, photo.id),
                do: "border-primary bg-primary text-primary-content",
                else: "border-white/90 bg-black/30"
              )
            ]}
          >
            <.icon :if={MapSet.member?(@selected, photo.id)} name="hero-check-micro" class="size-4" />
          </span>
          <.photo_image
            id={"#{dom_id}-img"}
            photo={photo}
            class="aspect-[4/3] transition duration-300 group-hover:scale-[1.04]"
          />
          <div class="pointer-events-none absolute inset-x-0 bottom-0 translate-y-1 bg-gradient-to-t from-black/70 to-transparent p-2 pt-6 text-xs text-white opacity-0 transition duration-200 group-hover:translate-y-0 group-hover:opacity-100">
            <div class="truncate font-medium">{CartosnapApp.Photos.Photo.title(photo)}</div>
            <div class="opacity-80">{photo_date(photo)}</div>
          </div>
          <.promoted_badge photo={photo} class="absolute right-1.5 top-1.5" />
          <.shape_badge photo={photo} class="absolute bottom-1.5 right-1.5" />
          <span
            :if={!@selecting and CartosnapApp.Photos.Photo.lat_lon(photo)}
            class="absolute left-1.5 top-1.5 grid size-6 place-items-center rounded-full bg-black/40 text-white opacity-0 backdrop-blur transition group-hover:opacity-100"
            title="Has a location"
          >
            <.icon name="hero-map-pin-micro" class="size-3.5" />
          </span>
        </.link>
      </div>

      <.table
        :if={@view_mode == :table}
        id="photos"
        rows={@streams.photos}
        row_click={fn {_id, photo} -> JS.navigate(~p"/photos/#{photo}") end}
      >
        <:col :let={{id, photo}} label="">
          <.photo_image id={"#{id}-img"} photo={photo} class="h-12 w-16 rounded" />
        </:col>
        <:col :let={{_id, photo}} label="Name">{CartosnapApp.Photos.Photo.title(photo)}</:col>
        <:col :let={{_id, photo}} label="Taken">{photo_date(photo)}</:col>
        <:col :let={{_id, photo}} label="Where">
          <.icon
            :if={CartosnapApp.Photos.Photo.lat_lon(photo)}
            name="hero-map-pin-micro"
            class="size-4 text-primary"
          />
        </:col>
        <:action :let={{id, photo}}>
          <button
            type="button"
            id={"#{id}-promote"}
            phx-click="toggle-photo-promoted"
            phx-value-id={photo.id}
            class={["btn btn-xs", if(photo.promoted, do: "btn-warning", else: "btn-ghost")]}
          >
            <.icon
              name={if photo.promoted, do: "hero-star-solid", else: "hero-star"}
              class="size-3.5"
            />
            {if photo.promoted, do: "Promoted", else: "Promote"}
          </button>
        </:action>
        <:action :let={{id, photo}}>
          <.link
            id={"#{id}-delete"}
            phx-click={JS.push("delete", value: %{id: photo.id}) |> hide("##{id}")}
            data-confirm="Delete this photo? Its files go too."
            class="text-error"
          >
            Delete
          </.link>
        </:action>
      </.table>

      <div
        :if={@selecting}
        id="bulk-bar"
        class="sticky bottom-4 z-30 mx-auto flex w-fit max-w-full flex-wrap items-center gap-2 rounded-box border border-base-300 bg-base-100/95 px-3 py-2 shadow-xl backdrop-blur"
      >
        <span class="px-1 text-sm font-semibold" id="bulk-count">
          {MapSet.size(@selected)} selected
        </span>
        <button type="button" id="bulk-select-all" phx-click="select-all" class="btn btn-ghost btn-xs">
          All
        </button>
        <button
          type="button"
          id="bulk-select-none"
          phx-click="select-none"
          class="btn btn-ghost btn-xs"
        >
          None
        </button>
        <span class="mx-1 h-5 w-px bg-base-300"></span>
        <button
          type="button"
          id="bulk-promote"
          phx-click="bulk-promote"
          phx-value-to="true"
          disabled={MapSet.size(@selected) == 0}
          class="btn btn-warning btn-soft btn-sm gap-1"
        >
          <.icon name="hero-star-solid" class="size-4" /> Promote
        </button>
        <button
          type="button"
          id="bulk-unpromote"
          phx-click="bulk-promote"
          phx-value-to="false"
          disabled={MapSet.size(@selected) == 0}
          class="btn btn-ghost btn-sm gap-1"
        >
          <.icon name="hero-star" class="size-4" /> Unpromote
        </button>
        <.form
          :if={@trip_options != []}
          for={@bulk_trip_form}
          id="bulk-trip-form"
          phx-change="bulk-add-to-trip"
          class="w-48"
        >
          <select
            name={@bulk_trip_form[:trip_id].name}
            id={@bulk_trip_form[:trip_id].id}
            class="select select-sm"
            disabled={MapSet.size(@selected) == 0}
            aria-label="Add the selected photos to a trip"
          >
            <option value="">Add to trip…</option>
            {Phoenix.HTML.Form.options_for_select(@trip_options, "")}
          </select>
        </.form>
        <button
          type="button"
          id="bulk-delete"
          phx-click="bulk-delete"
          disabled={MapSet.size(@selected) == 0}
          data-confirm={"Delete #{MapSet.size(@selected)} photos? Their files go too."}
          class="btn btn-ghost btn-sm text-error"
        >
          <.icon name="hero-trash-micro" class="size-4" /> Delete
        </button>
      </div>
    </Layouts.app>
    """
  end

  @impl true
  def handle_event("filter", %{"filter" => params}, socket) do
    params = params |> Facets.from_params() |> Facets.to_params()
    {:noreply, push_patch(socket, to: ~p"/photos?#{params}")}
  end

  def handle_event("view-mode", %{"mode" => mode}, socket) when mode in ~w(grid table) do
    {:noreply,
     socket
     |> assign(:view_mode, String.to_existing_atom(mode))
     |> load_photos()}
  end

  def handle_event("toggle-selecting", _params, socket) do
    selecting = !socket.assigns.selecting

    {:noreply,
     socket
     |> assign(:selecting, selecting)
     |> assign(:selected, MapSet.new())
     # Selecting happens in the grid.
     |> assign(:view_mode, if(selecting, do: :grid, else: socket.assigns.view_mode))
     |> load_photos()}
  end

  def handle_event("select-photo", %{"id" => id}, socket) do
    selected = socket.assigns.selected

    selected =
      if MapSet.member?(selected, id),
        do: MapSet.delete(selected, id),
        else: MapSet.put(selected, id)

    photo = Photos.get_photo!(socket.assigns.current_scope, id)
    # Re-inserted so the tile shows its new state.
    {:noreply, socket |> assign(:selected, selected) |> stream_insert(:photos, photo)}
  end

  def handle_event("select-all", _params, socket) do
    {:noreply, socket |> assign(:selected, MapSet.new(socket.assigns.ids)) |> load_photos()}
  end

  def handle_event("select-none", _params, socket) do
    {:noreply, socket |> assign(:selected, MapSet.new()) |> load_photos()}
  end

  def handle_event("bulk-promote", %{"to" => to}, socket) do
    promoted? = to == "true"
    ids = MapSet.to_list(socket.assigns.selected)
    {:ok, count} = Photos.set_promoted(socket.assigns.current_scope, ids, promoted?)
    verb = if promoted?, do: "Promoted", else: "Unpromoted"
    {:noreply, socket |> put_flash(:info, "#{verb} #{plural(count)}") |> load_photos()}
  end

  def handle_event("bulk-add-to-trip", %{"bulk" => %{"trip_id" => trip_id}}, socket)
      when trip_id != "" do
    scope = socket.assigns.current_scope
    ids = MapSet.to_list(socket.assigns.selected)
    {:ok, count} = Trips.add_photos(scope, trip_id, ids)

    name =
      Enum.find_value(socket.assigns.trip_options, fn {name, id} -> id == trip_id && name end)

    message =
      if count == 0,
        do: "Those photos were already in #{name}",
        else: "Added #{plural(count)} to #{name}"

    {:noreply,
     socket
     |> put_flash(:info, message)
     |> assign(:bulk_trip_form, to_form(%{"trip_id" => ""}, as: :bulk))}
  end

  def handle_event("bulk-add-to-trip", _params, socket), do: {:noreply, socket}

  def handle_event("bulk-delete", _params, socket) do
    ids = MapSet.to_list(socket.assigns.selected)
    {:ok, count} = Photos.delete_photos(socket.assigns.current_scope, ids)

    {:noreply,
     socket
     |> assign(:selected, MapSet.new())
     |> put_flash(:info, "Deleted #{plural(count)}")
     |> load_photos()}
  end

  def handle_event("toggle-promoted", _params, socket) do
    {:noreply,
     socket
     |> update(:promoted_only, &(!&1))
     |> load_photos()}
  end

  def handle_event("toggle-photo-promoted", %{"id" => id}, socket) do
    scope = socket.assigns.current_scope
    photo = Photos.get_photo!(scope, id)
    {:ok, _photo} = Photos.toggle_promoted(scope, photo)
    # The broadcast brings the change back through handle_info.
    {:noreply, socket}
  end

  def handle_event("delete", %{"id" => id}, socket) do
    scope = socket.assigns.current_scope
    photo = Photos.get_photo!(scope, id)
    {:ok, _} = Photos.delete_photo(scope, photo)
    {:noreply, socket}
  end

  @impl true
  def handle_info({:photo_created, photo}, socket) do
    socket = load_facets(socket)

    if socket.assigns.promoted_only or not matches?(photo, socket.assigns.filters) do
      {:noreply, socket}
    else
      {:noreply,
       socket
       |> stream_insert(:photos, photo, at: 0)
       |> update(:count, &(&1 + 1))
       |> update(:ids, &[photo.id | &1])}
    end
  end

  def handle_info({:photo_updated, photo}, socket) do
    if socket.assigns.promoted_only and not photo.promoted do
      {:noreply, socket |> stream_delete(:photos, photo) |> update(:count, &max(&1 - 1, 0))}
    else
      {:noreply, stream_insert(socket, :photos, photo)}
    end
  end

  def handle_info({:photo_deleted, photo}, socket) do
    {:noreply,
     socket
     |> stream_delete(:photos, photo)
     |> update(:count, &max(&1 - 1, 0))
     |> update(:selected, &MapSet.delete(&1, photo.id))
     |> update(:ids, &List.delete(&1, photo.id))
     |> load_facets()}
  end

  defp list_opts(socket),
    do: [promoted: socket.assigns.promoted_only, filters: socket.assigns.filters]

  defp load_photos(socket) do
    photos = Photos.list_photos(socket.assigns.current_scope, list_opts(socket))

    socket
    |> assign(:count, length(photos))
    |> assign(:ids, Enum.map(photos, & &1.id))
    |> stream(:photos, photos, reset: true)
    |> load_facets()
  end

  defp load_facets(socket) do
    assign(socket, :facets, Photos.facet_counts(socket.assigns.current_scope, list_opts(socket)))
  end

  defp matches?(photo, filters),
    do: Enum.all?(filters, fn {key, value} -> Map.get(photo, key) == value end)

  # A facet's choices, keeping a chosen value on offer even when nothing
  # matches it any more.
  defp facet_options(facets, filters, key) do
    options = Map.get(facets, key, [])

    case filters[key] do
      nil -> options
      value -> if List.keymember?(options, value, 0), do: options, else: [{value, 0} | options]
    end
  end

  defp plural(1), do: "1 photo"
  defp plural(n), do: "#{n} photos"
end