From a7e4b7f0e87b6cc35e7d4622492f5f77d1fda367 Mon Sep 17 00:00:00 2001 From: James Magahern Date: Wed, 10 Mar 2021 16:17:22 -0800 Subject: [PATCH] Smooth scrolling --- App/Resources/Tagger.js | 69 +++++++++++++++++++++++++++++++++++------ 1 file changed, 60 insertions(+), 9 deletions(-) diff --git a/App/Resources/Tagger.js b/App/Resources/Tagger.js index 39101fb..2feb97d 100644 --- a/App/Resources/Tagger.js +++ b/App/Resources/Tagger.js @@ -150,8 +150,62 @@ class ElementTagger { } } +class Scroller +{ + constructor() { + this.modelPositionY = 0; + this.modelPositionX = 0; + } + + scrollBy(xOffset, yOffset) { + var initialPositionY = this.modelPositionY; + var initialPositionX = this.modelPositionX; + if (this.timerIdentifier == undefined) { + this.startTimer(); + + initialPositionY = window.scrollY; + initialPositionX = window.scrollX; + } + + this.modelPositionY = initialPositionY + yOffset; + this.modelPositionY = Math.max( + 0, Math.min( + this.modelPositionY, document.documentElement.scrollHeight - window.visualViewport.height + ) + ); + + this.modelPositionX = initialPositionX + xOffset; + this.modelPositionX = Math.max( + 0, Math.min( + this.modelPositionX, document.documentElement.scrollWidth - window.visualViewport.width + ) + ); + } + + startTimer() { + this.timerIdentifier = setInterval(this.updateTimer, (30 / 1000), this); + } + + stopTimer() { + clearInterval(this.timerIdentifier); + this.timerIdentifier = undefined; + } + + updateTimer(self) { + const accelerationFactor = 0.05; + let positionOffsetY = (self.modelPositionY - window.scrollY) * accelerationFactor; + let positionOffsetX = (self.modelPositionX - window.scrollX) * accelerationFactor; + window.scrollBy(positionOffsetX, positionOffsetY); + + if (Math.abs(positionOffsetX) <= 1.0 && Math.abs(positionOffsetY) <= 1.0) { + self.stopTimer(); + } + } +} + (function() { let tagger = new ElementTagger(); + let scroller = new Scroller(); var tagAccum = []; document.addEventListener('keypress', (event) => { @@ -181,22 +235,19 @@ class ElementTagger { } } else { // Otherwise, interpret as a single character command - + let lowerKey = keyName.toLowerCase(); let scrollAmount = event.shiftKey ? window.visualViewport.height : 30; - - var scrollOptions = { behavior: 'smooth' }; // currently doesn't work with WebKit + if (lowerKey == 'j') { - scrollOptions.top = scrollAmount; + scroller.scrollBy(0, scrollAmount); } else if (lowerKey == 'k') { - scrollOptions.top = -scrollAmount; + scroller.scrollBy(0, -scrollAmount); } else if (lowerKey == 'h') { - scrollOptions.left = -scrollAmount; + scroller.scrollBy(-scrollAmount, 0); } else if (lowerKey == 'l') { - scrollOptions.left = scrollAmount; + scroller.scrollBy(scrollAmount, 0); } - - window.scrollBy(scrollOptions); } });