added sounds, updated nped config and tweaks + code quality improvements

This commit is contained in:
2025-09-23 13:03:54 +01:00
parent eab7e79d01
commit c2074f86a2
27 changed files with 224 additions and 139 deletions

View File

@@ -1,7 +1,9 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { CAM_BASE } from "../utils/config";
const base_url = import.meta.env.VITE_OUTSIDE_BASEURL;
const base_url = `${CAM_BASE}/api`;
console.log(base_url);
const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
const [, cameraSide] = queryKey;

View File

@@ -5,7 +5,6 @@ import { CAM_BASE } from "../utils/config";
const apiUrl = CAM_BASE;
async function fetchSnapshot(cameraSide: string) {
console.log(`${apiUrl}/${cameraSide}-preview`);
const response = await fetch(`${apiUrl}/${cameraSide}-preview`);
if (!response.ok) {
throw new Error("Cannot reach endpoint");

View File

@@ -2,10 +2,10 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import type { NPEDFieldType } from "../types/types";
import { useNPEDContext } from "../context/NPEDUserContext";
import { useEffect } from "react";
import { CAM_BASE } from "../utils/config";
const base_url = import.meta.env.VITE_OUTSIDE_BASEURL;
async function fetchNPEDDetails() {
const fetchUrl = `${base_url}/fetch-config?id=NPED`;
const fetchUrl = `${CAM_BASE}/api/fetch-config?id=NPED`;
const response = await fetch(fetchUrl);
if (!response.ok) throw new Error("Cannot reach fetch-config endpoint");
@@ -14,8 +14,8 @@ async function fetchNPEDDetails() {
async function signIn(loginDetails: NPEDFieldType) {
const { frontId, rearId, username, password, clientId } = loginDetails;
const NPEDLoginURLFront = `${base_url}/update-config?id=${frontId}`;
const NPEDLoginURLRear = `${base_url}/update-config?id=${rearId}`;
const NPEDLoginURLFront = `${CAM_BASE}/api/update-config?id=${frontId}`;
const NPEDLoginURLRear = `${CAM_BASE}/api/update-config?id=${rearId}`;
const frontCameraPayload = {
id: frontId,
fields: [
@@ -66,7 +66,7 @@ async function signOut() {
{ property: "propClientID", value: "" },
],
};
const NPEDLoginURLFront = `${base_url}/update-config?id=NPED`;
const NPEDLoginURLFront = `${CAM_BASE}/api/update-config?id=NPED`;
const response = await fetch(NPEDLoginURLFront, {
method: "POST",
body: JSON.stringify(nullPayload),

View File

@@ -1,6 +1,8 @@
import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { SightingType } from "../types/types";
import { useSoundOnChange } from "react-sounds";
import click from "../assets/sounds/ui/computer-mouse-click.mp3";
async function fetchSighting(url: string, ref: number): Promise<SightingType> {
const res = await fetch(`${url}${ref}`);
@@ -8,14 +10,19 @@ async function fetchSighting(url: string, ref: number): Promise<SightingType> {
return res.json();
}
export function useSightingFeed(url: string) {
export function useSightingFeed(url: string, side: string) {
const [sightings, setSightings] = useState<SightingType[]>([]);
const [selectedRef, setSelectedRef] = useState<number | null>(null);
const mostRecent = sightings[0] ?? null;
const latestRef = mostRecent?.ref ?? null;
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(
null
);
useSoundOnChange(click, latestRef, {
volume: side === "Rear" ? 0 : 1,
});
const currentRef = useRef<number>(-1);
const lastValidTimestamp = useRef<number>(Date.now());
@@ -61,6 +68,13 @@ export function useSightingFeed(url: string) {
return;
}
// if (Notification.permission === "granted") {
// new Notification("New Sighting!", {
// body: `Ref: ${data.ref}`,
// icon: "/MAV-blue.svg",
// });
// }
currentRef.current = data.ref;
lastValidTimestamp.current = now;
@@ -75,7 +89,6 @@ export function useSightingFeed(url: string) {
useEffect(() => {
if (query.error) {
// you can add logging/telemetry here
// console.error("Sighting feed error:", query.error);
}
}, [query.error]);

64
src/hooks/useSound.ts Normal file
View File

@@ -0,0 +1,64 @@
// useBeep.ts
import { useEffect, useRef } from "react";
import { useSoundEnabled } from "react-sounds"; // so it respects your SoundBtn toggle
/**
* Plays a sound whenever `latestRef` changes.
*
* @param src Path to the sound file
* @param latestRef The primitive value to watch (e.g. sighting.ref)
* @param opts volume: 0..1, enabledOverride: force enable/disable, minGapMs: throttle interval
*/
export function useBeep(
src: string,
latestRef: number | null,
opts?: { volume?: number; enabledOverride?: boolean; minGapMs?: number }
) {
const audioRef = useRef<HTMLAudioElement>(undefined);
const prevRef = useRef<number | null>(null);
const lastPlay = useRef(0);
const [enabled] = useSoundEnabled();
const minGap = opts?.minGapMs ?? 250; // dont play more than 4 times/sec
// Create the audio element once
useEffect(() => {
const a = new Audio(src);
a.preload = "auto";
if (opts?.volume !== undefined) a.volume = opts.volume;
audioRef.current = a;
return () => {
a.pause();
};
}, [src, opts?.volume]);
// Watch for ref changes
useEffect(() => {
if (latestRef == null) return;
const canPlay =
(opts?.enabledOverride ?? enabled) &&
document.visibilityState === "visible";
if (!canPlay) {
prevRef.current = latestRef; // consume the change
return;
}
if (prevRef.current !== null && latestRef !== prevRef.current) {
const now = Date.now();
if (now - lastPlay.current >= minGap) {
const a = audioRef.current;
if (a) {
try {
a.currentTime = 0; // restart from beginning
void a.play(); // fire and forget
lastPlay.current = now;
} catch (err) {
console.warn("Audio play failed:", err);
}
}
}
}
prevRef.current = latestRef;
}, [latestRef, enabled, opts?.enabledOverride, minGap]);
}