UNPKG

1.99 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.scrollItemIntoView = scrollItemIntoView;
7
8/*
9Copyright (c) 2018-2020 Uber Technologies, Inc.
10
11This source code is licensed under the MIT license found in the
12LICENSE file in the root directory of this source tree.
13*/
14
15/* eslint-disable import/prefer-default-export */
16// Helps scroll a list item into view when cycling through list via
17// keybindings and highlighted item is not in view.
18// Previously, this util had been using `scrollIntoView`. The issue with that method is that
19// it will not only scroll the parent scroll but also the window scroll bar - causing a jump.
20// problem description https://lists.w3.org/Archives/Public/www-style/2014Jul/0386.html
21// CHASE: I've noticed some performance issues when testing this with many items in the list.
22// I imagine the browser can debounce the `node.scrollIntoView` calls. Callers of this function
23// will likely want to debounce themselves.
24function scrollItemIntoView(child, parent, isFirst, isLast) {
25 var scrollAlignInView = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'auto';
26 if (!child) return;
27 var childRect = child.getBoundingClientRect();
28 var parentRect = parent.getBoundingClientRect(); // while scrolling down, if element is below view
29
30 if (childRect.bottom > parentRect.bottom) {
31 if (isLast) {
32 parent.scrollTop = parent.scrollHeight - parentRect.height;
33 } else {
34 var targetBottom = child.offsetTop + childRect.height;
35 parent.scrollTop = targetBottom - (scrollAlignInView === 'center' ? Math.round((parentRect.height + childRect.height) / 2) : parentRect.height);
36 } // while scrolling up, if element is above view
37
38 } else if (childRect.top < parentRect.top) {
39 if (isFirst) {
40 parent.scrollTop = 0;
41 } else {
42 parent.scrollTop = child.offsetTop - (scrollAlignInView === 'center' ? Math.round((parentRect.height - childRect.height) / 2) : 0);
43 }
44 }
45}
\No newline at end of file