Files
Mav-Mobile-UI/src/hooks/useGetOverviewSnapshot.ts

87 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-08-13 14:23:48 +01:00
import { useRef, useCallback, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
const apiUrl = import.meta.env.VITE_BASEURL;
const folkstoneUrl = import.meta.env.VITE_FOLKESTONE_BASE;
2025-09-17 14:39:56 +01:00
console.log(folkstoneUrl);
2025-08-13 14:23:48 +01:00
async function fetchSnapshot(cameraSide: string) {
const response = await fetch(
// `${folkstoneUrl}/Colour-preview`
`${apiUrl}/${cameraSide}-preview`
2025-08-13 14:23:48 +01:00
);
if (!response.ok) {
throw new Error("Cannot reach endpoint");
}
2025-09-12 08:21:52 +01:00
2025-08-13 14:23:48 +01:00
return await response.blob();
}
export function useGetOverviewSnapshot(cameraSide: string) {
const latestUrlRef = useRef<string | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const imageRef = useRef<HTMLImageElement | null>(null);
const drawImage = useCallback(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
const img = imageRef.current;
if (!canvas || !ctx || !img) return;
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}, []);
const {
data: snapshotBlob,
isError,
error,
isPending,
2025-08-13 14:23:48 +01:00
} = useQuery({
queryKey: ["overviewSnapshot", cameraSide],
queryFn: () => fetchSnapshot(cameraSide),
refetchOnWindowFocus: false,
refetchInterval: 250,
2025-08-13 14:23:48 +01:00
});
useEffect(() => {
if (!snapshotBlob) return;
const imgUrl = URL.createObjectURL(snapshotBlob);
const img = new Image();
imageRef.current = img;
img.onload = () => {
drawImage();
};
img.src = imgUrl;
if (latestUrlRef.current) {
URL.revokeObjectURL(latestUrlRef.current);
}
latestUrlRef.current = imgUrl;
return () => {
if (latestUrlRef.current) {
URL.revokeObjectURL(latestUrlRef.current);
latestUrlRef.current = null;
}
};
}, [snapshotBlob, drawImage]);
useEffect(() => {
window.addEventListener("resize", drawImage);
return () => {
window.removeEventListener("resize", drawImage);
};
}, [drawImage]);
if (isError) {
console.error("Snapshot error:", error);
}
return { canvasRef, isError, isPending };
2025-08-13 14:23:48 +01:00
}