Merged in feature/soundsettings (pull request #7)

Feature/soundsettings
This commit is contained in:
2025-10-03 14:02:12 +00:00
16 changed files with 396 additions and 84 deletions

View File

@@ -8,9 +8,11 @@ import Session from "./pages/Session";
import { NPEDUserProvider } from "./context/providers/NPEDUserContextProvider"; import { NPEDUserProvider } from "./context/providers/NPEDUserContextProvider";
import { AlertHitProvider } from "./context/providers/AlertHitProvider"; import { AlertHitProvider } from "./context/providers/AlertHitProvider";
import { SoundProvider } from "react-sounds"; import { SoundProvider } from "react-sounds";
import SoundContextProvider from "./context/providers/SoundContextProvider";
function App() { function App() {
return ( return (
<SoundContextProvider>
<SoundProvider initialEnabled={true}> <SoundProvider initialEnabled={true}>
<NPEDUserProvider> <NPEDUserProvider>
<AlertHitProvider> <AlertHitProvider>
@@ -27,6 +29,7 @@ function App() {
</AlertHitProvider> </AlertHitProvider>
</NPEDUserProvider> </NPEDUserProvider>
</SoundProvider> </SoundProvider>
</SoundContextProvider>
); );
} }

Binary file not shown.

View File

@@ -0,0 +1,14 @@
import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader";
import SoundSettingsFields from "./SoundSettingsFields";
const SoundSettingsCard = () => {
return (
<Card className="p-4">
<CardHeader title={"Sound Settings"} />
<SoundSettingsFields />
</Card>
);
};
export default SoundSettingsCard;

View File

@@ -0,0 +1,117 @@
import { Field, FieldArray, Form, Formik } from "formik";
import FormGroup from "../components/FormGroup";
import type { FormValues, Hotlist } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext";
import { toast } from "sonner";
const SoundSettingsFields = () => {
const { state, dispatch } = useSoundContext();
const hotlists: Hotlist[] = [
{ name: "hotlist0", sound: "" },
{ name: "hotlist1", sound: "" },
{ name: "hotlist2", sound: "" },
];
const soundOptions = state?.soundOptions?.map((soundOption) => ({
value: soundOption?.name,
label: soundOption?.name,
}));
const initialValues: FormValues = {
sightingSound: state.sightingSound ?? "switch",
NPEDsound: state.NPEDsound ?? "popup",
hotlists,
};
const handleSubmit = (values: FormValues) => {
dispatch({ type: "UPDATE", payload: values });
toast.success("Sound settings updated");
};
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{({ values }) => (
<Form className="flex flex-col space-y-3">
<FormGroup>
<label htmlFor="sightingSound">Sighting Sound</label>
<Field
as="select"
name="sightingSound"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
{soundOptions?.map(({ value, label }) => {
return (
<option key={value} value={value}>
{label}
</option>
);
})}
</Field>
</FormGroup>
<FormGroup>
<label htmlFor="NPEDsound">NPED notification Sound</label>
<Field
as="select"
name="NPEDsound"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
{soundOptions?.map(({ value, label }) => (
<option key={value} value={value}>
{label}
</option>
))}
</Field>
</FormGroup>
<div>
<h3 className="text-lg font-semibold mb-2">Hotlist Sounds</h3>
<FormGroup>
<FieldArray
name="hotlists"
render={() => (
<div className="w-full m-2">
{values.hotlists.length > 0 ? (
values.hotlists.map((hotlist, index) => (
<div
key={hotlist.name}
className="flex items-center m-2 w-full justify-between"
>
<label
htmlFor={`hotlists.${index}.sound`}
className="w-32 shrink-0"
>
{hotlist.name}
</label>
<Field
as="select"
name={`hotlists.${index}.sound`}
id={`hotlists.${index}.sound`}
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
{soundOptions?.map(({ value, label }) => (
<option key={value} value={value}>
{label}
</option>
))}
</Field>
</div>
))
) : (
<p>No hotlists yet, Add one</p>
)}
</div>
)}
/>
</FormGroup>
</div>
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
Save Settings
</button>
</Form>
)}
</Formik>
);
};
export default SoundSettingsFields;

View File

@@ -0,0 +1,68 @@
import { Form, Formik } from "formik";
import FormGroup from "../components/FormGroup";
import type { SoundUploadValue } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext";
import { toast } from "sonner";
const SoundUpload = () => {
const { dispatch } = useSoundContext();
const initialValues: SoundUploadValue = {
name: "",
soundFile: null,
};
const handleSubmit = (values: SoundUploadValue) => {
if (!values.soundFile) {
toast.warning("Please select an audio file");
} else {
dispatch({ type: "ADD", payload: values });
toast.success("Sound file upload successfully");
}
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
{({ setFieldValue, errors, setFieldError }) => (
<Form>
<FormGroup>
<label htmlFor="soundFile">Sound File</label>
<input
type="file"
name="soundFile"
id="sightingSoundinput"
accept="audio/mpeg"
onChange={(e) => {
if (
e.target?.files &&
e.target?.files[0]?.type === "audio/mpeg"
) {
setFieldValue("name", e.target.files[0].name);
setFieldValue("soundFile", e.target.files[0]);
} else {
setFieldError("soundFile", "Not an mp3 file");
toast.error("Not an mp3 file");
}
}}
/>
</FormGroup>
{errors.soundFile && (
<p className="text-red-500 text-sm mt-1">Not an mp3 file</p>
)}
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
disabled={errors.soundFile ? true : false}
>
Upload
</button>
</Form>
)}
</Formik>
);
};
export default SoundUpload;

View File

@@ -0,0 +1,14 @@
import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader";
import SoundUpload from "./SoundUpload";
const SoundUploadCard = () => {
return (
<Card className="p-4">
<CardHeader title={"Sound upload"} />
<SoundUpload />
</Card>
);
};
export default SoundUploadCard;

View File

@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { SightingType } from "../../types/types"; import type { SightingType } from "../../types/types";
import { BLANK_IMG } from "../../utils/utils"; import { BLANK_IMG, getSoundFileURL } from "../../utils/utils";
import NumberPlate from "../PlateStack/NumberPlate"; import NumberPlate from "../PlateStack/NumberPlate";
import Card from "../UI/Card"; import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader"; import CardHeader from "../UI/CardHeader";
@@ -15,6 +15,7 @@ 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"; import { useNPEDContext } from "../../context/NPEDUserContext";
import { useSoundContext } from "../../context/SoundContext";
function useNow(tickMs = 1000) { function useNow(tickMs = 1000) {
const [, setNow] = useState(() => Date.now()); const [, setNow] = useState(() => Date.now());
@@ -39,7 +40,13 @@ export default function SightingHistoryWidget({
title, title,
}: SightingHistoryProps) { }: SightingHistoryProps) {
useNow(1000); useNow(1000);
const { play } = useSound(popup); const { state } = useSoundContext();
const soundSrc = useMemo(() => {
return getSoundFileURL(state.NPEDsound) ?? popup;
}, [state.NPEDsound]);
const { play } = useSound(soundSrc);
const { const {
sightings, sightings,
setSelectedSighting, setSelectedSighting,

View File

@@ -9,6 +9,7 @@ type NavigationArrowProps = {
const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => { const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
const navigate = useNavigate(); const navigate = useNavigate();
const navigationDest = (side: string | undefined) => { const navigationDest = (side: string | undefined) => {
if (settingsPage) { if (settingsPage) {
navigate("/"); navigate("/");

View File

@@ -0,0 +1,18 @@
import { createContext, useContext, type Dispatch } from "react";
import type { SoundAction, SoundState } from "../types/types";
type SoundContextType = {
state: SoundState;
dispatch: Dispatch<SoundAction>;
};
export const SoundContext = createContext<SoundContextType | undefined>(
undefined
);
export const useSoundContext = () => {
const ctx = useContext(SoundContext);
if (!ctx)
throw new Error("useSoundContext must be used within <SoundContext>");
return ctx;
};

View File

@@ -0,0 +1,17 @@
import { useMemo, useReducer, type ReactNode } from "react";
import { SoundContext } from "../SoundContext";
import { initialState, reducer } from "../reducers/SoundContextReducer";
type SoundContextProviderProps = {
children: ReactNode;
};
const SoundContextProvider = ({ children }: SoundContextProviderProps) => {
const [state, dispatch] = useReducer(reducer, initialState);
const value = useMemo(() => ({ state, dispatch }), [state, dispatch]);
return (
<SoundContext.Provider value={value}>{children}</SoundContext.Provider>
);
};
export default SoundContextProvider;

View File

@@ -0,0 +1,38 @@
import type { SoundAction, SoundState } from "../../types/types";
export const initialState: SoundState = {
sightingSound: "switch",
NPEDsound: "popup",
hotlists: [],
soundOptions: [
{ name: "switch (Default)", soundFile: null },
{ name: "popup", soundFile: null },
{ name: "notification", soundFile: null },
],
};
export function reducer(state: SoundState, action: SoundAction): SoundState {
switch (action.type) {
case "UPDATE": {
return {
...state,
sightingSound: action.payload.sightingSound,
NPEDsound: action.payload.NPEDsound,
hotlists: action.payload.hotlists.map((hotlist) => ({
name: hotlist.name,
sound: hotlist.sound,
})),
};
}
case "ADD": {
return {
...state,
soundOptions: [...(state.soundOptions ?? []), action.payload],
};
}
default:
return state;
}
}

View File

@@ -1,7 +1,9 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useMemo, 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 { useSoundContext } from "../context/SoundContext";
import { getSoundFileURL } from "../utils/utils";
import switchSound from "../assets/sounds/ui/switch.mp3"; import switchSound from "../assets/sounds/ui/switch.mp3";
async function fetchSighting( async function fetchSighting(
@@ -14,6 +16,7 @@ async function fetchSighting(
} }
export function useSightingFeed(url: string | undefined) { export function useSightingFeed(url: string | undefined) {
const { state } = useSoundContext();
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 [sessionStarted, setSessionStarted] = useState(false);
@@ -23,8 +26,22 @@ export function useSightingFeed(url: string | undefined) {
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>( const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(
null null
); );
const first = useRef(true);
useSoundOnChange(switchSound, latestRef, { const trigger = useMemo(() => {
if (latestRef == null) return null;
if (first.current) {
first.current = false;
return Symbol("skip");
}
return latestRef;
}, [latestRef]);
const soundSrc = useMemo(() => {
return getSoundFileURL(state.sightingSound) ?? switchSound;
}, [state.sightingSound]);
//use latestref instead of trigger to revert back
useSoundOnChange(soundSrc, trigger, {
volume: 1, volume: 1,
}); });

View File

@@ -1,64 +0,0 @@
// 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]);
}

View File

@@ -8,6 +8,8 @@ import ModemCard from "../components/SettingForms/WiFi&Modem/ModemCard";
import SystemCard from "../components/SettingForms/System/SystemCard"; import SystemCard from "../components/SettingForms/System/SystemCard";
import { Toaster } from "sonner"; import { Toaster } from "sonner";
import { useNPEDAuth } from "../hooks/useNPEDAuth"; import { useNPEDAuth } from "../hooks/useNPEDAuth";
import SoundSettingsCard from "../components/SettingForms/Sound/SoundSettingsCard";
import SoundUploadCard from "../components/SettingForms/Sound/SoundUploadCard";
const SystemSettings = () => { const SystemSettings = () => {
useNPEDAuth(); useNPEDAuth();
@@ -20,6 +22,7 @@ const SystemSettings = () => {
<Tab>Output</Tab> <Tab>Output</Tab>
<Tab>Integrations</Tab> <Tab>Integrations</Tab>
<Tab>WiFi and Modem</Tab> <Tab>WiFi and Modem</Tab>
<Tab>Sound</Tab>
</TabList> </TabList>
<TabPanel> <TabPanel>
<div className="flex flex-col space-y-3"> <div className="flex flex-col space-y-3">
@@ -43,6 +46,12 @@ const SystemSettings = () => {
<ModemCard /> <ModemCard />
</div> </div>
</TabPanel> </TabPanel>
<TabPanel>
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-4 px-2 sm:px-4 lg:px-0 w-full">
<SoundSettingsCard />
<SoundUploadCard />
</div>
</TabPanel>
</Tabs> </Tabs>
<Toaster /> <Toaster />
</div> </div>

View File

@@ -262,6 +262,46 @@ export type ZoomLevel = {
level?: number; level?: number;
}; };
export type SoundValue = string;
export type Hotlist = {
name: string;
sound: SoundValue;
};
export type FormValues = {
sightingSound: SoundValue;
NPEDsound: SoundValue;
hotlists: Hotlist[];
};
export type SoundUploadValue = {
name: string;
soundFile: File | null;
};
export type SoundState = {
sightingSound: SoundValue;
NPEDsound: SoundValue;
hotlists: Hotlist[];
soundOptions?: SoundUploadValue[];
};
type UpdateAction = {
type: "UPDATE";
payload: {
sightingSound: SoundValue;
NPEDsound: SoundValue;
hotlists: Hotlist[];
};
};
type AddAction = {
type: "ADD";
payload: SoundUploadValue;
};
export type SoundAction = UpdateAction | AddAction;
export type WifiSettingValues = { export type WifiSettingValues = {
ssid: string; ssid: string;
password: string; password: string;

View File

@@ -1,3 +1,16 @@
import switchSound from "../assets/sounds/ui/switch.mp3";
import popup from "../assets/sounds/ui/popup_open.mp3";
import notification from "../assets/sounds/ui/notification.mp3";
export function getSoundFileURL(name: string) {
const sounds: Record<string, string> = {
switch: switchSound,
popup: popup,
notification: notification,
};
return sounds[name] ?? null;
}
const randomChars = () => { const randomChars = () => {
const uppercaseAsciiStart = 65; const uppercaseAsciiStart = 65;
const letterIndex = Math.floor(Math.random() * 26); const letterIndex = Math.floor(Math.random() * 26);