23.5 KiB · text History e569b6d
defmodule CartosnapAppWeb.ShareLive do
  @moduledoc """
  A trip as others see it, signed in or not: its photos one at a time in
  the order they were taken, a filmstrip, and a map. Two ways in, kept
  apart:

    * shared (`/s/<token>`): for the people the link was sent to;
    * public (`/t/<id>`): for anyone who comes across a public trip.

  Each has its own Presence room (`Trips.share_topic/1`,
  `Trips.public_topic/1`), so strangers on the public page never see who the
  link was sent to, and its own promoted-only setting. `?photo=<id>` opens
  at that photo.

  Watching together. Anyone can follow anyone (click them in the roster):
  your photo moves when theirs does, and following someone who is
  following someone else follows the chain. Moving on your own stops you
  following. Whoever owns the trip is the host: arriving viewers follow
  them, and Bring everyone here makes every viewer follow them again, from
  wherever they had wandered. Pointers over the photo are shared live, for
  whoever is on the same photo.

  Presence (`CartosnapAppWeb.Presence`, on `Trips.share_topic/1`) says who
  is here, which photo each is on (`at`, a photo id, so following survives
  the list changing) and whom each follows (`following`, a presence key).
  A summons goes out over PubSub as `{:summon, key, name}`. Pointer moves
  are too frequent for Presence: they go peer to peer as `{:cursor, ...}`
  and reach the browser as push events.
  """
  use CartosnapAppWeb, :live_view

  import CartosnapAppWeb.PhotoComponents
  import CartosnapAppWeb.Components.PhotoMap

  alias CartosnapApp.Trips
  alias CartosnapApp.Photos.Photo
  alias CartosnapAppWeb.Components.PhotoMap
  alias CartosnapAppWeb.Presence

  # Guests get a made-up name; anything friendly and short.
  @adjectives ~w(Amber Brisk Calm Daring Eager Gentle Hazy Jolly Lucky Merry Nimble Quiet Rosy Sunny Witty Zesty)
  @animals ~w(Badger Crane Dolphin Falcon Fox Heron Lynx Marten Otter Owl Puffin Seal Swift Tern Wren Yak)

  # Pointer and avatar colours: readable under white text on any theme.
  @colors ~w(#e11d48 #ea580c #ca8a04 #16a34a #0d9488 #0284c7 #4f46e5 #9333ea #db2777 #65a30d)

  @impl true
  def mount(params, _session, socket) do
    mode = if params["token"], do: :shared, else: :public

    case find_trip(mode, params["token"] || params["id"]) do
      nil ->
        message =
          if mode == :shared,
            do: "That trip isn't shared, or the link has changed.",
            else: "That trip isn't public."

        {:ok, socket |> put_flash(:error, message) |> push_navigate(to: ~p"/")}

      trip ->
        {:ok,
         socket
         |> assign(:mode, mode)
         |> assign(:key, params["token"] || params["id"])
         |> assign(:current, nil)
         |> assign(:start_at, params["photo"])
         |> assign_viewer(trip)
         |> load_photos(trip)
         |> join(trip)}
    end
  end

  defp find_trip(:shared, token), do: Trips.get_shared_trip(token)
  defp find_trip(:public, id), do: Trips.get_public_trip(id)

  defp assign_viewer(socket, trip) do
    user = socket.assigns.current_scope && socket.assigns.current_scope.user
    key = "v-" <> Base.url_encode64(:crypto.strong_rand_bytes(6), padding: false)

    name =
      case user do
        %{email: email} -> email |> String.split("@") |> hd()
        nil -> "#{Enum.random(@adjectives)} #{Enum.random(@animals)}"
      end

    socket
    |> assign(:page_title, trip.name)
    |> assign(:trip, trip)
    |> assign(:topic, topic(socket.assigns.mode, trip))
    |> assign(:me, key)
    |> assign(:name, name)
    |> assign(:color, Enum.at(@colors, :erlang.phash2(key, length(@colors))))
    |> assign(:host?, user != nil and user.id == trip.user)
    |> assign(:following, nil)
    |> assign(:present, [])
  end

  defp topic(:shared, trip), do: Trips.share_topic(trip)
  defp topic(:public, trip), do: Trips.public_topic(trip)

  defp load_photos(socket, trip) do
    photos =
      if socket.assigns.mode == :shared,
        do: Trips.list_shared_photos(trip),
        else: Trips.list_public_photos(trip)

    # Where we were, else where the link said to start, else the first.
    wanted = (socket.assigns.current && socket.assigns.current.id) || socket.assigns.start_at
    current = Enum.find(photos, &(&1.id == wanted)) || List.first(photos)

    socket
    |> assign(:trip, trip)
    |> assign(:photos, photos)
    |> assign(:points, PhotoMap.points(photos))
    |> assign(:current, current)
  end

  defp join(socket, trip) do
    if connected?(socket) do
      topic = socket.assigns.topic
      Phoenix.PubSub.subscribe(CartosnapApp.PubSub, topic)
      Trips.subscribe(trip)

      present = present_metas(topic)
      host = host_of(present)

      # Arriving, you follow the host if they're here (and you're not them),
      # unless the link asked for a particular photo.
      socket =
        if host && !socket.assigns.host? && is_nil(socket.assigns.start_at),
          do: socket |> assign(:following, host.key) |> jump_to(host.at),
          else: socket

      {:ok, _} =
        Presence.track(self(), topic, socket.assigns.me, %{
          name: socket.assigns.name,
          color: socket.assigns.color,
          host: socket.assigns.host?,
          at: current_id(socket),
          following: socket.assigns.following
        })

      assign(socket, :present, present_metas(topic))
    else
      socket
    end
  end

  @impl true
  def render(assigns) do
    assigns =
      assigns
      |> assign(:index, current_index(assigns))
      |> assign(:host, host_of(assigns.present))
      |> assign(:others, Enum.reject(assigns.present, &(&1.key == assigns.me)))

    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} wide>
      <div id="share" phx-window-keydown="key" class="flex min-h-[calc(100dvh-4rem)] flex-col">
        <div class="flex flex-wrap items-center justify-between gap-3 border-b border-base-300 px-4 py-3 sm:px-6">
          <div class="min-w-0">
            <div class="flex items-center gap-2">
              <h1 class="truncate text-lg font-bold tracking-tight">{@trip.name}</h1>
              <span
                id="view-kind"
                class={[
                  "badge badge-sm badge-soft shrink-0",
                  if(@mode == :public, do: "badge-success", else: "badge-info")
                ]}
              >
                {if @mode == :public, do: "Public", else: "Shared with you"}
              </span>
            </div>
            <p class="text-xs text-base-content/60">
              {CartosnapAppWeb.TripLive.Index.date_range(@trip)} · {length(@photos)} {if length(
                                                                                           @photos
                                                                                         ) == 1,
                                                                                         do: "photo",
                                                                                         else:
                                                                                           "photos"}
            </p>
          </div>

          <div class="flex flex-wrap items-center gap-3">
            <.follow_status
              host?={@host?}
              host={@host}
              followed={Enum.find(@others, &(&1.key == @following))}
              others={@others}
            />
            <ul id="share-roster" class="flex -space-x-2" aria-label="Who's here">
              <li
                :for={person <- [me(assigns) | @others]}
                id={"present-#{person.key}"}
                class="relative"
              >
                <button
                  type="button"
                  phx-click={person.key != @me && JS.push("follow", value: %{key: person.key})}
                  disabled={person.key == @me}
                  title={roster_title(person, @me, @following, @present)}
                  aria-pressed={to_string(person.key == @following)}
                  class={[
                    "relative grid size-8 place-items-center rounded-full text-xs font-bold text-white ring-2 transition-transform",
                    person.key == @following && "z-10 ring-primary",
                    person.key != @following && "ring-base-100",
                    person.key != @me && "cursor-pointer hover:z-10 hover:-translate-y-0.5"
                  ]}
                  style={"background: #{person.color}"}
                >
                  {initials(person.name)}
                </button>
                <span
                  :if={person.host}
                  class="absolute -right-1 -top-1 grid size-4 place-items-center rounded-full bg-warning text-warning-content ring-2 ring-base-100"
                >
                  <.icon name="hero-star-solid" class="size-2.5" />
                </span>
              </li>
            </ul>
          </div>
        </div>

        <%= if @current do %>
          <div class="grid flex-1 gap-0 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,36%)]">
            <section class="flex min-w-0 flex-col gap-3 p-4 sm:p-6">
              <div class="relative flex flex-1 items-center justify-center rounded-box bg-base-200 p-2">
                <%= if immersive?(@current) do %>
                  <%!-- Everyone looks around a sphere (or along a panorama)
                        their own way, so a pointer position means nothing
                        on anyone else's screen: no cursors here. --%>
                  <.photo_stage
                    id="share-stage"
                    photo={@current}
                    class="h-[62vh] w-full overflow-hidden rounded-field shadow-lg"
                  />
                <% else %>
                  <%!-- The wrapper is exactly the photo's box, so pointer
                        positions are fractions of the photo itself. --%>
                  <div class="relative inline-block max-w-full">
                    <img
                      id="share-photo"
                      src={src(@current, :full)}
                      alt={Photo.title(@current)}
                      class="block max-h-[62vh] max-w-full rounded-field object-contain shadow-lg"
                    />
                    <div
                      id="share-cursors"
                      phx-hook="ShareCursors"
                      phx-update="ignore"
                      data-photo={@current.id}
                      class="pointer-events-none absolute inset-0 overflow-visible"
                    >
                    </div>
                  </div>
                <% end %>

                <button
                  :if={@index > 0}
                  type="button"
                  id="share-prev"
                  phx-click="step"
                  phx-value-by="-1"
                  aria-label="Previous photo"
                  class="btn btn-circle absolute left-3 top-1/2 -translate-y-1/2 border-0 bg-base-100/80 shadow-md backdrop-blur hover:bg-base-100"
                >
                  <.icon name="hero-chevron-left" class="size-5" />
                </button>
                <button
                  :if={@index < length(@photos) - 1}
                  type="button"
                  id="share-next"
                  phx-click="step"
                  phx-value-by="1"
                  aria-label="Next photo"
                  class="btn btn-circle absolute right-3 top-1/2 -translate-y-1/2 border-0 bg-base-100/80 shadow-md backdrop-blur hover:bg-base-100"
                >
                  <.icon name="hero-chevron-right" class="size-5" />
                </button>
                <span
                  class="absolute bottom-3 right-3 rounded-full bg-black/55 px-2.5 py-1 text-xs font-medium text-white backdrop-blur"
                  id="share-counter"
                >
                  {@index + 1} / {length(@photos)}
                </span>
              </div>

              <div class="flex items-baseline justify-between gap-3">
                <div class="min-w-0">
                  <p class="truncate font-semibold" id="share-title">{Photo.title(@current)}</p>
                  <p class="text-xs text-base-content/60">
                    {photo_date(@current)}{if @current.place_name, do: " · #{@current.place_name}"}
                  </p>
                </div>
                <p class="hidden shrink-0 text-xs text-base-content/50 sm:block">← → to page</p>
              </div>

              <ol id="share-strip" class="flex gap-1.5 overflow-x-auto pb-1" aria-label="All photos">
                <li :for={{photo, i} <- Enum.with_index(@photos)} class="shrink-0">
                  <button
                    type="button"
                    id={"strip-#{photo.id}"}
                    phx-click="select"
                    phx-value-id={photo.id}
                    aria-current={photo.id == @current.id && "true"}
                    aria-label={"Photo #{i + 1}"}
                    class={[
                      "relative block size-14 overflow-hidden rounded-field transition",
                      if(photo.id == @current.id,
                        do: "ring-2 ring-primary ring-offset-2 ring-offset-base-100",
                        else: "opacity-70 hover:opacity-100"
                      )
                    ]}
                  >
                    <.photo_image id={"strip-#{photo.id}-img"} photo={photo} class="size-14" />
                    <span class="absolute inset-x-0 bottom-0.5 flex justify-center gap-0.5">
                      <span
                        :for={person <- Enum.filter(@others, &(&1.at == photo.id))}
                        class="size-2 rounded-full ring-1 ring-white"
                        style={"background: #{person.color}"}
                        title={person.name}
                      ></span>
                    </span>
                  </button>
                </li>
              </ol>
            </section>

            <aside class="min-h-72 border-t border-base-300 lg:border-l lg:border-t-0">
              <.photo_map
                id="share-map"
                points={@points}
                focus={@current.id}
                select_event="select"
                class="h-72 lg:h-full"
                rounded={false}
                empty_label="None of these photos has a location"
                label={"Map of #{@trip.name}"}
              />
            </aside>
          </div>
        <% else %>
          <div
            id="share-empty"
            class="grid flex-1 place-items-center p-10 text-center text-base-content/60"
          >
            <div>
              <.icon name="hero-photo" class="mx-auto size-10 opacity-40" />
              <p class="mt-3">Nothing to see in this trip yet.</p>
            </div>
          </div>
        <% end %>
      </div>
    </Layouts.app>
    """
  end

  attr :host?, :boolean, required: true
  attr :host, :map, default: nil
  attr :followed, :map, default: nil
  attr :others, :list, required: true

  defp follow_status(assigns) do
    ~H"""
    <div id="follow-status" class="flex items-center gap-2 text-sm">
      <%= cond do %>
        <% @followed -> %>
          <span class="badge badge-primary badge-soft gap-1" id="following">
            <span class="size-1.5 animate-pulse rounded-full bg-primary"></span>
            Following {@followed.name}
          </span>
          <button type="button" id="stop-following" phx-click="unfollow" class="btn btn-ghost btn-xs">
            Stop
          </button>
        <% @host? -> %>
          <span class="badge badge-warning badge-soft gap-1" id="hosting">
            <.icon name="hero-star-micro" class="size-3.5" />
            {if @others == [],
              do: "You're hosting",
              else: "You're hosting · #{length(@others)} watching"}
          </span>
          <button
            :if={@others != []}
            type="button"
            id="summon"
            phx-click="summon"
            class="btn btn-primary btn-sm"
          >
            <.icon name="hero-megaphone-micro" class="size-4" /> Bring everyone here
          </button>
        <% @host -> %>
          <span class="text-xs text-base-content/60" id="own-way">Browsing on your own</span>
          <button
            type="button"
            id="follow-host"
            phx-click={JS.push("follow", value: %{key: @host.key})}
            class="btn btn-primary btn-sm"
          >
            <.icon name="hero-arrow-uturn-left-micro" class="size-4" /> Follow {@host.name}
          </button>
        <% true -> %>
          <span class="text-xs text-base-content/60" id="no-host">Browsing on your own</span>
      <% end %>
    </div>
    """
  end

  ## Moving

  @impl true
  def handle_event("step", %{"by" => by}, socket) do
    by = if by in ["1", 1], do: 1, else: -1

    {:noreply,
     move_to(socket, Enum.at(socket.assigns.photos, current_index(socket.assigns) + by))}
  end

  def handle_event("key", %{"key" => "ArrowRight"}, socket),
    do: handle_event("step", %{"by" => "1"}, socket)

  def handle_event("key", %{"key" => "ArrowLeft"}, socket),
    do: handle_event("step", %{"by" => "-1"}, socket)

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

  def handle_event("select", %{"id" => id}, socket) do
    {:noreply, move_to(socket, Enum.find(socket.assigns.photos, &(&1.id == id)))}
  end

  def handle_event("follow", %{"key" => key}, socket) do
    case Enum.find(socket.assigns.present, &(&1.key == key)) do
      %{key: key, at: at} when key != socket.assigns.me ->
        {:noreply, socket |> assign(:following, key) |> jump_to(at) |> announce()}

      _ ->
        {:noreply, socket}
    end
  end

  def handle_event("unfollow", _params, socket),
    do: {:noreply, socket |> assign(:following, nil) |> announce()}

  # The host calls everyone back: every other viewer follows them again.
  def handle_event("summon", _params, %{assigns: %{host?: true}} = socket) do
    Phoenix.PubSub.broadcast_from(
      CartosnapApp.PubSub,
      self(),
      socket.assigns.topic,
      {:summon, socket.assigns.me, socket.assigns.name}
    )

    {:noreply, socket |> assign(:following, nil) |> put_flash(:info, "Everyone's following you")}
  end

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

  def handle_event("cursor", %{"x" => x, "y" => y}, socket) do
    position =
      if is_number(x) and is_number(y) and x >= -5 and x <= 105 and y >= -5 and y <= 105,
        do: {x, y},
        else: nil

    if socket.assigns.current do
      Phoenix.PubSub.broadcast_from(
        CartosnapApp.PubSub,
        self(),
        socket.assigns.topic,
        {:cursor, socket.assigns.me, socket.assigns.name, socket.assigns.color, position,
         socket.assigns.current.id}
      )
    end

    {:noreply, socket}
  end

  # A move of your own stops you following; whoever follows you comes along.
  defp move_to(socket, nil), do: socket

  defp move_to(socket, %Photo{} = photo) do
    socket |> assign(:following, nil) |> assign(:current, photo) |> focus_map() |> announce()
  end

  defp jump_to(socket, photo_id) do
    case Enum.find(socket.assigns.photos, &(&1.id == photo_id)) do
      nil -> socket
      photo -> socket |> assign(:current, photo) |> focus_map()
    end
  end

  defp focus_map(%{assigns: %{current: %Photo{id: id}}} = socket),
    do: push_event(socket, "photo-map:focus", %{id: "share-map", photo: id})

  defp focus_map(socket), do: socket

  defp announce(socket) do
    if connected?(socket) do
      Presence.update(self(), socket.assigns.topic, socket.assigns.me, fn meta ->
        %{meta | at: current_id(socket), following: socket.assigns.following}
      end)
    end

    socket
  end

  ## Others

  @impl true
  def handle_info(%Phoenix.Socket.Broadcast{event: "presence_diff", payload: diff}, socket) do
    present = present_metas(socket.assigns.topic)
    socket = socket |> assign(:present, present) |> keep_up(present)

    # Whoever left takes their pointer with them.
    socket =
      Enum.reduce(Map.keys(diff.leaves), socket, fn key, acc ->
        if Map.has_key?(diff.joins, key),
          do: acc,
          else: push_event(acc, "share:cursor-leave", %{id: key})
      end)

    {:noreply, socket}
  end

  def handle_info({:summon, key, name}, socket) do
    case Enum.find(socket.assigns.present, &(&1.key == key)) do
      nil ->
        {:noreply, socket}

      host ->
        {:noreply,
         socket
         |> assign(:following, key)
         |> jump_to(host.at)
         |> announce()
         |> put_flash(:info, "#{name} brought everyone here")}
    end
  end

  def handle_info({:cursor, key, name, color, position, photo_id}, socket) do
    {x, y} = position || {nil, nil}

    {:noreply,
     push_event(socket, "share:cursor", %{
       id: key,
       name: name,
       color: color,
       x: x,
       y: y,
       photo: photo_id
     })}
  end

  def handle_info(:share_revoked, socket) do
    {:noreply,
     socket
     |> put_flash(
       :error,
       if(socket.assigns.mode == :shared,
         do: "This trip is no longer shared.",
         else: "This trip is no longer public."
       )
     )
     |> push_navigate(to: ~p"/")}
  end

  def handle_info(:share_changed, socket) do
    trip = find_trip(socket.assigns.mode, socket.assigns.key)
    {:noreply, if(trip, do: socket |> load_photos(trip) |> announce(), else: socket)}
  end

  # Someone in the trip filed photos under it or took them out.
  def handle_info(:album_changed, socket),
    do: {:noreply, socket |> load_photos(socket.assigns.trip) |> announce()}

  # Someone in the trip changed a photo: promoted, renamed, resized, moved, deleted.
  def handle_info({event, _photo}, socket)
      when event in [:photo_created, :photo_updated, :photo_deleted] do
    {:noreply, socket |> load_photos(socket.assigns.trip) |> announce()}
  end

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

  ## Helpers

  defp present_metas(topic) do
    topic
    |> Presence.list()
    |> Enum.map(fn {key, %{metas: [meta | _]}} -> Map.put(meta, :key, key) end)
    |> Enum.sort_by(& &1.name)
  end

  # Following: go where the followed person is; if they've left, stop.
  defp keep_up(%{assigns: %{following: nil}} = socket, _present), do: socket

  defp keep_up(socket, present) do
    case Enum.find(present, &(&1.key == socket.assigns.following)) do
      nil ->
        socket |> assign(:following, nil) |> announce()

      %{at: at} ->
        if at == current_id(socket), do: socket, else: socket |> jump_to(at) |> announce()
    end
  end

  # The trip's owner, if here (in two tabs, either will do).
  defp host_of(present), do: Enum.find(present, & &1.host)

  defp roster_title(person, me, following, present) do
    whose =
      case person[:following] && Enum.find(present, &(&1.key == person.following)) do
        %{name: name} -> ", following #{name}"
        _ -> ""
      end

    host = if person.host, do: " (host)", else: ""

    cond do
      person.key == me -> "#{person.name} (you)#{whose}"
      person.key == following -> "#{person.name}#{host}: you're following#{whose}"
      true -> "Follow #{person.name}#{host}#{whose}"
    end
  end

  defp me(assigns) do
    %{
      key: assigns.me,
      name: assigns.name,
      color: assigns.color,
      host: assigns.host?,
      at: current_id(assigns),
      following: assigns.following
    }
  end

  defp current_id(%Phoenix.LiveView.Socket{assigns: assigns}), do: current_id(assigns)
  defp current_id(%{current: %Photo{id: id}}), do: id
  defp current_id(_assigns), do: nil

  defp current_index(%{current: %Photo{id: id}, photos: photos}),
    do: Enum.find_index(photos, &(&1.id == id)) || 0

  defp current_index(_assigns), do: 0

  defp initials(name) do
    name
    |> String.split(~r/[\s._-]+/, trim: true)
    |> Enum.take(2)
    |> Enum.map_join(&String.first/1)
    |> String.upcase()
  end
end