1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | import {FocusableElement} from '@react-types/shared';
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | interface ScrollableElement {
|
26 | element: HTMLElement,
|
27 | scrollTop: number,
|
28 | scrollLeft: number
|
29 | }
|
30 |
|
31 | export function focusWithoutScrolling(element: FocusableElement) {
|
32 | if (supportsPreventScroll()) {
|
33 | element.focus({preventScroll: true});
|
34 | } else {
|
35 | let scrollableElements = getScrollableElements(element);
|
36 | element.focus();
|
37 | restoreScrollPosition(scrollableElements);
|
38 | }
|
39 | }
|
40 |
|
41 | let supportsPreventScrollCached: boolean = null;
|
42 | function supportsPreventScroll() {
|
43 | if (supportsPreventScrollCached == null) {
|
44 | supportsPreventScrollCached = false;
|
45 | try {
|
46 | var focusElem = document.createElement('div');
|
47 | focusElem.focus({
|
48 | get preventScroll() {
|
49 | supportsPreventScrollCached = true;
|
50 | return true;
|
51 | }
|
52 | });
|
53 | } catch (e) {
|
54 |
|
55 | }
|
56 | }
|
57 |
|
58 | return supportsPreventScrollCached;
|
59 | }
|
60 |
|
61 | function getScrollableElements(element: FocusableElement): ScrollableElement[] {
|
62 | var parent = element.parentNode;
|
63 | var scrollableElements: ScrollableElement[] = [];
|
64 | var rootScrollingElement = document.scrollingElement || document.documentElement;
|
65 |
|
66 | while (parent instanceof HTMLElement && parent !== rootScrollingElement) {
|
67 | if (
|
68 | parent.offsetHeight < parent.scrollHeight ||
|
69 | parent.offsetWidth < parent.scrollWidth
|
70 | ) {
|
71 | scrollableElements.push({
|
72 | element: parent,
|
73 | scrollTop: parent.scrollTop,
|
74 | scrollLeft: parent.scrollLeft
|
75 | });
|
76 | }
|
77 | parent = parent.parentNode;
|
78 | }
|
79 |
|
80 | if (rootScrollingElement instanceof HTMLElement) {
|
81 | scrollableElements.push({
|
82 | element: rootScrollingElement,
|
83 | scrollTop: rootScrollingElement.scrollTop,
|
84 | scrollLeft: rootScrollingElement.scrollLeft
|
85 | });
|
86 | }
|
87 |
|
88 | return scrollableElements;
|
89 | }
|
90 |
|
91 | function restoreScrollPosition(scrollableElements: ScrollableElement[]) {
|
92 | for (let {element, scrollTop, scrollLeft} of scrollableElements) {
|
93 | element.scrollTop = scrollTop;
|
94 | element.scrollLeft = scrollLeft;
|
95 | }
|
96 | }
|