feat: add use clash hook

This commit is contained in:
GyDi 2022-11-23 17:44:40 +08:00
parent ffa21fbfd2
commit 28d3691e0b
No known key found for this signature in database
GPG Key ID: 9C3AD40F1F99880A
12 changed files with 196 additions and 191 deletions

View File

@ -1,57 +1,40 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
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 { useClashInfo } from "@/hooks/use-clash";
import { getInformation } from "@/services/api";
import { atomClashPort } from "@/services/states";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import TrafficGraph from "./traffic-graph"; import { TrafficGraph, type TrafficRef } 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";
// setup the traffic // setup the traffic
const LayoutTraffic = () => { const LayoutTraffic = () => {
const portValue = useRecoilValue(atomClashPort); const { clashInfo } = useClashInfo();
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
const [refresh, setRefresh] = useState({});
const trafficRef = useRef<any>();
// whether hide traffic graph // whether hide traffic graph
const { verge } = useVerge(); const { verge } = useVerge();
const trafficGraph = verge?.traffic_graph ?? true; const trafficGraph = verge?.traffic_graph ?? true;
const trafficRef = useRef<TrafficRef>(null);
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
// setup log ws during layout // setup log ws during layout
useLogSetup(); useLogSetup();
useEffect(() => { useEffect(() => {
// should reconnect the traffic ws if (!clashInfo) return;
const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => { const { server = "", secret = "" } = clashInfo;
unlisten.then((fn) => fn()); const ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
};
}, []);
useEffect(() => {
let ws: WebSocket | null = null;
getInformation().then((result) => {
const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
ws.addEventListener("message", (event) => { ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ITrafficItem; const data = JSON.parse(event.data) as ITrafficItem;
trafficRef.current?.appendData(data); trafficRef.current?.appendData(data);
setTraffic(data); setTraffic(data);
}); });
});
return () => ws?.close(); return () => ws?.close();
}, [portValue, refresh]); }, [clashInfo]);
const [up, upUnit] = parseTraffic(traffic.up); const [up, upUnit] = parseTraffic(traffic.up);
const [down, downUnit] = parseTraffic(traffic.down); const [down, downUnit] = parseTraffic(traffic.down);
@ -60,7 +43,7 @@ const LayoutTraffic = () => {
component: "span", component: "span",
color: "primary", color: "primary",
textAlign: "center", textAlign: "center",
sx: { flex: "1 1 54px" }, sx: { flex: "1 1 54px", userSelect: "none" },
}; };
const unitStyle: any = { const unitStyle: any = {
component: "span", component: "span",
@ -78,7 +61,7 @@ const LayoutTraffic = () => {
> >
{trafficGraph && ( {trafficGraph && (
<div style={{ width: "100%", height: 60, marginBottom: 6 }}> <div style={{ width: "100%", height: 60, marginBottom: 6 }}>
<TrafficGraph instance={trafficRef} /> <TrafficGraph ref={trafficRef} />
</div> </div>
)} )}

View File

@ -1,4 +1,4 @@
import { useEffect, useRef } from "react"; import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
import { useTheme } from "@mui/material"; import { useTheme } from "@mui/material";
const maxPoint = 30; const maxPoint = 30;
@ -16,34 +16,40 @@ const defaultList = Array(maxPoint + 2).fill({ up: 0, down: 0 });
type TrafficData = { up: number; down: number }; type TrafficData = { up: number; down: number };
interface Props { export interface TrafficRef {
instance: React.MutableRefObject<{
appendData: (data: TrafficData) => void; appendData: (data: TrafficData) => void;
toggleStyle: () => void; toggleStyle: () => void;
}>;
} }
/** /**
* draw the traffic graph * draw the traffic graph
*/ */
const TrafficGraph = (props: Props) => { export const TrafficGraph = forwardRef<TrafficRef>((props, ref) => {
const { instance } = props;
const countRef = useRef(0); const countRef = useRef(0);
const styleRef = useRef(true); const styleRef = useRef(true);
const listRef = useRef<TrafficData[]>(defaultList); const listRef = useRef<TrafficData[]>(defaultList);
const canvasRef = useRef<HTMLCanvasElement>(null!); const canvasRef = useRef<HTMLCanvasElement>(null!);
const cacheRef = useRef<TrafficData | null>(null);
const { palette } = useTheme(); const { palette } = useTheme();
useImperativeHandle(ref, () => ({
appendData: (data: TrafficData) => {
cacheRef.current = data;
},
toggleStyle: () => {
styleRef.current = !styleRef.current;
},
}));
useEffect(() => { useEffect(() => {
let timer: any; let timer: any;
let cache: TrafficData | null = null;
const zero = { up: 0, down: 0 }; const zero = { up: 0, down: 0 };
const handleData = () => { const handleData = () => {
const data = cache ? cache : zero; const data = cacheRef.current ? cacheRef.current : zero;
cache = null; cacheRef.current = null;
const list = listRef.current; const list = listRef.current;
if (list.length > maxPoint + 2) list.shift(); if (list.length > maxPoint + 2) list.shift();
@ -53,19 +59,9 @@ const TrafficGraph = (props: Props) => {
timer = setTimeout(handleData, 1000); timer = setTimeout(handleData, 1000);
}; };
instance.current = {
appendData: (data: TrafficData) => {
cache = data;
},
toggleStyle: () => {
styleRef.current = !styleRef.current;
},
};
handleData(); handleData();
return () => { return () => {
instance.current = null!;
if (timer) clearTimeout(timer); if (timer) clearTimeout(timer);
}; };
}, []); }, []);
@ -196,6 +192,4 @@ const TrafficGraph = (props: Props) => {
}, [palette]); }, [palette]);
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />; return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
}; });
export default TrafficGraph;

View File

@ -1,48 +1,36 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useEffect, useState } from "react"; import { useEffect } from "react";
import { useRecoilValue, useSetRecoilState } from "recoil"; import { useRecoilValue, useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event";
import { getInformation } from "@/services/api";
import { getClashLogs } from "@/services/cmds"; import { getClashLogs } from "@/services/cmds";
import { useClashInfo } from "@/hooks/use-clash";
import { atomEnableLog, atomLogData } from "@/services/states"; import { atomEnableLog, atomLogData } from "@/services/states";
const MAX_LOG_NUM = 1000; const MAX_LOG_NUM = 1000;
// setup the log websocket // setup the log websocket
export default function useLogSetup() { export const useLogSetup = () => {
const [refresh, setRefresh] = useState({}); const { clashInfo } = useClashInfo();
const enableLog = useRecoilValue(atomEnableLog); const enableLog = useRecoilValue(atomEnableLog);
const setLogData = useSetRecoilState(atomLogData); const setLogData = useSetRecoilState(atomLogData);
useEffect(() => { useEffect(() => {
if (!enableLog) return; if (!enableLog || !clashInfo) return;
getClashLogs().then(setLogData); getClashLogs().then(setLogData);
const handler = (event: MessageEvent<any>) => { const { server = "", secret = "" } = clashInfo;
const ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ILogItem; const data = JSON.parse(event.data) as ILogItem;
const time = dayjs().format("MM-DD HH:mm:ss"); const time = dayjs().format("MM-DD HH:mm:ss");
setLogData((l) => { setLogData((l) => {
if (l.length >= MAX_LOG_NUM) l.shift(); if (l.length >= MAX_LOG_NUM) l.shift();
return [...l, { ...data, time }]; return [...l, { ...data, time }];
}); });
};
const ws = getInformation().then((info) => {
const { server = "", secret = "" } = info;
const ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
return ws;
}); });
const unlisten = listen("verge://refresh-clash-config", () => return () => ws?.close();
setRefresh({}) }, [clashInfo, enableLog]);
);
return () => {
ws.then((ws) => ws?.close());
unlisten.then((fn) => fn());
}; };
}, [refresh, enableLog]);
}

View File

@ -1,55 +1,37 @@
import useSWR from "swr";
import { forwardRef, useImperativeHandle, useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { List, ListItem, ListItemText, TextField } from "@mui/material"; import { List, ListItem, ListItemText, TextField } from "@mui/material";
import { atomClashPort } from "@/services/states"; import { useClashInfo } from "@/hooks/use-clash";
import { getClashConfig } from "@/services/api";
import { patchClashConfig } from "@/services/cmds";
import { BaseDialog, DialogRef, Notice } from "@/components/base"; import { BaseDialog, DialogRef, Notice } from "@/components/base";
export const ClashPortViewer = forwardRef<DialogRef>((props, ref) => { export const ClashPortViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: config, mutate: mutateClash } = useSWR( const { clashInfo, patchInfo } = useClashInfo();
"getClashConfig",
getClashConfig
);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [port, setPort] = useState(config?.["mixed-port"] ?? 9090); const [port, setPort] = useState(clashInfo?.port ?? 7890);
const setGlobalClashPort = useSetRecoilState(atomClashPort);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: () => { open: () => {
if (config?.["mixed-port"]) { if (clashInfo?.port) setPort(clashInfo?.port);
setPort(config["mixed-port"]);
}
setOpen(true); setOpen(true);
}, },
close: () => setOpen(false), close: () => setOpen(false),
})); }));
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
if (port < 1000) { if (port === clashInfo?.port) {
return Notice.error("The port should not < 1000");
}
if (port > 65536) {
return Notice.error("The port should not > 65536");
}
setOpen(false); setOpen(false);
if (port === config?.["mixed-port"]) return; return;
}
try { try {
await patchClashConfig({ "mixed-port": port }); await patchInfo({ "mixed-port": port });
setGlobalClashPort(port); setOpen(false);
Notice.success("Change Clash port successfully!", 1000); Notice.success("Change Clash port successfully!", 1000);
mutateClash();
} catch (err: any) { } catch (err: any) {
Notice.error(err.message || err.toString(), 5000); Notice.error(err.message || err.toString(), 4000);
} }
}); });

View File

@ -1,17 +1,16 @@
import useSWR from "swr";
import { forwardRef, useImperativeHandle, useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { List, ListItem, ListItemText, TextField } from "@mui/material"; import { List, ListItem, ListItemText, TextField } from "@mui/material";
import { getClashInfo, patchClashConfig } from "@/services/cmds"; import { useClashInfo } from "@/hooks/use-clash";
import { getAxios } from "@/services/api";
import { BaseDialog, DialogRef, Notice } from "@/components/base"; import { BaseDialog, DialogRef, Notice } from "@/components/base";
export const ControllerViewer = forwardRef<DialogRef>((props, ref) => { export const ControllerViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const { data: clashInfo, mutate } = useSWR("getClashInfo", getClashInfo); const { clashInfo, patchInfo } = useClashInfo();
const [controller, setController] = useState(clashInfo?.server || ""); const [controller, setController] = useState(clashInfo?.server || "");
const [secret, setSecret] = useState(clashInfo?.secret || ""); const [secret, setSecret] = useState(clashInfo?.secret || "");
@ -26,14 +25,11 @@ export const ControllerViewer = forwardRef<DialogRef>((props, ref) => {
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
try { try {
await patchClashConfig({ "external-controller": controller, secret }); await patchInfo({ "external-controller": controller, secret });
mutate();
// 刷新接口
getAxios(true);
Notice.success("Change Clash Config successfully!", 1000); Notice.success("Change Clash Config successfully!", 1000);
setOpen(false); setOpen(false);
} catch (err) { } catch (err: any) {
console.log(err); Notice.error(err.message || err.toString(), 4000);
} }
}); });

View File

@ -1,23 +1,22 @@
import useSWR from "swr";
import { forwardRef, useImperativeHandle, useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Button, Box, Typography } from "@mui/material"; import { Button, Box, Typography } from "@mui/material";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { getClashInfo, openWebUrl } from "@/services/cmds"; import { openWebUrl } from "@/services/cmds";
import { BaseDialog, BaseEmpty, DialogRef, Notice } from "@/components/base"; import { BaseDialog, BaseEmpty, DialogRef, Notice } from "@/components/base";
import { useClashInfo } from "@/hooks/use-clash";
import { WebUIItem } from "./web-ui-item"; import { WebUIItem } from "./web-ui-item";
export const WebUIViewer = forwardRef<DialogRef>((props, ref) => { export const WebUIViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { clashInfo } = useClashInfo();
const { verge, patchVerge, mutateVerge } = useVerge(); const { verge, patchVerge, mutateVerge } = useVerge();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const { data: clashInfo } = useSWR("getClashInfo", getClashInfo);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: () => setOpen(true), open: () => setOpen(true),
close: () => setOpen(false), close: () => setOpen(false),
@ -53,9 +52,7 @@ export const WebUIViewer = forwardRef<DialogRef>((props, ref) => {
if (url.includes("%port") || url.includes("%secret")) { if (url.includes("%port") || url.includes("%secret")) {
if (!clashInfo) throw new Error("failed to get clash info"); if (!clashInfo) throw new Error("failed to get clash info");
if (!clashInfo.server?.includes(":")) { if (!clashInfo.server?.includes(":")) {
throw new Error( throw new Error(`failed to parse the server "${clashInfo.server}"`);
`failed to parse server with status ${clashInfo.status}`
);
} }
const port = clashInfo.server const port = clashInfo.server

View File

@ -1,4 +1,3 @@
import useSWR from "swr";
import { useRef } from "react"; import { useRef } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
@ -10,9 +9,8 @@ import {
IconButton, IconButton,
} from "@mui/material"; } from "@mui/material";
import { ArrowForward } from "@mui/icons-material"; import { ArrowForward } from "@mui/icons-material";
import { patchClashConfig } from "@/services/cmds";
import { getClashConfig, getVersion, updateConfigs } from "@/services/api";
import { DialogRef } from "@/components/base"; import { DialogRef } from "@/components/base";
import { useClash } from "@/hooks/use-clash";
import { GuardState } from "./mods/guard-state"; import { GuardState } from "./mods/guard-state";
import { CoreSwitch } from "./mods/core-switch"; import { CoreSwitch } from "./mods/core-switch";
import { WebUIViewer } from "./mods/web-ui-viewer"; import { WebUIViewer } from "./mods/web-ui-viewer";
@ -28,18 +26,14 @@ interface Props {
const SettingClash = ({ onError }: Props) => { const SettingClash = ({ onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: clashConfig, mutate: mutateClash } = useSWR( const { clash, version, mutateClash, patchClash } = useClash();
"getClashConfig",
getClashConfig
);
const { data: versionData } = useSWR("getVersion", getVersion);
const { const {
ipv6, ipv6,
"allow-lan": allowLan, "allow-lan": allowLan,
"log-level": logLevel, "log-level": logLevel,
"mixed-port": mixedPort, "mixed-port": mixedPort,
} = clashConfig ?? {}; } = clash ?? {};
const webRef = useRef<DialogRef>(null); const webRef = useRef<DialogRef>(null);
const fieldRef = useRef<DialogRef>(null); const fieldRef = useRef<DialogRef>(null);
@ -50,15 +44,6 @@ const SettingClash = ({ onError }: Props) => {
const onChangeData = (patch: Partial<IConfigData>) => { const onChangeData = (patch: Partial<IConfigData>) => {
mutateClash((old) => ({ ...(old! || {}), ...patch }), false); mutateClash((old) => ({ ...(old! || {}), ...patch }), false);
}; };
const onUpdateData = async (patch: Partial<IConfigData>) => {
await updateConfigs(patch);
await patchClashConfig(patch);
};
// get clash core version
const clashVer = versionData?.premium
? `${versionData.version} Premium`
: versionData?.version || "-";
return ( return (
<SettingList title={t("Clash Setting")}> <SettingList title={t("Clash Setting")}>
@ -74,7 +59,7 @@ const SettingClash = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ "allow-lan": e })} onChange={(e) => onChangeData({ "allow-lan": e })}
onGuard={(e) => onUpdateData({ "allow-lan": e })} onGuard={(e) => patchClash({ "allow-lan": e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
@ -87,7 +72,7 @@ const SettingClash = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ ipv6: e })} onChange={(e) => onChangeData({ ipv6: e })}
onGuard={(e) => onUpdateData({ ipv6: e })} onGuard={(e) => patchClash({ ipv6: e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
@ -100,7 +85,7 @@ const SettingClash = ({ onError }: Props) => {
onCatch={onError} onCatch={onError}
onFormat={(e: any) => e.target.value} onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ "log-level": e })} onChange={(e) => onChangeData({ "log-level": e })}
onGuard={(e) => onUpdateData({ "log-level": e })} onGuard={(e) => patchClash({ "log-level": e })}
> >
<Select size="small" sx={{ width: 100, "> div": { py: "7.5px" } }}> <Select size="small" sx={{ width: 100, "> div": { py: "7.5px" } }}>
<MenuItem value="debug">Debug</MenuItem> <MenuItem value="debug">Debug</MenuItem>
@ -159,7 +144,7 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem label={t("Clash Core")} extra={<CoreSwitch />}> <SettingItem label={t("Clash Core")} extra={<CoreSwitch />}>
<Typography sx={{ py: "7px" }}>{clashVer}</Typography> <Typography sx={{ py: "7px", pr: 1 }}>{version}</Typography>
</SettingItem> </SettingItem>
</SettingList> </SettingList>
); );

83
src/hooks/use-clash.ts Normal file
View File

@ -0,0 +1,83 @@
import useSWR, { mutate } from "swr";
import { useLockFn } from "ahooks";
import {
getAxios,
getClashConfig,
getVersion,
updateConfigs,
} from "@/services/api";
import { getClashInfo, patchClashConfig } from "@/services/cmds";
export const useClash = () => {
const { data: clash, mutate: mutateClash } = useSWR(
"getClashConfig",
getClashConfig
);
const { data: versionData, mutate: mutateVersion } = useSWR(
"getVersion",
getVersion
);
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
await updateConfigs(patch);
await patchClashConfig(patch);
mutateClash();
});
const version = versionData?.premium
? `${versionData.version} Premium`
: versionData?.meta
? `${versionData.version} Meta`
: versionData?.version || "-";
return {
clash,
version,
mutateClash,
mutateVersion,
patchClash,
};
};
export const useClashInfo = () => {
const { data: clashInfo, mutate: mutateInfo } = useSWR(
"getClashInfo",
getClashInfo
);
const patchInfo = async (
patch: Partial<
Pick<IConfigData, "mixed-port" | "external-controller" | "secret">
>
) => {
const hasInfo =
patch["mixed-port"] != null ||
patch["external-controller"] != null ||
patch.secret != null;
if (!hasInfo) return;
if (patch["mixed-port"]) {
const port = patch["mixed-port"];
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
}
await patchClashConfig(patch);
mutateInfo();
mutate("getClashConfig");
// 刷新接口
getAxios(true);
};
return {
clashInfo,
mutateInfo,
patchInfo,
};
};

View File

@ -13,8 +13,9 @@ import { useRecoilState } from "recoil";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { TableChartRounded, TableRowsRounded } from "@mui/icons-material"; import { TableChartRounded, TableRowsRounded } from "@mui/icons-material";
import { closeAllConnections, getInformation } from "@/services/api"; import { closeAllConnections } from "@/services/api";
import { atomConnectionSetting } from "@/services/states"; import { atomConnectionSetting } from "@/services/states";
import { useClashInfo } from "@/hooks/use-clash";
import { BaseEmpty, BasePage } from "@/components/base"; import { BaseEmpty, BasePage } from "@/components/base";
import ConnectionItem from "@/components/connection/connection-item"; import ConnectionItem from "@/components/connection/connection-item";
import ConnectionTable from "@/components/connection/connection-table"; import ConnectionTable from "@/components/connection/connection-table";
@ -25,6 +26,7 @@ type OrderFunc = (list: IConnectionsItem[]) => IConnectionsItem[];
const ConnectionsPage = () => { const ConnectionsPage = () => {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const { clashInfo } = useClashInfo();
const [filterText, setFilterText] = useState(""); const [filterText, setFilterText] = useState("");
const [curOrderOpt, setOrderOpt] = useState("Default"); const [curOrderOpt, setOrderOpt] = useState("Default");
@ -52,16 +54,15 @@ const ConnectionsPage = () => {
}, [connData, filterText, curOrderOpt]); }, [connData, filterText, curOrderOpt]);
useEffect(() => { useEffect(() => {
let ws: WebSocket | null = null; if (!clashInfo) return;
getInformation().then((result) => { const { server = "", secret = "" } = clashInfo;
const { server = "", secret = "" } = result; const ws = new WebSocket(`ws://${server}/connections?token=${secret}`);
ws = new WebSocket(`ws://${server}/connections?token=${secret}`);
ws.addEventListener("message", (event) => { ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as IConnections; const data = JSON.parse(event.data) as IConnections;
// 与前一次connections的展示顺序尽量保持一致 // 尽量与前一次connections的展示顺序保持一致
setConnData((old) => { setConnData((old) => {
const oldConn = old.connections; const oldConn = old.connections;
const maxLen = data.connections.length; const maxLen = data.connections.length;
@ -93,10 +94,9 @@ const ConnectionsPage = () => {
return { ...data, connections }; return { ...data, connections };
}); });
}); });
});
return () => ws?.close(); return () => ws?.close();
}, []); }, [clashInfo]);
const onCloseAll = useLockFn(closeAllConnections); const onCloseAll = useLockFn(closeAllConnections);
@ -140,6 +140,7 @@ const ConnectionsPage = () => {
height: "36px", height: "36px",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
userSelect: "text",
}} }}
> >
{!isTableLayout && ( {!isTableLayout && (
@ -176,7 +177,7 @@ const ConnectionsPage = () => {
/> />
</Box> </Box>
<Box height="calc(100% - 50px)"> <Box height="calc(100% - 50px)" sx={{ userSelect: "text" }}>
{filterConn.length === 0 ? ( {filterConn.length === 0 ? (
<BaseEmpty text="No Connections" /> <BaseEmpty text="No Connections" />
) : isTableLayout ? ( ) : isTableLayout ? (

View File

@ -43,6 +43,7 @@ export async function getVersion() {
const instance = await getAxios(); const instance = await getAxios();
return instance.get("/version") as Promise<{ return instance.get("/version") as Promise<{
premium: boolean; premium: boolean;
meta?: boolean;
version: string; version: string;
}>; }>;
} }

View File

@ -5,11 +5,6 @@ export const atomThemeMode = atom<"light" | "dark">({
default: "light", default: "light",
}); });
export const atomClashPort = atom<number>({
key: "atomClashPort",
default: 0,
});
export const atomLogData = atom<ILogItem[]>({ export const atomLogData = atom<ILogItem[]>({
key: "atomLogData", key: "atomLogData",
default: [], default: [],

View File

@ -94,8 +94,8 @@ interface IConnections {
type IProfileType = "local" | "remote" | "merge" | "script"; type IProfileType = "local" | "remote" | "merge" | "script";
interface IClashInfo { interface IClashInfo {
status: string; // status: string;
port?: string; // clash mixed port port?: number; // clash mixed port
server?: string; // external-controller server?: string; // external-controller
secret?: string; secret?: string;
} }