feat: drag the timeline with the mouse

This commit is contained in:
fromme committed 2026-11-12 11:14:25 +01:00
1 parent e976342c09
commit 9ba6529ee0
3 files changed
+95 -1

No files matched your search

@@ -1,12 +1,26 @@
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) {
@@ -23,4 +37,72 @@ export default class extends Controller {
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()
}
}