import Ticker from './Ticker.js';

const animate = (object, keyframes, { duration = 0, delay = 0, easing = (x) => x, onupdate = () => { } } = {}) => {
  let finishedResolve;
  const finished = new Promise((resolve) => finishedResolve = resolve);
  let time = 0;
  const keyframesMap = new Map(Object.entries(keyframes));
  for (const [key, value] of keyframesMap) {
    if (!(value instanceof Array)) {
      keyframesMap.set(key, [object[key], value]);
    }
  }
  const update = () => {
    duration = duration || 1;
    time += Ticker.deltaTime * 1000;

    let progress;
    if (time >= delay + duration) {
      Ticker.delete(update);
      progress = 1;
    } else {
      progress = Math.max(time - delay, 0) / duration;
      progress = easing(progress);
    }

    for (const [key, value] of keyframesMap) {
      object[key] = (value[1] - value[0]) * progress + value[0];
    }

    onupdate();

    if (progress === 1) {
      finishedResolve();
    }
  };

  update();
  Ticker.add(update);

  return {
    finished,
  };
};


export { animate };

@@ -28,16 +28,58 @@
 r.js';%0A%0A
+const keyframesSetObjectMap = new Map();%0A%0A
 const an
@@ -186,16 +186,16 @@
 %7D) =%3E %7B%0A
-
   let fi
@@ -356,16 +356,85 @@
 ames));%0A
+  /**%0A   * Set init value as current value if it doesn't exist%0A   */%0A
   for (c
@@ -568,16 +568,518 @@
   %7D%0A  %7D%0A
+  /**%0A   * Overwrite keyframes%0A   */%0A  let keyframesSet = keyframesSetObjectMap.get(object);%0A  if (!keyframesSet) %7B%0A    keyframesSet = new Set();%0A    keyframesSetObjectMap.set(object, keyframesSet);%0A  %7D%0A  for (const key of keyframesMap.keys()) %7B%0A    for (const previousKeyframes of keyframesSet) %7B%0A      previousKeyframes.delete(key);%0A      if (!previousKeyframes.size) %7B%0A        keyframesSet.delete(previousKeyframes);%0A      %7D%0A    %7D%0A  %7D%0A  keyframesSet.add(keyframesMap);%0A%0A  /**%0A   * Update loop%0A   */%0A
   const 
@@ -1221,37 +1221,8 @@
 ) %7B%0A
-      Ticker.delete(update);%0A
     
@@ -1505,24 +1505,180 @@
 ss === 1) %7B%0A
+      Ticker.delete(update);%0A      keyframesSet.delete(keyframesMap);%0A      if (!keyframesSet.size) %7B%0A        keyframesSetObjectMap.delete(object);%0A      %7D%0A
       finish
@@ -1748,16 +1748,16 @@
 eturn %7B%0A
-
     fini
@@ -1762,16 +1762,72 @@
 nished,%0A
+    cancel: () =%3E %7B%0A      Ticker.delete(update);%0A    %7D,%0A
   %7D;%0A%7D;%0A

update animate with properties override