Initialisieren
This commit is contained in:
53
components/providers/sound-provider.tsx
Normal file
53
components/providers/sound-provider.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { playSound, type SoundName } from "@/lib/sounds";
|
||||
import { useLocalStorage } from "@/hooks/use-local-storage";
|
||||
|
||||
type SoundContextValue = {
|
||||
enabled: boolean;
|
||||
toggle: () => void;
|
||||
play: (name: SoundName) => void;
|
||||
};
|
||||
|
||||
const SoundContext = createContext<SoundContextValue>({
|
||||
enabled: false,
|
||||
toggle: () => {},
|
||||
play: () => {},
|
||||
});
|
||||
|
||||
const STORAGE_KEY = "entscheidomat-sound";
|
||||
|
||||
export function SoundProvider({ children }: { children: ReactNode }) {
|
||||
const [enabled, setEnabled] = useLocalStorage(STORAGE_KEY, true);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setEnabled((prev) => !prev);
|
||||
}, [setEnabled]);
|
||||
|
||||
const play = useCallback(
|
||||
(name: SoundName) => {
|
||||
if (enabled) playSound(name);
|
||||
},
|
||||
[enabled],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ enabled, toggle, play }),
|
||||
[enabled, toggle, play],
|
||||
);
|
||||
|
||||
return (
|
||||
<SoundContext.Provider value={value}>{children}</SoundContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSound() {
|
||||
return useContext(SoundContext);
|
||||
}
|
||||
Reference in New Issue
Block a user