Files
kiss-translator/src/hooks/Setting.js

120 lines
2.5 KiB
JavaScript
Raw Normal View History

import {
createContext,
useCallback,
useContext,
useMemo,
useEffect,
} from "react";
import Alert from "@mui/material/Alert";
2025-10-13 11:29:22 +08:00
import {
STOKEY_SETTING,
DEFAULT_SETTING,
KV_SETTING_KEY,
MSG_SET_LOGLEVEL,
} from "../config";
2023-08-30 18:05:37 +08:00
import { useStorage } from "./Storage";
import { debounceSyncMeta } from "../libs/storage";
import Loading from "./Loading";
import { logger } from "../libs/log";
2025-10-13 11:29:22 +08:00
import { sendBgMsg } from "../libs/msg";
2025-10-14 22:41:18 +08:00
import { isExt } from "../libs/client";
2023-07-20 13:45:41 +08:00
2023-08-30 18:05:37 +08:00
const SettingContext = createContext({
setting: DEFAULT_SETTING,
updateSetting: () => {},
reloadSetting: () => {},
2023-08-30 18:05:37 +08:00
});
2025-11-15 21:05:06 +08:00
export function SettingProvider({ children, isSettingPage }) {
const {
data: setting,
isLoading,
update,
reload,
2025-11-15 21:05:06 +08:00
} = useStorage(
STOKEY_SETTING,
DEFAULT_SETTING,
isSettingPage ? KV_SETTING_KEY : ""
);
2023-09-01 16:39:57 +08:00
2025-10-15 12:43:24 +08:00
useEffect(() => {
if (typeof setting?.darkMode === "boolean") {
update((currentSetting) => ({
...currentSetting,
darkMode: currentSetting.darkMode ? "dark" : "light",
}));
}
}, [setting?.darkMode, update]);
useEffect(() => {
2025-11-15 21:05:06 +08:00
if (!isSettingPage) return;
(async () => {
try {
logger.setLevel(setting?.logLevel);
2025-10-14 22:41:18 +08:00
if (isExt) {
await sendBgMsg(MSG_SET_LOGLEVEL, setting?.logLevel);
}
} catch (error) {
logger.error("Failed to fetch log level, using default.", error);
}
})();
2025-11-15 21:05:06 +08:00
}, [isSettingPage, setting?.logLevel]);
2023-08-30 18:05:37 +08:00
const updateSetting = useCallback(
(objOrFn) => {
update(objOrFn);
debounceSyncMeta(KV_SETTING_KEY);
},
[update]
);
const updateChild = useCallback(
(key) => async (obj) => {
updateSetting((prev) => ({
...prev,
[key]: { ...(prev?.[key] || {}), ...obj },
}));
2023-08-30 18:05:37 +08:00
},
[updateSetting]
);
const value = useMemo(
() => ({
setting,
updateSetting,
updateChild,
reloadSetting: reload,
}),
[setting, updateSetting, updateChild, reload]
2023-08-30 18:05:37 +08:00
);
if (isLoading) {
return <Loading />;
}
if (!setting) {
<center>
<Alert severity="error" sx={{ maxWidth: 600, margin: "60px auto" }}>
<p>数据加载出错请刷新页面或卸载后重新安装</p>
<p>
Data loading error, please refresh the page or uninstall and
reinstall.
</p>
</Alert>
</center>;
2023-09-08 13:53:33 +08:00
}
2023-08-30 18:05:37 +08:00
return (
<SettingContext.Provider value={value}>{children}</SettingContext.Provider>
2023-08-30 18:05:37 +08:00
);
2023-07-20 13:45:41 +08:00
}
/**
2023-08-30 18:05:37 +08:00
* 设置 hook
2023-07-20 13:45:41 +08:00
* @returns
*/
2023-08-30 18:05:37 +08:00
export function useSetting() {
return useContext(SettingContext);
2023-07-20 13:45:41 +08:00
}