Skip to content

popup

Stable

A popup with text or HTML content, placed at a coordinate.

The example's template and LiveView, read from the files that run in the preview.

lib/maplibrex_demo_web/examples/popup_example.html.heex
<div id="popup-example">
  <.example_frame error={@map_error} error_id="example-popup-map-error">
    <%!-- The map centres on the chosen place, so the popup above it is in view. --%>
    <.map
      id="example-popup-map"
      center={@place.lng_lat}
      zoom={15}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- The popup sits next to <.map> and names it with map_id. Where it is,
        whether it is open and its anchor are assigns; its content is the
        slot. Every one of them follows its assign after mount. --%>
  <.popup
    id="example-popup"
    map_id="example-popup-map"
    lng_lat={@place.lng_lat}
    open={@open}
    anchor={@anchor}
    events={["popup:opened", "popup:closed"]}
  >
    <p class="font-bold">{name(@place.id)}</p>
    <p class="font-mono">{lng_lat(@place.lng_lat)}</p>

    <%!-- The popup shows the slot's own elements, so its ids are unique and
          its bindings work: a click, a form and a label's for. --%>
    <div class="mt-2 flex items-center gap-2">
      <.example_popup_button id="example-popup-like" phx-click="like">
        <.icon name="hero-heart-micro" class="size-4" />
        {gettext("Like")}
      </.example_popup_button>
      <span id="example-popup-likes" class="tabular-nums">
        {ngettext("1 like", "%{count} likes", @likes)}
      </span>
    </div>

    <.form
      for={@note_form}
      id="example-popup-note"
      phx-change="note"
      phx-submit="save_note"
      class="mt-2"
    >
      <div class="flex justify-between text-label">
        <label for="example-popup-note-text" class="font-bold">{gettext("Note")}</label>
        <span id="example-popup-note-length" class="font-mono tabular-nums">
          {String.length(@note_form[:text].value)}/40
        </span>
      </div>
      <div class="mt-1 flex gap-1.5">
        <input
          type="text"
          id="example-popup-note-text"
          name={@note_form[:text].name}
          value={@note_form[:text].value}
          maxlength="40"
          autocomplete="off"
          class="h-7 min-w-0 flex-1 rounded-ui border border-map-ink/25 bg-transparent px-2"
        />
        <.example_popup_button id="example-popup-note-save" type="submit">
          {gettext("Save")}
        </.example_popup_button>
      </div>
    </.form>
  </.popup>

  <div class="grid gap-x-8 gap-y-4 border-t border-line px-4 py-4 lg:grid-cols-[1fr_auto]">
    <div class="space-y-4">
      <%!-- Assigns: a place moves the popup and opens it. --%>
      <.example_group id="example-popup-places" label={gettext("Set assigns")}>
        <.example_button
          :for={place <- places()}
          id={"example-popup-place-#{place.id}"}
          pressed={@place.id == place.id}
          phx-click="place"
          phx-value-place={place.id}
        >
          {name(place.id)}
        </.example_button>
      </.example_group>

      <div class="flex flex-wrap gap-x-8 gap-y-4">
        <.example_group id="example-popup-anchor" label="anchor" code>
          <.example_button
            :for={anchor <- anchors()}
            id={"example-popup-anchor-#{anchor}"}
            code
            pressed={@anchor == anchor}
            phx-click="anchor"
            phx-value-anchor={anchor}
          >
            {anchor}
          </.example_button>
        </.example_group>

        <.example_group id="example-popup-toggle" label="open" code>
          <.form for={@options} id="example-popup-options" phx-change="options" class="py-1.5">
            <.example_checkbox field={@options[:open]} label="open" />
          </.form>
        </.example_group>
      </div>
    </div>

    <%!-- Commands: JS structs that open and close the popup in the browser,
          with no round trip; popup:opened and popup:closed then tell the
          server. --%>
    <.example_group id="example-popup-commands" label={gettext("Run commands")}>
      <.example_button
        id="example-popup-cmd-open"
        code
        phx-click={PopupCmd.open("example-popup", @place.lng_lat)}
      >
        open
      </.example_button>
      <.example_button
        id="example-popup-cmd-close"
        code
        phx-click={PopupCmd.close("example-popup")}
      >
        close
      </.example_button>
      <.example_button
        id="example-popup-cmd-toggle"
        code
        phx-click={PopupCmd.toggle("example-popup")}
      >
        toggle
      </.example_button>
    </.example_group>
  </div>

  <%!-- popup:opened and popup:closed keep open current. --%>
  <.example_readout values={[
    place: @place.id,
    anchor: @anchor,
    open: @open,
    last_event: @last_event || "—",
    likes: @likes,
    note: @note || "—"
  ]} />
</div>
lib/maplibrex_demo_web/examples/popup_example.ex
defmodule MaplibrexDemoWeb.Examples.PopupExample do
  @moduledoc """
  The example of `<.popup>`: a popup on its own, not attached to a marker,
  whose place, content, anchor and open state are assigns, opened and closed
  in the browser by commands too, with `popup:opened` and `popup:closed`
  keeping the server in step. Its content is LiveView content: a like
  button and a note form in it talk to the server like any other.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  alias MaplibreX.Components.Popup, as: PopupCmd

  # Demo plumbing, not needed in an application: applies the page's locale,
  # copies each map event to the page's Events tab and keeps @theme on the
  # page's light or dark theme.
  on_mount MaplibrexDemoWeb.Examples.Plumbing

  # OpenFreeMap's basemap for the page's theme: the map's style follows @theme.
  defp basemap("dark"), do: "https://tiles.openfreemap.org/styles/dark"
  defp basemap("light"), do: "https://tiles.openfreemap.org/styles/liberty"

  @places [
    %{id: "colosseum", lng_lat: [12.4922, 41.8902]},
    %{id: "pantheon", lng_lat: [12.4769, 41.8986]},
    %{id: "trevi", lng_lat: [12.4833, 41.9009]}
  ]

  # "auto", the default, lets MapLibre choose the side that keeps the popup
  # in view; the others pin the popup's top or bottom to its place.
  @anchors ~w(auto top bottom)

  @impl true
  def mount(_params, _session, socket) do
    {:ok,
     socket
     |> assign(place: hd(@places), anchor: "auto", last_event: nil, map_error: nil)
     |> assign(likes: 0, note: nil, note_form: note_form(""))
     |> assign_open(true)}
  end

  # Driven from the server: a place moves the popup and opens it; the
  # checkbox opens and closes it.

  @impl true
  def handle_event("place", %{"place" => id}, socket) do
    case Enum.find(@places, &(&1.id == id)) do
      nil -> {:noreply, socket}
      place -> {:noreply, socket |> assign(:place, place) |> assign_open(true)}
    end
  end

  def handle_event("options", %{"open" => open}, socket) do
    {:noreply, assign_open(socket, open == "true")}
  end

  # A new anchor replaces the popup with one anchored there, open if it was.
  def handle_event("anchor", %{"anchor" => anchor}, socket) when anchor in @anchors do
    {:noreply, assign(socket, :anchor, anchor)}
  end

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

  # From the popup's content: its bindings reach this LiveView as any other.

  def handle_event("like", _params, socket) do
    {:noreply, update(socket, :likes, &(&1 + 1))}
  end

  def handle_event("note", %{"note" => %{"text" => text}}, socket) do
    {:noreply, assign(socket, :note_form, note_form(text))}
  end

  def handle_event("save_note", %{"note" => %{"text" => text}}, socket) do
    note = if String.trim(text) != "", do: String.trim(text)
    {:noreply, assign(socket, note: note, note_form: note_form(text))}
  end

  # Events from the popup. Its close button, a click on the map and the
  # commands open and close it in the browser; popup:opened and popup:closed
  # tell the server, so `open` stays true to what the visitor sees.

  def handle_event("popup:opened", _payload, socket) do
    {:noreply, socket |> assign(:last_event, "popup:opened") |> assign_open(true)}
  end

  def handle_event("popup:closed", _payload, socket) do
    {:noreply, socket |> assign(:last_event, "popup:closed") |> assign_open(false)}
  end

  def handle_event("map:error", %{"error" => message}, socket) do
    {:noreply, assign(socket, :map_error, message)}
  end

  defp assign_open(socket, open) do
    assign(socket, open: open, options: to_form(%{"open" => open}))
  end

  defp note_form(text), do: to_form(%{"text" => text}, as: :note)

  defp places, do: @places
  defp anchors, do: @anchors

  defp name("colosseum"), do: gettext("Colosseum")
  defp name("pantheon"), do: gettext("Pantheon")
  defp name("trevi"), do: gettext("Trevi Fountain")

  defp lng_lat([lng, lat]), do: "#{lng}, #{lat}"
end