feat: add new file

This commit is contained in:
Daniel
2026-03-01 19:23:48 +08:00
parent d705fd6c83
commit c07fc681dd
24 changed files with 2711 additions and 166 deletions

30
src/api/websocket.ts Normal file
View File

@@ -0,0 +1,30 @@
type Handler = (data: unknown) => void
let ws: WebSocket | null = null
let handler: Handler | null = null
function getUrl(): string {
return `${window.location.origin.replace(/^http/, 'ws')}/ws`
}
export function connectSituationWebSocket(onData: Handler): () => void {
handler = onData
if (ws?.readyState === WebSocket.OPEN) return () => {}
ws = new WebSocket(getUrl())
ws.onmessage = (e) => {
try {
const msg = JSON.parse(e.data)
if (msg.type === 'situation' && msg.data) handler?.(msg.data)
} catch (_) {}
}
ws.onclose = () => {
ws = null
setTimeout(() => handler && connectSituationWebSocket(handler), 3000)
}
return () => {
handler = null
ws?.close()
ws = null
}
}