mirror of
https://github.com/Vomitblood/stort.git
synced 2025-03-29 18:21:00 +08:00
92 lines
2.7 KiB
TypeScript
92 lines
2.7 KiB
TypeScript
import { createContext, FC, ReactNode, useContext, useEffect, useState } from "react";
|
|
import { logcat } from "../lib/logcatService";
|
|
import { defaultSettings, readConfigFile, SettingsType, writeConfigFile } from "../lib/settings";
|
|
import { useAtom } from "jotai";
|
|
import { stagedSettingsAtom } from "../lib/store/jotai/settings";
|
|
|
|
// settings context
|
|
type SettingsContextProps = {
|
|
fetchSettings: () => void;
|
|
resetSettings: () => void;
|
|
settings: SettingsType;
|
|
settingsLoading: boolean;
|
|
updateSettings: (updates: SettingsType) => void;
|
|
};
|
|
|
|
const SettingsContext = createContext<SettingsContextProps | undefined>(undefined);
|
|
|
|
export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
|
logcat.log("Initializing settings...", "INFO");
|
|
|
|
// atoms
|
|
const [stagedSettings, setStagedSettings] = useAtom(stagedSettingsAtom);
|
|
|
|
// states
|
|
const [settings, setSettings] = useState<SettingsType>(defaultSettings);
|
|
const [settingsLoading, setSettingsLoading] = useState<boolean>(true);
|
|
|
|
const fetchSettings = async () => {
|
|
try {
|
|
const existingSettings = await readConfigFile();
|
|
// set settings state to existing settings
|
|
setSettings(existingSettings);
|
|
// also update the settings atom
|
|
setStagedSettings(existingSettings);
|
|
logcat.log("Settings loaded successfully", "INFO");
|
|
} catch (error) {
|
|
logcat.log(`Failed to load settings: ${error}`, "ERROR");
|
|
} finally {
|
|
setSettingsLoading(false);
|
|
}
|
|
};
|
|
|
|
const updateSettings = async (newSettings: SettingsType) => {
|
|
try {
|
|
await writeConfigFile(newSettings);
|
|
setSettings(newSettings);
|
|
logcat.log("Settings updated successfully", "INFO");
|
|
} catch (error) {
|
|
logcat.log(`Failed to update settings: ${error}`, "ERROR");
|
|
}
|
|
};
|
|
|
|
// set settings state to default values
|
|
// and write default values to the settings file
|
|
const resetSettings = async () => {
|
|
try {
|
|
await writeConfigFile(defaultSettings);
|
|
setSettings(defaultSettings);
|
|
logcat.log("Settings reset successfully", "INFO");
|
|
} catch (error) {
|
|
logcat.log(`Failed to reset settings: ${error}`, "ERROR");
|
|
}
|
|
};
|
|
|
|
// fetch user settings from local on first load every time
|
|
useEffect(() => {
|
|
fetchSettings();
|
|
}, []);
|
|
|
|
return (
|
|
<SettingsContext.Provider
|
|
value={{
|
|
fetchSettings,
|
|
resetSettings,
|
|
settings,
|
|
settingsLoading,
|
|
updateSettings,
|
|
}}
|
|
>
|
|
{children}
|
|
</SettingsContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useSettings = () => {
|
|
const context = useContext(SettingsContext);
|
|
if (context === undefined) {
|
|
throw new Error("Please use useSettings only within a SettingsProvider");
|
|
}
|
|
return context;
|
|
};
|