refactor(animations): introduce @angular/animation module (#14351)
PR Close: #14351
This commit is contained in:
committed by
Miško Hevery
parent
baa654a234
commit
96073e51c3
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {AnimationPlayer} from '@angular/core';
|
||||
import {StyleData} from '../common/style_data';
|
||||
import {NoOpAnimationPlayer} from '../private_import_core';
|
||||
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
export class NoOpAnimationDriver implements AnimationDriver {
|
||||
animate(
|
||||
element: any, keyframes: StyleData[], duration: number, delay: number, easing: string,
|
||||
previousPlayers: AnimationPlayer[] = []): AnimationPlayer {
|
||||
return new NoOpAnimationPlayer();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
export abstract class AnimationDriver {
|
||||
static NOOP: AnimationDriver = new NoOpAnimationDriver();
|
||||
abstract animate(
|
||||
element: any, keyframes: StyleData[], duration: number, delay: number, easing: string,
|
||||
previousPlayers?: AnimationPlayer[]): AnimationPlayer;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {TransitionInstruction} from '@angular/core';
|
||||
|
||||
export const enum AnimationTransitionInstructionType {TransitionAnimation, TimelineAnimation}
|
||||
|
||||
export interface AnimationEngineInstruction extends TransitionInstruction {
|
||||
type: AnimationTransitionInstructionType;
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {AnimationPlayer, Injectable} from '@angular/core';
|
||||
import {StyleData} from '../common/style_data';
|
||||
import {AnimationTimelineInstruction} from '../dsl/animation_timeline_instruction';
|
||||
import {AnimationTransitionInstruction} from '../dsl/animation_transition_instruction';
|
||||
import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer';
|
||||
import {AnimationGroupPlayer, NoOpAnimationPlayer, TransitionEngine} from '../private_import_core';
|
||||
|
||||
import {AnimationDriver} from './animation_driver';
|
||||
import {AnimationEngineInstruction, AnimationTransitionInstructionType} from './animation_engine_instruction';
|
||||
|
||||
export declare type AnimationPlayerTuple = {
|
||||
element: any; player: AnimationPlayer;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class DomAnimationTransitionEngine extends TransitionEngine {
|
||||
private _flaggedInserts = new Set<any>();
|
||||
private _queuedRemovals: any[] = [];
|
||||
private _queuedAnimations: AnimationPlayerTuple[] = [];
|
||||
private _activeElementAnimations = new Map<any, AnimationPlayer[]>();
|
||||
private _activeTransitionAnimations = new Map<any, {[triggerName: string]: AnimationPlayer}>();
|
||||
|
||||
constructor(private _driver: AnimationDriver, private _normalizer: AnimationStyleNormalizer) {
|
||||
super();
|
||||
}
|
||||
|
||||
insertNode(container: any, element: any) {
|
||||
container.appendChild(element);
|
||||
this._flaggedInserts.add(element);
|
||||
}
|
||||
|
||||
removeNode(element: any) { this._queuedRemovals.push(element); }
|
||||
|
||||
process(element: any, instructions: AnimationEngineInstruction[]): AnimationPlayer {
|
||||
const players = instructions.map(instruction => {
|
||||
if (instruction.type == AnimationTransitionInstructionType.TransitionAnimation) {
|
||||
return this._handleTransitionAnimation(
|
||||
element, <AnimationTransitionInstruction>instruction);
|
||||
}
|
||||
if (instruction.type == AnimationTransitionInstructionType.TimelineAnimation) {
|
||||
return this._handleTimelineAnimation(
|
||||
element, <AnimationTimelineInstruction>instruction, []);
|
||||
}
|
||||
return new NoOpAnimationPlayer();
|
||||
});
|
||||
return optimizeGroupPlayer(players);
|
||||
}
|
||||
|
||||
private _handleTransitionAnimation(element: any, instruction: AnimationTransitionInstruction):
|
||||
AnimationPlayer {
|
||||
const triggerName = instruction.triggerName;
|
||||
const elmTransitionMap = getOrSetAsInMap(this._activeTransitionAnimations, element, {});
|
||||
|
||||
let previousPlayers: AnimationPlayer[];
|
||||
if (instruction.isRemovalTransition) {
|
||||
// we make a copy of the array because the actual source array is modified
|
||||
// each time a player is finished/destroyed (the forEach loop would fail otherwise)
|
||||
previousPlayers = copyArray(this._activeElementAnimations.get(element));
|
||||
} else {
|
||||
previousPlayers = [];
|
||||
const existingPlayer = elmTransitionMap[triggerName];
|
||||
if (existingPlayer) {
|
||||
previousPlayers.push(existingPlayer);
|
||||
}
|
||||
}
|
||||
|
||||
// it's important to do this step before destroying the players
|
||||
// so that the onDone callback below won't fire before this
|
||||
eraseStyles(element, instruction.fromStyles);
|
||||
|
||||
// we first run this so that the previous animation player
|
||||
// data can be passed into the successive animation players
|
||||
const players = instruction.timelines.map(
|
||||
timelineInstruction => this._buildPlayer(element, timelineInstruction, previousPlayers));
|
||||
|
||||
previousPlayers.forEach(previousPlayer => previousPlayer.destroy());
|
||||
|
||||
const player = optimizeGroupPlayer(players);
|
||||
player.onDone(() => {
|
||||
player.destroy();
|
||||
const elmTransitionMap = this._activeTransitionAnimations.get(element);
|
||||
if (elmTransitionMap) {
|
||||
delete elmTransitionMap[triggerName];
|
||||
if (Object.keys(elmTransitionMap).length == 0) {
|
||||
this._activeTransitionAnimations.delete(element);
|
||||
}
|
||||
}
|
||||
deleteFromArrayMap(this._activeElementAnimations, element, player);
|
||||
setStyles(element, instruction.toStyles);
|
||||
});
|
||||
|
||||
this._queuePlayer(element, player);
|
||||
elmTransitionMap[triggerName] = player;
|
||||
|
||||
return player;
|
||||
}
|
||||
|
||||
private _handleTimelineAnimation(
|
||||
element: any, instruction: AnimationTimelineInstruction,
|
||||
previousPlayers: AnimationPlayer[]): AnimationPlayer {
|
||||
const player = this._buildPlayer(element, instruction, previousPlayers);
|
||||
player.onDestroy(() => { deleteFromArrayMap(this._activeElementAnimations, element, player); });
|
||||
this._queuePlayer(element, player);
|
||||
return player;
|
||||
}
|
||||
|
||||
private _buildPlayer(
|
||||
element: any, instruction: AnimationTimelineInstruction,
|
||||
previousPlayers: AnimationPlayer[]): AnimationPlayer {
|
||||
return this._driver.animate(
|
||||
element, this._normalizeKeyframes(instruction.keyframes), instruction.duration,
|
||||
instruction.delay, instruction.easing, previousPlayers);
|
||||
}
|
||||
|
||||
private _normalizeKeyframes(keyframes: StyleData[]): StyleData[] {
|
||||
const errors: string[] = [];
|
||||
const normalizedKeyframes: StyleData[] = [];
|
||||
keyframes.forEach(kf => {
|
||||
const normalizedKeyframe: StyleData = {};
|
||||
Object.keys(kf).forEach(prop => {
|
||||
let normalizedProp = prop;
|
||||
let normalizedValue = kf[prop];
|
||||
if (prop != 'offset') {
|
||||
normalizedProp = this._normalizer.normalizePropertyName(prop, errors);
|
||||
normalizedValue =
|
||||
this._normalizer.normalizeStyleValue(prop, normalizedProp, kf[prop], errors);
|
||||
}
|
||||
normalizedKeyframe[normalizedProp] = normalizedValue;
|
||||
});
|
||||
normalizedKeyframes.push(normalizedKeyframe);
|
||||
});
|
||||
if (errors.length) {
|
||||
const LINE_START = '\n - ';
|
||||
throw new Error(
|
||||
`Unable to animate due to the following errors:${LINE_START}${errors.join(LINE_START)}`);
|
||||
}
|
||||
return normalizedKeyframes;
|
||||
}
|
||||
|
||||
private _queuePlayer(element: any, player: AnimationPlayer) {
|
||||
const tuple = <AnimationPlayerTuple>{element, player};
|
||||
this._queuedAnimations.push(tuple);
|
||||
player.init();
|
||||
|
||||
const elementAnimations = getOrSetAsInMap(this._activeElementAnimations, element, []);
|
||||
elementAnimations.push(player);
|
||||
}
|
||||
|
||||
triggerAnimations() {
|
||||
while (this._queuedAnimations.length) {
|
||||
const {player, element} = this._queuedAnimations.shift();
|
||||
// in the event that an animation throws an error then we do
|
||||
// not want to re-run animations on any previous animations
|
||||
// if they have already been kicked off beforehand
|
||||
if (!player.hasStarted()) {
|
||||
player.play();
|
||||
}
|
||||
}
|
||||
|
||||
this._queuedRemovals.forEach(element => {
|
||||
if (this._flaggedInserts.has(element)) return;
|
||||
|
||||
let parent = element;
|
||||
let players: AnimationPlayer[];
|
||||
while (parent = parent.parentNode) {
|
||||
const match = this._activeElementAnimations.get(parent);
|
||||
if (match) {
|
||||
players = match;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (players) {
|
||||
optimizeGroupPlayer(players).onDone(() => remove(element));
|
||||
} else {
|
||||
if (element.parentNode) {
|
||||
remove(element);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this._queuedRemovals = [];
|
||||
this._flaggedInserts.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function getOrSetAsInMap(map: Map<any, any>, key: any, defaultValue: any) {
|
||||
let value = map.get(key);
|
||||
if (!value) {
|
||||
map.set(key, value = defaultValue);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function deleteFromArrayMap(map: Map<any, any[]>, key: any, value: any) {
|
||||
let arr = map.get(key);
|
||||
if (arr) {
|
||||
const index = arr.indexOf(value);
|
||||
if (index >= 0) {
|
||||
arr.splice(index, 1);
|
||||
if (arr.length == 0) {
|
||||
map.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setStyles(element: any, styles: StyleData) {
|
||||
Object.keys(styles).forEach(prop => { element.style[prop] = styles[prop]; });
|
||||
}
|
||||
|
||||
function eraseStyles(element: any, styles: StyleData) {
|
||||
Object.keys(styles).forEach(prop => {
|
||||
// IE requires '' instead of null
|
||||
// see https://github.com/angular/angular/issues/7916
|
||||
element.style[prop] = '';
|
||||
});
|
||||
}
|
||||
|
||||
function optimizeGroupPlayer(players: AnimationPlayer[]): AnimationPlayer {
|
||||
return players.length == 1 ? players[0] : new AnimationGroupPlayer(players);
|
||||
}
|
||||
|
||||
function copyArray(source: any[]): any[] {
|
||||
return source ? source.splice(0) : [];
|
||||
}
|
||||
|
||||
function remove(element: any) {
|
||||
element.parentNode.removeChild(element);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
export interface DOMAnimation {
|
||||
cancel(): void;
|
||||
play(): void;
|
||||
pause(): void;
|
||||
finish(): void;
|
||||
onfinish: Function;
|
||||
position: number;
|
||||
currentTime: number;
|
||||
addEventListener(eventName: string, handler: (event: any) => any): any;
|
||||
dispatchEvent(eventName: string): any;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {AnimationPlayer} from '@angular/core';
|
||||
|
||||
import {StyleData} from '../../common/style_data';
|
||||
import {AnimationDriver} from '../animation_driver';
|
||||
|
||||
import {WebAnimationsPlayer} from './web_animations_player';
|
||||
|
||||
export class WebAnimationsDriver implements AnimationDriver {
|
||||
animate(
|
||||
element: any, keyframes: StyleData[], duration: number, delay: number, easing: string,
|
||||
previousPlayers: AnimationPlayer[] = []): WebAnimationsPlayer {
|
||||
const playerOptions: {[key: string]: string |
|
||||
number} = {'duration': duration, 'delay': delay, 'fill': 'forwards'};
|
||||
|
||||
// we check for this to avoid having a null|undefined value be present
|
||||
// for the easing (which results in an error for certain browsers #9752)
|
||||
if (easing) {
|
||||
playerOptions['easing'] = easing;
|
||||
}
|
||||
|
||||
const previousWebAnimationPlayers = <WebAnimationsPlayer[]>previousPlayers.filter(
|
||||
player => { return player instanceof WebAnimationsPlayer; });
|
||||
return new WebAnimationsPlayer(element, keyframes, playerOptions, previousWebAnimationPlayers);
|
||||
}
|
||||
}
|
||||
|
||||
export function supportsWebAnimations() {
|
||||
return typeof Element !== 'undefined' && typeof(<any>Element).prototype['animate'] === 'function';
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {AUTO_STYLE, AnimationPlayer} from '@angular/core';
|
||||
|
||||
import {DOMAnimation} from './dom_animation';
|
||||
|
||||
export class WebAnimationsPlayer implements AnimationPlayer {
|
||||
private _onDoneFns: Function[] = [];
|
||||
private _onStartFns: Function[] = [];
|
||||
private _onDestroyFns: Function[] = [];
|
||||
private _player: DOMAnimation;
|
||||
private _duration: number;
|
||||
private _initialized = false;
|
||||
private _finished = false;
|
||||
private _started = false;
|
||||
private _destroyed = false;
|
||||
private _finalKeyframe: {[key: string]: string | number};
|
||||
|
||||
public parentPlayer: AnimationPlayer = null;
|
||||
public previousStyles: {[styleName: string]: string | number};
|
||||
|
||||
constructor(
|
||||
public element: any, public keyframes: {[key: string]: string | number}[],
|
||||
public options: {[key: string]: string | number},
|
||||
previousPlayers: WebAnimationsPlayer[] = []) {
|
||||
this._duration = <number>options['duration'];
|
||||
|
||||
this.previousStyles = {};
|
||||
previousPlayers.forEach(player => {
|
||||
let styles = player._captureStyles();
|
||||
Object.keys(styles).forEach(prop => this.previousStyles[prop] = styles[prop]);
|
||||
});
|
||||
}
|
||||
|
||||
private _onFinish() {
|
||||
if (!this._finished) {
|
||||
this._finished = true;
|
||||
this._onDoneFns.forEach(fn => fn());
|
||||
this._onDoneFns = [];
|
||||
}
|
||||
}
|
||||
|
||||
init(): void {
|
||||
if (this._initialized) return;
|
||||
this._initialized = true;
|
||||
|
||||
const keyframes = this.keyframes.map(styles => {
|
||||
const formattedKeyframe: {[key: string]: string | number} = {};
|
||||
Object.keys(styles).forEach((prop, index) => {
|
||||
let value = styles[prop];
|
||||
if (value == AUTO_STYLE) {
|
||||
value = _computeStyle(this.element, prop);
|
||||
}
|
||||
if (value != undefined) {
|
||||
formattedKeyframe[prop] = value;
|
||||
}
|
||||
});
|
||||
return formattedKeyframe;
|
||||
});
|
||||
|
||||
const previousStyleProps = Object.keys(this.previousStyles);
|
||||
if (previousStyleProps.length) {
|
||||
let startingKeyframe = keyframes[0];
|
||||
let missingStyleProps: string[] = [];
|
||||
previousStyleProps.forEach(prop => {
|
||||
if (startingKeyframe[prop] != null) {
|
||||
missingStyleProps.push(prop);
|
||||
}
|
||||
startingKeyframe[prop] = this.previousStyles[prop];
|
||||
});
|
||||
|
||||
if (missingStyleProps.length) {
|
||||
for (let i = 1; i < keyframes.length; i++) {
|
||||
let kf = keyframes[i];
|
||||
missingStyleProps.forEach(prop => { kf[prop] = _computeStyle(this.element, prop); });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._player = this._triggerWebAnimation(this.element, keyframes, this.options);
|
||||
this._finalKeyframe = _copyKeyframeStyles(keyframes[keyframes.length - 1]);
|
||||
|
||||
// this is required so that the player doesn't start to animate right away
|
||||
this._resetDomPlayerState();
|
||||
this._player.addEventListener('finish', () => this._onFinish());
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
_triggerWebAnimation(element: any, keyframes: any[], options: any): DOMAnimation {
|
||||
// jscompiler doesn't seem to know animate is a native property because it's not fully
|
||||
// supported yet across common browsers (we polyfill it for Edge/Safari) [CL #143630929]
|
||||
return <DOMAnimation>element['animate'](keyframes, options);
|
||||
}
|
||||
|
||||
get domPlayer() { return this._player; }
|
||||
|
||||
onStart(fn: () => void): void { this._onStartFns.push(fn); }
|
||||
|
||||
onDone(fn: () => void): void { this._onDoneFns.push(fn); }
|
||||
|
||||
onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); }
|
||||
|
||||
play(): void {
|
||||
this.init();
|
||||
if (!this.hasStarted()) {
|
||||
this._onStartFns.forEach(fn => fn());
|
||||
this._onStartFns = [];
|
||||
this._started = true;
|
||||
}
|
||||
this._player.play();
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.init();
|
||||
this._player.pause();
|
||||
}
|
||||
|
||||
finish(): void {
|
||||
this.init();
|
||||
this._onFinish();
|
||||
this._player.finish();
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this._resetDomPlayerState();
|
||||
this._destroyed = false;
|
||||
this._finished = false;
|
||||
this._started = false;
|
||||
}
|
||||
|
||||
private _resetDomPlayerState() {
|
||||
if (this._player) {
|
||||
this._player.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
restart(): void {
|
||||
this.reset();
|
||||
this.play();
|
||||
}
|
||||
|
||||
hasStarted(): boolean { return this._started; }
|
||||
|
||||
destroy(): void {
|
||||
if (!this._destroyed) {
|
||||
this._resetDomPlayerState();
|
||||
this._onFinish();
|
||||
this._destroyed = true;
|
||||
this._onDestroyFns.forEach(fn => fn());
|
||||
this._onDestroyFns = [];
|
||||
}
|
||||
}
|
||||
|
||||
get totalTime(): number { return this._duration; }
|
||||
|
||||
setPosition(p: number): void { this._player.currentTime = p * this.totalTime; }
|
||||
|
||||
getPosition(): number { return this._player.currentTime / this.totalTime; }
|
||||
|
||||
private _captureStyles(): {[prop: string]: string | number} {
|
||||
const styles: {[key: string]: string | number} = {};
|
||||
if (this.hasStarted()) {
|
||||
Object.keys(this._finalKeyframe).forEach(prop => {
|
||||
if (prop != 'offset') {
|
||||
styles[prop] =
|
||||
this._finished ? this._finalKeyframe[prop] : _computeStyle(this.element, prop);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return styles;
|
||||
}
|
||||
}
|
||||
|
||||
function _computeStyle(element: any, prop: string): string {
|
||||
return (<any>window.getComputedStyle(element))[prop];
|
||||
}
|
||||
|
||||
function _copyKeyframeStyles(styles: {[style: string]: string | number}):
|
||||
{[style: string]: string | number} {
|
||||
const newStyles: {[style: string]: string | number} = {};
|
||||
Object.keys(styles).forEach(prop => {
|
||||
if (prop != 'offset') {
|
||||
newStyles[prop] = styles[prop];
|
||||
}
|
||||
});
|
||||
return newStyles;
|
||||
}
|
||||
Reference in New Issue
Block a user