9.9 KiB · text History 1ba5ec3
// Photos on a map (CartosnapAppWeb.Components.PhotoMap). The server renders
// an empty element carrying the photos and tile settings as data attributes
// (and phx-update="ignore", so Leaflet owns what's inside); this draws them
// and keeps up as they change.
import L from "./leaflet_global"
import "leaflet.markercluster"

const PIN_SIZE = 44
const SINGLE_ZOOM = 14

const escapeHtml = text =>
  String(text ?? "").replace(/[&<>"']/g, c => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"})[c])

// Image URLs come from our own storage keys, but they only ever land in an
// attribute after this check: absolute http(s), or a same-origin path (dev's
// local uploads), never protocol-relative "//host".
const safeUrl = url =>
  typeof url === "string" && (/^https?:\/\//.test(url) || /^\/(?!\/)/.test(url)) ? url : null

const pinIcon = (point, focused) => {
  const src = safeUrl(point.thumb)
  const classes = ["photo-pin", point.promoted && "is-promoted", focused && "is-focused"].filter(Boolean).join(" ")
  const inner = src
    ? `<img src="${escapeHtml(src)}" alt="" loading="lazy" draggable="false">`
    : `<span class="grid h-full w-full place-items-center text-base-content/50"><span class="hero-photo size-5"></span></span>`
  return L.divIcon({
    className: "",
    iconSize: [PIN_SIZE, PIN_SIZE],
    iconAnchor: [PIN_SIZE / 2, PIN_SIZE / 2],
    html: `<span class="${classes}">${inner}</span>`
  })
}

const clusterIcon = cluster => {
  const count = cluster.getChildCount()
  const size = count < 10 ? 36 : count < 100 ? 44 : 54
  return L.divIcon({
    className: "",
    iconSize: [size, size],
    html: `<span class="photo-cluster">${count}</span>`
  })
}

const tooltipHtml = point =>
  `<div class="font-semibold">${escapeHtml(point.title)}</div>` +
  (point.date ? `<div class="opacity-70">${escapeHtml(point.date)}</div>` : "")

export default {
  mounted() {
    this.styles = JSON.parse(this.el.dataset.styles)
    this.single = this.el.dataset.mode === "single"
    this.markers = new Map()

    this.map = L.map(this.el, {
      // The page scrolls past a small map; click it to zoom with the wheel.
      scrollWheelZoom: Boolean(this.el.dataset.boundsEvent),
      zoomSnap: 0.5,
      worldCopyJump: true
    })
    this.map.attributionControl.setPrefix('<a href="https://leafletjs.com">Leaflet</a>')
    if (!this.map.scrollWheelZoom.enabled()) {
      this.map.on("click", () => this.map.scrollWheelZoom.enable())
      this.map.on("mouseout", () => this.map.scrollWheelZoom.disable())
    }

    this.tiles = L.tileLayer(this.tileUrl(), {
      maxZoom: 19,
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map)

    this.layer = this.single
      ? L.layerGroup()
      : L.markerClusterGroup({
          iconCreateFunction: clusterIcon,
          showCoverageOnHover: false,
          spiderfyOnMaxZoom: true,
          maxClusterRadius: 56
        })
    this.layer.addTo(this.map)
    // Areas of a trip (data-areas) sit under the pins.
    this.areaLayer = L.layerGroup().addTo(this.map)

    if (this.el.dataset.boundsEvent) {
      this.map.on("moveend", () => this.sendBounds())
    }

    // data-pick-event (read at click time, so the LiveView can switch it on
    // and off): a click on the map drops a pin there and says where.
    this.map.on("click", e => {
      const event = this.el.dataset.pickEvent
      if (!event) return
      const lat = e.latlng.lat
      const lon = L.Util.wrapNum(e.latlng.lng, [-180, 180], true)
      this.pickedAt = [lat, lon]
      this.pushEvent(event, {lat, lon})
    })

    this.handleEvent("photo-map:focus", ({id, photo}) => {
      if (id === this.el.id) this.focus(photo, true)
    })

    // data-focus-from names a list (a panel of cards carrying
    // data-photo-id); hovering a card lifts its pin. Client-only: hover has
    // no LiveView binding, and a round trip per mouse move would lag.
    const source = this.el.dataset.focusFrom && document.querySelector(this.el.dataset.focusFrom)
    if (source) {
      this.onHover = e => {
        const card = e.target.closest("[data-photo-id]")
        const id = card ? card.dataset.photoId : null
        if (id !== this.focused) this.focus(id, false)
      }
      this.onLeave = () => this.focus(null, false)
      source.addEventListener("mouseover", this.onHover)
      source.addEventListener("focusin", this.onHover)
      source.addEventListener("mouseleave", this.onLeave)
      this.focusSource = source
    }

    this.draw(true)

    // Leaflet measures its container once; tell it when the page resizes it.
    this.resizeObserver = new ResizeObserver(() => this.map.invalidateSize({pan: false}))
    this.resizeObserver.observe(this.el)

    // Follow the app theme with the matching tile style.
    this.themeObserver = new MutationObserver(() => this.tiles.setUrl(this.tileUrl()))
    this.themeObserver.observe(document.documentElement, {attributes: true, attributeFilter: ["data-theme"]})
  },

  updated() {
    // Only re-frame when WHERE things are changed, not when one is focused,
    // which would make the map jump under the pointer -- nor when the change
    // is a pin just dropped by clicking, which is already in view.
    const key = this.placesKey()
    const points = this.points()
    const justPicked = this.pickedAt && points.length === 1 &&
      points[0].lat === this.pickedAt[0] && points[0].lon === this.pickedAt[1]
    this.pickedAt = null
    this.draw(key !== this.drawnPlaces && !justPicked)
  },

  // data-areas: rings round parts of the map, each named; clicking one
  // sends data-area-event with its id. Redrawn only when they change.
  drawAreas() {
    const raw = this.el.dataset.areas || "[]"
    if (raw === this.drawnAreas) return
    this.drawnAreas = raw
    this.areaLayer.clearLayers()
    JSON.parse(raw).forEach(area => {
      const ring = L.circle([area.lat, area.lon], {
        radius: Math.max(area.radius * 1.15, 120),
        className: "photo-area",
        interactive: true
      }).bindTooltip(escapeHtml(area.name), {
        permanent: true,
        direction: "center",
        className: "photo-area-label",
        interactive: true
      })
      const event = this.el.dataset.areaEvent
      if (event) {
        ring.on("click", () => this.pushEvent(event, {id: area.id}))
        ring.getTooltip().on("click", () => this.pushEvent(event, {id: area.id}))
      }
      ring.addTo(this.areaLayer)
    })
  },

  destroyed() {
    if (this.focusSource) {
      this.focusSource.removeEventListener("mouseover", this.onHover)
      this.focusSource.removeEventListener("focusin", this.onHover)
      this.focusSource.removeEventListener("mouseleave", this.onLeave)
    }
    this.resizeObserver?.disconnect()
    this.themeObserver?.disconnect()
    this.map?.remove()
  },

  points() {
    return JSON.parse(this.el.dataset.points || "[]")
  },

  placesKey() {
    return this.points().map(p => `${p.id}@${p.lat},${p.lon}`).sort().join("|")
  },

  tileUrl() {
    const theme = document.documentElement.getAttribute("data-theme")
    const style = this.styles[theme] || this.styles.default
    return this.el.dataset.tileUrl.replace("{style}", style)
  },

  draw(fit) {
    this.drawAreas()
    const points = this.points()
    this.drawnPlaces = this.placesKey()
    this.layer.clearLayers()
    this.markers.clear()
    this.focused = this.el.dataset.focus || null

    const markers = points.map(point => {
      const marker = L.marker([point.lat, point.lon], {
        icon: pinIcon(point, point.id === this.focused),
        title: point.title,
        riseOnHover: true,
        zIndexOffset: point.id === this.focused ? 1000 : 0
      }).bindTooltip(tooltipHtml(point), {direction: "top", offset: [0, -PIN_SIZE / 2], className: "photo-map-tooltip"})

      // data-select-event: a pin picks its photo where it is (the shared
      // view); otherwise it opens the photo's page.
      const selectEvent = this.el.dataset.selectEvent
      if (selectEvent) {
        marker.on("click", () => this.pushEvent(selectEvent, {id: point.id}))
      } else if (point.href && !this.single) {
        marker.on("click", () => this.js().navigate(point.href))
      }
      marker.point = point
      this.markers.set(point.id, marker)
      return marker
    })

    if (this.single) markers.forEach(m => m.addTo(this.layer))
    else this.layer.addLayers(markers)

    if (fit) this.fit(points)
  },

  // Lift one pin above the rest; with `reveal`, bring it into view.
  focus(photoId, reveal) {
    const previous = this.focused && this.markers.get(this.focused)
    if (previous) {
      previous.setIcon(pinIcon(previous.point, false))
      previous.setZIndexOffset(0)
    }
    this.focused = photoId || null
    const marker = photoId && this.markers.get(photoId)
    if (!marker) return
    marker.setIcon(pinIcon(marker.point, true))
    marker.setZIndexOffset(1000)
    if (reveal && this.layer.getVisibleParent) {
      const parent = this.layer.getVisibleParent(marker)
      // Hidden in a cluster: open it rather than leave the focus invisible.
      if (parent && parent !== marker && !this.map.getBounds().contains(marker.getLatLng())) {
        this.layer.zoomToShowLayer(marker)
      }
    }
  },

  sendBounds() {
    const b = this.map.getBounds()
    this.pushEvent(this.el.dataset.boundsEvent, {
      north: b.getNorth(),
      south: b.getSouth(),
      east: L.Util.wrapNum(b.getEast(), [-180, 180], true),
      west: L.Util.wrapNum(b.getWest(), [-180, 180], true)
    })
  },

  fit(points) {
    if (points.length === 1) {
      this.map.setView([points[0].lat, points[0].lon], this.single ? SINGLE_ZOOM : 11)
    } else if (points.length > 1) {
      this.map.fitBounds(points.map(p => [p.lat, p.lon]), {padding: [40, 40], maxZoom: 15})
    } else {
      this.map.setView([30, 0], 2) // nothing yet: the whole world
    }
    // fitBounds fires moveend itself, but setView to the current view does not.
    if (this.el.dataset.boundsEvent) this.sendBounds()
  }
}