import { List } from '@pilotlab/lux-collections'; import is from '@pilotlab/lux-is'; import { Signal } from '@pilotlab/lux-signals'; import { HiResTimer } from '@pilotlab/lux-timer'; import IAnimation from './interfaces/iAnimation'; export class AnimationManager { constructor(timer:HiResTimer) { this.animations = new List(); this.p_completedAnimations = new List(); this.p_timer = timer; this.start(); } animations:List = null; protected p_completedAnimations:List = null; get isAllAnimationCompleted():boolean { return this._isAllAnimationCompleted; } private _isAllAnimationCompleted:boolean = false; length():number { if (this.animations != null) return this.animations.size; else return 0; } private _lengthCurrent:number = 0; get timer():HiResTimer { return this.p_timer; } set timer(value:HiResTimer) { this.stop(); this.p_timer = value; this.start(); } protected p_timer:HiResTimer; /** * Returns time elapsed in milliseconds. */ ticked:Signal = new Signal(); allAnimationsCompleted:Signal = new Signal(false); tick():void { if (is.empty(this.p_timer) || !this.p_isRunning) return; let elapsedMilliseconds:number = this.p_timer.elapsedMilliseconds; this.ticked.dispatch(elapsedMilliseconds); /// Tick animations let animation:IAnimation = null; let isAllCompleted:boolean = true; for (let i:number = 0; i < this.animations.size; i++) { animation = this.animations.item(i); if (animation.isCompleted === false) { isAllCompleted = false; animation.internalTick(elapsedMilliseconds); } else if (is.notEmpty(this.p_completedAnimations)) { this.p_completedAnimations.add(animation); } } if (isAllCompleted && !this._isAllAnimationCompleted) { this._isAllAnimationCompleted = true; this.allAnimationsCompleted.dispatch(true); } /// Cleanup all the completed animations. if (isAllCompleted) this.animations.clear(); else { for (let i:number = 0; i < this.p_completedAnimations.size; i++) { this.animations.delete(this.p_completedAnimations.item(i)); } } this.p_completedAnimations.clear(); if (this._lengthCurrent !== this.animations.size) { this._lengthCurrent = this.animations.size; } } stop():void { this.p_isRunning = false; } start():void { this.p_isRunning = true; } get isRunning():boolean { return this.p_isRunning; } protected p_isRunning:boolean = false; run(animation:IAnimation):IAnimation { if (is.notEmpty(this.animations)) { this.animations.add(animation); animation.internalAnimationManager = this; } return animation; } delete(animation:IAnimation):void { this.animations.delete(animation); } clear():void { this.animations.clear(); } interruptAll():void { this.animations.forEach(function (animation:IAnimation):boolean { animation.interrupt(); return true; }); } } // End class export default AnimationManager;