Files
privacy.sexy/src/presentation/components/Shared/Hooks/Resize/UseAnimationFrameLimiter.ts
undergroundwires 292362135d Centralize and optimize ResizeObserver usage
This commit addresses failures in end-to-end tests that occurred due to
`ResizeObserver` loop limit exceptions.

These errors were triggered by Vue dependency upgrades in the commit
aae5434451.
The errors had the following message:
> `ResizeObserver loop completed with undelivered notifications`

This error happens when there are too many observations and the observer
is not able to deliver all observations within a single animation frame.
See: WICG/resize-observer#38

his commit resolves the issue by controlling how many observations are
delivered per animation frame and limiting it to only one.

It improves performance by reducing layout trashing, improving frame
rates, and managing resources more effectively.

Changes:

- Introduce an animation frame control to manage observations more
  efficiently.
- Centralized `ResizeObserver` management within the `UseResizeObserver`
  hook to improve consistency and reuse across the application.
2024-05-20 10:36:49 +02:00

42 lines
1.3 KiB
TypeScript

import { onBeforeUnmount } from 'vue';
export function useAnimationFrameLimiter(
cancelAnimationFrame: CancelAnimationFrameFunction = window.cancelAnimationFrame,
requestAnimationFrame: RequestAnimationFrameFunction = window.requestAnimationFrame,
onTeardown: RegisterTeardownCallbackFunction = onBeforeUnmount,
): AnimationFrameLimiter {
let requestId: AnimationFrameId | null = null;
const cancelNextFrame = () => {
if (requestId === null) {
return;
}
cancelAnimationFrame(requestId);
};
const resetNextFrame = (callback: AnimationFrameRequestCallback) => {
cancelNextFrame();
requestId = requestAnimationFrame(callback);
};
onTeardown(() => {
cancelNextFrame();
});
return {
cancelNextFrame,
resetNextFrame,
};
}
export type CancelAnimationFrameFunction = typeof window.cancelAnimationFrame;
export type RequestAnimationFrameFunction = (callback: AnimationFrameRequestCallback) => number;
export type RegisterTeardownCallbackFunction = (callback: () => void) => void;
export type AnimationFrameId = ReturnType<typeof requestAnimationFrame>;
export type AnimationFrameRequestCallback = () => void;
export interface AnimationFrameLimiter {
cancelNextFrame(): void;
resetNextFrame(callback: AnimationFrameRequestCallback): void;
}