From 2b5b6cd17affd1e49588fb2bbc0944b7edda503c Mon Sep 17 00:00:00 2001 From: zsviczian Date: Sat, 29 Aug 2026 18:12:52 +0200 Subject: [PATCH] fix: schedule cross-document animations in owner window --- packages/common/src/utils.test.ts | 27 ++++++ packages/common/src/utils.ts | 14 ++- packages/excalidraw/animatedTrail.ts | 20 ++-- packages/excalidraw/components/App.tsx | 6 +- packages/excalidraw/reactUtils.ts | 12 ++- packages/excalidraw/renderer/animation.ts | 101 +++++++++++++------- packages/excalidraw/tests/animation.test.ts | 68 +++++++++++++ 7 files changed, 195 insertions(+), 53 deletions(-) diff --git a/packages/common/src/utils.test.ts b/packages/common/src/utils.test.ts index 2f148cb66f..20160884ea 100644 --- a/packages/common/src/utils.test.ts +++ b/packages/common/src/utils.test.ts @@ -200,5 +200,32 @@ describe("@excalidraw/common/utils", () => { expect(fn).not.toHaveBeenCalled(); }); + + it("should schedule and cancel through the supplied window", () => { + const fn = vi.fn(); + const ownerWindow = { + requestAnimationFrame: vi.fn((callback: FrameRequestCallback) => { + const frameId = ++nextFrameId; + frameCallbacks.set(frameId, callback); + return frameId; + }), + cancelAnimationFrame: vi.fn((frameId: number) => { + frameCallbacks.delete(frameId); + }), + }; + const throttled = throttleRAF(fn, ownerWindow); + + throttled("popout"); + + expect(ownerWindow.requestAnimationFrame).toHaveBeenCalledTimes(1); + expect(window.requestAnimationFrame).not.toHaveBeenCalled(); + + throttled.cancel(); + + expect(ownerWindow.cancelAnimationFrame).toHaveBeenCalledTimes(1); + expect(window.cancelAnimationFrame).not.toHaveBeenCalled(); + runScheduledFrame(); + expect(fn).not.toHaveBeenCalled(); + }); }); }); diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts index bd015a99a4..9b0b118855 100644 --- a/packages/common/src/utils.ts +++ b/packages/common/src/utils.ts @@ -181,12 +181,18 @@ export const debounce = ( }; // throttle callback to execute once per animation frame using the latest args -export const throttleRAF = (fn: (...args: T) => void) => { +export const throttleRAF = ( + fn: (...args: T) => void, + ownerWindow: Pick< + Window, + "requestAnimationFrame" | "cancelAnimationFrame" + > = window, +) => { let timerId: number | null = null; let lastArgs: T | null = null; const scheduleFunc = () => { - timerId = window.requestAnimationFrame(() => { + timerId = ownerWindow.requestAnimationFrame(() => { timerId = null; const args = lastArgs; lastArgs = null; @@ -205,7 +211,7 @@ export const throttleRAF = (fn: (...args: T) => void) => { }; ret.flush = () => { if (timerId !== null) { - cancelAnimationFrame(timerId); + ownerWindow.cancelAnimationFrame(timerId); timerId = null; } if (lastArgs) { @@ -216,7 +222,7 @@ export const throttleRAF = (fn: (...args: T) => void) => { ret.cancel = () => { lastArgs = null; if (timerId !== null) { - cancelAnimationFrame(timerId); + ownerWindow.cancelAnimationFrame(timerId); timerId = null; } }; diff --git a/packages/excalidraw/animatedTrail.ts b/packages/excalidraw/animatedTrail.ts index e98e6e50ee..dca3c529eb 100644 --- a/packages/excalidraw/animatedTrail.ts +++ b/packages/excalidraw/animatedTrail.ts @@ -93,16 +93,20 @@ export class AnimatedTrail implements Trail { } if (!AnimationController.running(this.key)) { - AnimationController.start(this.key, () => { - const needsNext = this.onFrame(); - if (needsNext) { - return { keep: true }; - } + AnimationController.start( + this.key, + () => { + const needsNext = this.onFrame(); + if (needsNext) { + return { keep: true }; + } - this.cleanup(); + this.cleanup(); - return null; - }); + return null; + }, + this.app.ownerWindow, + ); } } diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx index fee8ba0455..2911d110a1 100644 --- a/packages/excalidraw/components/App.tsx +++ b/packages/excalidraw/components/App.tsx @@ -9062,7 +9062,7 @@ class App extends React.Component { scrollX: this.state.scrollX - deltaX / this.state.zoom.value, scrollY: this.state.scrollY - deltaY / this.state.zoom.value, }); - }); + }, this.ownerWindow); const teardown = withBatchedUpdates( (lastPointerUp = () => { lastPointerUp = null; @@ -9275,7 +9275,7 @@ class App extends React.Component { } this.handlePointerMoveOverScrollbars(event, pointerDownState); - }); + }, this.ownerWindow); const onPointerUp = withBatchedUpdates(() => { lastPointerUp = null; isDraggingScrollBar = false; @@ -11447,7 +11447,7 @@ class App extends React.Component { }); } } - }); + }, this.ownerWindow); } // Returns whether the pointer move happened over either scrollbar diff --git a/packages/excalidraw/reactUtils.ts b/packages/excalidraw/reactUtils.ts index a779fcfccf..ccceb00d02 100644 --- a/packages/excalidraw/reactUtils.ts +++ b/packages/excalidraw/reactUtils.ts @@ -24,11 +24,15 @@ export const withBatchedUpdatesThrottled = < TFunction extends ((event: any) => void) | (() => void), >( func: Parameters["length"] extends 0 | 1 ? TFunction : never, + ownerWindow: Window = window, ) => { - // @ts-ignore - return throttleRAF>(((event) => { - unstable_batchedUpdates(func, event); - }) as TFunction); + return throttleRAF>( + // @ts-ignore + ((event) => { + unstable_batchedUpdates(func, event); + }) as TFunction, + ownerWindow, + ); }; export const isRenderThrottlingEnabled = (() => { diff --git a/packages/excalidraw/renderer/animation.ts b/packages/excalidraw/renderer/animation.ts index 27f85bb472..9727637839 100644 --- a/packages/excalidraw/renderer/animation.ts +++ b/packages/excalidraw/renderer/animation.ts @@ -9,16 +9,33 @@ type AnimationRecord = { animation: Animation; lastTime: number; state: any; + scheduler: AnimationScheduler; }; +type AnimationScheduler = Pick< + Window, + | "requestAnimationFrame" + | "cancelAnimationFrame" + | "setTimeout" + | "clearTimeout" +>; + +type ScheduledFrame = + | { id: number; type: "raf" } + | { id: number; type: "timeout" }; + export class AnimationController { - private static scheduledFrame: - | { id: ReturnType; type: "raf" } - | { id: ReturnType; type: "timeout" } - | null = null; + private static scheduledFrames = new Map< + AnimationScheduler, + ScheduledFrame + >(); private static animations = new Map(); - static start(key: string, animation: Animation) { + static start( + key: string, + animation: Animation, + scheduler: AnimationScheduler = window, + ) { if (AnimationController.animations.has(key)) { return; } @@ -27,6 +44,7 @@ export class AnimationController { animation, lastTime: 0, state: undefined, + scheduler, }; AnimationController.animations.set(key, record); @@ -39,7 +57,7 @@ export class AnimationController { } catch (error) { if (AnimationController.animations.get(key) === record) { AnimationController.animations.delete(key); - AnimationController.cancelScheduledFrameIfIdle(); + AnimationController.cancelScheduledFrameIfIdle(record.scheduler); } throw error; } @@ -53,63 +71,73 @@ export class AnimationController { if (!initialState) { AnimationController.animations.delete(key); - AnimationController.cancelScheduledFrameIfIdle(); + AnimationController.cancelScheduledFrameIfIdle(record.scheduler); return; } record.state = initialState; - AnimationController.scheduleNextFrame(); + AnimationController.scheduleNextFrame(record.scheduler); } - private static scheduleNextFrame() { - if (AnimationController.scheduledFrame) { + private static scheduleNextFrame(scheduler: AnimationScheduler) { + if (AnimationController.scheduledFrames.has(scheduler)) { return; } if (isRenderThrottlingEnabled()) { - AnimationController.scheduledFrame = { - id: requestAnimationFrame(AnimationController.tick), + AnimationController.scheduledFrames.set(scheduler, { + id: scheduler.requestAnimationFrame(() => + AnimationController.tick(scheduler), + ), type: "raf", - }; + }); } else { - AnimationController.scheduledFrame = { - id: setTimeout(AnimationController.tick, 0), + AnimationController.scheduledFrames.set(scheduler, { + id: scheduler.setTimeout(() => AnimationController.tick(scheduler), 0), type: "timeout", - }; + }); } } - private static cancelScheduledFrame() { - if (!AnimationController.scheduledFrame) { + private static cancelScheduledFrame(scheduler: AnimationScheduler) { + const scheduledFrame = AnimationController.scheduledFrames.get(scheduler); + if (!scheduledFrame) { return; } - if (AnimationController.scheduledFrame.type === "raf") { - cancelAnimationFrame(AnimationController.scheduledFrame.id); + if (scheduledFrame.type === "raf") { + scheduler.cancelAnimationFrame(scheduledFrame.id); } else { - clearTimeout(AnimationController.scheduledFrame.id); + scheduler.clearTimeout(scheduledFrame.id); } - AnimationController.scheduledFrame = null; + AnimationController.scheduledFrames.delete(scheduler); } - private static cancelScheduledFrameIfIdle() { - if (AnimationController.animations.size > 0) { + private static cancelScheduledFrameIfIdle(scheduler: AnimationScheduler) { + if ( + [...AnimationController.animations.values()].some( + (animation) => animation.scheduler === scheduler, + ) + ) { return false; } - AnimationController.cancelScheduledFrame(); + AnimationController.cancelScheduledFrame(scheduler); return true; } - private static tick() { - AnimationController.scheduledFrame = null; + private static tick(scheduler: AnimationScheduler) { + AnimationController.scheduledFrames.delete(scheduler); - if (AnimationController.animations.size > 0) { + const animations = [...AnimationController.animations].filter( + ([, animation]) => animation.scheduler === scheduler, + ); + + if (animations.length > 0) { // A callback may synchronously add, cancel, or replace animations. Work // from the frame's starting set so newly started animations begin on the // next frame and every record runs at most once per tick. - const animations = [...AnimationController.animations]; for (const [key, animation] of animations) { if (AnimationController.animations.get(key) !== animation) { continue; @@ -133,7 +161,7 @@ export class AnimationController { if (!state) { AnimationController.animations.delete(key); - if (AnimationController.cancelScheduledFrameIfIdle()) { + if (AnimationController.cancelScheduledFrameIfIdle(scheduler)) { return; } } else { @@ -142,11 +170,11 @@ export class AnimationController { } } - if (AnimationController.cancelScheduledFrameIfIdle()) { + if (AnimationController.cancelScheduledFrameIfIdle(scheduler)) { return; } - AnimationController.scheduleNextFrame(); + AnimationController.scheduleNextFrame(scheduler); } } @@ -155,12 +183,17 @@ export class AnimationController { } static cancel(key: string) { + const record = AnimationController.animations.get(key); AnimationController.animations.delete(key); - AnimationController.cancelScheduledFrameIfIdle(); + if (record) { + AnimationController.cancelScheduledFrameIfIdle(record.scheduler); + } } static reset() { AnimationController.animations.clear(); - AnimationController.cancelScheduledFrame(); + for (const scheduler of [...AnimationController.scheduledFrames.keys()]) { + AnimationController.cancelScheduledFrame(scheduler); + } } } diff --git a/packages/excalidraw/tests/animation.test.ts b/packages/excalidraw/tests/animation.test.ts index 2843b9d680..f4a73cb5fc 100644 --- a/packages/excalidraw/tests/animation.test.ts +++ b/packages/excalidraw/tests/animation.test.ts @@ -16,6 +16,7 @@ describe("AnimationController", () => { AnimationController.cancel(SECOND_KEY); window.EXCALIDRAW_THROTTLE_RENDER = undefined; vi.useRealTimers(); + vi.restoreAllMocks(); }); it("starts a new animation after the previous last animation was cancelled", async () => { @@ -164,4 +165,71 @@ describe("AnimationController", () => { expect(replacementFrames).toBe(2); expect(AnimationController.running(FIRST_KEY)).toBe(false); }); + + it("advances an animation on its supplied window while the main frame is stalled", () => { + window.EXCALIDRAW_THROTTLE_RENDER = true; + + let mainFrame: FrameRequestCallback | undefined; + vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => { + mainFrame = callback; + return 1; + }); + vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); + + let popoutFrame: FrameRequestCallback | undefined; + const popoutWindow = { + requestAnimationFrame: vi.fn((callback: FrameRequestCallback) => { + popoutFrame = callback; + return 2; + }), + cancelAnimationFrame: vi.fn(), + setTimeout: vi.fn(), + clearTimeout: vi.fn(), + }; + + let mainFrames = 0; + AnimationController.start(FIRST_KEY, () => { + mainFrames++; + return { keep: true }; + }); + + let popoutFrames = 0; + AnimationController.start( + SECOND_KEY, + ({ state }) => { + popoutFrames++; + return state ? null : { keep: true }; + }, + popoutWindow, + ); + + expect(mainFrames).toBe(1); + expect(popoutFrames).toBe(1); + expect(mainFrame).toBeTypeOf("function"); + expect(popoutFrame).toBeTypeOf("function"); + + popoutFrame!(16); + + expect(popoutFrames).toBe(2); + expect(mainFrames).toBe(1); + expect(AnimationController.running(SECOND_KEY)).toBe(false); + }); + + it("schedules and cancels a timer through the supplied window", () => { + const popoutWindow = { + requestAnimationFrame: vi.fn(), + cancelAnimationFrame: vi.fn(), + setTimeout: vi.fn(() => 3), + clearTimeout: vi.fn(), + }; + + AnimationController.start(SECOND_KEY, () => ({ keep: true }), popoutWindow); + + expect(popoutWindow.setTimeout).toHaveBeenCalledTimes(1); + + AnimationController.cancel(SECOND_KEY); + + expect(popoutWindow.clearTimeout).toHaveBeenCalledWith(3); + expect(AnimationController.running(SECOND_KEY)).toBe(false); + }); });