Refactor sound context and update sound settings functionality; remove console logs and improve sound file handling

This commit is contained in:
2025-10-01 15:21:07 +01:00
parent 1b7b2eec37
commit 68e944a6a2
11 changed files with 100 additions and 53 deletions

View File

@@ -24,7 +24,7 @@ const CameraSettingFields = ({
onZoomLevelChange, onZoomLevelChange,
}: CameraSettingsProps) => { }: CameraSettingsProps) => {
const [showPwd, setShowPwd] = useState(false); const [showPwd, setShowPwd] = useState(false);
console.log(initialData);
const initialValues = useMemo<CameraSettingValues>( const initialValues = useMemo<CameraSettingValues>(
() => ({ () => ({
friendlyName: initialData?.id ?? "", friendlyName: initialData?.id ?? "",
@@ -48,7 +48,6 @@ const CameraSettingFields = ({
}; };
const handleSubmit = (values: CameraSettingValues) => { const handleSubmit = (values: CameraSettingValues) => {
console.log(values);
updateCameraConfig(values); updateCameraConfig(values);
}; };

View File

@@ -12,20 +12,10 @@ const SoundSettingsFields = () => {
{ name: "hotlist2", sound: "" }, { name: "hotlist2", sound: "" },
]; ];
const soundOptions = [ const soundOptions = state?.soundOptions?.map((soundOption) => ({
{ value: soundOption?.name,
value: "switch", label: soundOption?.name,
label: "Switch (Default)", }));
},
{
value: "notification",
label: "Notification",
},
{
value: "popup",
label: "popup",
},
];
const initialValues: FormValues = { const initialValues: FormValues = {
sightingSound: state.sightingSound ?? "switch", sightingSound: state.sightingSound ?? "switch",
@@ -37,7 +27,6 @@ const SoundSettingsFields = () => {
dispatch({ type: "UPDATE", payload: values }); dispatch({ type: "UPDATE", payload: values });
toast.success("Sound settings updated"); toast.success("Sound settings updated");
}; };
console.log(state);
return ( return (
<Formik initialValues={initialValues} onSubmit={handleSubmit}> <Formik initialValues={initialValues} onSubmit={handleSubmit}>
{({ values }) => ( {({ values }) => (
@@ -49,7 +38,7 @@ const SoundSettingsFields = () => {
name="sightingSound" name="sightingSound"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60" className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
> >
{soundOptions.map(({ value, label }) => { {soundOptions?.map(({ value, label }) => {
return ( return (
<option key={value} value={value}> <option key={value} value={value}>
{label} {label}
@@ -65,7 +54,7 @@ const SoundSettingsFields = () => {
name="NPEDsound" name="NPEDsound"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60" className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
> >
{soundOptions.map(({ value, label }) => ( {soundOptions?.map(({ value, label }) => (
<option key={value} value={value}> <option key={value} value={value}>
{label} {label}
</option> </option>
@@ -97,7 +86,7 @@ const SoundSettingsFields = () => {
id={`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" className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
> >
{soundOptions.map(({ value, label }) => ( {soundOptions?.map(({ value, label }) => (
<option key={value} value={value}> <option key={value} value={value}>
{label} {label}
</option> </option>

View File

@@ -1,38 +1,61 @@
import { Form, Formik } from "formik"; import { Form, Formik } from "formik";
import FormGroup from "../components/FormGroup"; import FormGroup from "../components/FormGroup";
import type { SoundUploadValue } from "../../../types/types"; import type { SoundUploadValue } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext";
import { toast } from "sonner";
const SoundUpload = () => { const SoundUpload = () => {
const { dispatch } = useSoundContext();
const initialValues: SoundUploadValue = { const initialValues: SoundUploadValue = {
name: "",
soundFile: null, soundFile: null,
}; };
const handleSubmit = (values: SoundUploadValue) => { const handleSubmit = (values: SoundUploadValue) => {
console.log(values); if (!values.soundFile) {
toast.warning("Please select an audio file");
} else {
dispatch({ type: "ADD", payload: values });
toast.success("Sound file upload successfully");
}
}; };
return ( return (
<Formik initialValues={initialValues} onSubmit={handleSubmit}> <Formik
{({ setFieldValue }) => ( initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
{({ setFieldValue, errors, setFieldError }) => (
<Form> <Form>
<FormGroup> <FormGroup>
<label htmlFor="soundFile">Sighting Sound</label> <label htmlFor="soundFile">Sound File</label>
<input <input
type="file" type="file"
name="soundFile" name="soundFile"
id="sightingSoundinput" id="sightingSoundinput"
accept="audio/mpeg"
onChange={(e) => { onChange={(e) => {
if ( if (
e.target.files && e.target?.files &&
e.target.files[0].type.lastIndexOf(".mp3") e.target?.files[0]?.type === "audio/mpeg"
) ) {
setFieldValue("sightingSound", e.target.files[0]); 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> </FormGroup>
{errors.soundFile && (
<p className="text-red-500 text-sm mt-1">Not an mp3 file</p>
)}
<button <button
type="submit" 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" 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 Upload
</button> </button>

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, getSoundFileName } 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";
@@ -43,8 +43,8 @@ export default function SightingHistoryWidget({
const { state } = useSoundContext(); const { state } = useSoundContext();
const soundSrc = useMemo(() => { const soundSrc = useMemo(() => {
return getSoundFileName(state.sightingSound) ?? popup; return getSoundFileURL(state.NPEDsound) ?? popup;
}, [state.sightingSound]); }, [state.NPEDsound]);
const { play } = useSound(soundSrc); const { play } = useSound(soundSrc);
const { const {

View File

@@ -1,9 +1,9 @@
import { createContext, useContext, type Dispatch } from "react"; import { createContext, useContext, type Dispatch } from "react";
import type { SoundPayload, SoundState } from "../types/types"; import type { SoundAction, SoundState } from "../types/types";
type SoundContextType = { type SoundContextType = {
state: SoundState; state: SoundState;
dispatch: Dispatch<SoundPayload>; dispatch: Dispatch<SoundAction>;
}; };
export const SoundContext = createContext<SoundContextType | undefined>( export const SoundContext = createContext<SoundContextType | undefined>(

View File

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

View File

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

View File

@@ -2,9 +2,8 @@ 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 { useSoundContext } from "../context/SoundContext";
import { getSoundFileName } from "../utils/utils"; 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(
@@ -27,11 +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);
const trigger = useMemo(() => {
if (latestRef == null) return null;
if (first.current) {
first.current = false;
return Symbol("skip");
}
return latestRef;
}, [latestRef]);
const soundSrc = useMemo(() => { const soundSrc = useMemo(() => {
return getSoundFileName(state.sightingSound) ?? switchSound; return getSoundFileURL(state.sightingSound) ?? switchSound;
}, [state.sightingSound]); }, [state.sightingSound]);
useSoundOnChange(soundSrc, latestRef, { //use latestref instead of trigger to revert back
useSoundOnChange(soundSrc, trigger, {
volume: 1, volume: 1,
}); });

View File

@@ -7,7 +7,6 @@ const Dashboard = () => {
const mode = import.meta.env.MODE; const mode = import.meta.env.MODE;
const base_url = `${CAM_BASE}/SightingList/sightingSummary?mostRecentRef=`; const base_url = `${CAM_BASE}/SightingList/sightingSummary?mostRecentRef=`;
console.log(mode); console.log(mode);
console.log(base_url);
return ( return (
<SightingFeedProvider url={base_url}> <SightingFeedProvider url={base_url}>
<div className="mx-auto flex flex-col lg:flex-row gap-2 px-1 sm:px-2 lg:px-0 w-full min-h-screen"> <div className="mx-auto flex flex-col lg:flex-row gap-2 px-1 sm:px-2 lg:px-0 w-full min-h-screen">

View File

@@ -276,6 +276,7 @@ export type FormValues = {
}; };
export type SoundUploadValue = { export type SoundUploadValue = {
name: string;
soundFile: File | null; soundFile: File | null;
}; };
@@ -283,9 +284,21 @@ export type SoundState = {
sightingSound: SoundValue; sightingSound: SoundValue;
NPEDsound: SoundValue; NPEDsound: SoundValue;
hotlists: Hotlist[]; hotlists: Hotlist[];
soundOptions?: SoundUploadValue[];
}; };
export type SoundPayload = { type UpdateAction = {
type: string; type: "UPDATE";
payload: SoundState; payload: {
sightingSound: SoundValue;
NPEDsound: SoundValue;
hotlists: Hotlist[];
};
}; };
type AddAction = {
type: "ADD";
payload: SoundUploadValue;
};
export type SoundAction = UpdateAction | AddAction;

View File

@@ -2,7 +2,7 @@ import switchSound from "../assets/sounds/ui/switch.mp3";
import popup from "../assets/sounds/ui/popup_open.mp3"; import popup from "../assets/sounds/ui/popup_open.mp3";
import notification from "../assets/sounds/ui/notification.mp3"; import notification from "../assets/sounds/ui/notification.mp3";
export function getSoundFileName(name: string) { export function getSoundFileURL(name: string) {
const sounds: Record<string, string> = { const sounds: Record<string, string> = {
switch: switchSound, switch: switchSound,
popup: popup, popup: popup,