From 4149dcc88019263eefbe086698a1f16c97d36b4b Mon Sep 17 00:00:00 2001
From: Jannick Garthen <jannick.garthen@gmail.com>
Date: Sun, 16 Feb 2020 12:25:09 +0100
Subject: [PATCH] fix(utils): ensure utils exports are always bound to their
 parent object to avoid illegal invocation type errors

Closes #17
---
 lib/utils.ts | 28 ++++++++++++++++------------
 1 file changed, 16 insertions(+), 12 deletions(-)

diff --git a/lib/utils.ts b/lib/utils.ts
index 058868f..cf5fb19 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -162,27 +162,31 @@ export const warnNoResizeObserver = () => {
 type RequestAnimationFrameType = (callback: FrameRequestCallback) => number;
 
 export const requestAnimationFrame = ((): RequestAnimationFrameType => {
-  const fallback = (callback: FrameRequestCallback) =>
-    (setTimeout(callback, 1000 / 60) as unknown) as number;
   if (typeof window !== 'undefined') {
-    return (
+    const nativeRAF =
       window.requestAnimationFrame ||
       window.webkitRequestAnimationFrame ||
-      (<any>window).mozRequestAnimationFrame ||
-      fallback
-    );
+      (<any>window).mozRequestAnimationFrame;
+    if (nativeRAF) {
+      return nativeRAF.bind(window);
+    }
   }
-  return fallback;
+  return function requestAnimationFrameFallback(
+    callback: FrameRequestCallback,
+  ): number {
+    return (setTimeout(callback, 1000 / 60) as unknown) as number;
+  };
 })();
 
 export const cancelAnimationFrame = ((): ((handle: number) => void) => {
   if (typeof window !== 'undefined') {
-    return (
+    const nativeCAF =
       window.cancelAnimationFrame ||
       window.webkitCancelAnimationFrame ||
-      (<any>window).webkitCancelRequestAnimationFrame ||
-      clearTimeout
-    );
+      (<any>window).webkitCancelRequestAnimationFrame;
+    if (nativeCAF) {
+      return nativeCAF.bind(window);
+    }
   }
   return clearTimeout;
 })();
@@ -190,7 +194,7 @@ export const cancelAnimationFrame = ((): ((handle: number) => void) => {
 export const now =
   typeof performance !== 'undefined' && performance.now
     ? performance.now.bind(performance)
-    : Date.now;
+    : Date.now.bind(Date);
 export const createPerformanceMarker = () => {
   const start = now();
   return () => now() - start;