revite/src/context/Settings.tsx

62 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-06-19 07:34:53 -04:00
// This code is more or less redundant, but settings has so little state
// updates that I can't be asked to pass everything through props each
// time when I can just use the Context API.
//
// Replace references to SettingsContext with connectState in the future
// if it does cause problems though.
//
// This now also supports Audio stuff.
import defaultsDeep from "lodash.defaultsdeep";
2021-07-05 06:23:23 -04:00
2021-06-19 07:34:53 -04:00
import { createContext } from "preact";
import { useMemo } from "preact/hooks";
2021-06-19 07:34:53 -04:00
2021-07-05 06:23:23 -04:00
import { connectState } from "../redux/connector";
import {
DEFAULT_SOUNDS,
Settings,
SoundOptions,
} from "../redux/reducers/settings";
import { playSound, Sounds } from "../assets/sounds/Audio";
import { Children } from "../types/Preact";
export const SettingsContext = createContext<Settings>({});
2021-07-05 06:23:23 -04:00
export const SoundContext = createContext<(sound: Sounds) => void>(null!);
2021-06-19 07:34:53 -04:00
interface Props {
2021-07-05 06:23:23 -04:00
children?: Children;
settings: Settings;
2021-06-19 07:34:53 -04:00
}
2021-07-05 06:23:23 -04:00
function SettingsProvider({ settings, children }: Props) {
const play = useMemo(() => {
const enabled: SoundOptions = defaultsDeep(
settings.notification?.sounds ?? {},
DEFAULT_SOUNDS,
);
return (sound: Sounds) => {
if (enabled[sound]) {
playSound(sound);
}
};
}, [settings.notification]);
return (
<SettingsContext.Provider value={settings}>
<SoundContext.Provider value={play}>
{children}
</SoundContext.Provider>
</SettingsContext.Provider>
);
2021-06-19 07:34:53 -04:00
}
2021-07-05 06:23:23 -04:00
export default connectState<Omit<Props, "settings">>(
SettingsProvider,
(state) => {
return {
settings: state.settings,
};
},
);