1// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {globals} from './globals';
16
17export class Animation {
18  private startMs = 0;
19  private endMs = 0;
20  private boundOnAnimationFrame = this.onAnimationFrame.bind(this);
21
22  constructor(private onAnimationStep: (timeSinceStartMs: number) => void) {}
23
24  start(durationMs: number) {
25    const nowMs = performance.now();
26
27    // If the animation is already happening, just update its end time.
28    if (nowMs <= this.endMs) {
29      this.endMs = nowMs + durationMs;
30      return;
31    }
32    this.startMs = nowMs;
33    this.endMs = nowMs + durationMs;
34    globals.rafScheduler.start(this.boundOnAnimationFrame);
35  }
36
37  stop() {
38    this.endMs = 0;
39    globals.rafScheduler.stop(this.boundOnAnimationFrame);
40  }
41
42  get startTimeMs(): number {
43    return this.startMs;
44  }
45
46  private onAnimationFrame(nowMs: number) {
47    if (nowMs >= this.endMs) {
48      globals.rafScheduler.stop(this.boundOnAnimationFrame);
49      return;
50    }
51    this.onAnimationStep(Math.max(Math.round(nowMs - this.startMs), 0));
52  }
53}
54