From 2656e11bb04de0ee24f511d953692bc49382cb78 Mon Sep 17 00:00:00 2001 From: Stephane Zermatten Date: Sat, 26 Jan 2019 19:14:27 +0100 Subject: [PATCH] fix: Follow-up for pull request #870 (#910) * Cache main-nav in scrollIntoView.js. This change avoids continuously calling document.getElementById for the same element. * Fix firstVisibleElementIndex to always return a dictionary. Before this change, firstVisibleElementIndex would return -1 if it doesn't find anything. This made no sense since this function returns a dictionary on success. With this change, the function always returns a dictionary with the expected keys. * lint fix --- src/routes/_utils/scrollIntoView.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/routes/_utils/scrollIntoView.js b/src/routes/_utils/scrollIntoView.js index fe49afd2..286c39f9 100644 --- a/src/routes/_utils/scrollIntoView.js +++ b/src/routes/_utils/scrollIntoView.js @@ -3,8 +3,12 @@ import { getOffsetHeight } from './scrollContainer' import { smoothScroll } from './smoothScroll' +let mainNavElement function getTopOverlay () { - return document.getElementById('main-nav').clientHeight + if (!mainNavElement) { + mainNavElement = document.getElementById('main-nav') + } + return mainNavElement.clientHeight } export function isVisible (element) { @@ -20,6 +24,8 @@ export function isVisible (element) { export function firstVisibleElementIndex (items, itemElementFunction) { let offsetHeight = getOffsetHeight() let topOverlay = getTopOverlay() + let first = -1 + let firstComplete = -1 let len = items.length let i = -1 while (++i < len) { @@ -29,14 +35,13 @@ export function firstVisibleElementIndex (items, itemElementFunction) { } let rect = element.getBoundingClientRect() if (rect.top < offsetHeight && rect.bottom >= topOverlay) { - let firstComplete = i - if (rect.top < topOverlay && i < (len - 1)) { - firstComplete = i + 1 - } - return { first: i, firstComplete } + first = i + firstComplete = ( + rect.top < topOverlay && i < (len - 1)) ? i + 1 : i + break } } - return -1 + return { first, firstComplete } } export function scrollIntoViewIfNeeded (element) {