Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | export interface AnimationElementState {
name: string;
cssClass: string;
}
export interface AnimationElementConfig {
element: HTMLElement;
states: Array<AnimationElementState>;
}
/**
* Creates a basic animation element that appends and removes classes.
*
*
*
* ````
* const animationEl = new AnimationElement({
* element: document.getElementById("my-element"),
* states: [
* { name: 'intro', cssClass: 'my-element---intro'},
* { name: 'outro', cssClass: 'my-element---outro'},
* ]
* })
*
*
* animationEl.play('intro').then(()=> {
* // Do something.
* animationEl.play('outro');
* })
*
*
* ```
*
*/
export class AnimationElement {
private el: HTMLElement;
private states: Array<AnimationElementState>;
constructor(config: AnimationElementConfig) {
this.el = config.element;
this.states = config.states;
}
/**
* Removes all states from the element.
*/
public reset(): void {
this.states.forEach((state: AnimationElementState) => {
this.el.classList.remove(state.cssClass);
});
}
/**
* Plays a given state.
*
* ```
* animationElement.play('intro').then(()=> {
* // Do something when animation ends.
* })
*
*
* // Automatically remove 'intro' when animation is complete.
* animationElement.play('intro', true);
*
* ```
*/
public play(name: string, resetOnComplete = false): Promise<void> {
return new Promise((resolve) => {
const state = this.getState(name);
this.reset();
this.el.classList.add(state.cssClass);
this.el.addEventListener(
'animationend',
() => {
if (resetOnComplete) {
this.reset();
}
resolve();
},
{once: true}
);
});
}
/**
* Stack is similar to play but it doesn't remove previous cssClasses before
* appending the current state. This allows you to "stack" states.
*
* ```
* animationElement.play('intro').then(()=> {
* // Do something when animation ends.
* // Stacks the outro. Now the element would have .intro and .outro together
* animationElement.stack('outro');
* })
*
* ```
* @param name
* @param resetOnComplete
*/
public stack(name: string, resetOnComplete = false): Promise<void> {
return new Promise((resolve) => {
const state = this.getState(name);
this.el.classList.add(state.cssClass);
this.el.addEventListener(
'animationend',
() => {
if (resetOnComplete) {
this.reset();
}
resolve();
},
{once: true}
);
});
}
/**
* Filters through the state list to find a given state by name.
*/
private getState(name: string) {
return this.states.filter((state) => {
return state.name === name;
})[0];
}
public getElement(): HTMLElement {
return this.el;
}
}
|