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

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,
};
}