blob: d3b634be36723e4a15ce3227c319b3f74badbdaa [file] [log] [blame]
Primiano Tuccif30cd9c2018-08-13 01:53:26 +02001import {globals} from './globals';
2
Michail Schwab405002c2018-07-26 13:19:10 -04003// Copyright (C) 2018 The Android Open Source Project
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17export class Animation {
Primiano Tucci3cae4b62018-08-01 22:40:45 +010018 private startMs = 0;
19 private endMs = 0;
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020020 private boundOnAnimationFrame = this.onAnimationFrame.bind(this);
Michail Schwab405002c2018-07-26 13:19:10 -040021
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020022 constructor(private onAnimationStep: (timeSinceStartMs: number) => void) {}
Michail Schwab405002c2018-07-26 13:19:10 -040023
Primiano Tucci3cae4b62018-08-01 22:40:45 +010024 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;
Michail Schwab405002c2018-07-26 13:19:10 -040031 }
Primiano Tucci3cae4b62018-08-01 22:40:45 +010032 this.startMs = nowMs;
33 this.endMs = nowMs + durationMs;
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020034 globals.rafScheduler.start(this.boundOnAnimationFrame);
Michail Schwab405002c2018-07-26 13:19:10 -040035 }
36
37 stop() {
Primiano Tucci3cae4b62018-08-01 22:40:45 +010038 this.endMs = 0;
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020039 globals.rafScheduler.stop(this.boundOnAnimationFrame);
Michail Schwab405002c2018-07-26 13:19:10 -040040 }
41
Primiano Tucci3cae4b62018-08-01 22:40:45 +010042 get startTimeMs(): number {
43 return this.startMs;
Michail Schwab405002c2018-07-26 13:19:10 -040044 }
45
Primiano Tucci3cae4b62018-08-01 22:40:45 +010046 private onAnimationFrame(nowMs: number) {
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020047 if (nowMs >= this.endMs) {
48 globals.rafScheduler.stop(this.boundOnAnimationFrame);
49 return;
Michail Schwab405002c2018-07-26 13:19:10 -040050 }
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020051 this.onAnimationStep(Math.max(Math.round(nowMs - this.startMs), 0));
Michail Schwab405002c2018-07-26 13:19:10 -040052 }
Primiano Tucci3cae4b62018-08-01 22:40:45 +010053}