@alexsun-top/opencode-chat-room 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,443 @@
1
+ import { LS } from "./state.js";
2
+
3
+ export function initRooms(app) {
4
+ const $ = app.$;
5
+
6
+ app.showJoin = () => {
7
+ $("#chatView").hidden = true;
8
+ $("#joinView").hidden = false;
9
+ app.updateTitle();
10
+ void app.refreshRoomList();
11
+ $("#inRoomId").focus();
12
+ };
13
+ app.showChat = () => {
14
+ $("#joinView").hidden = true;
15
+ $("#chatView").hidden = false;
16
+ };
17
+ app.renderHead = () => {
18
+ $("#roomName").textContent = app.state.room.name;
19
+ $("#roomIdShort").textContent = app.state.room.id.slice(0, 8);
20
+ $("#btnCopyId").title = app.t("copyRoomIdTitle", { id: app.state.room.id });
21
+ $("#btnCopyId").setAttribute("aria-label", app.t("copyRoomId"));
22
+ app.setText($("#railIdentity"), "identityLabel", { name: app.state.myName });
23
+ app.updateTitle();
24
+ };
25
+
26
+ app.enterRoom = (room, name, intent = app.state.navigationGeneration) => {
27
+ app.ensureJoinedRoom(room, name);
28
+ if (intent === app.state.navigationGeneration) app.activateRoom(room.id);
29
+ else {
30
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
31
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
32
+ void app.refreshRoomList();
33
+ }
34
+ };
35
+
36
+ app.ensureJoinedRoom = (room, name) => {
37
+ const entry = app.state.rooms.get(room.id) || { unreadIds: new Map(), unreadOverflow: false, preview: "", previewAt: 0, position: 0, readTs: 0 };
38
+ entry.unreadIds ||= new Map();
39
+ entry.unreadOverflow ||= false;
40
+ entry.room = room;
41
+ entry.name = name;
42
+ entry.preview ||= room.messages.at(-1)?.text || "";
43
+ entry.previewAt ||= room.messages.at(-1)?.createdAt || 0;
44
+ app.state.rooms.set(room.id, entry);
45
+ app.state.roomNames.set(room.id, name);
46
+ app.state.joinedIds.add(room.id);
47
+ app.saveJoinedIds();
48
+ app.saveRoomNames();
49
+ app.startRoomWatcher();
50
+ };
51
+
52
+ app.activateRoom = (roomId) => {
53
+ app.state.navigationGeneration++;
54
+ const entry = app.state.rooms.get(roomId);
55
+ if (!entry) return;
56
+ if (app.state.room?.id === roomId) return;
57
+ if (app.state.room) {
58
+ app.saveDraft(app.state.room.id, $("#msgInput").value);
59
+ app.savePosition(app.state.room.id, $("#thread").scrollTop);
60
+ }
61
+ app.stopPolling();
62
+ app.state.room = entry.room;
63
+ app.state.myName = entry.name;
64
+ const hasSavedPosition = app.state.positions.has(roomId);
65
+ entry.position = app.state.positions.get(roomId) ?? entry.position;
66
+ app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
67
+ app.rendered = 0;
68
+ app.firstMessageId = null;
69
+ app.state.pendingAction = null;
70
+ LS.roomId = roomId;
71
+ LS.name = entry.name;
72
+ app.showChat();
73
+ app.renderHead();
74
+ $("#msgList").textContent = "";
75
+ app.renderMessages(false);
76
+ app.renderMembers();
77
+ $("#thread").scrollTop = hasSavedPosition ? entry.position : entry.position || $("#thread").scrollHeight;
78
+ $("#msgInput").disabled = false;
79
+ $("#msgInput").value = app.state.drafts.get(roomId) || "";
80
+ app.renderFailedMessages();
81
+ app.autoGrow($("#msgInput"));
82
+ app.updateDraftCount();
83
+ app.updateSendState();
84
+ app.hideSendError();
85
+ app.startPolling();
86
+ app.updateBadge();
87
+ app.updateJump();
88
+ app.markActiveRoomRead();
89
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
90
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
91
+ void app.refreshRoomList();
92
+ };
93
+
94
+ app.joinRoom = async (roomId, name) => {
95
+ if (app.state.rooms.has(roomId)) return app.activateRoom(roomId);
96
+ const intent = ++app.state.navigationGeneration;
97
+ app.state.pendingAction = null;
98
+ app.setJoinBusy(true);
99
+ app.hideJoinError();
100
+ try {
101
+ const room = await app.api(`/rooms/${encodeURIComponent(roomId)}/join`, {
102
+ method: "POST",
103
+ body: JSON.stringify({ sessionID: LS.sessionID, participantId: name, participantName: name }),
104
+ });
105
+ app.enterRoom(room, name, intent);
106
+ } catch (error) {
107
+ if (error.status === 401) {
108
+ app.state.pendingAction = { type: "join", roomId, name };
109
+ if (app.state.room) { app.openChatSettings(); app.showSendError("sendAuth"); }
110
+ else { app.openTokenBox(); app.showJoinError("authRetry"); }
111
+ } else app.showJoinError(error.network ? "networkRetry" : "joinFailed", { message: error.message });
112
+ } finally { app.setJoinBusy(false); }
113
+ };
114
+
115
+ app.createRoom = async (pending) => {
116
+ const fromChat = pending?.fromChat ?? Boolean(app.state.room);
117
+ const name = pending?.name || (fromChat ? app.state.myName : $("#inName").value.trim()) || app.t("guest");
118
+ const roomName = pending?.roomName || $(fromChat ? "#inRoomNameChat" : "#inRoomName").value.trim();
119
+ if (!roomName) return fromChat ? app.showSendError("roomNameRequired") : app.showJoinError("roomNameRequired");
120
+ const intent = ++app.state.navigationGeneration;
121
+ app.setJoinBusy(true);
122
+ app.hideJoinError();
123
+ app.state.pendingAction = null;
124
+ if (fromChat) $("#btnCreateChatRoom").disabled = true;
125
+ try {
126
+ const room = await app.api("/rooms", {
127
+ method: "POST",
128
+ body: JSON.stringify({ name: roomName, ownerId: name, sessionID: LS.sessionID }),
129
+ });
130
+ if (fromChat) {
131
+ $("#inRoomNameChat").value = "";
132
+ $("#railRoomForm").hidden = true;
133
+ }
134
+ app.enterRoom(room, name, intent);
135
+ } catch (error) {
136
+ if (error.status === 401) {
137
+ app.state.pendingAction = { type: "create", name, roomName, fromChat };
138
+ if (fromChat) { app.openChatSettings(); app.showSendError("sendAuth"); }
139
+ else { app.openTokenBox(); app.showJoinError("authRetry"); }
140
+ } else if (fromChat) app.showSendError("sendFailed", { message: error.message });
141
+ else app.showJoinError("createFailed", { message: error.message });
142
+ } finally {
143
+ app.setJoinBusy(false);
144
+ $("#btnCreateChatRoom").disabled = false;
145
+ }
146
+ };
147
+
148
+ app.setJoinBusy = (busy) => {
149
+ $("#btnJoin").disabled = busy;
150
+ $("#btnCreate").disabled = busy;
151
+ };
152
+
153
+ app.leaveRoom = (silent = false) => {
154
+ const roomId = app.state.room?.id;
155
+ if (roomId) void app.removeJoinedRoom(roomId, { leaveServer: !silent });
156
+ };
157
+ app.removeJoinedRoom = async (roomId, { leaveServer = false, reason = false } = {}) => {
158
+ const active = app.state.room?.id === roomId;
159
+ const entry = app.state.rooms.get(roomId);
160
+ if (active) {
161
+ app.state.navigationGeneration++;
162
+ app.saveDraft(roomId, $("#msgInput").value);
163
+ app.savePosition(roomId, $("#thread").scrollTop);
164
+ app.stopPolling();
165
+ app.closeMention();
166
+ app.state.room = null;
167
+ app.state.myName = "";
168
+ app.state.unread = 0;
169
+ app.rendered = 0;
170
+ app.firstMessageId = null;
171
+ $("#msgList").textContent = "";
172
+ $("#msgInput").disabled = true;
173
+ $("#btnSend").disabled = true;
174
+ }
175
+ app.state.rooms.delete(roomId);
176
+ app.state.memberSessions.delete(roomId);
177
+ app.state.joinedIds.delete(roomId);
178
+ app.state.roomNames.delete(roomId);
179
+ app.saveJoinedIds();
180
+ app.saveRoomNames();
181
+ if (leaveServer && entry) {
182
+ void app.api(`/rooms/${encodeURIComponent(roomId)}/leave`, {
183
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID }),
184
+ }).catch(() => {});
185
+ }
186
+ if (active) {
187
+ const next = app.state.rooms.keys().next().value;
188
+ if (next) app.activateRoom(next);
189
+ else {
190
+ LS.roomId = "";
191
+ LS.name = "";
192
+ app.showJoin();
193
+ if (reason) app.showJoinError("roomNotFound");
194
+ }
195
+ }
196
+ app.startRoomWatcher();
197
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
198
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
199
+ };
200
+
201
+ app.startRoomWatcher = () => {
202
+ clearTimeout(app.state.watcherTimer);
203
+ if (!app.state.rooms.size) return;
204
+ app.state.watcherTimer = setTimeout(async () => {
205
+ const inactive = [...app.state.rooms.keys()].filter((id) => id !== app.state.room?.id);
206
+ await bounded(inactive, 3, (roomId) => watchRoom(roomId, app));
207
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
208
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
209
+ app.startRoomWatcher();
210
+ }, 5000);
211
+ };
212
+
213
+ app.refreshRoomList = async () => {
214
+ const empty = $("#roomListEmpty"), chatEmpty = $("#roomListChatEmpty");
215
+ try {
216
+ const rooms = await app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`);
217
+ app.state.availableRooms = rooms;
218
+ if (!app.state.restored) await app.restoreJoinedRooms(rooms);
219
+ else {
220
+ syncCachedRooms(rooms, app);
221
+ await app.discoverDirectRooms(rooms);
222
+ }
223
+ app.renderRoomOptions($("#roomList"), rooms);
224
+ app.renderRoomOptions($("#roomListChat"), rooms);
225
+ empty.hidden = rooms.length > 0;
226
+ chatEmpty.hidden = rooms.length > 0;
227
+ } catch (error) {
228
+ if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
229
+ else {
230
+ app.setText(empty, "roomListError");
231
+ app.setText(chatEmpty, "roomListError");
232
+ empty.hidden = false;
233
+ chatEmpty.hidden = false;
234
+ }
235
+ }
236
+ };
237
+
238
+ app.restoreJoinedRooms = async (rooms) => {
239
+ if (app.state.restoring) {
240
+ while (app.state.restoring) await new Promise((resolve) => setTimeout(resolve, 10));
241
+ return;
242
+ }
243
+ app.state.restoring = true;
244
+ try {
245
+ const activeId = LS.roomId;
246
+ const directIds = rooms.filter((room) => room.kind === "direct" && room.directSessionIDs?.includes(LS.sessionID)).map((room) => room.id);
247
+ const candidates = [...new Set([...app.state.joinedIds, ...directIds])];
248
+ const valid = new Set();
249
+ await bounded(candidates, 3, async (roomId) => {
250
+ try {
251
+ const room = rooms.find((item) => item.id === roomId) || await app.api(`/rooms/${encodeURIComponent(roomId)}`);
252
+ const members = await app.api(`/rooms/${encodeURIComponent(roomId)}/members`);
253
+ const me = members.find((member) => member.sessionID === LS.sessionID);
254
+ if (!me) return;
255
+ valid.add(roomId);
256
+ app.ensureJoinedRoom(room, me.name);
257
+ } catch { /* Missing or inaccessible rooms are removed without rejoining them. */ }
258
+ });
259
+ app.state.joinedIds = valid;
260
+ app.saveJoinedIds();
261
+ app.state.restored = true;
262
+ if (activeId && valid.has(activeId)) app.activateRoom(activeId);
263
+ else {
264
+ LS.roomId = "";
265
+ LS.name = "";
266
+ const fallback = valid.values().next().value;
267
+ if (fallback) app.activateRoom(fallback);
268
+ else app.showJoin();
269
+ }
270
+ app.startRoomWatcher();
271
+ } finally { app.state.restoring = false; }
272
+ };
273
+
274
+ app.discoverDirectRooms = async (rooms) => {
275
+ const candidates = rooms.filter((room) => room.kind === "direct" && !app.state.rooms.has(room.id));
276
+ await bounded(candidates, 3, async (room) => {
277
+ try {
278
+ const members = await app.api(`/rooms/${encodeURIComponent(room.id)}/members`);
279
+ const me = members.find((member) => member.sessionID === LS.sessionID);
280
+ if (me) app.ensureJoinedRoom(room, me.name);
281
+ } catch { /* A direct room can be deleted while the sidebar refreshes. */ }
282
+ });
283
+ };
284
+
285
+ app.renderRoomOptions = (list, rooms) => {
286
+ if (!list) return;
287
+ list.textContent = "";
288
+ const ordered = [...rooms].sort((left, right) => Number(app.state.rooms.has(right.id)) - Number(app.state.rooms.has(left.id)));
289
+ for (const room of ordered) {
290
+ const row = document.createElement("li"), button = document.createElement("button");
291
+ button.type = "button";
292
+ button.dataset.roomId = room.id;
293
+ const entry = app.state.rooms.get(room.id);
294
+ button.className = `room-row${app.state.room?.id === room.id ? " selected" : ""}${entry ? " joined" : ""}`;
295
+ if (app.state.room?.id === room.id) button.setAttribute("aria-current", "page");
296
+ button.title = app.t(entry ? "joined" : "joinAction");
297
+ const name = document.createElement("span");
298
+ name.className = "r-name";
299
+ name.textContent = room.name;
300
+ const kind = document.createElement("span");
301
+ kind.className = "r-kind";
302
+ if (room.kind === "direct") app.setText(kind, "direct");
303
+ const meta = document.createElement("span");
304
+ meta.className = "r-meta";
305
+ const shownRoom = entry?.room || room;
306
+ meta.textContent = app.t("roomMeta", { members: shownRoom.participants.length, count: shownRoom.messages.length });
307
+ const preview = document.createElement("span");
308
+ preview.className = "r-preview";
309
+ const lastMessage = entry?.preview || room.messages.at(-1)?.text || "";
310
+ preview.textContent = entry ? lastMessage : "";
311
+ const status = document.createElement("span");
312
+ status.className = "r-status";
313
+ app.setText(status, entry ? "joined" : "joinAction");
314
+ button.append(name, kind, meta, preview, status);
315
+ const unread = entry?.unreadIds.size || (entry?.unreadOverflow ? 100 : 0);
316
+ if (unread) {
317
+ const badge = document.createElement("span");
318
+ badge.className = "r-badge";
319
+ badge.textContent = unread > 99 ? "99+" : String(unread);
320
+ badge.setAttribute("aria-label", app.t("unreadMessages", { count: unread }));
321
+ button.append(badge);
322
+ }
323
+ button.addEventListener("click", () => app.joinRoom(room.id, app.state.myName || $("#inName").value.trim() || app.t("guest")));
324
+ row.append(button);
325
+ list.append(row);
326
+ }
327
+ };
328
+
329
+ app.closePanels = () => {
330
+ document.querySelectorAll(".panel").forEach((panel) => { panel.hidden = true; });
331
+ $("#btnMembers").setAttribute("aria-expanded", "false");
332
+ $("#btnSettings").setAttribute("aria-expanded", "false");
333
+ };
334
+ app.togglePanel = (selector) => {
335
+ const panel = $(selector), wasHidden = panel.hidden;
336
+ app.closePanels();
337
+ panel.hidden = !wasHidden;
338
+ const trigger = $(selector === "#memberPanel" ? "#btnMembers" : "#btnSettings");
339
+ trigger.setAttribute("aria-expanded", String(wasHidden));
340
+ if (wasHidden) {
341
+ app.lastFocus = trigger;
342
+ if (selector === "#memberPanel") void app.loadManageableMembers();
343
+ const heading = panel.querySelector("h3");
344
+ heading.tabIndex = -1;
345
+ heading.focus();
346
+ }
347
+ };
348
+ app.openTokenBox = () => { $("#tokenBox").open = true; };
349
+ app.openChatSettings = () => {
350
+ app.closePanels();
351
+ $("#chatSettings").hidden = false;
352
+ $("#btnSettings").setAttribute("aria-expanded", "true");
353
+ $("#tokenHint").hidden = false;
354
+ $("#inTokenChat").focus();
355
+ };
356
+
357
+ app.deleteRoom = async () => {
358
+ const room = app.state.room;
359
+ if (!room || !confirm(app.t("deleteConfirm", { name: room.name }))) return;
360
+ try {
361
+ await app.api(`/rooms/${encodeURIComponent(room.id)}`, {
362
+ method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }),
363
+ });
364
+ await app.removeJoinedRoom(room.id);
365
+ app.clearDraft(room.id);
366
+ app.clearPosition(room.id);
367
+ app.saveFailedMessages(room.id, []);
368
+ } catch (error) { app.showSendError("sendFailed", { message: error.message }); }
369
+ };
370
+
371
+ app.copyRoomId = async () => {
372
+ try {
373
+ await navigator.clipboard.writeText(app.state.room.id);
374
+ app.flash($("#btnCopyId"), "copied");
375
+ } catch { app.showSendError("copyFailed", { id: app.state.room.id }); }
376
+ };
377
+
378
+ app.autoJoin = async () => {
379
+ await app.refreshRoomList();
380
+ };
381
+
382
+ app.retryPendingAction = () => {
383
+ const action = app.state.pendingAction;
384
+ if (action?.type === "join") void app.joinRoom(action.roomId, action.name);
385
+ else if (action?.type === "create") void app.createRoom(action);
386
+ else if (!app.state.room) void app.autoJoin();
387
+ };
388
+ }
389
+
390
+ async function bounded(items, limit, action) {
391
+ let cursor = 0;
392
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
393
+ while (cursor < items.length) await action(items[cursor++]);
394
+ }));
395
+ }
396
+
397
+ function syncCachedRooms(rooms, app) {
398
+ const remote = new Map(rooms.map((room) => [room.id, room]));
399
+ for (const [roomId, entry] of app.state.rooms) {
400
+ const fresh = remote.get(roomId);
401
+ if (!fresh) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId }); continue; }
402
+ if (app.state.room?.id === roomId) continue;
403
+ const messages = new Map([...entry.room.messages, ...fresh.messages].map((message) => [message.id, message]));
404
+ entry.room = { ...fresh, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
405
+ const latest = entry.room.messages.at(-1);
406
+ if (latest) { entry.preview = latest.text; entry.previewAt = latest.createdAt; }
407
+ }
408
+ }
409
+
410
+ async function watchRoom(roomId, app) {
411
+ const entry = app.state.rooms.get(roomId);
412
+ if (!entry || app.state.room?.id === roomId) return;
413
+ try {
414
+ const query = new URLSearchParams({ sessionID: app.LS.sessionID, roomId, excludeSelf: "0", timeout: "0" });
415
+ const result = await app.api(`/inbox?${query}`);
416
+ if (app.state.rooms.get(roomId) !== entry) return;
417
+ if (!result.member) { await app.removeJoinedRoom(roomId, { reason: false }); return; }
418
+ if (app.state.room?.id === roomId) return;
419
+ const sawSystem = (result.items || []).some((message) => message.senderId === "system");
420
+ for (const message of result.items || []) {
421
+ if (!entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
422
+ if (!entry.room.messages.some((item) => item.id === message.id)) entry.room.messages.push({ ...message, roomId });
423
+ if (message.createdAt >= entry.previewAt) {
424
+ entry.preview = message.text;
425
+ entry.previewAt = message.createdAt;
426
+ }
427
+ }
428
+ if (sawSystem || result.hasMore) {
429
+ const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
430
+ if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
431
+ entry.room.participants = latest.participants;
432
+ const messages = new Map([...entry.room.messages, ...latest.messages].map((message) => [message.id, message]));
433
+ entry.room.messages = [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500);
434
+ const newest = latest.messages.at(-1);
435
+ if (newest && newest.createdAt >= entry.previewAt) { entry.preview = newest.text; entry.previewAt = newest.createdAt; }
436
+ }
437
+ entry.unreadOverflow = Boolean(result.hasMore);
438
+ if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
439
+ } catch (error) {
440
+ if (error.status === 401) app.openChatSettings();
441
+ else if (error.status === 404) await app.removeJoinedRoom(roomId, { reason: false });
442
+ }
443
+ }