-
-
Notifications
You must be signed in to change notification settings - Fork 628
Expand file tree
/
Copy pathuseCollaboration.ts
More file actions
415 lines (382 loc) · 14.5 KB
/
Copy pathuseCollaboration.ts
File metadata and controls
415 lines (382 loc) · 14.5 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import {
applyProjectToStore,
clearHistory,
serializeProject,
useAppStore,
type CollaborationMode,
type CollaborationParticipant,
type CollaborationPresence,
type GeoLibreProject,
} from "@geolibre/core";
import { useCallback, useEffect, useMemo, useRef } from "react";
import type { RefObject } from "react";
import type { MapController } from "@geolibre/map";
import type { Map as MapLibreMap } from "maplibre-gl";
import i18n from "../i18n";
import { buildProjectEgressSnapshot } from "../lib/build-project-snapshot";
import { projectChanged } from "../lib/project-broadcast-changed";
import {
CollabConnection,
createSession,
resolveCollabBaseUrl,
sessionWsUrl,
} from "../lib/collab-client";
import type { CommentMutationAction, ServerMessage } from "../lib/collab-protocol";
const SNAPSHOT_DEBOUNCE_MS = 250;
const CURSOR_THROTTLE_MS = 40;
export interface CollaborationApi {
enabled: boolean;
canEdit: () => boolean;
start: (displayName: string, color: string, mode: CollaborationMode) => Promise<string>;
join: (sessionId: string, displayName: string, color: string) => Promise<void>;
leave: () => void;
setMode: (mode: CollaborationMode) => void;
setParticipantMode: (clientId: string, canEdit: boolean) => void;
setFollowHost: (enabled: boolean) => void;
sendChat: (text: string, coordinate?: { lng: number; lat: number } | null) => boolean;
sendCommentMutation: (action: CommentMutationAction) => boolean;
}
export function useCollaboration(
mapControllerRef: RefObject<MapController | null>,
): CollaborationApi {
const baseUrl = useMemo(() => resolveCollabBaseUrl(), []);
const enabled = baseUrl !== null;
const connRef = useRef<CollabConnection | null>(null);
const teardownRef = useRef<(() => void) | null>(null);
const lastContentRef = useRef<string | null>(null);
const revRef = useRef(0);
const selfIdRef = useRef<string | null>(null);
const syncPausedRef = useRef(false);
const restoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pendingConnectRef = useRef<{
resolve: () => void;
reject: (error: Error) => void;
} | null>(null);
useEffect(
() => () => {
disconnect();
useAppStore.getState().resetCollaboration();
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
const canEdit = (): boolean => {
const c = useAppStore.getState().collaboration;
if (!c.isActive) return false;
if (c.role === "host") return true;
const self = c.participants.find((p) => p.clientId === c.clientId);
return self?.editOverride ?? c.mode === "co-edit";
};
const sendSnapshot = (): void => {
if (!canEdit() || syncPausedRef.current) return;
const project = buildProjectEgressSnapshot(mapControllerRef);
const content = serializeProject(project);
if (content === lastContentRef.current) return;
lastContentRef.current = content;
revRef.current += 1;
connRef.current?.send({ type: "snapshot", project, rev: revRef.current });
};
const scheduleRestore = (): void => {
if (restoreTimerRef.current) clearTimeout(restoreTimerRef.current);
restoreTimerRef.current = setTimeout(() => {
restoreTimerRef.current = null;
useAppStore.setState((s) => ({ projectGeneration: s.projectGeneration + 1 }));
}, 200);
};
const applyRemoteSnapshot = (project: GeoLibreProject, initial: boolean): void => {
const localView = mapControllerRef.current?.readView() ?? useAppStore.getState().mapView;
const merged: GeoLibreProject = { ...project, mapView: localView };
if (initial) {
useAppStore
.getState()
.loadProject(merged, null, { rememberRecent: false, presenting: false });
} else {
const applied = applyProjectToStore(merged);
useAppStore.setState({ ...applied });
clearHistory();
scheduleRestore();
}
lastContentRef.current = serializeProject(buildProjectEgressSnapshot(mapControllerRef));
};
const handleMessage = (message: ServerMessage): void => {
const store = useAppStore.getState();
switch (message.type) {
case "welcome": {
selfIdRef.current = message.clientId;
store.setCollaboration({
isActive: true,
connecting: false,
clientId: message.clientId,
role: message.role,
mode: message.mode,
participants: message.participants,
chat: message.chat ?? [],
error: null,
});
for (const [clientId, entry] of Object.entries(message.presence)) {
if (clientId === message.clientId) continue;
const participant = message.participants.find((p) => p.clientId === clientId);
store.updateCollaborationPresence(clientId, {
displayName: participant?.displayName ?? i18n.t("collaborate.guest"),
color: participant?.color ?? "#888888",
cursor: entry.cursor,
view: entry.view,
});
}
if (message.snapshot) applyRemoteSnapshot(message.snapshot, true);
const pending = pendingConnectRef.current;
pendingConnectRef.current = null;
pending?.resolve();
break;
}
case "snapshot":
// origin is the server-assigned clientId of the sender; skip our own echo.
if (message.origin !== selfIdRef.current) {
applyRemoteSnapshot(message.project, false);
}
break;
case "presence": {
if (message.clientId === selfIdRef.current) break;
const collab = useAppStore.getState().collaboration;
const participant = collab.participants.find((p) => p.clientId === message.clientId);
const presence: CollaborationPresence = {
displayName: participant?.displayName ?? i18n.t("collaborate.guest"),
color: participant?.color ?? "#888888",
cursor: message.cursor,
view: message.view,
};
store.updateCollaborationPresence(message.clientId, presence);
if (collab.followHost && participant?.role === "host" && message.view) {
mapControllerRef.current?.applyView(message.view);
}
break;
}
case "participants": {
store.setCollaboration({ participants: message.participants });
const present = new Set(message.participants.map((p) => p.clientId));
const presence = useAppStore.getState().collaboration.presence;
for (const id of Object.keys(presence)) {
if (!present.has(id)) store.updateCollaborationPresence(id, null);
}
break;
}
case "mode":
store.setCollaboration({ mode: message.mode });
break;
case "chat":
// The relay echoes our own messages back with the server-assigned id.
// Always add via the echo so the server id is used — addCollaborationChat
// deduplicates by id so subsequent echoes are harmless.
store.addCollaborationChat(message.message);
break;
case "comment-mutation": {
// The relay excludes the sender (broadcast(msg, ws)), so we never receive
// our own mutations back over WebSocket. Apply everything we receive.
const action = message.action;
if (action.type === "add") {
store.addComment(action.comment);
} else if (action.type === "reply") {
store.replyToComment(action.commentId, action.reply);
} else if (action.type === "toggle-resolve") {
store.toggleResolveComment(action.commentId, action.resolved);
} else if (action.type === "delete") {
store.deleteComment(action.commentId);
}
break;
}
case "error":
store.setCollaboration({ error: message.message });
if (message.code === "too-large") syncPausedRef.current = true;
break;
}
};
// Called from onOpen — the socket is open and we are ready to join.
const attach = (displayName: string, color: string, hostToken: string | undefined): void => {
const conn = connRef.current;
if (!conn) return;
let debounce: ReturnType<typeof setTimeout> | null = null;
const scheduleSnapshot = () => {
if (debounce) clearTimeout(debounce);
debounce = setTimeout(() => {
debounce = null;
sendSnapshot();
}, SNAPSHOT_DEBOUNCE_MS);
};
const unsubscribe = useAppStore.subscribe((state, prev) => {
if (projectChanged(state, prev)) scheduleSnapshot();
});
const map = mapControllerRef.current?.getMap() ?? null;
const detachMap = map ? bindPresence(map, conn) : () => {};
conn.send({
type: "join",
clientId: selfIdRef.current ?? crypto.randomUUID(),
displayName,
color,
hostToken,
});
teardownRef.current = () => {
if (debounce) clearTimeout(debounce);
unsubscribe();
detachMap();
};
};
const bindPresence = (map: MapLibreMap, conn: CollabConnection): (() => void) => {
let lastCursor = 0;
const onMouseMove = (e: { lngLat: { lng: number; lat: number } }) => {
const now = Date.now();
if (now - lastCursor < CURSOR_THROTTLE_MS) return;
lastCursor = now;
conn.send({ type: "presence", cursor: { lng: e.lngLat.lng, lat: e.lngLat.lat } });
};
const onMouseOut = () => conn.send({ type: "presence", cursor: null });
const onMoveEnd = (event?: { flightCameraToken?: number }) => {
if (event?.flightCameraToken !== undefined) return;
conn.send({ type: "presence", view: mapControllerRef.current?.readView() ?? null });
};
map.on("mousemove", onMouseMove);
map.on("mouseout", onMouseOut);
map.on("moveend", onMoveEnd);
onMoveEnd();
return () => {
map.off("mousemove", onMouseMove);
map.off("mouseout", onMouseOut);
map.off("moveend", onMoveEnd);
};
};
const connect = (
sessionId: string,
displayName: string,
color: string,
hostToken: string | undefined,
): Promise<void> => {
disconnect();
syncPausedRef.current = false;
selfIdRef.current = crypto.randomUUID();
lastContentRef.current = null;
revRef.current = 0;
const normalizedCode = sessionId.trim().toUpperCase();
const selfParticipant: CollaborationParticipant = {
clientId: selfIdRef.current,
displayName,
color,
role: hostToken ? "host" : "guest",
editOverride: null,
};
useAppStore.getState().setCollaboration({
connecting: true,
isActive: false,
sessionId: normalizedCode,
selfName: displayName,
selfColor: color,
role: hostToken ? "host" : "guest",
mode: "co-edit",
clientId: selfIdRef.current,
participants: [selfParticipant],
error: null,
});
return new Promise<void>((resolve, reject) => {
pendingConnectRef.current = { resolve, reject };
const conn = new CollabConnection(sessionWsUrl(baseUrl!, normalizedCode), {
onOpen: () => {
if (connRef.current !== conn) return;
attach(displayName, color, hostToken);
},
onMessage: (msg) => {
if (connRef.current !== conn) return;
handleMessage(msg);
},
onClose: (reconnecting) => {
if (connRef.current && connRef.current !== conn) return;
teardownRef.current?.();
teardownRef.current = null;
if (reconnecting && pendingConnectRef.current) {
const p = pendingConnectRef.current;
pendingConnectRef.current = null;
conn.close();
useAppStore
.getState()
.setCollaboration({ connecting: false, error: "Could not connect to the session." });
p.reject(new Error("Could not connect to the session."));
}
},
});
connRef.current = conn;
conn.connect();
});
};
const disconnect = (): void => {
teardownRef.current?.();
teardownRef.current = null;
if (pendingConnectRef.current) {
const p = pendingConnectRef.current;
pendingConnectRef.current = null;
p.reject(new Error(i18n.t("comments.sessionDisconnected")));
}
connRef.current?.close();
connRef.current = null;
selfIdRef.current = null;
if (restoreTimerRef.current) {
clearTimeout(restoreTimerRef.current);
restoreTimerRef.current = null;
}
};
const start = useCallback(
async (displayName: string, color: string, mode: CollaborationMode) => {
const session = await createSession(mode, baseUrl);
await connect(session.sessionId, displayName, color, session.hostToken);
return session.sessionId;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[baseUrl],
);
const join = useCallback(
async (sessionId: string, displayName: string, color: string) => {
await connect(sessionId.trim().toUpperCase(), displayName, color, undefined);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[baseUrl],
);
const leave = useCallback(() => {
disconnect();
useAppStore.getState().resetCollaboration();
}, []);
const setMode = useCallback((mode: CollaborationMode) => {
connRef.current?.send({ type: "set-mode", mode });
}, []);
const setParticipantMode = useCallback((clientId: string, canEditFlag: boolean) => {
connRef.current?.send({ type: "set-participant-mode", clientId, canEdit: canEditFlag });
}, []);
const sendChat = useCallback((text: string, coordinate?: { lng: number; lat: number } | null) => {
const trimmed = text.trim();
if (!trimmed) return false;
// Send to the relay only. The relay broadcasts back to everyone including
// the sender with a server-assigned id; handleMessage("chat") adds it to
// the store then. This means the server's ordering is always the truth and
// the sender's message appears only once (via the echo, not optimistically).
return connRef.current?.send({ type: "chat", text: trimmed, coordinate }) ?? false;
}, []);
const sendCommentMutation = useCallback((action: CommentMutationAction) => {
return connRef.current?.send({ type: "comment-mutation", action }) ?? false;
}, []);
const setFollowHost = useCallback((enabled: boolean) => {
const store = useAppStore.getState();
store.setCollaboration({ followHost: enabled });
if (!enabled) return;
const host = store.collaboration.participants.find((p) => p.role === "host");
const view = host ? store.collaboration.presence[host.clientId]?.view : null;
if (view) mapControllerRef.current?.applyView(view);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
enabled,
canEdit,
start,
join,
leave,
setMode,
setParticipantMode,
setFollowHost,
sendChat,
sendCommentMutation,
};
}