@primer/react
Version:
An implementation of GitHub's Primer Design System using React
52 lines (46 loc) • 1.48 kB
JavaScript
/*
This file polyfills the following: https://github.com/whatwg/dom/issues/911
Once all targeted browsers support this DOM feature, this polyfill can be deleted.
This allows users to pass an AbortSignal to a call to addEventListener as part of the
AddEventListenerOptions object. When the signal is aborted, the event listener is
removed.
*/
let signalSupported = false;
function noop() {}
try {
const options = Object.create({}, {
signal: {
get() {
signalSupported = true;
}
}
});
window.addEventListener('test', noop, options);
window.removeEventListener('test', noop, options);
} catch (e) {
/* */
}
function featureSupported() {
return signalSupported;
}
function monkeyPatch() {
if (typeof window === 'undefined') {
return;
}
const originalAddEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (name, originalCallback, optionsOrCapture) {
if (typeof optionsOrCapture === 'object' && 'signal' in optionsOrCapture && optionsOrCapture.signal instanceof AbortSignal) {
originalAddEventListener.call(optionsOrCapture.signal, 'abort', () => {
this.removeEventListener(name, originalCallback, optionsOrCapture);
});
}
return originalAddEventListener.call(this, name, originalCallback, optionsOrCapture);
};
}
function polyfill() {
if (!featureSupported()) {
monkeyPatch();
signalSupported = true;
}
}
export { polyfill };