From 721d0afc73e3fa812d45b0af10b27006b3e87e57 Mon Sep 17 00:00:00 2001 From: Xevion Date: Thu, 2 Jan 2025 15:40:58 -0600 Subject: [PATCH] Add reconnection option, prevent autoplay, remove state on disconnect, mobile height adjustment --- frontend/src/components/Demo.tsx | 1 + frontend/src/components/useSocket.ts | 30 +++++++++++++++++++++++++--- frontend/src/pages/index.astro | 8 +++++--- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/frontend/src/components/Demo.tsx b/frontend/src/components/Demo.tsx index edd9cf6..d5e3394 100644 --- a/frontend/src/components/Demo.tsx +++ b/frontend/src/components/Demo.tsx @@ -26,6 +26,7 @@ const Demo = ({ class: className }: DemoProps) => { useEffect(() => { audioRef.current = new Audio("/notify.wav"); audioRef.current.volume = 1; + audioRef.current.autoplay = false; return () => { audioRef.current!.remove(); }; diff --git a/frontend/src/components/useSocket.ts b/frontend/src/components/useSocket.ts index 6f3abcb..4efd27a 100644 --- a/frontend/src/components/useSocket.ts +++ b/frontend/src/components/useSocket.ts @@ -1,6 +1,6 @@ import { withBackend } from "@/util"; import { useEffect, useRef, useState } from "react"; -import useWebSocket from "react-use-websocket"; +import useWebSocket, { ReadyState } from "react-use-websocket"; export interface Download { token: number; @@ -27,14 +27,22 @@ export interface UseSocketProps { notify?: (token: number) => void; } -export type Status = "connected" | "disconnected" | "connecting"; +export type Status = + | "connecting" + | "open" + | "closing" + | "closed" + | "uninstantiated"; function useSocket({ notify }: UseSocketProps): UseSocketResult { const { sendMessage, lastMessage, readyState } = useWebSocket( withBackend( window.location.protocol === "https:" ? "wss://" : "ws://", "/ws" - ) + ), + { + shouldReconnect: () => true, + } ); const [id, setId] = useState(null); @@ -44,6 +52,22 @@ function useSocket({ notify }: UseSocketProps): UseSocketResult { executables: Executable[]; } | null>(null); + const connectionStatus: Status = { + [ReadyState.CONNECTING]: "connecting", + [ReadyState.OPEN]: "open", + [ReadyState.CLOSING]: "closing", + [ReadyState.CLOSED]: "closed", + [ReadyState.UNINSTANTIATED]: "uninstantiated", + }[readyState] as Status; + + useEffect(() => { + if (readyState === WebSocket.CLOSED || readyState === WebSocket.CLOSING) { + setId(null); + setDownloads(null); + setExecutables(null); + } + }, [readyState]); + useEffect(() => { { if (lastMessage == null) return; diff --git a/frontend/src/pages/index.astro b/frontend/src/pages/index.astro index 1a663bb..46adf00 100644 --- a/frontend/src/pages/index.astro +++ b/frontend/src/pages/index.astro @@ -4,15 +4,17 @@ import Demo from "@/components/Demo"; --- -
+
-
+