From 866c7eab0f5947171fb00ddb78f8c8964ad2946c Mon Sep 17 00:00:00 2001 From: xaviergonz Date: Tue, 9 Aug 2022 23:16:45 +0200 Subject: [PATCH] fix calling play() then cancel() on an animation has different results in chrome and in safari --- packages/animation/src/Animation.ts | 23 +++++++++++++++---- .../animation/src/__tests__/index.test.ts | 8 +++---- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/packages/animation/src/Animation.ts b/packages/animation/src/Animation.ts index 7c70dac5..d7180d0f 100644 --- a/packages/animation/src/Animation.ts +++ b/packages/animation/src/Animation.ts @@ -75,6 +75,8 @@ export class Animation implements Omit { ) this.tick = (timestamp: number) => { + this.frameRequestId = undefined + // TODO: Temporary fix for OptionsResolver typing delay = delay as number @@ -156,7 +158,7 @@ export class Animation implements Omit { this.playState = "finished" this.resolve?.(latest) } else if (this.playState !== "idle") { - this.frameRequestId = requestAnimationFrame(this.tick) + this.requestAnimationFrame() } } @@ -180,7 +182,7 @@ export class Animation implements Omit { this.cancelTimestamp = this.startTime this.pauseTime = undefined - this.frameRequestId = requestAnimationFrame(this.tick) + this.requestAnimationFrame() } pause() { @@ -196,9 +198,7 @@ export class Animation implements Omit { stop() { this.playState = "idle" - if (this.frameRequestId !== undefined) { - cancelAnimationFrame(this.frameRequestId) - } + this.cancelAnimationFrame() this.reject?.(false) } @@ -238,4 +238,17 @@ export class Animation implements Omit { set playbackRate(rate) { this.rate = rate } + + private requestAnimationFrame() { + if (this.frameRequestId === undefined) { + this.frameRequestId = requestAnimationFrame(this.tick) + } + } + + private cancelAnimationFrame() { + if (this.frameRequestId !== undefined) { + cancelAnimationFrame(this.frameRequestId) + this.frameRequestId = undefined + } + } } diff --git a/packages/animation/src/__tests__/index.test.ts b/packages/animation/src/__tests__/index.test.ts index d9aee095..3b57123d 100644 --- a/packages/animation/src/__tests__/index.test.ts +++ b/packages/animation/src/__tests__/index.test.ts @@ -297,7 +297,7 @@ describe("animateNumber", () => { await animation.finished expect(output).toEqual([ 0.25, 0.5, 0.7499999999999999, 1, 0.25, 0.4999999999999998, - 0.4999999999999998, 0.4999999999999998, 1, + 0.4999999999999998, 0.4999999999999998, 0.7499999999999998, 1, ]) }) @@ -331,9 +331,9 @@ describe("animateNumber", () => { ) await animation.finished expect(output).toEqual([ - 0.125, 0.25, 0.37499999999999994, 0.37499999999999994, 0.25, 0.25, 0.25, - 0.37499999999999994, 0.5, 0.625, 0.7499999999999999, 0.8749999999999999, - 1, + 0.125, 0.25, 0.37499999999999994, 0.37499999999999994, 0.25, 0.25, 0.125, + 0.25, 0.37499999999999994, 0.5, 0.625, 0.7499999999999999, + 0.8749999999999999, 1, ]) expect(currentTime).toBe(150) })