@alexsun-top/opencode-chat-room 0.8.2 → 0.8.3

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 (92) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +466 -188
  5. package/package.json +8 -5
  6. package/packages/chat-room-channeld/README.md +25 -3
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +5 -0
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +17 -2
  11. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  12. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  13. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  14. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  15. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  16. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  17. package/packages/chat-room-channeld/src/protocol.ts +1 -0
  18. package/packages/chat-room-channeld/src/state.ts +73 -97
  19. package/packages/chat-room-channeld/src/stats.ts +140 -109
  20. package/server/assets/base.css +3 -1
  21. package/server/assets/chat/admin-badge.js +32 -30
  22. package/server/assets/chat/admin.js +198 -161
  23. package/server/assets/chat/announcements.js +295 -208
  24. package/server/assets/chat/attachment-store.js +106 -75
  25. package/server/assets/chat/attachments.js +686 -441
  26. package/server/assets/chat/chat-background.js +185 -156
  27. package/server/assets/chat/clipboard.js +44 -25
  28. package/server/assets/chat/confirm-dialog.js +36 -33
  29. package/server/assets/chat/copy-action.js +40 -40
  30. package/server/assets/chat/create-room-dialog.js +50 -47
  31. package/server/assets/chat/diagram-viewer.js +293 -234
  32. package/server/assets/chat/doc-preview.js +507 -441
  33. package/server/assets/chat/editor.js +423 -335
  34. package/server/assets/chat/events.js +637 -510
  35. package/server/assets/chat/files.js +476 -430
  36. package/server/assets/chat/history-loader.js +79 -73
  37. package/server/assets/chat/icons.js +9 -11
  38. package/server/assets/chat/image-zoom.js +239 -176
  39. package/server/assets/chat/index.js +2 -3
  40. package/server/assets/chat/install-prompt.js +86 -66
  41. package/server/assets/chat/integration-account-schema.js +88 -86
  42. package/server/assets/chat/integration-editor.js +162 -153
  43. package/server/assets/chat/integration-values.js +109 -100
  44. package/server/assets/chat/integrations.js +689 -622
  45. package/server/assets/chat/join-requests.js +408 -358
  46. package/server/assets/chat/locales/de.js +193 -194
  47. package/server/assets/chat/locales/es.js +193 -194
  48. package/server/assets/chat/locales/fr.js +193 -194
  49. package/server/assets/chat/locales/index.js +1 -2
  50. package/server/assets/chat/locales/it.js +193 -194
  51. package/server/assets/chat/locales/ja.js +193 -193
  52. package/server/assets/chat/locales/ko.js +193 -193
  53. package/server/assets/chat/markdown-footnotes.js +134 -102
  54. package/server/assets/chat/markdown.js +547 -403
  55. package/server/assets/chat/members.js +236 -197
  56. package/server/assets/chat/mentions.js +157 -133
  57. package/server/assets/chat/message-cache.js +40 -33
  58. package/server/assets/chat/message-polling.js +280 -227
  59. package/server/assets/chat/message-window.js +74 -55
  60. package/server/assets/chat/messages.js +552 -480
  61. package/server/assets/chat/office-preview.js +46 -45
  62. package/server/assets/chat/palette.js +450 -417
  63. package/server/assets/chat/panels.js +94 -78
  64. package/server/assets/chat/pwa.js +144 -73
  65. package/server/assets/chat/questions.js +372 -302
  66. package/server/assets/chat/recall.js +320 -273
  67. package/server/assets/chat/receipts.js +149 -121
  68. package/server/assets/chat/reminders.js +331 -214
  69. package/server/assets/chat/replies.js +165 -130
  70. package/server/assets/chat/resource-format.js +59 -62
  71. package/server/assets/chat/room-list.js +58 -55
  72. package/server/assets/chat/room-watcher.js +72 -50
  73. package/server/assets/chat/rooms.js +623 -500
  74. package/server/assets/chat/search.js +136 -114
  75. package/server/assets/chat/settings.js +223 -200
  76. package/server/assets/chat/shiki.js +61 -62
  77. package/server/assets/chat/shortcuts.js +212 -187
  78. package/server/assets/chat/side-pane.js +160 -150
  79. package/server/assets/chat/state.js +849 -735
  80. package/server/assets/chat/system-events.js +45 -43
  81. package/server/assets/chat/system-messages.js +57 -56
  82. package/server/assets/chat/task-form.js +178 -182
  83. package/server/assets/chat/task-row.js +158 -155
  84. package/server/assets/chat/tasks.js +653 -587
  85. package/server/assets/chat/viewport.js +32 -29
  86. package/server/assets/chat/window-controls.js +32 -32
  87. package/server/assets/conversation.css +10 -4
  88. package/server/chat-server.ts +9 -1
  89. package/server/chat.html +2 -1
  90. package/server/routes/pages.ts +7 -5
  91. package/server/sw.js +346 -268
  92. package/src/web/integration-rules-editor.ts +2 -0
@@ -1,427 +1,460 @@
1
1
  import { icon } from "./icons.js";
2
-
3
2
  // Alt+Space or Ctrl+P opens one keyboard-first surface: message search plus common room commands.
4
-
5
3
  const SEARCH_DEBOUNCE_MS = 120;
6
-
7
4
  export function initPalette(app) {
8
- const dialog = app.$("#paletteDialog");
9
- if (!dialog) return;
10
- const input = app.$("#paletteInput"), list = app.$("#paletteList"), status = app.$("#paletteStatus");
11
- const scopeButton = app.$("#paletteScope"), scopeLabel = app.$("#paletteScopeLabel"), modeLabel = app.$("#paletteMode");
12
- let scope = "room", items = [], selected = -1, sequence = 0, searchTimer = 0, suppressComposerFocus = false, hitTimer = 0;
13
- const t = (key, values) => app.t(key, values);
14
- const room = () => app.state.room;
15
-
16
- // The eyebrow names the real key on this platform, matching the shortcut sheet.
17
- const combo = app.$("#paletteCombo");
18
- const mac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
19
- if (combo) combo.textContent = mac ? "Ctrl + P / Option + Space" : "Ctrl + P / Alt + Space";
20
-
21
- const commands = () => {
22
- const available = [
23
- { id: "refresh", label: t("refreshRooms"), en: "Refresh rooms", icon: "arrow_sync", keywords: "reload rooms", run: () => void app.refreshRoomList?.() },
24
- { id: "create", label: t("createRoom"), en: "New room", icon: "add", keywords: "new room", focusComposer: false,
25
- run: () => room() ? app.openCreateRoomDialog?.() : app.$("#inRoomName")?.focus({ preventScroll: true }) },
26
- { id: "settings", label: t("settings"), en: "Settings", icon: "options", keywords: "preferences theme language", focusComposer: false, run: () => app.openSettings?.() },
27
- ];
28
- if (room()) available.push(
29
- { id: "members", label: t("members"), en: "Members", icon: "people", keywords: "people roster", focusComposer: false, run: () => app.$("#btnMembers")?.click() },
30
- { id: "questions", label: t("questions"), en: "Questions", icon: "question_circle", keywords: "answers", focusComposer: false, run: () => app.$("#btnQuestions")?.click() },
31
- { id: "announcements", label: t("announcements"), en: "Announcements", icon: "megaphone", keywords: "notice board", focusComposer: false, run: () => app.$("#btnAnnouncements")?.click() },
32
- ...(room().kind === "direct" ? [] : [{ id: "tasks", label: t("tasksTitle"), en: "Tasks", icon: "checkmark", keywords: "todo checklist work", focusComposer: false, run: () => app.openTasksDialog?.() }]),
33
- { id: "reminders", label: t("reminders"), en: "Reminders", icon: "alert", keywords: "schedule alarm", focusComposer: false, run: () => app.$("#btnReminders")?.click() },
34
- { id: "leave", label: t("paletteLeaveRoom"), en: "Leave room", icon: "arrow_exit", keywords: "exit quit", focusComposer: false, run: () => app.leaveRoom?.(false) },
35
- { id: "latest", label: t("paletteJumpLatest"), en: "Jump to latest", icon: "arrow_down", keywords: "bottom newest", run: () => app.jumpToBottom?.() },
36
- );
37
- return available;
38
- };
39
-
40
- const scopeText = () => t(scope === "all" ? "paletteScopeAll" : "paletteScopeRoom");
41
- const syncScope = () => {
42
- scopeLabel.textContent = scopeText();
43
- scopeButton.dataset.scope = scope;
44
- scopeButton.title = t("paletteScopeHint");
45
- scopeButton.setAttribute("aria-label", `${scopeText()}. ${t("paletteScopeHint")}`);
46
- };
47
-
48
- const appendSnippet = (node, text, needle) => {
49
- const flat = String(text ?? "").replace(/\s+/g, " ").trim();
50
- if (!flat) { node.textContent = ""; return; }
51
- const lower = flat.toLowerCase(), match = needle ? lower.indexOf(needle.toLowerCase()) : -1;
52
- let start = 0, end = flat.length;
53
- if (flat.length > 180) {
54
- start = match > 60 ? match - 60 : 0;
55
- end = Math.min(flat.length, start + 180);
56
- }
57
- const body = flat.slice(start, end);
58
- if (start > 0) node.append("…");
59
- if (match >= start && match < end) {
60
- const offset = match - start;
61
- node.append(body.slice(0, offset));
62
- const mark = document.createElement("mark");
63
- mark.textContent = body.slice(offset, offset + needle.length);
64
- node.append(mark, body.slice(offset + needle.length));
65
- } else node.append(body);
66
- if (end < flat.length) node.append("…");
67
- };
68
-
69
- const syncSelection = () => {
70
- const rows = [...list.querySelectorAll(".palette-row")];
71
- rows.forEach((row, index) => {
72
- row.setAttribute("aria-selected", String(index === selected));
73
- const enter = row.querySelector(".palette-enter");
74
- if (enter) enter.hidden = index !== selected;
75
- });
76
- input.setAttribute("aria-expanded", String(items.length > 0));
77
- if (items.length && selected >= 0) input.setAttribute("aria-activedescendant", `palette-option-${selected}`);
78
- else input.removeAttribute("aria-activedescendant");
79
- rows[selected]?.scrollIntoView({ block: "nearest" });
80
- };
81
-
82
- const render = (next, emptyKey) => {
83
- items = next;
84
- selected = next.length ? 0 : -1;
85
- list.textContent = "";
86
- next.forEach((item, index) => {
87
- const row = document.createElement("li");
88
- row.id = `palette-option-${index}`;
89
- row.className = `palette-row ${item.kind === "command" ? "palette-command" : "palette-result"}`;
90
- row.setAttribute("role", "option");
91
- row.style.setProperty("--palette-i", String(Math.min(index, 9)));
92
- if (item.kind === "command") {
93
- const badge = document.createElement("span");
94
- badge.className = "palette-icon";
95
- badge.innerHTML = icon(item.icon || "arrow_right");
96
- const label = document.createElement("span");
97
- label.className = "palette-label";
98
- label.textContent = item.label;
99
- const enter = document.createElement("kbd");
100
- enter.className = "palette-enter";
101
- enter.setAttribute("aria-hidden", "true");
102
- enter.textContent = "↵";
103
- row.append(badge, label, enter);
104
- } else {
105
- const top = document.createElement("span");
106
- top.className = "palette-result-top";
107
- const roomName = document.createElement("span");
108
- roomName.className = "palette-room";
109
- roomName.textContent = item.roomName || app.state.roomNames.get(item.roomId) || "";
110
- const sender = document.createElement("span");
111
- sender.className = "palette-sender";
112
- sender.textContent = item.sender || "";
113
- const time = document.createElement("time");
114
- time.className = "palette-time";
115
- if (item.createdAt) time.dateTime = new Date(item.createdAt).toISOString();
116
- time.textContent = item.createdAt ? app.fmtTime(item.createdAt) : "";
117
- top.append(roomName, sender, time);
118
- const snippet = document.createElement("span");
119
- snippet.className = "palette-snippet";
120
- appendSnippet(snippet, item.text, input.value.trim());
121
- row.append(top, snippet);
122
- }
123
- row.addEventListener("click", () => { selected = index; syncSelection(); activate(item); });
124
- list.append(row);
125
- });
126
- if (!next.length && emptyKey) {
127
- const empty = document.createElement("li");
128
- empty.className = "palette-empty";
129
- empty.setAttribute("role", "presentation");
130
- empty.textContent = t(emptyKey);
131
- list.append(empty);
132
- }
133
- syncSelection();
134
- };
135
-
136
- // Empty input is search, not a command wall: commands appear only after "/".
137
- const showIdle = () => {
138
- clearTimeout(searchTimer);
139
- sequence++;
140
- dialog.dataset.mode = "search";
141
- dialog.dataset.state = "ready";
142
- modeLabel.textContent = t("paletteSearchMode");
143
- list.setAttribute("aria-busy", "false");
144
- render([], null);
145
- status.textContent = t("palettePlaceholder");
146
- };
147
-
148
- const showCommands = (fragment = "") => {
149
- clearTimeout(searchTimer);
150
- sequence++;
151
- const needle = fragment.trim().toLowerCase();
152
- const available = commands()
153
- .filter((command) => !needle || `${command.label} ${command.en || ""} ${command.keywords || ""} ${command.id}`.toLowerCase().includes(needle))
154
- .map((command) => ({ kind: "command", ...command }));
155
- dialog.dataset.mode = "commands";
156
- dialog.dataset.state = "ready";
157
- modeLabel.textContent = t("paletteCommandMode");
158
- list.setAttribute("aria-busy", "false");
159
- render(available, "paletteNoCommands");
160
- status.textContent = needle
161
- ? available.length ? t("paletteResults", { count: available.length }) : t("paletteNoCommands")
162
- : t("paletteCommandsHint");
163
- };
164
-
165
- const senderName = (source, message) => {
166
- if (source.kind === "direct") return source.participants?.find((person) => person.id === message.senderId)?.name || message.senderId;
167
- return message.senderId;
168
- };
169
-
170
- const localSearch = (text, searchScope) => {
171
- const needle = text.toLowerCase();
172
- const entries = searchScope === "all"
173
- ? [...app.state.rooms.values()]
174
- : [app.state.rooms.get(app.state.room?.id)].filter(Boolean);
175
- const hits = [];
176
- for (const entry of entries) {
177
- const source = entry.room;
178
- if (!source?.messages) continue;
179
- for (const message of source.messages) {
180
- if (message.recalledAt || message.pending || message.senderId === "system") continue;
181
- const body = String(message.text ?? "");
182
- if (!body.toLowerCase().includes(needle)) continue;
183
- const hit = {
184
- roomId: source.id,
185
- roomName: source.name || app.state.roomNames.get(source.id) || "",
186
- messageId: message.id,
187
- sender: senderName(source, message),
188
- createdAt: message.createdAt,
189
- text: body,
5
+ const dialog = app.$("#paletteDialog");
6
+ if (!dialog)
7
+ return;
8
+ const input = app.$("#paletteInput"), list = app.$("#paletteList"), status = app.$("#paletteStatus");
9
+ const scopeButton = app.$("#paletteScope"), scopeLabel = app.$("#paletteScopeLabel"), modeLabel = app.$("#paletteMode");
10
+ let scope = "room", items = [], selected = -1, sequence = 0, searchTimer = 0, suppressComposerFocus = false, hitTimer = 0;
11
+ const t = (key, values) => app.t(key, values);
12
+ const room = () => app.state.room;
13
+ // The eyebrow names the real key on this platform, matching the shortcut sheet.
14
+ const combo = app.$("#paletteCombo");
15
+ const mac = /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
16
+ if (combo)
17
+ combo.textContent = mac ? "Ctrl + P / Option + Space" : "Ctrl + P / Alt + Space";
18
+ const commands = () => {
19
+ const available = [
20
+ { id: "refresh", label: t("refreshRooms"), en: "Refresh rooms", icon: "arrow_sync", keywords: "reload rooms", run: () => void app.refreshRoomList?.() },
21
+ { id: "create", label: t("createRoom"), en: "New room", icon: "add", keywords: "new room", focusComposer: false,
22
+ run: () => room() ? app.openCreateRoomDialog?.() : app.$("#inRoomName")?.focus({ preventScroll: true }) },
23
+ { id: "settings", label: t("settings"), en: "Settings", icon: "options", keywords: "preferences theme language", focusComposer: false, run: () => app.openSettings?.() },
24
+ ];
25
+ if (room())
26
+ available.push({ id: "members", label: t("members"), en: "Members", icon: "people", keywords: "people roster", focusComposer: false, run: () => app.$("#btnMembers")?.click() }, { id: "questions", label: t("questions"), en: "Questions", icon: "question_circle", keywords: "answers", focusComposer: false, run: () => app.$("#btnQuestions")?.click() }, { id: "announcements", label: t("announcements"), en: "Announcements", icon: "megaphone", keywords: "notice board", focusComposer: false, run: () => app.$("#btnAnnouncements")?.click() }, ...(room().kind === "direct" ? [] : [{ id: "tasks", label: t("tasksTitle"), en: "Tasks", icon: "checkmark", keywords: "todo checklist work", focusComposer: false, run: () => app.openTasksDialog?.() }]), { id: "reminders", label: t("reminders"), en: "Reminders", icon: "alert", keywords: "schedule alarm", focusComposer: false, run: () => app.$("#btnReminders")?.click() }, { id: "leave", label: t("paletteLeaveRoom"), en: "Leave room", icon: "arrow_exit", keywords: "exit quit", focusComposer: false, run: () => app.leaveRoom?.(false) }, { id: "latest", label: t("paletteJumpLatest"), en: "Jump to latest", icon: "arrow_down", keywords: "bottom newest", run: () => app.jumpToBottom?.() });
27
+ return available;
28
+ };
29
+ const scopeText = () => t(scope === "all" ? "paletteScopeAll" : "paletteScopeRoom");
30
+ const syncScope = () => {
31
+ scopeLabel.textContent = scopeText();
32
+ scopeButton.dataset.scope = scope;
33
+ scopeButton.title = t("paletteScopeHint");
34
+ scopeButton.setAttribute("aria-label", `${scopeText()}. ${t("paletteScopeHint")}`);
35
+ };
36
+ const appendSnippet = (node, text, needle) => {
37
+ const flat = String(text ?? "").replace(/\s+/g, " ").trim();
38
+ if (!flat) {
39
+ node.textContent = "";
40
+ return;
41
+ }
42
+ const lower = flat.toLowerCase(), match = needle ? lower.indexOf(needle.toLowerCase()) : -1;
43
+ let start = 0, end = flat.length;
44
+ if (flat.length > 180) {
45
+ start = match > 60 ? match - 60 : 0;
46
+ end = Math.min(flat.length, start + 180);
47
+ }
48
+ const body = flat.slice(start, end);
49
+ if (start > 0)
50
+ node.append("…");
51
+ if (match >= start && match < end) {
52
+ const offset = match - start;
53
+ node.append(body.slice(0, offset));
54
+ const mark = document.createElement("mark");
55
+ mark.textContent = body.slice(offset, offset + needle.length);
56
+ node.append(mark, body.slice(offset + needle.length));
57
+ }
58
+ else
59
+ node.append(body);
60
+ if (end < flat.length)
61
+ node.append("…");
62
+ };
63
+ const syncSelection = () => {
64
+ const rows = [...list.querySelectorAll(".palette-row")];
65
+ rows.forEach((row, index) => {
66
+ row.setAttribute("aria-selected", String(index === selected));
67
+ const enter = row.querySelector(".palette-enter");
68
+ if (enter)
69
+ enter.hidden = index !== selected;
70
+ });
71
+ input.setAttribute("aria-expanded", String(items.length > 0));
72
+ if (items.length && selected >= 0)
73
+ input.setAttribute("aria-activedescendant", `palette-option-${selected}`);
74
+ else
75
+ input.removeAttribute("aria-activedescendant");
76
+ rows[selected]?.scrollIntoView({ block: "nearest" });
77
+ };
78
+ const render = (next, emptyKey) => {
79
+ items = next;
80
+ selected = next.length ? 0 : -1;
81
+ list.textContent = "";
82
+ next.forEach((item, index) => {
83
+ const row = document.createElement("li");
84
+ row.id = `palette-option-${index}`;
85
+ row.className = `palette-row ${item.kind === "command" ? "palette-command" : "palette-result"}`;
86
+ row.setAttribute("role", "option");
87
+ row.style.setProperty("--palette-i", String(Math.min(index, 9)));
88
+ if (item.kind === "command") {
89
+ const badge = document.createElement("span");
90
+ badge.className = "palette-icon";
91
+ badge.innerHTML = icon(item.icon || "arrow_right");
92
+ const label = document.createElement("span");
93
+ label.className = "palette-label";
94
+ label.textContent = item.label;
95
+ const enter = document.createElement("kbd");
96
+ enter.className = "palette-enter";
97
+ enter.setAttribute("aria-hidden", "true");
98
+ enter.textContent = "↵";
99
+ row.append(badge, label, enter);
100
+ }
101
+ else {
102
+ const top = document.createElement("span");
103
+ top.className = "palette-result-top";
104
+ const roomName = document.createElement("span");
105
+ roomName.className = "palette-room";
106
+ roomName.textContent = item.roomName || app.state.roomNames.get(item.roomId) || "";
107
+ const sender = document.createElement("span");
108
+ sender.className = "palette-sender";
109
+ sender.textContent = item.sender || "";
110
+ const time = document.createElement("time");
111
+ time.className = "palette-time";
112
+ if (item.createdAt)
113
+ time.dateTime = new Date(item.createdAt).toISOString();
114
+ time.textContent = item.createdAt ? app.fmtTime(item.createdAt) : "";
115
+ top.append(roomName, sender, time);
116
+ const snippet = document.createElement("span");
117
+ snippet.className = "palette-snippet";
118
+ appendSnippet(snippet, item.text, input.value.trim());
119
+ row.append(top, snippet);
120
+ }
121
+ row.addEventListener("click", () => { selected = index; syncSelection(); activate(item); });
122
+ list.append(row);
123
+ });
124
+ if (!next.length && emptyKey) {
125
+ const empty = document.createElement("li");
126
+ empty.className = "palette-empty";
127
+ empty.setAttribute("role", "presentation");
128
+ empty.textContent = t(emptyKey);
129
+ list.append(empty);
130
+ }
131
+ syncSelection();
132
+ };
133
+ // Empty input is search, not a command wall: commands appear only after "/".
134
+ const showIdle = () => {
135
+ clearTimeout(searchTimer);
136
+ sequence++;
137
+ dialog.dataset.mode = "search";
138
+ dialog.dataset.state = "ready";
139
+ modeLabel.textContent = t("paletteSearchMode");
140
+ list.setAttribute("aria-busy", "false");
141
+ render([], null);
142
+ status.textContent = t("palettePlaceholder");
143
+ };
144
+ const showCommands = (fragment = "") => {
145
+ clearTimeout(searchTimer);
146
+ sequence++;
147
+ const needle = fragment.trim().toLowerCase();
148
+ const available = commands()
149
+ .filter((command) => !needle || `${command.label} ${command.en || ""} ${command.keywords || ""} ${command.id}`.toLowerCase().includes(needle))
150
+ .map((command) => ({ kind: "command", ...command }));
151
+ dialog.dataset.mode = "commands";
152
+ dialog.dataset.state = "ready";
153
+ modeLabel.textContent = t("paletteCommandMode");
154
+ list.setAttribute("aria-busy", "false");
155
+ render(available, "paletteNoCommands");
156
+ status.textContent = needle
157
+ ? available.length ? t("paletteResults", { count: available.length }) : t("paletteNoCommands")
158
+ : t("paletteCommandsHint");
159
+ };
160
+ const senderName = (source, message) => {
161
+ if (source.kind === "direct")
162
+ return source.participants?.find((person) => person.id === message.senderId)?.name || message.senderId;
163
+ return message.senderId;
164
+ };
165
+ const localSearch = (text, searchScope) => {
166
+ const needle = text.toLowerCase();
167
+ const entries = searchScope === "all"
168
+ ? [...app.state.rooms.values()]
169
+ : [app.state.rooms.get(app.state.room?.id)].filter(Boolean);
170
+ const hits = [];
171
+ for (const entry of entries) {
172
+ const source = entry.room;
173
+ if (!source?.messages)
174
+ continue;
175
+ for (const message of source.messages) {
176
+ if (message.recalledAt || message.pending || message.senderId === "system")
177
+ continue;
178
+ const body = String(message.text ?? "");
179
+ if (!body.toLowerCase().includes(needle))
180
+ continue;
181
+ const hit = {
182
+ roomId: source.id,
183
+ roomName: source.name || app.state.roomNames.get(source.id) || "",
184
+ messageId: message.id,
185
+ sender: senderName(source, message),
186
+ createdAt: message.createdAt,
187
+ text: body,
188
+ };
189
+ hits.push({ kind: "hit", raw: hit, ...hit });
190
+ }
191
+ }
192
+ hits.sort((a, b) => b.createdAt - a.createdAt);
193
+ return hits.slice(0, 80);
194
+ };
195
+ const normalizeHits = (raw) => raw.map((item) => {
196
+ if (!item || typeof item !== "object")
197
+ return null;
198
+ const message = item.message || {};
199
+ const roomId = String(item.roomId ?? item.roomID ?? item.room?.id ?? "");
200
+ const messageId = String(item.messageId ?? item.messageID ?? message.id ?? item.id ?? "");
201
+ if (!messageId)
202
+ return null;
203
+ return {
204
+ kind: "hit",
205
+ raw: item,
206
+ roomId,
207
+ messageId,
208
+ roomName: String(item.roomName ?? item.room?.name ?? app.state.roomNames.get(roomId) ?? app.state.rooms.get(roomId)?.room?.name ?? ""),
209
+ sender: String(item.senderName ?? item.sender ?? item.senderId ?? message.senderId ?? ""),
210
+ createdAt: Number(item.createdAt ?? message.createdAt ?? item.ts ?? 0) || 0,
211
+ text: String(item.text ?? item.snippet ?? item.preview ?? message.text ?? ""),
190
212
  };
191
- hits.push({ kind: "hit", raw: hit, ...hit });
192
- }
193
- }
194
- hits.sort((a, b) => b.createdAt - a.createdAt);
195
- return hits.slice(0, 80);
196
- };
197
-
198
- const normalizeHits = (raw) => raw.map((item) => {
199
- if (!item || typeof item !== "object") return null;
200
- const message = item.message || {};
201
- const roomId = String(item.roomId ?? item.roomID ?? item.room?.id ?? "");
202
- const messageId = String(item.messageId ?? item.messageID ?? message.id ?? item.id ?? "");
203
- if (!messageId) return null;
204
- return {
205
- kind: "hit",
206
- raw: item,
207
- roomId,
208
- messageId,
209
- roomName: String(item.roomName ?? item.room?.name ?? app.state.roomNames.get(roomId) ?? app.state.rooms.get(roomId)?.room?.name ?? ""),
210
- sender: String(item.senderName ?? item.sender ?? item.senderId ?? message.senderId ?? ""),
211
- createdAt: Number(item.createdAt ?? message.createdAt ?? item.ts ?? 0) || 0,
212
- text: String(item.text ?? item.snippet ?? item.preview ?? message.text ?? ""),
213
+ }).filter(Boolean);
214
+ const failSearch = () => {
215
+ dialog.dataset.state = "ready";
216
+ list.setAttribute("aria-busy", "false");
217
+ render([], null);
218
+ status.textContent = t("paletteSearchFailed");
213
219
  };
214
- }).filter(Boolean);
215
-
216
- const failSearch = () => {
217
- dialog.dataset.state = "ready";
218
- list.setAttribute("aria-busy", "false");
219
- render([], null);
220
- status.textContent = t("paletteSearchFailed");
221
- };
222
-
223
- const executeSearch = async (text, token) => {
224
- let result;
225
- try {
226
- result = typeof app.searchMessages === "function" ? await app.searchMessages(text, scope) : localSearch(text, scope);
227
- } catch {
228
- if (token === sequence) failSearch();
229
- return;
230
- }
231
- if (token !== sequence) return;
232
- const raw = Array.isArray(result) ? result
233
- : Array.isArray(result?.hits) ? result.hits
234
- : Array.isArray(result?.results) ? result.results
235
- : Array.isArray(result?.items) ? result.items : [];
236
- const hits = normalizeHits(raw).slice(0, 80);
237
- dialog.dataset.state = "ready";
238
- list.setAttribute("aria-busy", "false");
239
- render(hits, "paletteNoResults");
240
- status.textContent = hits.length ? t("paletteResults", { count: hits.length }) : t("paletteNoResults");
241
- };
242
-
243
- const scheduleSearch = () => {
244
- clearTimeout(searchTimer);
245
- const token = ++sequence;
246
- const value = input.value;
247
- if (!value.trim()) { showIdle(); return; }
248
- if (value.startsWith("/")) { showCommands(value.slice(1)); return; }
249
- const wasSearch = dialog.dataset.mode === "search";
250
- dialog.dataset.mode = "search";
251
- dialog.dataset.state = "searching";
252
- modeLabel.textContent = t("paletteSearchMode");
253
- list.setAttribute("aria-busy", "true");
254
- // Keep the previous hits visible while typing. Clearing them on every
255
- // keystroke is what makes the result list flicker.
256
- if (!wasSearch || !items.length) render([], null);
257
- else { selected = -1; syncSelection(); }
258
- status.textContent = t("paletteSearching");
259
- const text = value.trim();
260
- searchTimer = setTimeout(() => { void executeSearch(text, token); }, SEARCH_DEBOUNCE_MS);
261
- };
262
-
263
- const highlightHit = (item) => {
264
- if (!item?.messageId) return;
265
- clearTimeout(hitTimer);
266
- document.querySelectorAll("#msgList .palette-hit").forEach((row) => row.classList.remove("palette-hit"));
267
- let attempts = 0;
268
- const reveal = () => {
269
- const row = document.querySelector(`#msgList [data-msg-id="${CSS.escape(item.messageId)}"]`);
270
- if (row) {
271
- row.scrollIntoView({ block: "center", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
272
- row.classList.add("palette-hit");
273
- hitTimer = setTimeout(() => row.classList.remove("palette-hit"), 4000);
274
- return;
275
- }
276
- if (++attempts < 50) setTimeout(reveal, 50);
220
+ const executeSearch = async (text, token) => {
221
+ let result;
222
+ try {
223
+ result = typeof app.searchMessages === "function" ? await app.searchMessages(text, scope) : localSearch(text, scope);
224
+ }
225
+ catch {
226
+ if (token === sequence)
227
+ failSearch();
228
+ return;
229
+ }
230
+ if (token !== sequence)
231
+ return;
232
+ const raw = Array.isArray(result) ? result
233
+ : Array.isArray(result?.hits) ? result.hits
234
+ : Array.isArray(result?.results) ? result.results
235
+ : Array.isArray(result?.items) ? result.items : [];
236
+ const hits = normalizeHits(raw).slice(0, 80);
237
+ dialog.dataset.state = "ready";
238
+ list.setAttribute("aria-busy", "false");
239
+ render(hits, "paletteNoResults");
240
+ status.textContent = hits.length ? t("paletteResults", { count: hits.length }) : t("paletteNoResults");
277
241
  };
278
- reveal();
279
- };
280
-
281
- const openLocalHit = (item) => {
282
- if (item.roomId && app.state.room?.id !== item.roomId) app.activateRoom?.(item.roomId);
283
- };
284
-
285
- const activate = (item) => {
286
- if (!item) return;
287
- if (item.kind === "command") {
288
- closePalette({ focusComposer: item.focusComposer !== false });
289
- try { item.run(); } catch { /* The command owns its own error surface. */ }
290
- return;
291
- }
292
- closePalette();
293
- const raw = item.raw || item;
294
- if (typeof app.openSearchHit === "function") {
295
- Promise.resolve().then(() => app.openSearchHit(raw)).catch(() => openLocalHit(item)).finally(() => highlightHit(item));
296
- } else { openLocalHit(item); highlightHit(item); }
297
- };
298
-
299
- const moveSelection = (step) => {
300
- if (!items.length) return;
301
- selected = selected < 0 ? 0 : (selected + step + items.length) % items.length;
302
- syncSelection();
303
- };
304
-
305
- const toggleScope = () => {
306
- scope = scope === "room" ? "all" : "room";
307
- syncScope();
308
- const value = input.value;
309
- if (!value.trim()) showIdle();
310
- else if (value.startsWith("/")) showCommands(value.slice(1));
311
- else scheduleSearch();
312
- };
313
-
314
- const closePalette = (options = {}) => {
315
- if (!dialog.open) return;
316
- suppressComposerFocus = options.focusComposer === false;
317
- dialog.close();
318
- };
319
-
320
- const openPalette = () => {
321
- if (dialog.open) { input.focus(); return; }
322
- app.closePanels?.();
323
- app.closeMention?.();
324
- input.value = "";
325
- scope = "room";
326
- syncScope();
327
- showIdle();
328
- dialog.showModal();
329
- input.focus();
330
- };
331
- app.openPalette = openPalette;
332
-
333
- input.addEventListener("input", (event) => { if (!event.isComposing) scheduleSearch(); });
334
- // IME commits (Chinese, Japanese, Korean) may fire no plain input event after
335
- // composition ends, so filter the committed text here as well.
336
- input.addEventListener("compositionend", () => scheduleSearch());
337
- scopeButton.addEventListener("click", () => { toggleScope(); input.focus(); });
338
- app.$("#btnClosePalette")?.addEventListener("click", () => closePalette());
339
- let dismissPress = false;
340
- dialog.addEventListener("pointerdown", (event) => { dismissPress = event.target === dialog; });
341
- dialog.addEventListener("click", (event) => {
342
- if (event.target === dialog && dismissPress) closePalette();
343
- dismissPress = false;
344
- });
345
- dialog.addEventListener("cancel", (event) => { event.preventDefault(); closePalette(); });
346
- dialog.addEventListener("close", () => {
347
- clearTimeout(searchTimer);
348
- sequence++;
349
- list.setAttribute("aria-busy", "false");
350
- const suppressed = suppressComposerFocus;
351
- suppressComposerFocus = false;
352
- if (suppressed) return;
353
- requestAnimationFrame(() => {
354
- // A stacked dialog keeps its own focus; otherwise the composer owns the page.
355
- if (document.querySelector("dialog[open]")) return;
356
- const composer = app.$("#msgInput");
357
- if (app.state.room && !app.$("#chatView")?.hidden && composer?.contentEditable === "true") {
358
- const selection = getSelection();
359
- const selectionInside = Boolean(selection?.anchorNode && composer.contains(selection.anchorNode));
360
- composer.focus({ preventScroll: true });
361
- if (!selectionInside) composer.setCaret?.(composer.value.length);
362
- } else if (!app.state.room) app.$("#inRoomId")?.focus({ preventScroll: true });
242
+ const scheduleSearch = () => {
243
+ clearTimeout(searchTimer);
244
+ const token = ++sequence;
245
+ const value = input.value;
246
+ if (!value.trim()) {
247
+ showIdle();
248
+ return;
249
+ }
250
+ if (value.startsWith("/")) {
251
+ showCommands(value.slice(1));
252
+ return;
253
+ }
254
+ const wasSearch = dialog.dataset.mode === "search";
255
+ dialog.dataset.mode = "search";
256
+ dialog.dataset.state = "searching";
257
+ modeLabel.textContent = t("paletteSearchMode");
258
+ list.setAttribute("aria-busy", "true");
259
+ // Keep the previous hits visible while typing. Clearing them on every
260
+ // keystroke is what makes the result list flicker.
261
+ if (!wasSearch || !items.length)
262
+ render([], null);
263
+ else {
264
+ selected = -1;
265
+ syncSelection();
266
+ }
267
+ status.textContent = t("paletteSearching");
268
+ const text = value.trim();
269
+ searchTimer = setTimeout(() => { void executeSearch(text, token); }, SEARCH_DEBOUNCE_MS);
270
+ };
271
+ const highlightHit = (item) => {
272
+ if (!item?.messageId)
273
+ return;
274
+ clearTimeout(hitTimer);
275
+ document.querySelectorAll("#msgList .palette-hit").forEach((row) => row.classList.remove("palette-hit"));
276
+ let attempts = 0;
277
+ const reveal = () => {
278
+ const row = document.querySelector(`#msgList [data-msg-id="${CSS.escape(item.messageId)}"]`);
279
+ if (row) {
280
+ row.scrollIntoView({ block: "center", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
281
+ row.classList.add("palette-hit");
282
+ hitTimer = setTimeout(() => row.classList.remove("palette-hit"), 4000);
283
+ return;
284
+ }
285
+ if (++attempts < 50)
286
+ setTimeout(reveal, 50);
287
+ };
288
+ reveal();
289
+ };
290
+ const openLocalHit = (item) => {
291
+ if (item.roomId && app.state.room?.id !== item.roomId)
292
+ app.activateRoom?.(item.roomId);
293
+ };
294
+ const activate = (item) => {
295
+ if (!item)
296
+ return;
297
+ if (item.kind === "command") {
298
+ closePalette({ focusComposer: item.focusComposer !== false });
299
+ try {
300
+ item.run();
301
+ }
302
+ catch { /* The command owns its own error surface. */ }
303
+ return;
304
+ }
305
+ closePalette();
306
+ const raw = item.raw || item;
307
+ if (typeof app.openSearchHit === "function") {
308
+ Promise.resolve().then(() => app.openSearchHit(raw)).catch(() => openLocalHit(item)).finally(() => highlightHit(item));
309
+ }
310
+ else {
311
+ openLocalHit(item);
312
+ highlightHit(item);
313
+ }
314
+ };
315
+ const moveSelection = (step) => {
316
+ if (!items.length)
317
+ return;
318
+ selected = selected < 0 ? 0 : (selected + step + items.length) % items.length;
319
+ syncSelection();
320
+ };
321
+ const toggleScope = () => {
322
+ scope = scope === "room" ? "all" : "room";
323
+ syncScope();
324
+ const value = input.value;
325
+ if (!value.trim())
326
+ showIdle();
327
+ else if (value.startsWith("/"))
328
+ showCommands(value.slice(1));
329
+ else
330
+ scheduleSearch();
331
+ };
332
+ const closePalette = (options = {}) => {
333
+ if (!dialog.open)
334
+ return;
335
+ suppressComposerFocus = options.focusComposer === false;
336
+ dialog.close();
337
+ };
338
+ const openPalette = () => {
339
+ if (dialog.open) {
340
+ input.focus();
341
+ return;
342
+ }
343
+ app.closePanels?.();
344
+ app.closeMention?.();
345
+ input.value = "";
346
+ scope = "room";
347
+ syncScope();
348
+ showIdle();
349
+ dialog.showModal();
350
+ input.focus();
351
+ };
352
+ app.openPalette = openPalette;
353
+ input.addEventListener("input", (event) => { if (!event.isComposing)
354
+ scheduleSearch(); });
355
+ // IME commits (Chinese, Japanese, Korean) may fire no plain input event after
356
+ // composition ends, so filter the committed text here as well.
357
+ input.addEventListener("compositionend", () => scheduleSearch());
358
+ scopeButton.addEventListener("click", () => { toggleScope(); input.focus(); });
359
+ app.$("#btnClosePalette")?.addEventListener("click", () => closePalette());
360
+ let dismissPress = false;
361
+ dialog.addEventListener("pointerdown", (event) => { dismissPress = event.target === dialog; });
362
+ dialog.addEventListener("click", (event) => {
363
+ if (event.target === dialog && dismissPress)
364
+ closePalette();
365
+ dismissPress = false;
366
+ });
367
+ dialog.addEventListener("cancel", (event) => { event.preventDefault(); closePalette(); });
368
+ dialog.addEventListener("close", () => {
369
+ clearTimeout(searchTimer);
370
+ sequence++;
371
+ list.setAttribute("aria-busy", "false");
372
+ const suppressed = suppressComposerFocus;
373
+ suppressComposerFocus = false;
374
+ if (suppressed)
375
+ return;
376
+ requestAnimationFrame(() => {
377
+ // A stacked dialog keeps its own focus; otherwise the composer owns the page.
378
+ if (document.querySelector("dialog[open]"))
379
+ return;
380
+ const composer = app.$("#msgInput");
381
+ if (app.state.room && !app.$("#chatView")?.hidden && composer?.contentEditable === "true") {
382
+ const selection = getSelection();
383
+ const selectionInside = Boolean(selection?.anchorNode && composer.contains(selection.anchorNode));
384
+ composer.focus({ preventScroll: true });
385
+ if (!selectionInside)
386
+ composer.setCaret?.(composer.value.length);
387
+ }
388
+ else if (!app.state.room)
389
+ app.$("#inRoomId")?.focus({ preventScroll: true });
390
+ });
363
391
  });
364
- });
365
-
366
- dialog.addEventListener("keydown", (event) => {
367
- if (event.isComposing) return;
368
- if (event.key === "Tab") {
369
- event.preventDefault();
370
- toggleScope();
371
- return;
372
- }
373
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
374
- event.preventDefault();
375
- moveSelection(event.key === "ArrowDown" ? 1 : -1);
376
- return;
377
- }
378
- if (event.key === "Home" || event.key === "End") {
379
- if (!items.length) return;
380
- event.preventDefault();
381
- selected = event.key === "Home" ? 0 : items.length - 1;
382
- syncSelection();
383
- return;
384
- }
385
- if (event.key === "Enter") {
386
- if (!items.length || selected < 0) return;
387
- event.preventDefault();
388
- activate(items[selected]);
389
- return;
390
- }
391
- if (event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
392
- const digit = /^(?:Digit|Numpad)([1-9])$/.exec(event.code)?.[1] ?? (/^[1-9]$/.test(event.key) ? event.key : null);
393
- const index = digit ? Number(digit) - 1 : -1;
394
- if (digit) {
392
+ dialog.addEventListener("keydown", (event) => {
393
+ if (event.isComposing)
394
+ return;
395
+ if (event.key === "Tab") {
396
+ event.preventDefault();
397
+ toggleScope();
398
+ return;
399
+ }
400
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
401
+ event.preventDefault();
402
+ moveSelection(event.key === "ArrowDown" ? 1 : -1);
403
+ return;
404
+ }
405
+ if (event.key === "Home" || event.key === "End") {
406
+ if (!items.length)
407
+ return;
408
+ event.preventDefault();
409
+ selected = event.key === "Home" ? 0 : items.length - 1;
410
+ syncSelection();
411
+ return;
412
+ }
413
+ if (event.key === "Enter") {
414
+ if (!items.length || selected < 0)
415
+ return;
416
+ event.preventDefault();
417
+ activate(items[selected]);
418
+ return;
419
+ }
420
+ if (event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
421
+ const digit = /^(?:Digit|Numpad)([1-9])$/.exec(event.code)?.[1] ?? (/^[1-9]$/.test(event.key) ? event.key : null);
422
+ const index = digit ? Number(digit) - 1 : -1;
423
+ if (digit) {
424
+ event.preventDefault();
425
+ event.stopPropagation();
426
+ if (index >= 0 && index < items.length) {
427
+ selected = index;
428
+ syncSelection();
429
+ }
430
+ }
431
+ }
432
+ });
433
+ document.addEventListener("keydown", (event) => {
434
+ if (event.defaultPrevented || event.isComposing)
435
+ return;
436
+ const altSpace = event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
437
+ && (event.code === "Space" || event.key === " ");
438
+ const ctrlP = event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey
439
+ && (event.code === "KeyP" || event.key.toLowerCase() === "p");
440
+ if (!altSpace && !ctrlP)
441
+ return;
395
442
  event.preventDefault();
396
443
  event.stopPropagation();
397
- if (index >= 0 && index < items.length) {
398
- selected = index;
399
- syncSelection();
400
- }
401
- }
402
- }
403
- });
404
-
405
- document.addEventListener("keydown", (event) => {
406
- if (event.defaultPrevented || event.isComposing) return;
407
- const altSpace = event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
408
- && (event.code === "Space" || event.key === " ");
409
- const ctrlP = event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey
410
- && (event.code === "KeyP" || event.key.toLowerCase() === "p");
411
- if (!altSpace && !ctrlP) return;
412
- event.preventDefault();
413
- event.stopPropagation();
414
- openPalette();
415
- }, true);
416
-
417
- const applyLocale = app.applyLocale;
418
- app.applyLocale = () => {
419
- applyLocale();
420
- syncScope();
421
- if (!dialog.open) return;
422
- const value = input.value;
423
- if (!value.trim()) showIdle();
424
- else if (value.startsWith("/")) showCommands(value.slice(1));
425
- else scheduleSearch();
426
- };
427
- }
444
+ openPalette();
445
+ }, true);
446
+ const applyLocale = app.applyLocale;
447
+ app.applyLocale = () => {
448
+ applyLocale();
449
+ syncScope();
450
+ if (!dialog.open)
451
+ return;
452
+ const value = input.value;
453
+ if (!value.trim())
454
+ showIdle();
455
+ else if (value.startsWith("/"))
456
+ showCommands(value.slice(1));
457
+ else
458
+ scheduleSearch();
459
+ };
460
+ }