Open History to see the last commit
1import { useCallback, useEffect, useRef, useState } from 'react'
2import { newWebSocketRpcSession } from 'capnweb'
3import type { RpcStub } from 'capnweb'
4import type { ChatApi } from '../../chat-server/chat-api'
5import { ChatNotifier } from '@/lib/chat-notifier'
6
7export interface ConnectionState {
8 isConnected: boolean
9 isConnecting: boolean
10 connectionStatus: string
11 error: string | null
12}
13
14export function useChatConnection() {
15 const [state, setState] = useState<ConnectionState>({
16 isConnected: false,
17 isConnecting: false,
18 connectionStatus: 'Disconnected',
19 error: null,
20 })
21
22 const [api, setApi] = useState<RpcStub<ChatApi> | null>(null)
23 const [notifier, setNotifier] = useState<ChatNotifier | null>(null)
24 const apiRef = useRef<RpcStub<ChatApi> | null>(null)
25 const connectingRef = useRef(false)
26 const connectionIdRef = useRef(0)
27
28 const disconnect = useCallback(() => {
29 connectionIdRef.current += 1
30 connectingRef.current = false
31 if (apiRef.current) {
32 apiRef.current[Symbol.dispose]()
33 apiRef.current = null
34 }
35 setApi(null)
36 setNotifier(null)
37 setState({
38 isConnected: false,
39 isConnecting: false,
40 connectionStatus: 'Disconnected',
41 error: null,
42 })
43 }, [])
44
45 const connect = useCallback(() => {
46 if (connectingRef.current || apiRef.current) {
47 return
48 }
49
50 connectingRef.current = true
51 const connectionId = ++connectionIdRef.current
52 const sessionNotifier = new ChatNotifier()
53
54 setState((prev) => ({
55 ...prev,
56 isConnecting: true,
57 connectionStatus: 'Connecting...',
58 error: null,
59 }))
60
61 try {
62 const protocol =
63 typeof window !== 'undefined' && window.location.protocol === 'https:'
64 ? 'wss:'
65 : 'ws:'
66 const wsUrl =
67 typeof window !== 'undefined'
68 ? `${protocol}//${window.location.host}/api/websocket`
69 : 'ws://localhost:3000/api/websocket'
70
71 console.log('Connecting to chat:', wsUrl)
72
73 const stub = newWebSocketRpcSession<ChatApi>(wsUrl, sessionNotifier)
74 apiRef.current = stub
75
76 void (async () => {
77 try {
78 const chatState = await stub.getChatState()
79 if (connectionId !== connectionIdRef.current) {
80 stub[Symbol.dispose]()
81 return
82 }
83 if (!Array.isArray(chatState.onlineUsers)) {
84 throw new Error('Invalid chat state from server')
85 }
86
87 console.log('Chat RPC connection established')
88 setNotifier(sessionNotifier)
89 setApi(stub)
90 connectingRef.current = false
91 setState({
92 isConnected: true,
93 isConnecting: false,
94 connectionStatus: 'Connected',
95 error: null,
96 })
97 } catch (error) {
98 if (connectionId !== connectionIdRef.current) {
99 stub[Symbol.dispose]()
100 return
101 }
102 console.error('Chat connection failed:', error)
103 stub[Symbol.dispose]()
104 apiRef.current = null
105 setApi(null)
106 setNotifier(null)
107 connectingRef.current = false
108 setState({
109 isConnected: false,
110 isConnecting: false,
111 connectionStatus: 'Failed to connect',
112 error: error instanceof Error ? error.message : 'Unknown error',
113 })
114 }
115 })()
116 } catch (error) {
117 connectingRef.current = false
118 console.error('Failed to create chat session:', error)
119 setState({
120 isConnected: false,
121 isConnecting: false,
122 connectionStatus: 'Failed to connect',
123 error: error instanceof Error ? error.message : 'Unknown error',
124 })
125 }
126 }, [])
127
128 useEffect(() => {
129 return () => {
130 disconnect()
131 }
132 }, [disconnect])
133
134 return {
135 ...state,
136 api,
137 apiRef,
138 notifier,
139 connect,
140 disconnect,
141 }
142}