UNPKG

2.4 kBPlain TextView Raw
1/*
2 * Copyright 2020 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13/**
14 * Scrolls `scrollView` so that `element` is visible.
15 * Similar to `element.scrollIntoView({block: 'nearest'})` (not supported in Edge),
16 * but doesn't affect parents above `scrollView`.
17 */
18export function scrollIntoView(scrollView: HTMLElement, element: HTMLElement) {
19 let offsetX = relativeOffset(scrollView, element, 'left');
20 let offsetY = relativeOffset(scrollView, element, 'top');
21 let width = element.offsetWidth;
22 let height = element.offsetHeight;
23 let x = scrollView.scrollLeft;
24 let y = scrollView.scrollTop;
25 let maxX = x + scrollView.offsetWidth;
26 let maxY = y + scrollView.offsetHeight;
27
28 if (offsetX <= x) {
29 x = offsetX;
30 } else if (offsetX + width > maxX) {
31 x += offsetX + width - maxX;
32 }
33 if (offsetY <= y) {
34 y = offsetY;
35 } else if (offsetY + height > maxY) {
36 y += offsetY + height - maxY;
37 }
38
39 scrollView.scrollLeft = x;
40 scrollView.scrollTop = y;
41}
42
43/**
44 * Computes the offset left or top from child to ancestor by accumulating
45 * offsetLeft or offsetTop through intervening offsetParents.
46 */
47function relativeOffset(ancestor: HTMLElement, child: HTMLElement, axis: 'left'|'top') {
48 const prop = axis === 'left' ? 'offsetLeft' : 'offsetTop';
49 let sum = 0;
50 while (child.offsetParent) {
51 sum += child[prop];
52 if (child.offsetParent === ancestor) {
53 // Stop once we have found the ancestor we are interested in.
54 break;
55 } else if (child.offsetParent.contains(ancestor)) {
56 // If the ancestor is not `position:relative`, then we stop at
57 // _its_ offset parent, and we subtract off _its_ offset, so that
58 // we end up with the proper offset from child to ancestor.
59 sum -= ancestor[prop];
60 break;
61 }
62 child = child.offsetParent as HTMLElement;
63 }
64 return sum;
65}