@alexsun-top/opencode-chat-room 0.5.0 → 0.5.1
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 +14 -0
- package/README.md +8 -0
- package/README.zh-CN.md +8 -0
- package/docs/administrator-rooms.md +51 -0
- package/package.json +8 -1
- package/plugin.ts +10 -8
- 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 +45 -43
- package/server/assets/chat/admin.js +196 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/events.js +27 -5
- package/server/assets/chat/index.js +4 -0
- package/server/assets/chat/markdown.js +1 -12
- package/server/assets/chat/members.js +1 -1
- package/server/assets/chat/messages.js +32 -6
- package/server/assets/chat/rooms.js +21 -4
- package/server/assets/chat/state.js +43 -11
- package/server/assets/conversation.css +82 -37
- package/server/assets/responsive.css +74 -25
- package/server/chat-server.ts +2 -4
- package/server/chat.html +63 -29
- package/server/newrooms.ts +27 -10
- package/server/resource-routes.ts +3 -0
- package/server/wake.ts +6 -13
- package/skills/chatroom/SKILL.md +12 -0
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/center-client.ts +1 -1
- package/src/center-inbox.ts +2 -0
- package/src/sqlite-state.ts +46 -18
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +13 -3
- package/src/v2-plugin.ts +13 -2
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { LS } from "./state.js";
|
|
2
|
+
|
|
3
|
+
const MAX_PARALLEL_UPLOADS = 2;
|
|
4
|
+
const TEXT_LIMIT = 2000;
|
|
5
|
+
const previewTypes = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp"]);
|
|
6
|
+
|
|
7
|
+
export function initAttachments(app) {
|
|
8
|
+
const $ = app.$, input = $("#msgInput"), list = $("#attachmentList"), tray = $("#attachmentTray"), picker = $("#attachmentPicker");
|
|
9
|
+
const drafts = new Map();
|
|
10
|
+
const statuses = new Map();
|
|
11
|
+
app.state.sendingRooms ||= new Set();
|
|
12
|
+
let limit = null, configRequest = null, activeUploads = 0;
|
|
13
|
+
const roomId = () => app.state.room?.id || "";
|
|
14
|
+
const filesFor = (id) => drafts.get(id) || [];
|
|
15
|
+
const markers = (items) => items.filter((item) => item.resource).map((item) => `[[resource:${item.resource.id}]]`);
|
|
16
|
+
const textFor = (id, caption) => {
|
|
17
|
+
const parts = [String(caption || "").trim(), ...markers(filesFor(id))].filter(Boolean);
|
|
18
|
+
return { text: parts.join("\n\n"), ids: filesFor(id).filter((item) => item.resource).map((item) => item.resource.id) };
|
|
19
|
+
};
|
|
20
|
+
function formatSize(size) {
|
|
21
|
+
if (size < 1024) return `${size} B`;
|
|
22
|
+
const units = ["KiB", "MiB", "GiB"];
|
|
23
|
+
let value = size / 1024, index = 0;
|
|
24
|
+
while (value >= 1024 && index < units.length - 1) { value /= 1024; index++; }
|
|
25
|
+
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[index]}`;
|
|
26
|
+
}
|
|
27
|
+
function preserveLayout(change) {
|
|
28
|
+
const thread = $("#thread"), atBottom = Boolean(roomId() && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
|
|
29
|
+
if (atBottom) { change(); thread.scrollTop = thread.scrollHeight; }
|
|
30
|
+
else if (roomId() && app.preserveReadingLayout) void app.preserveReadingLayout(change).catch(() => {});
|
|
31
|
+
else change();
|
|
32
|
+
}
|
|
33
|
+
function setStatus(key = "", error = false, id = roomId(), values = {}) {
|
|
34
|
+
if (id) statuses.set(id, { key, error, values });
|
|
35
|
+
if (id === roomId()) preserveLayout(() => {
|
|
36
|
+
const node = $("#attachmentStatus"); node.textContent = key ? app.t(key, values) : ""; node.classList.toggle("danger-text", error); if (key) tray.hidden = false;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function prepareMessage(id, caption) {
|
|
40
|
+
const items = filesFor(id), composed = textFor(id, caption);
|
|
41
|
+
return { ...composed, ready: Boolean(composed.text) && composed.text.length <= TEXT_LIMIT && items.every((item) => item.status === "uploaded") };
|
|
42
|
+
}
|
|
43
|
+
app.prepareMessage = prepareMessage;
|
|
44
|
+
const baseDraftCount = app.updateDraftCount;
|
|
45
|
+
app.updateDraftCount = () => {
|
|
46
|
+
if (!roomId()) { $("#draftCount").classList.remove("over-limit"); return baseDraftCount(); }
|
|
47
|
+
const count = textFor(roomId(), input.value).text.length;
|
|
48
|
+
app.setText($("#draftCount"), "messageCount", { count });
|
|
49
|
+
$("#draftCount").classList.toggle("over-limit", count > TEXT_LIMIT);
|
|
50
|
+
};
|
|
51
|
+
app.updateSendState = () => {
|
|
52
|
+
const id = roomId(), message = id && prepareMessage(id, input.value);
|
|
53
|
+
$("#btnSend").disabled = !id || !message?.ready || app.state.sendingRooms.has(id);
|
|
54
|
+
};
|
|
55
|
+
app.completeAttachments = (id, resourceIDs) => {
|
|
56
|
+
const used = new Set(resourceIDs), items = filesFor(id), removed = items.filter((item) => used.has(item.resource?.id));
|
|
57
|
+
for (const item of removed) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
58
|
+
const remaining = items.filter((item) => !used.has(item.resource?.id));
|
|
59
|
+
if (remaining.length) drafts.set(id, remaining); else { drafts.delete(id); statuses.delete(id); }
|
|
60
|
+
if (roomId() === id) render();
|
|
61
|
+
};
|
|
62
|
+
app.completeAttachmentsFromText = (id, text) => app.completeAttachments(id, [...String(text).matchAll(/\[\[resource:([\da-f-]{36})\]\]/gi)].map((match) => match[1]));
|
|
63
|
+
const applyLocale = app.applyLocale;
|
|
64
|
+
app.applyLocale = () => { applyLocale(); updateLocale(); };
|
|
65
|
+
function updateLocale() {
|
|
66
|
+
const id = roomId(), items = filesFor(id);
|
|
67
|
+
items.forEach((item, index) => {
|
|
68
|
+
const row = list.children[index]; if (!row) return;
|
|
69
|
+
const detail = row.querySelector(".attachment-detail"), progress = row.querySelector("progress");
|
|
70
|
+
detail.textContent = `${formatSize(item.file.size)} · ${item.status === "failed" ? app.t(item.errorKey, item.errorValues || {}) : item.status === "uploaded" ? app.t("uploadReady") : item.status === "uploading" ? app.t("uploadPercent", { percent: item.percent || 0 }) : app.t("uploadQueued")}`;
|
|
71
|
+
const retry = row.querySelector('[data-upload-action="retry"]'); if (retry) { retry.textContent = app.t("retryUpload"); retry.setAttribute("aria-label", retry.textContent); }
|
|
72
|
+
const remove = row.querySelector('[data-upload-action="remove"]'); if (remove) { remove.textContent = app.t("removeFile"); remove.setAttribute("aria-label", remove.textContent); }
|
|
73
|
+
progress.setAttribute("aria-label", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
74
|
+
progress.setAttribute("aria-valuetext", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
75
|
+
});
|
|
76
|
+
const status = statuses.get(id); $("#attachmentStatus").textContent = status?.key ? app.t(status.key, status.values) : "";
|
|
77
|
+
if (status?.key) tray.hidden = false;
|
|
78
|
+
}
|
|
79
|
+
function render() {
|
|
80
|
+
preserveLayout(() => {
|
|
81
|
+
const id = roomId(), items = filesFor(id), savedStatus = statuses.get(id);
|
|
82
|
+
tray.hidden = !items.length && !savedStatus?.key; $("#attachmentVolatile").hidden = !items.length;
|
|
83
|
+
$("#attachmentStatus").textContent = savedStatus?.key ? app.t(savedStatus.key, savedStatus.values) : ""; $("#attachmentStatus").classList.toggle("danger-text", Boolean(savedStatus?.error));
|
|
84
|
+
list.replaceChildren();
|
|
85
|
+
items.forEach((item, index) => { const row = renderItem(item); row.dataset.index = String(index); list.append(row); });
|
|
86
|
+
app.updateDraftCount(); app.updateSendState();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
app.renderAttachments = render;
|
|
90
|
+
function renderItem(item) {
|
|
91
|
+
const row = document.createElement("li"), preview = document.createElement("span"), info = document.createElement("div"), name = document.createElement("p"), detail = document.createElement("p"), progress = document.createElement("progress"), actions = document.createElement("div");
|
|
92
|
+
row.className = "attachment-item"; preview.className = "attachment-preview";
|
|
93
|
+
if (previewTypes.has(item.file.type)) {
|
|
94
|
+
item.previewUrl ||= URL.createObjectURL(item.file);
|
|
95
|
+
const image = document.createElement("img"); image.src = item.previewUrl; image.alt = ""; preview.append(image);
|
|
96
|
+
} else preview.textContent = item.file.name.split(".").at(-1)?.slice(0, 4).toUpperCase() || "FILE";
|
|
97
|
+
info.className = "attachment-file"; name.className = "attachment-name"; name.textContent = item.file.name;
|
|
98
|
+
detail.className = `attachment-detail${item.status === "failed" ? " attachment-over-limit" : ""}`;
|
|
99
|
+
detail.textContent = `${formatSize(item.file.size)} · ${item.status === "failed" ? app.t(item.errorKey, item.errorValues || {}) : item.status === "uploaded" ? app.t("uploadReady") : item.status === "uploading" ? app.t("uploadPercent", { percent: item.percent || 0 }) : app.t("uploadQueued")}`;
|
|
100
|
+
progress.max = item.file.size || 1; progress.value = item.loaded || 0; progress.hidden = item.status !== "uploading";
|
|
101
|
+
progress.setAttribute("aria-label", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
102
|
+
item.progressNode = progress; item.detailNode = detail;
|
|
103
|
+
info.append(name, detail, progress); actions.className = "attachment-actions";
|
|
104
|
+
if (item.status === "failed") actions.append(action("retry", app.t("retryUpload")));
|
|
105
|
+
actions.append(action("remove", app.t("removeFile"))); row.append(preview, info, actions);
|
|
106
|
+
return row;
|
|
107
|
+
}
|
|
108
|
+
function action(kind, label) {
|
|
109
|
+
const button = document.createElement("button"); button.type = "button"; button.dataset.uploadAction = kind; button.textContent = label; button.setAttribute("aria-label", label); return button;
|
|
110
|
+
}
|
|
111
|
+
function removeItem(id, item) {
|
|
112
|
+
item.cancelled = true; item.xhr?.abort();
|
|
113
|
+
if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
114
|
+
const remaining = filesFor(id).filter((entry) => entry !== item);
|
|
115
|
+
if (remaining.length) drafts.set(id, remaining); else { drafts.delete(id); statuses.delete(id); }
|
|
116
|
+
if (roomId() === id) render();
|
|
117
|
+
}
|
|
118
|
+
function clearRoom(id) {
|
|
119
|
+
for (const item of [...filesFor(id)]) removeItem(id, item);
|
|
120
|
+
drafts.delete(id); statuses.delete(id);
|
|
121
|
+
}
|
|
122
|
+
app.disposeRoomAttachments = clearRoom;
|
|
123
|
+
function getLimit(refresh = false) {
|
|
124
|
+
if (refresh) limit = null;
|
|
125
|
+
if (limit !== null) return Promise.resolve(limit);
|
|
126
|
+
if (!configRequest || refresh) {
|
|
127
|
+
const request = app.api("/resources/config").then((data) => {
|
|
128
|
+
if (!Number.isSafeInteger(data.maxFileSizeBytes) || data.maxFileSizeBytes < 1) throw new Error("Invalid upload limit");
|
|
129
|
+
if (configRequest === request) limit = data.maxFileSizeBytes;
|
|
130
|
+
return data.maxFileSizeBytes;
|
|
131
|
+
}).finally(() => { if (configRequest === request) configRequest = null; });
|
|
132
|
+
configRequest = request;
|
|
133
|
+
}
|
|
134
|
+
return configRequest;
|
|
135
|
+
}
|
|
136
|
+
function pump() {
|
|
137
|
+
while (activeUploads < MAX_PARALLEL_UPLOADS) {
|
|
138
|
+
const next = [...drafts].flatMap(([id, items]) => items.map((item) => ({ id, item }))).find(({ item }) => item.status === "queued");
|
|
139
|
+
if (!next) return;
|
|
140
|
+
activeUploads++; next.item.status = "uploading"; next.item.percent = 0;
|
|
141
|
+
if (roomId() === next.id) render();
|
|
142
|
+
void uploadItem(next.id, next.item);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function uploadItem(id, item) {
|
|
146
|
+
try {
|
|
147
|
+
let max = null;
|
|
148
|
+
try { max = await getLimit(item.refreshLimit); } catch {}
|
|
149
|
+
item.refreshLimit = false;
|
|
150
|
+
if (item.cancelled) return;
|
|
151
|
+
if (max !== null && item.file.size > max) { item.errorKey = "fileTooLarge"; item.status = "failed"; if (roomId() === id) setStatus(item.errorKey, true, id); return; }
|
|
152
|
+
item.resource = await upload(id, item);
|
|
153
|
+
if (item.cancelled) return;
|
|
154
|
+
item.status = "uploaded"; item.loaded = item.file.size; item.percent = 100;
|
|
155
|
+
if (roomId() === id && filesFor(id).every((entry) => entry.status === "uploaded")) setStatus("uploadReady");
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (item.cancelled) return;
|
|
158
|
+
if (error.status === 413) { limit = null; item.errorKey = "fileTooLarge"; }
|
|
159
|
+
else item.errorKey = "uploadFailed";
|
|
160
|
+
item.status = "failed";
|
|
161
|
+
if (roomId() === id) setStatus(item.errorKey, true, id, item.errorValues || {});
|
|
162
|
+
} finally {
|
|
163
|
+
activeUploads--;
|
|
164
|
+
if (roomId() === id) render();
|
|
165
|
+
pump();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function upload(id, item) {
|
|
169
|
+
return new Promise((resolve, reject) => {
|
|
170
|
+
const xhr = new XMLHttpRequest(); item.xhr = xhr;
|
|
171
|
+
xhr.open("POST", `/rooms/${encodeURIComponent(id)}/resources`);
|
|
172
|
+
xhr.setRequestHeader("Content-Type", "application/octet-stream");
|
|
173
|
+
xhr.setRequestHeader("X-Session-ID", LS.sessionID);
|
|
174
|
+
xhr.setRequestHeader("X-File-Name", encodeURIComponent(item.file.name));
|
|
175
|
+
if (LS.token) xhr.setRequestHeader("Authorization", `Bearer ${LS.token}`);
|
|
176
|
+
xhr.timeout = 300000;
|
|
177
|
+
xhr.upload.onprogress = (event) => {
|
|
178
|
+
item.loaded = event.loaded; item.percent = Math.min(100, event.lengthComputable ? Math.floor(event.loaded / event.total * 100) : item.file.size ? Math.floor(event.loaded / item.file.size * 100) : 100);
|
|
179
|
+
if (roomId() === id) {
|
|
180
|
+
if (item.progressNode) { item.progressNode.value = item.loaded; item.progressNode.max = item.file.size || 1; item.progressNode.setAttribute("aria-valuetext", app.t("uploadPercent", { percent: item.percent })); }
|
|
181
|
+
if (item.detailNode) item.detailNode.textContent = `${formatSize(item.file.size)} · ${app.t("uploadPercent", { percent: item.percent })}`;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
xhr.onload = () => {
|
|
185
|
+
item.xhr = null;
|
|
186
|
+
if (xhr.status !== 201) return reject(Object.assign(new Error("Upload failed"), { status: xhr.status }));
|
|
187
|
+
try {
|
|
188
|
+
const resource = JSON.parse(xhr.responseText).resource;
|
|
189
|
+
if (!/^[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i.test(resource?.id) || resource.roomID !== id) throw new Error("Invalid resource response");
|
|
190
|
+
resolve(resource);
|
|
191
|
+
} catch { reject(new Error("Invalid resource response")); }
|
|
192
|
+
};
|
|
193
|
+
xhr.onerror = () => { item.xhr = null; reject(Object.assign(new Error("Upload failed"), { network: true })); };
|
|
194
|
+
xhr.ontimeout = () => { item.xhr = null; reject(Object.assign(new Error("Upload timed out"), { timeout: true })); };
|
|
195
|
+
xhr.onabort = () => { item.xhr = null; reject(Object.assign(new Error("Upload cancelled"), { aborted: true })); };
|
|
196
|
+
xhr.send(item.file);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
function addFiles(files) {
|
|
200
|
+
const id = roomId(); if (!id) return;
|
|
201
|
+
const accepted = [...files].filter((file) => file instanceof File);
|
|
202
|
+
if (!accepted.length) return;
|
|
203
|
+
const items = filesFor(id);
|
|
204
|
+
for (const file of accepted) items.push({ file, status: "queued", loaded: 0, percent: 0, cancelled: false });
|
|
205
|
+
drafts.set(id, items); setStatus(""); render(); pump();
|
|
206
|
+
}
|
|
207
|
+
function retryItem(item) {
|
|
208
|
+
if (item.status !== "failed") return;
|
|
209
|
+
item.refreshLimit = item.errorKey === "fileTooLarge"; item.status = "queued"; item.errorKey = ""; item.errorValues = null; item.loaded = 0; item.percent = 0;
|
|
210
|
+
if (roomId()) setStatus(""); render(); pump();
|
|
211
|
+
}
|
|
212
|
+
$("#btnAddAttachments").addEventListener("click", () => picker.click());
|
|
213
|
+
picker.addEventListener("change", () => { addFiles(picker.files || []); picker.value = ""; });
|
|
214
|
+
list.addEventListener("click", (event) => {
|
|
215
|
+
const button = event.target.closest?.("[data-upload-action]"); if (!button) return;
|
|
216
|
+
const id = roomId(), index = Number(button.closest(".attachment-item")?.dataset.index), item = filesFor(id)[index];
|
|
217
|
+
if (!item) return;
|
|
218
|
+
if (button.dataset.uploadAction === "retry") { retryItem(item); $("#btnAddAttachments").focus(); }
|
|
219
|
+
else { removeItem(id, item); (list.querySelector(`[data-index="${Math.min(index, filesFor(id).length - 1)}"] [data-upload-action=remove]`) || $("#btnAddAttachments")).focus(); }
|
|
220
|
+
});
|
|
221
|
+
const chatView = $("#chatView"), overlay = $("#attachmentDropOverlay");
|
|
222
|
+
const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes("Files");
|
|
223
|
+
const showDrop = () => { chatView.classList.add("drag-over"); overlay.hidden = false; };
|
|
224
|
+
const clearDrop = () => { chatView.classList.remove("drag-over"); overlay.hidden = true; };
|
|
225
|
+
chatView.addEventListener("dragenter", (event) => { if (!hasFiles(event)) return; event.preventDefault(); showDrop(); });
|
|
226
|
+
chatView.addEventListener("dragover", (event) => { if (!hasFiles(event)) return; event.preventDefault(); event.dataTransfer.dropEffect = "copy"; showDrop(); });
|
|
227
|
+
chatView.addEventListener("dragleave", (event) => { if (hasFiles(event) && !chatView.contains(event.relatedTarget)) clearDrop(); });
|
|
228
|
+
chatView.addEventListener("drop", (event) => { if (!hasFiles(event)) return; event.preventDefault(); clearDrop(); addFiles(event.dataTransfer.files); });
|
|
229
|
+
input.addEventListener("paste", (event) => {
|
|
230
|
+
const images = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file" && item.type.startsWith("image/")).map((item) => item.getAsFile()).filter(Boolean);
|
|
231
|
+
if (!images.length) return;
|
|
232
|
+
if (!event.clipboardData.getData("text/plain")) event.preventDefault();
|
|
233
|
+
addFiles(images);
|
|
234
|
+
});
|
|
235
|
+
document.addEventListener("chat-room-activated", (event) => {
|
|
236
|
+
render(); const id = event.detail; $("#btnAddAttachments").disabled = !id;
|
|
237
|
+
void getLimit().catch(() => {});
|
|
238
|
+
});
|
|
239
|
+
render();
|
|
240
|
+
}
|
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
-
import {
|
|
2
|
+
import { copyTextToClipboard } from "./markdown.js";
|
|
3
3
|
|
|
4
4
|
export function initEvents(app) {
|
|
5
5
|
const $ = app.$;
|
|
6
|
+
app.showRestoreFailure = (message) => {
|
|
7
|
+
document.documentElement.classList.add("session-restore");
|
|
8
|
+
$("#joinView").hidden = $("#chatView").hidden = true;
|
|
9
|
+
$("#restoreView").hidden = false;
|
|
10
|
+
$("#restoreError").textContent = message;
|
|
11
|
+
$("#restoreError").hidden = false;
|
|
12
|
+
$("#btnRestoreRetry").hidden = false;
|
|
13
|
+
};
|
|
6
14
|
const roomRail = $("#roomRail"), drawerTrigger = $("#btnRoomsDrawer"), backdrop = $("#roomDrawerBackdrop");
|
|
7
15
|
const smallScreen = () => matchMedia("(max-width: 760px)").matches;
|
|
8
16
|
let readingPosition = null, resizeFrame = 0, resizeGeneration = 0, scrollGeneration = 0, resizeResetTimer = 0;
|
|
@@ -157,6 +165,16 @@ export function initEvents(app) {
|
|
|
157
165
|
$("#btnDeleteRoom").addEventListener("click", () => void app.deleteRoom());
|
|
158
166
|
$("#btnMembers").addEventListener("click", () => app.togglePanel("#memberPanel"));
|
|
159
167
|
$("#btnSettings").addEventListener("click", () => app.togglePanel("#chatSettings"));
|
|
168
|
+
$("#btnRoomOptions").addEventListener("click", () => {
|
|
169
|
+
const panel = $("#roomOptions"), open = panel.hidden;
|
|
170
|
+
app.closePanels(); panel.hidden = !open;
|
|
171
|
+
$("#btnRoomOptions").setAttribute("aria-expanded", String(open));
|
|
172
|
+
});
|
|
173
|
+
$("#btnRestoreRetry").addEventListener("click", () => {
|
|
174
|
+
$("#btnRestoreRetry").hidden = true;
|
|
175
|
+
$("#restoreError").hidden = true;
|
|
176
|
+
void app.refreshRoomList();
|
|
177
|
+
});
|
|
160
178
|
$("#btnRefreshRooms").addEventListener("click", () => void app.refreshRoomList());
|
|
161
179
|
$("#btnNewRoom").addEventListener("click", () => {
|
|
162
180
|
const form = $("#railRoomForm");
|
|
@@ -200,7 +218,13 @@ export function initEvents(app) {
|
|
|
200
218
|
});
|
|
201
219
|
const thread = $("#thread");
|
|
202
220
|
const markScrollIntent = () => { scrollGeneration++; app.state.userScrollIntentUntil = performance.now() + 700; };
|
|
203
|
-
|
|
221
|
+
// Stop wheel overscroll at the ends. Without this, some layouts let the
|
|
222
|
+
// document absorb the leftover delta and the view jumps a few pixels.
|
|
223
|
+
thread.addEventListener("wheel", (event) => {
|
|
224
|
+
markScrollIntent();
|
|
225
|
+
const gap = thread.scrollHeight - thread.clientHeight - thread.scrollTop;
|
|
226
|
+
if (event.deltaY < 0 && thread.scrollTop <= 0 || event.deltaY > 0 && gap <= 2) event.preventDefault();
|
|
227
|
+
}, { passive: false });
|
|
204
228
|
thread.addEventListener("touchmove", markScrollIntent, { passive: true });
|
|
205
229
|
thread.addEventListener("pointerdown", (event) => {
|
|
206
230
|
if (event.clientX >= thread.getBoundingClientRect().right - 18) markScrollIntent();
|
|
@@ -225,8 +249,6 @@ export function initEvents(app) {
|
|
|
225
249
|
app.queueReceiptRefresh();
|
|
226
250
|
});
|
|
227
251
|
$("#msgList").addEventListener("click", (event) => {
|
|
228
|
-
const button = event.target.closest("[data-copy-code]");
|
|
229
|
-
if (button) void copyCodeFromButton(button, app);
|
|
230
252
|
const messageButton = event.target.closest("[data-copy-message]");
|
|
231
253
|
if (messageButton) void copyTextToClipboard(messageButton._copyText).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
|
|
232
254
|
});
|
|
@@ -273,7 +295,7 @@ export function initEvents(app) {
|
|
|
273
295
|
$("#inToken").value = LS.token;
|
|
274
296
|
$("#inTokenChat").value = LS.token;
|
|
275
297
|
void app.refreshRoomList();
|
|
276
|
-
$("#inRoomId").focus();
|
|
298
|
+
if (!$("#joinView").hidden) $("#inRoomId").focus();
|
|
277
299
|
}
|
|
278
300
|
|
|
279
301
|
async function loadAnchorHistory(roomId, entry, messageId, app, readTs = 0, signal) {
|
|
@@ -7,12 +7,16 @@ import { initEvents } from "./events.js";
|
|
|
7
7
|
import { initQuestions } from "./questions.js";
|
|
8
8
|
import { initReceipts } from "./receipts.js";
|
|
9
9
|
import { initAnnouncements } from "./announcements.js";
|
|
10
|
+
import { initAdmin } from "./admin.js";
|
|
11
|
+
import { initAttachments } from "./attachments.js";
|
|
10
12
|
|
|
11
13
|
initMentions(app);
|
|
12
14
|
initMessages(app);
|
|
15
|
+
initAttachments(app);
|
|
13
16
|
initReceipts(app);
|
|
14
17
|
initMembers(app);
|
|
15
18
|
initRooms(app);
|
|
16
19
|
initQuestions(app);
|
|
17
20
|
initEvents(app);
|
|
18
21
|
initAnnouncements(app);
|
|
22
|
+
initAdmin(app);
|
|
@@ -37,7 +37,6 @@ export function renderMarkdown(root, text, app) {
|
|
|
37
37
|
link.rel = "noopener noreferrer";
|
|
38
38
|
});
|
|
39
39
|
fragment.querySelectorAll('input[type="checkbox"]').forEach((input) => { input.disabled = true; });
|
|
40
|
-
fragment.querySelectorAll("pre").forEach((pre) => addCodeCopy(pre, app));
|
|
41
40
|
root.appendChild(fragment);
|
|
42
41
|
for (let i = 0; i < diagramNodes.length; i++) {
|
|
43
42
|
const source = diagrams.get(`CHATDIAGRAM${nonce}${i}END`);
|
|
@@ -92,14 +91,9 @@ function showDiagramFallback(node, source, app, loading) {
|
|
|
92
91
|
node.append(status);
|
|
93
92
|
if (!loading) {
|
|
94
93
|
const pre = document.createElement("pre"), code = document.createElement("code");
|
|
95
|
-
code.textContent = source; pre.append(code);
|
|
94
|
+
code.textContent = source; pre.append(code); node.append(pre);
|
|
96
95
|
}
|
|
97
96
|
}
|
|
98
|
-
function addCodeCopy(pre, app) {
|
|
99
|
-
const button = document.createElement("button");
|
|
100
|
-
button.type = "button"; button.className = "code-copy"; button.dataset.copyCode = "";
|
|
101
|
-
button.dataset.i18n = "copyCode"; button.textContent = app.t("copyCode"); pre.append(button);
|
|
102
|
-
}
|
|
103
97
|
|
|
104
98
|
function replaceResourceMarkers(fragment, app) {
|
|
105
99
|
const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_TEXT), nodes = [], cards = [], roomId = app.state.room?.id;
|
|
@@ -259,11 +253,6 @@ function replaceMentionTokens(fragment, mentions, app) {
|
|
|
259
253
|
}
|
|
260
254
|
}
|
|
261
255
|
|
|
262
|
-
export function copyCodeFromButton(button, app) {
|
|
263
|
-
const code = button.parentElement.querySelector("code")?.textContent || "";
|
|
264
|
-
return copyTextToClipboard(code).then((copied) => copied ? app.flash(button, "copiedCode") : app.showSendError("copyCodeFailed"));
|
|
265
|
-
}
|
|
266
|
-
|
|
267
256
|
export async function copyTextToClipboard(text) {
|
|
268
257
|
try {
|
|
269
258
|
if (navigator.clipboard?.writeText) {
|
|
@@ -12,7 +12,7 @@ export function initMembers(app) {
|
|
|
12
12
|
|
|
13
13
|
app.renderMembers = () => {
|
|
14
14
|
const people = app.state.room?.participants || [];
|
|
15
|
-
app.setText($("#btnMembers"), "membersCount", { count: people.length });
|
|
15
|
+
app.setText($("#btnMembers .action-label"), "membersCount", { count: people.length });
|
|
16
16
|
const list = $("#memberList");
|
|
17
17
|
list.textContent = "";
|
|
18
18
|
for (const person of people) {
|
|
@@ -8,12 +8,14 @@ export function initMessages(app) {
|
|
|
8
8
|
let pollDelay = 2000;
|
|
9
9
|
|
|
10
10
|
app.autoGrow = (textarea) => {
|
|
11
|
+
const thread = $("#thread"), atBottom = Boolean(app.state.room && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
|
|
11
12
|
textarea.style.overflowY = "hidden";
|
|
12
13
|
const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
|
|
13
14
|
const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
|
|
14
15
|
const border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
|
|
15
16
|
if (!textarea.value) {
|
|
16
17
|
textarea.style.height = `${Math.max(line + padding + border, parseFloat(style.minHeight) || 0)}px`;
|
|
18
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
17
19
|
return;
|
|
18
20
|
}
|
|
19
21
|
textarea.style.height = "auto";
|
|
@@ -21,6 +23,7 @@ export function initMessages(app) {
|
|
|
21
23
|
const overflow = textarea.scrollHeight > limit + 1;
|
|
22
24
|
textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
|
|
23
25
|
textarea.style.overflowY = overflow ? "auto" : "hidden";
|
|
26
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
24
27
|
};
|
|
25
28
|
app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
|
|
26
29
|
app.updateDraftCount = () => app.setText($("#draftCount"), "messageCount", { count: $("#msgInput").value.length });
|
|
@@ -61,6 +64,7 @@ export function initMessages(app) {
|
|
|
61
64
|
const updated = await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, {
|
|
62
65
|
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion) }),
|
|
63
66
|
});
|
|
67
|
+
app.completeAttachmentsFromText?.(roomId, item.text);
|
|
64
68
|
const entry = app.state.rooms.get(roomId);
|
|
65
69
|
if (entry) {
|
|
66
70
|
entry.room = mergeRoom(entry.room, updated);
|
|
@@ -167,8 +171,21 @@ export function initMessages(app) {
|
|
|
167
171
|
copy.type = "button";
|
|
168
172
|
copy.className = "message-copy";
|
|
169
173
|
copy.dataset.copyMessage = "";
|
|
170
|
-
copy.
|
|
171
|
-
copy.
|
|
174
|
+
copy.setAttribute("aria-label", app.t("copyMessage"));
|
|
175
|
+
copy.dataset.i18nAriaLabel = "copyMessage";
|
|
176
|
+
copy.dataset.i18nTitle = "copyMessage";
|
|
177
|
+
copy.title = app.t("copyMessage");
|
|
178
|
+
const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
|
179
|
+
icon.classList.add("message-copy-icon"); icon.setAttribute("viewBox", "0 0 24 24"); icon.setAttribute("aria-hidden", "true");
|
|
180
|
+
const back = document.createElementNS("http://www.w3.org/2000/svg", "rect");
|
|
181
|
+
back.setAttribute("x", "4"); back.setAttribute("y", "3"); back.setAttribute("width", "13"); back.setAttribute("height", "15"); back.setAttribute("rx", "2");
|
|
182
|
+
const front = document.createElementNS("http://www.w3.org/2000/svg", "rect");
|
|
183
|
+
front.setAttribute("x", "8"); front.setAttribute("y", "7"); front.setAttribute("width", "12"); front.setAttribute("height", "14"); front.setAttribute("rx", "2");
|
|
184
|
+
icon.append(back, front);
|
|
185
|
+
const feedback = document.createElement("span");
|
|
186
|
+
feedback.className = "message-copy-feedback"; feedback.dataset.flashOutput = ""; feedback.dataset.i18n = "copyMessage";
|
|
187
|
+
feedback.hidden = true; feedback.setAttribute("role", "status"); feedback.setAttribute("aria-live", "polite"); feedback.textContent = app.t("copyMessage");
|
|
188
|
+
copy.append(icon, feedback);
|
|
172
189
|
copy._copyText = String(message.text ?? "");
|
|
173
190
|
row.append(copy);
|
|
174
191
|
if (live) row.classList.add("in");
|
|
@@ -266,20 +283,25 @@ export function initMessages(app) {
|
|
|
266
283
|
};
|
|
267
284
|
|
|
268
285
|
app.send = async () => {
|
|
269
|
-
const input = $("#msgInput"),
|
|
270
|
-
if (!
|
|
286
|
+
const input = $("#msgInput"), room = app.state.room, isQuestion = Boolean(app.isQuestionSending?.());
|
|
287
|
+
if (!room || app.state.sendingRooms?.has(room.id)) return;
|
|
288
|
+
const message = app.prepareMessage?.(room.id, input.value) || { text: input.value.trim(), ids: [], ready: Boolean(input.value.trim()) };
|
|
289
|
+
if (!message.ready) return;
|
|
290
|
+
const text = message.text;
|
|
271
291
|
const revision = app.state.draftRevision.get(room.id) || 0;
|
|
292
|
+
app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
|
|
272
293
|
app.closeMention();
|
|
273
294
|
input.value = "";
|
|
274
295
|
app.clearDraft(room.id);
|
|
275
296
|
app.autoGrow(input);
|
|
276
|
-
app.updateSendState();
|
|
277
297
|
app.updateDraftCount();
|
|
298
|
+
app.updateSendState();
|
|
278
299
|
app.hideSendError();
|
|
279
300
|
try {
|
|
280
301
|
const updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
|
|
281
302
|
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, isQuestion }),
|
|
282
303
|
});
|
|
304
|
+
app.completeAttachments?.(room.id, message.ids);
|
|
283
305
|
if (app.state.room?.id !== room.id) return;
|
|
284
306
|
app.state.room = updated;
|
|
285
307
|
const entry = app.state.rooms.get(room.id);
|
|
@@ -300,6 +322,7 @@ export function initMessages(app) {
|
|
|
300
322
|
const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
|
|
301
323
|
const failures = app.state.failedMessages.get(room.id) || [];
|
|
302
324
|
app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, isQuestion }]);
|
|
325
|
+
app.completeAttachments?.(room.id, message.ids);
|
|
303
326
|
app.renderFailedMessages();
|
|
304
327
|
if (app.state.room?.id !== room.id) return;
|
|
305
328
|
if (unchanged) app.clearDraft(room.id);
|
|
@@ -308,6 +331,9 @@ export function initMessages(app) {
|
|
|
308
331
|
app.updateDraftCount();
|
|
309
332
|
if (error.status === 401) { app.openChatSettings(); app.showSendError("sendAuth"); }
|
|
310
333
|
else app.showSendError(error.network ? "sendNetwork" : "sendFailed", { message: error.message });
|
|
334
|
+
} finally {
|
|
335
|
+
app.state.sendingRooms.delete(room.id);
|
|
336
|
+
if (app.state.room?.id === room.id) app.updateSendState();
|
|
311
337
|
}
|
|
312
338
|
};
|
|
313
339
|
|
|
@@ -364,7 +390,7 @@ export function initMessages(app) {
|
|
|
364
390
|
if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
|
|
365
391
|
added++;
|
|
366
392
|
}
|
|
367
|
-
if (entry && item.createdAt > entry.readTs && !
|
|
393
|
+
if (entry && item.createdAt > entry.readTs && !isOwnMessage(item, app) && !entry.unreadIds.has(item.id)) {
|
|
368
394
|
entry.unreadIds.set(item.id, item); unreadChanged = true;
|
|
369
395
|
}
|
|
370
396
|
}
|
|
@@ -5,15 +5,19 @@ export function initRooms(app) {
|
|
|
5
5
|
const $ = app.$;
|
|
6
6
|
|
|
7
7
|
app.showJoin = (refresh = true) => {
|
|
8
|
+
document.documentElement.classList.remove("session-restore");
|
|
8
9
|
if (!$("#inName").value) $("#inName").value = LS.name;
|
|
9
10
|
$("#chatView").hidden = true;
|
|
11
|
+
$("#restoreView").hidden = true;
|
|
10
12
|
$("#joinView").hidden = false;
|
|
11
13
|
app.updateTitle();
|
|
12
14
|
if (refresh) void app.refreshRoomList();
|
|
13
15
|
$("#inRoomId").focus();
|
|
14
16
|
};
|
|
15
17
|
app.showChat = () => {
|
|
18
|
+
document.documentElement.classList.remove("session-restore");
|
|
16
19
|
$("#joinView").hidden = true;
|
|
20
|
+
$("#restoreView").hidden = true;
|
|
17
21
|
$("#chatView").hidden = false;
|
|
18
22
|
};
|
|
19
23
|
app.renderHead = () => {
|
|
@@ -21,7 +25,7 @@ export function initRooms(app) {
|
|
|
21
25
|
$("#roomIdShort").textContent = app.state.room.id.slice(0, 8);
|
|
22
26
|
$("#btnCopyId").title = app.t("copyRoomIdTitle", { id: app.state.room.id });
|
|
23
27
|
$("#btnCopyId").setAttribute("aria-label", app.t("copyRoomId"));
|
|
24
|
-
|
|
28
|
+
$("#railIdentity").textContent = app.state.myName;
|
|
25
29
|
$("#profileAvatar").textContent = Array.from(app.state.myName.trim())[0]?.toLocaleUpperCase() || "?";
|
|
26
30
|
app.updateTitle();
|
|
27
31
|
};
|
|
@@ -166,6 +170,7 @@ export function initRooms(app) {
|
|
|
166
170
|
app.removeJoinedRoom = async (roomId, { leaveServer = false, reason = false } = {}) => {
|
|
167
171
|
const active = app.state.room?.id === roomId;
|
|
168
172
|
const entry = app.state.rooms.get(roomId);
|
|
173
|
+
app.disposeRoomAttachments?.(roomId);
|
|
169
174
|
if (active) {
|
|
170
175
|
app.state.navigationGeneration++;
|
|
171
176
|
app.saveDraft(roomId, $("#msgInput").value);
|
|
@@ -235,7 +240,11 @@ export function initRooms(app) {
|
|
|
235
240
|
empty.hidden = rooms.length > 0;
|
|
236
241
|
chatEmpty.hidden = rooms.length > 0;
|
|
237
242
|
} catch (error) {
|
|
238
|
-
if (error.status === 401)
|
|
243
|
+
if (error.status === 401) {
|
|
244
|
+
if (!app.state.room && !app.state.restored) { app.showJoin(false); app.openTokenBox(); app.showJoinError("authRetry"); }
|
|
245
|
+
else app.state.room ? app.openChatSettings() : app.openTokenBox();
|
|
246
|
+
}
|
|
247
|
+
else if (!app.state.restored && !app.state.room) app.showRestoreFailure(app.t("networkRetry"));
|
|
239
248
|
else {
|
|
240
249
|
app.setText(empty, "roomListError");
|
|
241
250
|
app.setText(chatEmpty, "roomListError");
|
|
@@ -262,6 +271,7 @@ export function initRooms(app) {
|
|
|
262
271
|
const candidates = [...new Set([activeId, ...rooms.filter((room) => room.joined).map((room) => room.id), ...app.state.joinedIds, ...directIds].filter(Boolean))];
|
|
263
272
|
const valid = new Set();
|
|
264
273
|
const unresolved = new Set();
|
|
274
|
+
let authFailed = false;
|
|
265
275
|
await bounded(candidates, 3, async (roomId) => {
|
|
266
276
|
try {
|
|
267
277
|
const room = rooms.find((item) => item.id === roomId) || await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
@@ -273,6 +283,7 @@ export function initRooms(app) {
|
|
|
273
283
|
} catch (error) {
|
|
274
284
|
if (error.status !== 404) {
|
|
275
285
|
unresolved.add(roomId);
|
|
286
|
+
if (error.status === 401) authFailed = true;
|
|
276
287
|
if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
|
|
277
288
|
}
|
|
278
289
|
}
|
|
@@ -281,12 +292,16 @@ export function initRooms(app) {
|
|
|
281
292
|
app.state.restorePending = unresolved;
|
|
282
293
|
app.saveJoinedIds();
|
|
283
294
|
app.state.restored = unresolved.size === 0;
|
|
295
|
+
if (authFailed) { app.showJoin(false); app.openTokenBox(); app.showJoinError("authRetry"); return; }
|
|
284
296
|
if (activeId && valid.has(activeId)) app.activateRoom(activeId);
|
|
285
|
-
else if (activeId && unresolved.has(activeId))
|
|
297
|
+
else if (activeId && unresolved.has(activeId)) {
|
|
298
|
+
app.showRestoreFailure(app.t("networkRetry"));
|
|
299
|
+
}
|
|
286
300
|
else {
|
|
287
301
|
LS.roomId = "";
|
|
288
302
|
const fallback = valid.values().next().value;
|
|
289
303
|
if (fallback) app.activateRoom(fallback);
|
|
304
|
+
else if (unresolved.size) app.showRestoreFailure(app.t("networkRetry"));
|
|
290
305
|
else app.showJoin(false);
|
|
291
306
|
}
|
|
292
307
|
app.startRoomWatcher();
|
|
@@ -361,6 +376,7 @@ export function initRooms(app) {
|
|
|
361
376
|
document.querySelectorAll(".panel").forEach((panel) => { panel.hidden = true; });
|
|
362
377
|
$("#btnMembers").setAttribute("aria-expanded", "false");
|
|
363
378
|
$("#btnSettings").setAttribute("aria-expanded", "false");
|
|
379
|
+
$("#btnRoomOptions").setAttribute("aria-expanded", "false");
|
|
364
380
|
};
|
|
365
381
|
app.togglePanel = (selector) => {
|
|
366
382
|
const panel = $(selector), wasHidden = panel.hidden;
|
|
@@ -392,12 +408,13 @@ export function initRooms(app) {
|
|
|
392
408
|
try {
|
|
393
409
|
await app.api(`/rooms/${encodeURIComponent(room.id)}`, {
|
|
394
410
|
method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }),
|
|
411
|
+
headers: LS.adminToken ? { "X-Chat-Admin-Token": LS.adminToken } : {},
|
|
395
412
|
});
|
|
396
413
|
await app.removeJoinedRoom(room.id);
|
|
397
414
|
app.clearDraft(room.id);
|
|
398
415
|
app.clearPosition(room.id);
|
|
399
416
|
app.saveFailedMessages(room.id, []);
|
|
400
|
-
} catch (error) { app.showSendError("sendFailed", { message: error.message }); }
|
|
417
|
+
} catch (error) { app.showSendError(error.status === 403 && error.message.includes("operator token required") ? "adminRoomDeleteDenied" : "sendFailed", { message: error.message }); }
|
|
401
418
|
};
|
|
402
419
|
|
|
403
420
|
app.copyRoomId = async () => {
|