From 6f5acee1c340299221ee92b391eff0fa44bdcc37 Mon Sep 17 00:00:00 2001 From: GyDi Date: Sat, 5 Aug 2023 17:21:15 +0800 Subject: [PATCH] fix: websocket disconnect when window focus --- src/hooks/use-visibility.ts | 7 +++++++ src/hooks/use-websocket.ts | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/hooks/use-visibility.ts b/src/hooks/use-visibility.ts index bf8aa9a..31d6d3d 100644 --- a/src/hooks/use-visibility.ts +++ b/src/hooks/use-visibility.ts @@ -8,10 +8,17 @@ export const useVisibility = () => { setVisible(document.visibilityState === "visible"); }; + const handleFocus = () => setVisible(true); + const handleClick = () => setVisible(true); + handleVisibilityChange(); + document.addEventListener("focus", handleFocus); + document.addEventListener("pointerdown", handleClick); document.addEventListener("visibilitychange", handleVisibilityChange); return () => { + document.removeEventListener("focus", handleFocus); + document.removeEventListener("pointerdown", handleClick); document.removeEventListener("visibilitychange", handleVisibilityChange); }; }, []); diff --git a/src/hooks/use-websocket.ts b/src/hooks/use-websocket.ts index 1c92e7b..f6b5f3d 100644 --- a/src/hooks/use-websocket.ts +++ b/src/hooks/use-websocket.ts @@ -2,12 +2,12 @@ import { useRef } from "react"; export type WsMsgFn = (event: MessageEvent) => void; -interface Options { +export interface WsOptions { errorCount?: number; // default is 5 retryInterval?: number; // default is 2500 } -export const useWebsocket = (onMessage: WsMsgFn, options?: Options) => { +export const useWebsocket = (onMessage: WsMsgFn, options?: WsOptions) => { const wsRef = useRef(null); const timerRef = useRef(null);