-
-
Notifications
You must be signed in to change notification settings - Fork 404
Expand file tree
/
Copy pathuse-socket-events.ts
More file actions
245 lines (208 loc) · 6.91 KB
/
use-socket-events.ts
File metadata and controls
245 lines (208 loc) · 6.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { Dispatch, SetStateAction, useCallback, useEffect, useRef, useState } from 'react';
import { usePage } from '@inertiajs/react';
import { PaginatedData, SharedData } from '@/types';
export type SocketEventData = {
project_id: number;
type: string;
data: Record<string, unknown>;
};
export const SOCKET_EVENT = 'vito:socket-event' as const;
declare global {
interface WindowEventMap {
[SOCKET_EVENT]: CustomEvent<SocketEventData>;
}
}
type WebSocketMessage =
| { type: 'connected'; project_id: number }
| { type: 'subscribed'; project_id: number }
| { type: 'event'; data: SocketEventData }
| { type: 'error'; message: string };
const RECONNECT_BASE_DELAY = 1000;
const RECONNECT_MAX_DELAY = 30000;
async function requestEventsToken(csrfToken: string): Promise<{ token: string; url: string } | null> {
try {
const response = await fetch(route('events.token'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken,
},
});
if (!response.ok) return null;
return await response.json();
} catch {
return null;
}
}
export function useSocketEvents(): void {
const { auth, csrf_token } = usePage<SharedData>().props;
const authRef = useRef(auth);
const csrfRef = useRef(csrf_token);
authRef.current = auth;
csrfRef.current = csrf_token;
const wsRef = useRef<WebSocket | null>(null);
const reconnectAttemptRef = useRef(0);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const currentProjectIdRef = useRef<number | null>(null);
const cleanup = useCallback(() => {
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current);
reconnectTimerRef.current = null;
}
if (wsRef.current) {
wsRef.current.onclose = null;
wsRef.current.onerror = null;
wsRef.current.onmessage = null;
wsRef.current.close();
wsRef.current = null;
}
}, []);
const scheduleReconnect = useCallback((connectFn: () => void) => {
const delay = Math.min(RECONNECT_BASE_DELAY * Math.pow(2, reconnectAttemptRef.current), RECONNECT_MAX_DELAY);
reconnectAttemptRef.current++;
reconnectTimerRef.current = setTimeout(connectFn, delay);
}, []);
const connect = useCallback(async () => {
if (!authRef.current || !csrfRef.current) {
return;
}
cleanup();
const tokenData = await requestEventsToken(csrfRef.current);
if (!tokenData) {
scheduleReconnect(() => connect());
return;
}
const ws = new WebSocket(`${tokenData.url}?token=${tokenData.token}`);
wsRef.current = ws;
ws.onmessage = (event) => {
try {
const msg: WebSocketMessage = JSON.parse(event.data);
switch (msg.type) {
case 'connected':
reconnectAttemptRef.current = 0;
currentProjectIdRef.current = msg.project_id;
break;
case 'subscribed':
currentProjectIdRef.current = msg.project_id;
break;
case 'event':
window.dispatchEvent(new CustomEvent(SOCKET_EVENT, { detail: msg.data }));
break;
case 'error':
console.warn('[WS Events]', msg.message);
break;
}
} catch {
// ignore non-JSON messages
}
};
ws.onclose = () => {
wsRef.current = null;
scheduleReconnect(() => connect());
};
ws.onerror = () => {
// onclose will fire after onerror, reconnection handled there
};
}, [cleanup, scheduleReconnect]);
// Switch project subscription when the current project changes
const projectId = auth?.currentProject?.id;
useEffect(() => {
if (wsRef.current?.readyState === WebSocket.OPEN && projectId && projectId !== currentProjectIdRef.current) {
wsRef.current.send(JSON.stringify({ type: 'subscribe', project_id: projectId }));
}
}, [projectId]);
// Connect on mount, cleanup on unmount
useEffect(() => {
connect();
return cleanup;
}, [connect, cleanup]);
}
/**
* Listen for socket events on a page. The callback receives the event data
* and can decide whether to handle it or ignore it.
*/
export function useSocketListener(callback: (data: SocketEventData) => void): void {
const callbackRef = useRef(callback);
callbackRef.current = callback;
useEffect(() => {
const handler = (e: CustomEvent<SocketEventData>) => {
callbackRef.current(e.detail);
};
window.addEventListener(SOCKET_EVENT, handler);
return () => window.removeEventListener(SOCKET_EVENT, handler);
}, []);
}
/**
* Keeps a single resource in sync with socket events.
*
* Returns the live resource (initially from Inertia props, updated via socket).
* Pass `null` to skip listening (safe to call unconditionally).
*/
export function useRealtimeRecord<T extends { id: number }>(initial: T | null | undefined, eventPrefix: string): T | null {
const [record, setRecord] = useState<T | null>(initial ?? null);
useEffect(() => {
setRecord(initial ?? null);
}, [initial]);
useSocketListener(
useCallback(
(event) => {
if (!initial) return;
if (event.type === `${eventPrefix}.updated` && event.data && 'id' in event.data && event.data.id === initial.id) {
setRecord(event.data as unknown as T);
}
},
[eventPrefix, initial?.id],
),
);
return record;
}
/**
* Manages paginated Inertia data with realtime socket updates.
*
* Listens for socket events matching `{eventPrefix}.updated` (replace row),
* and `{eventPrefix}.deleted` (remove row) automatically.
*
* Returns the live data and setter for custom handling.
*/
export function useRealtime<T extends { id: number }>(
initialData: PaginatedData<T>,
eventPrefix: string,
): [PaginatedData<T>, Dispatch<SetStateAction<PaginatedData<T>>>] {
const [data, setData] = useState<PaginatedData<T>>(initialData);
useEffect(() => {
setData(initialData);
}, [initialData]);
useSocketListener(
useCallback(
(event) => {
const { type, data: eventData } = event;
if (!type?.startsWith(`${eventPrefix}.`) || !eventData || typeof eventData !== 'object' || !('id' in eventData)) {
return;
}
const action = type.slice(eventPrefix.length + 1);
switch (action) {
case 'created':
setData((prev) => ({
...prev,
data: [eventData as unknown as T, ...prev.data],
}));
break;
case 'updated':
setData((prev) => ({
...prev,
data: prev.data.map((item) => (item.id === (eventData as unknown as T).id ? (eventData as unknown as T) : item)),
}));
break;
case 'deleted':
setData((prev) => ({
...prev,
data: prev.data.filter((item) => item.id !== eventData.id),
}));
break;
}
},
[eventPrefix],
),
);
return [data, setData];
}