From 82cdbe9d2647354e10c36a653c5efc1c1f83bffb Mon Sep 17 00:00:00 2001 From: Levi Thomason Date: Wed, 22 Feb 2017 17:15:09 -0800 Subject: [PATCH] docs(Layout): fix scroll to anchor --- docs/app/Components/Layout.js | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/docs/app/Components/Layout.js b/docs/app/Components/Layout.js index d72421cf85..dd135c2310 100644 --- a/docs/app/Components/Layout.js +++ b/docs/app/Components/Layout.js @@ -28,27 +28,39 @@ export default class Layout extends Component { } resetPage = () => { - window.scrollTo(0, 0) + clearTimeout(this.scrollStartTimeout) + + scrollTo(0, 0) + anchors .add('h2, h3, h4, h5, h6') .remove([1, 2, 3, 4, 5, 6].map(n => `.rendered-example h${n}`).join(', ')) .remove('.no-anchor') - this.scrollStartTimeout = setTimeout(this.scrollToAnchor(), 2000) + this.scrollStartTimeout = setTimeout(this.scrollToAnchor, 500) } scrollToAnchor = () => { const anchor = location.hash && document.querySelector(location.hash) + // no scroll to target, stop if (!anchor) return const elementTop = Math.round(anchor.getBoundingClientRect().top) - if (elementTop !== 0) { - const step = Math.ceil(elementTop / Math.max(15 - Math.log(elementTop), 1)) - window.scrollBy(0, step) - requestAnimationFrame(this.scrollToAnchor) - } + // scrolled to element, stop + if (elementTop === 0) return + + // hit max scroll boundaries, stop + const isScrolledToTop = scrollY === 0 + const isScrolledToBottom = scrollY + document.body.clientHeight === document.body.scrollHeight + const scrollStep = Math.ceil((Math.abs(elementTop / 8))) * Math.sign(elementTop) + + if (isScrolledToBottom && scrollStep > 0 || isScrolledToTop && scrollStep < 0) return + + // more scrolling to do! + scrollBy(0, scrollStep) + requestAnimationFrame(this.scrollToAnchor) } render() {