From 3b8889586ef8e6c4c9b6816e737819ce2040af07 Mon Sep 17 00:00:00 2001 From: atomicpages Date: Tue, 10 Sep 2019 08:53:20 -0700 Subject: [PATCH] 0.3.4 * Ensuring polyfills are SSR safe --- src/index.ts | 2 ++ src/utils/polyfills.ts | 40 ++++++++++++++++++++++++++++++++++++++++ src/utils/utils.ts | 19 ------------------- 3 files changed, 42 insertions(+), 19 deletions(-) create mode 100644 src/utils/polyfills.ts diff --git a/src/index.ts b/src/index.ts index 2b95d58..e158163 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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(); diff --git a/src/utils/polyfills.ts b/src/utils/polyfills.ts new file mode 100644 index 0000000..be82e9c --- /dev/null +++ b/src/utils/polyfills.ts @@ -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(); + } +} diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 807ce2a..3248861 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -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; - }; -}