fix animated scrolling (#2780)

This commit is contained in:
Felix Häusler 2021-12-25 14:45:42 +01:00 committed by GitHub
parent 2287780248
commit f89ec51938
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 27 deletions

View File

@ -693,7 +693,13 @@ export default {
this.editor.on('selectionChange', changes => {
const { y } = changes.cursorCoords
if (this.typewriter) {
animatedScrollTo(container, container.scrollTop + y - STANDAR_Y, 100)
const startPosition = container.scrollTop
const toPosition = startPosition + y - STANDAR_Y
// Prevent micro shakes and unnecessary scrolling.
if (Math.abs(startPosition - toPosition) > 2) {
animatedScrollTo(container, toPosition, 100)
}
}
// Used to fix #628: auto scroll cursor to visible if the cursor is too low.

View File

@ -19,14 +19,6 @@ export const delay = time => {
return p
}
// help functions
const easeInOutQuad = function (t, b, c, d) {
t /= d / 2
if (t < 1) return c / 2 * t * t + b
t--
return -c / 2 * (t * (t - 2) - 1) + b
}
const ID_PREFEX = 'mt-'
let id = 0
const DOTU = 'DOTU'
@ -160,35 +152,36 @@ export const animatedScrollTo = function (element, to, duration, callback) {
const start = element.scrollTop
const change = to - start
const animationStart = +new Date()
let animating = true
let lastpos = null
// Prevent animation on small steps
if (Math.abs(change) <= 6) {
element.scrollTop = to
return
}
const easeInOutQuad = function (t, b, c, d) {
t /= d / 2
if (t < 1) return (c / 2) * t * t + b
t--
return (-c / 2) * (t * (t - 2) - 1) + b
}
const animateScroll = function () {
if (!animating) {
return
}
requestAnimationFrame(animateScroll)
const now = +new Date()
const val = Math.floor(easeInOutQuad(now - animationStart, start, change, duration))
if (lastpos) {
if (lastpos === element.scrollTop) {
lastpos = val
element.scrollTop = val
} else {
animating = false
}
} else {
lastpos = val
element.scrollTop = val
}
element.scrollTop = val
if (now > animationStart + duration) {
element.scrollTop = to
animating = false
if (callback) {
callback()
}
} else {
requestAnimationFrame(animateScroll)
}
}
requestAnimationFrame(animateScroll)
}