forked from willmcpo/body-scroll-lock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbodyScrollLock.js
239 lines (198 loc) · 7.6 KB
/
bodyScrollLock.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// @flow
// Adopted and modified solution from Bohdan Didukh (2017)
// https://stackoverflow.com/questions/41594997/ios-10-safari-prevent-scrolling-behind-a-fixed-overlay-and-maintain-scroll-posi
export interface BodyScrollOptions {
reserveScrollBarGap?: boolean;
allowTouchMove?: (el: any) => boolean;
}
interface Lock {
targetElement: any;
options: BodyScrollOptions;
}
// Older browsers don't support event options, feature detect it.
let hasPassiveEvents = false;
if (typeof window !== 'undefined') {
const passiveTestOptions = {
get passive() {
hasPassiveEvents = true;
return undefined;
},
};
window.addEventListener('testPassive', null, passiveTestOptions);
window.removeEventListener('testPassive', null, passiveTestOptions);
}
const isIosDevice =
typeof window !== 'undefined' &&
window.navigator &&
window.navigator.platform &&
/iP(ad|hone|od)/.test(window.navigator.platform);
type HandleScrollEvent = TouchEvent;
let locks: Array<Lock> = [];
let documentListenerAdded: boolean = false;
let initialClientY: number = -1;
let previousBodyOverflowSetting;
let previousBodyPaddingRight;
// returns true if `el` should be allowed to receive touchmove events
const allowTouchMove = (el: EventTarget): boolean =>
locks.some(lock => {
if (lock.options.allowTouchMove && lock.options.allowTouchMove(el)) {
return true;
}
return false;
});
const preventDefault = (rawEvent: HandleScrollEvent): boolean => {
const e = rawEvent || window.event;
// For the case whereby consumers adds a touchmove event listener to document.
// Recall that we do document.addEventListener('touchmove', preventDefault, { passive: false })
// in disableBodyScroll - so if we provide this opportunity to allowTouchMove, then
// the touchmove event on document will break.
if (allowTouchMove(e.target)) {
return true;
}
// Do not prevent if the event has more than one touch (usually meaning this is a multi touch gesture like pinch to zoom)
if (e.touches.length > 1) return true;
if (e.preventDefault) e.preventDefault();
return false;
};
const setOverflowHidden = (options?: BodyScrollOptions) => {
// Setting overflow on body/documentElement synchronously in Desktop Safari slows down
// the responsiveness for some reason. Setting within a setTimeout fixes this.
setTimeout(() => {
// If previousBodyPaddingRight is already set, don't set it again.
if (previousBodyPaddingRight === undefined) {
const reserveScrollBarGap = !!options && options.reserveScrollBarGap === true;
const scrollBarGap = window.innerWidth - document.documentElement.clientWidth;
if (reserveScrollBarGap && scrollBarGap > 0) {
previousBodyPaddingRight = document.body.style.paddingRight;
document.body.style.paddingRight = `${scrollBarGap}px`;
}
}
// If previousBodyOverflowSetting is already set, don't set it again.
if (previousBodyOverflowSetting === undefined) {
previousBodyOverflowSetting = document.body.style.overflow;
document.body.style.overflow = 'hidden';
}
});
};
const restoreOverflowSetting = () => {
// Setting overflow on body/documentElement synchronously in Desktop Safari slows down
// the responsiveness for some reason. Setting within a setTimeout fixes this.
setTimeout(() => {
if (previousBodyPaddingRight !== undefined) {
document.body.style.paddingRight = previousBodyPaddingRight;
// Restore previousBodyPaddingRight to undefined so setOverflowHidden knows it
// can be set again.
previousBodyPaddingRight = undefined;
}
if (previousBodyOverflowSetting !== undefined) {
document.body.style.overflow = previousBodyOverflowSetting;
// Restore previousBodyOverflowSetting to undefined
// so setOverflowHidden knows it can be set again.
previousBodyOverflowSetting = undefined;
}
});
};
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions
const isTargetElementTotallyScrolled = (targetElement: any): boolean =>
targetElement ? targetElement.scrollHeight - targetElement.scrollTop <= targetElement.clientHeight : false;
const handleScroll = (event: HandleScrollEvent, targetElement: any): boolean => {
const clientY = event.targetTouches[0].clientY - initialClientY;
if (allowTouchMove(event.target)) {
return false;
}
if (targetElement && targetElement.scrollTop === 0 && clientY > 0) {
// element is at the top of its scroll
return preventDefault(event);
}
if (isTargetElementTotallyScrolled(targetElement) && clientY < 0) {
// element is at the top of its scroll
return preventDefault(event);
}
event.stopPropagation();
return true;
};
export const disableBodyScroll = (targetElement: any, options?: BodyScrollOptions): void => {
if (isIosDevice) {
// targetElement must be provided, and disableBodyScroll must not have been
// called on this targetElement before.
if (!targetElement) {
// eslint-disable-next-line no-console
console.error(
'disableBodyScroll unsuccessful - targetElement must be provided when calling disableBodyScroll on IOS devices.'
);
return;
}
if (targetElement && !locks.some(lock => lock.targetElement === targetElement)) {
const lock = {
targetElement,
options: options || {},
};
locks = [...locks, lock];
targetElement.ontouchstart = (event: HandleScrollEvent) => {
if (event.targetTouches.length === 1) {
// detect single touch
initialClientY = event.targetTouches[0].clientY;
}
};
targetElement.ontouchmove = (event: HandleScrollEvent) => {
if (event.targetTouches.length === 1) {
// detect single touch
handleScroll(event, targetElement);
}
};
if (!documentListenerAdded) {
document.addEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
documentListenerAdded = true;
}
}
} else {
setOverflowHidden(options);
const lock = {
targetElement,
options: options || {},
};
locks = [...locks, lock];
}
};
export const clearAllBodyScrollLocks = (): void => {
if (isIosDevice) {
// Clear all locks ontouchstart/ontouchmove handlers, and the references
locks.forEach((lock: Lock) => {
lock.targetElement.ontouchstart = null;
lock.targetElement.ontouchmove = null;
});
if (documentListenerAdded) {
document.removeEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
documentListenerAdded = false;
}
locks = [];
// Reset initial clientY
initialClientY = -1;
} else {
restoreOverflowSetting();
locks = [];
}
};
export const enableBodyScroll = (targetElement: any): void => {
if (isIosDevice) {
if (!targetElement) {
// eslint-disable-next-line no-console
console.error(
'enableBodyScroll unsuccessful - targetElement must be provided when calling enableBodyScroll on IOS devices.'
);
return;
}
targetElement.ontouchstart = null;
targetElement.ontouchmove = null;
locks = locks.filter(lock => lock.targetElement !== targetElement);
if (documentListenerAdded && locks.length === 0) {
document.removeEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
documentListenerAdded = false;
}
} else if (locks.length === 1 && locks[0].targetElement === targetElement) {
restoreOverflowSetting();
locks = [];
} else {
locks = locks.filter(lock => lock.targetElement !== targetElement);
}
};