All files / menu utils.js

80% Statements 12/15
58.33% Branches 7/12
100% Functions 1/1
85.71% Lines 12/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                    17x 17x                                     4x   4x 4x     4x 2x     2x 2x       2x 2x     2x        
/*
Copyright (c) 2018-2019 Uber Technologies, Inc.
 
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
/* eslint-disable import/prefer-default-export */
import smoothscroll from 'smoothscroll-polyfill';
 
Eif (__BROWSER__) {
  smoothscroll.polyfill();
}
 
// Helps scroll a list item into view when cycling through list via
// keybindings and highlighted item is not in view.
 
// Previously, this util had been using `scrollIntoView`. The issue with that method is that
// it will not only scroll the parent scroll but also the window scroll bar - causing a jump.
// problem description https://lists.w3.org/Archives/Public/www-style/2014Jul/0386.html
 
// CHASE: I've noticed some performance issues when testing this with many items in the list.
// I imagine the browser can debounce the `node.scrollIntoView` calls. Callers of this function
// will likely want to debounce themselves.
export function scrollItemIntoView(
  child: ?HTMLElement,
  parent: HTMLElement,
  isFirst?: boolean,
  isLast?: boolean,
) {
  Iif (!child) return;
 
  const childRect = child.getBoundingClientRect();
  const parentRect = parent.getBoundingClientRect();
 
  // while scrolling down, if element is below view
  if (childRect.bottom > parentRect.bottom) {
    Iif (isLast) {
      parent.scrollTop = parent.scrollHeight - parentRect.height;
    } else {
      const targetBottom = child.offsetTop + childRect.height;
      parent.scrollTop = targetBottom - parentRect.height;
    }
 
    // while scrolling up, if element is above view
  } else Eif (childRect.top < parentRect.top) {
    Iif (isFirst) {
      parent.scrollTop = 0;
    } else {
      parent.scrollTop = child.offsetTop;
    }
  }
}