2.5 KiB · text History 1ba5ec3
// A wide panorama (CartosnapAppWeb.PhotoComponents.photo_stage/1): the
// photo at full height in a strip that scrolls sideways. Touch scrolls it
// natively; this adds dragging it with a mouse, the wheel scrolling it
// sideways, and opening on its middle, where a panorama's subject usually
// is. The strip is the element itself; the photo is its <img>.
export default {
  mounted() {
    const img = this.el.querySelector("img")
    const centre = () => {
      this.el.scrollLeft = (this.el.scrollWidth - this.el.clientWidth) / 2
      this.progress()
    }
    if (img.complete) centre()
    else img.addEventListener("load", centre, {once: true})

    this.bar = this.el.parentElement.querySelector("[data-role=pano-progress]")
    this.el.addEventListener("scroll", () => this.progress(), {passive: true})

    let drag = null
    this.el.addEventListener("pointerdown", e => {
      if (e.pointerType !== "mouse" || e.button !== 0) return
      drag = {x: e.clientX, left: this.el.scrollLeft, v: 0, t: performance.now()}
      this.el.setPointerCapture(e.pointerId)
      this.el.classList.add("cursor-grabbing")
      cancelAnimationFrame(this.glide)
    })
    this.el.addEventListener("pointermove", e => {
      if (!drag) return
      const now = performance.now()
      const left = drag.left - (e.clientX - drag.x)
      drag.v = (left - this.el.scrollLeft) / Math.max(1, now - drag.t)
      drag.t = now
      this.el.scrollLeft = left
    })
    const release = () => {
      if (!drag) return
      let v = drag.v * 16
      drag = null
      this.el.classList.remove("cursor-grabbing")
      const step = () => {
        if (Math.abs(v) < 0.5) return
        this.el.scrollLeft += v
        v *= 0.92
        this.glide = requestAnimationFrame(step)
      }
      step()
    }
    this.el.addEventListener("pointerup", release)
    this.el.addEventListener("pointercancel", release)

    // A vertical wheel pans it: there is nothing to scroll up and down.
    this.el.addEventListener("wheel", e => {
      if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return
      e.preventDefault()
      this.el.scrollLeft += e.deltaY
    }, {passive: false})
  },

  destroyed() {
    cancelAnimationFrame(this.glide)
  },

  // How far along the strip the view is, as a bar under it.
  progress() {
    if (!this.bar) return
    const range = this.el.scrollWidth
    if (range <= this.el.clientWidth) return this.bar.classList.add("hidden")
    this.bar.style.left = `${(this.el.scrollLeft / range) * 100}%`
    this.bar.style.width = `${(this.el.clientWidth / range) * 100}%`
  }
}