fix: schedule cross-document animations in owner window

This commit is contained in:
zsviczian committed 2026-08-29 18:12:52 +02:00
1 parent 5de7e5e35b
commit 2b5b6cd17a
7 files changed
+195 -53

No files matched your search

+27
View File
@@ -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();
});
});
});
+10 -4
View File
@@ -181,12 +181,18 @@ export const debounce = <T extends any[]>(
};
// throttle callback to execute once per animation frame using the latest args
export const throttleRAF = <T extends any[]>(fn: (...args: T) => void) => {
export const throttleRAF = <T extends any[]>(
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 = <T extends any[]>(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 = <T extends any[]>(fn: (...args: T) => void) => {
ret.cancel = () => {
lastArgs = null;
if (timerId !== null) {
cancelAnimationFrame(timerId);
ownerWindow.cancelAnimationFrame(timerId);
timerId = null;
}
};
+12 -8
View File
@@ -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,
);
}
}
+3 -3
View File
@@ -9062,7 +9062,7 @@ class App extends React.Component<AppProps, AppState> {
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<AppProps, AppState> {
}
this.handlePointerMoveOverScrollbars(event, pointerDownState);
});
}, this.ownerWindow);
const onPointerUp = withBatchedUpdates(() => {
lastPointerUp = null;
isDraggingScrollBar = false;
@@ -11447,7 +11447,7 @@ class App extends React.Component<AppProps, AppState> {
});
}
}
});
}, this.ownerWindow);
}
// Returns whether the pointer move happened over either scrollbar
+8 -4
View File
@@ -24,11 +24,15 @@ export const withBatchedUpdatesThrottled = <
TFunction extends ((event: any) => void) | (() => void),
>(
func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
ownerWindow: Window = window,
) => {
// @ts-ignore
return throttleRAF<Parameters<TFunction>>(((event) => {
unstable_batchedUpdates(func, event);
}) as TFunction);
return throttleRAF<Parameters<TFunction>>(
// @ts-ignore
((event) => {
unstable_batchedUpdates(func, event);
}) as TFunction,
ownerWindow,
);
};
export const isRenderThrottlingEnabled = (() => {
+67 -34
View File
@@ -9,16 +9,33 @@ type AnimationRecord = {
animation: Animation<any>;
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<typeof requestAnimationFrame>; type: "raf" }
| { id: ReturnType<typeof setTimeout>; type: "timeout" }
| null = null;
private static scheduledFrames = new Map<
AnimationScheduler,
ScheduledFrame
>();
private static animations = new Map<string, AnimationRecord>();
static start<R extends object>(key: string, animation: Animation<R>) {
static start<R extends object>(
key: string,
animation: Animation<R>,
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);
}
}
}
@@ -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);
});
});