import { Controller } from '@hotwired/stimulus' // pixels the mouse has to move before a press becomes a drag, so clicks on bars still work const DRAG_THRESHOLD = 4 export default class extends Controller { static targets = [ 'scroller', 'today' ] connect() { this.drag = null this.suppressClick = this.suppressClick.bind(this) requestAnimationFrame(() => this.scrollToToday({ behavior: 'instant' })) } scrollerTargetConnected(scroller) { // capture phase, so a drag ending on a link or button does not also open it scroller.addEventListener('click', this.suppressClick, true) } scrollerTargetDisconnected(scroller) { scroller.removeEventListener('click', this.suppressClick, true) } // centres today's column; the house column stays in front of the left part scrollToToday({ behavior = 'smooth' } = {}) { if (false === this.hasScrollerTarget || false === this.hasTodayTarget) { return } const scroller = this.scrollerTarget const scrollerRect = scroller.getBoundingClientRect() const todayRect = this.todayTarget.getBoundingClientRect() const scrollLeft = todayRect.left - scrollerRect.left + scroller.scrollLeft const centered = scrollLeft - (scroller.clientWidth / 2) + (todayRect.width / 2) const maxScrollLeft = scroller.scrollWidth - scroller.clientWidth scroller.scrollTo({ left: Math.min(Math.max(0, centered), maxScrollLeft), behavior }) } // pressing the mouse button on the timeline and moving drags it along; touch scrolls natively startDrag(event) { if (0 !== event.button || 'mouse' !== event.pointerType) { return } // a drag without a following click must not swallow the next one this.dragged = false this.drag = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, scrollLeft: this.scrollerTarget.scrollLeft, scrollTop: this.scrollerTarget.scrollTop, moved: false, } } moveDrag(event) { if (null === this.drag || event.pointerId !== this.drag.pointerId) { return } const dx = event.clientX - this.drag.x const dy = event.clientY - this.drag.y if (false === this.drag.moved) { if (Math.hypot(dx, dy) < DRAG_THRESHOLD) { return } this.drag.moved = true this.scrollerTarget.setPointerCapture(event.pointerId) this.scrollerTarget.classList.add('timeline--dragging') window.getSelection()?.removeAllRanges() } this.scrollerTarget.scrollLeft = this.drag.scrollLeft - dx this.scrollerTarget.scrollTop = this.drag.scrollTop - dy } endDrag(event) { if (null === this.drag || event.pointerId !== this.drag.pointerId) { return } this.dragged = this.drag.moved this.drag = null this.scrollerTarget.classList.remove('timeline--dragging') if (this.scrollerTarget.hasPointerCapture(event.pointerId)) { this.scrollerTarget.releasePointerCapture(event.pointerId) } } // links are draggable by default, which would take over the press preventNativeDrag(event) { event.preventDefault() } suppressClick(event) { if (true !== this.dragged) { return } this.dragged = false event.preventDefault() event.stopPropagation() } }