@alexsun-top/opencode-chat-room 0.7.5 → 0.7.6

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 (42) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/cli.ts +20 -0
  5. package/dist/cli.js +18 -0
  6. package/package.json +1 -1
  7. package/server/assets/chat/doc-preview.js +113 -0
  8. package/server/assets/chat/events.js +6 -0
  9. package/server/assets/chat/files.js +14 -6
  10. package/server/assets/chat/index.js +2 -0
  11. package/server/assets/chat/locales/de.js +3 -3
  12. package/server/assets/chat/locales/es.js +3 -3
  13. package/server/assets/chat/locales/fr.js +3 -3
  14. package/server/assets/chat/locales/it.js +3 -3
  15. package/server/assets/chat/locales/ja.js +3 -3
  16. package/server/assets/chat/locales/ko.js +3 -3
  17. package/server/assets/chat/markdown.js +12 -4
  18. package/server/assets/chat/palette.js +9 -5
  19. package/server/assets/chat/state.js +6 -6
  20. package/server/assets/chat/system-messages.js +7 -1
  21. package/server/assets/doc-preview.css +158 -0
  22. package/server/assets/edit-room.css +8 -0
  23. package/server/assets/settings.css +9 -2
  24. package/server/chat.html +33 -15
  25. package/server/sw.js +1 -0
  26. package/src/tui/app.mjs +16 -1
  27. package/src/tui/http.mjs +109 -10
  28. package/src/tui/info-app.mjs +435 -0
  29. package/src/tui/info-content.mjs +198 -0
  30. package/src/tui/join-app.mjs +71 -0
  31. package/src/tui/main.mjs +23 -4
  32. package/src/tui/markdown.mjs +269 -0
  33. package/src/tui/message-app.mjs +177 -0
  34. package/src/tui/message-view.mjs +128 -0
  35. package/src/tui/palette-app.mjs +85 -9
  36. package/src/tui/palette.mjs +17 -2
  37. package/src/tui/reminder-app.mjs +189 -0
  38. package/src/tui/room-settings-app.mjs +249 -0
  39. package/src/tui/ui-content.mjs +136 -93
  40. package/src/tui/ui-overlay-view.mjs +255 -0
  41. package/src/tui/ui-view.mjs +2 -190
  42. package/src/tui/ui.mjs +103 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.6 — 2026-11-22
4
+
5
+ - Restore a usable caret when the search palette closes: the composer keeps keyboard focus and typing works immediately after Escape.
6
+ - Keep internal resource IDs out of user-facing text: the room rail previews attachment-only messages as Attachments, and terminal message bodies replace `[[resource:…]]` markers with Attachments instead of showing UUIDs.
7
+ - Use `/` as the command prefix in the web search palette, so `/` alone lists every command and `/leave` filters to Leave room; plain text still searches messages. Placeholders and translations follow.
8
+ - Start the terminal client automatically with Bun when `bunx` launches the package under Node but a supported Bun is installed, so the plain `bunx @alexsun-top/opencode-chat-room cli` form works.
9
+ - Render terminal message bodies as Markdown with theme-aware syntax highlighting, and show `<at>@name</at>` as a highlighted mention instead of literal tags. Keep recall, question, search-highlight, and sticky-scroll behavior.
10
+ - Add `/` command mode to the terminal client with Quit, members, announcements, questions and ask, files (download/upload/delete), join approvals, reminders, a redacted settings summary, room settings, and recall/reveal/reply by message ID, alongside the existing room, message, and search commands.
11
+ - Fix the terminal client's false disconnects: a 20-second inbox long poll now uses a matching request timeout instead of being cut off by the generic 10-second timeout.
12
+ - Preview Markdown resources in a rendered document view: a fixed right reading pane on wide, tall windows and a modal overlay on narrow or short ones, with Download retained and focus restored on close.
13
+ - Give every Settings row and Edit room field a matching Fluent icon, without adding another icon style or external requests.
14
+ - Manage room reminders from the terminal client: list, create one-time or cron reminders, edit text, pause/resume, and delete.
15
+ - Reject terminal file uploads over 100 MiB before reading them, so a large file cannot exhaust memory.
16
+
3
17
  ## 0.7.5 — 2026-11-21
4
18
 
5
19
  - Ask before applying a web app update: when a new service worker is ready, a bottom-left prompt offers **Update now** or **Later**. Nothing reloads until **Update now** is chosen; **Later** keeps the current page intact and lets the update apply on the next open.
package/README.md CHANGED
@@ -24,7 +24,7 @@ When upgrading an existing install, quit OpenCode first or use `opencode plugin
24
24
  On a machine reachable by the other devices, start the server. Replace `your-password` with a shared password:
25
25
 
26
26
  ```bash
27
- npx --yes --package=@alexsun-top/opencode-chat-room@0.7.5 -- opencode-chat-room --host 0.0.0.0 --port 4399 --token 'your-password'
27
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.7.6 -- opencode-chat-room --host 0.0.0.0 --port 4399 --token 'your-password'
28
28
  ```
29
29
 
30
30
  The server runs on Node.js 24.2+, Deno 2, or Bun; `bunx` and Deno commands are in the [reference](docs/reference.en.md#central-mode-multi-host). OpenCode itself still runs on Bun.
@@ -53,7 +53,7 @@ docker run --rm -p 4399:4399 -v chat-room-data:/data \
53
53
  ghcr.io/agentsyaml/opencode-chat-room:latest
54
54
  ```
55
55
 
56
- Pin a release with `ghcr.io/agentsyaml/opencode-chat-room:v0.7.5`. Rooms, messages and receipts live in the `/data` volume; keep it mounted across upgrades. If you bind-mount a host directory instead of a named volume, make it writable by uid `10001`.
56
+ Pin a release with `ghcr.io/agentsyaml/opencode-chat-room:v0.7.6`. Rooms, messages and receipts live in the `/data` volume; keep it mounted across upgrades. If you bind-mount a host directory instead of a named volume, make it writable by uid `10001`.
57
57
 
58
58
  ## 3. Start chatting
59
59
 
@@ -64,9 +64,9 @@ Pin a release with `ghcr.io/agentsyaml/opencode-chat-room:v0.7.5`. Rooms, messag
64
64
  - Use the room's reminder button for one-time or recurring reminders. Times default to the server's time zone.
65
65
  - Reminder text supports `{{time}}`, `{{initiator}}`, and `{{room}}`.
66
66
  - A compact shortcut chip under the composer shows Alt+/ (Option+/ on Mac); click it or press the keys to open the sheet. Alt+1…9 switches to a joined room by its position in the rail, Alt+Home/Alt+End smoothly scroll to the oldest/latest loaded message, and PageUp/PageDown scrolls the conversation in one animated step while you type, and Settings sets that step with a slider as a percentage of the conversation height (default 90%).
67
- - Press Alt+Space (Option+Space on Mac) anywhere, including the composer, to search messages. Search starts in the current room; Tab switches to all joined rooms and back. Type `>` to filter common commands instead. ↑/↓ and Enter open a result and highlight it in the conversation; Esc or a backdrop click closes and returns to the composer.
68
- - Attach files, drag them in, or paste images. The default limit is 500 MiB per file. Room Options also opens Announcements and Files, where Files can be filtered by uploader, preview supported media, and downloaded or deleted.
69
- - In a terminal, run `bunx --bun --package @alexsun-top/opencode-chat-room@0.7.5 opencode-chat-room cli` against the same server. The terminal client is built into the main package and supports room navigation, pending joins, sending, and Alt+Space (or Ctrl+P) search. It uses OpenTUI: Bun 1.3.14+ is recommended, Node.js 26.4+ needs `--experimental-ffi`, and Deno is not supported for this client. Only `cli` loads OpenTUI; the server and `watch` stay on Node.js 24.2+, Deno 2, and Bun.
67
+ - Press Alt+Space (Option+Space on Mac) anywhere, including the composer, to search messages. Search starts in the current room; Tab switches to all joined rooms and back. Type `/` to filter common commands instead. ↑/↓ and Enter open a result and highlight it in the conversation; Esc or a backdrop click closes and returns to the composer.
68
+ - Attach files, drag them in, or paste images. The default limit is 500 MiB per file. Room Options also opens Announcements and Files, where Files can be filtered by uploader, preview supported media and Markdown documents, and downloaded or deleted.
69
+ - In a terminal, run `bunx --package @alexsun-top/opencode-chat-room@0.7.6 opencode-chat-room cli` against the same server. The terminal client is built into the main package, renders Markdown with highlighted mentions, and supports room navigation, pending joins, sending, members, announcements, questions and asking, files, reminders, room settings, join approvals, recall/reveal/reply by message ID, settings, and Alt+Space (or Ctrl+P) search. Typing `/` in an empty composer opens commands, including quit. It uses OpenTUI: Bun 1.3.14+ is recommended, Node.js 26.4+ needs `--experimental-ffi`, and Deno is not supported for this client. If `bunx` starts the package with Node but a supported Bun is installed, the CLI relaunches itself with Bun. Only `cli` loads OpenTUI; the server and `watch` stay on Node.js 24.2+, Deno 2, and Bun.
70
70
  - Fenced code blocks are syntax-highlighted locally. Hover or focus a block for icon-only wrap and copy controls.
71
71
  - Agents can recall a message by ID; the original stays available to current members.
72
72
  - Agents can use the `room` tool's `read_resource` action to save an attachment to a temporary file before opening it.
package/README.zh-CN.md CHANGED
@@ -24,7 +24,7 @@
24
24
  在一台可被其他设备访问的机器上启动服务器,把 `换成自己的密码` 换成共享密码:
25
25
 
26
26
  ```bash
27
- npx --yes --package=@alexsun-top/opencode-chat-room@0.7.5 -- opencode-chat-room --host 0.0.0.0 --port 4399 --token '换成自己的密码'
27
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.7.6 -- opencode-chat-room --host 0.0.0.0 --port 4399 --token '换成自己的密码'
28
28
  ```
29
29
 
30
30
  服务端可在 Node.js 24.2+、Deno 2 或 Bun 上运行;`bunx` 与 Deno 命令见[参考文档](docs/reference.zh-CN.md)。OpenCode 本身仍运行在 Bun 上。
@@ -53,7 +53,7 @@ docker run --rm -p 4399:4399 -v chat-room-data:/data \
53
53
  ghcr.io/agentsyaml/opencode-chat-room:latest
54
54
  ```
55
55
 
56
- 用 `ghcr.io/agentsyaml/opencode-chat-room:v0.7.5` 可以固定到具体版本。房间、消息和回执都保存在 `/data` 卷里,升级时保留该卷即可。如果改用宿主目录做挂载,需要让该目录对 uid `10001` 可写。
56
+ 用 `ghcr.io/agentsyaml/opencode-chat-room:v0.7.6` 可以固定到具体版本。房间、消息和回执都保存在 `/data` 卷里,升级时保留该卷即可。如果改用宿主目录做挂载,需要让该目录对 uid `10001` 可写。
57
57
 
58
58
  ## 3. 开始聊天
59
59
 
@@ -64,9 +64,9 @@ docker run --rm -p 4399:4399 -v chat-room-data:/data \
64
64
  - 点击房间里的提醒按钮,可创建一次性或周期提醒。默认使用服务器时区。
65
65
  - 提醒正文支持 `{{time}}`、`{{initiator}}`、`{{room}}` 模板变量。
66
66
  - 输入框下方保留唯一快捷键入口,以紧凑标签显示 Alt+/(Mac 为 Option+/);点击或按快捷键都能打开面板。Alt+1…9 按房间在侧栏中的位置切换已加入房间,Alt+Home/Alt+End 平滑滚动到最早/最新的已加载消息,输入时用 PageUp/PageDown 按动画滚动一屏,步长可在设置中用滑动条按会话高度百分比调整(默认 90%)。
67
- - 在任意位置(包括输入框)按 Alt+Space(Mac 为 Option+Space)打开搜索:默认搜索当前房间,按 Tab 切换到全部已加入房间;输入 `>` 可改为过滤常用命令。↑/↓ 加 Enter 打开结果并在会话中高亮;Esc 或点击遮罩关闭并回到输入框。
68
- - 点击附件按钮、拖入文件或粘贴图片即可分享;默认单文件上限为 500 MiB。房间选项里还有“公告”和“文件”;文件可以按上传者筛选、预览支持的媒体,并下载或删除。
69
- - 终端里可以运行 `bunx --bun --package @alexsun-top/opencode-chat-room@0.7.5 opencode-chat-room cli` 连接同一个服务器。终端客户端已并入主包,支持房间切换、待审批加入、发消息和 Alt+Space(或 Ctrl+P)搜索。它使用 OpenTUI:推荐 Bun 1.3.14+,Node.js 26.4+ 需要 `--experimental-ffi`,Deno 不支持该客户端。只有 `cli` 会加载 OpenTUI;服务端和 `watch` 仍支持 Node.js 24.2+、Deno 2 和 Bun。
67
+ - 在任意位置(包括输入框)按 Alt+Space(Mac 为 Option+Space)打开搜索:默认搜索当前房间,按 Tab 切换到全部已加入房间;输入 `/` 可改为过滤常用命令。↑/↓ 加 Enter 打开结果并在会话中高亮;Esc 或点击遮罩关闭并回到输入框。
68
+ - 点击附件按钮、拖入文件或粘贴图片即可分享;默认单文件上限为 500 MiB。房间选项里还有“公告”和“文件”;文件可以按上传者筛选、预览支持的媒体和 Markdown 文档,并下载或删除。
69
+ - 终端里可以运行 `bunx --package @alexsun-top/opencode-chat-room@0.7.6 opencode-chat-room cli` 连接同一个服务器。终端客户端已并入主包,会渲染 Markdown 并高亮提及,支持房间切换、待审批加入、发消息、成员、公告、提问与发起提问、文件、提醒、房间设置、加入审核、按消息 ID 撤回/揭示/回复、设置和 Alt+Space(或 Ctrl+P)搜索;在空输入框输入 `/` 可打开命令并退出程序。它使用 OpenTUI:推荐 Bun 1.3.14+,Node.js 26.4+ 需要 `--experimental-ffi`,Deno 不支持该客户端。如果 `bunx` 使用 Node 启动但本机安装了受支持的 Bun,CLI 会自动改用 Bun 重新启动。只有 `cli` 会加载 OpenTUI;服务端和 `watch` 仍支持 Node.js 24.2+、Deno 2 和 Bun。
70
70
  - 围栏代码块会在本地做语法高亮;鼠标悬停或键盘聚焦时显示纯图标的自动换行和复制按钮。
71
71
  - Agent 可按消息 ID 撤回;当前成员仍可查看原文。
72
72
  - Agent 收到附件后可通过 `room` 的 `read_resource` 操作保存到临时文件,再打开查看。
package/cli.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
2
3
  import { existsSync } from "node:fs";
3
4
  import { readFile } from "node:fs/promises";
4
5
  import { fileURLToPath } from "node:url";
@@ -41,7 +42,26 @@ function validatePort(value: string): void {
41
42
  }
42
43
 
43
44
  const args = process.argv.slice(2);
45
+
46
+ // `bunx package` runs the bin with Node by default, even when Bun is installed.
47
+ // The terminal client needs Bun here, so hand off to a supported Bun when one is
48
+ // available instead of making every user remember the --bun flag.
49
+ function relaunchTuiWithBun(): void {
50
+ if (process.versions.bun) return;
51
+ const probe = spawnSync("bun", ["--version"], { encoding: "utf8" });
52
+ if (probe.error || probe.status !== 0) return;
53
+ const [major = 0, minor = 0, patch = 0] = String(probe.stdout).trim().split(".").map(Number);
54
+ const supported = major > 1 || (major === 1 && (minor > 3 || (minor === 3 && patch >= 14)));
55
+ if (!supported) return;
56
+ const child = spawnSync("bun", [fileURLToPath(import.meta.url), ...process.argv.slice(2)], {
57
+ stdio: "inherit",
58
+ env: process.env,
59
+ });
60
+ process.exit(child.status ?? 1);
61
+ }
62
+
44
63
  if (args[0] === "cli") {
64
+ relaunchTuiWithBun();
45
65
  // Keep the plain-JS TUI outside dist so bundling cannot hoist OpenTUI into
46
66
  // every CLI command. The packaged layout has dist/cli.js beside src/tui.
47
67
  const packaged = new URL("../src/tui/main.mjs", import.meta.url);
package/dist/cli.js CHANGED
@@ -7678,6 +7678,7 @@ var init_chat_server = __esm(async () => {
7678
7678
  });
7679
7679
 
7680
7680
  // cli.ts
7681
+ import { spawnSync } from "node:child_process";
7681
7682
  import { existsSync as existsSync3 } from "node:fs";
7682
7683
  import { readFile as readFile3 } from "node:fs/promises";
7683
7684
  import { fileURLToPath as fileURLToPath5 } from "node:url";
@@ -7715,7 +7716,24 @@ function validatePort(value) {
7715
7716
  }
7716
7717
  }
7717
7718
  var args = process.argv.slice(2);
7719
+ function relaunchTuiWithBun() {
7720
+ if (process.versions.bun)
7721
+ return;
7722
+ const probe = spawnSync("bun", ["--version"], { encoding: "utf8" });
7723
+ if (probe.error || probe.status !== 0)
7724
+ return;
7725
+ const [major = 0, minor = 0, patch = 0] = String(probe.stdout).trim().split(".").map(Number);
7726
+ const supported = major > 1 || major === 1 && (minor > 3 || minor === 3 && patch >= 14);
7727
+ if (!supported)
7728
+ return;
7729
+ const child = spawnSync("bun", [fileURLToPath5(import.meta.url), ...process.argv.slice(2)], {
7730
+ stdio: "inherit",
7731
+ env: process.env
7732
+ });
7733
+ process.exit(child.status ?? 1);
7734
+ }
7718
7735
  if (args[0] === "cli") {
7736
+ relaunchTuiWithBun();
7719
7737
  const packaged = new URL("../src/tui/main.mjs", import.meta.url);
7720
7738
  const source = new URL("./src/tui/main.mjs", import.meta.url);
7721
7739
  const entry = existsSync3(fileURLToPath5(packaged)) ? packaged : source;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.7.5",
3
+ "version": "0.7.6",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,113 @@
1
+ // Markdown resources open in a reading pane on wide screens, or in a modal overlay
2
+ // when the window is too narrow or too short to give the chat a usable column.
3
+ import { formatBytes, renderMarkdown } from "./markdown.js";
4
+
5
+ const PANE_QUERY = "(min-width: 1100px) and (min-height: 560px)";
6
+
7
+ export function initDocPreview(app) {
8
+ const dialog = app.$("#docPreview");
9
+ if (!dialog) return;
10
+ const title = app.$("#docPreviewTitle"), size = app.$("#docPreviewSize");
11
+ const status = app.$("#docPreviewStatus"), body = app.$("#docPreviewBody");
12
+ const empty = app.$("#docPreviewEmpty"), download = app.$("#btnDocPreviewDownload");
13
+ const chatView = app.$("#chatView"), pane = matchMedia(PANE_QUERY);
14
+ let current = null, blob = null, token = 0, opener = null, pendingReopen = false;
15
+
16
+ const show = () => {
17
+ if (pane.matches) {
18
+ dialog.classList.add("is-pane");
19
+ chatView.classList.add("has-doc");
20
+ if (!dialog.open) dialog.show();
21
+ } else {
22
+ dialog.classList.remove("is-pane");
23
+ chatView.classList.remove("has-doc");
24
+ if (!dialog.open) dialog.showModal();
25
+ }
26
+ };
27
+
28
+ // Crossing the breakpoint keeps the document: the pane becomes an overlay, or back.
29
+ const syncMode = () => {
30
+ if (!dialog.open || pane.matches === dialog.classList.contains("is-pane")) return;
31
+ pendingReopen = true;
32
+ dialog.close();
33
+ show();
34
+ title.focus({ preventScroll: true });
35
+ };
36
+
37
+ const open = async (roomId, resource, source) => {
38
+ opener = source instanceof HTMLElement ? source : null;
39
+ current = { roomId, resource };
40
+ const request = ++token;
41
+ blob = null;
42
+ title.textContent = resource.name;
43
+ size.textContent = formatBytes(resource.size);
44
+ status.textContent = app.t("resourceLoading");
45
+ body.textContent = "";
46
+ empty.hidden = true;
47
+ download.disabled = true;
48
+ if (app.preserveReadingLayout) await app.preserveReadingLayout(show);
49
+ else show();
50
+ if (request !== token) return;
51
+ title.focus({ preventScroll: true });
52
+ try {
53
+ const data = await app.apiBlob(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(resource.id)}/content`);
54
+ if (request !== token) return;
55
+ const text = await data.text();
56
+ if (request !== token) return;
57
+ blob = data;
58
+ renderMarkdown(body, text, app);
59
+ empty.hidden = body.children.length > 0;
60
+ status.textContent = "";
61
+ download.disabled = false;
62
+ } catch {
63
+ if (request === token) status.textContent = app.t("docPreviewFailed");
64
+ }
65
+ };
66
+
67
+ const close = (restoreFocus = true) => {
68
+ if (!restoreFocus) opener = null;
69
+ if (dialog.open) dialog.close();
70
+ };
71
+
72
+ const downloadDocument = () => {
73
+ if (!blob || !current) return;
74
+ const url = URL.createObjectURL(blob), link = document.createElement("a");
75
+ link.href = url;
76
+ link.download = String(current.resource.name).replace(/[\\/\u0000-\u001f\u007f]/g, "_") || "download";
77
+ document.body.append(link); link.click(); link.remove();
78
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
79
+ };
80
+
81
+ app.openDocPreview = (roomId, resource, source) => { void open(roomId, resource, source); };
82
+ app.closeDocPreview = () => close();
83
+
84
+ app.$("#btnCloseDocPreview")?.addEventListener("click", () => close());
85
+ download.addEventListener("click", downloadDocument);
86
+ dialog.addEventListener("click", (event) => {
87
+ if (event.target === dialog && !dialog.classList.contains("is-pane")) close();
88
+ });
89
+ dialog.addEventListener("cancel", (event) => { event.preventDefault(); close(); });
90
+ document.addEventListener("keydown", (event) => {
91
+ if (event.key !== "Escape" || !dialog.open || !dialog.classList.contains("is-pane")) return;
92
+ event.preventDefault();
93
+ close();
94
+ });
95
+ dialog.addEventListener("close", () => {
96
+ // A breakpoint switch closes and reopens the same dialog; its queued close event
97
+ // must not wipe the document that is already back on screen.
98
+ if (pendingReopen) { pendingReopen = false; return; }
99
+ token++;
100
+ current = null; blob = null;
101
+ chatView.classList.remove("has-doc");
102
+ dialog.classList.remove("is-pane");
103
+ title.textContent = ""; size.textContent = ""; status.textContent = "";
104
+ body.textContent = ""; empty.hidden = true; download.disabled = true;
105
+ const target = opener; opener = null;
106
+ if (target?.isConnected && target.getClientRects().length) target.focus({ preventScroll: true });
107
+ else app.focusChatComposer?.({ force: true });
108
+ });
109
+ const onChange = () => syncMode();
110
+ if (pane.addEventListener) pane.addEventListener("change", onChange);
111
+ else pane.addListener(onChange);
112
+ document.addEventListener("chat-room-activated", () => close(false));
113
+ }
@@ -12,7 +12,13 @@ export function initEvents(app) {
12
12
  if ($("#chatView").hidden || editor.contentEditable !== "true" || !editor.getClientRects().length) return false;
13
13
  if (roomRail.classList.contains("drawer-open")) return false;
14
14
  if (!force && (document.activeElement !== document.body || window.getSelection()?.toString())) return false;
15
+ const selection = window.getSelection();
16
+ const selectionInside = Boolean(selection?.anchorNode && editor.contains(selection.anchorNode));
15
17
  editor.focus({ preventScroll: true });
18
+ // A closed modal can leave the DOM selection inside its removed input even
19
+ // after the composer looks focused. Re-seat the caret so the next keystroke
20
+ // lands in the editor instead of disappearing.
21
+ if (force && !selectionInside) editor.setCaret?.(editor.value.length);
16
22
  return true;
17
23
  };
18
24
  app.focusComposer = () => {
@@ -2,6 +2,7 @@
2
2
  import { LS } from "./state.js";
3
3
  import { isRoomAdmin } from "./admin-badge.js";
4
4
  import { icon } from "./icons.js";
5
+ import { isMarkdownResource } from "./markdown.js";
5
6
 
6
7
  const PAGE_SIZE = 500;
7
8
  const UNKNOWN_UPLOADER = "__unknown_uploader__";
@@ -178,10 +179,11 @@ export function initFiles(app) {
178
179
  const actions = document.createElement("div");
179
180
  actions.className = "file-actions";
180
181
  const previewID = `file-preview-${resource.id}`;
181
- if (mediaKind(resource.mimeType)) {
182
- actions.append(actionButton("preview", app.t("filesPreviewLabel", { name: resource.name }), ICONS.preview, {
183
- "aria-expanded": "false", "aria-controls": previewID,
184
- }));
182
+ if (mediaKind(resource.mimeType) || isMarkdownResource(resource)) {
183
+ const inline = mediaKind(resource.mimeType);
184
+ actions.append(actionButton("preview", app.t("filesPreviewLabel", { name: resource.name }), ICONS.preview, inline
185
+ ? { "aria-expanded": "false", "aria-controls": previewID }
186
+ : {}));
185
187
  }
186
188
  actions.append(actionButton("download", app.t("filesDownloadLabel", { name: resource.name }), ICONS.download));
187
189
  if (canDelete(resource)) actions.append(actionButton("delete", app.t("filesDeleteLabel", { name: resource.name }), ICONS.trash));
@@ -338,7 +340,8 @@ export function initFiles(app) {
338
340
  hideError();
339
341
  const target = opener;
340
342
  opener = null;
341
- if (target?.isConnected) target.focus({ preventScroll: true });
343
+ // A document preview opens right after the file list closes; keep focus there.
344
+ if (target?.isConnected && !document.querySelector("dialog[open]")) target.focus({ preventScroll: true });
342
345
  });
343
346
  list.addEventListener("click", (event) => {
344
347
  const button = event.target.closest?.("[data-file-action]");
@@ -347,7 +350,12 @@ export function initFiles(app) {
347
350
  const resource = items.find((item) => item.id === row?.dataset.resourceId);
348
351
  if (!resource) return;
349
352
  const action = button.dataset.fileAction;
350
- if (action === "preview") void togglePreview(resource, row, button);
353
+ if (action === "preview" && isMarkdownResource(resource)) {
354
+ // The document pane lives in the chat view; the modal file list would hide it.
355
+ close();
356
+ app.openDocPreview(resource.roomID, resource, null);
357
+ }
358
+ else if (action === "preview") void togglePreview(resource, row, button);
351
359
  else if (action === "download") void download(resource);
352
360
  else if (action === "delete") void removeResource(resource);
353
361
  });
@@ -23,6 +23,7 @@ import { initInstallPrompt } from "./install-prompt.js";
23
23
  import { initShortcuts } from "./shortcuts.js";
24
24
  import { initPalette } from "./palette.js";
25
25
  import { initFiles } from "./files.js";
26
+ import { initDocPreview } from "./doc-preview.js";
26
27
  import { initViewport } from "./viewport.js";
27
28
  import { initSettings } from "./settings.js";
28
29
 
@@ -52,3 +53,4 @@ initViewport();
52
53
  initInstallPrompt(app);
53
54
  initPalette(app);
54
55
  initFiles(app);
56
+ initDocPreview(app);
@@ -43,7 +43,7 @@ export const de = {
43
43
  reminderEdit: "Bearbeiten", reminderEditHeading: "Erinnerung bearbeiten", reminderSave: "Änderungen speichern",
44
44
  reminderCreated: "Erinnerung erstellt.", reminderUpdated: "Erinnerung aktualisiert.", reminderDeleted: "Erinnerung gelöscht.",
45
45
  reminderInvalid: "Prüfen Sie Datum, CRON-Ausdruck mit 5 Feldern, IANA-Zeitzone und Erinnerungstext.", reminderLoadFailed: "Erinnerungen konnten nicht geladen werden. Ihr Entwurf ist noch da.",
46
- diagramLoading: "Diagramm wird gerendert…", diagramRenderFailed: "Diagramm nicht verfügbar; Quelle wird angezeigt.", resourceLoading: "Datei wird geladen…", resourceFailed: "Diese Datei konnte nicht geladen werden.", resourceDownload: "Herunterladen", resourceMoreActions: "Weitere Aktionen für {name}", resourcePreview: "Vorschau", resourceHide: "Vorschau ausblenden", zoomImage: "Bild öffnen", imagePreviewTitle: "Bildvorschau", imageZoomControls: "Bildzoom", zoomIn: "Vergrößern", zoomOut: "Verkleinern", zoomReset: "Zoom zurücksetzen", installTitle: "OC Chat installieren", installBody: "Zum Startbildschirm hinzufügen, um im Vollbild zu chatten.", installAction: "Installieren", installHow: "So installieren", installNotNow: "Später", installIosGuide: "Tippen Sie auf Teilen und dann auf Zum Home-Bildschirm.",
46
+ diagramLoading: "Diagramm wird gerendert…", diagramRenderFailed: "Diagramm nicht verfügbar; Quelle wird angezeigt.", resourceLoading: "Datei wird geladen…", resourceFailed: "Diese Datei konnte nicht geladen werden.", resourceDownload: "Herunterladen", resourceMoreActions: "Weitere Aktionen für {name}", resourcePreview: "Vorschau", resourceHide: "Vorschau ausblenden", docPreviewEyebrow: "Markdown-Vorschau", docPreviewFailed: "Dieses Dokument konnte nicht geladen werden.", docPreviewEmpty: "Dieses Dokument ist leer.", zoomImage: "Bild öffnen", imagePreviewTitle: "Bildvorschau", imageZoomControls: "Bildzoom", zoomIn: "Vergrößern", zoomOut: "Verkleinern", zoomReset: "Zoom zurücksetzen", installTitle: "OC Chat installieren", installBody: "Zum Startbildschirm hinzufügen, um im Vollbild zu chatten.", installAction: "Installieren", installHow: "So installieren", installNotNow: "Später", installIosGuide: "Tippen Sie auf Teilen und dann auf Zum Home-Bildschirm.",
47
47
  pwaUpdateTitle: "Update verfügbar", pwaUpdateBody: "Eine neue Version ist bereit. Jetzt neu laden oder beim nächsten Öffnen der App aktualisieren.", pwaUpdateNow: "Jetzt aktualisieren", pwaUpdateLater: "Später",
48
48
  announcementDelete: "Ankündigung löschen",
49
49
  announcementNew: "Neue Ankündigung", announcementEmpty: "Noch keine Ankündigungen.", announcementLoading: "Ankündigungen werden geladen…",
@@ -84,7 +84,7 @@ export const de = {
84
84
  shortcutsScroll: "Nachrichten beim Tippen scrollen", shortcutsJump: "Zum Anfang oder Ende der Unterhaltung springen", shortcutsMenus: "Menüs und Dialoge",
85
85
  shortcutsClose: "Geöffnetes Menü, Panel oder Dialog schließen",
86
86
  paletteTitle: "Suche und Befehle", paletteSearchLabel: "Nachrichten suchen",
87
- palettePlaceholder: "Nachrichten suchen oder > für Befehle", paletteScopeRoom: "Dieser Raum", paletteScopeAll: "Alle Räume",
87
+ palettePlaceholder: "Nachrichten suchen oder / für Befehle", paletteScopeRoom: "Dieser Raum", paletteScopeAll: "Alle Räume",
88
88
  paletteScopeHint: "Tab wechselt zwischen diesem Raum und allen beigetretenen Räumen", paletteSearchMode: "Suche", paletteCommandMode: "Befehle",
89
89
  paletteSearching: "Suche läuft…", paletteNoResults: "Keine Nachrichten gefunden.", paletteNoCommands: "Keine passenden Befehle.",
90
90
  paletteResults: ({ count }) => `${count} Ergebnis${count === 1 ? "" : "se"}`, paletteCommandsHint: "Häufige Befehle",
@@ -94,7 +94,7 @@ export const de = {
94
94
  filesUnknownUploader: "Unbekannter Absender", filesSummary: ({ count, size }) => `${count} Datei${count === 1 ? "" : "en"} · ${size}`,
95
95
  filesLoading: "Dateien werden geladen…", filesLoadFailed: "Dateien konnten nicht geladen werden. Bitte erneut versuchen.", filesEmpty: "In diesem Raum gibt es noch keine Dateien.",
96
96
  filesEmptyFiltered: "Keine Dateien von diesem Absender.", filesLoadMore: "Mehr laden",
97
- filesHint: "Bilder, Audio und Video lassen sich ansehen. Jede Datei lässt sich herunterladen.",
97
+ filesHint: "Bilder, Audio, Video und Markdown lassen sich ansehen. Jede Datei lässt sich herunterladen.",
98
98
  filesPreviewFailed: "Vorschau konnte nicht geladen werden.", filesDownloadFailed: "Diese Datei konnte nicht heruntergeladen werden.",
99
99
  filesPreviewLabel: ({ name }) => `${name} ansehen`, filesDownloadLabel: ({ name }) => `${name} herunterladen`,
100
100
  filesDeleteLabel: ({ name }) => `${name} löschen`, filesRefresh: "Dateien aktualisieren",
@@ -43,7 +43,7 @@ export const es = {
43
43
  reminderEdit: "Editar", reminderEditHeading: "Editar recordatorio", reminderSave: "Guardar cambios",
44
44
  reminderCreated: "Recordatorio creado.", reminderUpdated: "Recordatorio actualizado.", reminderDeleted: "Recordatorio eliminado.",
45
45
  reminderInvalid: "Revisa la fecha, la expresión CRON de 5 campos, la zona horaria IANA y el texto del recordatorio.", reminderLoadFailed: "No se pudieron cargar los recordatorios. Tu borrador sigue aquí.",
46
- diagramLoading: "Generando el diagrama…", diagramRenderFailed: "El diagrama no está disponible; se muestra su código fuente.", resourceLoading: "Cargando archivo…", resourceFailed: "No se pudo cargar este archivo.", resourceDownload: "Descargar", resourceMoreActions: "Más acciones para {name}", resourcePreview: "Vista previa", resourceHide: "Ocultar vista previa", zoomImage: "Abrir imagen", imagePreviewTitle: "Vista previa de la imagen", imageZoomControls: "Zoom de la imagen", zoomIn: "Acercar", zoomOut: "Alejar", zoomReset: "Restablecer zoom", installTitle: "Instalar OC Chat", installBody: "Añádelo a tu pantalla de inicio para chatear a pantalla completa.", installAction: "Instalar", installHow: "Cómo instalar", installNotNow: "Ahora no", installIosGuide: "Toca Compartir y luego Añadir a pantalla de inicio.",
46
+ diagramLoading: "Generando el diagrama…", diagramRenderFailed: "El diagrama no está disponible; se muestra su código fuente.", resourceLoading: "Cargando archivo…", resourceFailed: "No se pudo cargar este archivo.", resourceDownload: "Descargar", resourceMoreActions: "Más acciones para {name}", resourcePreview: "Vista previa", resourceHide: "Ocultar vista previa", docPreviewEyebrow: "Vista previa de Markdown", docPreviewFailed: "No se pudo cargar este documento.", docPreviewEmpty: "Este documento está vacío.", zoomImage: "Abrir imagen", imagePreviewTitle: "Vista previa de la imagen", imageZoomControls: "Zoom de la imagen", zoomIn: "Acercar", zoomOut: "Alejar", zoomReset: "Restablecer zoom", installTitle: "Instalar OC Chat", installBody: "Añádelo a tu pantalla de inicio para chatear a pantalla completa.", installAction: "Instalar", installHow: "Cómo instalar", installNotNow: "Ahora no", installIosGuide: "Toca Compartir y luego Añadir a pantalla de inicio.",
47
47
  pwaUpdateTitle: "Actualización disponible", pwaUpdateBody: "Hay una nueva versión lista. Recarga ahora o actualiza la próxima vez que abras la aplicación.", pwaUpdateNow: "Actualizar ahora", pwaUpdateLater: "Más tarde",
48
48
  announcementDelete: "Eliminar anuncio",
49
49
  announcementNew: "Nuevo anuncio", announcementEmpty: "Aún no hay anuncios.", announcementLoading: "Cargando anuncios…",
@@ -84,7 +84,7 @@ export const es = {
84
84
  shortcutsScroll: "Desplazar los mensajes mientras escribes", shortcutsJump: "Ir al principio o al final de la conversación", shortcutsMenus: "Menús y diálogos",
85
85
  shortcutsClose: "Cerrar el menú, panel o diálogo abierto",
86
86
  paletteTitle: "Búsqueda y comandos", paletteSearchLabel: "Buscar mensajes",
87
- palettePlaceholder: "Busca mensajes o escribe > para comandos", paletteScopeRoom: "Esta sala", paletteScopeAll: "Todas las salas",
87
+ palettePlaceholder: "Busca mensajes o escribe / para comandos", paletteScopeRoom: "Esta sala", paletteScopeAll: "Todas las salas",
88
88
  paletteScopeHint: "Tab alterna entre esta sala y todas las salas unidas", paletteSearchMode: "Búsqueda", paletteCommandMode: "Comandos",
89
89
  paletteSearching: "Buscando…", paletteNoResults: "No se encontraron mensajes.", paletteNoCommands: "No hay comandos coincidentes.",
90
90
  paletteResults: ({ count }) => `${count} resultado${count === 1 ? "" : "s"}`, paletteCommandsHint: "Comandos habituales",
@@ -94,7 +94,7 @@ export const es = {
94
94
  filesUnknownUploader: "Autor desconocido", filesSummary: ({ count, size }) => `${count} archivo${count === 1 ? "" : "s"} · ${size}`,
95
95
  filesLoading: "Cargando archivos…", filesLoadFailed: "No se pudieron cargar los archivos. Inténtalo de nuevo.", filesEmpty: "Esta sala aún no tiene archivos.",
96
96
  filesEmptyFiltered: "No hay archivos de este autor.", filesLoadMore: "Cargar más",
97
- filesHint: "Puedes previsualizar imágenes, audio y vídeo. Todos los archivos se pueden descargar.",
97
+ filesHint: "Puedes previsualizar imágenes, audio, vídeo y Markdown. Todos los archivos se pueden descargar.",
98
98
  filesPreviewFailed: "No se pudo cargar la vista previa.", filesDownloadFailed: "No se pudo descargar este archivo.",
99
99
  filesPreviewLabel: ({ name }) => `Vista previa de ${name}`, filesDownloadLabel: ({ name }) => `Descargar ${name}`,
100
100
  filesDeleteLabel: ({ name }) => `Eliminar ${name}`, filesRefresh: "Actualizar archivos",
@@ -43,7 +43,7 @@ export const fr = {
43
43
  reminderEdit: "Modifier", reminderEditHeading: "Modifier le rappel", reminderSave: "Enregistrer les modifications",
44
44
  reminderCreated: "Rappel créé.", reminderUpdated: "Rappel mis à jour.", reminderDeleted: "Rappel supprimé.",
45
45
  reminderInvalid: "Vérifiez la date, l’expression CRON à 5 champs, le fuseau IANA et le texte du rappel.", reminderLoadFailed: "Impossible de charger les rappels. Votre brouillon est toujours là.",
46
- diagramLoading: "Rendu du diagramme…", diagramRenderFailed: "Diagramme indisponible, affichage de sa source.", resourceLoading: "Chargement du fichier…", resourceFailed: "Impossible de charger ce fichier.", resourceDownload: "Télécharger", resourceMoreActions: "Plus d’actions pour {name}", resourcePreview: "Aperçu", resourceHide: "Masquer l’aperçu", zoomImage: "Ouvrir l’image", imagePreviewTitle: "Aperçu de l’image", imageZoomControls: "Zoom de l’image", zoomIn: "Zoom avant", zoomOut: "Zoom arrière", zoomReset: "Réinitialiser le zoom", installTitle: "Installer OC Chat", installBody: "Ajoutez-le à votre écran d’accueil pour discuter en plein écran.", installAction: "Installer", installHow: "Comment installer", installNotNow: "Plus tard", installIosGuide: "Touchez Partager, puis Ajouter à l’écran d’accueil.",
46
+ diagramLoading: "Rendu du diagramme…", diagramRenderFailed: "Diagramme indisponible, affichage de sa source.", resourceLoading: "Chargement du fichier…", resourceFailed: "Impossible de charger ce fichier.", resourceDownload: "Télécharger", resourceMoreActions: "Plus d’actions pour {name}", resourcePreview: "Aperçu", resourceHide: "Masquer l’aperçu", docPreviewEyebrow: "Aperçu Markdown", docPreviewFailed: "Impossible de charger ce document.", docPreviewEmpty: "Ce document est vide.", zoomImage: "Ouvrir l’image", imagePreviewTitle: "Aperçu de l’image", imageZoomControls: "Zoom de l’image", zoomIn: "Zoom avant", zoomOut: "Zoom arrière", zoomReset: "Réinitialiser le zoom", installTitle: "Installer OC Chat", installBody: "Ajoutez-le à votre écran d’accueil pour discuter en plein écran.", installAction: "Installer", installHow: "Comment installer", installNotNow: "Plus tard", installIosGuide: "Touchez Partager, puis Ajouter à l’écran d’accueil.",
47
47
  pwaUpdateTitle: "Mise à jour disponible", pwaUpdateBody: "Une nouvelle version est prête. Rechargez maintenant ou mettez à jour à la prochaine ouverture de l’application.", pwaUpdateNow: "Mettre à jour", pwaUpdateLater: "Plus tard",
48
48
  announcementDelete: "Supprimer l’annonce",
49
49
  announcementNew: "Nouvelle annonce", announcementEmpty: "Aucune annonce pour l’instant.", announcementLoading: "Chargement des annonces…",
@@ -84,7 +84,7 @@ export const fr = {
84
84
  shortcutsScroll: "Faire défiler les messages pendant la saisie", shortcutsJump: "Aller au début ou à la fin de la conversation", shortcutsMenus: "Menus et boîtes de dialogue",
85
85
  shortcutsClose: "Fermer le menu, le panneau ou la boîte de dialogue ouverts",
86
86
  paletteTitle: "Recherche et commandes", paletteSearchLabel: "Rechercher des messages",
87
- palettePlaceholder: "Rechercher des messages, ou > pour les commandes", paletteScopeRoom: "Ce salon", paletteScopeAll: "Tous les salons",
87
+ palettePlaceholder: "Rechercher des messages, ou / pour les commandes", paletteScopeRoom: "Ce salon", paletteScopeAll: "Tous les salons",
88
88
  paletteScopeHint: "Tab bascule entre ce salon et tous les salons rejoints", paletteSearchMode: "Recherche", paletteCommandMode: "Commandes",
89
89
  paletteSearching: "Recherche…", paletteNoResults: "Aucun message trouvé.", paletteNoCommands: "Aucune commande correspondante.",
90
90
  paletteResults: ({ count }) => `${count} résultat${count === 1 ? "" : "s"}`, paletteCommandsHint: "Commandes courantes",
@@ -94,7 +94,7 @@ export const fr = {
94
94
  filesUnknownUploader: "Envoyeur inconnu", filesSummary: ({ count, size }) => `${count} fichier${count === 1 ? "" : "s"} · ${size}`,
95
95
  filesLoading: "Chargement des fichiers…", filesLoadFailed: "Impossible de charger les fichiers. Réessayez.", filesEmpty: "Ce salon n’a pas encore de fichiers.",
96
96
  filesEmptyFiltered: "Aucun fichier de cet envoyeur.", filesLoadMore: "Charger plus",
97
- filesHint: "Prévisualisez les images, l’audio et la vidéo. Tous les fichiers peuvent être téléchargés.",
97
+ filesHint: "Prévisualisez les images, l’audio, la vidéo et Markdown. Tous les fichiers peuvent être téléchargés.",
98
98
  filesPreviewFailed: "Impossible de charger cet aperçu.", filesDownloadFailed: "Impossible de télécharger ce fichier.",
99
99
  filesPreviewLabel: ({ name }) => `Aperçu de ${name}`, filesDownloadLabel: ({ name }) => `Télécharger ${name}`,
100
100
  filesDeleteLabel: ({ name }) => `Supprimer ${name}`, filesRefresh: "Actualiser les fichiers",
@@ -43,7 +43,7 @@ export const it = {
43
43
  reminderEdit: "Modifica", reminderEditHeading: "Modifica promemoria", reminderSave: "Salva modifiche",
44
44
  reminderCreated: "Promemoria creato.", reminderUpdated: "Promemoria aggiornato.", reminderDeleted: "Promemoria eliminato.",
45
45
  reminderInvalid: "Controlla la data, l’espressione CRON a 5 campi, il fuso orario IANA e il testo del promemoria.", reminderLoadFailed: "Impossibile caricare i promemoria. La tua bozza è ancora qui.",
46
- diagramLoading: "Rendering del diagramma…", diagramRenderFailed: "Diagramma non disponibile; viene mostrato il codice sorgente.", resourceLoading: "Caricamento del file…", resourceFailed: "Impossibile caricare questo file.", resourceDownload: "Scarica", resourceMoreActions: "Altre azioni per {name}", resourcePreview: "Anteprima", resourceHide: "Nascondi anteprima", zoomImage: "Apri immagine", imagePreviewTitle: "Anteprima immagine", imageZoomControls: "Zoom immagine", zoomIn: "Ingrandisci", zoomOut: "Riduci", zoomReset: "Reimposta zoom", installTitle: "Installa OC Chat", installBody: "Aggiungilo alla schermata Home per una chat a schermo intero.", installAction: "Installa", installHow: "Come installare", installNotNow: "Non ora", installIosGuide: "Tocca Condividi, poi Aggiungi alla schermata Home.",
46
+ diagramLoading: "Rendering del diagramma…", diagramRenderFailed: "Diagramma non disponibile; viene mostrato il codice sorgente.", resourceLoading: "Caricamento del file…", resourceFailed: "Impossibile caricare questo file.", resourceDownload: "Scarica", resourceMoreActions: "Altre azioni per {name}", resourcePreview: "Anteprima", resourceHide: "Nascondi anteprima", docPreviewEyebrow: "Anteprima Markdown", docPreviewFailed: "Impossibile caricare questo documento.", docPreviewEmpty: "Questo documento è vuoto.", zoomImage: "Apri immagine", imagePreviewTitle: "Anteprima immagine", imageZoomControls: "Zoom immagine", zoomIn: "Ingrandisci", zoomOut: "Riduci", zoomReset: "Reimposta zoom", installTitle: "Installa OC Chat", installBody: "Aggiungilo alla schermata Home per una chat a schermo intero.", installAction: "Installa", installHow: "Come installare", installNotNow: "Non ora", installIosGuide: "Tocca Condividi, poi Aggiungi alla schermata Home.",
47
47
  pwaUpdateTitle: "Aggiornamento disponibile", pwaUpdateBody: "È pronta una nuova versione. Ricarica ora o aggiorna la prossima volta che apri l’app.", pwaUpdateNow: "Aggiorna ora", pwaUpdateLater: "Più tardi",
48
48
  announcementDelete: "Elimina annuncio",
49
49
  announcementNew: "Nuovo annuncio", announcementEmpty: "Nessun annuncio.", announcementLoading: "Caricamento degli annunci…",
@@ -84,7 +84,7 @@ export const it = {
84
84
  shortcutsScroll: "Scorri i messaggi mentre scrivi", shortcutsJump: "Vai all’inizio o alla fine della conversazione", shortcutsMenus: "Menu e finestre di dialogo",
85
85
  shortcutsClose: "Chiudi il menu, il pannello o la finestra di dialogo aperti",
86
86
  paletteTitle: "Ricerca e comandi", paletteSearchLabel: "Cerca messaggi",
87
- palettePlaceholder: "Cerca messaggi o digita > per i comandi", paletteScopeRoom: "Questa stanza", paletteScopeAll: "Tutte le stanze",
87
+ palettePlaceholder: "Cerca messaggi o digita / per i comandi", paletteScopeRoom: "Questa stanza", paletteScopeAll: "Tutte le stanze",
88
88
  paletteScopeHint: "Tab alterna tra questa stanza e tutte le stanze a cui hai aderito", paletteSearchMode: "Ricerca", paletteCommandMode: "Comandi",
89
89
  paletteSearching: "Ricerca in corso…", paletteNoResults: "Nessun messaggio trovato.", paletteNoCommands: "Nessun comando corrispondente.",
90
90
  paletteResults: ({ count }) => `${count} risultat${count === 1 ? "o" : "i"}`, paletteCommandsHint: "Comandi frequenti",
@@ -94,7 +94,7 @@ export const it = {
94
94
  filesUnknownUploader: "Autore sconosciuto", filesSummary: ({ count, size }) => `${count} file · ${size}`,
95
95
  filesLoading: "Caricamento dei file…", filesLoadFailed: "Impossibile caricare i file. Riprova.", filesEmpty: "Questa stanza non ha ancora file.",
96
96
  filesEmptyFiltered: "Nessun file di questo autore.", filesLoadMore: "Carica altri",
97
- filesHint: "Puoi visualizzare immagini, audio e video. Tutti i file si possono scaricare.",
97
+ filesHint: "Puoi visualizzare immagini, audio, video e Markdown. Tutti i file si possono scaricare.",
98
98
  filesPreviewFailed: "Impossibile caricare l’anteprima.", filesDownloadFailed: "Impossibile scaricare questo file.",
99
99
  filesPreviewLabel: ({ name }) => `Anteprima di ${name}`, filesDownloadLabel: ({ name }) => `Scarica ${name}`,
100
100
  filesDeleteLabel: ({ name }) => `Elimina ${name}`, filesRefresh: "Aggiorna i file",
@@ -44,7 +44,7 @@ export const ja = {
44
44
  reminderEdit: "編集", reminderEditHeading: "リマインダーを編集", reminderSave: "変更を保存",
45
45
  reminderCreated: "リマインダーを作成しました。", reminderUpdated: "リマインダーを更新しました。", reminderDeleted: "リマインダーを削除しました。",
46
46
  reminderInvalid: "日時、5 フィールドの CRON 式、IANA タイムゾーン、リマインダーのテキストを確認してください。", reminderLoadFailed: "リマインダーを読み込めませんでした。下書きは残っています。",
47
- diagramLoading: "図を描画中…", diagramRenderFailed: "図を表示できません。ソースを表示しています。", resourceLoading: "ファイルを読み込み中…", resourceFailed: "このファイルを読み込めませんでした。", resourceDownload: "ダウンロード", resourceMoreActions: "{name} のその他の操作", resourcePreview: "プレビュー", resourceHide: "プレビューを隠す", zoomImage: "画像を開く", imagePreviewTitle: "画像プレビュー", imageZoomControls: "画像のズーム", zoomIn: "拡大", zoomOut: "縮小", zoomReset: "ズームをリセット", installTitle: "OC Chat をインストール", installBody: "ホーム画面に追加すると、全画面でチャットできます。", installAction: "インストール", installHow: "インストール方法", installNotNow: "後で", installIosGuide: "共有をタップし、「ホーム画面に追加」を選択します。",
47
+ diagramLoading: "図を描画中…", diagramRenderFailed: "図を表示できません。ソースを表示しています。", resourceLoading: "ファイルを読み込み中…", resourceFailed: "このファイルを読み込めませんでした。", resourceDownload: "ダウンロード", resourceMoreActions: "{name} のその他の操作", resourcePreview: "プレビュー", resourceHide: "プレビューを隠す", docPreviewEyebrow: "Markdown プレビュー", docPreviewFailed: "このドキュメントを読み込めませんでした。", docPreviewEmpty: "このドキュメントは空です。", zoomImage: "画像を開く", imagePreviewTitle: "画像プレビュー", imageZoomControls: "画像のズーム", zoomIn: "拡大", zoomOut: "縮小", zoomReset: "ズームをリセット", installTitle: "OC Chat をインストール", installBody: "ホーム画面に追加すると、全画面でチャットできます。", installAction: "インストール", installHow: "インストール方法", installNotNow: "後で", installIosGuide: "共有をタップし、「ホーム画面に追加」を選択します。",
48
48
  pwaUpdateTitle: "アップデートがあります", pwaUpdateBody: "新しいバージョンの準備ができました。今すぐ再読み込みするか、次回起動時に更新できます。", pwaUpdateNow: "今すぐ更新", pwaUpdateLater: "後で",
49
49
  announcementDelete: "お知らせを削除",
50
50
  announcementNew: "新しいお知らせ", announcementEmpty: "お知らせはまだありません。", announcementLoading: "お知らせを読み込み中…",
@@ -84,7 +84,7 @@ export const ja = {
84
84
  shortcutsScroll: "入力中にメッセージをスクロール", shortcutsJump: "会話の先頭または末尾に移動", shortcutsMenus: "メニューとダイアログ",
85
85
  shortcutsClose: "開いているメニュー、パネル、ダイアログを閉じる",
86
86
  paletteTitle: "検索とコマンド", paletteSearchLabel: "メッセージを検索",
87
- palettePlaceholder: "メッセージを検索、> でコマンド", paletteScopeRoom: "このルーム", paletteScopeAll: "すべてのルーム",
87
+ palettePlaceholder: "メッセージを検索、/ でコマンド", paletteScopeRoom: "このルーム", paletteScopeAll: "すべてのルーム",
88
88
  paletteScopeHint: "Tab でこのルームと参加中のすべてのルームを切り替えます", paletteSearchMode: "検索", paletteCommandMode: "コマンド",
89
89
  paletteSearching: "検索中…", paletteNoResults: "メッセージは見つかりませんでした。", paletteNoCommands: "一致するコマンドはありません。",
90
90
  paletteResults: ({ count }) => `${count} 件の結果`, paletteCommandsHint: "よく使うコマンド",
@@ -94,7 +94,7 @@ export const ja = {
94
94
  filesUnknownUploader: "不明なアップロード者", filesSummary: ({ count, size }) => `${count} 個のファイル · ${size}`,
95
95
  filesLoading: "ファイルを読み込み中…", filesLoadFailed: "ファイルを読み込めませんでした。もう一度お試しください。", filesEmpty: "このルームにはまだファイルがありません。",
96
96
  filesEmptyFiltered: "このアップロード者のファイルはありません。", filesLoadMore: "さらに読み込む",
97
- filesHint: "画像・音声・動画をプレビューできます。すべてのファイルをダウンロードできます。",
97
+ filesHint: "画像・音声・動画・Markdown をプレビューできます。すべてのファイルをダウンロードできます。",
98
98
  filesPreviewFailed: "プレビューを読み込めませんでした。", filesDownloadFailed: "このファイルをダウンロードできませんでした。",
99
99
  filesPreviewLabel: ({ name }) => `${name} をプレビュー`, filesDownloadLabel: ({ name }) => `${name} をダウンロード`,
100
100
  filesDeleteLabel: ({ name }) => `${name} を削除`, filesRefresh: "ファイルを更新",
@@ -44,7 +44,7 @@ export const ko = {
44
44
  reminderEdit: "편집", reminderEditHeading: "리마인더 편집", reminderSave: "변경 사항 저장",
45
45
  reminderCreated: "리마인더를 만들었습니다.", reminderUpdated: "리마인더를 수정했습니다.", reminderDeleted: "리마인더를 삭제했습니다.",
46
46
  reminderInvalid: "날짜, 5필드 CRON 식, IANA 시간대, 리마인더 텍스트를 확인하세요.", reminderLoadFailed: "리마인더를 불러오지 못했습니다. 작성 중인 내용은 그대로 있습니다.",
47
- diagramLoading: "다이어그램 그리는 중…", diagramRenderFailed: "다이어그램을 표시할 수 없습니다. 원본을 표시합니다.", resourceLoading: "파일 불러오는 중…", resourceFailed: "이 파일을 불러오지 못했습니다.", resourceDownload: "다운로드", resourceMoreActions: "{name}의 추가 작업", resourcePreview: "미리 보기", resourceHide: "미리 보기 숨기기", zoomImage: "이미지 열기", imagePreviewTitle: "이미지 미리 보기", imageZoomControls: "이미지 확대/축소", zoomIn: "확대", zoomOut: "축소", zoomReset: "확대/축소 초기화", installTitle: "OC Chat 설치", installBody: "홈 화면에 추가하면 전체 화면으로 채팅할 수 있습니다.", installAction: "설치", installHow: "설치 방법", installNotNow: "나중에", installIosGuide: "공유를 탭한 다음 홈 화면에 추가를 선택하세요.",
47
+ diagramLoading: "다이어그램 그리는 중…", diagramRenderFailed: "다이어그램을 표시할 수 없습니다. 원본을 표시합니다.", resourceLoading: "파일 불러오는 중…", resourceFailed: "이 파일을 불러오지 못했습니다.", resourceDownload: "다운로드", resourceMoreActions: "{name}의 추가 작업", resourcePreview: "미리 보기", resourceHide: "미리 보기 숨기기", docPreviewEyebrow: "Markdown 미리 보기", docPreviewFailed: "이 문서를 불러오지 못했습니다.", docPreviewEmpty: "이 문서는 비어 있습니다.", zoomImage: "이미지 열기", imagePreviewTitle: "이미지 미리 보기", imageZoomControls: "이미지 확대/축소", zoomIn: "확대", zoomOut: "축소", zoomReset: "확대/축소 초기화", installTitle: "OC Chat 설치", installBody: "홈 화면에 추가하면 전체 화면으로 채팅할 수 있습니다.", installAction: "설치", installHow: "설치 방법", installNotNow: "나중에", installIosGuide: "공유를 탭한 다음 홈 화면에 추가를 선택하세요.",
48
48
  pwaUpdateTitle: "업데이트 가능", pwaUpdateBody: "새 버전이 준비되었습니다. 지금 새로고침하거나 다음에 앱을 열 때 업데이트할 수 있습니다.", pwaUpdateNow: "지금 업데이트", pwaUpdateLater: "나중에",
49
49
  announcementDelete: "공지 삭제",
50
50
  announcementNew: "새 공지", announcementEmpty: "아직 공지가 없습니다.", announcementLoading: "공지 불러오는 중…",
@@ -84,7 +84,7 @@ export const ko = {
84
84
  shortcutsScroll: "입력 중에 메시지 스크롤", shortcutsJump: "대화의 시작이나 끝으로 이동", shortcutsMenus: "메뉴 및 대화 상자",
85
85
  shortcutsClose: "열린 메뉴, 패널 또는 대화 상자 닫기",
86
86
  paletteTitle: "검색 및 명령", paletteSearchLabel: "메시지 검색",
87
- palettePlaceholder: "메시지를 검색하거나 > 로 명령 사용", paletteScopeRoom: "이 방", paletteScopeAll: "모든 방",
87
+ palettePlaceholder: "메시지를 검색하거나 / 로 명령 사용", paletteScopeRoom: "이 방", paletteScopeAll: "모든 방",
88
88
  paletteScopeHint: "Tab 키로 이 방과 참여 중인 모든 방을 전환합니다", paletteSearchMode: "검색", paletteCommandMode: "명령",
89
89
  paletteSearching: "검색 중…", paletteNoResults: "메시지를 찾지 못했습니다.", paletteNoCommands: "일치하는 명령이 없습니다.",
90
90
  paletteResults: ({ count }) => `결과 ${count}개`, paletteCommandsHint: "자주 쓰는 명령",
@@ -94,7 +94,7 @@ export const ko = {
94
94
  filesUnknownUploader: "알 수 없는 업로더", filesSummary: ({ count, size }) => `${count}개 파일 · ${size}`,
95
95
  filesLoading: "파일을 불러오는 중…", filesLoadFailed: "파일을 불러오지 못했습니다. 다시 시도해 주세요.", filesEmpty: "이 방에는 아직 파일이 없습니다.",
96
96
  filesEmptyFiltered: "이 업로더의 파일이 없습니다.", filesLoadMore: "더 불러오기",
97
- filesHint: "이미지, 오디오, 동영상을 미리 볼 수 있습니다. 모든 파일을 다운로드할 수 있습니다.",
97
+ filesHint: "이미지, 오디오, 동영상, Markdown을 미리 볼 수 있습니다. 모든 파일을 다운로드할 수 있습니다.",
98
98
  filesPreviewFailed: "미리보기를 불러오지 못했습니다.", filesDownloadFailed: "이 파일을 다운로드하지 못했습니다.",
99
99
  filesPreviewLabel: ({ name }) => `${name} 미리보기`, filesDownloadLabel: ({ name }) => `${name} 다운로드`,
100
100
  filesDeleteLabel: ({ name }) => `${name} 삭제`, filesRefresh: "파일 새로고침",
@@ -8,6 +8,11 @@ let mermaidReady = false;
8
8
  const previewUrls = new Map();
9
9
  let previewObserver;
10
10
 
11
+ export function isMarkdownResource(resource) {
12
+ const mime = String(resource?.mimeType || "").split(";")[0].trim().toLowerCase();
13
+ return mime === "text/markdown" || mime === "text/x-markdown" || /\.(?:md|markdown)$/i.test(String(resource?.name || ""));
14
+ }
15
+
11
16
  export function renderMarkdown(root, text, app) {
12
17
  const mentions = [], diagrams = new Map();
13
18
  const nonce = createRandomId();
@@ -221,11 +226,14 @@ async function loadResourceCard(card, roomId, app) {
221
226
  remove = resourceMenuItem("resourceDelete", () => deleteResource(card, roomId, id, resource, app, status, remove), app);
222
227
  actions.append(resourceSplit(app, resource, download, remove));
223
228
  } else actions.append(download);
224
- if (previewKind(type)) {
225
- const preview = resourceButton("resourcePreview", resource.name, () => previewResource(card, roomId, id, resource, type, preview, app, status), app);
229
+ const markdown = isMarkdownResource(resource);
230
+ if (previewKind(type) || markdown) {
231
+ const preview = resourceButton("resourcePreview", resource.name, () => markdown
232
+ ? app.openDocPreview(roomId, resource, preview)
233
+ : previewResource(card, roomId, id, resource, type, preview, app, status), app);
226
234
  actions.append(preview);
227
235
  // Media you sent yourself is shown inline; other people's media stays collapsed.
228
- if (card.closest(".msg.own")) void previewResource(card, roomId, id, resource, type, preview, app, status);
236
+ if (!markdown && card.closest(".msg.own")) void previewResource(card, roomId, id, resource, type, preview, app, status);
229
237
  }
230
238
  } catch (error) { if (card.isConnected) setResourceError(card, app, error?.status === 404 ? "resourceDeleted" : "resourceFailed"); }
231
239
  }
@@ -384,7 +392,7 @@ function previewKind(type) {
384
392
  if (["video/mp4", "video/webm", "video/ogg"].includes(type)) return "video";
385
393
  return "";
386
394
  }
387
- function formatBytes(value) {
395
+ export function formatBytes(value) {
388
396
  const bytes = Math.max(0, Number(value) || 0);
389
397
  if (bytes < 1024) return `${bytes} B`;
390
398
  return bytes < 1048576 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1048576).toFixed(1)} MB`;