refactor: NPED Context, sound update and start session

This commit is contained in:
2025-09-25 10:38:49 +01:00
parent efd037754e
commit 80b407943f
20 changed files with 96 additions and 39 deletions

Binary file not shown.

View File

@@ -16,6 +16,7 @@ type AlertItemProps = {
const AlertItem = ({ item }: AlertItemProps) => { const AlertItem = ({ item }: AlertItemProps) => {
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
const { dispatch } = useAlertHitContext(); const { dispatch } = useAlertHitContext();
// const {d} = useCameraBlackboard(); // const {d} = useCameraBlackboard();
const motionAway = (item?.motion ?? "").toUpperCase() === "AWAY"; const motionAway = (item?.motion ?? "").toUpperCase() === "AWAY";
const isHotListHit = item?.metadata?.hotlistMatches?.Hotlist0 === true; const isHotListHit = item?.metadata?.hotlistMatches?.Hotlist0 === true;

View File

@@ -1,12 +1,13 @@
import { useSound } from "react-sounds";
import Card from "../UI/Card"; import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader"; import CardHeader from "../UI/CardHeader";
import { useNPEDContext } from "../../context/NPEDUserContext";
const SessionCard = () => { const SessionCard = () => {
const { play } = useSound("notification/notification"); const { sessionStarted, setSessionStarted, sessionList } = useNPEDContext();
// function onStart(): void {
// throw new Error("Function not implemented."); const handleStartClick = () => {
// } setSessionStarted(!sessionStarted);
};
return ( return (
<Card> <Card>
@@ -14,15 +15,13 @@ const SessionCard = () => {
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<button <button
className="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full" className="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full"
onClick={() => { onClick={handleStartClick}
play();
}}
> >
Start Session Start Session
</button> </button>
<ul className="text-white space-y-2"> <ul className="text-white space-y-2">
<li>Number of Vehicles: </li> <li>Number of Vehicles: {sessionList.length} </li>
<li>Vehicles without Tax: </li> <li>Vehicles without Tax: </li>
<li>Vehicles without MOT: </li> <li>Vehicles without MOT: </li>
<li>Vehicles with NPED Cat A: </li> <li>Vehicles with NPED Cat A: </li>

View File

@@ -1,6 +1,7 @@
import { Form, Formik } from "formik"; import { Form, Formik } from "formik";
import type { HotlistUploadType } from "../../../types/types"; import type { HotlistUploadType } from "../../../types/types";
import { useSystemConfig } from "../../../hooks/useSystemConfig"; import { useSystemConfig } from "../../../hooks/useSystemConfig";
import { CAM_BASE } from "../../../utils/config";
const NPEDHotlist = () => { const NPEDHotlist = () => {
const { uploadSettings } = useSystemConfig(); const { uploadSettings } = useSystemConfig();
@@ -14,7 +15,7 @@ const NPEDHotlist = () => {
opts: { opts: {
timeoutMs: 30000, timeoutMs: 30000,
fieldName: "upload", fieldName: "upload",
uploadUrl: "http://192.168.0.90:8080/upload/hotlist-upload/2", uploadUrl: `${CAM_BASE}/upload/hotlist-upload/2`,
}, },
}; };

View File

@@ -15,6 +15,7 @@ import NPED_CAT_B from "/NPED_Cat_B.svg";
import NPED_CAT_C from "/NPED_Cat_C.svg"; import NPED_CAT_C from "/NPED_Cat_C.svg";
import popup from "../../assets/sounds/ui/popup_open.mp3"; import popup from "../../assets/sounds/ui/popup_open.mp3";
import { useSound } from "react-sounds"; import { useSound } from "react-sounds";
import { useNPEDContext } from "../../context/NPEDUserContext";
function useNow(tickMs = 1000) { function useNow(tickMs = 1000) {
const [, setNow] = useState(() => Date.now()); const [, setNow] = useState(() => Date.now());
@@ -46,9 +47,18 @@ export default function SightingHistoryWidget({
setSightingModalOpen, setSightingModalOpen,
isSightingModalOpen, isSightingModalOpen,
selectedSighting, selectedSighting,
mostRecent,
} = useSightingFeedContext(); } = useSightingFeedContext();
const { dispatch } = useAlertHitContext(); const { dispatch } = useAlertHitContext();
const { sessionStarted, setSessionList, sessionList } = useNPEDContext();
useEffect(() => {
if (sessionStarted) {
if (!mostRecent) return;
setSessionList([...sessionList, mostRecent]);
}
}, [mostRecent, sessionStarted, setSessionList]);
const hasAutoOpenedRef = useRef(false); const hasAutoOpenedRef = useRef(false);
@@ -84,10 +94,11 @@ export default function SightingHistoryWidget({
useEffect(() => { useEffect(() => {
if (hasAutoOpenedRef.current) return; if (hasAutoOpenedRef.current) return;
const firstHot = rows?.find((r) => { const firstHot = rows?.find((r) => {
const isHotListHit = r?.metadata?.hotlistMatches?.Hotlist0 === true;
const isNPEDHitA = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "A"; const isNPEDHitA = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "A";
const isNPEDHitB = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "B"; const isNPEDHitB = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "B";
const isNPEDHitC = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "C"; const isNPEDHitC = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "C";
return isNPEDHitA || isNPEDHitB || isNPEDHitC; return isNPEDHitA || isNPEDHitB || isNPEDHitC || isHotListHit;
}); });
if (firstHot) { if (firstHot) {
setSelectedSighting(firstHot); setSelectedSighting(firstHot);

View File

@@ -11,6 +11,7 @@ import {
import type { VersionFieldType } from "../../types/types"; import type { VersionFieldType } from "../../types/types";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import SoundBtn from "./SoundBtn"; import SoundBtn from "./SoundBtn";
import { useNPEDContext } from "../../context/NPEDUserContext";
async function fetchVersions( async function fetchVersions(
signal?: AbortSignal signal?: AbortSignal
@@ -43,6 +44,7 @@ export default function Header() {
const [offsetMs, setOffsetMs] = useState<number | null>(null); const [offsetMs, setOffsetMs] = useState<number | null>(null);
const [nowMs, setNowMs] = useState<number>(Date.now()); const [nowMs, setNowMs] = useState<number>(Date.now());
const [isFullscreen, setIsFullscreen] = useState(false); const [isFullscreen, setIsFullscreen] = useState(false);
const { sessionStarted } = useNPEDContext();
const toggleFullscreen = () => { const toggleFullscreen = () => {
if (!document.fullscreenElement) { if (!document.fullscreenElement) {
@@ -98,6 +100,9 @@ export default function Header() {
</Link> </Link>
</div> </div>
<div className="flex flex-col lg:flex-row items-center space-x-24 justify-items-center"> <div className="flex flex-col lg:flex-row items-center space-x-24 justify-items-center">
{sessionStarted && (
<div className="text-green-400 font-bold">Session Active</div>
)}
<div className="flex flex-col leading-tight text-white tabular-nums text-xl text-right mx-auto md:mx-10 space-y-1 my-2"> <div className="flex flex-col leading-tight text-white tabular-nums text-xl text-right mx-auto md:mx-10 space-y-1 my-2">
<h2>Local: {localStr}</h2> <h2>Local: {localStr}</h2>
<h2>UTC: {utcStr}</h2> <h2>UTC: {utcStr}</h2>

View File

@@ -3,14 +3,14 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
type NavigationArrowProps = { type NavigationArrowProps = {
side: string; side: string | undefined;
settingsPage?: boolean; settingsPage?: boolean;
}; };
const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => { const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
const navigate = useNavigate(); const navigate = useNavigate();
const navigationDest = (side: string) => { const navigationDest = (side: string | undefined) => {
if (settingsPage) { if (settingsPage) {
navigate("/"); navigate("/");
return; return;

View File

@@ -1,9 +1,13 @@
import { createContext, useContext, type SetStateAction } from "react"; import { createContext, useContext, type SetStateAction } from "react";
import type { NPEDUser } from "../types/types"; import type { NPEDUser, SightingType } from "../types/types";
type UserContextValue = { type UserContextValue = {
user: NPEDUser | null; user: NPEDUser | null;
setUser: React.Dispatch<SetStateAction<NPEDUser | null>>; setUser: React.Dispatch<SetStateAction<NPEDUser | null>>;
sessionStarted: boolean;
setSessionStarted: React.Dispatch<SetStateAction<boolean>>;
sessionList: SightingType[];
setSessionList: React.Dispatch<SetStateAction<SightingType[]>>;
}; };
export const NPEDUserContext = createContext<UserContextValue | undefined>( export const NPEDUserContext = createContext<UserContextValue | undefined>(

View File

@@ -7,7 +7,7 @@ type SightingFeedContextType = {
setSelectedRef: (ref: number | null) => void; setSelectedRef: (ref: number | null) => void;
// effectiveSelected: SightingType | null; // effectiveSelected: SightingType | null;
mostRecent: SightingType | null; mostRecent: SightingType | null;
side: string; side: string | undefined;
selectedSighting: SightingType | null; selectedSighting: SightingType | null;
setSelectedSighting: (sighting: SightingType | SightingType | null) => void; setSelectedSighting: (sighting: SightingType | SightingType | null) => void;
setSightingModalOpen: (isSightingModalOpen: boolean) => void; setSightingModalOpen: (isSightingModalOpen: boolean) => void;
@@ -15,6 +15,9 @@ type SightingFeedContextType = {
isError: boolean; isError: boolean;
isLoading: boolean; isLoading: boolean;
data: SightingType | undefined; data: SightingType | undefined;
sessionList: SightingType[];
sessionStarted: boolean;
setSessionStarted: (started: boolean) => void;
}; };
export const SightingFeedContext = createContext< export const SightingFeedContext = createContext<

View File

@@ -1,5 +1,5 @@
import { useState, type ReactNode } from "react"; import { useState, type ReactNode } from "react";
import type { NPEDUser } from "../../types/types"; import type { NPEDUser, SightingType } from "../../types/types";
import { NPEDUserContext } from "../NPEDUserContext"; import { NPEDUserContext } from "../NPEDUserContext";
type NPEDUserProviderType = { type NPEDUserProviderType = {
@@ -8,9 +8,20 @@ type NPEDUserProviderType = {
export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => { export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => {
const [user, setUser] = useState<NPEDUser | null>(null); const [user, setUser] = useState<NPEDUser | null>(null);
const [sessionStarted, setSessionStarted] = useState(false);
const [sessionList, setSessionList] = useState<SightingType[]>([]);
return ( return (
<NPEDUserContext.Provider value={{ user, setUser }}> <NPEDUserContext.Provider
value={{
user,
setUser,
setSessionStarted,
sessionStarted,
sessionList,
setSessionList,
}}
>
{children} {children}
</NPEDUserContext.Provider> </NPEDUserContext.Provider>
); );

View File

@@ -3,9 +3,9 @@ import { useSightingFeed } from "../../hooks/useSightingFeed";
import { SightingFeedContext } from "../SightingFeedContext"; import { SightingFeedContext } from "../SightingFeedContext";
type SightingFeedProviderProps = { type SightingFeedProviderProps = {
url: string; url?: string | undefined;
children: ReactNode; children: ReactNode;
side: string; side?: string | undefined;
}; };
export const SightingFeedProvider = ({ export const SightingFeedProvider = ({
@@ -23,7 +23,10 @@ export const SightingFeedProvider = ({
setSelectedSighting, setSelectedSighting,
selectedSighting, selectedSighting,
mostRecent, mostRecent,
} = useSightingFeed(url, side); sessionList,
sessionStarted,
setSessionStarted,
} = useSightingFeed(url);
const [isSightingModalOpen, setSightingModalOpen] = useState(false); const [isSightingModalOpen, setSightingModalOpen] = useState(false);
@@ -42,6 +45,9 @@ export const SightingFeedProvider = ({
isLoading, isLoading,
side, side,
data, data,
sessionList,
sessionStarted,
setSessionStarted,
}} }}
> >
{children} {children}

View File

@@ -1,10 +1,9 @@
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { useRef } from "react"; import { useRef } from "react";
import { CAM_BASE } from "../utils/config";
const apiUrl = import.meta.env.VITE_BASEURL;
async function fetchOverviewImage(cameraSide: string) { async function fetchOverviewImage(cameraSide: string) {
const response = await fetch(`${apiUrl}${cameraSide}-preview`); const response = await fetch(`${CAM_BASE}/${cameraSide}-preview`);
if (!response.ok) throw new Error("could not fetch overview image"); if (!response.ok) throw new Error("could not fetch overview image");
return response.blob(); return response.blob();
} }

View File

@@ -2,25 +2,30 @@ import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import type { SightingType } from "../types/types"; import type { SightingType } from "../types/types";
import { useSoundOnChange } from "react-sounds"; import { useSoundOnChange } from "react-sounds";
import click from "../assets/sounds/ui/computer-mouse-click.mp3"; import switchSound from "../assets/sounds/ui/switch.mp3";
async function fetchSighting(url: string, ref: number): Promise<SightingType> { async function fetchSighting(
url: string | undefined,
ref: number
): Promise<SightingType> {
const res = await fetch(`${url}${ref}`); const res = await fetch(`${url}${ref}`);
if (!res.ok) throw new Error(String(res.status)); if (!res.ok) throw new Error(String(res.status));
return res.json(); return res.json();
} }
export function useSightingFeed(url: string, side: string) { export function useSightingFeed(url: string | undefined) {
const [sightings, setSightings] = useState<SightingType[]>([]); const [sightings, setSightings] = useState<SightingType[]>([]);
const [selectedRef, setSelectedRef] = useState<number | null>(null); const [selectedRef, setSelectedRef] = useState<number | null>(null);
const [sessionStarted, setSessionStarted] = useState(false);
const [sessionList, setSessionList] = useState<SightingType[]>([]);
const mostRecent = sightings[0] ?? null; const mostRecent = sightings[0] ?? null;
const latestRef = mostRecent?.ref ?? null; const latestRef = mostRecent?.ref ?? null;
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>( const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(
null null
); );
useSoundOnChange(click, latestRef, { useSoundOnChange(switchSound, latestRef, {
volume: side === "Rear" ? 0 : 1, volume: 1,
}); });
const currentRef = useRef<number>(-1); const currentRef = useRef<number>(-1);
@@ -52,6 +57,13 @@ export function useSightingFeed(url: string, side: string) {
staleTime: 0, staleTime: 0,
}); });
useEffect(() => {
if (sessionStarted) {
if (!mostRecent) return;
setSessionList([...sessionList, mostRecent]);
}
}, [mostRecent, sessionList, sessionStarted]);
useEffect(() => { useEffect(() => {
const data = query.data; const data = query.data;
if (!data) return; if (!data) return;
@@ -92,13 +104,15 @@ export function useSightingFeed(url: string, side: string) {
// console.error("Sighting feed error:", query.error); // console.error("Sighting feed error:", query.error);
} }
}, [query.error]); }, [query.error]);
return { return {
sightings, sightings,
selectedRef, selectedRef,
setSelectedRef, setSelectedRef,
mostRecent, mostRecent,
selectedSighting, selectedSighting,
sessionList,
sessionStarted,
setSessionStarted,
setSelectedSighting, setSelectedSighting,
data: query.data, data: query.data,
isLoading: query.isLoading, isLoading: query.isLoading,

View File

@@ -13,7 +13,7 @@ Modal.setAppElement("#root");
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<BrowserRouter basename="/index"> <BrowserRouter basename="/InCarTest">
<App /> <App />
</BrowserRouter> </BrowserRouter>
</QueryClientProvider> </QueryClientProvider>

View File

@@ -2,6 +2,7 @@ import FrontCameraOverviewCard from "../components/FrontCameraOverview/FrontCame
import RearCameraOverviewCard from "../components/RearCameraOverview/RearCameraOverviewCard"; import RearCameraOverviewCard from "../components/RearCameraOverview/RearCameraOverviewCard";
import SightingHistoryWidget from "../components/SightingsWidget/SightingWidget"; import SightingHistoryWidget from "../components/SightingsWidget/SightingWidget";
import { SightingFeedProvider } from "../context/providers/SightingFeedProvider"; import { SightingFeedProvider } from "../context/providers/SightingFeedProvider";
import { CAM_BASE } from "../utils/config"; import { CAM_BASE } from "../utils/config";
const Dashboard = () => { const Dashboard = () => {

View File

@@ -2,18 +2,21 @@ import HistoryList from "../components/HistoryList/HistoryList.tsx";
import HitSearchCard from "../components/SessionForm/HitSearchCard.tsx"; import HitSearchCard from "../components/SessionForm/HitSearchCard.tsx";
import SessionCard from "../components/SessionForm/SessionCard.tsx"; import SessionCard from "../components/SessionForm/SessionCard.tsx";
import { useAlertHitContext } from "../context/AlertHitContext.ts"; import { useAlertHitContext } from "../context/AlertHitContext.ts";
import { SightingFeedProvider } from "../context/providers/SightingFeedProvider.tsx";
const Session = () => { const Session = () => {
useAlertHitContext(); useAlertHitContext();
return ( return (
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-1 sm:px-2 lg:px-0 w-full"> <SightingFeedProvider>
<HitSearchCard /> <div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-1 sm:px-2 lg:px-0 w-full">
<SessionCard /> <HitSearchCard />
<div className="col-span-2"> <SessionCard />
<HistoryList /> <div className="col-span-2">
<HistoryList />
</div>
</div> </div>
</div> </SightingFeedProvider>
); );
}; };

View File

@@ -1,5 +1,4 @@
// const rawCamBase = import.meta.env.VITE_CAM_BASE; const rawCamBase = import.meta.env.VITE_CAM_BASE;
const rawCamBase = import.meta.env.VITE_OUTSIDE_BASEURL;
export const CAM_BASE = export const CAM_BASE =
rawCamBase && rawCamBase.trim().length > 0 rawCamBase && rawCamBase.trim().length > 0

View File

@@ -6,5 +6,5 @@ import tailwindcss from "@tailwindcss/vite";
export default defineConfig({ export default defineConfig({
plugins: [react(), tailwindcss()], plugins: [react(), tailwindcss()],
server: { host: true }, server: { host: true },
base: "/index", base: "/InCarTest",
}); });