Files
image-studio/view/canvas/useCanvasResize.ts

35 lines
1.2 KiB
TypeScript

import { useEffect, useRef, type RefObject } from "react";
import type { Dispatch } from "@commands/dispatcher";
import { commandIds } from "@commands/ids";
export function useCanvasResize(canvasRef: RefObject<HTMLCanvasElement | null>, dispatch: Dispatch) {
const lastSize = useRef<{ w: number; h: number } | undefined>(undefined);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
let animationFrame: number | undefined;
const resizeObserver = new ResizeObserver(([entry]) => {
if (!entry) return;
const width = Math.floor(entry.contentRect.width);
const height = Math.floor(entry.contentRect.height);
if (lastSize.current?.w === width && lastSize.current.h === height) return;
if (animationFrame !== undefined) cancelAnimationFrame(animationFrame);
animationFrame = requestAnimationFrame(() => {
lastSize.current = { w: width, h: height };
dispatch(commandIds.viewportSetSize, { w: width, h: height });
});
});
resizeObserver.observe(canvas);
return () => {
if (animationFrame !== undefined) cancelAnimationFrame(animationFrame);
resizeObserver.disconnect();
};
}, [canvasRef, dispatch]);
}