6.6 KiB · text History e569b6d
defmodule CartosnapAppWeb.Components.PhotoMap do
  @moduledoc """
  Photos on a map. The server renders an empty element carrying the photos
  and tile settings as data attributes (`phx-update="ignore"`, so Leaflet
  owns what's inside); `assets/js/photo_map.js` draws them and keeps up as
  they change.

  Talking back and forth with the LiveView:

    * clicking a pin navigates to that photo (with `select_event`, it sends
      that event instead);
    * with `bounds_event`, every pan and zoom sends the visible box to the
      LiveView as `%{"north" => _, "south" => _, "east" => _, "west" => _}`;
    * with `pick_event`, a click on the map sends where it landed;
    * with `focus_from`, hovering a card in that list lifts its pin;
    * `areas` rings and names parts of the map; with `area_event`,
      clicking one sends that event with its id;
    * `push_event(socket, "photo-map:focus", %{id: map_id, photo: photo_id})`
      lifts one pin above the rest (nil photo clears it).

  Tiles come from our own OSM tile server (tiles.neiam.org), which renders
  one style per app theme, so the map follows the theme instead of being a
  bright rectangle in a dark page. Two limits come with it, both from the
  server: it only serves pages whose Referer it allowlists (`*.neiam.org`
  covers cs.neiam.org). It covers the whole world.

  Configure with `config :cartosnap_app, :map, tile_url: ..., styles: ...`;
  `{style}` in the URL is replaced per theme.
  """

  use Phoenix.Component

  alias CartosnapApp.Photos.Photo
  alias CartosnapApp.Storage

  @default_tile_url "https://tiles.neiam.org/{style}/{z}/{x}/{y}.png"

  # App theme -> tile style, as the sibling apps map them. Themes without a
  # style of their own get the plain dark one; `light` gets grayscale rather
  # than full-colour carto, which would out-shout the photos.
  @default_styles %{
    "light" => "grayscale",
    "dark" => "dark",
    "her" => "her",
    "afterdark" => "dark",
    "blueprint" => "dark",
    "forest" => "dark",
    "sky" => "dark",
    "clays" => "dark",
    "stones" => "dark",
    "default" => "grayscale"
  }

  attr :id, :string, required: true
  attr :points, :list, required: true, doc: "from `points/1`"

  attr :mode, :string,
    default: "cluster",
    values: ~w(cluster single),
    doc: "`cluster` groups nearby pins; `single` is one photo's place, zoomed in"

  attr :focus, :string, default: nil, doc: "the id of a photo to lift above the rest"
  attr :bounds_event, :string, default: nil, doc: "an event to send the visible box to"

  attr :focus_from, :string,
    default: nil,
    doc: "a selector for a list of `data-photo-id` cards; hovering one lifts its pin"

  attr :pick_event, :string,
    default: nil,
    doc: "when set, a click on the map sends this event with `%{\"lat\" => _, \"lon\" => _}`"

  attr :select_event, :string,
    default: nil,
    doc:
      "when set, clicking a pin sends this event with `%{\"id\" => photo_id}` instead of opening it"

  attr :areas, :list,
    default: [],
    doc: "areas to ring and name on the map (`CartosnapApp.Trips.Areas`), from `areas/1`"

  attr :area_event, :string,
    default: nil,
    doc: "when set, clicking an area sends this event with `%{\"id\" => area_id}`"

  attr :empty_label, :string, default: "No photos with a location yet"
  attr :label, :string, default: "Map of photos"
  attr :class, :any, default: "h-80", doc: "sizing for the map's frame"
  attr :rounded, :boolean, default: true

  def photo_map(assigns) do
    assigns =
      assigns
      |> assign(:tile_url, config(:tile_url, @default_tile_url))
      |> assign(:styles, config(:styles, @default_styles))

    ~H"""
    <%!-- The size lives on this wrapper, never on the map: the map is
          phx-update="ignore", where LiveView only updates data attributes,
          so its class is frozen at first render. `isolate` keeps Leaflet's
          z-index 1000 controls under the nav and dropdowns. --%>
    <div class={[
      "relative isolate z-0 overflow-hidden",
      @rounded && "rounded-box border border-base-300 shadow-sm",
      @class
    ]}>
      <div
        id={@id}
        phx-hook="PhotoMap"
        phx-update="ignore"
        data-points={Jason.encode!(@points)}
        data-tile-url={@tile_url}
        data-styles={Jason.encode!(@styles)}
        data-mode={@mode}
        data-focus={@focus}
        data-bounds-event={@bounds_event}
        data-focus-from={@focus_from}
        data-pick-event={@pick_event}
        data-select-event={@select_event}
        data-areas={Jason.encode!(@areas)}
        data-area-event={@area_event}
        class="photo-map h-full w-full"
        role="region"
        aria-label={@label}
      >
      </div>
      <div
        :if={@points == [] and @empty_label}
        class="pointer-events-none absolute inset-0 z-[500] grid place-items-center"
      >
        <span class="rounded-full bg-base-100/90 px-3 py-1.5 text-xs font-medium shadow">
          {@empty_label}
        </span>
      </div>
    </div>
    """
  end

  @doc """
  The pins for some photos: those with a position, each with what the map
  shows of it. Photos without a position are left out.
  """
  def points(photos) do
    for %Photo{} = photo <- photos, {lat, lon} <- [Photo.lat_lon(photo)] do
      %{
        id: photo.id,
        lat: lat,
        lon: lon,
        title: Photo.title(photo),
        date: photo.date && Calendar.strftime(photo.date, "%b %-d, %Y"),
        thumb: Storage.public_url(photo.url_thumb || photo.url_preview),
        promoted: photo.promoted,
        href: "/photos/#{photo.id}"
      }
    end
  end

  @doc "What the map needs of some areas: where each is, how big, and its name."
  def areas(areas) do
    for area <- areas do
      %{id: area.id, name: area.name, lat: area.lat, lon: area.lon, radius: area.radius}
    end
  end

  @doc "Whether a pin lies inside `%{\"north\" => _, ...}` bounds."
  def in_bounds?(%{lat: lat, lon: lon}, %{"north" => n, "south" => s, "east" => e, "west" => w})
      when is_number(n) and is_number(s) and is_number(e) and is_number(w) do
    lat >= s and lat <= n and lon_within?(lon, w, e)
  end

  def in_bounds?(_point, _bounds), do: true

  # A box across the antimeridian has its west edge east of its east edge.
  defp lon_within?(lon, w, e) when w <= e, do: lon >= w and lon <= e
  defp lon_within?(lon, w, e), do: lon >= w or lon <= e

  @doc """
  Where the tiles come from: the URL template with `{style}` in it, and the
  tile style per app theme.
  """
  def tiles do
    %{
      url: config(:tile_url, @default_tile_url),
      styles: config(:styles, @default_styles)
    }
  end

  defp config(key, default) do
    :cartosnap_app |> Application.get_env(:map, []) |> Keyword.get(key, default)
  end
end