Skip to content

Commit

Permalink
fix: only bind passive events when supported
Browse files Browse the repository at this point in the history
  • Loading branch information
guidobouman committed May 8, 2018
1 parent d1a514e commit 8ad9ebf
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/panelSnap.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
getTargetScrollTop,
getElementsInContainerViewport,
elementFillsContainer,
passiveIsSupported,
} from './utilities';

let INSTANCE_COUNTER = 0;
Expand Down Expand Up @@ -49,7 +50,7 @@ export default class PanelSnap {

this.container.addEventListener('mouseup', this.onMouseUp.bind(this));
this.container.addEventListener('mousedown', this.onMouseDown.bind(this));
this.scrollContainer.addEventListener('wheel', this.onWheel.bind(this), { passive: true });
this.scrollContainer.addEventListener('wheel', this.onWheel.bind(this), passiveIsSupported && { passive: true });
}

on(name, handler) {
Expand Down
21 changes: 21 additions & 0 deletions src/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,24 @@ export function elementFillsContainer(container, element) {
elementRect.right >= containerRect.right
);
}

// Taken from MDN
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
export const passiveIsSupported = (function () {
let isSupported = false;

try {
const options = Object.defineProperty({}, 'passive', {
get() { // eslint-disable-line getter-return
isSupported = true;
},
});

window.addEventListener('test', null, options);
window.removeEventListener('test', null, options);
} catch (e) {
// Do nothing
}

return isSupported;
}());
7 changes: 7 additions & 0 deletions src/utilities.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
getTargetScrollTop,
getElementsInContainerViewport,
elementFillsContainer,
passiveIsSupported,
} from './utilities';

const SCREEN_WIDTH = 800;
Expand Down Expand Up @@ -229,3 +230,9 @@ describe('elementFillsContainer', () => {
expect(elementFillsContainer(container, getElement(99, 499))).toBe(false);
});
});

describe('isPassiveSupported', () => {
test('returns false in JSDOM', () => {
expect(passiveIsSupported).toBe(false);
});
});

0 comments on commit 8ad9ebf

Please sign in to comment.