@alexsun-top/opencode-chat-room 0.4.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 +29 -0
- package/README.md +38 -5
- package/README.zh-CN.md +34 -4
- package/docs/administrator-rooms.md +51 -0
- package/package.json +11 -1
- package/plugin.ts +28 -17
- 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/announcement-routes.ts +34 -0
- package/server/assets/MERMAID-LICENSE +21 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +60 -43
- package/server/assets/chat/admin.js +196 -0
- package/server/assets/chat/announcements.js +119 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/events.js +206 -10
- package/server/assets/chat/index.js +6 -0
- package/server/assets/chat/markdown.js +208 -16
- package/server/assets/chat/members.js +5 -2
- package/server/assets/chat/messages.js +85 -23
- package/server/assets/chat/receipts.js +22 -17
- package/server/assets/chat/rooms.js +32 -10
- package/server/assets/chat/state.js +88 -22
- package/server/assets/conversation.css +100 -40
- package/server/assets/mermaid-11.12.2.min.js +2811 -0
- package/server/assets/responsive.css +108 -49
- package/server/chat-server.ts +10 -11
- package/server/chat.html +85 -32
- package/server/member-routes.ts +3 -0
- package/server/newrooms.ts +29 -10
- package/server/resource-routes.ts +68 -0
- package/server/wake.ts +7 -14
- package/skills/chatroom/SKILL.md +104 -0
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/agent-receipts.ts +4 -4
- package/src/announcement-tool.ts +25 -0
- package/src/announcements.ts +16 -0
- package/src/center-client.ts +27 -1
- package/src/center-inbox.ts +11 -9
- package/src/chatroom-skill.ts +15 -0
- package/src/plugin-notifications.ts +7 -9
- package/src/resource-upload.ts +50 -0
- package/src/resources.ts +104 -0
- package/src/sqlite-state.ts +81 -12
- package/src/store.ts +1 -10
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +19 -4
- package/src/v2-plugin.ts +45 -8
|
@@ -1,33 +1,230 @@
|
|
|
1
1
|
import { createRandomId } from "./state.js";
|
|
2
2
|
|
|
3
3
|
const mentionPattern = /<at>@([^<]+)<\/at>/g;
|
|
4
|
+
const resourcePattern = /\[\[resource:([\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})\]\]/gi;
|
|
5
|
+
let mermaidReady = false;
|
|
6
|
+
const previewUrls = new Map();
|
|
7
|
+
let previewObserver;
|
|
4
8
|
|
|
5
9
|
export function renderMarkdown(root, text, app) {
|
|
6
|
-
const mentions = [];
|
|
10
|
+
const mentions = [], diagrams = new Map();
|
|
7
11
|
const nonce = createRandomId();
|
|
8
12
|
const source = String(text).replace(mentionPattern, (_, name) => {
|
|
9
13
|
const token = `CHATMENTION${nonce}${mentions.length}END`;
|
|
10
14
|
mentions.push({ token, name, literal: `<at>@${name}</at>` });
|
|
11
15
|
return token;
|
|
12
16
|
});
|
|
13
|
-
const
|
|
17
|
+
const renderer = new window.marked.Renderer(), renderCode = renderer.code.bind(renderer);
|
|
18
|
+
renderer.code = (token) => {
|
|
19
|
+
if ((token.lang || "").trim().toLowerCase().split(/\s+/)[0] !== "mermaid") return renderCode(token);
|
|
20
|
+
const key = `CHATDIAGRAM${nonce}${diagrams.size}END`;
|
|
21
|
+
const literalToken = new RegExp(`CHATMENTION${nonce}\\d+END`, "g");
|
|
22
|
+
diagrams.set(key, token.text.replace(literalToken, (value) => mentions.find((mention) => mention.token === value)?.literal || value));
|
|
23
|
+
return `<div data-chat-mermaid="${key}"></div>`;
|
|
24
|
+
};
|
|
25
|
+
const parsed = window.marked.parse(source, { gfm: true, breaks: true, async: false, renderer });
|
|
14
26
|
const fragment = window.DOMPurify.sanitize(parsed, { RETURN_DOM_FRAGMENT: true });
|
|
15
27
|
replaceMentionTokens(fragment, mentions, app);
|
|
28
|
+
const resources = replaceResourceMarkers(fragment, app);
|
|
29
|
+
const diagramNodes = [...fragment.querySelectorAll("[data-chat-mermaid]")];
|
|
30
|
+
for (const node of diagramNodes) {
|
|
31
|
+
const source = diagrams.get(node.dataset.chatMermaid);
|
|
32
|
+
node.removeAttribute("data-chat-mermaid"); node.className = "mermaid-diagram";
|
|
33
|
+
if (source !== undefined) showDiagramFallback(node, source, app, !isUnsafeDiagram(source));
|
|
34
|
+
}
|
|
16
35
|
fragment.querySelectorAll("a").forEach((link) => {
|
|
17
36
|
link.target = "_blank";
|
|
18
37
|
link.rel = "noopener noreferrer";
|
|
19
38
|
});
|
|
20
39
|
fragment.querySelectorAll('input[type="checkbox"]').forEach((input) => { input.disabled = true; });
|
|
21
|
-
fragment.querySelectorAll("pre").forEach((pre) => {
|
|
22
|
-
const button = document.createElement("button");
|
|
23
|
-
button.type = "button";
|
|
24
|
-
button.className = "code-copy";
|
|
25
|
-
button.dataset.copyCode = "";
|
|
26
|
-
button.dataset.i18n = "copyCode";
|
|
27
|
-
button.textContent = app.t("copyCode");
|
|
28
|
-
pre.appendChild(button);
|
|
29
|
-
});
|
|
30
40
|
root.appendChild(fragment);
|
|
41
|
+
for (let i = 0; i < diagramNodes.length; i++) {
|
|
42
|
+
const source = diagrams.get(`CHATDIAGRAM${nonce}${i}END`);
|
|
43
|
+
if (!isUnsafeDiagram(source)) void renderDiagram(diagramNodes[i], source, app);
|
|
44
|
+
}
|
|
45
|
+
for (const resource of resources) void loadResourceCard(resource.card, resource.roomId, app);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function initializeMermaid() {
|
|
49
|
+
if (mermaidReady) return;
|
|
50
|
+
if (!window.mermaid) await new Promise((resolve, reject) => {
|
|
51
|
+
const script = document.querySelector('script[src$="mermaid-11.12.2.min.js"]');
|
|
52
|
+
if (!script) return reject(new Error("Mermaid bundle is missing"));
|
|
53
|
+
script.addEventListener("load", resolve, { once: true });
|
|
54
|
+
script.addEventListener("error", reject, { once: true });
|
|
55
|
+
window.addEventListener("load", resolve, { once: true });
|
|
56
|
+
});
|
|
57
|
+
if (!window.mermaid) throw new Error("Mermaid bundle failed to load");
|
|
58
|
+
window.mermaid.initialize({
|
|
59
|
+
startOnLoad: false, securityLevel: "strict", htmlLabels: false,
|
|
60
|
+
theme: matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "default",
|
|
61
|
+
flowchart: { htmlLabels: false }, maxTextSize: 20000, maxEdges: 200, suppressErrorRendering: true,
|
|
62
|
+
secure: ["secure", "securityLevel", "startOnLoad", "htmlLabels", "flowchart", "theme", "themeCSS", "themeVariables", "dompurifyConfig", "maxTextSize", "maxEdges", "suppressErrorRendering"],
|
|
63
|
+
});
|
|
64
|
+
mermaidReady = true;
|
|
65
|
+
}
|
|
66
|
+
async function renderDiagram(node, source, app) {
|
|
67
|
+
if (source === undefined || isUnsafeDiagram(source)) return;
|
|
68
|
+
try {
|
|
69
|
+
await initializeMermaid();
|
|
70
|
+
const { svg } = await window.mermaid.render(`oc-chat-${createRandomId()}`, source);
|
|
71
|
+
if (!node.isConnected) return;
|
|
72
|
+
const fragment = window.DOMPurify.sanitize(svg, {
|
|
73
|
+
RETURN_DOM_FRAGMENT: true, USE_PROFILES: { svg: true, svgFilters: true },
|
|
74
|
+
FORBID_TAGS: ["foreignObject", "a", "script"], FORBID_ATTR: ["href", "xlink:href", "onclick", "onload"],
|
|
75
|
+
ALLOW_DATA_ATTR: false,
|
|
76
|
+
});
|
|
77
|
+
if (!fragment.querySelector("svg")) throw new Error("Diagram SVG was rejected");
|
|
78
|
+
const update = () => node.replaceChildren(fragment);
|
|
79
|
+
if (app.preserveReadingLayout) await app.preserveReadingLayout(update); else update();
|
|
80
|
+
} catch {
|
|
81
|
+
if (node.isConnected) showDiagramFallback(node, source, app, false);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function isUnsafeDiagram(source = "") {
|
|
85
|
+
return /%%\s*\{|^\s*---\s*(?:\r?\n)|\burl\s*\(|@import|@\s*\{[^}]*\b(?:img|image)\s*:/i.test(source);
|
|
86
|
+
}
|
|
87
|
+
function showDiagramFallback(node, source, app, loading) {
|
|
88
|
+
node.textContent = "";
|
|
89
|
+
const status = document.createElement("p"); status.className = "diagram-status";
|
|
90
|
+
status.setAttribute("role", "status"); status.textContent = app.t(loading ? "diagramLoading" : "diagramRenderFailed");
|
|
91
|
+
node.append(status);
|
|
92
|
+
if (!loading) {
|
|
93
|
+
const pre = document.createElement("pre"), code = document.createElement("code");
|
|
94
|
+
code.textContent = source; pre.append(code); node.append(pre);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function replaceResourceMarkers(fragment, app) {
|
|
99
|
+
const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_TEXT), nodes = [], cards = [], roomId = app.state.room?.id;
|
|
100
|
+
while (walker.nextNode()) nodes.push(walker.currentNode);
|
|
101
|
+
for (const node of nodes) {
|
|
102
|
+
if (node.parentElement?.closest("code, pre, a")) continue;
|
|
103
|
+
const value = node.nodeValue || "", replacement = document.createDocumentFragment();
|
|
104
|
+
let last = 0, match;
|
|
105
|
+
resourcePattern.lastIndex = 0;
|
|
106
|
+
while ((match = resourcePattern.exec(value))) {
|
|
107
|
+
replacement.append(document.createTextNode(value.slice(last, match.index)));
|
|
108
|
+
const card = document.createElement("span"), status = document.createElement("span");
|
|
109
|
+
card.className = "chat-resource"; card.dataset.resourceId = match[1]; card.setAttribute("role", "group");
|
|
110
|
+
status.className = "resource-status"; status.setAttribute("role", "status");
|
|
111
|
+
status.textContent = app.t("resourceLoading"); card.append(status); replacement.append(card);
|
|
112
|
+
cards.push({ card, roomId }); last = resourcePattern.lastIndex;
|
|
113
|
+
}
|
|
114
|
+
if (last) { replacement.append(document.createTextNode(value.slice(last))); node.replaceWith(replacement); }
|
|
115
|
+
}
|
|
116
|
+
return cards;
|
|
117
|
+
}
|
|
118
|
+
async function loadResourceCard(card, roomId, app) {
|
|
119
|
+
try {
|
|
120
|
+
const id = card.dataset.resourceId;
|
|
121
|
+
const result = await app.api(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(id)}`);
|
|
122
|
+
if (!card.isConnected) return;
|
|
123
|
+
const resource = result.resource, type = String(resource.mimeType).split(";")[0].toLowerCase();
|
|
124
|
+
card.setAttribute("aria-label", resource.name);
|
|
125
|
+
const info = document.createElement("span"), name = document.createElement("span"), size = document.createElement("span"), actions = document.createElement("span"), status = document.createElement("span");
|
|
126
|
+
info.className = "resource-info"; name.className = "resource-name"; name.textContent = resource.name;
|
|
127
|
+
size.className = "resource-size"; size.textContent = formatBytes(resource.size); info.append(name, size);
|
|
128
|
+
actions.className = "resource-actions"; status.className = "resource-status"; status.setAttribute("role", "status");
|
|
129
|
+
card.replaceChildren(info, actions, status);
|
|
130
|
+
const download = resourceButton("resourceDownload", resource.name, () => downloadResource(card, roomId, id, resource, app, status, download), app);
|
|
131
|
+
actions.append(download);
|
|
132
|
+
if (previewKind(type)) {
|
|
133
|
+
const preview = resourceButton("resourcePreview", resource.name, () => previewResource(card, roomId, id, resource, type, preview, app, status), app);
|
|
134
|
+
actions.append(preview);
|
|
135
|
+
}
|
|
136
|
+
} catch { if (card.isConnected) setResourceError(card, app); }
|
|
137
|
+
}
|
|
138
|
+
function resourceButton(key, name, action, app) {
|
|
139
|
+
const button = document.createElement("button");
|
|
140
|
+
button.type = "button"; button.className = "btn ghost small resource-button";
|
|
141
|
+
button.dataset.i18n = key; button.textContent = app.t(key);
|
|
142
|
+
button.setAttribute("aria-label", `${app.t(key)}: ${name}`);
|
|
143
|
+
button.addEventListener("click", action); return button;
|
|
144
|
+
}
|
|
145
|
+
async function downloadResource(card, roomId, id, resource, app, status, button) {
|
|
146
|
+
if (!card.isConnected || button.disabled) return;
|
|
147
|
+
button.disabled = true;
|
|
148
|
+
status.textContent = app.t("resourceLoading");
|
|
149
|
+
try {
|
|
150
|
+
const blob = await app.apiBlob(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(id)}/content`);
|
|
151
|
+
if (!card.isConnected) return;
|
|
152
|
+
const url = URL.createObjectURL(blob), link = document.createElement("a");
|
|
153
|
+
link.href = url; link.download = String(resource.name).replace(/[\\/\u0000-\u001f\u007f]/g, "_") || "download";
|
|
154
|
+
document.body.append(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
155
|
+
status.textContent = "";
|
|
156
|
+
} catch { if (card.isConnected) status.textContent = app.t("resourceFailed"); }
|
|
157
|
+
finally { if (card.isConnected) button.disabled = false; }
|
|
158
|
+
}
|
|
159
|
+
async function previewResource(card, roomId, id, resource, type, button, app, status) {
|
|
160
|
+
if (!card.isConnected || button.disabled) return;
|
|
161
|
+
button.disabled = true;
|
|
162
|
+
if (card._previewElement) {
|
|
163
|
+
try {
|
|
164
|
+
await app.preserveReadingLayout(() => card._previewElement.remove());
|
|
165
|
+
URL.revokeObjectURL(card._resourceUrl); previewUrls.delete(card); delete card._resourceUrl; delete card._previewElement;
|
|
166
|
+
if (card.isConnected) { button.dataset.i18n = "resourcePreview"; button.textContent = app.t("resourcePreview"); }
|
|
167
|
+
} catch {
|
|
168
|
+
if (!card.isConnected) return;
|
|
169
|
+
} finally { if (card.isConnected) button.disabled = false; }
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
status.textContent = app.t("resourceLoading");
|
|
173
|
+
let url;
|
|
174
|
+
try {
|
|
175
|
+
const blob = await app.apiBlob(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(id)}/content`);
|
|
176
|
+
if (!card.isConnected) return;
|
|
177
|
+
url = URL.createObjectURL(blob);
|
|
178
|
+
const kind = previewKind(type), media = document.createElement(kind), ready = waitForMediaSize(media, kind);
|
|
179
|
+
if (kind === "img") media.alt = resource.name;
|
|
180
|
+
else { media.controls = true; media.preload = "metadata"; }
|
|
181
|
+
media.addEventListener("error", () => { if (card.isConnected) status.textContent = app.t("resourceFailed"); });
|
|
182
|
+
media.src = url;
|
|
183
|
+
await app.preserveReadingLayout(async () => { status.textContent = ""; card.append(media); await ready; });
|
|
184
|
+
if (!card.isConnected) { URL.revokeObjectURL(url); return; }
|
|
185
|
+
card._resourceUrl = url; card._previewElement = media; previewUrls.set(card, url); watchPreviewRemoval();
|
|
186
|
+
button.dataset.i18n = "resourceHide"; button.textContent = app.t("resourceHide");
|
|
187
|
+
} catch { if (url) URL.revokeObjectURL(url); if (card.isConnected) status.textContent = app.t("resourceFailed"); }
|
|
188
|
+
finally { if (card.isConnected) button.disabled = false; }
|
|
189
|
+
}
|
|
190
|
+
function waitForMediaSize(media, kind) {
|
|
191
|
+
const event = kind === "img" ? "load" : "loadedmetadata";
|
|
192
|
+
if (kind === "img" && media.complete && media.naturalWidth) return Promise.resolve();
|
|
193
|
+
if (kind !== "img" && media.readyState >= 1) return Promise.resolve();
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
media.addEventListener(event, resolve, { once: true });
|
|
196
|
+
media.addEventListener("error", reject, { once: true });
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
function previewKind(type) {
|
|
200
|
+
if (["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"].includes(type)) return "img";
|
|
201
|
+
if (["audio/mpeg", "audio/ogg", "audio/wav", "audio/webm", "audio/mp4"].includes(type)) return "audio";
|
|
202
|
+
if (["video/mp4", "video/webm", "video/ogg"].includes(type)) return "video";
|
|
203
|
+
return "";
|
|
204
|
+
}
|
|
205
|
+
function formatBytes(value) {
|
|
206
|
+
const bytes = Math.max(0, Number(value) || 0);
|
|
207
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
208
|
+
return bytes < 1048576 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1048576).toFixed(1)} MB`;
|
|
209
|
+
}
|
|
210
|
+
function setResourceError(card, app) {
|
|
211
|
+
card.textContent = "";
|
|
212
|
+
const status = document.createElement("span"); status.className = "resource-status";
|
|
213
|
+
status.setAttribute("role", "status"); status.textContent = app.t("resourceFailed"); card.append(status);
|
|
214
|
+
}
|
|
215
|
+
function watchPreviewRemoval() {
|
|
216
|
+
const list = document.querySelector("#msgList");
|
|
217
|
+
if (previewObserver || !list) return;
|
|
218
|
+
previewObserver = new MutationObserver((records) => {
|
|
219
|
+
for (const node of records.flatMap((record) => [...record.removedNodes])) {
|
|
220
|
+
if (!(node instanceof Element)) continue;
|
|
221
|
+
for (const card of [node, ...node.querySelectorAll(".chat-resource")]) {
|
|
222
|
+
const url = previewUrls.get(card);
|
|
223
|
+
if (url && !card.isConnected) { URL.revokeObjectURL(url); previewUrls.delete(card); }
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
previewObserver.observe(list, { childList: true, subtree: true });
|
|
31
228
|
}
|
|
32
229
|
|
|
33
230
|
function replaceMentionTokens(fragment, mentions, app) {
|
|
@@ -56,11 +253,6 @@ function replaceMentionTokens(fragment, mentions, app) {
|
|
|
56
253
|
}
|
|
57
254
|
}
|
|
58
255
|
|
|
59
|
-
export function copyCodeFromButton(button, app) {
|
|
60
|
-
const code = button.parentElement.querySelector("code")?.textContent || "";
|
|
61
|
-
return copyTextToClipboard(code).then((copied) => copied ? app.flash(button, "copiedCode") : app.showSendError("copyCodeFailed"));
|
|
62
|
-
}
|
|
63
|
-
|
|
64
256
|
export async function copyTextToClipboard(text) {
|
|
65
257
|
try {
|
|
66
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) {
|
|
@@ -90,13 +90,16 @@ export function initMembers(app) {
|
|
|
90
90
|
app.state.receiptRefreshTimer = setTimeout(() => void app.loadVisibleReceipts(roomId, generation), 180);
|
|
91
91
|
};
|
|
92
92
|
app.queueReceiptObservation = () => {
|
|
93
|
+
if ((app.state.resizeScrollAdjusting || app.state.layoutScrollAdjusting)
|
|
94
|
+
&& performance.now() > app.state.userScrollIntentUntil) return;
|
|
93
95
|
app.state.receiptObservation = { roomId: app.state.room?.id, generation: app.state.pollGeneration };
|
|
94
96
|
if (app.state.receiptObservationFrame) return;
|
|
95
97
|
app.state.receiptObservationFrame = requestAnimationFrame(() => {
|
|
96
98
|
app.state.receiptObservationFrame = 0;
|
|
97
99
|
const target = app.state.receiptObservation;
|
|
98
100
|
app.state.receiptObservation = null;
|
|
99
|
-
if (!target ||
|
|
101
|
+
if (!target || (app.state.resizeScrollAdjusting || app.state.layoutScrollAdjusting)
|
|
102
|
+
&& performance.now() > app.state.userScrollIntentUntil || document.hidden || !document.hasFocus() || !current(app, target.roomId, target.generation)) return;
|
|
100
103
|
void app.loadVisibleReceipts(target.roomId, target.generation);
|
|
101
104
|
void app.ackVisibleMessages(target.roomId, target.generation);
|
|
102
105
|
});
|
|
@@ -8,8 +8,22 @@ 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);
|
|
12
|
+
textarea.style.overflowY = "hidden";
|
|
13
|
+
const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
|
|
14
|
+
const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
|
|
15
|
+
const border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
|
|
16
|
+
if (!textarea.value) {
|
|
17
|
+
textarea.style.height = `${Math.max(line + padding + border, parseFloat(style.minHeight) || 0)}px`;
|
|
18
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
11
21
|
textarea.style.height = "auto";
|
|
12
|
-
|
|
22
|
+
const limit = line * 5 + padding;
|
|
23
|
+
const overflow = textarea.scrollHeight > limit + 1;
|
|
24
|
+
textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
|
|
25
|
+
textarea.style.overflowY = overflow ? "auto" : "hidden";
|
|
26
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
13
27
|
};
|
|
14
28
|
app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
|
|
15
29
|
app.updateDraftCount = () => app.setText($("#draftCount"), "messageCount", { count: $("#msgInput").value.length });
|
|
@@ -50,6 +64,7 @@ export function initMessages(app) {
|
|
|
50
64
|
const updated = await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, {
|
|
51
65
|
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion) }),
|
|
52
66
|
});
|
|
67
|
+
app.completeAttachmentsFromText?.(roomId, item.text);
|
|
53
68
|
const entry = app.state.rooms.get(roomId);
|
|
54
69
|
if (entry) {
|
|
55
70
|
entry.room = mergeRoom(entry.room, updated);
|
|
@@ -73,6 +88,7 @@ export function initMessages(app) {
|
|
|
73
88
|
}
|
|
74
89
|
};
|
|
75
90
|
app.jumpToBottom = () => {
|
|
91
|
+
app.state.readAnchorGuard = null;
|
|
76
92
|
$("#thread").scrollTop = $("#thread").scrollHeight;
|
|
77
93
|
const entry = app.state.room && app.state.rooms.get(app.state.room.id);
|
|
78
94
|
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
|
|
@@ -97,6 +113,10 @@ export function initMessages(app) {
|
|
|
97
113
|
const thread = $("#thread");
|
|
98
114
|
if (!room || !entry || document.hidden || !document.hasFocus()
|
|
99
115
|
|| thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
|
|
116
|
+
if (app.state.readAnchorGuard?.roomId === room.id) {
|
|
117
|
+
if (performance.now() > app.state.userScrollIntentUntil) return;
|
|
118
|
+
app.state.readAnchorGuard = null;
|
|
119
|
+
}
|
|
100
120
|
const timestamp = room.messages.reduce((latest, message) => Math.max(latest, message.createdAt), entry.readTs);
|
|
101
121
|
if (!timestamp || timestamp <= entry.readTs) return;
|
|
102
122
|
try {
|
|
@@ -105,6 +125,7 @@ export function initMessages(app) {
|
|
|
105
125
|
});
|
|
106
126
|
if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation) return;
|
|
107
127
|
entry.readTs = timestamp;
|
|
128
|
+
app.saveReadTs(room.id, timestamp);
|
|
108
129
|
entry.unreadOverflow = false;
|
|
109
130
|
for (const [id, message] of entry.unreadIds) if (message.createdAt <= timestamp) entry.unreadIds.delete(id);
|
|
110
131
|
app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
|
|
@@ -126,10 +147,7 @@ export function initMessages(app) {
|
|
|
126
147
|
row.append(text);
|
|
127
148
|
} else {
|
|
128
149
|
const direct = app.state.room.kind === "direct";
|
|
129
|
-
const
|
|
130
|
-
const own = direct ? message.senderId === LS.sessionID
|
|
131
|
-
: message.senderSessionID ? message.senderSessionID === LS.sessionID
|
|
132
|
-
: message.senderId === app.state.myName && sameName?.length === 1 && sameName[0].sessionID === LS.sessionID;
|
|
150
|
+
const own = isOwnMessage(message, app);
|
|
133
151
|
const sender = direct
|
|
134
152
|
? app.state.room.participants.find((person) => person.id === message.senderId)?.name || app.t("guest")
|
|
135
153
|
: message.senderId;
|
|
@@ -153,8 +171,21 @@ export function initMessages(app) {
|
|
|
153
171
|
copy.type = "button";
|
|
154
172
|
copy.className = "message-copy";
|
|
155
173
|
copy.dataset.copyMessage = "";
|
|
156
|
-
copy.
|
|
157
|
-
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);
|
|
158
189
|
copy._copyText = String(message.text ?? "");
|
|
159
190
|
row.append(copy);
|
|
160
191
|
if (live) row.classList.add("in");
|
|
@@ -252,20 +283,25 @@ export function initMessages(app) {
|
|
|
252
283
|
};
|
|
253
284
|
|
|
254
285
|
app.send = async () => {
|
|
255
|
-
const input = $("#msgInput"),
|
|
256
|
-
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;
|
|
257
291
|
const revision = app.state.draftRevision.get(room.id) || 0;
|
|
292
|
+
app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
|
|
258
293
|
app.closeMention();
|
|
259
294
|
input.value = "";
|
|
260
295
|
app.clearDraft(room.id);
|
|
261
296
|
app.autoGrow(input);
|
|
262
|
-
app.updateSendState();
|
|
263
297
|
app.updateDraftCount();
|
|
298
|
+
app.updateSendState();
|
|
264
299
|
app.hideSendError();
|
|
265
300
|
try {
|
|
266
301
|
const updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
|
|
267
302
|
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, isQuestion }),
|
|
268
303
|
});
|
|
304
|
+
app.completeAttachments?.(room.id, message.ids);
|
|
269
305
|
if (app.state.room?.id !== room.id) return;
|
|
270
306
|
app.state.room = updated;
|
|
271
307
|
const entry = app.state.rooms.get(room.id);
|
|
@@ -286,6 +322,7 @@ export function initMessages(app) {
|
|
|
286
322
|
const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
|
|
287
323
|
const failures = app.state.failedMessages.get(room.id) || [];
|
|
288
324
|
app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, isQuestion }]);
|
|
325
|
+
app.completeAttachments?.(room.id, message.ids);
|
|
289
326
|
app.renderFailedMessages();
|
|
290
327
|
if (app.state.room?.id !== room.id) return;
|
|
291
328
|
if (unchanged) app.clearDraft(room.id);
|
|
@@ -294,6 +331,9 @@ export function initMessages(app) {
|
|
|
294
331
|
app.updateDraftCount();
|
|
295
332
|
if (error.status === 401) { app.openChatSettings(); app.showSendError("sendAuth"); }
|
|
296
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();
|
|
297
337
|
}
|
|
298
338
|
};
|
|
299
339
|
|
|
@@ -338,18 +378,22 @@ export function initMessages(app) {
|
|
|
338
378
|
return;
|
|
339
379
|
}
|
|
340
380
|
if (data.member !== true || !Array.isArray(data.items)) return;
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
381
|
+
const items = data.items, previousReceivedTs = entry?.receivedTs || 0, messages = app.state.room.messages;
|
|
382
|
+
const known = new Set(messages.map((message) => message.id));
|
|
383
|
+
const previousUnreadOverflow = Boolean(entry?.unreadOverflow);
|
|
384
|
+
let sawSystem = false, added = 0, unreadChanged = false;
|
|
385
|
+
for (const item of items) {
|
|
386
|
+
if (item.senderId === "system") sawSystem = true;
|
|
387
|
+
const wasKnown = known.has(item.id);
|
|
388
|
+
if (!wasKnown) {
|
|
389
|
+
messages.push({ ...item, roomId }); known.add(item.id);
|
|
390
|
+
if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
|
|
391
|
+
added++;
|
|
392
|
+
}
|
|
393
|
+
if (entry && item.createdAt > entry.readTs && !isOwnMessage(item, app) && !entry.unreadIds.has(item.id)) {
|
|
394
|
+
entry.unreadIds.set(item.id, item); unreadChanged = true;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
353
397
|
if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
|
|
354
398
|
if (entry) entry.unreadOverflow = Boolean(data.hasMore);
|
|
355
399
|
if (messages.length > 500) messages.splice(0, messages.length - 500);
|
|
@@ -358,7 +402,7 @@ export function initMessages(app) {
|
|
|
358
402
|
await app.refreshRoomMeta(roomId, generation);
|
|
359
403
|
if (!isCurrentPoll(roomId, generation)) return;
|
|
360
404
|
}
|
|
361
|
-
|
|
405
|
+
if (added || unreadChanged || entry && previousUnreadOverflow !== entry.unreadOverflow) {
|
|
362
406
|
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : app.state.unread + added;
|
|
363
407
|
app.updateBadge();
|
|
364
408
|
}
|
|
@@ -432,6 +476,16 @@ export function initMessages(app) {
|
|
|
432
476
|
|
|
433
477
|
function trimMessages(list, app) {
|
|
434
478
|
if (list.children.length <= 400 || hasMessageSelection(list)) return;
|
|
479
|
+
const saved = app.state.positions.get(app.state.room?.id), rows = [...list.querySelectorAll("[data-msg-id]")];
|
|
480
|
+
const anchor = saved?.messageId && rows.find((row) => row.dataset.msgId === saved.messageId);
|
|
481
|
+
if (anchor && rows.indexOf(anchor) < rows.length - 280) {
|
|
482
|
+
const recent = rows.at(-300);
|
|
483
|
+
while (list.firstElementChild && list.firstElementChild !== anchor) list.firstElementChild.remove();
|
|
484
|
+
let next = anchor.nextElementSibling;
|
|
485
|
+
while (next && next !== recent) { const after = next.nextElementSibling; next.remove(); next = after; }
|
|
486
|
+
const gap = document.createElement("li"); gap.className = "gap"; app.setText(gap, "messagesBetweenOmitted"); anchor.after(gap);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
435
489
|
while (list.children.length > 300) list.removeChild(list.firstChild);
|
|
436
490
|
if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
|
|
437
491
|
const gap = document.createElement("li");
|
|
@@ -441,4 +495,12 @@ function trimMessages(list, app) {
|
|
|
441
495
|
}
|
|
442
496
|
}
|
|
443
497
|
|
|
498
|
+
function isOwnMessage(message, app) {
|
|
499
|
+
const room = app.state.room, direct = room.kind === "direct";
|
|
500
|
+
const sameName = app.state.memberSessions.get(room.id)?.filter((member) => member.name === message.senderId);
|
|
501
|
+
return direct ? message.senderId === LS.sessionID
|
|
502
|
+
: message.senderSessionID ? message.senderSessionID === LS.sessionID
|
|
503
|
+
: message.senderId === app.state.myName && sameName?.length === 1 && sameName[0].sessionID === LS.sessionID;
|
|
504
|
+
}
|
|
505
|
+
|
|
444
506
|
}
|
|
@@ -27,7 +27,7 @@ export function initReceipts(app) {
|
|
|
27
27
|
const next = $("#msgList").querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
28
28
|
if (next) thread.scrollTop += next.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorTop;
|
|
29
29
|
}
|
|
30
|
-
if (selectedID) renderPanel();
|
|
30
|
+
if (selectedID) { renderPanel(); positionPanel(); }
|
|
31
31
|
};
|
|
32
32
|
$("#msgList").addEventListener("click", (event) => {
|
|
33
33
|
const button = event.target.closest(".message-readers");
|
|
@@ -42,33 +42,38 @@ export function initReceipts(app) {
|
|
|
42
42
|
document.addEventListener("keydown", (event) => {
|
|
43
43
|
if (event.key === "Escape" && selectedID) { event.preventDefault(); close(true); }
|
|
44
44
|
});
|
|
45
|
+
window.addEventListener("resize", positionPanel);
|
|
46
|
+
window.addEventListener("scroll", positionPanel, true);
|
|
45
47
|
|
|
46
48
|
function open(id, button) {
|
|
47
49
|
selectedID = id; trigger = button;
|
|
48
50
|
button.setAttribute("aria-expanded", "true");
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}, () => $("#btnCloseReaders").focus());
|
|
51
|
+
panel.hidden = false; renderPanel(); positionPanel();
|
|
52
|
+
requestAnimationFrame(() => $("#readerHeading").focus({ preventScroll: true }));
|
|
52
53
|
}
|
|
53
54
|
function close(restoreFocus) {
|
|
54
55
|
if (!selectedID) return;
|
|
55
56
|
const previous = trigger;
|
|
56
57
|
selectedID = ""; trigger = null;
|
|
57
58
|
previous?.setAttribute("aria-expanded", "false");
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}, () => { if (restoreFocus && previous?.isConnected) previous.focus({ preventScroll: true }); });
|
|
59
|
+
panel.hidden = true;
|
|
60
|
+
if (restoreFocus && previous?.isConnected) previous.focus({ preventScroll: true });
|
|
61
61
|
}
|
|
62
|
-
function
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
62
|
+
function positionPanel() {
|
|
63
|
+
if (!selectedID || panel.hidden) return;
|
|
64
|
+
if (!trigger?.isConnected) return close(false);
|
|
65
|
+
const anchor = trigger.getBoundingClientRect(), margin = 12;
|
|
66
|
+
if (anchor.bottom <= 0 || anchor.top >= innerHeight) return close(false);
|
|
67
|
+
const width = Math.min(320, innerWidth - margin * 2);
|
|
68
|
+
panel.style.width = `${width}px`;
|
|
69
|
+
const belowSpace = innerHeight - margin - anchor.bottom - 8;
|
|
70
|
+
const aboveSpace = anchor.top - margin - 8;
|
|
71
|
+
const placeBelow = belowSpace >= aboveSpace;
|
|
72
|
+
panel.style.maxHeight = `${Math.max(0, placeBelow ? belowSpace : aboveSpace)}px`;
|
|
73
|
+
const height = panel.getBoundingClientRect().height;
|
|
74
|
+
const left = Math.max(margin, Math.min(anchor.right - width, innerWidth - width - margin));
|
|
75
|
+
const top = placeBelow ? anchor.bottom + 8 : anchor.top - height - 8;
|
|
76
|
+
panel.style.left = `${left}px`; panel.style.top = `${top}px`;
|
|
72
77
|
}
|
|
73
78
|
function renderPanel() {
|
|
74
79
|
const message = app.state.room?.messages.find((item) => item.id === selectedID);
|