42.5 KiB · text History e569b6d
defmodule CartosnapAppWeb.PhotoLive.Show do
  @moduledoc """
  One photo: the image (or its details, or its EXIF), where it was taken,
  and the trips it's in.

  Its owner renames, promotes, pins and files it here. Anyone who shares a
  trip with it can look (`Photos.get_viewable_photo!/2`), and the trip's
  owner can take it out of their trip, but nothing else.

  Newer/older step through your own photos (`?in=promoted`: just the
  promoted ones), or through everyone's in one trip (`?trip=<id>`).
  """
  use CartosnapAppWeb, :live_view

  import CartosnapAppWeb.PhotoComponents
  import CartosnapAppWeb.Components.PhotoMap

  alias CartosnapApp.Geocoder
  alias CartosnapApp.Geocoder.Place
  alias CartosnapApp.Photos
  alias CartosnapApp.Photos.Facets
  alias CartosnapApp.Photos.Photo
  alias CartosnapApp.Trips
  alias CartosnapApp.Trips.Trip
  alias CartosnapAppWeb.Components.PhotoMap

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

    {:ok,
     socket
     |> assign(:tab, :image)
     |> assign(:editing_name, false)
     |> assign(:shot_open, false)
     |> assign(:flat, false)
     |> assign(:subscribed, MapSet.new())
     |> reset_locating()
     |> assign(:trip_options, Trips.trip_options(socket.assigns.current_scope))}
  end

  @impl true
  def handle_params(%{"id" => id} = params, _url, socket) do
    scope = socket.assigns.current_scope
    photo = Photos.get_viewable_photo!(scope, id)
    trips = Trips.photo_trips(scope, photo)
    owner? = photo.user == scope.user.id

    {:noreply,
     socket
     |> assign(:owner?, owner?)
     |> assign(:within, within(params, trips, owner?))
     |> assign(:editing_name, false)
     |> reset_locating()
     |> subscribe_trips(trips)
     |> assign_photo(photo, trips)}
  end

  # Someone else's photo changes on its trips' topics, not on ours.
  defp subscribe_trips(socket, trips) do
    if connected?(socket) do
      Enum.reduce(trips, socket, fn trip, acc ->
        if MapSet.member?(acc.assigns.subscribed, trip.id) do
          acc
        else
          Trips.subscribe(trip)
          update(acc, :subscribed, &MapSet.put(&1, trip.id))
        end
      end)
    else
      socket
    end
  end

  # Pinning a photo by hand: `locating` while the search is open,
  # `pending` (`%{lat, lon, name}`) once a place or a spot on the map has
  # been picked but not yet saved.
  defp reset_locating(socket) do
    socket
    |> assign(:locating, false)
    |> assign(:pending, nil)
    |> assign(:place_query, "")
    |> assign(:place_form, to_form(%{"q" => ""}, as: :place))
    |> assign(:places, [])
    |> assign(:suggestions, [])
    |> assign(:searching, false)
    |> assign(:search_failed, false)
  end

  # Places from this photo's trips (or the owner's own photos), offered
  # before searching: the photos just before and after it, then the named
  # places already used. Picked like a search result.
  defp suggestions(socket) do
    %{current_scope: scope, photo: photo, trips: trips} = socket.assigns
    %{before: before, after: next, places: places} = Photos.place_suggestions(scope, photo, trips)

    neighbours =
      [{"before", before}, {"after", next}]
      |> Enum.reject(fn {_id, place} -> is_nil(place) end)
      |> Enum.uniq_by(fn {_id, place} -> {place.lat, place.lon} end)
      |> Enum.map(fn {id, place} ->
        Map.merge(place, %{id: id, hint: neighbour_hint(id, place, photo)})
      end)

    taken = MapSet.new(neighbours, & &1.name)

    named =
      places
      |> Enum.reject(&MapSet.member?(taken, &1.name))
      |> Enum.with_index(fn place, i -> Map.merge(place, %{id: "used-#{i}", hint: nil}) end)

    neighbours ++ named
  end

  defp suggestions_from([]), do: "From your photos"
  defp suggestions_from([trip]), do: "From #{trip.name}"
  defp suggestions_from(_trips), do: "From its trips"

  defp neighbour_hint(side, place, photo) do
    gap = place.date && photo.date && abs(DateTime.diff(photo.date, place.date, :minute))
    label = if side == "before", do: "Photo before", else: "Photo after"

    if gap,
      do: "#{label} · #{gap_text(gap)} #{if side == "before", do: "earlier", else: "later"}",
      else: label
  end

  defp gap_text(minutes) when minutes < 1, do: "moments"
  defp gap_text(minutes) when minutes < 60, do: "#{minutes} min"
  defp gap_text(minutes) when minutes < 48 * 60, do: "#{div(minutes, 60)} h"
  defp gap_text(minutes), do: "#{div(minutes, 60 * 24)} days"

  # While searching, only the used places whose names match.
  defp shown_suggestions(suggestions, query) do
    case String.trim(query) |> String.downcase() do
      "" ->
        suggestions

      q ->
        Enum.filter(suggestions, &(&1.name && String.contains?(String.downcase(&1.name), q)))
    end
  end

  # The map shows the pending pin while one is being chosen, else the photo's own.
  defp assign_points(socket) do
    photo = socket.assigns.photo

    points =
      case socket.assigns.pending do
        %{lat: lat, lon: lon} -> PhotoMap.points([%{photo | geo_point: Photo.point(lat, lon)}])
        nil -> PhotoMap.points([photo])
      end

    assign(socket, :points, points)
  end

  # What newer/older step through: a trip named in `?trip=` (one this photo
  # is in and the viewer can see), else the owner's own photos (all, or
  # promoted). Someone else's photo steps through its first trip.
  defp within(params, trips, owner?) do
    trip = params["trip"] && Enum.find(trips, &(&1.id == params["trip"]))

    cond do
      trip -> trip
      owner? and params["in"] == "promoted" -> :promoted
      owner? -> :all
      true -> List.first(trips)
    end
  end

  defp assign_photo(socket, photo, trips \\ nil) do
    scope = socket.assigns.current_scope
    trips = trips || Trips.photo_trips(scope, photo)
    within = socket.assigns.within
    # The trip being stepped through may have been taken away.
    within =
      if match?(%Trip{}, within) and not Enum.any?(trips, &(&1.id == within.id)),
        do: if(socket.assigns.owner?, do: :all, else: List.first(trips)),
        else: within

    socket
    |> assign(:page_title, Photo.title(photo))
    |> assign(:photo, photo)
    |> assign(:trips, trips)
    |> assign(:within, within)
    |> assign(:shared_by, if(socket.assigns.owner?, do: nil, else: owner_name(photo)))
    |> assign(
      :neighbors,
      if(within, do: Photos.neighbors(scope, photo, within), else: %{newer: nil, older: nil})
    )
    |> assign_points()
    |> assign(:name_form, to_form(Photos.change_photo(photo)))
    |> assign(:add_trip_form, to_form(%{"trip_id" => ""}, as: :filing))
  end

  defp owner_name(%Photo{user: user_id}),
    do: CartosnapApp.Accounts.display_names([user_id])[user_id] || "someone"

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:photos} wide>
      <div id="photo-view" phx-window-keydown="key" class="flex flex-col lg:h-[calc(100dvh-4rem)]">
        <div class="flex flex-wrap items-center justify-between gap-2 border-b border-base-300 px-4 py-2 sm:px-6">
          <div class="flex items-center gap-2">
            <%= case @within do %>
              <% %Trip{} = trip -> %>
                <.link navigate={~p"/trips/#{trip}"} class="btn btn-ghost btn-sm" id="back-to-photos">
                  <.icon name="hero-arrow-left-micro" class="size-4" /> {trip.name}
                </.link>
              <% _ -> %>
                <.link navigate={~p"/photos"} class="btn btn-ghost btn-sm" id="back-to-photos">
                  <.icon name="hero-arrow-left-micro" class="size-4" /> Photos
                </.link>
            <% end %>
            <div role="tablist" class="tabs tabs-box tabs-sm" id="photo-tabs">
              <button
                :for={{tab, label} <- [image: "Photo", details: "Details", exif: "EXIF"]}
                type="button"
                role="tab"
                id={"tab-#{tab}"}
                aria-selected={to_string(@tab == tab)}
                phx-click="tab"
                phx-value-tab={tab}
                class={["tab", @tab == tab && "tab-active"]}
              >
                {label}
              </button>
            </div>
          </div>

          <div class="flex items-center gap-2" id="photo-stepper">
            <div class="join" role="group" aria-label="Step through">
              <.step_link
                id="photo-newer"
                to={@neighbors.newer}
                within={@within}
                label="Newer"
                icon="hero-chevron-left-micro"
              />
              <.step_link
                id="photo-older"
                to={@neighbors.older}
                within={@within}
                label="Older"
                icon="hero-chevron-right-micro"
                trailing
              />
            </div>
            <div class="join" role="group" aria-label="Step within">
              <.link
                :for={{value, label} <- within_options(@trips, @owner?)}
                patch={photo_path(@photo, value)}
                id={"within-#{within_id(value)}"}
                class={[
                  "btn btn-xs join-item max-w-[14ch] truncate",
                  within_value(@within) == value && "btn-active"
                ]}
              >
                {label}
              </.link>
            </div>
          </div>
        </div>

        <div class="grid min-h-0 flex-1 lg:grid-cols-[minmax(0,1fr)_22rem]">
          <section class="relative flex min-h-[65dvh] min-w-0 flex-col bg-base-300/40 lg:min-h-0">
            <div :if={@tab == :image} id="photo-image" class="group relative min-h-0 flex-1">
              <div class="absolute inset-0">
                <%= if immersive?(@photo) and not @flat do %>
                  <.photo_stage id="photo-stage" photo={@photo} class="h-full w-full" />
                <% else %>
                  <.photo_image
                    id={"photo-#{@photo.id}"}
                    photo={@photo}
                    variant={:full}
                    class="h-full w-full"
                    img_class="object-contain p-2 drop-shadow-xl sm:p-4"
                  />
                <% end %>
              </div>
              <button
                :if={immersive?(@photo)}
                type="button"
                id="toggle-flat"
                phx-click="toggle-flat"
                aria-pressed={to_string(@flat)}
                class="btn btn-xs absolute right-3 top-3 z-10 gap-1 rounded-full border-0 bg-black/45 text-white backdrop-blur hover:bg-black/65"
              >
                <%= if @flat do %>
                  <.icon
                    name={
                      if Photo.sphere?(@photo),
                        do: "hero-globe-alt-micro",
                        else: "hero-arrows-right-left-micro"
                    }
                    class="size-3.5"
                  />
                  {if Photo.sphere?(@photo), do: "View in 360°", else: "Pan across"}
                <% else %>
                  <.icon name="hero-photo-micro" class="size-3.5" /> Flat
                <% end %>
              </button>
              <.link
                :if={@neighbors.newer}
                patch={photo_path(@neighbors.newer, within_value(@within))}
                id="stage-newer"
                aria-label="Newer photo"
                class="btn btn-circle absolute left-3 top-1/2 -translate-y-1/2 border-0 bg-base-100/70 opacity-0 shadow-md backdrop-blur transition group-hover:opacity-100 focus-visible:opacity-100"
              >
                <.icon name="hero-chevron-left" class="size-5" />
              </.link>
              <.link
                :if={@neighbors.older}
                patch={photo_path(@neighbors.older, within_value(@within))}
                id="stage-older"
                aria-label="Older photo"
                class="btn btn-circle absolute right-3 top-1/2 -translate-y-1/2 border-0 bg-base-100/70 opacity-0 shadow-md backdrop-blur transition group-hover:opacity-100 focus-visible:opacity-100"
              >
                <.icon name="hero-chevron-right" class="size-5" />
              </.link>
            </div>

            <div
              :if={@tab == :details}
              id="photo-details"
              class="m-4 overflow-y-auto rounded-box border border-base-300 bg-base-100 sm:m-6"
            >
              <.list>
                <:item title="Name">{Photo.title(@photo)}</:item>
                <:item title="Original file">{@photo.filename}</:item>
                <:item title="Taken">
                  {@photo.date && Calendar.strftime(@photo.date, "%A, %B %-d, %Y at %H:%M")}
                </:item>
                <:item title="Where">
                  <%= case Photo.lat_lon(@photo) do %>
                    <% {lat, lon} -> %>
                      <div :if={@photo.place_name}>{@photo.place_name}</div>
                      <span class="font-mono text-sm">{format_coords(lat, lon)}</span>
                    <% nil -> %>
                      <span class="text-base-content/60">No location recorded</span>
                  <% end %>
                </:item>
                <:item title="Processed">
                  {if Photo.processed?(@photo), do: "Yes", else: "Still resizing…"}
                </:item>
                <:item title="Blurhash"><code class="text-xs">{@photo.blurhash}</code></:item>
              </.list>
            </div>

            <div :if={@tab == :exif} id="photo-exif" class="space-y-4 overflow-y-auto p-4 sm:p-6">
              <p
                :if={@photo.exif in [nil, %{}]}
                class="rounded-box border border-dashed border-base-300 p-8 text-center text-base-content/60"
              >
                This photo has no EXIF data.
              </p>
              <div
                :for={{group, values} <- exif_groups(@photo.exif)}
                class="overflow-hidden rounded-box border border-base-300"
              >
                <h3 class="bg-base-200 px-4 py-2 text-xs font-semibold uppercase tracking-wider">
                  {group}
                </h3>
                <table class="table table-sm table-zebra">
                  <tbody>
                    <tr :for={{key, value} <- values}>
                      <td class="w-1/3 font-mono text-xs">{key}</td>
                      <td class="break-all font-mono text-xs">
                        <%= case @owner? && exif_facet(@photo, group, key) do %>
                          <% facet when is_atom(facet) and facet not in [nil, false] -> %>
                            <.link
                              navigate={~p"/photos?#{shot_filter(@photo, facet)}"}
                              id={"exif-#{group}-#{key}"}
                              class="group/exif inline-flex items-center gap-1 text-primary hover:underline"
                              title={"Your photos with this #{Facets.get(facet).label |> String.downcase()}"}
                            >
                              {format_exif(value)}
                              <.icon
                                name="hero-funnel-micro"
                                class="size-3 opacity-0 transition group-hover/exif:opacity-70"
                              />
                            </.link>
                          <% _ -> %>
                            {format_exif(value)}
                        <% end %>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </section>

          <aside class="space-y-5 overflow-y-auto border-t border-base-300 bg-base-100 p-4 sm:p-6 lg:border-l lg:border-t-0">
            <div class="space-y-1">
              <%= cond do %>
                <% not @owner? -> %>
                  <h1 class="text-2xl font-bold leading-tight tracking-tight">
                    {Photo.title(@photo)}
                  </h1>
                  <p id="shared-by" class="text-sm text-base-content/60">Shared by {@shared_by}</p>
                <% @editing_name -> %>
                  <.form
                    for={@name_form}
                    id="photo-name-form"
                    phx-submit="save-name"
                    phx-change="validate-name"
                  >
                    <.input
                      field={@name_form[:name]}
                      type="text"
                      placeholder={@photo.filename}
                      phx-mounted={JS.focus()}
                    />
                    <div class="flex gap-2">
                      <button
                        type="submit"
                        class="btn btn-primary btn-sm"
                        phx-disable-with="Saving…"
                      >Save</button>
                      <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel-name">Cancel</button>
                    </div>
                  </.form>
                <% true -> %>
                  <button
                    type="button"
                    id="edit-name"
                    phx-click="edit-name"
                    class="group flex w-full items-start gap-2 text-left"
                    title="Rename"
                  >
                    <h1 class="text-2xl font-bold leading-tight tracking-tight">
                      {Photo.title(@photo)}
                    </h1>
                    <.icon
                      name="hero-pencil-square-micro"
                      class="mt-2 size-4 shrink-0 opacity-0 transition group-hover:opacity-60"
                    />
                  </button>
              <% end %>
              <p class="text-sm text-base-content/60">{photo_date(@photo)}</p>
            </div>

            <div class="flex flex-wrap gap-2">
              <button
                :if={@owner?}
                type="button"
                id="toggle-promoted"
                phx-click="toggle-promoted"
                class={[
                  "btn btn-sm gap-1.5",
                  if(@photo.promoted, do: "btn-warning", else: "btn-outline")
                ]}
              >
                <.icon
                  name={if @photo.promoted, do: "hero-star-solid", else: "hero-star"}
                  class="size-4"
                />
                {if @photo.promoted, do: "Promoted", else: "Promote"}
              </button>
              <a
                :if={@photo.url_original}
                href={src(@photo, :original)}
                target="_blank"
                rel="noopener"
                class="btn btn-ghost btn-sm"
                id="open-original"
              >
                <.icon name="hero-arrow-top-right-on-square-micro" class="size-4" /> Original
              </a>
              <button
                :if={@owner?}
                type="button"
                id="delete-photo"
                phx-click="delete"
                data-confirm="Delete this photo? Its files go too."
                class="btn btn-ghost btn-sm text-error"
              >
                <.icon name="hero-trash-micro" class="size-4" /> Delete
              </button>
            </div>

            <section :if={shot_details(@photo) != []} id="photo-shot" class="text-xs">
              <button
                type="button"
                id="toggle-shot"
                phx-click="toggle-shot"
                aria-expanded={to_string(@shot_open)}
                aria-controls="photo-shot-details"
                class="group flex w-full items-center gap-1.5 text-left"
              >
                <.icon
                  name="hero-chevron-right-micro"
                  class={[
                    "size-3.5 shrink-0 text-base-content/50 transition-transform",
                    @shot_open && "rotate-90"
                  ]}
                />
                <span class="font-semibold uppercase tracking-wider text-base-content/60 group-hover:text-base-content">
                  Camera
                </span>
                <span :if={!@shot_open} class="min-w-0 truncate text-base-content/50">
                  {shot_summary(@photo)}
                </span>
              </button>
              <dl
                :if={@shot_open}
                id="photo-shot-details"
                class="mt-2 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 pl-5"
              >
                <%= for {key, value} <- shot_details(@photo) do %>
                  <dt class="text-base-content/50">{Facets.get(key).label}</dt>
                  <dd id={"photo-shot-#{key}"} class="break-words">
                    <.link
                      :if={@owner?}
                      navigate={~p"/photos?#{shot_filter(@photo, key)}"}
                      class="link link-hover decoration-base-content/30"
                      title={"Your photos with this #{Facets.get(key).label |> String.downcase()}"}
                    >
                      {Facets.format(key, value)}
                    </.link>
                    <span :if={!@owner?}>{Facets.format(key, value)}</span>
                  </dd>
                <% end %>
              </dl>
            </section>

            <section id="photo-trips" class="space-y-2">
              <h2 class="text-xs font-semibold uppercase tracking-wider text-base-content/60">
                Trips
              </h2>
              <ul :if={@trips != []} class="flex flex-wrap gap-1.5">
                <li
                  :for={trip <- @trips}
                  id={"photo-trip-#{trip.id}"}
                  class="badge badge-lg gap-1 pr-1"
                >
                  <.link navigate={~p"/trips/#{trip}"} class="hover:underline">{trip.name}</.link>
                  <button
                    :if={@owner? or Trips.owner?(@current_scope, trip)}
                    type="button"
                    phx-click="remove-from-trip"
                    phx-value-id={trip.id}
                    aria-label={"Take out of #{trip.name}"}
                    class="btn btn-ghost btn-xs btn-circle"
                  >
                    <.icon name="hero-x-mark-micro" class="size-3.5" />
                  </button>
                </li>
              </ul>
              <p :if={@trips == [] and not @owner?} class="text-sm text-base-content/60">
                Not in any trip you share.
              </p>
              <%= if @owner? do %>
                <.form
                  :if={add_trip_options(@trip_options, @trips) != []}
                  for={@add_trip_form}
                  id="photo-trip-form"
                  phx-change="add-to-trip"
                >
                  <.input
                    field={@add_trip_form[:trip_id]}
                    type="select"
                    prompt={if @trips == [], do: "Add to a trip…", else: "Add to another trip…"}
                    options={add_trip_options(@trip_options, @trips)}
                  />
                </.form>
                <p :if={@trip_options == []} class="text-xs text-base-content/60">
                  <.link navigate={~p"/trips/new"} class="link">Make a trip</.link>
                  to file photos under it.
                </p>
              <% end %>
            </section>

            <.location_panel
              editable={@owner?}
              photo={@photo}
              points={@points}
              locating={@locating}
              pending={@pending}
              place_form={@place_form}
              place_query={@place_query}
              places={@places}
              suggestions={@suggestions}
              suggestions_from={suggestions_from(@trips)}
              searching={@searching}
              search_failed={@search_failed}
            />
          </aside>
        </div>
      </div>
    </Layouts.app>
    """
  end

  attr :editable, :boolean, default: true
  attr :photo, Photo, required: true
  attr :points, :list, required: true
  attr :locating, :boolean, required: true
  attr :pending, :map, default: nil
  attr :place_form, :any, required: true
  attr :place_query, :string, required: true
  attr :places, :list, required: true
  attr :suggestions, :list, default: []
  attr :suggestions_from, :string, default: nil
  attr :searching, :boolean, required: true
  attr :search_failed, :boolean, required: true

  defp location_panel(assigns) do
    assigns =
      assigns
      |> assign(:position, Photo.lat_lon(assigns.photo))
      |> assign(:shown_suggestions, shown_suggestions(assigns.suggestions, assigns.place_query))

    ~H"""
    <section id="photo-location" class="space-y-2">
      <div class="flex items-center justify-between gap-2">
        <h2 class="text-xs font-semibold uppercase tracking-wider text-base-content/60">Where</h2>
        <div :if={@editable and !@locating} class="flex gap-1">
          <button type="button" id="locate-photo" phx-click="locate" class="btn btn-ghost btn-xs">
            <.icon name="hero-map-pin-micro" class="size-3.5" />
            {if @position, do: "Change", else: "Set location"}
          </button>
          <button
            :if={@position}
            type="button"
            id="remove-location"
            phx-click="remove-location"
            data-confirm="Take this photo off the map?"
            class="btn btn-ghost btn-xs text-error"
          >
            Remove
          </button>
        </div>
      </div>

      <%= if @locating do %>
        <div
          id="locate-panel"
          class="space-y-2 rounded-box border border-primary/40 bg-base-200/60 p-3"
        >
          <.form
            for={@place_form}
            id="place-search-form"
            phx-change="search-place"
            phx-submit="search-place"
          >
            <label class="input input-sm w-full">
              <.icon name="hero-magnifying-glass-micro" class="size-4 opacity-60" />
              <input
                type="search"
                name={@place_form[:q].name}
                id={@place_form[:q].id}
                value={@place_form[:q].value}
                placeholder="Search for a place"
                autocomplete="off"
                phx-debounce="350"
                phx-mounted={JS.focus()}
                class="grow"
              />
              <span :if={@searching} class="loading loading-spinner loading-xs"></span>
            </label>
          </.form>

          <div :if={@shown_suggestions != []} id="place-suggestions" class="space-y-1">
            <p class="px-1 text-[0.65rem] font-semibold uppercase tracking-wider text-base-content/50">
              {@suggestions_from}
            </p>
            <div class="flex flex-wrap gap-1.5">
              <button
                :for={place <- @shown_suggestions}
                type="button"
                id={"suggestion-#{place.id}"}
                phx-click="pick-suggestion"
                phx-value-id={place.id}
                title={place.hint}
                class={[
                  "flex max-w-full flex-col items-start rounded-box border px-2.5 py-1 text-left text-xs transition hover:border-primary/60 hover:bg-base-100",
                  if(@pending && @pending.id == "suggestion-#{place.id}",
                    do: "border-primary bg-primary/10",
                    else: "border-base-300 bg-base-100/60"
                  )
                ]}
              >
                <span class="flex max-w-full items-center gap-1 font-medium">
                  <.icon
                    name={if place.hint, do: "hero-clock-micro", else: "hero-map-pin-micro"}
                    class="size-3 shrink-0 opacity-60"
                  />
                  <span class="truncate">
                    {place.name || format_coords(place.lat, place.lon)}
                  </span>
                </span>
                <span :if={place.hint} class="text-[0.65rem] opacity-60">{place.hint}</span>
              </button>
            </div>
          </div>

          <ul
            :if={@places != []}
            id="place-results"
            class="menu menu-sm w-full rounded-box bg-base-100 p-1"
          >
            <li :for={place <- @places}>
              <button
                type="button"
                id={"place-#{place.id}"}
                phx-click="pick-place"
                phx-value-id={place.id}
                class={[
                  "flex flex-col items-start gap-0",
                  @pending && @pending.id == place.id && "menu-active"
                ]}
              >
                <span class="font-medium">{place.name}</span>
                <span class="text-xs opacity-60">{Place.detail(place)}</span>
              </button>
            </li>
          </ul>
          <p
            :if={!@searching and @places == [] and String.length(@place_query) >= 3}
            id="place-no-results"
            class="px-1 text-xs text-base-content/60"
          >
            {if @search_failed, do: "Search isn't answering right now.", else: "Nothing found."} You can click the map instead.
          </p>
          <p :if={String.length(@place_query) < 3} class="px-1 text-xs text-base-content/60">
            Type a place, or click the map to drop a pin.
          </p>
        </div>
      <% else %>
        <p :if={@photo.place_name} id="photo-place-name" class="text-sm font-medium">
          {@photo.place_name}
        </p>
      <% end %>

      <.photo_map
        id="photo-location-map"
        points={@points}
        mode="single"
        pick_event={@locating && "map-pick"}
        empty_label={if @locating, do: "Click to drop a pin", else: "No location recorded"}
        class="h-56"
        label="Where this photo was taken"
      />

      <div :if={@locating} class="flex items-center justify-between gap-2">
        <p class="min-w-0 truncate text-xs text-base-content/70" id="pending-location">
          <%= cond do %>
            <% @pending && @pending.name -> %>
              {@pending.name}
            <% @pending -> %>
              <span class="font-mono">{format_coords(@pending.lat, @pending.lon)}</span>
            <% true -> %>
              Nothing picked yet
          <% end %>
        </p>
        <div class="flex shrink-0 gap-1">
          <button
            type="button"
            id="cancel-locate"
            phx-click="cancel-locate"
            class="btn btn-ghost btn-sm"
          >
            Cancel
          </button>
          <button
            type="button"
            id="save-location"
            phx-click="save-location"
            disabled={is_nil(@pending)}
            class="btn btn-primary btn-sm"
          >
            Save
          </button>
        </div>
      </div>
    </section>
    """
  end

  attr :id, :string, required: true
  attr :to, :any, required: true
  attr :within, :any, required: true
  attr :label, :string, required: true
  attr :icon, :string, required: true
  attr :trailing, :boolean, default: false

  defp step_link(%{to: nil} = assigns) do
    ~H"""
    <span id={@id} class="btn btn-sm join-item btn-disabled" aria-disabled="true">
      <.icon :if={!@trailing} name={@icon} class="size-4" /> {@label}
      <.icon :if={@trailing} name={@icon} class="size-4" />
    </span>
    """
  end

  defp step_link(assigns) do
    ~H"""
    <.link
      id={@id}
      patch={photo_path(@to, within_value(@within))}
      class="btn btn-sm join-item"
    >
      <.icon :if={!@trailing} name={@icon} class="size-4" /> {@label}
      <.icon :if={@trailing} name={@icon} class="size-4" />
    </.link>
    """
  end

  # A `within` as it travels in links: nil (all), "promoted", or {:trip, id}.
  defp photo_path(photo, nil), do: ~p"/photos/#{photo}"
  defp photo_path(photo, "promoted"), do: ~p"/photos/#{photo}?#{[in: "promoted"]}"
  defp photo_path(photo, {:trip, id}), do: ~p"/photos/#{photo}?#{[trip: id]}"

  defp within_options(trips, owner?) do
    own = if owner?, do: [{nil, "All"}, {"promoted", "Promoted"}], else: []
    own ++ Enum.map(trips, &{{:trip, &1.id}, &1.name})
  end

  defp within_value(:all), do: nil
  defp within_value(:promoted), do: "promoted"
  defp within_value(%Trip{id: id}), do: {:trip, id}
  defp within_value(nil), do: nil

  defp within_id(nil), do: "all"
  defp within_id("promoted"), do: "promoted"
  defp within_id({:trip, id}), do: "trip-#{id}"

  defp add_trip_options(options, trips) do
    in_trips = MapSet.new(trips, & &1.id)
    Enum.reject(options, fn {_name, id} -> MapSet.member?(in_trips, id) end)
  end

  # ← and → step through, unless a name or a place is being typed.
  @impl true
  def handle_event(
        "key",
        %{"key" => key},
        %{assigns: %{editing_name: false, locating: false}} = socket
      )
      when key in ["ArrowLeft", "ArrowRight"] do
    target =
      if key == "ArrowLeft",
        do: socket.assigns.neighbors.newer,
        else: socket.assigns.neighbors.older

    case target do
      nil ->
        {:noreply, socket}

      photo ->
        {:noreply, push_patch(socket, to: photo_path(photo, within_value(socket.assigns.within)))}
    end
  end

  def handle_event("key", _params, socket), do: {:noreply, socket}

  def handle_event("toggle-flat", _params, socket),
    do: {:noreply, update(socket, :flat, &(!&1))}

  def handle_event("toggle-shot", _params, socket),
    do: {:noreply, update(socket, :shot_open, &(!&1))}

  def handle_event("tab", %{"tab" => tab}, socket) when tab in ~w(image details exif) do
    {:noreply, assign(socket, :tab, String.to_existing_atom(tab))}
  end

  def handle_event("edit-name", _params, socket),
    do: {:noreply, assign(socket, :editing_name, true)}

  def handle_event("cancel-name", _params, socket) do
    {:noreply,
     socket
     |> assign(:editing_name, false)
     |> assign(:name_form, to_form(Photos.change_photo(socket.assigns.photo)))}
  end

  def handle_event("validate-name", %{"photo" => params}, socket) do
    changeset = Photos.change_photo(socket.assigns.photo, params)
    {:noreply, assign(socket, :name_form, to_form(changeset, action: :validate))}
  end

  def handle_event("save-name", %{"photo" => params}, socket) do
    scope = socket.assigns.current_scope

    case Photos.update_photo(scope, socket.assigns.photo, Map.take(params, ["name"])) do
      {:ok, photo} ->
        {:noreply,
         socket
         |> assign(:editing_name, false)
         |> assign_photo(photo)}

      {:error, changeset} ->
        {:noreply, assign(socket, :name_form, to_form(changeset))}
    end
  end

  def handle_event("toggle-promoted", _params, socket) do
    scope = socket.assigns.current_scope
    {:ok, photo} = Photos.toggle_promoted(scope, socket.assigns.photo)
    {:noreply, assign_photo(socket, %{photo | trips: socket.assigns.photo.trips})}
  end

  def handle_event("add-to-trip", %{"filing" => %{"trip_id" => trip_id}}, socket)
      when trip_id != "" do
    scope = socket.assigns.current_scope
    {:ok, _count} = Trips.add_photos(scope, trip_id, [socket.assigns.photo.id])
    trip = Trips.get_trip!(scope, trip_id)

    {:noreply,
     socket
     |> subscribe_trips([trip])
     |> assign_photo(socket.assigns.photo)
     |> put_flash(:info, "Added to #{trip.name}")}
  end

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

  def handle_event("remove-from-trip", %{"id" => trip_id}, socket) do
    scope = socket.assigns.current_scope

    case Enum.find(socket.assigns.trips, &(&1.id == trip_id)) do
      nil ->
        {:noreply, socket}

      trip ->
        case Trips.remove_photo(scope, trip, socket.assigns.photo) do
          :ok ->
            {:noreply,
             socket |> put_flash(:info, "Taken out of #{trip.name}") |> after_unfiling()}

          {:error, _} ->
            {:noreply, socket}
        end
    end
  end

  def handle_event("locate", _params, socket) do
    socket = socket |> reset_locating() |> assign(:locating, true)
    {:noreply, socket |> assign(:suggestions, suggestions(socket)) |> assign_points()}
  end

  def handle_event("pick-suggestion", %{"id" => id}, socket) do
    case Enum.find(socket.assigns.suggestions, &(&1.id == id)) do
      nil ->
        {:noreply, socket}

      place ->
        pending = %{id: "suggestion-#{id}", lat: place.lat, lon: place.lon, name: place.name}
        {:noreply, socket |> assign(:pending, pending) |> assign_points()}
    end
  end

  def handle_event("cancel-locate", _params, socket) do
    {:noreply, socket |> reset_locating() |> assign_points()}
  end

  def handle_event("search-place", %{"place" => %{"q" => query}}, socket) do
    near = Photo.lat_lon(socket.assigns.photo)

    socket =
      socket
      |> assign(:place_query, query)
      |> assign(:place_form, to_form(%{"q" => query}, as: :place))
      |> assign(:search_failed, false)

    if String.length(String.trim(query)) < 3 do
      {:noreply, assign(socket, places: [], searching: false)}
    else
      # A newer search started under the same name wins; an older one's
      # answer is dropped.
      {:noreply,
       socket
       |> assign(:searching, true)
       |> start_async(:geocode, fn -> Geocoder.search(query, near: near) end)}
    end
  end

  def handle_event("pick-place", %{"id" => id}, socket) do
    case Enum.find(socket.assigns.places, &(&1.id == id)) do
      nil ->
        {:noreply, socket}

      place ->
        pending = %{id: place.id, lat: place.lat, lon: place.lon, name: Place.label(place)}
        {:noreply, socket |> assign(:pending, pending) |> assign_points()}
    end
  end

  def handle_event("map-pick", %{"lat" => lat, "lon" => lon}, socket)
      when is_number(lat) and is_number(lon) do
    if socket.assigns.locating do
      {:noreply,
       socket |> assign(:pending, %{id: nil, lat: lat, lon: lon, name: nil}) |> assign_points()}
    else
      {:noreply, socket}
    end
  end

  def handle_event("save-location", _params, %{assigns: %{pending: %{} = pending}} = socket) do
    scope = socket.assigns.current_scope
    photo = socket.assigns.photo

    case Photos.set_photo_location(scope, photo, {pending.lat, pending.lon}, pending.name) do
      {:ok, updated} ->
        {:noreply,
         socket
         |> reset_locating()
         |> assign_photo(updated)
         |> put_flash(:info, "Location saved")}

      {:error, _changeset} ->
        {:noreply, put_flash(socket, :error, "That isn't a place on the map")}
    end
  end

  def handle_event("save-location", _params, socket), do: {:noreply, socket}

  def handle_event("remove-location", _params, socket) do
    photo = socket.assigns.photo
    {:ok, updated} = Photos.set_photo_location(socket.assigns.current_scope, photo, nil)

    {:noreply,
     socket
     |> reset_locating()
     |> assign_photo(updated)
     |> put_flash(:info, "Location removed")}
  end

  def handle_event("delete", _params, socket) do
    scope = socket.assigns.current_scope
    %{newer: newer, older: older} = socket.assigns.neighbors
    {:ok, _} = Photos.delete_photo(scope, socket.assigns.photo)

    next =
      case older || newer do
        nil -> ~p"/photos"
        photo -> photo_path(photo, within_value(socket.assigns.within))
      end

    {:noreply, socket |> put_flash(:info, "Photo deleted") |> push_navigate(to: next)}
  end

  @impl true
  def handle_async(:geocode, {:ok, {:ok, places}}, socket) do
    {:noreply, assign(socket, places: places, searching: false)}
  end

  def handle_async(:geocode, _failed, socket) do
    {:noreply, assign(socket, places: [], searching: false, search_failed: true)}
  end

  @impl true
  def handle_info(
        {:photo_updated, %Photo{id: id} = photo},
        %{assigns: %{photo: %{id: id}}} = socket
      ) do
    {:noreply, assign_photo(socket, %{photo | trips: socket.assigns.photo.trips})}
  end

  def handle_info({:photo_deleted, %Photo{id: id}}, %{assigns: %{photo: %{id: id}}} = socket) do
    to = if socket.assigns.owner?, do: ~p"/photos", else: ~p"/trips"
    {:noreply, socket |> put_flash(:info, "Photo deleted") |> push_navigate(to: to)}
  end

  # A trip's photos or people changed: this photo's trips may have too.
  def handle_info(:album_changed, socket), do: {:noreply, after_unfiling(socket)}

  def handle_info({:member_removed, user_id}, socket) do
    if user_id == socket.assigns.current_scope.user.id,
      do: {:noreply, after_unfiling(socket)},
      else: {:noreply, socket}
  end

  def handle_info(_message, socket), do: {:noreply, socket}

  # Someone else's photo taken out of the last trip they shared: there's
  # nothing left for them to see.
  defp after_unfiling(socket) do
    if socket.assigns.owner? or
         Trips.photo_trips(socket.assigns.current_scope, socket.assigns.photo) != [] do
      assign_photo(socket, socket.assigns.photo)
    else
      push_navigate(socket, to: ~p"/trips")
    end
  end

  defp format_coords(lat, lon),
    do: "#{format_coord(lat, "N", "S")}, #{format_coord(lon, "E", "W")}"

  defp format_coord(value, pos, neg) do
    hemisphere = if value >= 0, do: pos, else: neg
    "#{:erlang.float_to_binary(abs(value) / 1, decimals: 5)}° #{hemisphere}"
  end

  # One line for the folded section: the camera and the exposure triangle.
  defp shot_summary(photo) do
    [:camera, :f_number, :exposure, :iso]
    |> Enum.flat_map(fn key ->
      case Map.get(photo, key) do
        nil -> []
        value -> [Facets.format(key, value)]
      end
    end)
    |> Enum.join(" · ")
  end

  defp shot_details(photo) do
    for key <- Facets.keys(), value = Map.get(photo, key), not is_nil(value), do: {key, value}
  end

  # A detail opens your photos that share it; past the camera itself, with
  # the same camera too, since an aperture means most within one camera.
  defp shot_filter(photo, :camera), do: Facets.to_params(camera: photo.camera)

  defp shot_filter(photo, key) do
    [camera: photo.camera]
    |> Enum.reject(fn {_key, value} -> is_nil(value) end)
    |> Keyword.put(key, Map.fetch!(photo, key))
    |> Facets.to_params()
  end

  # EXIF arrives as nested maps: top-level groups ("exif", "gps", ...) and
  # loose top-level tags, which go under "image".
  defp exif_groups(nil), do: []

  defp exif_groups(exif) when is_map(exif) do
    {groups, loose} = Enum.split_with(exif, fn {_k, v} -> is_map(v) end)

    groups = Enum.map(groups, fn {k, v} -> {k, Enum.sort(v)} end) |> Enum.sort()
    if loose == [], do: groups, else: [{"image", Enum.sort(loose)} | groups]
  end

  # The EXIF entries that a camera detail was read from, so they can link
  # to photos sharing it (see Images.shooting/1).
  @exif_facets %{
    {"image", "make"} => :camera,
    {"image", "model"} => :camera,
    {"exif", "lens_model"} => :lens,
    {"exif", "f_number"} => :f_number,
    {"exif", "focal_length"} => :focal_length,
    {"exif", "iso_speed_ratings"} => :iso,
    {"exif", "exposure_time"} => :exposure
  }

  defp exif_facet(photo, group, key) do
    with facet when not is_nil(facet) <- Map.get(@exif_facets, {group, key}),
         value when not is_nil(value) <- Map.get(photo, facet),
         do: facet
  end

  defp format_exif(value) when is_binary(value), do: value
  defp format_exif(value) when is_list(value), do: Enum.map_join(value, ", ", &format_exif/1)
  defp format_exif(value) when is_map(value), do: Jason.encode!(value)
  defp format_exif(nil), do: "—"
  defp format_exif(value), do: to_string(value)
end