3.6 KiB · text History 44bc4f7
// Everyone's pointer over the shared photo (CartosnapAppWeb.ShareLive).
//
// Set on an overlay laid exactly over the photo (phx-update="ignore", so
// the cursors drawn here survive renders). Positions travel as percentages
// of the photo, so a pointer over someone's nose on a phone lands on the
// same nose on a wide screen. Only people on the same photo are shown.

const THROTTLE_MS = 50

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

// Colours come from the server's palette; still checked before use.
const safeColor = color => (typeof color === "string" && /^#[0-9a-f]{3,8}$/i.test(color) ? color : "#888")

const cursorHtml = (name, color) => `
  <svg width="18" height="18" viewBox="0 0 18 18" class="drop-shadow" aria-hidden="true">
    <path d="M2 1.5 L15.5 8.2 L9.3 9.6 L6.4 15.5 Z" fill="${color}" stroke="white" stroke-width="1.4" stroke-linejoin="round"/>
  </svg>
  <span class="share-cursor-name" style="background:${color}">${escapeHtml(name)}</span>`

export default {
  mounted() {
    this.cursors = new Map()
    this.target = this.el.parentElement
    this.lastSent = 0
    this.pending = null

    this.onMove = e => {
      const rect = this.target.getBoundingClientRect()
      if (!rect.width || !rect.height) return
      const x = ((e.clientX - rect.left) / rect.width) * 100
      const y = ((e.clientY - rect.top) / rect.height) * 100
      this.send({x: Math.round(x * 10) / 10, y: Math.round(y * 10) / 10})
    }
    this.onLeave = () => this.send({x: null, y: null}, true)

    this.target.addEventListener("pointermove", this.onMove)
    this.target.addEventListener("pointerleave", this.onLeave)

    this.handleEvent("share:cursor", ({id, name, color, x, y, photo}) => this.place(id, name, color, x, y, photo))
    this.handleEvent("share:cursor-leave", ({id}) => this.remove(id))
  },

  updated() {
    // A new photo: only the people on it stay.
    for (const [id, cursor] of this.cursors) this.show(cursor)
  },

  destroyed() {
    this.target.removeEventListener("pointermove", this.onMove)
    this.target.removeEventListener("pointerleave", this.onLeave)
    clearTimeout(this.timer)
  },

  // At most one message per THROTTLE_MS, always ending on the latest spot.
  send(position, now = false) {
    const elapsed = Date.now() - this.lastSent
    this.pending = position
    if (now || elapsed >= THROTTLE_MS) {
      clearTimeout(this.timer)
      this.flush()
    } else if (!this.timer) {
      this.timer = setTimeout(() => this.flush(), THROTTLE_MS - elapsed)
    }
  },

  flush() {
    this.timer = null
    if (!this.pending) return
    this.lastSent = Date.now()
    this.pushEvent("cursor", this.pending)
    this.pending = null
  },

  place(id, name, color, x, y, photo) {
    let cursor = this.cursors.get(id)
    if (!cursor) {
      const el = document.createElement("div")
      el.className = "share-cursor"
      el.innerHTML = cursorHtml(name, safeColor(color))
      this.el.appendChild(el)
      cursor = {el}
      this.cursors.set(id, cursor)
    }
    Object.assign(cursor, {x, y, photo})
    if (typeof x === "number" && typeof y === "number") {
      cursor.el.style.left = `${Math.min(Math.max(x, 0), 100)}%`
      cursor.el.style.top = `${Math.min(Math.max(y, 0), 100)}%`
    }
    this.show(cursor)
  },

  show(cursor) {
    const here = cursor.photo === this.el.dataset.photo && typeof cursor.x === "number"
    cursor.el.classList.toggle("is-hidden", !here)
  },

  remove(id) {
    this.cursors.get(id)?.el.remove()
    this.cursors.delete(id)
  }
}