@alexsun-top/opencode-chat-room 0.5.0 → 0.5.2
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.
- package/CHANGELOG.md +26 -0
- package/README.md +23 -7
- package/README.zh-CN.md +23 -7
- package/docs/administrator-rooms.md +51 -0
- package/package.json +11 -2
- package/plugin.ts +29 -12
- package/server/admin-auth.ts +16 -0
- package/server/admin-plan-routes.ts +79 -0
- package/server/admin-routes.ts +154 -0
- package/server/admin-scheduler.ts +42 -0
- package/server/admin-state.ts +61 -0
- package/server/admin-task-routes.ts +182 -0
- package/server/assets/base.css +55 -43
- package/server/assets/chat/admin.js +223 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/editor.js +211 -0
- package/server/assets/chat/events.js +34 -10
- package/server/assets/chat/index.js +8 -0
- package/server/assets/chat/markdown.js +1 -12
- package/server/assets/chat/members.js +1 -1
- package/server/assets/chat/mentions.js +38 -28
- package/server/assets/chat/message-window.js +18 -0
- package/server/assets/chat/messages.js +64 -46
- package/server/assets/chat/questions.js +113 -41
- package/server/assets/chat/receipts.js +0 -1
- package/server/assets/chat/reminders.js +101 -0
- package/server/assets/chat/replies.js +149 -0
- package/server/assets/chat/rooms.js +30 -10
- package/server/assets/chat/state.js +68 -18
- package/server/assets/conversation.css +111 -45
- package/server/assets/responsive.css +83 -28
- package/server/chat-server.ts +23 -6
- package/server/chat.html +82 -31
- package/server/inbox.ts +5 -1
- package/server/newrooms.ts +27 -10
- package/server/resource-routes.ts +3 -0
- package/server/room-reminders.ts +212 -0
- package/server/wake.ts +11 -15
- package/skills/chatroom/SKILL.md +21 -1
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/agent-receipts.ts +13 -18
- package/src/center-client.ts +1 -1
- package/src/center-inbox.ts +2 -0
- package/src/plugin-notifications.ts +4 -0
- package/src/queue.ts +7 -2
- package/src/reminder-client.ts +50 -0
- package/src/resource-read.ts +118 -0
- package/src/resources.ts +1 -1
- package/src/sqlite-state.ts +89 -21
- package/src/store.ts +22 -8
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +13 -3
- package/src/v2-plugin.ts +24 -7
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
import { createRandomId, LS } from "./state.js";
|
|
2
2
|
import { renderMarkdown } from "./markdown.js";
|
|
3
|
-
import { hasMessageSelection, pruneMessageRows } from "./message-window.js";
|
|
3
|
+
import { hasMessageSelection, pruneMessageRows, trimMessages } from "./message-window.js";
|
|
4
4
|
import { formatSystemMessage, setRoomPreview } from "./system-messages.js";
|
|
5
|
+
import { installEditor } from "./editor.js";
|
|
5
6
|
|
|
6
7
|
export function initMessages(app) {
|
|
7
8
|
const $ = app.$;
|
|
9
|
+
installEditor($("#msgInput"));
|
|
8
10
|
let pollDelay = 2000;
|
|
9
11
|
|
|
10
12
|
app.autoGrow = (textarea) => {
|
|
13
|
+
const thread = $("#thread"), atBottom = Boolean(app.state.room && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
|
|
11
14
|
textarea.style.overflowY = "hidden";
|
|
12
15
|
const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
|
|
13
16
|
const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
|
|
14
17
|
const border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
|
|
15
18
|
if (!textarea.value) {
|
|
16
19
|
textarea.style.height = `${Math.max(line + padding + border, parseFloat(style.minHeight) || 0)}px`;
|
|
20
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
17
21
|
return;
|
|
18
22
|
}
|
|
19
23
|
textarea.style.height = "auto";
|
|
@@ -21,6 +25,7 @@ export function initMessages(app) {
|
|
|
21
25
|
const overflow = textarea.scrollHeight > limit + 1;
|
|
22
26
|
textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
|
|
23
27
|
textarea.style.overflowY = overflow ? "auto" : "hidden";
|
|
28
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
24
29
|
};
|
|
25
30
|
app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
|
|
26
31
|
app.updateDraftCount = () => app.setText($("#draftCount"), "messageCount", { count: $("#msgInput").value.length });
|
|
@@ -43,6 +48,11 @@ export function initMessages(app) {
|
|
|
43
48
|
for (const item of items) {
|
|
44
49
|
const row = document.createElement("article"), text = document.createElement("p");
|
|
45
50
|
row.className = "failed-message";
|
|
51
|
+
if (item.replyTarget) {
|
|
52
|
+
const context = document.createElement("small"); context.className = "failed-reply-context";
|
|
53
|
+
context.textContent = `${item.replyTarget.senderId}: ${String(item.replyTarget.text).slice(0, 120)}`;
|
|
54
|
+
row.dataset.replyTargetId = item.replyToMessageID; row.append(context);
|
|
55
|
+
}
|
|
46
56
|
text.textContent = item.text;
|
|
47
57
|
row.append(text, failedAction("retryFailed", roomId, item.id, app), failedAction("discardFailed", roomId, item.id, app));
|
|
48
58
|
panel.append(row);
|
|
@@ -58,12 +68,12 @@ export function initMessages(app) {
|
|
|
58
68
|
app.state.retryingFailedIds.add(failedId);
|
|
59
69
|
app.renderFailedMessages();
|
|
60
70
|
try {
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
71
|
+
const questionTarget = item.replyTarget?.isQuestion, entry = app.state.rooms.get(roomId);
|
|
72
|
+
const updated = questionTarget ? (await app.answerQuestionFromReply(roomId, item.replyToMessageID, item.text), entry?.room)
|
|
73
|
+
: await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion), ...(item.replyToMessageID ? { replyToMessageID: item.replyToMessageID } : {}) }) });
|
|
74
|
+
app.completeAttachmentsFromText?.(roomId, item.text);
|
|
65
75
|
if (entry) {
|
|
66
|
-
entry.room = mergeRoom(entry.room, updated);
|
|
76
|
+
if (!questionTarget) entry.room = mergeRoom(entry.room, updated);
|
|
67
77
|
const latest = entry.room.messages.at(-1);
|
|
68
78
|
if (latest && latest.createdAt >= entry.previewAt) setRoomPreview(entry, latest);
|
|
69
79
|
}
|
|
@@ -126,6 +136,7 @@ export function initMessages(app) {
|
|
|
126
136
|
for (const [id, message] of entry.unreadIds) if (message.createdAt <= timestamp) entry.unreadIds.delete(id);
|
|
127
137
|
app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
|
|
128
138
|
app.updateBadge();
|
|
139
|
+
app.updateJump();
|
|
129
140
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
130
141
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
131
142
|
} catch { /* The next active poll will retry the read watermark. */ }
|
|
@@ -163,14 +174,29 @@ export function initMessages(app) {
|
|
|
163
174
|
content.append(body, app.createReceiptButton(message, own));
|
|
164
175
|
row.append(meta, content);
|
|
165
176
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
177
|
+
if (message.senderId !== "system") {
|
|
178
|
+
const copy = document.createElement("button");
|
|
179
|
+
copy.type = "button";
|
|
180
|
+
copy.className = "message-copy";
|
|
181
|
+
copy.dataset.copyMessage = "";
|
|
182
|
+
copy.setAttribute("aria-label", app.t("copyMessage"));
|
|
183
|
+
copy.dataset.i18nAriaLabel = "copyMessage";
|
|
184
|
+
copy.dataset.i18nTitle = "copyMessage";
|
|
185
|
+
copy.title = app.t("copyMessage");
|
|
186
|
+
const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
|
187
|
+
icon.classList.add("message-copy-icon"); icon.setAttribute("viewBox", "0 0 24 24"); icon.setAttribute("aria-hidden", "true");
|
|
188
|
+
const back = document.createElementNS("http://www.w3.org/2000/svg", "rect");
|
|
189
|
+
back.setAttribute("x", "4"); back.setAttribute("y", "3"); back.setAttribute("width", "13"); back.setAttribute("height", "15"); back.setAttribute("rx", "2");
|
|
190
|
+
const front = document.createElementNS("http://www.w3.org/2000/svg", "rect");
|
|
191
|
+
front.setAttribute("x", "8"); front.setAttribute("y", "7"); front.setAttribute("width", "12"); front.setAttribute("height", "14"); front.setAttribute("rx", "2");
|
|
192
|
+
icon.append(back, front);
|
|
193
|
+
const feedback = document.createElement("span");
|
|
194
|
+
feedback.className = "message-copy-feedback"; feedback.dataset.flashOutput = ""; feedback.dataset.i18n = "copyMessage";
|
|
195
|
+
feedback.hidden = true; feedback.setAttribute("role", "status"); feedback.setAttribute("aria-live", "polite"); feedback.textContent = app.t("copyMessage");
|
|
196
|
+
copy.append(icon, feedback);
|
|
197
|
+
copy._copyText = String(message.text ?? "");
|
|
198
|
+
row.append(copy);
|
|
199
|
+
}
|
|
174
200
|
if (live) row.classList.add("in");
|
|
175
201
|
return row;
|
|
176
202
|
};
|
|
@@ -266,20 +292,29 @@ export function initMessages(app) {
|
|
|
266
292
|
};
|
|
267
293
|
|
|
268
294
|
app.send = async () => {
|
|
269
|
-
const input = $("#msgInput"),
|
|
270
|
-
|
|
295
|
+
const input = $("#msgInput"), room = app.state.room, replyTarget = room && app.replyTargetFor?.(room.id);
|
|
296
|
+
const isQuestion = !replyTarget && Boolean(app.isQuestionSending?.());
|
|
297
|
+
if (!room || app.state.sendingRooms?.has(room.id)) return;
|
|
298
|
+
const message = app.prepareMessage?.(room.id, input.value) || { text: input.value.trim(), ids: [], ready: Boolean(input.value.trim()) };
|
|
299
|
+
if (!message.ready) return;
|
|
300
|
+
const text = message.text;
|
|
271
301
|
const revision = app.state.draftRevision.get(room.id) || 0;
|
|
302
|
+
app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
|
|
272
303
|
app.closeMention();
|
|
304
|
+
app.clearReplyTarget?.(room.id);
|
|
273
305
|
input.value = "";
|
|
274
306
|
app.clearDraft(room.id);
|
|
275
307
|
app.autoGrow(input);
|
|
276
|
-
app.updateSendState();
|
|
277
308
|
app.updateDraftCount();
|
|
309
|
+
app.updateSendState();
|
|
278
310
|
app.hideSendError();
|
|
279
311
|
try {
|
|
280
|
-
|
|
281
|
-
|
|
312
|
+
let updated;
|
|
313
|
+
if (replyTarget?.isQuestion) { await app.answerQuestionFromReply(room.id, replyTarget.id, text); updated = app.state.rooms.get(room.id)?.room || room; }
|
|
314
|
+
else updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
|
|
315
|
+
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, isQuestion, ...(!isQuestion && replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
|
|
282
316
|
});
|
|
317
|
+
app.completeAttachments?.(room.id, message.ids);
|
|
283
318
|
if (app.state.room?.id !== room.id) return;
|
|
284
319
|
app.state.room = updated;
|
|
285
320
|
const entry = app.state.rooms.get(room.id);
|
|
@@ -299,7 +334,8 @@ export function initMessages(app) {
|
|
|
299
334
|
} catch (error) {
|
|
300
335
|
const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
|
|
301
336
|
const failures = app.state.failedMessages.get(room.id) || [];
|
|
302
|
-
app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, isQuestion }]);
|
|
337
|
+
app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, isQuestion, ...(!isQuestion && replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
|
|
338
|
+
app.completeAttachments?.(room.id, message.ids);
|
|
303
339
|
app.renderFailedMessages();
|
|
304
340
|
if (app.state.room?.id !== room.id) return;
|
|
305
341
|
if (unchanged) app.clearDraft(room.id);
|
|
@@ -308,6 +344,9 @@ export function initMessages(app) {
|
|
|
308
344
|
app.updateDraftCount();
|
|
309
345
|
if (error.status === 401) { app.openChatSettings(); app.showSendError("sendAuth"); }
|
|
310
346
|
else app.showSendError(error.network ? "sendNetwork" : "sendFailed", { message: error.message });
|
|
347
|
+
} finally {
|
|
348
|
+
app.state.sendingRooms.delete(room.id);
|
|
349
|
+
if (app.state.room?.id === room.id) app.updateSendState();
|
|
311
350
|
}
|
|
312
351
|
};
|
|
313
352
|
|
|
@@ -364,13 +403,13 @@ export function initMessages(app) {
|
|
|
364
403
|
if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
|
|
365
404
|
added++;
|
|
366
405
|
}
|
|
367
|
-
if (entry && item.createdAt > entry.readTs && !
|
|
406
|
+
if (entry && item.createdAt > entry.readTs && !isOwnMessage(item, app) && !entry.unreadIds.has(item.id)) {
|
|
368
407
|
entry.unreadIds.set(item.id, item); unreadChanged = true;
|
|
369
408
|
}
|
|
370
409
|
}
|
|
371
410
|
if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
|
|
372
411
|
if (entry) entry.unreadOverflow = Boolean(data.hasMore);
|
|
373
|
-
|
|
412
|
+
if (messages.length > 500) { const anchorId = app.state.positions.get(roomId)?.messageId, anchor = anchorId && messages.find((item) => item.id === anchorId); messages.splice(0, messages.length - 500); if (anchor && !messages.includes(anchor)) messages.unshift(anchor); }
|
|
374
413
|
const rendered = app.renderMessages(true);
|
|
375
414
|
if (sawSystem) {
|
|
376
415
|
await app.refreshRoomMeta(roomId, generation);
|
|
@@ -448,33 +487,12 @@ export function initMessages(app) {
|
|
|
448
487
|
return { ...updated, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
|
|
449
488
|
}
|
|
450
489
|
|
|
451
|
-
function trimMessages(list, app) {
|
|
452
|
-
if (list.children.length <= 400 || hasMessageSelection(list)) return;
|
|
453
|
-
const saved = app.state.positions.get(app.state.room?.id), rows = [...list.querySelectorAll("[data-msg-id]")];
|
|
454
|
-
const anchor = saved?.messageId && rows.find((row) => row.dataset.msgId === saved.messageId);
|
|
455
|
-
if (anchor && rows.indexOf(anchor) < rows.length - 280) {
|
|
456
|
-
const recent = rows.at(-300);
|
|
457
|
-
while (list.firstElementChild && list.firstElementChild !== anchor) list.firstElementChild.remove();
|
|
458
|
-
let next = anchor.nextElementSibling;
|
|
459
|
-
while (next && next !== recent) { const after = next.nextElementSibling; next.remove(); next = after; }
|
|
460
|
-
const gap = document.createElement("li"); gap.className = "gap"; app.setText(gap, "messagesBetweenOmitted"); anchor.after(gap);
|
|
461
|
-
return;
|
|
462
|
-
}
|
|
463
|
-
while (list.children.length > 300) list.removeChild(list.firstChild);
|
|
464
|
-
if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
|
|
465
|
-
const gap = document.createElement("li");
|
|
466
|
-
gap.className = "gap";
|
|
467
|
-
app.setText(gap, "earlierMessages");
|
|
468
|
-
list.insertBefore(gap, list.firstChild);
|
|
469
|
-
}
|
|
470
490
|
}
|
|
471
491
|
|
|
472
|
-
function isOwnMessage(message, app) {
|
|
473
|
-
const
|
|
492
|
+
export function isOwnMessage(message, app, room = app.state.room, myName = app.state.myName) {
|
|
493
|
+
const direct = room.kind === "direct";
|
|
474
494
|
const sameName = app.state.memberSessions.get(room.id)?.filter((member) => member.name === message.senderId);
|
|
475
495
|
return direct ? message.senderId === LS.sessionID
|
|
476
496
|
: message.senderSessionID ? message.senderSessionID === LS.sessionID
|
|
477
|
-
: message.senderId ===
|
|
478
|
-
}
|
|
479
|
-
|
|
497
|
+
: message.senderId === myName && sameName?.length === 1 && sameName[0].sessionID === LS.sessionID;
|
|
480
498
|
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
+
import { installEditor } from "./editor.js";
|
|
3
|
+
import { copyTextToClipboard, renderMarkdown } from "./markdown.js";
|
|
2
4
|
|
|
3
5
|
export function initQuestions(app) {
|
|
4
|
-
const $ = app.$, pending = new Map(), selected = new Map(), drafts = new Map(), questionMode = new Map(), submitting = new Set();
|
|
6
|
+
const $ = app.$, pending = new Map(), selected = new Map(), drafts = new Map(), questionMode = new Map(), submitting = new Set(), unsupported = new Set();
|
|
5
7
|
let request = 0;
|
|
6
8
|
const panel = $("#questionPanel"), trigger = $("#btnQuestions"), list = $("#questionList"), status = $("#questionStatus");
|
|
7
9
|
app.isQuestionSending = () => Boolean(questionMode.get(app.state.room?.id));
|
|
@@ -32,13 +34,15 @@ export function initQuestions(app) {
|
|
|
32
34
|
trigger.setAttribute("aria-label", `${app.t("questions")}: ${items.length}`);
|
|
33
35
|
list.textContent = "";
|
|
34
36
|
for (const question of items) {
|
|
35
|
-
const item = document.createElement("li"),
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
button.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
37
|
+
const item = document.createElement("li"), card = document.createElement("article"), select = document.createElement("button"), body = document.createElement("div");
|
|
38
|
+
card.className = `question-item${selected.get(roomId) === question.id ? " selected" : ""}`;
|
|
39
|
+
card.dataset.questionId = question.id;
|
|
40
|
+
select.type = "button"; select.className = "question-select"; select.textContent = app.t("selectQuestion");
|
|
41
|
+
select.setAttribute("aria-pressed", String(selected.get(roomId) === question.id));
|
|
42
|
+
body.className = "question-item-body";
|
|
43
|
+
renderMarkdown(body, question.text, app);
|
|
44
|
+
card.append(body, select);
|
|
45
|
+
item.append(card);
|
|
42
46
|
list.append(item);
|
|
43
47
|
}
|
|
44
48
|
status.hidden = items.length > 0 || status.dataset.error === "true";
|
|
@@ -50,9 +54,11 @@ export function initQuestions(app) {
|
|
|
50
54
|
function renderReply(roomId) {
|
|
51
55
|
const box = $("#questionReply"), question = (pending.get(roomId) || []).find((item) => item.id === selected.get(roomId));
|
|
52
56
|
if (question && box.dataset.roomId === roomId && box.dataset.questionId === question.id) {
|
|
53
|
-
const key = `${roomId}\0${question.id}`, input = box.querySelector("
|
|
57
|
+
const key = `${roomId}\0${question.id}`, input = box.querySelector("[contenteditable]"), send = box.querySelector("button[type=submit]"), copy = box.querySelector(".question-copy"), feedback = box.querySelector(".question-copy-feedback");
|
|
54
58
|
box.hidden = false;
|
|
55
|
-
|
|
59
|
+
copy.textContent = app.t("copyQuestion"); send.textContent = app.t("sendAnswer"); input.setAttribute("aria-placeholder", app.t("answerPlaceholder"));
|
|
60
|
+
if (feedback.dataset.copyState) feedback.textContent = app.t(feedback.dataset.copyState);
|
|
61
|
+
if (input && send) send.disabled = !input.value.trim() || input.value.length > 2000 || submitting.has(key);
|
|
56
62
|
return;
|
|
57
63
|
}
|
|
58
64
|
box.textContent = "";
|
|
@@ -60,36 +66,70 @@ export function initQuestions(app) {
|
|
|
60
66
|
box.dataset.questionId = question?.id || "";
|
|
61
67
|
box.hidden = !question;
|
|
62
68
|
if (!question) return;
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
69
|
+
const copy = document.createElement("button"), feedback = document.createElement("p"), form = document.createElement("form"), input = document.createElement("div"), send = document.createElement("button");
|
|
70
|
+
copy.type = "button"; copy.className = "btn ghost small question-copy"; copy.textContent = app.t("copyQuestion");
|
|
71
|
+
feedback.className = "question-copy-feedback"; feedback.setAttribute("role", "status"); feedback.setAttribute("aria-live", "polite");
|
|
72
|
+
copy.addEventListener("click", async () => {
|
|
73
|
+
feedback.dataset.copyState = await copyTextToClipboard(question.text) ? "questionCopied" : "questionCopyFailed";
|
|
74
|
+
feedback.textContent = app.t(feedback.dataset.copyState);
|
|
75
|
+
});
|
|
66
76
|
form.className = "question-reply-form";
|
|
67
77
|
input.className = "input";
|
|
68
|
-
input.
|
|
69
|
-
input.
|
|
70
|
-
input.
|
|
78
|
+
input.setAttribute("role", "textbox"); input.setAttribute("aria-multiline", "true");
|
|
79
|
+
input.setAttribute("contenteditable", "true"); input.classList.add("message-editor");
|
|
80
|
+
input.setAttribute("aria-autocomplete", "list"); input.setAttribute("aria-controls", "mentionPicker"); input.setAttribute("aria-expanded", "false");
|
|
81
|
+
input.setAttribute("aria-placeholder", app.t("answerPlaceholder"));
|
|
71
82
|
input.setAttribute("aria-label", app.t("answerPlaceholder"));
|
|
72
|
-
input
|
|
83
|
+
installEditor(input);
|
|
73
84
|
const key = `${roomId}\0${question.id}`;
|
|
85
|
+
input.draftValue = drafts.has(key) ? drafts.get(key) : questionAuthorMention(question, roomId, app);
|
|
74
86
|
send.type = "submit";
|
|
75
87
|
send.className = "btn primary small";
|
|
76
88
|
send.textContent = app.t("sendAnswer");
|
|
77
|
-
send.disabled = !input.value.trim() || submitting.has(key);
|
|
78
|
-
input.addEventListener("input", () => {
|
|
79
|
-
drafts.set(`${roomId}\0${question.id}`, input.
|
|
80
|
-
|
|
89
|
+
send.disabled = !input.value.trim() || input.value.length > 2000 || submitting.has(key);
|
|
90
|
+
input.addEventListener("input", (event) => {
|
|
91
|
+
drafts.set(`${roomId}\0${question.id}`, input.draftValue);
|
|
92
|
+
if (!event.isComposing) app.recomputeMention(input);
|
|
93
|
+
send.disabled = !input.value.trim() || input.value.length > 2000 || submitting.has(key);
|
|
94
|
+
if (input.value.length > 2000) { app.setText(status, "answerTooLong"); status.hidden = false; }
|
|
95
|
+
});
|
|
96
|
+
input.addEventListener("compositionend", () => app.recomputeMention(input));
|
|
97
|
+
input.addEventListener("keydown", (event) => {
|
|
98
|
+
if (app.handleMentionKey(event, input)) return;
|
|
99
|
+
if (event.key === "Enter" && !event.shiftKey && !event.isComposing && event.keyCode !== 229) { event.preventDefault(); form.requestSubmit(); }
|
|
81
100
|
});
|
|
101
|
+
input.addEventListener("keyup", (event) => { if (!event.isComposing && /^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key)) app.recomputeMention(input); });
|
|
102
|
+
input.addEventListener("click", () => app.recomputeMention(input));
|
|
103
|
+
input.addEventListener("blur", () => { if (app.mention?.editor === input) app.closeMention(); });
|
|
82
104
|
form.addEventListener("submit", (event) => {
|
|
83
105
|
event.preventDefault();
|
|
84
106
|
void answer(roomId, question.id, input.value.trim(), send);
|
|
85
107
|
});
|
|
86
108
|
form.append(input, send);
|
|
87
|
-
box.append(
|
|
109
|
+
box.append(copy, feedback, form);
|
|
110
|
+
input.setCaret(input.value.length);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function questionAuthorMention(question, roomId, app) {
|
|
114
|
+
const members = app.state.memberSessions.get(roomId) || [];
|
|
115
|
+
const author = question.senderSessionID
|
|
116
|
+
? members.filter((member) => member.sessionID === question.senderSessionID)
|
|
117
|
+
: members.filter((member) => member.name === question.senderId);
|
|
118
|
+
if (author.length !== 1 || members.filter((member) => member.name === author[0].name).length !== 1 || author[0].sessionID === LS.sessionID || author[0].name === "all") return "";
|
|
119
|
+
return `<at>@${author[0].name}</at> `;
|
|
88
120
|
}
|
|
89
121
|
|
|
90
122
|
async function load(roomId = app.state.room?.id) {
|
|
91
123
|
if (!roomId) return;
|
|
92
124
|
const id = ++request;
|
|
125
|
+
if (unsupported.has(roomId)) {
|
|
126
|
+
const member = await roomMembership(roomId);
|
|
127
|
+
if (id !== request || app.state.room?.id !== roomId) return;
|
|
128
|
+
if (member === false) await app.removeJoinedRoom(roomId, { reason: true });
|
|
129
|
+
else if (member === true) showUnavailable();
|
|
130
|
+
else showFailed();
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
93
133
|
if (app.state.room?.id === roomId && !pending.has(roomId)) {
|
|
94
134
|
app.setText(status, "questionsLoading");
|
|
95
135
|
status.hidden = false;
|
|
@@ -103,17 +143,46 @@ export function initQuestions(app) {
|
|
|
103
143
|
render(roomId);
|
|
104
144
|
} catch (error) {
|
|
105
145
|
if (id !== request || app.state.room?.id !== roomId) return;
|
|
146
|
+
if (error.status === 404) {
|
|
147
|
+
const member = await roomMembership(roomId);
|
|
148
|
+
if (id !== request || app.state.room?.id !== roomId) return;
|
|
149
|
+
if (member === false) await app.removeJoinedRoom(roomId, { reason: true });
|
|
150
|
+
else if (member === true) { unsupported.add(roomId); showUnavailable(); }
|
|
151
|
+
else showFailed();
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
106
154
|
if (error.status === 401) app.openChatSettings();
|
|
107
|
-
|
|
108
|
-
app.setText(status, "questionsFailed");
|
|
109
|
-
status.hidden = false;
|
|
155
|
+
showFailed();
|
|
110
156
|
render(roomId);
|
|
111
157
|
}
|
|
112
158
|
}
|
|
113
159
|
|
|
160
|
+
async function roomMembership(roomId) {
|
|
161
|
+
const query = new URLSearchParams({ sessionID: LS.sessionID, roomId, timeout: "0" });
|
|
162
|
+
try { const result = await app.api(`/inbox?${query}`); return typeof result.member === "boolean" ? result.member : null; }
|
|
163
|
+
catch { return null; }
|
|
164
|
+
}
|
|
165
|
+
function showUnavailable() { status.dataset.error = "true"; app.setText(status, "questionsUnsupported"); status.hidden = false; }
|
|
166
|
+
function showFailed() { status.dataset.error = "true"; app.setText(status, "questionsFailed"); status.hidden = false; }
|
|
167
|
+
|
|
168
|
+
app.answerQuestionFromReply = async (roomId, questionId, text) => {
|
|
169
|
+
if (text.length > 2000) throw Object.assign(new Error(app.t("answerTooLong")), { status: 413 });
|
|
170
|
+
try {
|
|
171
|
+
const result = await app.api(`/rooms/${encodeURIComponent(roomId)}/questions/${encodeURIComponent(questionId)}/answers`, {
|
|
172
|
+
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text }),
|
|
173
|
+
});
|
|
174
|
+
applyAnswer(roomId, questionId, result);
|
|
175
|
+
return result;
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (error.status === 409 || error.status === 404) await load(roomId);
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
114
182
|
async function answer(roomId, questionId, text, button) {
|
|
115
183
|
const key = `${roomId}\0${questionId}`;
|
|
116
184
|
if (!text || submitting.has(key)) return;
|
|
185
|
+
if (text.length > 2000) { app.setText(status, "answerTooLong"); status.hidden = false; return; }
|
|
117
186
|
submitting.add(key);
|
|
118
187
|
button.disabled = true;
|
|
119
188
|
renderReply(roomId);
|
|
@@ -121,17 +190,7 @@ export function initQuestions(app) {
|
|
|
121
190
|
const result = await app.api(`/rooms/${encodeURIComponent(roomId)}/questions/${encodeURIComponent(questionId)}/answers`, {
|
|
122
191
|
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text }),
|
|
123
192
|
});
|
|
124
|
-
|
|
125
|
-
if (entry && result.answer && !entry.room.messages.some((item) => item.id === result.answer.id)) {
|
|
126
|
-
entry.room.messages.push({ ...result.answer, roomId });
|
|
127
|
-
entry.room.messages.sort((left, right) => left.createdAt - right.createdAt);
|
|
128
|
-
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
129
|
-
if (app.state.room?.id === roomId) app.renderMessages(true);
|
|
130
|
-
}
|
|
131
|
-
pending.set(roomId, (pending.get(roomId) || []).filter((item) => item.id !== result.questionID));
|
|
132
|
-
if (selected.get(roomId) === questionId) selected.delete(roomId);
|
|
133
|
-
drafts.delete(`${roomId}\0${questionId}`);
|
|
134
|
-
if (app.state.room?.id === roomId) render(roomId);
|
|
193
|
+
applyAnswer(roomId, questionId, result);
|
|
135
194
|
void load(roomId);
|
|
136
195
|
} catch (error) {
|
|
137
196
|
if (error.status === 409 || error.status === 404) {
|
|
@@ -157,6 +216,19 @@ export function initQuestions(app) {
|
|
|
157
216
|
}
|
|
158
217
|
}
|
|
159
218
|
|
|
219
|
+
function applyAnswer(roomId, questionId, result) {
|
|
220
|
+
const entry = app.state.rooms.get(roomId);
|
|
221
|
+
if (entry && result.answer && !entry.room.messages.some((item) => item.id === result.answer.id)) {
|
|
222
|
+
entry.room.messages.push({ ...result.answer, roomId }); entry.room.messages.sort((a, b) => a.createdAt - b.createdAt);
|
|
223
|
+
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
224
|
+
if (app.state.room?.id === roomId) app.renderMessages(true);
|
|
225
|
+
}
|
|
226
|
+
pending.set(roomId, (pending.get(roomId) || []).filter((item) => item.id !== (result.questionID || questionId)));
|
|
227
|
+
if (selected.get(roomId) === questionId) selected.delete(roomId);
|
|
228
|
+
drafts.delete(`${roomId}\0${questionId}`);
|
|
229
|
+
if (app.state.room?.id === roomId) render(roomId);
|
|
230
|
+
}
|
|
231
|
+
|
|
160
232
|
trigger.addEventListener("click", () => {
|
|
161
233
|
const open = panel.hidden;
|
|
162
234
|
app.closePanels();
|
|
@@ -170,11 +242,11 @@ export function initQuestions(app) {
|
|
|
170
242
|
$("#btnRefreshQuestions").addEventListener("click", () => void load());
|
|
171
243
|
list.addEventListener("click", (event) => {
|
|
172
244
|
event.stopPropagation();
|
|
173
|
-
const
|
|
174
|
-
if (!button || !app.state.room) return;
|
|
175
|
-
selected.set(app.state.room.id,
|
|
245
|
+
const card = event.target.closest(".question-item[data-question-id]"), select = event.target.closest(".question-select");
|
|
246
|
+
if (!card || (!select && event.target.closest("a, button, input, textarea, select, [contenteditable=true]")) || !app.state.room) return;
|
|
247
|
+
selected.set(app.state.room.id, card.dataset.questionId);
|
|
176
248
|
render(app.state.room.id);
|
|
177
|
-
$("#questionReply
|
|
249
|
+
$("#questionReply [contenteditable]")?.focus();
|
|
178
250
|
});
|
|
179
251
|
|
|
180
252
|
const closePanels = app.closePanels;
|
|
@@ -200,5 +272,5 @@ export function initQuestions(app) {
|
|
|
200
272
|
applyLocale();
|
|
201
273
|
if (app.state.room) render(app.state.room.id);
|
|
202
274
|
};
|
|
203
|
-
setInterval(() => { if (app.state.room) void load(); }, 5000);
|
|
275
|
+
setInterval(() => { if (app.state.room && !panel.hidden) void load(); }, 5000);
|
|
204
276
|
}
|
|
@@ -81,7 +81,6 @@ export function initReceipts(app) {
|
|
|
81
81
|
const readers = readersFor(message);
|
|
82
82
|
$("#readerHeading").textContent = app.t("readerPanelTitle");
|
|
83
83
|
$("#readerCount").textContent = readerStatus(message, readers);
|
|
84
|
-
$("#readerExcerpt").textContent = message.text;
|
|
85
84
|
const list = $("#readerList"); list.textContent = "";
|
|
86
85
|
const members = app.state.memberSessions.get(app.state.room.id) || [];
|
|
87
86
|
for (const reader of readers) {
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { LS } from "./state.js";
|
|
2
|
+
|
|
3
|
+
export function initReminders(app) {
|
|
4
|
+
const $ = app.$, panel = $("#reminderPanel"), trigger = $("#btnReminders"), list = $("#reminderList");
|
|
5
|
+
let reminders = [], generation = 0, roomGeneration = 0, activeRoomId;
|
|
6
|
+
const drafts = new Map();
|
|
7
|
+
const roomId = () => app.state.room?.id;
|
|
8
|
+
const status = (text) => { $("#reminderStatus").textContent = text; };
|
|
9
|
+
const current = (id, context) => roomId() === id && roomGeneration === context;
|
|
10
|
+
const invalidateLoads = () => { generation++; };
|
|
11
|
+
const errorText = (error) => error?.message || app.t("requestFailed", { status: error?.status || "?" });
|
|
12
|
+
function formDraft() {
|
|
13
|
+
return { type: $("#reminderType").value, at: $("#reminderAt").value, cron: $("#reminderCron").value, timezone: $("#reminderTimezone").value, text: $("#reminderText").value };
|
|
14
|
+
}
|
|
15
|
+
function restoreDraft(draft) {
|
|
16
|
+
$("#reminderType").value = draft?.type || "once"; $("#reminderAt").value = draft?.at || "";
|
|
17
|
+
$("#reminderCron").value = draft?.cron || ""; $("#reminderTimezone").value = draft?.timezone || "";
|
|
18
|
+
$("#reminderText").value = draft?.text || ""; $("#reminderType").dispatchEvent(new Event("change"));
|
|
19
|
+
}
|
|
20
|
+
function formatTime(value, timezone) {
|
|
21
|
+
const effectiveZone = timezone || "UTC";
|
|
22
|
+
const formatted = new Intl.DateTimeFormat(undefined, { timeZone: effectiveZone, dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
|
|
23
|
+
return `${formatted} · ${effectiveZone}`;
|
|
24
|
+
}
|
|
25
|
+
function render() {
|
|
26
|
+
list.textContent = "";
|
|
27
|
+
if (!reminders.length) { status(app.t("reminderEmpty")); return; }
|
|
28
|
+
status("");
|
|
29
|
+
for (const reminder of reminders) {
|
|
30
|
+
const row = document.createElement("li"), text = document.createElement("p"), detail = document.createElement("p");
|
|
31
|
+
text.textContent = reminder.text; detail.className = "hint";
|
|
32
|
+
const timezone = reminder.schedule.timezone;
|
|
33
|
+
const schedule = reminder.schedule.type === "once" ? formatTime(reminder.schedule.at, timezone) : `${reminder.schedule.expression} · ${timezone}`;
|
|
34
|
+
detail.textContent = `${schedule}${reminder.paused ? ` · ${app.t("reminderPaused")}` : reminder.nextRunAt ? ` · ${app.t("reminderNext", { time: formatTime(reminder.nextRunAt, timezone) })}` : ""}`;
|
|
35
|
+
const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "btn ghost small"; toggle.textContent = app.t(reminder.paused ? "reminderResume" : "reminderPause");
|
|
36
|
+
toggle.addEventListener("click", () => void update(reminder, !reminder.paused));
|
|
37
|
+
const remove = document.createElement("button"); remove.type = "button"; remove.className = "btn ghost small danger-text"; remove.textContent = app.t("reminderDelete");
|
|
38
|
+
remove.addEventListener("click", () => { if (confirm(app.t("reminderDeleteConfirm"))) void erase(reminder); });
|
|
39
|
+
row.append(text, detail, toggle, remove); list.append(row);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function load(id = roomId()) {
|
|
43
|
+
if (!id) return;
|
|
44
|
+
const request = ++generation, context = roomGeneration; status(app.t("reminderLoading"));
|
|
45
|
+
try {
|
|
46
|
+
const query = new URLSearchParams({ sessionID: LS.sessionID });
|
|
47
|
+
const result = await app.api(`/rooms/${encodeURIComponent(id)}/reminders?${query}`);
|
|
48
|
+
if (!current(id, context) || generation !== request) return;
|
|
49
|
+
reminders = Array.isArray(result.reminders) ? result.reminders : []; render();
|
|
50
|
+
} catch (error) { if (current(id, context) && generation === request) status(errorText(error)); }
|
|
51
|
+
}
|
|
52
|
+
function validCron(expression) {
|
|
53
|
+
const fields = expression.trim().split(/\s+/);
|
|
54
|
+
return fields.length === 5 && fields.every((field) => /^[0-9*/?,\-]+$/.test(field));
|
|
55
|
+
}
|
|
56
|
+
async function update(reminder, paused) {
|
|
57
|
+
const id = roomId(), context = roomGeneration;
|
|
58
|
+
try {
|
|
59
|
+
await app.api(`/rooms/${encodeURIComponent(id)}/reminders/${encodeURIComponent(reminder.id)}`, { method: "PATCH", body: JSON.stringify({ sessionID: LS.sessionID, paused }) });
|
|
60
|
+
if (current(id, context)) { invalidateLoads(); reminders = reminders.map((item) => item.id === reminder.id ? { ...item, paused } : item); render(); status(app.t("reminderUpdated")); await load(id); }
|
|
61
|
+
} catch (error) { if (current(id, context)) { invalidateLoads(); status(errorText(error)); } }
|
|
62
|
+
}
|
|
63
|
+
async function erase(reminder) {
|
|
64
|
+
const id = roomId(), context = roomGeneration;
|
|
65
|
+
try {
|
|
66
|
+
await app.api(`/rooms/${encodeURIComponent(id)}/reminders/${encodeURIComponent(reminder.id)}`, { method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }) });
|
|
67
|
+
if (current(id, context)) { invalidateLoads(); reminders = reminders.filter((entry) => entry.id !== reminder.id); render(); status(app.t("reminderDeleted")); }
|
|
68
|
+
} catch (error) { if (current(id, context)) { invalidateLoads(); status(errorText(error)); } }
|
|
69
|
+
}
|
|
70
|
+
const type = $("#reminderType"), date = $("#reminderAt"), cron = $("#reminderCron");
|
|
71
|
+
type.addEventListener("change", () => {
|
|
72
|
+
const once = type.value === "once";
|
|
73
|
+
$("#reminderOnceField").hidden = !once; $("#reminderCronFields").hidden = once;
|
|
74
|
+
date.required = once; cron.required = !once;
|
|
75
|
+
});
|
|
76
|
+
$("#reminderForm").addEventListener("submit", async (event) => {
|
|
77
|
+
event.preventDefault();
|
|
78
|
+
const id = roomId(), context = roomGeneration, zone = $("#reminderTimezone").value.trim(), text = $("#reminderText").value.trim();
|
|
79
|
+
const schedule = type.value === "once"
|
|
80
|
+
? { type: "once", at: `${date.value}:00`, ...(zone ? { timezone: zone } : {}) }
|
|
81
|
+
: { type: "cron", expression: cron.value.trim(), ...(zone ? { timezone: zone } : {}) };
|
|
82
|
+
if (!id || !text || text.length > 1000 || type.value === "once" && !date.value || type.value === "cron" && !validCron(schedule.expression)) return status(app.t("reminderInvalid"));
|
|
83
|
+
try {
|
|
84
|
+
const result = await app.api(`/rooms/${encodeURIComponent(id)}/reminders`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, schedule, text }) });
|
|
85
|
+
if (current(id, context)) { invalidateLoads(); reminders = [...reminders.filter((item) => item.id !== result.reminder.id), result.reminder]; render(); status(app.t("reminderCreated")); }
|
|
86
|
+
} catch (error) { if (current(id, context)) { invalidateLoads(); status(errorText(error)); } }
|
|
87
|
+
});
|
|
88
|
+
$("#btnRefreshReminders").addEventListener("click", () => void load());
|
|
89
|
+
trigger.addEventListener("click", () => {
|
|
90
|
+
const open = panel.hidden; app.closePanels(); panel.hidden = !open; trigger.setAttribute("aria-expanded", String(open));
|
|
91
|
+
if (open) { void load(); $("#reminderHeading").focus(); }
|
|
92
|
+
});
|
|
93
|
+
document.addEventListener("keydown", (event) => { if (event.key === "Escape" && !panel.hidden) { app.closePanels(); trigger.focus(); } });
|
|
94
|
+
const close = app.closePanels;
|
|
95
|
+
app.closePanels = () => { close(); panel.hidden = true; trigger.setAttribute("aria-expanded", "false"); };
|
|
96
|
+
document.addEventListener("chat-room-activated", (event) => {
|
|
97
|
+
if (activeRoomId) drafts.set(activeRoomId, formDraft());
|
|
98
|
+
activeRoomId = event.detail; restoreDraft(drafts.get(activeRoomId));
|
|
99
|
+
roomGeneration++; generation++; reminders = []; render(); void load(activeRoomId);
|
|
100
|
+
});
|
|
101
|
+
}
|