<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style type="text/css">
      #target {
        background: green;
        height:  50px;
        width:  50px;
      }
  </style>
</head>
<body>
  <div id="target"></div>
</body>
<script src="../../../testcommon.js"></script>
<script type="text/javascript">
  function sendResult(message) {
    top.postMessage(message, '*');
  }

  function waitForAnimationReady(anim) {
    // Resolution of the ready promise, though UA dependent, is expected to
    // happen within a few frames. Throttling rendering of the frame owning
    // the animation's timeline may delay resolution of the ready promise,
    // resulting in a test failure.
    let frameTimeout = 10;
    let resolved = false;
    return new Promise((resolve, reject) => {
      anim.ready.then(() => {
        resolved = true;
        resolve('PASS');
      });
      const tick = () => {
        requestAnimationFrame(() => {
          if (!resolved) {
            if (--frameTimeout == 0)
              resolve('FAIL: Animation is still pending');
            else
              tick();
          }
        });
      };
      tick();
    });
  }

  function verifyAnimationIsUpdating() {
    return new Promise(resolve => {
      waitForAnimationFrames(3).then(() => {
        const opacity = getComputedStyle(target).opacity;
        const result =
            (opacity == 1) ? 'FAIL: opacity remained unchanged' : 'PASS';
        resolve(result);
      });
    });
  }

  async function runTest() {
    const anim = document.getAnimations()[0];
    if (!anim) {
      setResult('FAIL: Failed to create animation');
      return;
    }
    waitForAnimationReady(anim).then(result => {
      if (result != 'PASS') {
        sendResult(result);
        return;
      }
      verifyAnimationIsUpdating().then(result => {
        sendResult(result);
      });
    });
  }
</script>
</html>
