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

3
.env
View File

@@ -1 +1,2 @@
VITE_BASEURL=http://192.168.75.11/ 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 *.njsproj
*.sln *.sln
*.sw? *.sw?
.env

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -16,9 +16,9 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
return; return;
} }
if (side === "TargetDetectionFront") { if (side === "Front") {
navigate("/front-camera-settings"); navigate("/front-camera-settings");
} else if (side === "TargetDetectionRear") { } else if (side === "Rear") {
navigate("/Rear-Camera-settings"); navigate("/Rear-Camera-settings");
} }
}; };
@@ -42,10 +42,9 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
</> </>
); );
} }
return ( return (
<> <>
{side === "TargetDetectionFront" ? ( {side === "Front" ? (
<FontAwesomeIcon <FontAwesomeIcon
icon={faArrowLeft} icon={faArrowLeft}
className="absolute top-[50%] left-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce" 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"; import { useSightingFeed } from "../hooks/useSightingFeed";
type SightingFeedContextType = { type SightingFeedContextType = {
items: (SightingWidgetType | null | undefined)[]; sightings: (SightingWidgetType | null | undefined)[];
selectedRef: number | null; selectedRef: number | null;
setSelectedRef: (ref: number | null) => void; setSelectedRef: (ref: number | null) => void;
effectiveSelected: SightingWidgetType | null; effectiveSelected: SightingWidgetType | null;
mostRecent: SightingWidgetType | null;
side: string;
isPending: boolean;
noSighting: boolean;
}; };
type SightingFeedProviderProps = { type SightingFeedProviderProps = {
baseUrl: string; url: string;
entries?: number;
pollMs?: number;
autoSelectLatest?: boolean;
children: ReactNode; children: ReactNode;
side: string;
}; };
const SightingFeedContext = createContext<SightingFeedContextType | undefined>( const SightingFeedContext = createContext<SightingFeedContextType | undefined>(
@@ -22,17 +24,32 @@ const SightingFeedContext = createContext<SightingFeedContextType | undefined>(
); );
export const SightingFeedProvider = ({ export const SightingFeedProvider = ({
baseUrl,
entries = 7,
pollMs = 500,
autoSelectLatest = true,
children, children,
url,
side,
}: SightingFeedProviderProps) => { }: SightingFeedProviderProps) => {
const { items, selectedRef, setSelectedRef, effectiveSelected } = const {
useSightingFeed(baseUrl, { limit: entries, pollMs, autoSelectLatest }); sightings,
selectedRef,
setSelectedRef,
effectiveSelected,
mostRecent,
isPending,
noSighting,
} = useSightingFeed(url);
return ( return (
<SightingFeedContext.Provider <SightingFeedContext.Provider
value={{ items, selectedRef, setSelectedRef, effectiveSelected }} value={{
sightings,
selectedRef,
setSelectedRef,
effectiveSelected,
mostRecent,
side,
isPending,
noSighting,
}}
> >
{children} {children}
</SightingFeedContext.Provider> </SightingFeedContext.Provider>

View File

@@ -4,6 +4,7 @@ import { useQuery } from "@tanstack/react-query";
const apiUrl = import.meta.env.VITE_BASEURL; const apiUrl = import.meta.env.VITE_BASEURL;
async function fetchSnapshot(cameraSide: string) { async function fetchSnapshot(cameraSide: string) {
console.log(`${apiUrl}/${cameraSide}-preview`);
const response = await fetch( const response = await fetch(
// `http://100.116.253.81/Colour-preview` // `http://100.116.253.81/Colour-preview`
`${apiUrl}/${cameraSide}-preview` `${apiUrl}/${cameraSide}-preview`
@@ -40,7 +41,7 @@ export function useGetOverviewSnapshot(cameraSide: string) {
queryKey: ["overviewSnapshot", cameraSide], queryKey: ["overviewSnapshot", cameraSide],
queryFn: () => fetchSnapshot(cameraSide), queryFn: () => fetchSnapshot(cameraSide),
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
refetchInterval: 1000, // refetchInterval: 1000,
}); });
useEffect(() => { 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"; import { useRef } from "react";
const apiUrl = import.meta.env.VITE_BASEURL; const apiUrl = import.meta.env.VITE_BASEURL;
const FAST_MS = 200; // tab visible
const SLOW_MS = 2000; // tab hidden
async function fetchOverviewImage(cameraSide: string) { async function fetchOverviewImage(cameraSide: string) {
const response = await fetch(`${apiUrl}${cameraSide}-preview`); const response = await fetch(`${apiUrl}${cameraSide}-preview`);
@@ -14,7 +16,11 @@ export function useOverviewVideo() {
const { isPending, isError, data } = useQuery({ const { isPending, isError, data } = useQuery({
queryKey: ["overviewVideo"], queryKey: ["overviewVideo"],
queryFn: () => fetchOverviewImage("CameraFront"), queryFn: () => fetchOverviewImage("CameraFront"),
refetchInterval: 500, // refetchInterval: () =>
// typeof document !== "undefined" && document.visibilityState === "hidden"
// ? SLOW_MS
// : FAST_MS,
// refetchIntervalInBackground: false,
}); });
if (isPending) return; if (isPending) return;

View File

@@ -1,91 +1,84 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import type { SightingWidgetType } from "../types/types"; import type { SightingWidgetType } from "../types/types";
import { useQuery } from "@tanstack/react-query";
export function useSightingFeed( // const url = `http://100.82.205.44/SightingListFront/sightingSummary?mostRecentRef=-1`;
baseUrl: string,
{ async function fetchSighting(url: string, ref: number, signal?: AbortSignal) {
limit = 7, const dynamicUrl = `${url}${ref}`;
pollMs = 800, const res = await fetch(dynamicUrl, { signal });
autoSelectLatest = true, if (!res.ok) throw new Error(String(res.status));
}: { return (await res.json()) as SightingWidgetType;
limit?: number; }
pollMs?: number;
autoSelectLatest?: boolean; export function useSightingFeed(url: string) {
} = {} const [sightings, setSightings] = useState<SightingWidgetType[]>(
) { () => Array(7).fill(null) as unknown as SightingWidgetType[]
const [items, setItems] = useState<SightingWidgetType[]>(
() => Array(limit).fill(null) as unknown as SightingWidgetType[]
); );
const [noSighting, setNoSighting] = useState(false);
const [selectedRef, setSelectedRef] = useState<number | null>(null); const [selectedRef, setSelectedRef] = useState<number | null>(null);
const [mostRecent, setMostRecent] = useState<SightingWidgetType | null>(null); const [mostRecent, setMostRecent] = useState<SightingWidgetType | null>(null);
const mostRecentRef = useRef<number>(-1); 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( const selected = useMemo(
() => () =>
selectedRef == null selectedRef == null
? null ? null
: items.find((x) => x?.ref === selectedRef) ?? null, : sightings.find((s) => s?.ref === selectedRef) ?? null,
[items, selectedRef] [sightings, selectedRef]
); );
const effectiveSelected = selected ?? mostRecent ?? null; 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 { return {
items, sightings,
selectedRef, selectedRef,
setSelectedRef, setSelectedRef,
mostRecent, mostRecent,
effectiveSelected, effectiveSelected,
mostRecentRef, mostRecentRef,
isPending,
noSighting,
}; };
} }

View File

@@ -1,29 +1,26 @@
import FrontCameraOverviewCard from "../components/FrontCameraOverview/FrontCameraOverviewCard"; import FrontCameraOverviewCard from "../components/FrontCameraOverview/FrontCameraOverviewCard";
import RearCameraOverviewCard from "../components/RearCameraOverview/RearCameraOverviewCard"; import RearCameraOverviewCard from "../components/RearCameraOverview/RearCameraOverviewCard";
import { useNavigate } from "react-router";
import { useSwipeable } from "react-swipeable";
import SightingHistoryWidget from "../components/SightingsWidget/SightingWidget"; import SightingHistoryWidget from "../components/SightingsWidget/SightingWidget";
import { SightingFeedProvider } from "../context/SightingFeedContext"; import { SightingFeedProvider } from "../context/SightingFeedContext";
const Dashboard = () => { const Dashboard = () => {
const navigate = useNavigate();
const handlers = useSwipeable({
onSwipedDown: () => navigate("/system-settings"),
trackMouse: true,
});
return ( return (
<div <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">
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
{...handlers} url={
> "http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef="
<SightingFeedProvider baseUrl={"http://100.82.205.44/SightingListFront"}> }
side="Front"
>
<FrontCameraOverviewCard className="order-1" /> <FrontCameraOverviewCard className="order-1" />
<SightingHistoryWidget className="order-3" /> <SightingHistoryWidget className="order-3" />
</SightingFeedProvider> </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" /> <RearCameraOverviewCard className="order-2" />
<SightingHistoryWidget className="order-4" /> <SightingHistoryWidget className="order-4" />
</SightingFeedProvider> </SightingFeedProvider>

View File

@@ -87,3 +87,60 @@ export function drawRects(
ctx.stroke(); 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]);