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

View File

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

View File

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

View File

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

View File

@ -24,61 +24,6 @@ export const DEFAULT_STATE: HeadState = {
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() {
const current = useRecoilValue(atomCurrentProfile);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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