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

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