allow scroll-to-top to be canceled by a user scroll (#79)

This commit is contained in:
codl 2018-04-12 04:43:22 +02:00 committed by Nolan Lawson
parent 01fe4e5729
commit 6fcecce311

View file

@ -13,7 +13,12 @@ const scroll = (node, key, target) => {
const elapsed = Date.now() - startTime const elapsed = Date.now() - startTime
const percentage = elapsed / duration const percentage = elapsed / duration
if (percentage > 1 || interrupt) { if (interrupt) {
return
}
if (percentage > 1) {
cleanup()
return return
} }
@ -21,11 +26,22 @@ const scroll = (node, key, target) => {
requestAnimationFrame(step) requestAnimationFrame(step)
} }
const cancel = () => {
interrupt = true
cleanup()
}
const cleanup = () => {
node.removeEventListener('wheel', cancel)
node.removeEventListener('touchstart', cancel)
}
node.addEventListener('wheel', cancel, {passive: true})
node.addEventListener('touchstart', cancel, {passive: true})
step() step()
return () => { return cancel
interrupt = true
}
} }
export const smoothScrollToTop = node => scroll(node, 'scrollTop', 0) export const smoothScrollToTop = node => scroll(node, 'scrollTop', 0)