feat: add use clash hook

This commit is contained in:
GyDi
2022-11-23 17:44:40 +08:00
parent 2709d1ff6e
commit 5e626e2cc5
12 changed files with 196 additions and 191 deletions

View File

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

View File

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

View File

@@ -1,48 +1,36 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useEffect } from "react";
import { useRecoilValue, useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event";
import { getInformation } from "@/services/api";
import { getClashLogs } from "@/services/cmds";
import { useClashInfo } from "@/hooks/use-clash";
import { atomEnableLog, atomLogData } from "@/services/states";
const MAX_LOG_NUM = 1000;
// setup the log websocket
export default function useLogSetup() {
const [refresh, setRefresh] = useState({});
export const useLogSetup = () => {
const { clashInfo } = useClashInfo();
const enableLog = useRecoilValue(atomEnableLog);
const setLogData = useSetRecoilState(atomLogData);
useEffect(() => {
if (!enableLog) return;
if (!enableLog || !clashInfo) return;
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 time = dayjs().format("MM-DD HH:mm:ss");
setLogData((l) => {
if (l.length >= MAX_LOG_NUM) l.shift();
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", () =>
setRefresh({})
);
return () => {
ws.then((ws) => ws?.close());
unlisten.then((fn) => fn());
};
}, [refresh, enableLog]);
}
return () => ws?.close();
}, [clashInfo, enableLog]);
};