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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/dist/cli.js +815 -192
  5. package/package.json +3 -2
  6. package/plugin.ts +15 -3
  7. package/server/assets/base.css +0 -2
  8. package/server/assets/chat/announcements.js +5 -2
  9. package/server/assets/chat/clipboard.js +30 -0
  10. package/server/assets/chat/copy-action.js +48 -0
  11. package/server/assets/chat/diagram-viewer.js +253 -0
  12. package/server/assets/chat/doc-preview.js +160 -13
  13. package/server/assets/chat/editor.js +10 -7
  14. package/server/assets/chat/events.js +26 -5
  15. package/server/assets/chat/files.js +26 -5
  16. package/server/assets/chat/history-loader.js +3 -1
  17. package/server/assets/chat/index.js +11 -1
  18. package/server/assets/chat/join-requests.js +6 -3
  19. package/server/assets/chat/locales/de.js +20 -2
  20. package/server/assets/chat/locales/es.js +20 -2
  21. package/server/assets/chat/locales/fr.js +20 -2
  22. package/server/assets/chat/locales/it.js +20 -2
  23. package/server/assets/chat/locales/ja.js +20 -2
  24. package/server/assets/chat/locales/ko.js +20 -2
  25. package/server/assets/chat/markdown.js +75 -86
  26. package/server/assets/chat/messages.js +7 -3
  27. package/server/assets/chat/palette.js +40 -18
  28. package/server/assets/chat/pwa.js +2 -0
  29. package/server/assets/chat/questions.js +6 -0
  30. package/server/assets/chat/resource-format.js +74 -0
  31. package/server/assets/chat/rooms.js +9 -1
  32. package/server/assets/chat/shortcuts.js +14 -3
  33. package/server/assets/chat/side-pane.js +136 -0
  34. package/server/assets/chat/state.js +85 -8
  35. package/server/assets/chat/system-messages.js +3 -1
  36. package/server/assets/chat/task-form.js +197 -0
  37. package/server/assets/chat/task-row.js +170 -0
  38. package/server/assets/chat/tasks.js +521 -0
  39. package/server/assets/chat/viewport.js +5 -0
  40. package/server/assets/conversation.css +25 -1
  41. package/server/assets/diagram-viewer.css +141 -0
  42. package/server/assets/doc-preview.css +24 -5
  43. package/server/assets/responsive.css +108 -14
  44. package/server/assets/tasks.css +419 -0
  45. package/server/chat-server.ts +9 -4
  46. package/server/chat.html +120 -21
  47. package/server/member-routes.ts +3 -0
  48. package/server/resource-routes.ts +3 -1
  49. package/server/sw.js +247 -4
  50. package/server/task-routes.ts +53 -0
  51. package/skills/chatroom/SKILL.md +3 -1
  52. package/src/README.md +3 -3
  53. package/src/agent/chatroom-skill.ts +8 -2
  54. package/src/agent/task-tool.ts +155 -0
  55. package/src/center/center-client.ts +44 -0
  56. package/src/rooms/resources.ts +2 -2
  57. package/src/rooms/tasks.ts +246 -0
  58. package/src/runtime/v2-plugin.ts +11 -2
  59. package/src/runtime/watch.ts +38 -5
  60. package/src/state/sqlite-state.ts +93 -8
  61. package/src/state/store.ts +2 -2
  62. package/src/tui/app.mjs +14 -4
  63. package/src/tui/http.mjs +2 -2
  64. package/src/tui/info-app.mjs +24 -15
  65. package/src/tui/join-app.mjs +3 -3
  66. package/src/tui/main.mjs +4 -4
  67. package/src/tui/markdown.mjs +31 -5
  68. package/src/tui/mentions.mjs +218 -0
  69. package/src/tui/message-app.mjs +15 -11
  70. package/src/tui/palette-app.mjs +19 -9
  71. package/src/tui/reminder-app.mjs +14 -10
  72. package/src/tui/ui-content.mjs +12 -3
  73. package/src/tui/ui-mentions.mjs +44 -0
  74. package/src/tui/ui-suggest-view.mjs +63 -0
  75. package/src/tui/ui-suggest.mjs +197 -0
  76. package/src/tui/ui-theme.mjs +2 -1
  77. package/src/tui/ui-view.mjs +2 -0
  78. package/src/tui/ui.mjs +17 -9
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.7.6",
3
+ "version": "0.7.8",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -40,6 +40,7 @@
40
40
  "server/join-requests.ts",
41
41
  "server/room-join.ts",
42
42
  "server/member-routes.ts",
43
+ "server/task-routes.ts",
43
44
  "server/announcement-routes.ts",
44
45
  "server/resource-routes.ts",
45
46
  "server/admin-routes.ts",
@@ -66,7 +67,7 @@
66
67
  "server": "node cli.ts",
67
68
  "server:bun": "bun cli.ts",
68
69
  "server:deno": "deno run --allow-env --allow-read --allow-write --allow-net cli.ts",
69
- "test": "for file in src/tests/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done && bun test src/tui/test",
70
+ "test": "for file in src/tests/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done && bun test src/tui/test --isolate",
70
71
  "typecheck": "tsc --noEmit"
71
72
  },
72
73
  "engines": {
package/plugin.ts CHANGED
@@ -30,6 +30,7 @@ import { explicitlyAddresses } from "./src/center/mentions.ts";
30
30
  import { createV2Setup, type V2Runtime } from "./src/runtime/v2-plugin.ts";
31
31
  import { createV1Server } from "./src/runtime/v1-plugin.ts";
32
32
  import { runAnnouncementTool } from "./src/agent/announcement-tool.ts";
33
+ import { runTaskTool } from "./src/agent/task-tool.ts";
33
34
  import { uploadAgentResource } from "./src/rooms/resource-upload.ts";
34
35
  import { readAgentResource, resourceReadFailure } from "./src/rooms/resource-read.ts";
35
36
  import { adminTool, adminToolDescription, adminToolSchema } from "./src/agent/admin-client.ts";
@@ -247,7 +248,7 @@ export async function pollKnownSessions(
247
248
  await flushReceiptCandidates({ destination: receiptDestination(""), receiverOwnerID: transport.receiverOwnerID }).catch(() => {});
248
249
  }
249
250
 
250
- const READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "join_status", "announcement_list", "announcement_read"]);
251
+ const READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "join_status", "announcement_list", "announcement_read", "task_list"]);
251
252
 
252
253
  function actionableError(error: unknown): string {
253
254
  const message = error instanceof Error ? error.message : String(error);
@@ -270,7 +271,7 @@ function actionableError(error: unknown): string {
270
271
  }
271
272
 
272
273
  export const roomArgs = z.object({
273
- action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
274
+ action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
274
275
  name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
275
276
  roomId: z.string().optional().describe("Room UUID, not the room name. Required for resource actions and every room-scoped action."),
276
277
  messageId: z.string().optional().describe("For recall: the full message ID returned by send or poll; required for recall."),
@@ -280,6 +281,15 @@ export const roomArgs = z.object({
280
281
  isQuestion: z.boolean().optional().describe("For send: mark the message as a question awaiting an answer."),
281
282
  announcementName: z.string().optional().describe("Exact announcement name from announcement_list; distinct from participant or room name."),
282
283
  content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters; required for announcement_write."),
284
+ taskId: z.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
285
+ title: z.string().optional().describe("Task title, 1 to 200 characters; required for task_create."),
286
+ description: z.string().optional().describe("Task description, at most 5000 characters."),
287
+ assignee: z.string().optional().describe("Participant display name responsible for the task; empty leaves it unassigned."),
288
+ status: z.enum(["todo", "doing", "done"]).optional().describe("Task status; the assignee may change only this field."),
289
+ dueDate: z.string().optional().describe("Task due date as YYYY-MM-DD; empty clears it."),
290
+ participants: z.array(z.string()).optional().describe("Task participants as room participant display names; empty clears them."),
291
+ conclusion: z.string().optional().describe("Task conclusion, at most 5000 characters; empty clears it."),
292
+ steps: z.array(z.union([z.string(), z.object({ text: z.string(), done: z.boolean().optional() })])).optional().describe("Task checklist, at most 30 steps; each is text of 1 to 300 characters or {text, done}; empty clears them."),
283
293
  reminderId: z.string().optional().describe("Reminder UUID from reminder_list; required for reminder_update and reminder_delete."),
284
294
  schedule: z.discriminatedUnion("type", [z.object({ type: z.literal("once"), at: z.string(), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() }), z.object({ type: z.literal("cron"), expression: z.string().regex(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() })]).optional(),
285
295
  paused: z.boolean().optional(),
@@ -343,6 +353,8 @@ const roomExecute = async (
343
353
  }
344
354
  const announcementResult = await runAnnouncementTool(args, context.sessionID);
345
355
  if (announcementResult !== undefined) return announcementResult;
356
+ const taskResult = await runTaskTool(args, context.sessionID);
357
+ if (taskResult !== undefined) return taskResult;
346
358
  // ponytail: act as the identity this session registered with on join
347
359
  let selfName = identity();
348
360
  let joinPrevName: string | undefined;
@@ -525,7 +537,7 @@ const roomExecute = async (
525
537
  }
526
538
  };
527
539
  const room = tool({
528
- description: "Chat room operations: create, join, leave and list rooms; send, poll and recall messages; list members and announcements; manage reminders. Sent and polled messages carry full message IDs; recall takes roomId plus messageId and withdraws the message for everyone (agents their own, room admins any). Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. Resource actions need both roomId (the room UUID) and resourceId (the UUID in the marker); the marker alone does not identify the room. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads. Room joinPolicy \"approval\" makes join a pending request: you are not a member while pending, never claim otherwise, and use join_status to check whether a human administrator approved it.",
540
+ description: "Chat room operations: create, join, leave and list rooms; send, poll and recall messages; list members, announcements and tasks; create, update and delete room tasks; manage reminders. Sent and polled messages carry full message IDs; recall takes roomId plus messageId and withdraws the message for everyone (agents their own, room admins any). Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. Resource actions need both roomId (the room UUID) and resourceId (the UUID in the marker); the marker alone does not identify the room. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads. Room joinPolicy \"approval\" makes join a pending request: you are not a member while pending, never claim otherwise, and use join_status to check whether a human administrator approved it.",
529
541
  args: roomArgs.shape,
530
542
  execute: roomExecute,
531
543
  });
@@ -347,8 +347,6 @@
347
347
  transition: background .12s, border-color .12s;
348
348
  }
349
349
  .room-row:hover { background: var(--surface-2); border-color: var(--line); }
350
- .room-row.room-switch-enter { animation: room-switch-row .15s cubic-bezier(.1, .9, .2, 1); }
351
- @keyframes room-switch-row { from { opacity: .55; transform: translateY(var(--room-switch-shift, 3px)); } }
352
350
  .r-name { font-weight: 600; font-size: 14px; }
353
351
  .r-meta { font-size: 12px; color: var(--ink-3); font-variant-numeric: tabular-nums; }
354
352
  .r-go {
@@ -118,10 +118,12 @@ export function initAnnouncements(app) {
118
118
  });
119
119
  $("#btnNewAnnouncement").addEventListener("click", () => openEditor(null));
120
120
  $("#btnDeleteAnnouncement").addEventListener("click", async () => {
121
- const id = roomId(), name = selected;
122
- if (!id || !name || !(await app.confirmAction(app.t("announcementDeleteConfirm", { name })))) return;
121
+ const id = roomId(), name = selected, button = $("#btnDeleteAnnouncement");
122
+ if (!id || !name || button.disabled) return;
123
+ button.disabled = true;
123
124
  const context = roomGeneration, captured = editorSnapshot();
124
125
  try {
126
+ if (!(await app.confirmAction(app.t("announcementDeleteConfirm", { name })))) return;
125
127
  await app.api(`/rooms/${encodeURIComponent(id)}/announcements/${encodeURIComponent(name)}`, { method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }) });
126
128
  if (currentRoom(id, context)) {
127
129
  generation++; items = items.filter((item) => item.name !== name); render();
@@ -129,6 +131,7 @@ export function initAnnouncements(app) {
129
131
  if (editorMatches(captured)) { select(null); status(app.t("announcementDeleted")); formStatus(""); dialog.close(); }
130
132
  }
131
133
  } catch (error) { if (currentRoom(id, context) && editorMatches(captured)) formStatus(error.message); }
134
+ finally { button.disabled = false; }
132
135
  });
133
136
  $("#btnRefreshAnnouncements").addEventListener("click", () => void load());
134
137
  $("#btnCloseAnnouncement").addEventListener("click", () => dialog.close());
@@ -0,0 +1,30 @@
1
+ // Clipboard writes with a legacy fallback for browsers or permissions that block
2
+ // the async Clipboard API. Mention copy keeps its marker HTML for later pastes.
3
+ export async function copyTextToClipboard(text, mentionSource = false) {
4
+ // The HTML marker lets a later paste rebuild mention chips; unmarked external text stays literal.
5
+ const html = mentionSource ? `<div data-chatroom-mentions>${String(text).replace(/[&<>"]/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[char])}</div>` : "";
6
+ try {
7
+ if (html && navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
8
+ await navigator.clipboard.write([new ClipboardItem({ "text/plain": new Blob([text], { type: "text/plain" }), "text/html": new Blob([html], { type: "text/html" }) })]);
9
+ return true;
10
+ }
11
+ if (navigator.clipboard?.writeText) {
12
+ await navigator.clipboard.writeText(text);
13
+ return true;
14
+ }
15
+ } catch { /* Use the legacy clipboard command when permission is unavailable. */ }
16
+ const field = document.createElement(html ? "div" : "textarea"), selection = getSelection(), active = document.activeElement;
17
+ const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index).cloneRange()) : [];
18
+ if (html) { field.contentEditable = "true"; field.innerHTML = html; } else field.value = text;
19
+ field.setAttribute("readonly", "");
20
+ field.style.cssText = "position:fixed;left:-9999px;top:0";
21
+ document.body.append(field);
22
+ if (html && selection) { const range = document.createRange(); range.selectNodeContents(field); selection.removeAllRanges(); selection.addRange(range); }
23
+ else if (!html) field.select();
24
+ let copied = false;
25
+ try { copied = document.execCommand("copy"); } catch { /* Clipboard access may be disabled. */ }
26
+ field.remove();
27
+ if (selection) { selection.removeAllRanges(); ranges.forEach((range) => selection.addRange(range)); }
28
+ if (active instanceof HTMLElement) active.focus({ preventScroll: true });
29
+ return copied;
30
+ }
@@ -0,0 +1,48 @@
1
+ // Copy buttons for resource cards, the file list, and the preview header.
2
+ import { copyTextToClipboard } from "./clipboard.js";
3
+ import { iconNode } from "./icons.js";
4
+
5
+ export function createCopyButton(app, className = "") {
6
+ const button = document.createElement("button");
7
+ button.type = "button";
8
+ button.className = `copy-action ${className}`.trim();
9
+ button.dataset.i18nAriaLabel = "copyMessage";
10
+ button.dataset.i18nTitle = "copyMessage";
11
+ button.setAttribute("aria-label", app.t("copyMessage"));
12
+ button.title = app.t("copyMessage");
13
+ const feedback = document.createElement("span");
14
+ feedback.className = "copy-feedback";
15
+ feedback.setAttribute("role", "status");
16
+ feedback.setAttribute("aria-live", "polite");
17
+ button.append(iconNode("copy", "copy-action-icon copy-icon"), iconNode("checkmark", "copy-action-icon copy-check"), feedback);
18
+ return button;
19
+ }
20
+
21
+ export function setCopyFeedback(button, app, copied) {
22
+ clearTimeout(button._copyFeedbackTimer);
23
+ button.classList.toggle("is-copied", copied);
24
+ button.classList.toggle("is-copy-failed", !copied);
25
+ const key = copied ? "copied" : "copyMessageFailed";
26
+ const feedback = button.querySelector(".copy-feedback");
27
+ if (feedback) feedback.textContent = app.t(key);
28
+ button.setAttribute("aria-label", app.t(key));
29
+ button.title = app.t(key);
30
+ button._copyFeedbackTimer = setTimeout(() => {
31
+ button.classList.remove("is-copied", "is-copy-failed");
32
+ button.setAttribute("aria-label", app.t("copyMessage"));
33
+ button.title = app.t("copyMessage");
34
+ if (feedback) feedback.textContent = "";
35
+ }, 1600);
36
+ }
37
+
38
+ export async function copyResourceText(button, app, readText) {
39
+ let copied = false;
40
+ try {
41
+ const text = await readText();
42
+ copied = typeof text === "string" && text.length > 0 && await copyTextToClipboard(text);
43
+ } catch {
44
+ copied = false;
45
+ }
46
+ setCopyFeedback(button, app, copied);
47
+ return copied;
48
+ }
@@ -0,0 +1,253 @@
1
+ import { createRandomId } from "./state.js";
2
+ import { iconNode } from "./icons.js";
3
+
4
+ const MIN_SCALE = .5, MAX_SCALE = 4, ZOOM_STEP = 1.25, FIT_PADDING = 24;
5
+ let mermaidReady = false, mermaidPalette = "";
6
+ const diagramSources = new WeakMap();
7
+ export function rememberDiagramSource(node, source) { diagramSources.set(node, source); }
8
+
9
+ // The diagram palette is the chat palette, resolved for the active theme.
10
+ function mermaidThemeVariables() {
11
+ const style = getComputedStyle(document.documentElement);
12
+ const token = (name) => style.getPropertyValue(name).trim();
13
+ const surface = token("--surface"), surface2 = token("--surface-2");
14
+ const ink = token("--ink"), ink2 = token("--ink-2");
15
+ const accent = token("--accent"), accentSoft = token("--accent-soft");
16
+ return {
17
+ background: surface2,
18
+ primaryColor: accentSoft, primaryTextColor: ink, primaryBorderColor: accent,
19
+ secondaryColor: surface, secondaryTextColor: ink2,
20
+ tertiaryColor: surface2, tertiaryTextColor: ink2,
21
+ lineColor: ink2, textColor: ink,
22
+ edgeLabelBackground: surface,
23
+ clusterBkg: surface2, clusterBorder: token("--line"),
24
+ fontFamily: getComputedStyle(document.body).fontFamily || "sans-serif",
25
+ fontSize: "15px",
26
+ actorBkg: accentSoft, actorTextColor: ink, actorBorder: accent,
27
+ signalColor: ink2, signalTextColor: ink,
28
+ labelBoxBkgColor: accentSoft, labelTextColor: ink,
29
+ noteBkgColor: surface, noteTextColor: ink2,
30
+ };
31
+ }
32
+
33
+ // Mermaid bundles are loaded once. Re-initialization happens only when the
34
+ // resolved palette changes, so a theme switch repaints existing diagrams.
35
+ async function initializeMermaid() {
36
+ if (!window.mermaid) await new Promise((resolve, reject) => {
37
+ const script = document.querySelector('script[src$="mermaid-11.12.2.min.js"]');
38
+ if (!script) return reject(new Error("Mermaid bundle is missing"));
39
+ script.addEventListener("load", resolve, { once: true });
40
+ script.addEventListener("error", reject, { once: true });
41
+ window.addEventListener("load", resolve, { once: true });
42
+ });
43
+ if (!window.mermaid) throw new Error("Mermaid bundle failed to load");
44
+ const themeVariables = mermaidThemeVariables(), signature = JSON.stringify(themeVariables);
45
+ if (mermaidReady && signature === mermaidPalette) return;
46
+ window.mermaid.initialize({
47
+ startOnLoad: false, securityLevel: "strict", htmlLabels: false, theme: "base", themeVariables,
48
+ flowchart: { htmlLabels: false, useMaxWidth: false }, sequence: { useMaxWidth: false }, gantt: { useMaxWidth: false },
49
+ maxTextSize: 20000, maxEdges: 200, suppressErrorRendering: true,
50
+ secure: ["secure", "securityLevel", "startOnLoad", "htmlLabels", "flowchart", "theme", "themeVariables", "themeCSS", "dompurifyConfig", "maxTextSize", "maxEdges", "suppressErrorRendering"],
51
+ });
52
+ mermaidReady = true; mermaidPalette = signature;
53
+ }
54
+ export async function renderDiagram(node, source, app) {
55
+ if (source === undefined || isUnsafeDiagram(source)) return;
56
+ try {
57
+ await initializeMermaid();
58
+ const { svg } = await window.mermaid.render(`oc-chat-${createRandomId()}`, source);
59
+ if (!node.isConnected) return;
60
+ const fragment = window.DOMPurify.sanitize(svg, {
61
+ RETURN_DOM_FRAGMENT: true, USE_PROFILES: { svg: true, svgFilters: true },
62
+ FORBID_TAGS: ["foreignObject", "a", "script"], FORBID_ATTR: ["href", "xlink:href", "onclick", "onload"],
63
+ ALLOW_DATA_ATTR: false,
64
+ });
65
+ const diagram = fragment.querySelector("svg");
66
+ if (!diagram) throw new Error("Diagram SVG was rejected");
67
+ // The intrinsic width stays in the viewBox; the message column scales it down.
68
+ diagram.removeAttribute("style");
69
+ const update = () => node.replaceChildren(fragment);
70
+ if (app.preserveReadingLayout) await app.preserveReadingLayout(update); else update();
71
+ } catch {
72
+ if (node.isConnected) showDiagramFallback(node, source, app, false);
73
+ }
74
+ }
75
+ export function isUnsafeDiagram(source = "") {
76
+ return /%%\s*\{|^\s*---\s*(?:\r?\n)|\burl\s*\(|@import|@\s*\{[^}]*\b(?:img|image)\s*:/i.test(source);
77
+ }
78
+ export function showDiagramFallback(node, source, app, loading) {
79
+ node.textContent = "";
80
+ const status = document.createElement("p"); status.className = "diagram-status";
81
+ status.setAttribute("role", "status"); status.textContent = app.t(loading ? "diagramLoading" : "diagramRenderFailed");
82
+ node.append(status);
83
+ if (!loading) {
84
+ // The source block is readable text, not a button: nothing would open.
85
+ node.removeAttribute("tabindex"); node.removeAttribute("role"); node.removeAttribute("aria-label");
86
+ delete node.dataset.i18nAriaLabel;
87
+ const pre = document.createElement("pre"), code = document.createElement("code");
88
+ code.textContent = source; pre.append(code); node.append(pre);
89
+ }
90
+ }
91
+
92
+ // The overlay shows a sanitized copy of the rendered SVG, so the thread keeps its
93
+ // diagram and only the scale changes. A full-screen dialog keeps the thread in place.
94
+ export function initDiagramViewer(app) {
95
+ const dialog = app.$("#diagramViewer"), body = app.$("#diagramViewerBody"), stage = app.$("#diagramViewerStage");
96
+ if (!dialog || !body || !stage) return;
97
+ const level = app.$("#diagramZoomLevel"), zoomOut = app.$("#btnDiagramZoomOut"), zoomIn = app.$("#btnDiagramZoomIn"), fitButton = app.$("#btnDiagramFit");
98
+ zoomOut?.append(iconNode("subtract"));
99
+ zoomIn?.append(iconNode("add"));
100
+ let trigger = null, scale = 1, fitScale = 1, stageWidth = 0, stageHeight = 0, panX = 0, panY = 0, limitX = 0, limitY = 0, drag = null;
101
+ const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
102
+
103
+ function computeFit() {
104
+ if (!stageWidth || !stageHeight) return 1;
105
+ const width = Math.max(1, body.clientWidth - FIT_PADDING * 2);
106
+ const height = Math.max(1, body.clientHeight - FIT_PADDING * 2);
107
+ return clamp(Math.min(width / stageWidth, height / stageHeight), MIN_SCALE, MAX_SCALE);
108
+ }
109
+ function layout() {
110
+ limitX = Math.max(0, (stageWidth * scale - body.clientWidth) / 2);
111
+ limitY = Math.max(0, (stageHeight * scale - body.clientHeight) / 2);
112
+ panX = clamp(panX, -limitX, limitX); panY = clamp(panY, -limitY, limitY);
113
+ stage.style.transform = `translate(-50%, -50%) translate(${panX}px, ${panY}px) scale(${scale})`;
114
+ body.classList.toggle("is-pannable", limitX > .5 || limitY > .5);
115
+ if (level) level.textContent = `${Math.round(scale * 100)}%`;
116
+ if (zoomOut) zoomOut.disabled = scale <= MIN_SCALE + .001;
117
+ if (zoomIn) zoomIn.disabled = scale >= MAX_SCALE - .001;
118
+ }
119
+ function zoomTo(next, x, y) {
120
+ const target = clamp(next, MIN_SCALE, MAX_SCALE);
121
+ if (Math.abs(target - scale) < .001) return;
122
+ const box = body.getBoundingClientRect();
123
+ const centerX = box.left + box.width / 2, centerY = box.top + box.height / 2;
124
+ const ratio = target / scale;
125
+ // Keep the point under the pointer fixed while the diagram scales.
126
+ panX = x - centerX - (x - centerX - panX) * ratio;
127
+ panY = y - centerY - (y - centerY - panY) * ratio;
128
+ scale = target;
129
+ layout();
130
+ }
131
+ function zoomBy(factor) {
132
+ const box = body.getBoundingClientRect();
133
+ zoomTo(scale * factor, box.left + box.width / 2, box.top + box.height / 2);
134
+ }
135
+ function resetZoom() {
136
+ fitScale = computeFit(); scale = fitScale; panX = 0; panY = 0; layout();
137
+ }
138
+ function openDiagram(sourceSvg, sourceText) {
139
+ if (!sourceSvg) return;
140
+ const size = diagramSize(sourceSvg), clone = cloneDiagram(sourceSvg, size);
141
+ // A rejected copy still shows the source instead of an empty overlay.
142
+ if (!clone && !sourceText) return;
143
+ stageWidth = size.width; stageHeight = size.height;
144
+ stage.style.width = `${stageWidth}px`; stage.style.height = `${stageHeight}px`;
145
+ if (clone) stage.replaceChildren(clone);
146
+ else {
147
+ const pre = document.createElement("pre");
148
+ pre.className = "diagram-viewer-source";
149
+ pre.textContent = String(sourceText);
150
+ stage.replaceChildren(pre);
151
+ }
152
+ trigger = sourceSvg.closest(".mermaid-diagram") || sourceSvg;
153
+ if (!dialog.open) dialog.showModal();
154
+ document.body.classList.add("diagram-viewer-open");
155
+ resetZoom();
156
+ }
157
+ const close = () => { if (dialog.open) dialog.close(); };
158
+ function cloneDiagram(svg, size) {
159
+ try {
160
+ const markup = new XMLSerializer().serializeToString(svg);
161
+ const fragment = window.DOMPurify.sanitize(markup, {
162
+ RETURN_DOM_FRAGMENT: true, USE_PROFILES: { svg: true, svgFilters: true },
163
+ FORBID_TAGS: ["foreignObject", "a", "script"], FORBID_ATTR: ["href", "xlink:href", "onclick", "onload"],
164
+ ALLOW_DATA_ATTR: false,
165
+ });
166
+ const clone = fragment.querySelector("svg");
167
+ if (!clone) return null;
168
+ clone.removeAttribute("style");
169
+ clone.setAttribute("width", String(size.width));
170
+ clone.setAttribute("height", String(size.height));
171
+ return clone;
172
+ } catch { return null; }
173
+ }
174
+ function diagramSize(svg) {
175
+ const box = svg.viewBox?.baseVal;
176
+ let width = box?.width || 0, height = box?.height || 0;
177
+ if (!(width > 0) || !(height > 0)) {
178
+ width = parseFloat(svg.getAttribute("width")) || 0;
179
+ height = parseFloat(svg.getAttribute("height")) || 0;
180
+ }
181
+ return { width: width > 0 ? width : 640, height: height > 0 ? height : 420 };
182
+ }
183
+ const outside = (target) => target?.closest?.(".diagram-viewer-toolbar");
184
+ dialog.addEventListener("click", (event) => { if (event.target === dialog) close(); });
185
+ dialog.addEventListener("wheel", (event) => {
186
+ if (!dialog.open) return;
187
+ event.preventDefault();
188
+ if (outside(event.target)) return;
189
+ const delta = event.deltaMode === 1 ? event.deltaY * 16 : event.deltaY;
190
+ zoomTo(scale * Math.exp(-delta * .0015), event.clientX, event.clientY);
191
+ }, { passive: false });
192
+ stage.addEventListener("dblclick", (event) => { event.preventDefault(); resetZoom(); });
193
+ stage.addEventListener("pointerdown", (event) => {
194
+ if (event.button !== 0 || (limitX <= 0 && limitY <= 0)) return;
195
+ drag = { id: event.pointerId, x: event.clientX, y: event.clientY, panX, panY };
196
+ stage.setPointerCapture(event.pointerId);
197
+ body.classList.add("is-dragging");
198
+ event.preventDefault();
199
+ });
200
+ stage.addEventListener("pointermove", (event) => {
201
+ if (!drag || event.pointerId !== drag.id) return;
202
+ panX = drag.panX + event.clientX - drag.x; panY = drag.panY + event.clientY - drag.y;
203
+ layout();
204
+ });
205
+ const endDrag = (event) => {
206
+ if (!drag || event.pointerId !== drag.id) return;
207
+ drag = null; body.classList.remove("is-dragging");
208
+ if (stage.hasPointerCapture(event.pointerId)) stage.releasePointerCapture(event.pointerId);
209
+ };
210
+ stage.addEventListener("pointerup", endDrag);
211
+ stage.addEventListener("pointercancel", endDrag);
212
+ app.$("#btnCloseDiagram")?.addEventListener("click", close);
213
+ // The viewer sits above the document pane; Esc must close this layer only.
214
+ document.addEventListener("keydown", (event) => {
215
+ if (event.key !== "Escape" || !dialog.open) return;
216
+ event.preventDefault();
217
+ event.stopImmediatePropagation();
218
+ close();
219
+ }, true);
220
+ fitButton?.addEventListener("click", resetZoom);
221
+ zoomIn?.addEventListener("click", () => zoomBy(ZOOM_STEP));
222
+ zoomOut?.addEventListener("click", () => zoomBy(1 / ZOOM_STEP));
223
+ dialog.addEventListener("close", () => {
224
+ document.body.classList.remove("diagram-viewer-open");
225
+ stage.replaceChildren();
226
+ scale = 1; panX = 0; panY = 0;
227
+ const target = trigger; trigger = null;
228
+ if (target?.isConnected) target.focus({ preventScroll: true });
229
+ });
230
+ window.addEventListener("resize", () => {
231
+ if (!dialog.open) return;
232
+ const wasFit = Math.abs(scale - fitScale) < .001 && panX === 0 && panY === 0;
233
+ fitScale = computeFit();
234
+ if (wasFit) { scale = fitScale; panX = 0; panY = 0; }
235
+ else scale = Math.max(scale, MIN_SCALE);
236
+ layout();
237
+ });
238
+ // Theme and language changes must repaint diagrams, including the document preview.
239
+ const rerenderDiagrams = () => {
240
+ for (const node of document.querySelectorAll(".mermaid-diagram")) {
241
+ const source = diagramSources.get(node);
242
+ if (source === undefined || !node.querySelector("svg")) continue;
243
+ void renderDiagram(node, source, app);
244
+ }
245
+ };
246
+ new MutationObserver((records) => {
247
+ if (records.some((record) => record.attributeName === "data-theme" || record.attributeName === "lang")) rerenderDiagrams();
248
+ }).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "lang"] });
249
+ matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
250
+ if ((document.documentElement.dataset.theme || "system") === "system") rerenderDiagrams();
251
+ });
252
+ app.openDiagram = openDiagram;
253
+ }