From 9e9c4ad5873bf354c5a80cb38d4bc573216ce287 Mon Sep 17 00:00:00 2001 From: GyDi Date: Mon, 10 Jul 2023 23:44:09 +0800 Subject: [PATCH] fix: optimize traffic graph high CPU usage when hidden --- src/components/layout/layout-traffic.tsx | 29 +++++------------------- src/hooks/use-visibility.ts | 20 ++++++++++++++++ 2 files changed, 26 insertions(+), 23 deletions(-) create mode 100644 src/hooks/use-visibility.ts diff --git a/src/components/layout/layout-traffic.tsx b/src/components/layout/layout-traffic.tsx index f97c6cf..4095c05 100644 --- a/src/components/layout/layout-traffic.tsx +++ b/src/components/layout/layout-traffic.tsx @@ -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 && (
diff --git a/src/hooks/use-visibility.ts b/src/hooks/use-visibility.ts new file mode 100644 index 0000000..bf8aa9a --- /dev/null +++ b/src/hooks/use-visibility.ts @@ -0,0 +1,20 @@ +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; +};