@alexsun-top/opencode-chat-room 0.7.7 → 0.8.0
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.
- package/CHANGELOG.md +32 -0
- package/LICENSE +21 -0
- package/README.md +45 -36
- package/README.zh-CN.md +50 -41
- package/dist/cli.js +2696 -365
- package/package.json +14 -4
- package/packages/chat-room-channeld/README.md +242 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
- package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
- package/packages/chat-room-channeld/src/adapter.ts +475 -0
- package/packages/chat-room-channeld/src/cli.ts +124 -0
- package/packages/chat-room-channeld/src/config.ts +207 -0
- package/packages/chat-room-channeld/src/delivery.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
- package/packages/chat-room-channeld/src/framing.ts +128 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
- package/packages/chat-room-channeld/src/host.ts +509 -0
- package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
- package/packages/chat-room-channeld/src/log.ts +26 -0
- package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
- package/packages/chat-room-channeld/src/protocol.ts +75 -0
- package/packages/chat-room-channeld/src/published.ts +37 -0
- package/packages/chat-room-channeld/src/rules.ts +127 -0
- package/packages/chat-room-channeld/src/state.ts +485 -0
- package/packages/chat-room-channeld/src/stats.ts +167 -0
- package/plugin.ts +22 -5
- package/server/addressing-routes.ts +130 -0
- package/server/assets/NOTICE.txt +2 -2
- package/server/assets/SHIKI-LICENSE +22 -0
- package/server/assets/base.css +9 -1
- package/server/assets/chat/announcements.js +5 -2
- package/server/assets/chat/clipboard.js +30 -0
- package/server/assets/chat/copy-action.js +48 -0
- package/server/assets/chat/diagram-viewer.js +253 -0
- package/server/assets/chat/doc-preview.js +149 -12
- package/server/assets/chat/events.js +25 -4
- package/server/assets/chat/files.js +26 -5
- package/server/assets/chat/forward.js +69 -0
- package/server/assets/chat/history-loader.js +3 -1
- package/server/assets/chat/index.js +11 -1
- package/server/assets/chat/join-requests.js +6 -3
- package/server/assets/chat/locales/de.js +7 -2
- package/server/assets/chat/locales/es.js +7 -2
- package/server/assets/chat/locales/fr.js +7 -2
- package/server/assets/chat/locales/it.js +7 -2
- package/server/assets/chat/locales/ja.js +7 -2
- package/server/assets/chat/locales/ko.js +7 -2
- package/server/assets/chat/markdown-footnotes.js +115 -0
- package/server/assets/chat/markdown.js +65 -113
- package/server/assets/chat/messages.js +6 -3
- package/server/assets/chat/palette.js +33 -16
- package/server/assets/chat/pwa.js +2 -0
- package/server/assets/chat/questions.js +5 -0
- package/server/assets/chat/replies.js +7 -1
- package/server/assets/chat/resource-format.js +74 -0
- package/server/assets/chat/rooms.js +3 -0
- package/server/assets/chat/shiki.js +87 -0
- package/server/assets/chat/side-pane.js +143 -0
- package/server/assets/chat/state.js +63 -9
- package/server/assets/chat/system-messages.js +2 -0
- package/server/assets/chat/task-row.js +2 -1
- package/server/assets/chat/tasks.js +29 -2
- package/server/assets/chat/viewport.js +5 -0
- package/server/assets/code-highlight.css +20 -31
- package/server/assets/conversation.css +27 -2
- package/server/assets/diagram-viewer.css +141 -0
- package/server/assets/doc-preview.css +26 -6
- package/server/assets/responsive.css +87 -13
- package/server/assets/shiki.bundle.js +152 -0
- package/server/assets/tasks.css +1 -4
- package/server/channels.ts +314 -0
- package/server/chat-server.ts +36 -8
- package/server/chat.html +33 -5
- package/server/resource-routes.ts +3 -1
- package/server/sw.js +236 -4
- package/skills/chatroom/SKILL.md +1 -1
- package/src/agent/chatroom-skill.ts +8 -2
- package/src/center/center-client.ts +79 -1
- package/src/config/file-config.ts +34 -0
- package/src/rooms/resources.ts +2 -2
- package/src/runtime/v2-plugin.ts +8 -2
- package/src/runtime/watch.ts +41 -7
- package/src/state/sqlite-state.ts +67 -18
- package/src/state/store.ts +11 -5
- package/src/tui/app.mjs +10 -2
- package/src/tui/http.mjs +16 -2
- package/src/tui/info-app.mjs +24 -15
- package/src/tui/join-app.mjs +3 -3
- package/src/tui/main.mjs +1 -1
- package/src/tui/markdown.mjs +5 -3
- package/src/tui/mentions.mjs +3 -3
- package/src/tui/message-app.mjs +14 -11
- package/src/tui/palette-app.mjs +10 -7
- package/src/tui/reminder-app.mjs +14 -10
- package/src/tui/ui-content.mjs +3 -1
- package/server/assets/HIGHLIGHT-LICENSE +0 -29
- package/server/assets/highlight-10.7.3.min.js +0 -1358
package/plugin.ts
CHANGED
|
@@ -271,14 +271,19 @@ function actionableError(error: unknown): string {
|
|
|
271
271
|
}
|
|
272
272
|
|
|
273
273
|
export const roomArgs = z.object({
|
|
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
|
+
action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "get_message", "catch_up", "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"]),
|
|
275
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."),
|
|
276
276
|
roomId: z.string().optional().describe("Room UUID, not the room name. Required for resource actions and every room-scoped action."),
|
|
277
|
-
messageId: z.string().optional().describe("For recall: the full message ID returned by send
|
|
277
|
+
messageId: z.string().optional().describe("For recall and get_message: the full message ID returned by send, poll, or catch_up."),
|
|
278
278
|
resourceId: z.string().optional().describe("Resource UUID returned by upload_resource. read_resource and delete_resource also require roomId."),
|
|
279
279
|
filePath: z.string().optional().describe("Absolute path to a regular local file to upload; central mode only; requires host read permission."),
|
|
280
280
|
text: z.string().max(5000).optional().describe("Message text, at most 5000 characters; required for send."),
|
|
281
281
|
isQuestion: z.boolean().optional().describe("For send: mark the message as a question awaiting an answer."),
|
|
282
|
+
parentMessageId: z.string().optional().describe("For send: the ID of the message this one answers or replies to."),
|
|
283
|
+
replyToMessageID: z.string().optional().describe("Legacy alias of parentMessageId for send."),
|
|
284
|
+
clientMessageID: z.string().max(100).optional().describe("For send: idempotency key; retrying with the same ID and parent creates one message."),
|
|
285
|
+
afterSeq: z.number().int().min(0).optional().describe("For catch_up: return messages with seq greater than this cursor; omit to start at 0."),
|
|
286
|
+
limit: z.number().int().min(1).max(200).optional().describe("For catch_up: page size from 1 to 200; the server default is 50."),
|
|
282
287
|
announcementName: z.string().optional().describe("Exact announcement name from announcement_list; distinct from participant or room name."),
|
|
283
288
|
content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters; required for announcement_write."),
|
|
284
289
|
taskId: z.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
|
|
@@ -327,8 +332,9 @@ const roomExecute = async (
|
|
|
327
332
|
if (runtime.center.center) {
|
|
328
333
|
// ponytail: central mode — self-pull inbox first, then act via HTTP
|
|
329
334
|
// (skipped for poll: poll itself pulls the inbox, so racing the
|
|
330
|
-
// fire-and-forget check would read the position it just advanced
|
|
331
|
-
|
|
335
|
+
// fire-and-forget check would read the position it just advanced;
|
|
336
|
+
// get_message and catch_up stay read-only: no delivery, ack or wake)
|
|
337
|
+
if (args.action !== "poll" && args.action !== "get_message" && args.action !== "catch_up") {
|
|
332
338
|
void checkCenterInbox(runtime.center, context.sessionID, runtime.transport);
|
|
333
339
|
}
|
|
334
340
|
return await centerAction(runtime.center, {
|
|
@@ -475,6 +481,14 @@ const roomExecute = async (
|
|
|
475
481
|
if (!args.roomId) {
|
|
476
482
|
return "error: roomId is required; use a room UUID from the room list, not the room name";
|
|
477
483
|
}
|
|
484
|
+
// Local rooms can neither thread replies nor dedupe retries; fail
|
|
485
|
+
// loudly instead of silently dropping the caller's intent.
|
|
486
|
+
if (args.parentMessageId || args.replyToMessageID) {
|
|
487
|
+
return "error: replies require central server mode (CHAT_ROOM_SERVER_URL)";
|
|
488
|
+
}
|
|
489
|
+
if (args.clientMessageID) {
|
|
490
|
+
return "error: clientMessageID requires central server mode (CHAT_ROOM_SERVER_URL)";
|
|
491
|
+
}
|
|
478
492
|
if (!args.text?.trim()) {
|
|
479
493
|
return "error: text is required; pass a non-empty message body";
|
|
480
494
|
}
|
|
@@ -519,6 +533,9 @@ const roomExecute = async (
|
|
|
519
533
|
)
|
|
520
534
|
.join("\n") + (pollPage?.hasMore ? "\nMore unread messages remain; poll again." : "");
|
|
521
535
|
}
|
|
536
|
+
case "get_message":
|
|
537
|
+
case "catch_up":
|
|
538
|
+
return `error: ${args.action} requires central server mode (CHAT_ROOM_SERVER_URL)`;
|
|
522
539
|
default:
|
|
523
540
|
return "error: unsupported room action";
|
|
524
541
|
}
|
|
@@ -537,7 +554,7 @@ const roomExecute = async (
|
|
|
537
554
|
}
|
|
538
555
|
};
|
|
539
556
|
const room = tool({
|
|
540
|
-
description: "Chat room operations: create, join, leave and list rooms; send, poll and recall messages;
|
|
557
|
+
description: "Chat room operations: create, join, leave and list rooms; send, poll and recall messages; get_message fetches one message by ID (recalled messages come back as tombstones); catch_up pages messages after a seq cursor and is read-only (no read receipt or wake). Send accepts parentMessageId to reply to a message. 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.",
|
|
541
558
|
args: roomArgs.shape,
|
|
542
559
|
execute: roomExecute,
|
|
543
560
|
});
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Stable message addressing for clients resuming after a restart: fetch one
|
|
2
|
+
// message by ID, or page forward from a persisted seq. Both endpoints are
|
|
3
|
+
// member-only and use a uniform 404 so they reveal neither room nor message.
|
|
4
|
+
import { explicitlyAddresses } from "../src/center/mentions.ts";
|
|
5
|
+
import type { HistoryMessage } from "../src/state/sqlite-state.ts";
|
|
6
|
+
import { countOpenQuestions, readHistory, readMessage, readOpenQuestionRefs, readState } from "../src/state/store.ts";
|
|
7
|
+
|
|
8
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
9
|
+
const MAX_SESSION = 128;
|
|
10
|
+
const DEFAULT_LIMIT = 50;
|
|
11
|
+
const MAX_LIMIT = 200;
|
|
12
|
+
// Resource attachments are referenced by a UUID marker in the message text.
|
|
13
|
+
const RESOURCE_MARKER = /\[\[resource:([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\]\]/gi;
|
|
14
|
+
|
|
15
|
+
type MemberContext = {
|
|
16
|
+
allowed: boolean;
|
|
17
|
+
name: string;
|
|
18
|
+
roomKind: "group" | "direct";
|
|
19
|
+
senderNames: Map<string, string>;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function decode(value: string): string | undefined {
|
|
23
|
+
try { return decodeURIComponent(value); }
|
|
24
|
+
catch { return undefined; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function memberContext(roomID: string, sessionID: string): Promise<MemberContext> {
|
|
28
|
+
return readState((service, registry) => {
|
|
29
|
+
const room = service.listRooms().find((candidate) => candidate.id === roomID);
|
|
30
|
+
const entry = sessionID && sessionID.length <= MAX_SESSION ? registry[roomID]?.[sessionID] : undefined;
|
|
31
|
+
// Pending and kicked sessions have no registry entry; a stale entry without
|
|
32
|
+
// a participant is not a membership either.
|
|
33
|
+
const allowed = Boolean(room && entry) && (room!.kind === "direct"
|
|
34
|
+
? Boolean(room!.directSessionIDs?.includes(sessionID))
|
|
35
|
+
: service.containsParticipant(roomID, entry!.name));
|
|
36
|
+
return {
|
|
37
|
+
allowed,
|
|
38
|
+
name: entry?.name ?? "",
|
|
39
|
+
roomKind: room?.kind === "direct" ? "direct" : "group",
|
|
40
|
+
senderNames: new Map([...room?.participants.values() ?? []].map((participant) => [participant.id, participant.name])),
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function extractResourceIDs(text: string): string[] {
|
|
46
|
+
return [...new Set([...text.matchAll(RESOURCE_MARKER)].map((match) => match[1]!))];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function messageView(message: HistoryMessage, senderName: string) {
|
|
50
|
+
if (message.recalledAt !== undefined) {
|
|
51
|
+
// A tombstone exposes only addressing metadata: never the original text or
|
|
52
|
+
// the resources it referenced.
|
|
53
|
+
return {
|
|
54
|
+
id: message.id, roomId: message.roomId, seq: message.seq, senderId: message.senderId,
|
|
55
|
+
createdAt: message.createdAt, recalled: true as const, recalledAt: message.recalledAt,
|
|
56
|
+
recalledBy: message.recalledBy ?? null, text: null, unavailable: "recalled" as const, resourceIDs: [] as string[],
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
id: message.id, roomId: message.roomId, seq: message.seq, senderId: message.senderId, senderName,
|
|
61
|
+
text: message.text, createdAt: message.createdAt, isQuestion: message.isQuestion === true,
|
|
62
|
+
parentMessageId: message.answerToMessageID ?? null, answeredByMessageId: message.answeredByMessageID ?? null,
|
|
63
|
+
recalled: false as const, resourceIDs: extractResourceIDs(message.text),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function getMessage(req: Request, url: URL, match: RegExpMatchArray): Promise<Response> {
|
|
68
|
+
if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
|
|
69
|
+
const roomID = decode(match[1]!), messageID = decode(match[2]!);
|
|
70
|
+
if (roomID === undefined || messageID === undefined) return json({ error: "not found" }, 404);
|
|
71
|
+
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
72
|
+
const access = await memberContext(roomID, sessionID);
|
|
73
|
+
if (!access.allowed) return json({ error: "not found" }, 404);
|
|
74
|
+
const message = await readMessage(roomID, messageID);
|
|
75
|
+
if (!message) return json({ error: "not found" }, 404);
|
|
76
|
+
return json(messageView(message, access.senderNames.get(message.senderId) ?? message.senderId));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function catchUp(req: Request, url: URL, match: RegExpMatchArray): Promise<Response> {
|
|
80
|
+
if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
|
|
81
|
+
const roomID = decode(match[1]!);
|
|
82
|
+
if (roomID === undefined) return json({ error: "not found" }, 404);
|
|
83
|
+
const afterText = url.searchParams.get("afterSeq");
|
|
84
|
+
const limitText = url.searchParams.get("limit");
|
|
85
|
+
// Reject anything that is not a plain non-negative integer: Number("") and
|
|
86
|
+
// Number("1.5") would otherwise silently become different cursors.
|
|
87
|
+
if ((afterText !== null && !/^\d+$/.test(afterText)) || (limitText !== null && !/^\d+$/.test(limitText))) {
|
|
88
|
+
return json({ error: "afterSeq must be a non-negative integer and limit must be 1-200" }, 400);
|
|
89
|
+
}
|
|
90
|
+
const afterSeq = afterText === null ? 0 : Number(afterText);
|
|
91
|
+
const limit = limitText === null ? DEFAULT_LIMIT : Number(limitText);
|
|
92
|
+
if (!Number.isSafeInteger(afterSeq) || !Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
93
|
+
return json({ error: "afterSeq must be a non-negative integer and limit must be 1-200" }, 400);
|
|
94
|
+
}
|
|
95
|
+
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
96
|
+
const access = await memberContext(roomID, sessionID);
|
|
97
|
+
if (!access.allowed) return json({ error: "not found" }, 404);
|
|
98
|
+
// Strictly read-only: no receipts, read cursor, admission update, wake, model
|
|
99
|
+
// call, or any other write. Catch-up can be retried and shared safely.
|
|
100
|
+
const page = await readHistory(roomID, undefined, limit, undefined, afterSeq);
|
|
101
|
+
const messages = page.messages.map((message) =>
|
|
102
|
+
messageView(message, access.senderNames.get(message.senderId) ?? message.senderId));
|
|
103
|
+
const unreadMentions = page.messages
|
|
104
|
+
.filter((message) => message.recalledAt === undefined &&
|
|
105
|
+
explicitlyAddresses(message, access.name, sessionID, access.roomKind))
|
|
106
|
+
.map((message) => ({ id: message.id, seq: message.seq }));
|
|
107
|
+
// Open questions are room-wide. The array is capped at 200 refs so the
|
|
108
|
+
// response stays bounded; the count always reports the total open questions.
|
|
109
|
+
const [unansweredQuestions, unansweredQuestionCount] = await Promise.all([
|
|
110
|
+
readOpenQuestionRefs(roomID),
|
|
111
|
+
countOpenQuestions(roomID),
|
|
112
|
+
]);
|
|
113
|
+
return json({
|
|
114
|
+
messages,
|
|
115
|
+
nextCursor: page.messages.at(-1)?.seq ?? afterSeq,
|
|
116
|
+
hasMore: page.hasMore,
|
|
117
|
+
unreadMentions,
|
|
118
|
+
unreadMentionCount: unreadMentions.length,
|
|
119
|
+
unansweredQuestions,
|
|
120
|
+
unansweredQuestionCount,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function addressingRoutes(req: Request, url: URL): Promise<Response | undefined> {
|
|
125
|
+
const message = url.pathname.match(/^\/rooms\/([^/]+)\/messages\/([^/]+)$/);
|
|
126
|
+
if (message) return getMessage(req, url, message);
|
|
127
|
+
const resume = url.pathname.match(/^\/rooms\/([^/]+)\/catch-up$/);
|
|
128
|
+
if (resume) return catchUp(req, url, resume);
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
package/server/assets/NOTICE.txt
CHANGED
|
@@ -3,7 +3,7 @@ Browser vendors bundled locally; no external requests are made at runtime.
|
|
|
3
3
|
marked 18.0.4 — MIT License, see MARKED-LICENSE.
|
|
4
4
|
DOMPurify 3.4.7 — MPL 2.0 or Apache License 2.0, see DOMPURIFY-LICENSE.
|
|
5
5
|
Mermaid 11.12.2 — MIT License, see MERMAID-LICENSE.
|
|
6
|
-
|
|
6
|
+
Shiki 4.6.0 — MIT License, see SHIKI-LICENSE.
|
|
7
7
|
Fluent System Icons (@fluentui/svg-icons 1.1.347) — MIT License, see FLUENT-ICONS-LICENSE.
|
|
8
8
|
|
|
9
|
-
Sources: https://www.npmjs.com/package/marked, https://www.npmjs.com/package/dompurify, https://www.npmjs.com/package/mermaid, https://www.npmjs.com/package/
|
|
9
|
+
Sources: https://www.npmjs.com/package/marked, https://www.npmjs.com/package/dompurify, https://www.npmjs.com/package/mermaid, https://www.npmjs.com/package/shiki and https://github.com/microsoft/fluentui-system-icons
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Pine Wu
|
|
4
|
+
Copyright (c) 2023 Anthony Fu <https://github.com/antfu>
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/server/assets/base.css
CHANGED
|
@@ -375,7 +375,7 @@
|
|
|
375
375
|
.resource-split { position: relative; display: inline-flex; align-items: stretch; }
|
|
376
376
|
.resource-split .resource-download { border-right: 0; border-radius: 10px 0 0 10px; }
|
|
377
377
|
.resource-split .resource-split-toggle { display: grid; place-items: center; width: 34px; min-height: 34px; padding: 0; border-radius: 0 10px 10px 0; color: var(--ink-2); }
|
|
378
|
-
.resource-split .resource-split-toggle svg { width:
|
|
378
|
+
.resource-split .resource-split-toggle svg { width: 16px; height: 16px; }
|
|
379
379
|
.resource-split .resource-split-toggle[aria-expanded="true"] { color: var(--accent); background: var(--accent-soft); }
|
|
380
380
|
.resource-split-menu { position: absolute; z-index: 30; top: calc(100% + 5px); right: 0; min-width: 160px; padding: 4px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); box-shadow: var(--shadow); }
|
|
381
381
|
|
|
@@ -442,4 +442,12 @@
|
|
|
442
442
|
.join-policy input::after { display: none; }
|
|
443
443
|
}
|
|
444
444
|
|
|
445
|
+
/* Footnotes from Markdown definitions render as an endnote list. */
|
|
446
|
+
.footnotes { margin-top: 14px; padding-top: 8px; border-top: 1px solid color-mix(in srgb, var(--line) 80%, transparent); color: var(--ink-2); font-size: .88em; }
|
|
447
|
+
.footnotes ol { margin: 0; padding-left: 20px; }
|
|
448
|
+
.footnotes li { margin: 3px 0; }
|
|
449
|
+
.footnote-ref { font-size: .78em; line-height: 0; }
|
|
450
|
+
.footnote-ref a { text-decoration: none; }
|
|
451
|
+
.footnote-backref { margin-left: 2px; text-decoration: none; }
|
|
452
|
+
|
|
445
453
|
/* Conversation layout */
|
|
@@ -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 ||
|
|
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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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
|
+
}
|