Skip to content

Commit

Permalink
0.3.4
Browse files Browse the repository at this point in the history
* Ensuring polyfills are SSR safe
  • Loading branch information
atomicpages committed Sep 10, 2019
1 parent fd1065a commit 3b88895
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 19 deletions.
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
import { useShuttleState } from './components/Shuttle/hooks/useShuttleState';
import { useShuttleKeyboardControls } from './components/Shuttle/hooks/useShuttleKeyboardControls';
import { Shuttle } from './components/Shuttle/Shuttle';
import { polyfill } from './utils/polyfills';

export { Shuttle, useShuttleState, useShuttleKeyboardControls };
polyfill();
40 changes: 40 additions & 0 deletions src/utils/polyfills.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const __CLIENT__ = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);

function matchPolyfill() {
if (typeof Element.prototype.matches !== 'function') {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
Element.prototype.matches = Element.prototype.matches =
// @ts-ignore
Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
}

function closestPolyfill() {
if (typeof Element.prototype.closest !== 'function') {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
Element.prototype.closest = function closest(selector: string) {
let element: any = this;

do {
if (element.matches(selector)) {
return element;
}

element = element.parentElement || element.parentNode;
} while (element !== null && element.nodeType === 1);

return null;
};
}
}

export function polyfill() {
if (__CLIENT__) {
matchPolyfill();
closestPolyfill();
}
}
19 changes: 0 additions & 19 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,22 +165,3 @@ export const isContainer = (container: HTMLDivElement) => {

return bool && (name === SHUTTLE_CONTAINERS.SOURCE || name === SHUTTLE_CONTAINERS.TARGET);
};

// IE 9+ polyfill for closest
// https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
if (!Element.prototype.closest) {
Element.prototype.closest = function(selector: string) {
// @ts-ignore
let el: any = this;

do {
if (el.matches(selector)) {
return el;
}

el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);

return null;
};
}

0 comments on commit 3b88895

Please sign in to comment.