@alexsun-top/opencode-chat-room 0.6.6 → 0.6.8
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 +28 -0
- package/README.md +6 -3
- package/README.zh-CN.md +7 -3
- package/cli.ts +1 -1
- package/docs/administrator-rooms.md +11 -5
- package/index.ts +2 -2
- package/package.json +6 -2
- package/plugin.ts +57 -26
- package/server/admin-routes.ts +15 -7
- package/server/admin-state.ts +2 -2
- package/server/announcement-routes.ts +2 -2
- package/server/assets/attachments.css +25 -0
- package/server/assets/base.css +251 -39
- package/server/assets/chat/admin-badge.js +49 -0
- package/server/assets/chat/admin.js +77 -24
- package/server/assets/chat/announcements.js +27 -11
- package/server/assets/chat/attachment-store.js +106 -0
- package/server/assets/chat/attachments.js +245 -25
- package/server/assets/chat/events.js +56 -12
- package/server/assets/chat/image-zoom.js +141 -0
- package/server/assets/chat/index.js +10 -0
- package/server/assets/chat/install-prompt.js +82 -0
- package/server/assets/chat/join-requests.js +355 -0
- package/server/assets/chat/markdown.js +82 -5
- package/server/assets/chat/members.js +16 -6
- package/server/assets/chat/message-polling.js +158 -0
- package/server/assets/chat/message-window.js +14 -0
- package/server/assets/chat/messages.js +12 -132
- package/server/assets/chat/panels.js +37 -0
- package/server/assets/chat/questions.js +10 -6
- package/server/assets/chat/recall.js +279 -0
- package/server/assets/chat/receipts.js +3 -1
- package/server/assets/chat/reminders.js +67 -9
- package/server/assets/chat/replies.js +1 -1
- package/server/assets/chat/room-list.js +60 -0
- package/server/assets/chat/room-watcher.js +5 -1
- package/server/assets/chat/rooms.js +36 -84
- package/server/assets/chat/shortcuts.js +254 -0
- package/server/assets/chat/state.js +97 -24
- package/server/assets/chat/system-messages.js +28 -7
- package/server/assets/conversation.css +18 -26
- package/server/assets/keyboard-hints.css +51 -0
- package/server/assets/recall.css +29 -0
- package/server/assets/responsive.css +58 -16
- package/server/chat-server.ts +81 -62
- package/server/chat.html +238 -72
- package/server/history-route.ts +1 -1
- package/server/inbox.ts +3 -3
- package/server/join-requests.ts +106 -0
- package/server/member-routes.ts +4 -4
- package/server/message-recall-routes.ts +37 -0
- package/server/newrooms.ts +105 -13
- package/server/resource-routes.ts +19 -5
- package/server/room-join.ts +59 -0
- package/server/room-owner.ts +72 -0
- package/server/room-payload.ts +6 -2
- package/server/room-reminders.ts +3 -3
- package/server/sw.js +2 -0
- package/server/wake.ts +48 -19
- package/skills/chatroom/SKILL.md +35 -1
- package/src/README.md +22 -0
- package/src/{admin-client.ts → agent/admin-client.ts} +39 -9
- package/src/{admin-credentials.ts → agent/admin-credentials.ts} +1 -1
- package/src/{agent-presence.ts → agent/agent-presence.ts} +2 -2
- package/src/{agent-receipts.ts → agent/agent-receipts.ts} +2 -2
- package/src/{announcement-tool.ts → agent/announcement-tool.ts} +2 -2
- package/src/{chatroom-skill.ts → agent/chatroom-skill.ts} +1 -1
- package/src/{center-client.ts → center/center-client.ts} +103 -13
- package/src/{center-inbox.ts → center/center-inbox.ts} +44 -19
- package/src/{center-wake.ts → center/center-wake.ts} +31 -18
- package/src/{mentions.ts → center/mentions.ts} +1 -1
- package/src/center/message-ids.ts +7 -0
- package/src/center/notification-budget.ts +16 -0
- package/src/{queue-transport.ts → center/queue-transport.ts} +3 -3
- package/src/{queue.ts → center/queue.ts} +16 -6
- package/src/{reminder-client.ts → center/reminder-client.ts} +1 -1
- package/src/{session-delivery.ts → center/session-delivery.ts} +1 -1
- package/src/{announcements.ts → rooms/announcements.ts} +2 -2
- package/src/{resource-upload.ts → rooms/resource-upload.ts} +1 -1
- package/src/{resources.ts → rooms/resources.ts} +55 -9
- package/src/{room-service.ts → rooms/room-service.ts} +22 -2
- package/src/{background.ts → runtime/background.ts} +3 -3
- package/src/{plugin-notifications.ts → runtime/plugin-notifications.ts} +45 -19
- package/src/{v1-plugin.ts → runtime/v1-plugin.ts} +4 -4
- package/src/{v2-plugin.ts → runtime/v2-plugin.ts} +10 -10
- package/src/{v2-receiver.ts → runtime/v2-receiver.ts} +7 -7
- package/src/{watch.ts → runtime/watch.ts} +12 -12
- package/src/{member-state.ts → state/member-state.ts} +2 -2
- package/src/state/roles.ts +34 -0
- package/src/{sqlite-state.ts → state/sqlite-state.ts} +226 -37
- package/src/{store.ts → state/store.ts} +23 -4
- package/src/tests/announcement-board.ts +185 -0
- /package/src/{resource-read.ts → rooms/resource-read.ts} +0 -0
- /package/src/{receiver-owner.ts → state/receiver-owner.ts} +0 -0
- /package/src/{receiver-state.ts → state/receiver-state.ts} +0 -0
|
@@ -3,6 +3,7 @@ import { LS } from "./state.js";
|
|
|
3
3
|
export function initAnnouncements(app) {
|
|
4
4
|
const $ = app.$, drafts = new Map();
|
|
5
5
|
const panel = $("#announcementPanel"), trigger = $("#btnAnnouncements"), list = $("#announcementList");
|
|
6
|
+
const dialog = $("#announcementDialog"), heading = $("#announcementDialogHeading");
|
|
6
7
|
let items = [], selected = "", generation = 0, roomGeneration = 0, editorRevision = 0, saveToken = 0;
|
|
7
8
|
const key = (id, name = selected) => `${id}\0${name ? `item\0${name}` : "new"}`;
|
|
8
9
|
const roomId = () => app.state.room?.id;
|
|
@@ -20,14 +21,15 @@ export function initAnnouncements(app) {
|
|
|
20
21
|
if (saved?.name === snapshot.name && saved.content === snapshot.content) drafts.delete(key(id, name));
|
|
21
22
|
}
|
|
22
23
|
function status(text) { $("#announcementStatus").textContent = text; }
|
|
24
|
+
function formStatus(text) { $("#announcementDialogStatus").textContent = text; }
|
|
23
25
|
function count() { $("#announcementCount").textContent = app.t("announcementCount", { count: Array.from($("#announcementContent").value).length }); }
|
|
24
26
|
function render() {
|
|
25
27
|
list.textContent = "";
|
|
26
28
|
for (const entry of items) {
|
|
27
29
|
const li = document.createElement("li"), button = document.createElement("button");
|
|
28
|
-
button.type = "button"; button.textContent = entry.name;
|
|
30
|
+
button.type = "button"; button.textContent = entry.name; button.setAttribute("aria-haspopup", "dialog");
|
|
29
31
|
if (entry.name === selected) button.setAttribute("aria-current", "true");
|
|
30
|
-
button.addEventListener("click", (event) => { event.stopPropagation();
|
|
32
|
+
button.addEventListener("click", (event) => { event.stopPropagation(); openEditor(entry); });
|
|
31
33
|
li.append(button); list.append(li);
|
|
32
34
|
}
|
|
33
35
|
if (!items.length) status(app.t("announcementEmpty"));
|
|
@@ -45,6 +47,14 @@ export function initAnnouncements(app) {
|
|
|
45
47
|
$("#btnDeleteAnnouncement").hidden = !selected;
|
|
46
48
|
render(); count();
|
|
47
49
|
}
|
|
50
|
+
function openEditor(entry) {
|
|
51
|
+
select(entry);
|
|
52
|
+
if (entry) { delete heading.dataset.i18n; heading.textContent = entry.name; }
|
|
53
|
+
else { heading.dataset.i18n = "announcementNew"; heading.textContent = app.t("announcementNew"); }
|
|
54
|
+
formStatus("");
|
|
55
|
+
if (!dialog.open) dialog.showModal();
|
|
56
|
+
$(entry ? "#announcementContent" : "#announcementName").focus();
|
|
57
|
+
}
|
|
48
58
|
async function load(id = roomId()) {
|
|
49
59
|
if (!id) return;
|
|
50
60
|
const request = ++generation, context = roomGeneration; status(app.t("announcementLoading"));
|
|
@@ -78,8 +88,8 @@ export function initAnnouncements(app) {
|
|
|
78
88
|
$("#announcementForm").addEventListener("submit", async (event) => {
|
|
79
89
|
event.preventDefault();
|
|
80
90
|
const id = roomId(), name = $("#announcementName").value.trim(), content = $("#announcementContent").value;
|
|
81
|
-
if (!id || !name || Array.from(name).length > 64 || Array.from(content).length > 5000) return
|
|
82
|
-
if (!selected && items.some((item) => item.name === name)) return
|
|
91
|
+
if (!id || !name || Array.from(name).length > 64 || Array.from(content).length > 5000) return formStatus(app.t("announcementInvalid"));
|
|
92
|
+
if (!selected && items.some((item) => item.name === name)) return formStatus(app.t("announcementDuplicate"));
|
|
83
93
|
const context = roomGeneration, captured = editorSnapshot(), draftName = selected, button = $("#btnSaveAnnouncement"), token = ++saveToken;
|
|
84
94
|
storeDraft(id, draftName); button.disabled = true;
|
|
85
95
|
try {
|
|
@@ -89,11 +99,12 @@ export function initAnnouncements(app) {
|
|
|
89
99
|
if (currentRoom(id, context)) {
|
|
90
100
|
generation++; items = [...items.filter((item) => item.name !== name), result.announcement]; render();
|
|
91
101
|
clearDraftIfUnchanged(id, draftName, captured);
|
|
92
|
-
if (editorMatches(captured)) { select(result.announcement); status(app.t("announcementSaved")); }
|
|
102
|
+
if (editorMatches(captured)) { select(result.announcement); status(app.t("announcementSaved")); formStatus(""); dialog.close(); }
|
|
93
103
|
else if (!selected) {
|
|
94
104
|
// Keep editing the newer draft under the name the create just reserved.
|
|
95
105
|
drafts.delete(key(id, draftName));
|
|
96
106
|
selected = result.announcement.name;
|
|
107
|
+
heading.textContent = selected; delete heading.dataset.i18n;
|
|
97
108
|
$("#announcementName").value = selected; $("#announcementName").readOnly = true;
|
|
98
109
|
$("#btnDeleteAnnouncement").hidden = false;
|
|
99
110
|
drafts.set(key(id, selected), { name: selected, content: $("#announcementContent").value });
|
|
@@ -101,11 +112,11 @@ export function initAnnouncements(app) {
|
|
|
101
112
|
}
|
|
102
113
|
}
|
|
103
114
|
} catch (error) {
|
|
104
|
-
if (currentRoom(id, context) && editorMatches(captured))
|
|
115
|
+
if (currentRoom(id, context) && editorMatches(captured)) formStatus(error.status === 403 ? error.message : app.t("announcementLoadFailed"));
|
|
105
116
|
}
|
|
106
117
|
finally { if (token === saveToken) button.disabled = false; }
|
|
107
118
|
});
|
|
108
|
-
$("#btnNewAnnouncement").addEventListener("click", () =>
|
|
119
|
+
$("#btnNewAnnouncement").addEventListener("click", () => openEditor(null));
|
|
109
120
|
$("#btnDeleteAnnouncement").addEventListener("click", async () => {
|
|
110
121
|
const id = roomId(), name = selected;
|
|
111
122
|
if (!id || !name || !confirm(app.t("announcementDeleteConfirm", { name }))) return;
|
|
@@ -115,20 +126,25 @@ export function initAnnouncements(app) {
|
|
|
115
126
|
if (currentRoom(id, context)) {
|
|
116
127
|
generation++; items = items.filter((item) => item.name !== name); render();
|
|
117
128
|
clearDraftIfUnchanged(id, name, captured);
|
|
118
|
-
if (editorMatches(captured)) { select(null); status(app.t("announcementDeleted")); }
|
|
129
|
+
if (editorMatches(captured)) { select(null); status(app.t("announcementDeleted")); formStatus(""); dialog.close(); }
|
|
119
130
|
}
|
|
120
|
-
} catch (error) { if (currentRoom(id, context) && editorMatches(captured))
|
|
131
|
+
} catch (error) { if (currentRoom(id, context) && editorMatches(captured)) formStatus(error.message); }
|
|
121
132
|
});
|
|
122
133
|
$("#btnRefreshAnnouncements").addEventListener("click", () => void load());
|
|
134
|
+
$("#btnCloseAnnouncement").addEventListener("click", () => dialog.close());
|
|
135
|
+
$("#btnCancelAnnouncement").addEventListener("click", () => dialog.close());
|
|
136
|
+
dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
|
|
123
137
|
trigger.addEventListener("click", () => {
|
|
124
138
|
const open = panel.hidden; app.closePanels(); panel.hidden = !open;
|
|
125
139
|
trigger.setAttribute("aria-expanded", String(open)); if (open) { void load(); $("#announcementHeading").focus(); }
|
|
126
140
|
});
|
|
127
|
-
document.addEventListener("keydown", (event) => { if (event.key === "Escape" && !panel.hidden) { app.closePanels(); trigger.focus(); } });
|
|
141
|
+
document.addEventListener("keydown", (event) => { if (event.key === "Escape" && !dialog.open && !panel.hidden) { app.closePanels(); trigger.focus(); } });
|
|
128
142
|
const close = app.closePanels;
|
|
129
|
-
app.closePanels = () => { close(); panel.hidden = true; trigger.setAttribute("aria-expanded", "false"); };
|
|
143
|
+
app.closePanels = () => { close(); panel.hidden = true; trigger.setAttribute("aria-expanded", "false"); if (dialog.open) dialog.close(); };
|
|
130
144
|
document.addEventListener("chat-room-activated", (event) => {
|
|
131
145
|
const id = event.detail;
|
|
146
|
+
if (dialog.open) dialog.close();
|
|
147
|
+
formStatus("");
|
|
132
148
|
roomGeneration++; generation++; saveToken++; $("#btnSaveAnnouncement").disabled = false;
|
|
133
149
|
selected = ""; items = []; select(null); void load(id);
|
|
134
150
|
});
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Durable recovery for pasted attachments. Text is written synchronously so it
|
|
2
|
+
// survives the same task that creates the file; other blobs use IndexedDB.
|
|
3
|
+
const DB_NAME = "oc-chat-attachments", STORE = "pending", TEXT_PREFIX = "chat.pendingText:";
|
|
4
|
+
let dbPromise;
|
|
5
|
+
|
|
6
|
+
function database() {
|
|
7
|
+
if (dbPromise) return dbPromise;
|
|
8
|
+
dbPromise = new Promise((resolve) => {
|
|
9
|
+
try {
|
|
10
|
+
const request = indexedDB.open(DB_NAME, 1);
|
|
11
|
+
request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: "key" });
|
|
12
|
+
request.onsuccess = () => resolve(request.result);
|
|
13
|
+
request.onerror = request.onblocked = () => resolve(null);
|
|
14
|
+
} catch { resolve(null); }
|
|
15
|
+
});
|
|
16
|
+
return dbPromise;
|
|
17
|
+
}
|
|
18
|
+
function done(request) {
|
|
19
|
+
return new Promise((resolve) => { request.onsuccess = () => resolve(request.result); request.onerror = () => resolve(undefined); });
|
|
20
|
+
}
|
|
21
|
+
function committed(tx) {
|
|
22
|
+
return new Promise((resolve) => { tx.oncomplete = () => resolve(true); tx.onerror = tx.onabort = () => resolve(false); });
|
|
23
|
+
}
|
|
24
|
+
async function write(record) {
|
|
25
|
+
const db = await database(); if (!db) return false;
|
|
26
|
+
try {
|
|
27
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
28
|
+
tx.objectStore(STORE).put(record);
|
|
29
|
+
return await committed(tx);
|
|
30
|
+
} catch { return false; }
|
|
31
|
+
}
|
|
32
|
+
async function remove(key) {
|
|
33
|
+
const db = await database(); if (!db) return;
|
|
34
|
+
try {
|
|
35
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
36
|
+
tx.objectStore(STORE).delete(key);
|
|
37
|
+
await committed(tx);
|
|
38
|
+
} catch { /* Best effort; stale blobs are harmless. */ }
|
|
39
|
+
}
|
|
40
|
+
function readTexts() {
|
|
41
|
+
const records = [];
|
|
42
|
+
try {
|
|
43
|
+
for (let index = 0; index < localStorage.length; index++) {
|
|
44
|
+
const key = localStorage.key(index);
|
|
45
|
+
if (!key?.startsWith(TEXT_PREFIX)) continue;
|
|
46
|
+
try { records.push(JSON.parse(localStorage.getItem(key) || "null")); } catch { /* Ignore one damaged record. */ }
|
|
47
|
+
}
|
|
48
|
+
} catch { /* Storage may be blocked. */ }
|
|
49
|
+
return records.filter((record) => record && typeof record.key === "string");
|
|
50
|
+
}
|
|
51
|
+
function writeText(record) {
|
|
52
|
+
try { localStorage.setItem(TEXT_PREFIX + record.key, JSON.stringify(record)); return true; }
|
|
53
|
+
catch { return false; }
|
|
54
|
+
}
|
|
55
|
+
function forgetText(key) {
|
|
56
|
+
try { localStorage.removeItem(TEXT_PREFIX + key); } catch { /* Storage may be blocked. */ }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function persist(item, roomId) {
|
|
60
|
+
const record = {
|
|
61
|
+
key: item.uploadID, roomId, name: item.file.name, textSource: item.textSource,
|
|
62
|
+
type: item.file.type, lastModified: item.file.lastModified, createdAt: Date.now(),
|
|
63
|
+
};
|
|
64
|
+
if (typeof item.textContent === "string" && writeText({ ...record, text: item.textContent })) {
|
|
65
|
+
item.durable = true;
|
|
66
|
+
return Promise.resolve(true);
|
|
67
|
+
}
|
|
68
|
+
item.persist = write({ ...record, blob: item.file }).then((ok) => { item.durable = ok; return ok; });
|
|
69
|
+
return item.persist;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function forget(item) {
|
|
73
|
+
forgetText(item.uploadID);
|
|
74
|
+
void Promise.resolve(item.persist).finally(() => remove(item.uploadID));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function forgetTextSource(roomId, textSource) {
|
|
78
|
+
for (const record of readTexts()) if (record.roomId === roomId && record.textSource === textSource) forgetText(record.key);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function recover(roomId, draft) {
|
|
82
|
+
const texts = readTexts().filter((record) => record.roomId === roomId);
|
|
83
|
+
const files = (await readFiles()).filter((record) => record.roomId === roomId);
|
|
84
|
+
const seen = new Set(), restored = [];
|
|
85
|
+
for (const record of [...texts, ...files]) {
|
|
86
|
+
if (seen.has(record.key)) continue;
|
|
87
|
+
seen.add(record.key);
|
|
88
|
+
if (record.textSource !== undefined && record.textSource === draft) { forgetText(record.key); void remove(record.key); continue; }
|
|
89
|
+
try {
|
|
90
|
+
const content = typeof record.text === "string" ? record.text : record.blob;
|
|
91
|
+
const file = new File([content], record.name, { type: record.type || "text/plain", lastModified: record.lastModified });
|
|
92
|
+
restored.push({ file, uploadID: record.key, textSource: record.textSource, textContent: record.text });
|
|
93
|
+
} catch { /* Skip a damaged record instead of failing the whole restore. */ }
|
|
94
|
+
}
|
|
95
|
+
return restored;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function readFiles() {
|
|
99
|
+
const db = await database(); if (!db) return [];
|
|
100
|
+
try {
|
|
101
|
+
const tx = db.transaction(STORE, "readonly");
|
|
102
|
+
const result = await done(tx.objectStore(STORE).getAll());
|
|
103
|
+
return Array.isArray(result) ? result : [];
|
|
104
|
+
} catch { return []; }
|
|
105
|
+
}
|
|
106
|
+
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
+
import { followsBottom } from "./message-window.js";
|
|
3
|
+
import { persist, forget, recover, forgetTextSource } from "./attachment-store.js";
|
|
2
4
|
|
|
3
5
|
const MAX_PARALLEL_UPLOADS = 2;
|
|
4
|
-
const
|
|
6
|
+
const MAX_BUFFERED_BYTES = 32 * 1024 * 1024; // Pasted files are small; larger ones stream to keep the heap bounded.
|
|
7
|
+
const TEXT_LIMIT = 5000;
|
|
5
8
|
const previewTypes = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp"]);
|
|
6
9
|
|
|
7
10
|
export function initAttachments(app) {
|
|
@@ -9,10 +12,45 @@ export function initAttachments(app) {
|
|
|
9
12
|
const drafts = new Map();
|
|
10
13
|
const statuses = new Map();
|
|
11
14
|
app.state.sendingRooms ||= new Set();
|
|
12
|
-
let limit = null, configRequest = null, activeUploads = 0;
|
|
15
|
+
let limit = null, configRequest = null, activeUploads = 0, eagerQueued = 0;
|
|
16
|
+
const converting = new Set(), restoring = new Set(), uploadWaiters = new Map();
|
|
17
|
+
let editorLock = null, unloadGuard = false;
|
|
13
18
|
const roomId = () => app.state.room?.id || "";
|
|
14
19
|
const filesFor = (id) => drafts.get(id) || [];
|
|
15
20
|
const markers = (items) => items.filter((item) => item.resource).map((item) => `[[resource:${item.resource.id}]]`);
|
|
21
|
+
const validResource = (resource, id) => /^[\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;
|
|
22
|
+
// crypto.randomUUID needs a secure context; the chat also runs on plain-HTTP LANs.
|
|
23
|
+
function newUploadID() {
|
|
24
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
25
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
26
|
+
const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
27
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
28
|
+
}
|
|
29
|
+
// Pasted files are read at paste time so a handle the browser cannot read fails
|
|
30
|
+
// as a read error, not later as a misleading network error. Eager reads only take
|
|
31
|
+
// the free upload slots; the rest read when they start uploading, so at most
|
|
32
|
+
// MAX_PARALLEL_UPLOADS buffers are held.
|
|
33
|
+
function releaseEager(item) {
|
|
34
|
+
if (item.eagerQueued) { item.eagerQueued = false; eagerQueued--; }
|
|
35
|
+
}
|
|
36
|
+
function releaseBuffer(item) {
|
|
37
|
+
item.buffer = null;
|
|
38
|
+
if (item.readPending) item.released = true;
|
|
39
|
+
else { item.read = null; releaseEager(item); }
|
|
40
|
+
}
|
|
41
|
+
function startRead(item, eager = false) {
|
|
42
|
+
if (!item.pasted || item.file.size > MAX_BUFFERED_BYTES) return null;
|
|
43
|
+
if (eager) {
|
|
44
|
+
if (activeUploads + eagerQueued >= MAX_PARALLEL_UPLOADS) return null;
|
|
45
|
+
item.eagerQueued = true; eagerQueued++;
|
|
46
|
+
}
|
|
47
|
+
const read = Promise.resolve().then(() => item.file.arrayBuffer());
|
|
48
|
+
item.read = read; item.readPending = true; item.released = false;
|
|
49
|
+
// Hold the eager slot until the read settles, even if the item is removed meanwhile.
|
|
50
|
+
const settle = () => { item.readPending = false; if (item.released) { item.read = null; releaseEager(item); } };
|
|
51
|
+
void read.then(settle, settle);
|
|
52
|
+
return read;
|
|
53
|
+
}
|
|
16
54
|
const textFor = (id, caption) => {
|
|
17
55
|
const parts = [String(caption || "").trim(), ...markers(filesFor(id))].filter(Boolean);
|
|
18
56
|
return { text: parts.join("\n\n"), ids: filesFor(id).filter((item) => item.resource).map((item) => item.resource.id) };
|
|
@@ -25,7 +63,9 @@ export function initAttachments(app) {
|
|
|
25
63
|
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[index]}`;
|
|
26
64
|
}
|
|
27
65
|
function preserveLayout(change) {
|
|
28
|
-
const thread = $("#thread")
|
|
66
|
+
const thread = $("#thread");
|
|
67
|
+
// A follower can sit a few lines above the edge while a restored draft grows the composer.
|
|
68
|
+
const atBottom = Boolean(roomId() && followsBottom(app, 0));
|
|
29
69
|
if (atBottom) { change(); thread.scrollTop = thread.scrollHeight; }
|
|
30
70
|
else if (roomId() && app.preserveReadingLayout) void app.preserveReadingLayout(change).catch(() => {});
|
|
31
71
|
else change();
|
|
@@ -37,8 +77,67 @@ export function initAttachments(app) {
|
|
|
37
77
|
});
|
|
38
78
|
}
|
|
39
79
|
function prepareMessage(id, caption) {
|
|
40
|
-
const items = filesFor(id), composed = textFor(id, caption);
|
|
41
|
-
|
|
80
|
+
const items = filesFor(id), composed = textFor(id, caption), body = String(caption || "");
|
|
81
|
+
const overLimit = composed.text.length > TEXT_LIMIT, question = Boolean(app.replyTargetFor?.(id)?.isQuestion);
|
|
82
|
+
// A prior attempt can already carry this text; reusing it avoids a second file.
|
|
83
|
+
const conversion = body.length > TEXT_LIMIT ? items.find((item) => item.textSource === body) : undefined;
|
|
84
|
+
const markerText = textFor(id, "").text, effective = conversion ? markerText : composed.text;
|
|
85
|
+
// Converting moves the draft into a file; the message then carries only resource markers.
|
|
86
|
+
const canConvert = overLimit && body.length > TEXT_LIMIT && markerText.length <= TEXT_LIMIT && !question && items.every((item) => item.status !== "failed");
|
|
87
|
+
return { ...composed, overLimit, conversion, canConvert, ready: Boolean(composed.text) && effective.length <= TEXT_LIMIT && items.every((item) => item.status === "uploaded") };
|
|
88
|
+
}
|
|
89
|
+
const pastedTextName = () => `pasted-text-${new Date().toISOString().slice(0, 19).replace(/\D/g, "")}.txt`;
|
|
90
|
+
// Mentions are stored as editor tokens; the file gets the visible text instead.
|
|
91
|
+
const plainText = (text) => String(text).replace(/<at>@([^<]+)<\/at>/g, "@$1");
|
|
92
|
+
const textFile = (text) => new File([text], pastedTextName(), { type: "text/plain" });
|
|
93
|
+
function persistItem(item, id) {
|
|
94
|
+
if (!item.pasted) return;
|
|
95
|
+
void persist(item, id).then((ok) => { if (!ok) persistenceFailed(id); });
|
|
96
|
+
}
|
|
97
|
+
function persistenceFailed(id) {
|
|
98
|
+
updateDurability();
|
|
99
|
+
setStatus("attachmentNotPersisted", true, id);
|
|
100
|
+
}
|
|
101
|
+
function warnUnload(event) { event.preventDefault(); event.returnValue = ""; }
|
|
102
|
+
function updateDurability() {
|
|
103
|
+
const unsafe = [...drafts.values()].flat().some((item) => item.durable === false);
|
|
104
|
+
if (unsafe && !unloadGuard) { window.onbeforeunload = warnUnload; unloadGuard = true; }
|
|
105
|
+
else if (!unsafe && unloadGuard) { window.onbeforeunload = null; unloadGuard = false; }
|
|
106
|
+
const id = roomId(), hint = $("#attachmentVolatile"), volatile = filesFor(id).some((item) => item.durable === false);
|
|
107
|
+
hint.textContent = app.t(volatile ? "attachmentNotPersisted" : "attachmentVolatile");
|
|
108
|
+
hint.classList.toggle("danger-text", volatile);
|
|
109
|
+
}
|
|
110
|
+
async function restoreRoom(id) {
|
|
111
|
+
if (restoring.has(id)) return;
|
|
112
|
+
restoring.add(id);
|
|
113
|
+
try {
|
|
114
|
+
const restored = await recover(id, app.state.drafts.get(id) || "");
|
|
115
|
+
const existing = filesFor(id), keys = new Set(existing.map((item) => item.uploadID)), items = [...existing];
|
|
116
|
+
for (const record of restored) {
|
|
117
|
+
if (keys.has(record.uploadID)) continue;
|
|
118
|
+
keys.add(record.uploadID);
|
|
119
|
+
items.push({ ...record, pasted: true, status: "queued", buffer: undefined, read: undefined, retried: false, loaded: 0, percent: 0, cancelled: false, durable: true });
|
|
120
|
+
}
|
|
121
|
+
if (items.length === existing.length) return;
|
|
122
|
+
drafts.set(id, items);
|
|
123
|
+
if (roomId() === id) { render(); pump(); }
|
|
124
|
+
} finally {
|
|
125
|
+
restoring.delete(id);
|
|
126
|
+
if (roomId() === id) app.updateSendState();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function lockComposer() {
|
|
130
|
+
if (editorLock) return;
|
|
131
|
+
editorLock = { editable: input.contentEditable, disabled: input.getAttribute("aria-disabled"), busy: input.getAttribute("aria-busy"), selection: input.getSelectionOffsets?.() || null };
|
|
132
|
+
input.contentEditable = "false"; input.setAttribute("aria-disabled", "true"); input.setAttribute("aria-busy", "true");
|
|
133
|
+
}
|
|
134
|
+
function unlockComposer() {
|
|
135
|
+
if (!editorLock) return;
|
|
136
|
+
input.contentEditable = "true";
|
|
137
|
+
input.setAttribute("aria-disabled", editorLock.disabled ?? "false");
|
|
138
|
+
if (editorLock.busy === null) input.removeAttribute("aria-busy"); else input.setAttribute("aria-busy", editorLock.busy);
|
|
139
|
+
const selection = editorLock.selection; editorLock = null;
|
|
140
|
+
if (selection) input.setSelectionRange?.(selection[0], selection[1]);
|
|
42
141
|
}
|
|
43
142
|
app.prepareMessage = prepareMessage;
|
|
44
143
|
const baseDraftCount = app.updateDraftCount;
|
|
@@ -50,11 +149,11 @@ export function initAttachments(app) {
|
|
|
50
149
|
};
|
|
51
150
|
app.updateSendState = () => {
|
|
52
151
|
const id = roomId(), message = id && prepareMessage(id, input.value);
|
|
53
|
-
$("#btnSend").disabled = !id || !message?.ready || app.state.sendingRooms.has(id);
|
|
152
|
+
$("#btnSend").disabled = !id || !(message?.ready || message?.canConvert) || app.state.sendingRooms.has(id) || converting.has(id) || restoring.has(id);
|
|
54
153
|
};
|
|
55
154
|
app.completeAttachments = (id, resourceIDs) => {
|
|
56
155
|
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);
|
|
156
|
+
for (const item of removed) { forget(item); if (item.previewUrl) URL.revokeObjectURL(item.previewUrl); }
|
|
58
157
|
const remaining = items.filter((item) => !used.has(item.resource?.id));
|
|
59
158
|
if (remaining.length) drafts.set(id, remaining); else { drafts.delete(id); statuses.delete(id); }
|
|
60
159
|
if (roomId() === id) render();
|
|
@@ -75,6 +174,7 @@ export function initAttachments(app) {
|
|
|
75
174
|
});
|
|
76
175
|
const status = statuses.get(id); $("#attachmentStatus").textContent = status?.key ? app.t(status.key, status.values) : "";
|
|
77
176
|
if (status?.key) tray.hidden = false;
|
|
177
|
+
updateDurability();
|
|
78
178
|
}
|
|
79
179
|
function render() {
|
|
80
180
|
preserveLayout(() => {
|
|
@@ -83,6 +183,7 @@ export function initAttachments(app) {
|
|
|
83
183
|
$("#attachmentStatus").textContent = savedStatus?.key ? app.t(savedStatus.key, savedStatus.values) : ""; $("#attachmentStatus").classList.toggle("danger-text", Boolean(savedStatus?.error));
|
|
84
184
|
list.replaceChildren();
|
|
85
185
|
items.forEach((item, index) => { const row = renderItem(item); row.dataset.index = String(index); list.append(row); });
|
|
186
|
+
updateDurability();
|
|
86
187
|
app.updateDraftCount(); app.updateSendState();
|
|
87
188
|
});
|
|
88
189
|
}
|
|
@@ -90,7 +191,7 @@ export function initAttachments(app) {
|
|
|
90
191
|
function renderItem(item) {
|
|
91
192
|
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
193
|
row.className = "attachment-item"; preview.className = "attachment-preview";
|
|
93
|
-
if (previewTypes.has(item.file.type)) {
|
|
194
|
+
if (previewTypes.has(item.file.type) && item.errorKey !== "fileUnreadable") {
|
|
94
195
|
item.previewUrl ||= URL.createObjectURL(item.file);
|
|
95
196
|
const image = document.createElement("img"); image.src = item.previewUrl; image.alt = ""; preview.append(image);
|
|
96
197
|
} else preview.textContent = item.file.name.split(".").at(-1)?.slice(0, 4).toUpperCase() || "FILE";
|
|
@@ -108,8 +209,9 @@ export function initAttachments(app) {
|
|
|
108
209
|
function action(kind, label) {
|
|
109
210
|
const button = document.createElement("button"); button.type = "button"; button.dataset.uploadAction = kind; button.textContent = label; button.setAttribute("aria-label", label); return button;
|
|
110
211
|
}
|
|
111
|
-
function removeItem(id, item) {
|
|
112
|
-
item.cancelled = true; item.xhr?.abort();
|
|
212
|
+
function removeItem(id, item, purge = true) {
|
|
213
|
+
item.cancelled = true; item.xhr?.abort(); releaseBuffer(item);
|
|
214
|
+
if (purge) forget(item);
|
|
113
215
|
if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
114
216
|
const remaining = filesFor(id).filter((entry) => entry !== item);
|
|
115
217
|
if (remaining.length) {
|
|
@@ -117,10 +219,12 @@ export function initAttachments(app) {
|
|
|
117
219
|
if (statuses.get(id)?.error && !remaining.some((entry) => entry.status === "failed")) statuses.delete(id);
|
|
118
220
|
} else { drafts.delete(id); statuses.delete(id); }
|
|
119
221
|
if (roomId() === id) render();
|
|
222
|
+
settleUploads(id);
|
|
120
223
|
}
|
|
121
224
|
function clearRoom(id) {
|
|
122
|
-
for (const item of [...filesFor(id)]) removeItem(id, item);
|
|
225
|
+
for (const item of [...filesFor(id)]) removeItem(id, item, false);
|
|
123
226
|
drafts.delete(id); statuses.delete(id);
|
|
227
|
+
settleUploads(id);
|
|
124
228
|
}
|
|
125
229
|
app.disposeRoomAttachments = clearRoom;
|
|
126
230
|
function getLimit(refresh = false) {
|
|
@@ -140,7 +244,7 @@ export function initAttachments(app) {
|
|
|
140
244
|
while (activeUploads < MAX_PARALLEL_UPLOADS) {
|
|
141
245
|
const next = [...drafts].flatMap(([id, items]) => items.map((item) => ({ id, item }))).find(({ item }) => item.status === "queued");
|
|
142
246
|
if (!next) return;
|
|
143
|
-
activeUploads++; next.item.status = "uploading"; next.item.percent = 0;
|
|
247
|
+
activeUploads++; releaseEager(next.item); next.item.status = "uploading"; next.item.percent = 0;
|
|
144
248
|
if (roomId() === next.id) render();
|
|
145
249
|
void uploadItem(next.id, next.item);
|
|
146
250
|
}
|
|
@@ -151,23 +255,65 @@ export function initAttachments(app) {
|
|
|
151
255
|
try { max = await getLimit(item.refreshLimit); } catch {}
|
|
152
256
|
item.refreshLimit = false;
|
|
153
257
|
if (item.cancelled) return;
|
|
154
|
-
if (max !== null && item.file.size > max) { item.errorKey = "fileTooLarge"; item.status = "failed"; if (roomId() === id) setStatus(item.errorKey, true, id); return; }
|
|
155
|
-
item.
|
|
258
|
+
if (max !== null && item.file.size > max) { releaseBuffer(item); item.errorKey = "fileTooLarge"; item.status = "failed"; if (roomId() === id) setStatus(item.errorKey, true, id); return; }
|
|
259
|
+
if (item.pasted && item.file.size <= MAX_BUFFERED_BYTES) {
|
|
260
|
+
try {
|
|
261
|
+
const buffer = await (item.read ?? startRead(item));
|
|
262
|
+
if (item.cancelled) return;
|
|
263
|
+
item.buffer = buffer;
|
|
264
|
+
} catch {
|
|
265
|
+
releaseBuffer(item);
|
|
266
|
+
if (item.cancelled) return;
|
|
267
|
+
item.errorKey = "fileUnreadable"; item.errorValues = null; item.status = "failed";
|
|
268
|
+
if (roomId() === id) setStatus("fileUnreadable", true, id);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
item.resource = await sendUpload(id, item);
|
|
156
273
|
if (item.cancelled) return;
|
|
157
|
-
item.status = "uploaded"; item.loaded = item.file.size; item.percent = 100;
|
|
158
|
-
if (roomId() === id && filesFor(id).every((entry) => entry.status === "uploaded")) setStatus("uploadReady");
|
|
274
|
+
item.status = "uploaded"; item.loaded = item.file.size; item.percent = 100; releaseBuffer(item);
|
|
275
|
+
if (roomId() === id && filesFor(id).every((entry) => entry.status === "uploaded")) setStatus(filesFor(id).some((entry) => entry.durable === false) ? "attachmentNotPersisted" : "uploadReady");
|
|
159
276
|
} catch (error) {
|
|
277
|
+
releaseBuffer(item);
|
|
160
278
|
if (item.cancelled) return;
|
|
161
279
|
if (error.status === 413) { limit = null; item.errorKey = "fileTooLarge"; }
|
|
162
|
-
else item.errorKey = "
|
|
280
|
+
else if (error.unreadable) item.errorKey = "fileUnreadable";
|
|
281
|
+
else { item.errorKey = "uploadFailed"; item.errorValues = { reason: error.status ? `HTTP ${error.status}` : error.timeout ? "timeout" : error.network ? "network" : error.message }; }
|
|
163
282
|
item.status = "failed";
|
|
164
283
|
if (roomId() === id) setStatus(item.errorKey, true, id, item.errorValues || {});
|
|
165
284
|
} finally {
|
|
166
285
|
activeUploads--;
|
|
167
286
|
if (roomId() === id) render();
|
|
168
287
|
pump();
|
|
288
|
+
settleUploads(id);
|
|
169
289
|
}
|
|
170
290
|
}
|
|
291
|
+
// One fallback after a network failure: a lost response is recovered by ID, and a
|
|
292
|
+
// file the XHR could not send is retried once from bytes read into memory.
|
|
293
|
+
async function sendUpload(id, item) {
|
|
294
|
+
try { return await upload(id, item); }
|
|
295
|
+
catch (error) {
|
|
296
|
+
if (!error.network || item.cancelled || item.retried) throw error;
|
|
297
|
+
item.retried = true; item.loaded = 0; item.percent = 0;
|
|
298
|
+
const existing = await findUploaded(id, item);
|
|
299
|
+
if (item.cancelled) throw error;
|
|
300
|
+
if (existing) return existing;
|
|
301
|
+
if (item.buffer === undefined && item.file.size <= MAX_BUFFERED_BYTES) {
|
|
302
|
+
try { item.buffer = await item.file.arrayBuffer(); }
|
|
303
|
+
catch { if (item.cancelled) throw error; throw Object.assign(new Error("Upload unreadable"), { unreadable: true }); }
|
|
304
|
+
}
|
|
305
|
+
if (item.cancelled || !item.buffer) throw error;
|
|
306
|
+
return upload(id, item);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
async function findUploaded(id, item) {
|
|
310
|
+
try {
|
|
311
|
+
const response = await fetch(`/rooms/${encodeURIComponent(id)}/resources/${item.uploadID}`, { headers: LS.token ? { Authorization: `Bearer ${LS.token}` } : {} });
|
|
312
|
+
if (!response.ok) return undefined;
|
|
313
|
+
const resource = (await response.json()).resource;
|
|
314
|
+
return validResource(resource, id) && resource.name === item.file.name && resource.uploaderSessionID === LS.sessionID ? resource : undefined;
|
|
315
|
+
} catch { return undefined; }
|
|
316
|
+
}
|
|
171
317
|
function upload(id, item) {
|
|
172
318
|
return new Promise((resolve, reject) => {
|
|
173
319
|
const xhr = new XMLHttpRequest(); item.xhr = xhr;
|
|
@@ -175,6 +321,7 @@ export function initAttachments(app) {
|
|
|
175
321
|
xhr.setRequestHeader("Content-Type", "application/octet-stream");
|
|
176
322
|
xhr.setRequestHeader("X-Session-ID", LS.sessionID);
|
|
177
323
|
xhr.setRequestHeader("X-File-Name", encodeURIComponent(item.file.name));
|
|
324
|
+
xhr.setRequestHeader("X-Resource-ID", item.uploadID);
|
|
178
325
|
if (LS.token) xhr.setRequestHeader("Authorization", `Bearer ${LS.token}`);
|
|
179
326
|
xhr.timeout = 1800000;
|
|
180
327
|
xhr.upload.onprogress = (event) => {
|
|
@@ -189,27 +336,91 @@ export function initAttachments(app) {
|
|
|
189
336
|
if (xhr.status !== 201) return reject(Object.assign(new Error("Upload failed"), { status: xhr.status }));
|
|
190
337
|
try {
|
|
191
338
|
const resource = JSON.parse(xhr.responseText).resource;
|
|
192
|
-
if (
|
|
339
|
+
if (!validResource(resource, id)) throw new Error("Invalid resource response");
|
|
193
340
|
resolve(resource);
|
|
194
341
|
} catch { reject(new Error("Invalid resource response")); }
|
|
195
342
|
};
|
|
343
|
+
// A browser can surface a file handle it cannot read (cloud placeholder, network
|
|
344
|
+
// drive, cleaned temp file) as a bare network error; XHR exposes no finer cause.
|
|
196
345
|
xhr.onerror = () => { item.xhr = null; reject(Object.assign(new Error("Upload failed"), { network: true })); };
|
|
197
346
|
xhr.ontimeout = () => { item.xhr = null; reject(Object.assign(new Error("Upload timed out"), { timeout: true })); };
|
|
198
347
|
xhr.onabort = () => { item.xhr = null; reject(Object.assign(new Error("Upload cancelled"), { aborted: true })); };
|
|
199
|
-
xhr.send(item.file);
|
|
348
|
+
xhr.send(item.buffer ?? item.file);
|
|
200
349
|
});
|
|
201
350
|
}
|
|
202
|
-
function addFiles(files) {
|
|
351
|
+
function addFiles(files, pasted = false, meta = {}) {
|
|
203
352
|
const id = roomId(); if (!id) return;
|
|
204
353
|
const accepted = [...files].filter((file) => file instanceof File);
|
|
205
354
|
if (!accepted.length) return;
|
|
206
355
|
const items = filesFor(id);
|
|
207
|
-
|
|
356
|
+
accepted.forEach((file, index) => {
|
|
357
|
+
const item = { file, uploadID: newUploadID(), pasted, buffer: undefined, read: undefined, retried: false, status: "queued", loaded: 0, percent: 0, cancelled: false, ...(index ? {} : meta) };
|
|
358
|
+
items.push(item);
|
|
359
|
+
if (pasted) { startRead(item, true); persistItem(item, id); }
|
|
360
|
+
});
|
|
208
361
|
drafts.set(id, items); setStatus(""); render(); pump();
|
|
209
362
|
}
|
|
363
|
+
function settleUploads(id) {
|
|
364
|
+
const waiters = uploadWaiters.get(id);
|
|
365
|
+
if (!waiters) return;
|
|
366
|
+
const items = filesFor(id);
|
|
367
|
+
if (items.some((item) => item.status === "queued" || item.status === "uploading")) return;
|
|
368
|
+
uploadWaiters.delete(id);
|
|
369
|
+
const uploaded = items.length > 0 && items.every((item) => item.status === "uploaded");
|
|
370
|
+
for (const resolve of waiters) resolve(uploaded);
|
|
371
|
+
}
|
|
372
|
+
function waitForUploads(id) {
|
|
373
|
+
return new Promise((resolve) => {
|
|
374
|
+
uploadWaiters.set(id, [...(uploadWaiters.get(id) || []), resolve]);
|
|
375
|
+
settleUploads(id);
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
const baseSend = app.send;
|
|
379
|
+
app.send = async () => {
|
|
380
|
+
const id = roomId();
|
|
381
|
+
if (!id || converting.has(id) || restoring.has(id) || app.state.sendingRooms.has(id)) return false;
|
|
382
|
+
const message = prepareMessage(id, input.value);
|
|
383
|
+
if (!message.canConvert) return baseSend();
|
|
384
|
+
const requested = input.value, revision = app.state.draftRevision.get(id) || 0, replyId = app.replyTargetFor?.(id)?.id;
|
|
385
|
+
converting.add(id);
|
|
386
|
+
lockComposer();
|
|
387
|
+
app.saveDraft(id, input.draftValue);
|
|
388
|
+
let item = message.conversion;
|
|
389
|
+
try {
|
|
390
|
+
if (!item) {
|
|
391
|
+
const content = plainText(requested), attachment = textFile(content);
|
|
392
|
+
addFiles([attachment], true, { textSource: requested, textContent: content });
|
|
393
|
+
item = filesFor(id).find((entry) => entry.file === attachment);
|
|
394
|
+
}
|
|
395
|
+
setStatus("sendAsFile", false, id, { count: requested.length });
|
|
396
|
+
if (!(await waitForUploads(id))) {
|
|
397
|
+
if (roomId() === id) {
|
|
398
|
+
if (item?.status === "failed") setStatus("sendAsFileFailed", true, id);
|
|
399
|
+
else if (!item) setStatus("");
|
|
400
|
+
}
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
if (roomId() !== id) return false;
|
|
404
|
+
const changed = (app.state.draftRevision.get(id) || 0) !== revision || app.replyTargetFor?.(id)?.id !== replyId;
|
|
405
|
+
if (changed) { setStatus("uploadReady"); return false; }
|
|
406
|
+
// The composer stayed locked, so clearing it now cannot drop text typed during the upload.
|
|
407
|
+
unlockComposer();
|
|
408
|
+
input.value = "";
|
|
409
|
+
app.clearDraft(id);
|
|
410
|
+
const sent = await baseSend();
|
|
411
|
+
if (sent) forgetTextSource(id, requested);
|
|
412
|
+
return sent;
|
|
413
|
+
} finally {
|
|
414
|
+
converting.delete(id);
|
|
415
|
+
if (roomId() === id) { unlockComposer(); app.updateDraftCount(); app.updateSendState(); }
|
|
416
|
+
else editorLock = null;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
210
419
|
function retryItem(item) {
|
|
211
420
|
if (item.status !== "failed") return;
|
|
212
|
-
|
|
421
|
+
if (item.errorKey === "fileUnreadable") item.read = null;
|
|
422
|
+
item.refreshLimit = item.errorKey === "fileTooLarge"; item.status = "queued"; item.errorKey = ""; item.errorValues = null; item.loaded = 0; item.percent = 0; item.retried = false;
|
|
423
|
+
if (item.pasted && !item.readPending) startRead(item, true);
|
|
213
424
|
if (roomId()) setStatus(""); render(); pump();
|
|
214
425
|
}
|
|
215
426
|
$("#btnAddAttachments").addEventListener("click", () => picker.click());
|
|
@@ -229,15 +440,24 @@ export function initAttachments(app) {
|
|
|
229
440
|
chatView.addEventListener("dragover", (event) => { if (!hasFiles(event)) return; event.preventDefault(); event.dataTransfer.dropEffect = "copy"; showDrop(); });
|
|
230
441
|
chatView.addEventListener("dragleave", (event) => { if (hasFiles(event) && !chatView.contains(event.relatedTarget)) clearDrop(); });
|
|
231
442
|
chatView.addEventListener("drop", (event) => { if (!hasFiles(event)) return; event.preventDefault(); clearDrop(); addFiles(event.dataTransfer.files); });
|
|
443
|
+
// Capture before the editor's paste handler: an oversized paste never enters the DOM.
|
|
232
444
|
input.addEventListener("paste", (event) => {
|
|
445
|
+
const text = event.clipboardData?.getData("text/plain") || "";
|
|
446
|
+
if (text.length > TEXT_LIMIT && roomId() && input.contentEditable === "true") {
|
|
447
|
+
event.preventDefault();
|
|
448
|
+
const files = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file").map((item) => item.getAsFile()).filter(Boolean);
|
|
449
|
+
addFiles([textFile(text), ...files], true, { textSource: text, textContent: text });
|
|
450
|
+
setStatus("pasteAsFile", false, roomId(), { count: text.length });
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
233
453
|
const images = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file" && item.type.startsWith("image/")).map((item) => item.getAsFile()).filter(Boolean);
|
|
234
454
|
if (!images.length) return;
|
|
235
455
|
if (!event.clipboardData.getData("text/plain")) event.preventDefault();
|
|
236
|
-
addFiles(images);
|
|
237
|
-
});
|
|
456
|
+
addFiles(images, true);
|
|
457
|
+
}, true);
|
|
238
458
|
document.addEventListener("chat-room-activated", (event) => {
|
|
239
459
|
render(); const id = event.detail; $("#btnAddAttachments").disabled = !id;
|
|
240
|
-
void getLimit().catch(() => {});
|
|
460
|
+
void restoreRoom(id); void getLimit().catch(() => {});
|
|
241
461
|
});
|
|
242
462
|
render();
|
|
243
463
|
}
|