Skip to content

Commit

Permalink
feat(@okikio/animate): ✨
Browse files Browse the repository at this point in the history
pause Animation when page is out of focus

`Animate.pauseOnPageHidden = false` at top of page disables the feature
  • Loading branch information
okikio committed May 17, 2021
1 parent c647698 commit b388ff1
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion packages/animate/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1228,7 +1228,47 @@ export class Animate {
public promise: Promise<Animate[]>;
constructor(options: IAnimationOptions) {
this.loop = this.loop.bind(this);
this.onVisibilityChange = this.onVisibilityChange.bind(this);
this.updateOptions(options);

this.visibilityPlayState = this.getPlayState();
if (Animate.pauseOnPageHidden) {
document.addEventListener('visibilitychange', this.onVisibilityChange);
}
}

/**
* Tells all animate instances to pause when the page is hidden
*
* @static
* @type {Boolean}
* @memberof Animate
*/
static pauseOnPageHidden: Boolean = true;

/**
* Store the last remebered playstate before page was hidden
*
* @protected
* @type {TypePlayStates}
* @memberof Animate
*/
protected visibilityPlayState: TypePlayStates;

/**
* document `visibilitychange` event handler
*/
protected onVisibilityChange() {
if (document.hidden) {
this.visibilityPlayState = this.getPlayState();
if (this.is("running")) {
this.loop();
this.pause();
}
} else {
if (this.visibilityPlayState == "running" && this.is("paused"))
this.play();
}
}

/**
Expand Down Expand Up @@ -1287,8 +1327,8 @@ export class Animate {
*/
public loop(): void {
this.stopLoop();
this.emit("update", this.getProgress(), this);
this.animationFrame = window.requestAnimationFrame(this.loop);
this.emit("update", this.getProgress(), this);
}

/**
Expand Down Expand Up @@ -1391,6 +1431,11 @@ export class Animate {
*/
public stop() {
this.cancel();

if (Animate.pauseOnPageHidden) {
document.removeEventListener('visibilitychange', this.onVisibilityChange);
}

this.computedOptions.clear();
this.animations.clear();
this.keyframeEffects.clear();
Expand Down

0 comments on commit b388ff1

Please sign in to comment.