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

82 lines
2.0 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";
import { CAM_BASE } from "../utils/config";
2025-08-13 14:23:48 +01:00
const apiUrl = CAM_BASE;
// const fetch_url = `http://100.82.205.44/Colour-preview`;
async function fetchSnapshot(cameraSide: string) {
const response = await fetch(`${apiUrl}/${cameraSide}-preview`, {
signal: AbortSignal.timeout(500),
});
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(side: string) {
2025-08-13 14:23:48 +01:00
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"],
queryFn: () => fetchSnapshot(side),
2025-08-13 14:23:48 +01:00
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]);
return { canvasRef, isError, error, isPending };
2025-08-13 14:23:48 +01:00
}