Skip to content
Snippets Groups Projects
Unverified Commit 9e9c4ad5 authored by GyDi's avatar GyDi
Browse files

fix: optimize traffic graph high CPU usage when hidden

parent ce231431
No related branches found
No related tags found
No related merge requests found
......@@ -5,6 +5,7 @@ import { useClashInfo } from "@/hooks/use-clash";
import { useVerge } from "@/hooks/use-verge";
import { TrafficGraph, type TrafficRef } from "./traffic-graph";
import { useLogSetup } from "./use-log-setup";
import { useVisibility } from "@/hooks/use-visibility";
import { useWebsocket } from "@/hooks/use-websocket";
import parseTraffic from "@/utils/parse-traffic";
......@@ -28,8 +29,10 @@ const LayoutTraffic = () => {
setTraffic(data);
});
const pageVisible = useVisibility();
useEffect(() => {
if (!clashInfo) return;
if (!clashInfo || !pageVisible) return;
const { server = "", secret = "" } = clashInfo;
connect(`ws://${server}/traffic?token=${encodeURIComponent(secret)}`);
......@@ -37,27 +40,7 @@ const LayoutTraffic = () => {
return () => {
disconnect();
};
}, [clashInfo]);
useEffect(() => {
// 页面隐藏时去掉请求
const handleVisibleChange = () => {
if (!clashInfo) return;
if (document.visibilityState === "visible") {
// reconnect websocket
const { server = "", secret = "" } = clashInfo;
connect(`ws://${server}/traffic?token=${encodeURIComponent(secret)}`);
} else {
disconnect();
}
};
document.addEventListener("visibilitychange", handleVisibleChange);
return () => {
document.removeEventListener("visibilitychange", handleVisibleChange);
};
}, []);
}, [clashInfo, pageVisible]);
const [up, upUnit] = parseTraffic(traffic.up);
const [down, downUnit] = parseTraffic(traffic.down);
......@@ -82,7 +65,7 @@ const LayoutTraffic = () => {
position="relative"
onClick={trafficRef.current?.toggleStyle}
>
{trafficGraph && (
{trafficGraph && pageVisible && (
<div style={{ width: "100%", height: 60, marginBottom: 6 }}>
<TrafficGraph ref={trafficRef} />
</div>
......
import { useEffect, useState } from "react";
export const useVisibility = () => {
const [visible, setVisible] = useState(true);
useEffect(() => {
const handleVisibilityChange = () => {
setVisible(document.visibilityState === "visible");
};
handleVisibilityChange();
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, []);
return visible;
};
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment