updated image loading

This commit is contained in:
2025-08-22 10:38:28 +01:00
parent 44af1b21b7
commit 5ededd8e05
15 changed files with 258 additions and 120 deletions

1
.env
View File

@@ -1 +1,2 @@
VITE_BASEURL=http://192.168.75.11/
VITE_TESTURL=http://100.82.205.44/SightingListRear/sightingSummary?mostRecentRef=-1

1
.gitignore vendored
View File

@@ -22,3 +22,4 @@ dist-ssr
*.njsproj
*.sln
*.sw?
.env

View File

@@ -14,6 +14,7 @@ const FrontCameraOverviewCard = ({ className }: CardProps) => {
const navigate = useNavigate();
const handlers = useSwipeable({
onSwipedRight: () => navigate("/front-camera-settings"),
onSwipedDown: () => navigate("/system-settings"),
trackMouse: true,
});

View File

@@ -1,10 +1,11 @@
import clsx from "clsx";
import Card from "../UI/Card";
import { SnapshotContainer } from "../CameraOverview/SnapshotContainer";
// import { SnapshotContainer } from "../CameraOverview/SnapshotContainer";
import { useSwipeable } from "react-swipeable";
import { useNavigate } from "react-router";
import CardHeader from "../UI/CardHeader";
import { faCamera } from "@fortawesome/free-regular-svg-icons";
import SightingOverview from "../SightingOverview/SightingOverview";
type CardProps = React.HTMLAttributes<HTMLDivElement>;
@@ -12,14 +13,21 @@ const RearCameraOverviewCard = ({ className }: CardProps) => {
const navigate = useNavigate();
const handlers = useSwipeable({
onSwipedLeft: () => navigate("/rear-camera-settings"),
onSwipedDown: () => navigate("/system-settings"),
trackMouse: true,
});
return (
<Card className={clsx("min-h-[40vh] md:min-h-[60vh] h-auto", className)}>
<Card
className={clsx(
"relative min-h-[40vh] md:min-h-[60vh] h-auto",
className
)}
>
<div className="flex flex-col space-y-3 h-full" {...handlers}>
<CardHeader title="Rear Overiew" icon={faCamera} />
<SnapshotContainer side="TargetDetectionRear" />
<SightingOverview />
{/* <SnapshotContainer side="TargetDetectionRear" /> */}
</div>
</Card>
);

View File

@@ -1,8 +1,11 @@
import { Form, Formik, Field } from "formik";
import FormGroup from "../components/FormGroup";
import type { NPEDFieldType } from "../../../types/types";
import { useNPEDAuth } from "../../../hooks/useNPEDAuh";
const NPEDFields = () => {
const { signIn, isError } = useNPEDAuth();
const initialValues = {
username: "",
password: "",
@@ -10,7 +13,8 @@ const NPEDFields = () => {
};
const handleSubmit = (values: NPEDFieldType) => {
alert(JSON.stringify(values));
console.log(isError);
signIn(values);
};
return (

View File

@@ -5,8 +5,15 @@ import { useOverviewOverlay } from "../../hooks/useOverviewOverlay";
import { useSightingFeedContext } from "../../context/SightingFeedContext";
import { useHiDPICanvas } from "../../hooks/useHiDPICanvas";
import NavigationArrow from "../UI/NavigationArrow";
import { useSwipeable } from "react-swipeable";
import { useNavigate } from "react-router";
const SightingOverview = () => {
const navigate = useNavigate();
const handlers = useSwipeable({
onSwipedRight: () => navigate("/front-camera-settings"),
trackMouse: true,
});
const [overlayMode, setOverlayMode] = useState<0 | 1 | 2>(0);
const imgRef = useRef<HTMLImageElement | null>(null);
@@ -16,20 +23,17 @@ const SightingOverview = () => {
setOverlayMode((m) => ((m + 1) % 3) as 0 | 1 | 2);
}, []);
const { effectiveSelected } = useSightingFeedContext();
const { effectiveSelected, side, mostRecent, noSighting } =
useSightingFeedContext();
useOverviewOverlay(effectiveSelected, overlayMode, imgRef, canvasRef);
useOverviewOverlay(mostRecent, overlayMode, imgRef, canvasRef);
const { sync } = useHiDPICanvas(imgRef, canvasRef);
if (noSighting) return <p>loading</p>;
return (
<div className="mt-2 grid gap-3">
{/* <div className="flex items-center gap-3 text-sm">
<div className="font-semibold">{effectiveSelected?.vrm ?? "—"}</div>
<div>{effectiveSelected?.countryCode ?? "—"}</div>
<div className="opacity-80">{effectiveSelected?.timeStamp ?? "—"}</div>
</div> */}
<div className="inline-block">
<div className="inline-block w-[90%] mx-auto" {...handlers}>
<NavigationArrow side={side} />
<div className="relative aspect-[5/4]">
<img
ref={imgRef}
@@ -37,12 +41,12 @@ const SightingOverview = () => {
sync();
setOverlayMode((m) => m);
}}
src={effectiveSelected?.overviewUrl || BLANK_IMG}
src={mostRecent?.overviewUrl || BLANK_IMG}
alt="overview"
className="absolute inset-0 w-full h-full object-contain cursor-pointer z-10"
onClick={onOverviewClick}
style={{
display: effectiveSelected?.overviewUrl ? "block" : "none",
display: mostRecent?.overviewUrl ? "block" : "none",
}}
/>
<canvas

View File

@@ -29,7 +29,7 @@ export default function SightingHistoryWidget({
className,
}: SightingHistoryWidgetProps) {
useNow(1000);
const { items, selectedRef, setSelectedRef } = useSightingFeedContext();
const { sightings, selectedRef, setSelectedRef } = useSightingFeedContext();
const onRowClick = useCallback(
(ref: number) => {
@@ -39,8 +39,8 @@ export default function SightingHistoryWidget({
);
const rows = useMemo(
() => items.filter(Boolean) as SightingWidgetType[],
[items]
() => sightings?.filter(Boolean) as SightingWidgetType[],
[sightings]
);
return (
@@ -49,7 +49,7 @@ export default function SightingHistoryWidget({
<div className="flex flex-col gap-3 ">
{/* Rows */}
<div className="flex flex-col">
{rows.map((obj, idx) => {
{rows?.map((obj, idx) => {
const isSelected = obj?.ref === selectedRef;
const motionAway = (obj?.motion ?? "").toUpperCase() === "AWAY";
const primaryIsColour = obj?.srcCam === 1;

View File

@@ -16,9 +16,9 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
return;
}
if (side === "TargetDetectionFront") {
if (side === "Front") {
navigate("/front-camera-settings");
} else if (side === "TargetDetectionRear") {
} else if (side === "Rear") {
navigate("/Rear-Camera-settings");
}
};
@@ -42,10 +42,9 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
</>
);
}
return (
<>
{side === "TargetDetectionFront" ? (
{side === "Front" ? (
<FontAwesomeIcon
icon={faArrowLeft}
className="absolute top-[50%] left-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce"

View File

@@ -3,18 +3,20 @@ import type { SightingWidgetType } from "../types/types";
import { useSightingFeed } from "../hooks/useSightingFeed";
type SightingFeedContextType = {
items: (SightingWidgetType | null | undefined)[];
sightings: (SightingWidgetType | null | undefined)[];
selectedRef: number | null;
setSelectedRef: (ref: number | null) => void;
effectiveSelected: SightingWidgetType | null;
mostRecent: SightingWidgetType | null;
side: string;
isPending: boolean;
noSighting: boolean;
};
type SightingFeedProviderProps = {
baseUrl: string;
entries?: number;
pollMs?: number;
autoSelectLatest?: boolean;
url: string;
children: ReactNode;
side: string;
};
const SightingFeedContext = createContext<SightingFeedContextType | undefined>(
@@ -22,17 +24,32 @@ const SightingFeedContext = createContext<SightingFeedContextType | undefined>(
);
export const SightingFeedProvider = ({
baseUrl,
entries = 7,
pollMs = 500,
autoSelectLatest = true,
children,
url,
side,
}: SightingFeedProviderProps) => {
const { items, selectedRef, setSelectedRef, effectiveSelected } =
useSightingFeed(baseUrl, { limit: entries, pollMs, autoSelectLatest });
const {
sightings,
selectedRef,
setSelectedRef,
effectiveSelected,
mostRecent,
isPending,
noSighting,
} = useSightingFeed(url);
return (
<SightingFeedContext.Provider
value={{ items, selectedRef, setSelectedRef, effectiveSelected }}
value={{
sightings,
selectedRef,
setSelectedRef,
effectiveSelected,
mostRecent,
side,
isPending,
noSighting,
}}
>
{children}
</SightingFeedContext.Provider>

View File

@@ -4,6 +4,7 @@ import { useQuery } from "@tanstack/react-query";
const apiUrl = import.meta.env.VITE_BASEURL;
async function fetchSnapshot(cameraSide: string) {
console.log(`${apiUrl}/${cameraSide}-preview`);
const response = await fetch(
// `http://100.116.253.81/Colour-preview`
`${apiUrl}/${cameraSide}-preview`
@@ -40,7 +41,7 @@ export function useGetOverviewSnapshot(cameraSide: string) {
queryKey: ["overviewSnapshot", cameraSide],
queryFn: () => fetchSnapshot(cameraSide),
refetchOnWindowFocus: false,
refetchInterval: 1000,
// refetchInterval: 1000,
});
useEffect(() => {

49
src/hooks/useNPEDAuh.ts Normal file
View File

@@ -0,0 +1,49 @@
import { useMutation } from "@tanstack/react-query";
import type { NPEDFieldType } from "../types/types";
const url = "https://jsonplaceholder.typicode.com/posts";
async function signIn(loginDetails: NPEDFieldType) {
console.log(loginDetails);
const response = await fetch(url, {
method: "POST",
body: JSON.stringify(loginDetails),
});
if (!response.ok) throw new Error("cannot reach NPED endpoint");
return response.json();
}
async function signOut() {
const response = await fetch(url, { method: "POST" });
if (!response.ok) throw new Error("cannot reach NPED sign out endpoint");
return response.json();
}
function setUserContext(user) {
console.log(user);
}
export const useNPEDAuth = () => {
const signInMutation = useMutation({
mutationKey: ["NPEDSignin"],
mutationFn: signIn,
onSuccess: (data) => setUserContext(data),
});
const signOutMutation = useMutation({
mutationKey: ["auth", "NPEDSignOut"],
mutationFn: signOut,
onSuccess: () => setUserContext(null),
});
return {
signIn: signInMutation.mutate,
signInAsync: signInMutation.mutateAsync,
isPending: signInMutation.isPending,
isError: signInMutation.isError,
error: signInMutation.error,
data: signInMutation.data,
signOut: signOutMutation.mutate,
};
};

View File

@@ -2,6 +2,8 @@ import { useQuery } from "@tanstack/react-query";
import { useRef } from "react";
const apiUrl = import.meta.env.VITE_BASEURL;
const FAST_MS = 200; // tab visible
const SLOW_MS = 2000; // tab hidden
async function fetchOverviewImage(cameraSide: string) {
const response = await fetch(`${apiUrl}${cameraSide}-preview`);
@@ -14,7 +16,11 @@ export function useOverviewVideo() {
const { isPending, isError, data } = useQuery({
queryKey: ["overviewVideo"],
queryFn: () => fetchOverviewImage("CameraFront"),
refetchInterval: 500,
// refetchInterval: () =>
// typeof document !== "undefined" && document.visibilityState === "hidden"
// ? SLOW_MS
// : FAST_MS,
// refetchIntervalInBackground: false,
});
if (isPending) return;

View File

@@ -1,91 +1,84 @@
import { useEffect, useMemo, useRef, useState } from "react";
import type { SightingWidgetType } from "../types/types";
import { useQuery } from "@tanstack/react-query";
export function useSightingFeed(
baseUrl: string,
{
limit = 7,
pollMs = 800,
autoSelectLatest = true,
}: {
limit?: number;
pollMs?: number;
autoSelectLatest?: boolean;
} = {}
) {
const [items, setItems] = useState<SightingWidgetType[]>(
() => Array(limit).fill(null) as unknown as SightingWidgetType[]
// const url = `http://100.82.205.44/SightingListFront/sightingSummary?mostRecentRef=-1`;
async function fetchSighting(url: string, ref: number, signal?: AbortSignal) {
const dynamicUrl = `${url}${ref}`;
const res = await fetch(dynamicUrl, { signal });
if (!res.ok) throw new Error(String(res.status));
return (await res.json()) as SightingWidgetType;
}
export function useSightingFeed(url: string) {
const [sightings, setSightings] = useState<SightingWidgetType[]>(
() => Array(7).fill(null) as unknown as SightingWidgetType[]
);
const [noSighting, setNoSighting] = useState(false);
const [selectedRef, setSelectedRef] = useState<number | null>(null);
const [mostRecent, setMostRecent] = useState<SightingWidgetType | null>(null);
const mostRecentRef = useRef<number>(-1);
const lastSeenRef = useRef<number | null>(null);
const { data, isPending } = useQuery({
queryKey: ["sighting"],
queryFn: ({ signal }) => fetchSighting(url, mostRecentRef.current, signal),
refetchInterval: 200,
refetchIntervalInBackground: true,
refetchOnWindowFocus: false,
staleTime: 0,
notifyOnChangeProps: ["data"],
});
useEffect(() => {
if (!data) return;
if (data.ref === -1) {
setNoSighting(true);
} else {
setNoSighting(false);
}
if (data.ref === lastSeenRef.current) return; // duplicate payload → do nothing
lastSeenRef.current = data.ref;
setSightings((prev) => {
const existing = prev.find((p) => p?.ref === data.ref);
const next = existing
? prev
: [data, ...prev.filter(Boolean)].slice(0, 7);
const stillHasSelection =
selectedRef != null && next.some((s) => s?.ref === selectedRef);
if (!stillHasSelection) {
setSelectedRef(data.ref);
}
return next;
});
setMostRecent(sightings[0]);
mostRecentRef.current = data.ref ?? -1;
}, [data, selectedRef, sightings]);
// effective selected (fallback to most recent)
const selected = useMemo(
() =>
selectedRef == null
? null
: items.find((x) => x?.ref === selectedRef) ?? null,
[items, selectedRef]
: sightings.find((s) => s?.ref === selectedRef) ?? null,
[sightings, selectedRef]
);
const effectiveSelected = selected ?? mostRecent ?? null;
useEffect(() => {
let delay = pollMs;
let dead = false;
const controller = new AbortController();
async function tick() {
try {
// Pause when tab hidden to save CPU/network
if (document.hidden) {
setTimeout(tick, Math.max(delay, 2000));
return;
}
const url = `http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef=${mostRecentRef.current}`;
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(String(res.status));
const obj: SightingWidgetType = await res.json();
if (obj && typeof obj.ref === "number" && obj.ref > -1) {
setItems((prev) => {
const next = [obj, ...prev].slice(0, limit);
// maintain selection if still present; otherwise select newest if allowed
const stillExists =
selectedRef != null && next.some((x) => x?.ref === selectedRef);
if (autoSelectLatest && !stillExists) {
setSelectedRef(obj.ref);
}
return next;
});
setMostRecent(obj);
mostRecentRef.current = obj.ref;
delay = pollMs; // reset backoff on success
}
} catch {
// exponential backoff (max 10s)
delay = Math.min(delay * 2, 10000);
} finally {
if (!dead) setTimeout(tick, delay);
}
}
const t = setTimeout(tick, pollMs);
return () => {
dead = true;
controller.abort();
clearTimeout(t);
};
}, [baseUrl, limit, pollMs, autoSelectLatest, selectedRef]);
return {
items,
sightings,
selectedRef,
setSelectedRef,
mostRecent,
effectiveSelected,
mostRecentRef,
isPending,
noSighting,
};
}

View File

@@ -1,29 +1,26 @@
import FrontCameraOverviewCard from "../components/FrontCameraOverview/FrontCameraOverviewCard";
import RearCameraOverviewCard from "../components/RearCameraOverview/RearCameraOverviewCard";
import { useNavigate } from "react-router";
import { useSwipeable } from "react-swipeable";
import SightingHistoryWidget from "../components/SightingsWidget/SightingWidget";
import { SightingFeedProvider } from "../context/SightingFeedContext";
const Dashboard = () => {
const navigate = useNavigate();
const handlers = useSwipeable({
onSwipedDown: () => navigate("/system-settings"),
trackMouse: true,
});
return (
<div
className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full"
{...handlers}
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full">
<SightingFeedProvider
url={
"http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef="
}
side="Front"
>
<SightingFeedProvider baseUrl={"http://100.82.205.44/SightingListFront"}>
<FrontCameraOverviewCard className="order-1" />
<SightingHistoryWidget className="order-3" />
</SightingFeedProvider>
<SightingFeedProvider baseUrl="http://100.82.205.44/SightingListRear">
<SightingFeedProvider
url="http://100.82.205.44/SightingListRear/sightingSummary?mostRecentRef="
side="Rear"
>
<RearCameraOverviewCard className="order-2" />
<SightingHistoryWidget className="order-4" />
</SightingFeedProvider>

View File

@@ -87,3 +87,60 @@ export function drawRects(
ctx.stroke();
});
}
// setSelectedRef(data?.ref);
//setItems(data);
// const selected = useMemo(
// () =>
// selectedRef == null
// ? null
// : items.find((x) => x?.ref === selectedRef) ?? null,
// [items, selectedRef]
// );
// const effectiveSelected = selected ?? mostRecent ?? null;
// useEffect(() => {
// let delay = pollMs;
// let dead = false;
// const controller = new AbortController();
// async function tick() {
// try {
// // Pause when tab hidden to save CPU/network
// if (document.hidden) {
// setTimeout(tick, Math.max(delay, 2000));
// return;
// }
// if (obj && typeof obj.ref === "number" && obj.ref > -1) {
// setItems((prev) => {
// const next = [obj, ...prev].slice(0, limit);
// // maintain selection if still present; otherwise select newest if allowed
// const stillExists =
// selectedRef != null && next.some((x) => x?.ref === selectedRef);
// if (autoSelectLatest && !stillExists) {
// setSelectedRef(obj.ref);
// }
// return next;
// });
// setMostRecent(obj);
// mostRecentRef.current = obj.ref;
// delay = pollMs; // reset backoff on success
// }
// } catch {
// // exponential backoff (max 10s)
// delay = Math.min(delay * 2, 10000);
// } finally {
// if (!dead) setTimeout(tick, delay);
// }
// }
// const t = setTimeout(tick, pollMs);
// return () => {
// dead = true;
// controller.abort();
// clearTimeout(t);
// };
// }, [baseUrl, limit, pollMs, autoSelectLatest, selectedRef]);