-
Notifications
You must be signed in to change notification settings - Fork 47
/
index.js
53 lines (43 loc) · 1.81 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
import { eventListenerOptionsSupported, noop } from './utils';
const defaultOptions = {
passive: true,
capture: false
};
const supportedPassiveTypes = [
'scroll', 'wheel',
'touchstart', 'touchmove', 'touchenter', 'touchend', 'touchleave',
'mouseout', 'mouseleave', 'mouseup', 'mousedown', 'mousemove', 'mouseenter', 'mousewheel', 'mouseover'
];
const getDefaultPassiveOption = (passive, eventName) => {
if (passive !== undefined) return passive;
return supportedPassiveTypes.indexOf(eventName) === -1 ? false : defaultOptions.passive;
};
const getWritableOptions = (options) => {
const passiveDescriptor = Object.getOwnPropertyDescriptor(options, 'passive');
return passiveDescriptor && passiveDescriptor.writable !== true && passiveDescriptor.set === undefined
? Object.assign({}, options)
: options;
};
const prepareSafeListener = (listener, passive) => {
if (!passive) return listener;
return function (e) {
e.preventDefault = noop;
return listener.call(this, e);
};
};
const overwriteAddEvent = (superMethod) => {
EventTarget.prototype.addEventListener = function (type, listener, options) {
const usesListenerOptions = typeof options === 'object' && options !== null;
const useCapture = usesListenerOptions ? options.capture : options;
options = usesListenerOptions ? getWritableOptions(options) : {};
options.passive = getDefaultPassiveOption(options.passive, type);
options.capture = useCapture === undefined ? defaultOptions.capture : useCapture;
listener = prepareSafeListener(listener, options.passive);
superMethod.call(this, type, listener, options);
};
};
const supportsPassive = eventListenerOptionsSupported();
if (supportsPassive) {
const addEvent = EventTarget.prototype.addEventListener;
overwriteAddEvent(addEvent);
}