From c950e4a3f8fc45a73c70079813658302ee364aee Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Sat, 27 Apr 2024 20:20:31 +0800 Subject: [PATCH] refactor: add server page reconnect --- src/client/api/socketio.ts | 2 +- src/client/components/server/useServerMap.ts | 13 +++++++++++- src/client/hooks/useVisibilityChange.ts | 22 ++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 src/client/hooks/useVisibilityChange.ts diff --git a/src/client/api/socketio.ts b/src/client/api/socketio.ts index e89391b..80b1ebe 100644 --- a/src/client/api/socketio.ts +++ b/src/client/api/socketio.ts @@ -86,7 +86,7 @@ export function useSocket() { } ); - return { emit, subscribe }; + return { socket, emit, subscribe }; } export function useSocketSubscribe( diff --git a/src/client/components/server/useServerMap.ts b/src/client/components/server/useServerMap.ts index 863345a..9442a2b 100644 --- a/src/client/components/server/useServerMap.ts +++ b/src/client/components/server/useServerMap.ts @@ -1,11 +1,22 @@ -import { useSocketSubscribe } from '@/api/socketio'; +import { useSocket, useSocketSubscribe } from '@/api/socketio'; import { ServerStatusInfo } from '../../../types'; +import { useVisibilityChange } from '@/hooks/useVisibilityChange'; export function useServerMap(): Record { + const { socket } = useSocket(); const serverMap = useSocketSubscribe>( 'onServerStatusUpdate', {} ); + /** + * Auto reconnect when reconnect + */ + useVisibilityChange((visibility) => { + if (visibility && socket?.disconnected === true) { + socket.connect(); + } + }); + return serverMap; } diff --git a/src/client/hooks/useVisibilityChange.ts b/src/client/hooks/useVisibilityChange.ts new file mode 100644 index 0000000..afd4847 --- /dev/null +++ b/src/client/hooks/useVisibilityChange.ts @@ -0,0 +1,22 @@ +import { useEffect } from 'react'; +import { useEvent } from './useEvent'; + +export function useVisibilityChange(callback: (visibility: boolean) => void) { + const fn = useEvent(callback); + + useEffect(() => { + const handleVisibilityChange = () => { + if (document.visibilityState === 'visible') { + fn(true); + } else { + fn(false); + } + }; + + document.addEventListener('visibilitychange', handleVisibilityChange); + + return () => { + document.removeEventListener('visibilitychange', handleVisibilityChange); + }; + }, []); +}