From 572d81ecef1521a0c8d7b4c6277121109ed3ac9a Mon Sep 17 00:00:00 2001 From: GyDi Date: Sun, 20 Nov 2022 20:12:58 +0800 Subject: [PATCH] fix: use verge hook --- src/components/layout/layout-traffic.tsx | 7 +-- src/components/layout/use-custom-theme.ts | 9 ++- src/components/proxy/proxy-groups.tsx | 14 ++--- src/components/proxy/proxy-head.tsx | 13 ++--- src/components/proxy/use-head-state.ts | 55 ------------------- src/components/setting/mods/core-switch.tsx | 13 ++--- src/components/setting/mods/hotkey-viewer.tsx | 15 ++--- src/components/setting/mods/misc-viewer.tsx | 10 ++-- .../setting/mods/sysproxy-viewer.tsx | 19 ++----- src/components/setting/mods/web-ui-viewer.tsx | 25 +++------ src/components/setting/setting-system.tsx | 31 ++++------- src/components/setting/setting-theme.tsx | 14 ++--- src/components/setting/setting-verge.tsx | 25 +++------ .../{use-verge-config.ts => use-verge.ts} | 12 ++-- src/pages/_layout.tsx | 10 ++-- 15 files changed, 84 insertions(+), 188 deletions(-) rename src/hooks/{use-verge-config.ts => use-verge.ts} (56%) diff --git a/src/components/layout/layout-traffic.tsx b/src/components/layout/layout-traffic.tsx index b122d21..296f677 100644 --- a/src/components/layout/layout-traffic.tsx +++ b/src/components/layout/layout-traffic.tsx @@ -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(); // 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(); diff --git a/src/components/layout/use-custom-theme.ts b/src/components/layout/use-custom-theme.ts index 7c52371..595444e 100644 --- a/src/components/layout/use-custom-theme.ts +++ b/src/components/layout/use-custom-theme.ts @@ -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(() => { diff --git a/src/components/proxy/proxy-groups.tsx b/src/components/proxy/proxy-groups.tsx index ebaccc8..94b8992 100644 --- a/src/components/proxy/proxy-groups.tsx +++ b/src/components/proxy/proxy-groups.tsx @@ -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(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!)) { diff --git a/src/components/proxy/proxy-head.tsx b/src/components/proxy/proxy-head.tsx index 04bc6ca..0515f99 100644 --- a/src/components/proxy/proxy-head.tsx +++ b/src/components/proxy/proxy-head.tsx @@ -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 ( diff --git a/src/components/proxy/use-head-state.ts b/src/components/proxy/use-head-state.ts index 630f594..daba79b 100644 --- a/src/components/proxy/use-head-state.ts +++ b/src/components/proxy/use-head-state.ts @@ -24,61 +24,6 @@ export const DEFAULT_STATE: HeadState = { testUrl: "", }; -export default function useHeadState(groupName: string) { - const current = useRecoilValue(atomCurrentProfile); - - const [state, setState] = useState(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) => { - 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); diff --git a/src/components/setting/mods/core-switch.tsx b/src/components/setting/mods/core-switch.tsx index b451131..c0a4417 100644 --- a/src/components/setting/mods/core-switch.tsx +++ b/src/components/setting/mods/core-switch.tsx @@ -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(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"); diff --git a/src/components/setting/mods/hotkey-viewer.tsx b/src/components/setting/mods/hotkey-viewer.tsx index 7cabed3..ace2ad0 100644 --- a/src/components/setting/mods/hotkey-viewer.tsx +++ b/src/components/setting/mods/hotkey-viewer.tsx @@ -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>({}); @@ -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()); } diff --git a/src/components/setting/mods/misc-viewer.tsx b/src/components/setting/mods/misc-viewer.tsx index d747eba..098dd3f 100644 --- a/src/components/setting/mods/misc-viewer.tsx +++ b/src/components/setting/mods/misc-viewer.tsx @@ -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 { diff --git a/src/components/setting/mods/sysproxy-viewer.tsx b/src/components/setting/mods/sysproxy-viewer.tsx index c442ef4..42b8735 100644 --- a/src/components/setting/mods/sysproxy-viewer.tsx +++ b/src/components/setting/mods/sysproxy-viewer.tsx @@ -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()); diff --git a/src/components/setting/mods/web-ui-viewer.tsx b/src/components/setting/mods/web-ui-viewer.tsx index 18b0bf3..e0aafb0 100644 --- a/src/components/setting/mods/web-ui-viewer.tsx +++ b/src/components/setting/mods/web-ui-viewer.tsx @@ -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); diff --git a/src/components/setting/setting-system.tsx b/src/components/setting/setting-system.tsx index ee0dc6f..ba5db0b 100644 --- a/src/components/setting/setting-system.tsx +++ b/src/components/setting/setting-system.tsx @@ -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) => { - 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 })} > @@ -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 })} > @@ -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 })} > @@ -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 })} > @@ -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 })} > diff --git a/src/components/setting/setting-theme.tsx b/src/components/setting/setting-theme.tsx index 13ea2bc..041eec8 100644 --- a/src/components/setting/setting-theme.tsx +++ b/src/components/setting/setting-theme.tsx @@ -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); diff --git a/src/components/setting/setting-verge.tsx b/src/components/setting/setting-verge.tsx index 7bfa416..2616def 100644 --- a/src/components/setting/setting-verge.tsx +++ b/src/components/setting/setting-verge.tsx @@ -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) => { - 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 })} >