-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
100 lines (91 loc) · 2.76 KB
/
index.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// focus - focusOptions - preventScroll polyfill
(function() {
if (
typeof window === "undefined" ||
typeof document === "undefined" ||
typeof HTMLElement === "undefined"
) {
return;
}
var supportsPreventScrollOption = false;
try {
var focusElem = document.createElement("div");
focusElem.addEventListener(
"focus",
function(event) {
event.preventDefault();
event.stopPropagation();
},
true
);
focusElem.focus(
Object.defineProperty({}, "preventScroll", {
get: function() {
// Edge v18 gives a false positive for supporting inputs
if (
navigator &&
typeof navigator.userAgent !== 'undefined' &&
navigator.userAgent &&
navigator.userAgent.match(/Edge\/1[7-8]/)) {
return supportsPreventScrollOption = false
}
supportsPreventScrollOption = true;
}
})
);
} catch (e) {}
if (
HTMLElement.prototype.nativeFocus === undefined &&
!supportsPreventScrollOption
) {
HTMLElement.prototype.nativeFocus = HTMLElement.prototype.focus;
var calcScrollableElements = function(element) {
var parent = element.parentNode;
var scrollableElements = [];
var rootScrollingElement =
document.scrollingElement || document.documentElement;
while (parent && parent !== rootScrollingElement) {
if (
parent.offsetHeight < parent.scrollHeight ||
parent.offsetWidth < parent.scrollWidth
) {
scrollableElements.push([
parent,
parent.scrollTop,
parent.scrollLeft
]);
}
parent = parent.parentNode;
}
parent = rootScrollingElement;
scrollableElements.push([parent, parent.scrollTop, parent.scrollLeft]);
return scrollableElements;
};
var restoreScrollPosition = function(scrollableElements) {
for (var i = 0; i < scrollableElements.length; i++) {
scrollableElements[i][0].scrollTop = scrollableElements[i][1];
scrollableElements[i][0].scrollLeft = scrollableElements[i][2];
}
scrollableElements = [];
};
var patchedFocus = function(args) {
if (args && args.preventScroll) {
var evScrollableElements = calcScrollableElements(this);
if (typeof setTimeout === 'function') {
var thisElem = this;
setTimeout(function () {
thisElem.nativeFocus();
restoreScrollPosition(evScrollableElements);
}, 0);
} else {
this.nativeFocus();
restoreScrollPosition(evScrollableElements);
}
}
else {
this.nativeFocus();
}
};
HTMLElement.prototype.focus = patchedFocus;
}
})();