@alexsun-top/opencode-chat-room 0.8.4 → 0.8.5

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.
Files changed (136) hide show
  1. package/CHANGELOG.md +5 -1
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/cli.ts +1 -1
  5. package/dist/cli.js +35 -16
  6. package/package.json +14 -11
  7. package/packages/chat-room-channeld/README.md +3 -2
  8. package/packages/chat-room-channeld/src/inbound.ts +3 -6
  9. package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
  10. package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
  11. package/packages/chat-room-channeld/src/pg/worker.mjs +107 -99
  12. package/packages/chat-room-channeld/src/pg/worker.mts +166 -0
  13. package/plugin.ts +1 -1
  14. package/server/assets/chat/admin.js +4 -1
  15. package/server/assets/chat/announcements.js +3 -0
  16. package/server/assets/chat/attachments.js +3 -3
  17. package/server/assets/chat/clipboard.js +1 -1
  18. package/server/assets/chat/copy-action.js +1 -1
  19. package/server/assets/chat/doc-preview.js +1 -1
  20. package/server/assets/chat/editor.js +11 -7
  21. package/server/assets/chat/events.js +7 -5
  22. package/server/assets/chat/files.js +5 -1
  23. package/server/assets/chat/integration-editor.js +2 -0
  24. package/server/assets/chat/integrations.js +1 -1
  25. package/server/assets/chat/join-requests.js +1 -1
  26. package/server/assets/chat/markdown-footnotes.js +8 -7
  27. package/server/assets/chat/markdown.js +6 -5
  28. package/server/assets/chat/members.js +3 -3
  29. package/server/assets/chat/mentions.js +8 -5
  30. package/server/assets/chat/message-cache.js +1 -1
  31. package/server/assets/chat/message-polling.js +2 -2
  32. package/server/assets/chat/message-window.js +1 -1
  33. package/server/assets/chat/messages.js +17 -3
  34. package/server/assets/chat/office-preview.js +3 -3
  35. package/server/assets/chat/palette.js +5 -3
  36. package/server/assets/chat/panels.js +19 -0
  37. package/server/assets/chat/questions.js +3 -2
  38. package/server/assets/chat/reminders.js +3 -0
  39. package/server/assets/chat/replies.js +6 -3
  40. package/server/assets/chat/resource-format.js +2 -2
  41. package/server/assets/chat/rooms.js +7 -4
  42. package/server/assets/chat/settings.js +4 -3
  43. package/server/assets/chat/shortcuts.js +3 -1
  44. package/server/assets/chat/side-pane.js +1 -1
  45. package/server/assets/chat/state.js +30 -11
  46. package/server/assets/chat/system-events.js +3 -2
  47. package/server/assets/chat/system-messages.js +15 -15
  48. package/server/assets/chat/tasks.js +4 -3
  49. package/server/assets/chat/window-controls.js +3 -2
  50. package/server/assets/conversation.css +14 -2
  51. package/server/assets/doc-preview.css +6 -0
  52. package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
  53. package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
  54. package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
  55. package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
  56. package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
  57. package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
  58. package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
  59. package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
  60. package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
  61. package/server/sw.js +3 -1
  62. package/skills/chatroom/SKILL.md +9 -0
  63. package/src/README.md +1 -1
  64. package/src/agent/agent-receipts.ts +12 -4
  65. package/src/center/center-client.ts +1 -1
  66. package/src/state/pg-sql.mjs +157 -142
  67. package/src/state/pg-sql.mts +175 -0
  68. package/src/state/pg-worker.mjs +107 -99
  69. package/src/state/pg-worker.mts +166 -0
  70. package/src/state/store.ts +21 -7
  71. package/src/tui/app-types.mjs +1 -0
  72. package/src/tui/app-types.mts +175 -0
  73. package/src/tui/app.mjs +426 -423
  74. package/src/tui/app.mts +500 -0
  75. package/src/tui/config.mjs +166 -158
  76. package/src/tui/config.mts +247 -0
  77. package/src/tui/http.mjs +239 -206
  78. package/src/tui/http.mts +412 -0
  79. package/src/tui/i18n.mjs +17 -20
  80. package/src/tui/i18n.mts +42 -0
  81. package/src/tui/info-app.mjs +431 -427
  82. package/src/tui/info-app.mts +500 -0
  83. package/src/tui/info-content.mjs +205 -199
  84. package/src/tui/info-content.mts +341 -0
  85. package/src/tui/join-app.mjs +75 -64
  86. package/src/tui/join-app.mts +99 -0
  87. package/src/tui/locales/en.mjs +302 -320
  88. package/src/tui/locales/en.mts +349 -0
  89. package/src/tui/locales/zh-CN.mjs +302 -320
  90. package/src/tui/locales/zh-CN.mts +349 -0
  91. package/src/tui/main.mjs +219 -213
  92. package/src/tui/main.mts +255 -0
  93. package/src/tui/markdown.mjs +128 -272
  94. package/src/tui/markdown.mts +152 -0
  95. package/src/tui/mentions.mjs +181 -184
  96. package/src/tui/mentions.mts +251 -0
  97. package/src/tui/message-app.mjs +181 -173
  98. package/src/tui/message-app.mts +213 -0
  99. package/src/tui/message-view.mjs +90 -111
  100. package/src/tui/message-view.mts +151 -0
  101. package/src/tui/messages.mjs +55 -49
  102. package/src/tui/messages.mts +106 -0
  103. package/src/tui/palette-app.mjs +364 -344
  104. package/src/tui/palette-app.mts +388 -0
  105. package/src/tui/palette.mjs +100 -98
  106. package/src/tui/palette.mts +176 -0
  107. package/src/tui/prefs.mjs +56 -63
  108. package/src/tui/prefs.mts +126 -0
  109. package/src/tui/reminder-app.mjs +191 -181
  110. package/src/tui/reminder-app.mts +228 -0
  111. package/src/tui/room-settings-app.mjs +257 -242
  112. package/src/tui/room-settings-app.mts +301 -0
  113. package/src/tui/session.mjs +30 -29
  114. package/src/tui/session.mts +51 -0
  115. package/src/tui/settings-app.mjs +151 -138
  116. package/src/tui/settings-app.mts +179 -0
  117. package/src/tui/ui-content.mjs +426 -421
  118. package/src/tui/ui-content.mts +499 -0
  119. package/src/tui/ui-help.mjs +58 -67
  120. package/src/tui/ui-help.mts +87 -0
  121. package/src/tui/ui-mentions.mjs +34 -36
  122. package/src/tui/ui-mentions.mts +60 -0
  123. package/src/tui/ui-overlay-view.mjs +259 -267
  124. package/src/tui/ui-overlay-view.mts +322 -0
  125. package/src/tui/ui-suggest-view.mjs +54 -57
  126. package/src/tui/ui-suggest-view.mts +78 -0
  127. package/src/tui/ui-suggest.mjs +164 -167
  128. package/src/tui/ui-suggest.mts +248 -0
  129. package/src/tui/ui-theme.mjs +52 -57
  130. package/src/tui/ui-theme.mts +98 -0
  131. package/src/tui/ui-view.mjs +267 -275
  132. package/src/tui/ui-view.mts +308 -0
  133. package/src/tui/ui.mjs +372 -359
  134. package/src/tui/ui.mts +440 -0
  135. package/src/tui/wire.mjs +215 -0
  136. package/src/tui/wire.mts +383 -0
@@ -61,6 +61,8 @@ export function initIntegrationEditor(app, options) {
61
61
  return;
62
62
  }
63
63
  const first = result.errors[0];
64
+ if (!first)
65
+ return;
64
66
  error.textContent = app.t("integrationsRulesErrors", {
65
67
  count: result.errors.length,
66
68
  first: `Line ${first.line}: ${first.message}`,
@@ -513,7 +513,7 @@ export function initIntegrations(app) {
513
513
  accountSchemaField.hidden = accountSchema.hidden;
514
514
  // Without a declared schema the raw env rows are the only way to configure
515
515
  // the account, so keep them open; schema-backed plugins can collapse them.
516
- accountAdvanced.open = accountSchema.hidden;
516
+ accountAdvanced.open = Boolean(accountSchema.hidden);
517
517
  };
518
518
  const openAccount = (account = null, presetPlugin = "") => {
519
519
  if (data.editable === false)
@@ -72,7 +72,7 @@ export function initJoinRequests(app) {
72
72
  clearTimeout(pending.timer);
73
73
  if (!pending.roomId || pending.status !== "pending")
74
74
  return;
75
- pending.timer = setTimeout(() => void checkPending(), delay);
75
+ pending.timer = window.setTimeout(() => void checkPending(), delay);
76
76
  }
77
77
  async function checkPending() {
78
78
  if (pending.checking || !pending.roomId || pending.status !== "pending")
@@ -18,24 +18,25 @@ function maskCode(value, nonce) {
18
18
  blocks.push(line);
19
19
  return key;
20
20
  }),
21
- restore: (text) => text.replace(new RegExp(`CHATCODETOKEN${nonce}(\\d+)END`, "g"), (_, index) => blocks[Number(index)]),
21
+ restore: (text) => text.replace(new RegExp(`CHATCODETOKEN${nonce}(\\d+)END`, "g"), (_, index) => blocks[Number(index)] ?? ""),
22
22
  };
23
23
  }
24
24
  export function prepareFootnotes(value, nonce) {
25
25
  const code = maskCode(value, nonce);
26
26
  const lines = code.masked.split("\n"), definitions = new Map(), kept = [];
27
27
  for (let index = 0; index < lines.length; index++) {
28
- const match = /^ {0,3}\[\^([^\]\s]+)\]:[ \t]*(.*)$/.exec(lines[index]);
28
+ const line = lines[index] ?? "";
29
+ const match = /^ {0,3}\[\^([^\]\s]+)\]:[ \t]*(.*)$/.exec(line);
29
30
  if (!match) {
30
- kept.push(lines[index]);
31
+ kept.push(line);
31
32
  continue;
32
33
  }
33
- let body = match[2].trim();
34
- while (index + 1 < lines.length && /^(?: {2,}|\t)/.test(lines[index + 1])) {
34
+ let body = (match[2] ?? "").trim();
35
+ while (index + 1 < lines.length && /^(?: {2,}|\t)/.test(lines[index + 1] ?? "")) {
35
36
  index++;
36
- body += `\n${lines[index].replace(/^(?: {2,4}|\t)/, "")}`;
37
+ body += `\n${(lines[index] ?? "").replace(/^(?: {2,4}|\t)/, "")}`;
37
38
  }
38
- definitions.set(match[1], code.restore(body));
39
+ definitions.set(match[1] ?? "", code.restore(body));
39
40
  kept.push("");
40
41
  }
41
42
  const references = new Map(), tokens = [], tokenLabels = [];
@@ -37,7 +37,7 @@ function sanitizerKeepsTag(name) {
37
37
  return keeps;
38
38
  }
39
39
  function escapeHtmlText(value) {
40
- return String(value).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char]));
40
+ return String(value).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char] ?? char));
41
41
  }
42
42
  /**
43
43
  * Render plain text that may contain resource markers into attachment cards.
@@ -97,9 +97,10 @@ export function renderMarkdown(root, text, app) {
97
97
  for (const code of codeBlocks)
98
98
  void enhanceCodeElement(code);
99
99
  for (let i = 0; i < diagramNodes.length; i++) {
100
+ const node = diagramNodes[i];
100
101
  const source = diagrams.get(`CHATDIAGRAM${nonce}${i}END`);
101
- if (!isUnsafeDiagram(source))
102
- void renderDiagram(diagramNodes[i], source, app);
102
+ if (node && !isUnsafeDiagram(source))
103
+ void renderDiagram(node, source, app);
103
104
  }
104
105
  for (const resource of resources)
105
106
  void loadResourceCard(resource.card, resource.roomId ?? "", app);
@@ -192,7 +193,7 @@ async function copyCode(button, code, app) {
192
193
  const key = copied ? "copiedMessage" : "copyMessageFailed";
193
194
  button.setAttribute("aria-label", app.t(key));
194
195
  button.title = app.t(key);
195
- button._feedbackTimer = setTimeout(() => {
196
+ button._feedbackTimer = window.setTimeout(() => {
196
197
  button.classList.remove("is-copied", "is-copy-failed");
197
198
  button.setAttribute("aria-label", app.t("copyMessage"));
198
199
  button.title = app.t("copyMessage");
@@ -259,7 +260,7 @@ async function loadResourceCard(card, roomId, app) {
259
260
  const result = await app.api(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(id)}`);
260
261
  if (!card.isConnected)
261
262
  return;
262
- const resource = result.resource, type = String(resource.mimeType).split(";")[0].toLowerCase();
263
+ const resource = result.resource, type = (String(resource.mimeType).split(";")[0] ?? "").toLowerCase();
263
264
  card.setAttribute("aria-label", resource.name);
264
265
  const info = document.createElement("span"), name = document.createElement("span"), size = document.createElement("span"), actions = document.createElement("span"), status = document.createElement("span");
265
266
  info.className = "resource-info";
@@ -102,7 +102,7 @@ export function initMembers(app) {
102
102
  memberEmpty.hidden = members.length > 0;
103
103
  void app.refreshJoinRequests?.();
104
104
  app.queueReceiptObservation?.();
105
- app.state.memberRefreshTimer = setTimeout(() => {
105
+ app.state.memberRefreshTimer = window.setTimeout(() => {
106
106
  if (current(app, room.id, generation) && !document.hidden)
107
107
  void app.loadManageableMembers();
108
108
  }, 5000);
@@ -114,7 +114,7 @@ export function initMembers(app) {
114
114
  else if (status === 404)
115
115
  app.state.memberApiUnavailable.add(room.id);
116
116
  else if (current(app, room.id, generation) && !document.hidden)
117
- app.state.memberRefreshTimer = setTimeout(() => void app.loadManageableMembers(), 5000);
117
+ app.state.memberRefreshTimer = window.setTimeout(() => void app.loadManageableMembers(), 5000);
118
118
  }
119
119
  };
120
120
  app.loadVisibleReceipts = async (roomId, generation = app.state.pollGeneration) => {
@@ -138,7 +138,7 @@ export function initMembers(app) {
138
138
  app.queueReceiptRefresh = () => {
139
139
  clearTimeout(app.state.receiptRefreshTimer);
140
140
  const roomId = app.state.room?.id, generation = app.state.pollGeneration;
141
- app.state.receiptRefreshTimer = setTimeout(() => void app.loadVisibleReceipts(roomId, generation), 180);
141
+ app.state.receiptRefreshTimer = window.setTimeout(() => void app.loadVisibleReceipts(roomId, generation), 180);
142
142
  };
143
143
  app.queueReceiptObservation = () => {
144
144
  if ((app.state.resizeScrollAdjusting || app.state.layoutScrollAdjusting)
@@ -97,9 +97,12 @@ export function initMentions(app) {
97
97
  }
98
98
  if (event.key === "Enter" || event.key === "Tab") {
99
99
  if (mention.items.length) {
100
- event.preventDefault();
101
- app.insertMention(mention.items[mention.index]);
102
- return true;
100
+ const item = mention.items[mention.index];
101
+ if (item) {
102
+ event.preventDefault();
103
+ app.insertMention(item);
104
+ return true;
105
+ }
103
106
  }
104
107
  app.closeMention();
105
108
  return event.key === "Tab";
@@ -165,10 +168,10 @@ function currentMention(input) {
165
168
  if (position !== end)
166
169
  return null;
167
170
  let start = position;
168
- while (start > 0 && /[\p{L}\p{N}_]/u.test(value[start - 1]))
171
+ while (start > 0 && /[\p{L}\p{N}_]/u.test(value.charAt(start - 1)))
169
172
  start--;
170
173
  const at = start - 1;
171
- if (at >= 0 && value[at] === "@" && (at === 0 || !/[A-Za-z0-9_]/.test(value[at - 1]))) {
174
+ if (at >= 0 && value.charAt(at) === "@" && (at === 0 || !/[A-Za-z0-9_]/.test(value.charAt(at - 1)))) {
172
175
  return { start: at, query: value.slice(start, position) };
173
176
  }
174
177
  return null;
@@ -47,7 +47,7 @@ const pending = new Map();
47
47
  export function cacheRoomSoon(app, roomId) {
48
48
  if (pending.has(roomId))
49
49
  return;
50
- pending.set(roomId, setTimeout(() => {
50
+ pending.set(roomId, window.setTimeout(() => {
51
51
  pending.delete(roomId);
52
52
  const entry = app.state.rooms.get(roomId);
53
53
  if (!entry?.room)
@@ -32,7 +32,7 @@ export function initMessagePolling(app, isUnreadMessage) {
32
32
  stopRecovery();
33
33
  recoveryRoom = roomId;
34
34
  recoveryGeneration = app.state.pollGeneration;
35
- recoveryTimer = setTimeout(() => { void probeRecovery(roomId, recoveryGeneration); }, immediate ? 0 : 2000);
35
+ recoveryTimer = window.setTimeout(() => { void probeRecovery(roomId, recoveryGeneration); }, immediate ? 0 : 2000);
36
36
  }
37
37
  async function probeRecovery(roomId, generation) {
38
38
  recoveryTimer = null;
@@ -71,7 +71,7 @@ export function initMessagePolling(app, isUnreadMessage) {
71
71
  app.openChatSettings();
72
72
  return;
73
73
  }
74
- recoveryTimer = setTimeout(() => { void probeRecovery(roomId, generation); }, 2000);
74
+ recoveryTimer = window.setTimeout(() => { void probeRecovery(roomId, generation); }, 2000);
75
75
  }
76
76
  finally {
77
77
  clearTimeout(timer);
@@ -42,7 +42,7 @@ export function flashMessageRow(app, row) {
42
42
  row.classList.remove("jump-flash");
43
43
  void row.offsetWidth;
44
44
  row.classList.add("jump-flash");
45
- row._jumpFlashTimer = setTimeout(() => row.classList.remove("jump-flash"), 900);
45
+ row._jumpFlashTimer = window.setTimeout(() => row.classList.remove("jump-flash"), 900);
46
46
  app.updateJump?.();
47
47
  }
48
48
  // Resolve app.state.focusMessageId against the loaded state and rendered rows.
@@ -264,8 +264,12 @@ export function initMessages(app) {
264
264
  const content = document.createElement("div");
265
265
  content.className = "msg-content";
266
266
  content.append(body);
267
- if (!message.pending)
268
- content.append(app.createReceiptButton(message, own));
267
+ if (!message.pending) {
268
+ const stack = document.createElement("div");
269
+ stack.className = "msg-receipt-stack";
270
+ stack.append(app.createReceiptButton(message, own));
271
+ content.append(stack);
272
+ }
269
273
  row.append(meta, content);
270
274
  }
271
275
  if (message.senderId !== "system") {
@@ -329,7 +333,7 @@ export function initMessages(app) {
329
333
  const lastId = [...list.querySelectorAll("[data-msg-id]")].at(-1)?.dataset.msgId;
330
334
  if (lastId)
331
335
  for (let index = messages.length - 1; index >= 0; index--)
332
- if (messages[index].id === lastId) {
336
+ if (messages[index]?.id === lastId) {
333
337
  startIndex = index + 1;
334
338
  break;
335
339
  }
@@ -337,6 +341,8 @@ export function initMessages(app) {
337
341
  const renderEnd = focus ? Math.min(messages.length, focus.index + 120) : messages.length;
338
342
  for (let index = renderStart; index < renderEnd; index++) {
339
343
  const message = messages[index];
344
+ if (!message)
345
+ break;
340
346
  if (renderedIds.has(message.id) || app.failedRenderIds.has(message.id))
341
347
  continue;
342
348
  try {
@@ -354,6 +360,14 @@ export function initMessages(app) {
354
360
  if (last.classList.contains("msg") && last.getAttribute("data-sender") === message.senderId
355
361
  && message.createdAt - Number(last.getAttribute("data-ts")) < 8 * 60 * 1000)
356
362
  row.classList.add("repeat");
363
+ if (row.classList.contains("repeat")) {
364
+ // A grouped row shows its own clock beside the badge, not a meta line.
365
+ const time = row.querySelector(".msg-time"), stack = row.querySelector(".msg-receipt-stack");
366
+ if (time && stack) {
367
+ time.textContent = app.timeHM(message.createdAt);
368
+ stack.prepend(time);
369
+ }
370
+ }
357
371
  list.append(row);
358
372
  last = row;
359
373
  renderedIds.add(message.id);
@@ -10,10 +10,10 @@ const loaded = new Map();
10
10
  export class OfficePreviewError extends Error {
11
11
  name = "OfficePreviewError";
12
12
  }
13
- function load(kind) {
13
+ function load(kind, url) {
14
14
  let pending = loaded.get(kind);
15
15
  if (!pending) {
16
- pending = import(FORMATS[kind].url);
16
+ pending = import(url);
17
17
  pending.catch(() => loaded.delete(kind));
18
18
  loaded.set(kind, pending);
19
19
  }
@@ -55,7 +55,7 @@ export async function renderOffice(kind, blob, container, options = {}) {
55
55
  container.classList.add("office-preview");
56
56
  container.setAttribute("aria-busy", "true");
57
57
  try {
58
- const bundle = await load(kind);
58
+ const bundle = await load(kind, format.url);
59
59
  await bundle.render(blob, container, options);
60
60
  }
61
61
  catch (error) {
@@ -280,7 +280,7 @@ export function initPalette(app) {
280
280
  }
281
281
  status.textContent = t("paletteSearching");
282
282
  const text = value.trim();
283
- searchTimer = setTimeout(() => { void executeSearch(text, token); }, SEARCH_DEBOUNCE_MS);
283
+ searchTimer = window.setTimeout(() => { void executeSearch(text, token); }, SEARCH_DEBOUNCE_MS);
284
284
  };
285
285
  const highlightHit = (item) => {
286
286
  if (!item?.messageId)
@@ -293,7 +293,7 @@ export function initPalette(app) {
293
293
  if (row) {
294
294
  row.scrollIntoView({ block: "center", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
295
295
  row.classList.add("palette-hit");
296
- hitTimer = setTimeout(() => row.classList.remove("palette-hit"), 4000);
296
+ hitTimer = window.setTimeout(() => row.classList.remove("palette-hit"), 4000);
297
297
  return;
298
298
  }
299
299
  if (++attempts < 50)
@@ -428,7 +428,9 @@ export function initPalette(app) {
428
428
  if (!items.length || selected < 0)
429
429
  return;
430
430
  event.preventDefault();
431
- activate(items[selected]);
431
+ const item = items[selected];
432
+ if (item)
433
+ activate(item);
432
434
  return;
433
435
  }
434
436
  if (event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
@@ -1,6 +1,25 @@
1
1
  const PANEL_DEFAULTS = { announcements: "dialog", files: "dialog", tasks: "pane", reminders: "dialog" };
2
2
  const PANEL_MODES = ["dialog", "pane"];
3
3
  const PANE_QUERY = "(min-width: 1100px) and (min-height: 560px)";
4
+ // A press and release both on the backdrop closes. The backdrop hit-tests as the
5
+ // dialog itself, so the box check keeps a click on the dialog padding inside, and
6
+ // the press check keeps a drag that started inside from dismissing on release.
7
+ export function closeOnBackdrop(dialog, close) {
8
+ const outside = (event) => {
9
+ const box = dialog.getBoundingClientRect();
10
+ return event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom;
11
+ };
12
+ let pressedOutside = false;
13
+ dialog.addEventListener("pointerdown", (event) => {
14
+ pressedOutside = event.target === dialog && outside(event);
15
+ });
16
+ dialog.addEventListener("click", (event) => {
17
+ const dismiss = pressedOutside && event.target === dialog && outside(event);
18
+ pressedOutside = false;
19
+ if (dismiss && dialog.open)
20
+ close();
21
+ });
22
+ }
4
23
  export function initPanels(app) {
5
24
  const $ = app.$;
6
25
  const pane = matchMedia(PANE_QUERY);
@@ -182,9 +182,10 @@ export function initQuestions(app) {
182
182
  const author = question.senderSessionID
183
183
  ? members.filter((member) => member.sessionID === question.senderSessionID)
184
184
  : members.filter((member) => member.name === question.senderId);
185
- if (author.length !== 1 || members.filter((member) => member.name === author[0].name).length !== 1 || author[0].sessionID === LS.sessionID || author[0].name === "all")
185
+ const only = author.length === 1 ? author[0] : undefined;
186
+ if (!only || members.filter((member) => member.name === only.name).length !== 1 || only.sessionID === LS.sessionID || only.name === "all")
186
187
  return "";
187
- return autoMentionDraft(author[0].name);
188
+ return autoMentionDraft(only.name);
188
189
  }
189
190
  async function load(roomId = app.state.room?.id) {
190
191
  if (!roomId)
@@ -1,4 +1,5 @@
1
1
  import { LS } from "./state.js";
2
+ import { closeOnBackdrop } from "./panels.js";
2
3
  export function initReminders(app) {
3
4
  const $ = (selector) => {
4
5
  const element = app.$(selector);
@@ -299,6 +300,8 @@ export function initReminders(app) {
299
300
  dialog.addEventListener("close", () => { editing = null; });
300
301
  trigger.addEventListener("click", () => { app.closePanels(); openSurface(); });
301
302
  $("#btnCloseReminders").addEventListener("click", () => closeSurface());
303
+ // The reminder list is a list, so a backdrop click closes it; the editor stays.
304
+ closeOnBackdrop(surface, () => closeSurface());
302
305
  surface.addEventListener("cancel", (event) => { event.preventDefault(); closeSurface(); });
303
306
  surface.addEventListener("close", () => {
304
307
  if (pendingReopen) {
@@ -119,8 +119,11 @@ function uniqueAuthor(message, app) {
119
119
  const members = app.state.memberSessions.get(app.state.room?.id ?? "") || [];
120
120
  const matches = message.senderSessionID ? members.filter((item) => item.sessionID === message.senderSessionID)
121
121
  : members.filter((item) => item.name === message.senderId);
122
- const name = matches[0]?.name;
123
- return matches.length === 1 && members.filter((item) => item.name === name).length === 1 && matches[0].sessionID !== LS.sessionID && name !== "all" ? name : "";
122
+ const only = matches.length === 1 ? matches[0] : undefined;
123
+ if (!only)
124
+ return "";
125
+ const name = only.name;
126
+ return members.filter((item) => item.name === name).length === 1 && only.sessionID !== LS.sessionID && name !== "all" ? name : "";
124
127
  }
125
128
  function senderName(message, app) {
126
129
  if (message.senderSessionID === LS.sessionID)
@@ -191,7 +194,7 @@ async function jumpToOriginal(roomId, messageId, app) {
191
194
  row.classList.remove("jump-flash");
192
195
  void row.offsetWidth;
193
196
  row.classList.add("jump-flash");
194
- row._jumpFlashTimer = setTimeout(() => row.classList.remove("jump-flash"), 900);
197
+ row._jumpFlashTimer = window.setTimeout(() => row.classList.remove("jump-flash"), 900);
195
198
  }
196
199
  }
197
200
  const quote = document.querySelector(`[data-reply-target-id="${CSS.escape(messageId)}"]`);
@@ -61,7 +61,7 @@ function isTextMime(mime) {
61
61
  return mime.startsWith("text/") || TEXT_MIMES.has(mime);
62
62
  }
63
63
  export function docPreviewFormat(resource) {
64
- const mime = String(resource?.mimeType || "").split(";")[0].trim().toLowerCase();
64
+ const mime = (String(resource?.mimeType || "").split(";")[0] ?? "").trim().toLowerCase();
65
65
  const name = String(resource?.name || "");
66
66
  const ext = fileExtension(name);
67
67
  if (mime === "application/pdf" || ext === "pdf")
@@ -76,7 +76,7 @@ export function docPreviewFormat(resource) {
76
76
  const knownExtension = Object.hasOwn(EXTENSION_LANGUAGES, ext);
77
77
  if (!knownExtension && !isTextMime(mime))
78
78
  return null;
79
- const language = knownExtension ? EXTENSION_LANGUAGES[ext] : MIME_LANGUAGES[mime] || "";
79
+ const language = (knownExtension ? EXTENSION_LANGUAGES[ext] : MIME_LANGUAGES[mime]) ?? "";
80
80
  return { kind: "text", language, label: LANGUAGE_NAMES[language] || (ext ? ext.toUpperCase() : "Text") };
81
81
  }
82
82
  export const isDocPreviewResource = (resource) => docPreviewFormat(resource) !== null;
@@ -391,7 +391,7 @@ export function initRooms(app) {
391
391
  clearTimeout(app.state.watcherTimer);
392
392
  if (!app.state.rooms.size && !app.state.restorePending?.size && !app.state.restoreRetry)
393
393
  return;
394
- app.state.watcherTimer = setTimeout(async () => {
394
+ app.state.watcherTimer = window.setTimeout(async () => {
395
395
  // A hidden tab has no reader; skip background room polling until it is
396
396
  // visible again (the next timer tick after visibility resumes).
397
397
  if (typeof document !== "undefined" && document.hidden) {
@@ -603,7 +603,7 @@ export function initRooms(app) {
603
603
  // button and then restore it to "undefined" (the button has no data-i18n).
604
604
  clearTimeout(button._copiedTimer);
605
605
  button.classList.add("copied");
606
- button._copiedTimer = setTimeout(() => button.classList.remove("copied"), 1200);
606
+ button._copiedTimer = window.setTimeout(() => button.classList.remove("copied"), 1200);
607
607
  }
608
608
  catch {
609
609
  app.showSendError("copyFailed", { id: roomId });
@@ -625,8 +625,11 @@ export function initRooms(app) {
625
625
  async function bounded(items, limit, action) {
626
626
  let cursor = 0;
627
627
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
628
- while (cursor < items.length)
629
- await action(items[cursor++]);
628
+ while (cursor < items.length) {
629
+ const item = items[cursor++];
630
+ if (item !== undefined)
631
+ await action(item);
632
+ }
630
633
  }));
631
634
  }
632
635
  function syncCachedRooms(rooms, app) {
@@ -7,7 +7,8 @@ const isDarkColor = (color) => {
7
7
  const value = parseInt(part, 16) / 255;
8
8
  return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
9
9
  });
10
- return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2] < 0.4;
10
+ const [r = 0, g = 0, b = 0] = channels;
11
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.4;
11
12
  };
12
13
  export function initSettings(app) {
13
14
  const $ = app.$;
@@ -138,7 +139,7 @@ export function initSettings(app) {
138
139
  if (target < 0)
139
140
  return;
140
141
  event.preventDefault();
141
- activateTab(tabs[target].dataset.settingsTab, { focus: true });
142
+ activateTab(tabs[target]?.dataset.settingsTab, { focus: true });
142
143
  };
143
144
  for (const tab of tabs) {
144
145
  tab.addEventListener("click", () => activateTab(tab.dataset.settingsTab));
@@ -191,7 +192,7 @@ export function initSettings(app) {
191
192
  const color = validColor(customColorInput.value);
192
193
  scheduleCustomPaint(color);
193
194
  clearTimeout(customPersistTimer);
194
- customPersistTimer = setTimeout(() => {
195
+ customPersistTimer = window.setTimeout(() => {
195
196
  customPersistTimer = 0;
196
197
  commitCustomColor(validColor(customColorInput.value));
197
198
  }, CUSTOM_COLOR_PERSIST_DELAY);
@@ -1,3 +1,4 @@
1
+ import { closeOnBackdrop } from "./panels.js";
1
2
  export function initShortcuts(app) {
2
3
  const dialog = app.$("#shortcutsDialog");
3
4
  if (!dialog)
@@ -23,6 +24,7 @@ export function initShortcuts(app) {
23
24
  app.$("#btnShortcuts")?.addEventListener("mousedown", (event) => event.preventDefault());
24
25
  app.$("#btnShortcuts")?.addEventListener("click", openSheet);
25
26
  app.$("#btnCloseShortcuts")?.addEventListener("click", () => dialog.close());
27
+ closeOnBackdrop(dialog, () => dialog.close());
26
28
  dialog.addEventListener("close", () => requestAnimationFrame(() => app.focusComposer?.()));
27
29
  let scrollFrame = 0;
28
30
  let scrollGeneration = 0;
@@ -120,7 +122,7 @@ export function initShortcuts(app) {
120
122
  if (!bottom) {
121
123
  app.state.jumpToLoadedTop = true;
122
124
  clearTimeout(app.state.jumpToLoadedTopTimer);
123
- app.state.jumpToLoadedTopTimer = setTimeout(() => { app.state.jumpToLoadedTop = false; }, reduced ? 150 : 800);
125
+ app.state.jumpToLoadedTopTimer = window.setTimeout(() => { app.state.jumpToLoadedTop = false; }, reduced ? 150 : 800);
124
126
  }
125
127
  animateScroll(bottom ? thread.scrollHeight : 0);
126
128
  };
@@ -35,7 +35,7 @@ export function initSidePaneSplitter(app) {
35
35
  paneWasOpen = open;
36
36
  view.classList.add("pane-animating");
37
37
  clearTimeout(animationTimer);
38
- animationTimer = setTimeout(() => view.classList.remove("pane-animating"), ANIMATION_MS);
38
+ animationTimer = window.setTimeout(() => view.classList.remove("pane-animating"), ANIMATION_MS);
39
39
  };
40
40
  // A wide task board must leave the conversation a full working column; the
41
41
  // Markdown preview keeps the normal minimum.
@@ -69,7 +69,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
69
69
  };
70
70
  const read = (key) => {
71
71
  if (Object.hasOwn(memory, key))
72
- return memory[key];
72
+ return memory[key] ?? null;
73
73
  try {
74
74
  return (storage ?? globalThis.localStorage).getItem(key);
75
75
  }
@@ -298,6 +298,11 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
298
298
  }
299
299
  return auth.token;
300
300
  };
301
+ const networkError = () => {
302
+ const error = new Error(translate("networkError"));
303
+ error.network = true;
304
+ return error;
305
+ };
301
306
  const apiResponse = async (url, options = {}) => {
302
307
  assertIdentity();
303
308
  const headers = { ...options.headers };
@@ -310,9 +315,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
310
315
  response = await (fetcher ?? globalThis.fetch)(url, { ...options, headers });
311
316
  }
312
317
  catch {
313
- const error = new Error(translate("networkError"));
314
- error.network = true;
315
- throw error;
318
+ throw networkError();
316
319
  }
317
320
  assertIdentity();
318
321
  if (!response.ok) {
@@ -324,10 +327,26 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
324
327
  }
325
328
  return response;
326
329
  };
327
- const api = async (url, options) => {
328
- const response = await apiResponse(url, options), data = await response.json().catch(() => ({}));
329
- assertIdentity();
330
- return data;
330
+ const api = async (url, { timeoutMs = 20_000, ...options } = {}) => {
331
+ // Bound restore reads through the end of the body, without timing out writes or downloads.
332
+ const controller = !options.signal && (options.method ?? "GET") === "GET" ? new AbortController() : undefined;
333
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : undefined;
334
+ try {
335
+ const response = await apiResponse(url, controller ? { ...options, signal: controller.signal } : options);
336
+ const data = await response.json().catch(() => ({}));
337
+ controller?.signal.throwIfAborted();
338
+ assertIdentity();
339
+ return data;
340
+ }
341
+ catch (error) {
342
+ if (controller?.signal.aborted)
343
+ throw networkError();
344
+ throw error;
345
+ }
346
+ finally {
347
+ if (timer !== undefined)
348
+ clearTimeout(timer);
349
+ }
331
350
  };
332
351
  const apiBlob = async (url, options) => {
333
352
  const response = await apiResponse(url, options), blob = await response.blob();
@@ -747,13 +766,13 @@ export const messages = {
747
766
  };
748
767
  // Every locale falls back to English for keys it has not translated yet.
749
768
  for (const dictionary of Object.values(messages)) {
750
- for (const key of Object.keys(messages.en)) {
769
+ for (const [key, entry] of Object.entries(messages.en)) {
751
770
  if (dictionary[key] === undefined)
752
- dictionary[key] = messages.en[key];
771
+ dictionary[key] = entry;
753
772
  }
754
773
  }
755
774
  app.t = (key, values = {}) => {
756
- const entry = messages[app.locale][key] ?? messages.en[key] ?? key;
775
+ const entry = messages[app.locale]?.[key] ?? messages.en[key] ?? key;
757
776
  const text = typeof entry === "function" ? entry(values) : entry;
758
777
  return String(text).replace(/\{(\w+)\}/g, (_, name) => String(values[name] ?? ""));
759
778
  };
@@ -1,6 +1,7 @@
1
1
  import { iconNode } from "./icons.js";
2
2
  import { formatRelayMessage, formatSystemMessage, systemMessageKind } from "./system-messages.js";
3
3
  import { renderMarkdown, renderResourceText } from "./markdown.js";
4
+ const noticeIcon = "megaphone";
4
5
  const icons = {
5
6
  join: "add",
6
7
  leave: "arrow_exit",
@@ -8,7 +9,7 @@ const icons = {
8
9
  admin: "shield_checkmark",
9
10
  forward: "arrow_swap",
10
11
  reminder: "alert",
11
- notice: "megaphone",
12
+ notice: noticeIcon,
12
13
  };
13
14
  // Notices are Markdown and switch from a pill to a card once they pass three
14
15
  // rendered lines; relays always keep the message-card shape because they carry
@@ -41,7 +42,7 @@ export function renderSystemRow(row, message, app) {
41
42
  event.className = "sys-event";
42
43
  event.setAttribute("role", "note");
43
44
  mark.className = "sys-icon";
44
- mark.append(iconNode(icons[kind] || icons.notice, "sys-icon-glyph"));
45
+ mark.append(iconNode(icons[kind] ?? noticeIcon, "sys-icon-glyph"));
45
46
  text.className = "sys-text";
46
47
  if (kind === "relay")
47
48
  renderResourceText(text, formatRelayMessage(message, app), app);