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
This commit is contained in:
Stephane Zermatten 2019-01-26 19:14:27 +01:00 committed by Nolan Lawson
parent d976b621b8
commit 2656e11bb0
1 changed files with 12 additions and 7 deletions

View File

@ -3,8 +3,12 @@ import {
getOffsetHeight } from './scrollContainer' getOffsetHeight } from './scrollContainer'
import { smoothScroll } from './smoothScroll' import { smoothScroll } from './smoothScroll'
let mainNavElement
function getTopOverlay () { function getTopOverlay () {
return document.getElementById('main-nav').clientHeight if (!mainNavElement) {
mainNavElement = document.getElementById('main-nav')
}
return mainNavElement.clientHeight
} }
export function isVisible (element) { export function isVisible (element) {
@ -20,6 +24,8 @@ export function isVisible (element) {
export function firstVisibleElementIndex (items, itemElementFunction) { export function firstVisibleElementIndex (items, itemElementFunction) {
let offsetHeight = getOffsetHeight() let offsetHeight = getOffsetHeight()
let topOverlay = getTopOverlay() let topOverlay = getTopOverlay()
let first = -1
let firstComplete = -1
let len = items.length let len = items.length
let i = -1 let i = -1
while (++i < len) { while (++i < len) {
@ -29,14 +35,13 @@ export function firstVisibleElementIndex (items, itemElementFunction) {
} }
let rect = element.getBoundingClientRect() let rect = element.getBoundingClientRect()
if (rect.top < offsetHeight && rect.bottom >= topOverlay) { if (rect.top < offsetHeight && rect.bottom >= topOverlay) {
let firstComplete = i first = i
if (rect.top < topOverlay && i < (len - 1)) { firstComplete = (
firstComplete = i + 1 rect.top < topOverlay && i < (len - 1)) ? i + 1 : i
} break
return { first: i, firstComplete }
} }
} }
return -1 return { first, firstComplete }
} }
export function scrollIntoViewIfNeeded (element) { export function scrollIntoViewIfNeeded (element) {