fix: use verge hook

This commit is contained in:
GyDi 2022-11-20 20:12:58 +08:00
parent a4ce7a4037
commit 572d81ecef
No known key found for this signature in database
GPG Key ID: 9C3AD40F1F99880A
15 changed files with 84 additions and 188 deletions

View File

@ -1,12 +1,11 @@
import useSWR from "swr";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useRecoilValue } from "recoil"; import { useRecoilValue } from "recoil";
import { Box, Typography } from "@mui/material"; import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material"; import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { getInformation } from "@/services/api"; import { getInformation } from "@/services/api";
import { getVergeConfig } from "@/services/cmds";
import { atomClashPort } from "@/services/states"; import { atomClashPort } from "@/services/states";
import { useVerge } from "@/hooks/use-verge";
import TrafficGraph from "./traffic-graph"; import TrafficGraph from "./traffic-graph";
import useLogSetup from "./use-log-setup"; import useLogSetup from "./use-log-setup";
import parseTraffic from "@/utils/parse-traffic"; import parseTraffic from "@/utils/parse-traffic";
@ -20,8 +19,8 @@ const LayoutTraffic = () => {
const trafficRef = useRef<any>(); const trafficRef = useRef<any>();
// whether hide traffic graph // whether hide traffic graph
const { data } = useSWR("getVergeConfig", getVergeConfig); const { verge } = useVerge();
const trafficGraph = data?.traffic_graph ?? true; const trafficGraph = verge?.traffic_graph ?? true;
// setup log ws during layout // setup log ws during layout
useLogSetup(); useLogSetup();

View File

@ -1,18 +1,17 @@
import useSWR from "swr";
import { useEffect, useMemo } from "react"; import { useEffect, useMemo } from "react";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import { createTheme } from "@mui/material"; import { createTheme } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window"; import { appWindow } from "@tauri-apps/api/window";
import { getVergeConfig } from "@/services/cmds";
import { atomThemeMode } from "@/services/states"; import { atomThemeMode } from "@/services/states";
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme"; import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
import { useVerge } from "@/hooks/use-verge";
/** /**
* custome theme * custom theme
*/ */
export default function useCustomTheme() { export default function useCustomTheme() {
const { data } = useSWR("getVergeConfig", getVergeConfig); const { verge } = useVerge();
const { theme_mode, theme_setting } = data ?? {}; const { theme_mode, theme_setting } = verge ?? {};
const [mode, setMode] = useRecoilState(atomThemeMode); const [mode, setMode] = useRecoilState(atomThemeMode);
useEffect(() => { useEffect(() => {

View File

@ -1,12 +1,6 @@
import { useRef } from "react"; import { useRef } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { import { Box, ListItem, ListItemText, Typography } from "@mui/material";
Box,
Divider,
ListItem,
ListItemText,
Typography,
} from "@mui/material";
import { Virtuoso, type VirtuosoHandle } from "react-virtuoso"; import { Virtuoso, type VirtuosoHandle } from "react-virtuoso";
import { import {
ExpandLessRounded, ExpandLessRounded,
@ -21,7 +15,7 @@ import {
deleteConnection, deleteConnection,
} from "@/services/api"; } from "@/services/api";
import { useProfiles } from "@/hooks/use-profiles"; import { useProfiles } from "@/hooks/use-profiles";
import { useVergeConfig } from "@/hooks/use-verge-config"; import { useVerge } from "@/hooks/use-verge";
import { useRenderList, type IRenderItem } from "./use-render-list"; import { useRenderList, type IRenderItem } from "./use-render-list";
import { HeadState } from "./use-head-state"; import { HeadState } from "./use-head-state";
import { ProxyHead } from "./proxy-head"; import { ProxyHead } from "./proxy-head";
@ -37,7 +31,7 @@ export const ProxyGroups = (props: Props) => {
const { renderList, onProxies, onHeadState } = useRenderList(mode); const { renderList, onProxies, onHeadState } = useRenderList(mode);
const { data: vergeConfig } = useVergeConfig(); const { verge } = useVerge();
const { current, patchCurrent } = useProfiles(); const { current, patchCurrent } = useProfiles();
const virtuosoRef = useRef<VirtuosoHandle>(null); const virtuosoRef = useRef<VirtuosoHandle>(null);
@ -52,7 +46,7 @@ export const ProxyGroups = (props: Props) => {
onProxies(); onProxies();
// 断开连接 // 断开连接
if (vergeConfig?.auto_close_connection) { if (verge?.auto_close_connection) {
getConnections().then(({ connections }) => { getConnections().then(({ connections }) => {
connections.forEach((conn) => { connections.forEach((conn) => {
if (conn.chains.includes(now!)) { if (conn.chains.includes(now!)) {

View File

@ -14,10 +14,10 @@ import {
SortByAlphaRounded, SortByAlphaRounded,
SortRounded, SortRounded,
} from "@mui/icons-material"; } from "@mui/icons-material";
import { useVergeConfig } from "@/hooks/use-verge-config"; import { useVerge } from "@/hooks/use-verge";
import delayManager from "@/services/delay";
import type { HeadState } from "./use-head-state"; import type { HeadState } from "./use-head-state";
import type { ProxySortType } from "./use-filter-sort"; import type { ProxySortType } from "./use-filter-sort";
import delayManager from "@/services/delay";
interface Props { interface Props {
sx?: SxProps; sx?: SxProps;
@ -42,14 +42,11 @@ export const ProxyHead = (props: Props) => {
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, []); }, []);
const { data: vergeConfig } = useVergeConfig(); const { verge } = useVerge();
useEffect(() => { useEffect(() => {
delayManager.setUrl( delayManager.setUrl(groupName, testUrl || verge?.default_latency_test!);
groupName, }, [groupName, testUrl, verge?.default_latency_test]);
testUrl || vergeConfig?.default_latency_test!
);
}, [groupName, testUrl, vergeConfig?.default_latency_test]);
return ( return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}> <Box sx={{ display: "flex", alignItems: "center", ...sx }}>

View File

@ -24,61 +24,6 @@ export const DEFAULT_STATE: HeadState = {
testUrl: "", testUrl: "",
}; };
export default function useHeadState(groupName: string) {
const current = useRecoilValue(atomCurrentProfile);
const [state, setState] = useState<HeadState>(DEFAULT_STATE);
useEffect(() => {
if (!current) {
setState(DEFAULT_STATE);
return;
}
try {
const data = JSON.parse(
localStorage.getItem(HEAD_STATE_KEY)!
) as HeadStateStorage;
const value = data[current][groupName] || DEFAULT_STATE;
if (value && typeof value === "object") {
setState({ ...DEFAULT_STATE, ...value });
} else {
setState(DEFAULT_STATE);
}
} catch {}
}, [current, groupName]);
const setHeadState = useCallback(
(obj: Partial<HeadState>) => {
setState((old) => {
const ret = { ...old, ...obj };
setTimeout(() => {
try {
const item = localStorage.getItem(HEAD_STATE_KEY);
let data = (item ? JSON.parse(item) : {}) as HeadStateStorage;
if (!data || typeof data !== "object") data = {};
if (!data[current]) data[current] = {};
data[current][groupName] = ret;
localStorage.setItem(HEAD_STATE_KEY, JSON.stringify(data));
} catch {}
});
return ret;
});
},
[current, groupName]
);
return [state, setHeadState] as const;
}
export function useHeadStateNew() { export function useHeadStateNew() {
const current = useRecoilValue(atomCurrentProfile); const current = useRecoilValue(atomCurrentProfile);

View File

@ -1,9 +1,10 @@
import useSWR, { useSWRConfig } from "swr"; import { mutate } from "swr";
import { useState } from "react"; import { useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { Menu, MenuItem } from "@mui/material"; import { Menu, MenuItem } from "@mui/material";
import { Settings } from "@mui/icons-material"; import { Settings } from "@mui/icons-material";
import { changeClashCore, getVergeConfig } from "@/services/cmds"; import { changeClashCore } from "@/services/cmds";
import { useVerge } from "@/hooks/use-verge";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
const VALID_CORE = [ const VALID_CORE = [
@ -12,21 +13,19 @@ const VALID_CORE = [
]; ];
const CoreSwitch = () => { const CoreSwitch = () => {
const { mutate } = useSWRConfig(); const { verge, mutateVerge } = useVerge();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const [anchorEl, setAnchorEl] = useState<any>(null); const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 }); const [position, setPosition] = useState({ left: 0, top: 0 });
const { clash_core = "clash" } = vergeConfig ?? {}; const { clash_core = "clash" } = verge ?? {};
const onCoreChange = useLockFn(async (core: string) => { const onCoreChange = useLockFn(async (core: string) => {
if (core === clash_core) return; if (core === clash_core) return;
try { try {
await changeClashCore(core); await changeClashCore(core);
mutate("getVergeConfig"); mutateVerge();
setTimeout(() => { setTimeout(() => {
mutate("getClashConfig"); mutate("getClashConfig");
mutate("getVersion"); mutate("getVersion");

View File

@ -1,4 +1,3 @@
import useSWR from "swr";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
@ -11,7 +10,7 @@ import {
styled, styled,
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "@/services/cmds"; import { useVerge } from "@/hooks/use-verge";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { ModalHandler } from "@/hooks/use-modal-handler";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
import HotkeyInput from "./hotkey-input"; import HotkeyInput from "./hotkey-input";
@ -51,10 +50,7 @@ const HotkeyViewer = ({ handler }: Props) => {
}; };
} }
const { data: vergeConfig, mutate: mutateVerge } = useSWR( const { verge, patchVerge } = useVerge();
"getVergeConfig",
getVergeConfig
);
const [hotkeyMap, setHotkeyMap] = useState<Record<string, string[]>>({}); const [hotkeyMap, setHotkeyMap] = useState<Record<string, string[]>>({});
@ -62,7 +58,7 @@ const HotkeyViewer = ({ handler }: Props) => {
if (!open) return; if (!open) return;
const map = {} as typeof hotkeyMap; const map = {} as typeof hotkeyMap;
vergeConfig?.hotkeys?.forEach((text) => { verge?.hotkeys?.forEach((text) => {
const [func, key] = text.split(",").map((e) => e.trim()); const [func, key] = text.split(",").map((e) => e.trim());
if (!func || !key) return; if (!func || !key) return;
@ -74,7 +70,7 @@ const HotkeyViewer = ({ handler }: Props) => {
}); });
setHotkeyMap(map); setHotkeyMap(map);
}, [vergeConfig?.hotkeys, open]); }, [verge?.hotkeys, open]);
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
const hotkeys = Object.entries(hotkeyMap) const hotkeys = Object.entries(hotkeyMap)
@ -93,9 +89,8 @@ const HotkeyViewer = ({ handler }: Props) => {
.filter(Boolean); .filter(Boolean);
try { try {
patchVergeConfig({ hotkeys }); patchVerge({ hotkeys });
setOpen(false); setOpen(false);
mutateVerge();
} catch (err: any) { } catch (err: any) {
Notice.error(err.message || err.toString()); Notice.error(err.message || err.toString());
} }

View File

@ -14,7 +14,7 @@ import {
TextField, TextField,
} from "@mui/material"; } from "@mui/material";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { ModalHandler } from "@/hooks/use-modal-handler";
import { useVergeConfig } from "@/hooks/use-verge-config"; import { useVerge } from "@/hooks/use-verge";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
interface Props { interface Props {
@ -23,7 +23,7 @@ interface Props {
const MiscViewer = ({ handler }: Props) => { const MiscViewer = ({ handler }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data, patchVerge } = useVergeConfig(); const { verge, patchVerge } = useVerge();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [values, setValues] = useState({ const [values, setValues] = useState({
@ -41,11 +41,11 @@ const MiscViewer = ({ handler }: Props) => {
useEffect(() => { useEffect(() => {
if (open) { if (open) {
setValues({ setValues({
autoCloseConnection: data?.auto_close_connection || false, autoCloseConnection: verge?.auto_close_connection || false,
defaultLatencyTest: data?.default_latency_test || "", defaultLatencyTest: verge?.default_latency_test || "",
}); });
} }
}, [open, data]); }, [open, verge]);
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
try { try {

View File

@ -18,11 +18,8 @@ import {
TextField, TextField,
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
import { import { useVerge } from "@/hooks/use-verge";
getSystemProxy, import { getSystemProxy } from "@/services/cmds";
getVergeConfig,
patchVergeConfig,
} from "@/services/cmds";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { ModalHandler } from "@/hooks/use-modal-handler";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
@ -52,17 +49,14 @@ const SysproxyViewer = ({ handler }: Props) => {
}; };
} }
const { data: vergeConfig, mutate: mutateVerge } = useSWR( const { verge, patchVerge } = useVerge();
"getVergeConfig",
getVergeConfig
);
const { const {
enable_system_proxy: enabled, enable_system_proxy: enabled,
enable_proxy_guard, enable_proxy_guard,
system_proxy_bypass, system_proxy_bypass,
proxy_guard_duration, proxy_guard_duration,
} = vergeConfig ?? {}; } = verge ?? {};
const { data: sysproxy } = useSWR( const { data: sysproxy } = useSWR(
open ? "getSystemProxy" : null, open ? "getSystemProxy" : null,
@ -81,7 +75,7 @@ const SysproxyViewer = ({ handler }: Props) => {
bypass: system_proxy_bypass, bypass: system_proxy_bypass,
duration: proxy_guard_duration ?? 10, duration: proxy_guard_duration ?? 10,
}); });
}, [vergeConfig]); }, [verge]);
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
if (value.duration < 5) { if (value.duration < 5) {
@ -102,8 +96,7 @@ const SysproxyViewer = ({ handler }: Props) => {
} }
try { try {
await patchVergeConfig(patch); await patchVerge(patch);
mutateVerge();
setOpen(false); setOpen(false);
} catch (err: any) { } catch (err: any) {
Notice.error(err.message || err.toString()); Notice.error(err.message || err.toString());

View File

@ -10,12 +10,8 @@ import {
DialogTitle, DialogTitle,
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
import { import { useVerge } from "@/hooks/use-verge";
getClashInfo, import { getClashInfo, openWebUrl } from "@/services/cmds";
getVergeConfig,
openWebUrl,
patchVergeConfig,
} from "@/services/cmds";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { ModalHandler } from "@/hooks/use-modal-handler";
import BaseEmpty from "@/components/base/base-empty"; import BaseEmpty from "@/components/base/base-empty";
import WebUIItem from "./web-ui-item"; import WebUIItem from "./web-ui-item";
@ -27,12 +23,10 @@ interface Props {
const WebUIViewer = ({ handler, onError }: Props) => { const WebUIViewer = ({ handler, onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: vergeConfig, mutate: mutateVerge } = useSWR(
"getVergeConfig",
getVergeConfig
);
const webUIList = vergeConfig?.web_ui_list || []; const { verge, patchVerge, mutateVerge } = useVerge();
const webUIList = verge?.web_ui_list || [];
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
@ -47,24 +41,21 @@ const WebUIViewer = ({ handler, onError }: Props) => {
const handleAdd = useLockFn(async (value: string) => { const handleAdd = useLockFn(async (value: string) => {
const newList = [value, ...webUIList]; const newList = [value, ...webUIList];
mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false); mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false);
await patchVergeConfig({ web_ui_list: newList }); await patchVerge({ web_ui_list: newList });
await mutateVerge();
}); });
const handleChange = useLockFn(async (index: number, value?: string) => { const handleChange = useLockFn(async (index: number, value?: string) => {
const newList = [...webUIList]; const newList = [...webUIList];
newList[index] = value ?? ""; newList[index] = value ?? "";
mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false); mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false);
await patchVergeConfig({ web_ui_list: newList }); await patchVerge({ web_ui_list: newList });
await mutateVerge();
}); });
const handleDelete = useLockFn(async (index: number) => { const handleDelete = useLockFn(async (index: number) => {
const newList = [...webUIList]; const newList = [...webUIList];
newList.splice(index, 1); newList.splice(index, 1);
mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false); mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false);
await patchVergeConfig({ web_ui_list: newList }); await patchVerge({ web_ui_list: newList });
await mutateVerge();
}); });
const { data: clashInfo } = useSWR("getClashInfo", getClashInfo); const { data: clashInfo } = useSWR("getClashInfo", getClashInfo);

View File

@ -3,11 +3,8 @@ import { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { IconButton, Switch } from "@mui/material"; import { IconButton, Switch } from "@mui/material";
import { ArrowForward, PrivacyTipRounded, Settings } from "@mui/icons-material"; import { ArrowForward, PrivacyTipRounded, Settings } from "@mui/icons-material";
import { import { checkService } from "@/services/cmds";
checkService, import { useVerge } from "@/hooks/use-verge";
getVergeConfig,
patchVergeConfig,
} from "@/services/cmds";
import { SettingList, SettingItem } from "./setting"; import { SettingList, SettingItem } from "./setting";
import useModalHandler from "@/hooks/use-modal-handler"; import useModalHandler from "@/hooks/use-modal-handler";
import getSystem from "@/utils/get-system"; import getSystem from "@/utils/get-system";
@ -24,17 +21,14 @@ const isWIN = getSystem() === "windows";
const SettingSystem = ({ onError }: Props) => { const SettingSystem = ({ onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: vergeConfig, mutate: mutateVerge } = useSWR( const { verge, mutateVerge, patchVerge } = useVerge();
"getVergeConfig",
getVergeConfig
);
// service mode // service mode
const [serviceOpen, setServiceOpen] = useState(false); const [serviceOpen, setServiceOpen] = useState(false);
const { data: serviceStatus } = useSWR( const { data: serviceStatus } = useSWR(
isWIN ? "checkService" : null, isWIN ? "checkService" : null,
checkService, checkService,
{ revalidateIfStale: true, shouldRetryOnError: false } { revalidateIfStale: false, shouldRetryOnError: false }
); );
const { const {
@ -43,11 +37,11 @@ const SettingSystem = ({ onError }: Props) => {
enable_service_mode, enable_service_mode,
enable_silent_start, enable_silent_start,
enable_system_proxy, enable_system_proxy,
} = vergeConfig ?? {}; } = verge ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<IVergeConfig>) => { const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...vergeConfig, ...patch }, false); mutateVerge({ ...verge, ...patch }, false);
}; };
const sysproxyHandler = useModalHandler(); const sysproxyHandler = useModalHandler();
@ -63,7 +57,7 @@ const SettingSystem = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_tun_mode: e })} onChange={(e) => onChangeData({ enable_tun_mode: e })}
onGuard={(e) => patchVergeConfig({ enable_tun_mode: e })} onGuard={(e) => patchVerge({ enable_tun_mode: e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
@ -89,7 +83,7 @@ const SettingSystem = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_service_mode: e })} onChange={(e) => onChangeData({ enable_service_mode: e })}
onGuard={(e) => patchVergeConfig({ enable_service_mode: e })} onGuard={(e) => patchVerge({ enable_service_mode: e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
@ -131,10 +125,7 @@ const SettingSystem = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_system_proxy: e })} onChange={(e) => onChangeData({ enable_system_proxy: e })}
onGuard={async (e) => { onGuard={(e) => patchVerge({ enable_system_proxy: e })}
await patchVergeConfig({ enable_system_proxy: e });
mutateVerge(); // update bypass value
}}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
@ -147,7 +138,7 @@ const SettingSystem = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_auto_launch: e })} onChange={(e) => onChangeData({ enable_auto_launch: e })}
onGuard={(e) => patchVergeConfig({ enable_auto_launch: e })} onGuard={(e) => patchVerge({ enable_auto_launch: e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
@ -160,7 +151,7 @@ const SettingSystem = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_silent_start: e })} onChange={(e) => onChangeData({ enable_silent_start: e })}
onGuard={(e) => patchVergeConfig({ enable_silent_start: e })} onGuard={(e) => patchVerge({ enable_silent_start: e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>

View File

@ -1,4 +1,3 @@
import useSWR from "swr";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@ -15,7 +14,7 @@ import {
TextField, TextField,
useTheme, useTheme,
} from "@mui/material"; } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "@/services/cmds"; import { useVerge } from "@/hooks/use-verge";
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme"; import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
interface Props { interface Props {
@ -40,12 +39,10 @@ const SettingTheme = (props: Props) => {
const { open, onClose, onError } = props; const { open, onClose, onError } = props;
const { t } = useTranslation(); const { t } = useTranslation();
const { data: vergeConfig, mutate } = useSWR(
"getVergeConfig",
getVergeConfig
);
const { theme_setting } = vergeConfig ?? {}; const { verge, patchVerge } = useVerge();
const { theme_setting } = verge ?? {};
const [theme, setTheme] = useState(theme_setting || {}); const [theme, setTheme] = useState(theme_setting || {});
useEffect(() => { useEffect(() => {
@ -64,8 +61,7 @@ const SettingTheme = (props: Props) => {
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
try { try {
await patchVergeConfig({ theme_setting: theme }); await patchVerge({ theme_setting: theme });
mutate();
onClose(); onClose();
} catch (err: any) { } catch (err: any) {
onError?.(err); onError?.(err);

View File

@ -1,4 +1,3 @@
import useSWR from "swr";
import { useState } from "react"; import { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
@ -8,13 +7,9 @@ import {
Switch, Switch,
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
import { import { openAppDir, openLogsDir, patchVergeConfig } from "@/services/cmds";
getVergeConfig,
openAppDir,
openLogsDir,
patchVergeConfig,
} from "@/services/cmds";
import { ArrowForward } from "@mui/icons-material"; import { ArrowForward } from "@mui/icons-material";
import { useVerge } from "@/hooks/use-verge";
import { SettingList, SettingItem } from "./setting"; import { SettingList, SettingItem } from "./setting";
import { version } from "@root/package.json"; import { version } from "@root/package.json";
import useModalHandler from "@/hooks/use-modal-handler"; import useModalHandler from "@/hooks/use-modal-handler";
@ -31,19 +26,17 @@ interface Props {
const SettingVerge = ({ onError }: Props) => { const SettingVerge = ({ onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: vergeConfig, mutate: mutateVerge } = useSWR(
"getVergeConfig",
getVergeConfig
);
const { theme_mode, theme_blur, traffic_graph, language } = vergeConfig ?? {}; const { verge, patchVerge, mutateVerge } = useVerge();
const { theme_mode, theme_blur, traffic_graph, language } = verge ?? {};
const [themeOpen, setThemeOpen] = useState(false); const [themeOpen, setThemeOpen] = useState(false);
const [configOpen, setConfigOpen] = useState(false); const [configOpen, setConfigOpen] = useState(false);
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<IVergeConfig>) => { const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...vergeConfig, ...patch }, false); mutateVerge({ ...verge, ...patch }, false);
}; };
const miscHandler = useModalHandler(); const miscHandler = useModalHandler();
@ -60,7 +53,7 @@ const SettingVerge = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={(e: any) => e.target.value} onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ language: e })} onChange={(e) => onChangeData({ language: e })}
onGuard={(e) => patchVergeConfig({ language: e })} onGuard={(e) => patchVerge({ language: e })}
> >
<Select size="small" sx={{ width: 100, "> div": { py: "7.5px" } }}> <Select size="small" sx={{ width: 100, "> div": { py: "7.5px" } }}>
<MenuItem value="zh"></MenuItem> <MenuItem value="zh"></MenuItem>
@ -74,7 +67,7 @@ const SettingVerge = ({ onError }: Props) => {
value={theme_mode} value={theme_mode}
onCatch={onError} onCatch={onError}
onChange={(e) => onChangeData({ theme_mode: e })} onChange={(e) => onChangeData({ theme_mode: e })}
onGuard={(e) => patchVergeConfig({ theme_mode: e })} onGuard={(e) => patchVerge({ theme_mode: e })}
> >
<ThemeModeSwitch /> <ThemeModeSwitch />
</GuardState> </GuardState>
@ -87,7 +80,7 @@ const SettingVerge = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_blur: e })} onChange={(e) => onChangeData({ theme_blur: e })}
onGuard={(e) => patchVergeConfig({ theme_blur: e })} onGuard={(e) => patchVerge({ theme_blur: e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>

View File

@ -1,16 +1,20 @@
import useSWR from "swr"; import useSWR from "swr";
import { getVergeConfig, patchVergeConfig } from "@/services/cmds"; import { getVergeConfig, patchVergeConfig } from "@/services/cmds";
export const useVergeConfig = () => { export const useVerge = () => {
const { data, mutate } = useSWR("getVergeConfig", getVergeConfig); const { data: verge, mutate: mutateVerge } = useSWR(
"getVergeConfig",
getVergeConfig
);
const patchVerge = async (value: Partial<IVergeConfig>) => { const patchVerge = async (value: Partial<IVergeConfig>) => {
await patchVergeConfig(value); await patchVergeConfig(value);
mutate(); mutateVerge();
}; };
return { return {
data, verge,
mutateVerge,
patchVerge, patchVerge,
}; };
}; };

View File

@ -1,7 +1,7 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import i18next from "i18next"; import i18next from "i18next";
import relativeTime from "dayjs/plugin/relativeTime"; import relativeTime from "dayjs/plugin/relativeTime";
import useSWR, { SWRConfig, useSWRConfig } from "swr"; import { SWRConfig, mutate } from "swr";
import { useEffect } from "react"; import { useEffect } from "react";
import { useSetRecoilState } from "recoil"; import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@ -12,7 +12,8 @@ import { appWindow } from "@tauri-apps/api/window";
import { routers } from "./_routers"; import { routers } from "./_routers";
import { getAxios } from "@/services/api"; import { getAxios } from "@/services/api";
import { atomCurrentProfile } from "@/services/states"; import { atomCurrentProfile } from "@/services/states";
import { getVergeConfig, getProfiles } from "@/services/cmds"; import { getProfiles } from "@/services/cmds";
import { useVerge } from "@/hooks/use-verge";
import { ReactComponent as LogoSvg } from "@/assets/image/logo.svg"; import { ReactComponent as LogoSvg } from "@/assets/image/logo.svg";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
import LayoutItem from "@/components/layout/layout-item"; import LayoutItem from "@/components/layout/layout-item";
@ -34,12 +35,11 @@ const OS = getSystem();
const Layout = () => { const Layout = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { theme } = useCustomTheme(); const { theme } = useCustomTheme();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { verge } = useVerge();
const { theme_blur, language } = vergeConfig || {}; const { theme_blur, language } = verge || {};
const setCurrentProfile = useSetRecoilState(atomCurrentProfile); const setCurrentProfile = useSetRecoilState(atomCurrentProfile);