@songsid/agend 2.4.0-beta.2 → 2.4.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/dist/agent-cli.js +1 -1
  2. package/dist/agent-endpoint.d.ts +1 -1
  3. package/dist/agent-endpoint.js +8 -2
  4. package/dist/agent-endpoint.js.map +1 -1
  5. package/dist/agent-token-header.d.ts +1 -1
  6. package/dist/agent-token-header.js +1 -1
  7. package/dist/auth-api.d.ts +3 -0
  8. package/dist/auth-api.js +15 -1
  9. package/dist/auth-api.js.map +1 -1
  10. package/dist/backend/agy-model-switch.d.ts +22 -0
  11. package/dist/backend/agy-model-switch.js +62 -0
  12. package/dist/backend/agy-model-switch.js.map +1 -0
  13. package/dist/backend/antigravity.js +60 -3
  14. package/dist/backend/antigravity.js.map +1 -1
  15. package/dist/backend/cli-runtime-switch.d.ts +71 -0
  16. package/dist/backend/cli-runtime-switch.js +176 -0
  17. package/dist/backend/cli-runtime-switch.js.map +1 -0
  18. package/dist/backend/codex-model-switch.d.ts +41 -0
  19. package/dist/backend/codex-model-switch.js +170 -0
  20. package/dist/backend/codex-model-switch.js.map +1 -0
  21. package/dist/backend/credential-profile.js +1 -1
  22. package/dist/backend/credential-profile.js.map +1 -1
  23. package/dist/backend/grok-model-switch.d.ts +16 -0
  24. package/dist/backend/grok-model-switch.js +45 -0
  25. package/dist/backend/grok-model-switch.js.map +1 -0
  26. package/dist/backend/grok.js +1 -1
  27. package/dist/backend/grok.js.map +1 -1
  28. package/dist/backend/muse.d.ts +2 -0
  29. package/dist/backend/muse.js +7 -3
  30. package/dist/backend/muse.js.map +1 -1
  31. package/dist/build-provenance.json +1 -1
  32. package/dist/channel/mcp-server.js +10 -1
  33. package/dist/channel/mcp-server.js.map +1 -1
  34. package/dist/channel/mcp-tools.js +8 -0
  35. package/dist/channel/mcp-tools.js.map +1 -1
  36. package/dist/classic-channel-manager.d.ts +1 -1
  37. package/dist/classic-channel-manager.js +1 -1
  38. package/dist/cli-audited.js +12 -12
  39. package/dist/cli-audited.js.map +1 -1
  40. package/dist/daemon.d.ts +48 -2
  41. package/dist/daemon.js +302 -21
  42. package/dist/daemon.js.map +1 -1
  43. package/dist/delivery-consumed-watch.js +3 -0
  44. package/dist/delivery-consumed-watch.js.map +1 -1
  45. package/dist/event-log.d.ts +1 -1
  46. package/dist/event-log.js +1 -1
  47. package/dist/fleet-manager.d.ts +104 -2
  48. package/dist/fleet-manager.js +665 -27
  49. package/dist/fleet-manager.js.map +1 -1
  50. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +10 -0
  51. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +2 -0
  52. package/dist/general-knowledge/skills/fleet-health/SKILL.md +18 -0
  53. package/dist/general-knowledge/skills/hub/SKILL.md +154 -0
  54. package/dist/general-knowledge/skills/model-discovery/SKILL.md +4 -0
  55. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +17 -3
  56. package/dist/hub/admin-dashboard.d.ts +85 -0
  57. package/dist/hub/admin-dashboard.js +161 -0
  58. package/dist/hub/admin-dashboard.js.map +1 -0
  59. package/dist/hub/attachments/store.d.ts +2 -0
  60. package/dist/hub/attachments/store.js +6 -0
  61. package/dist/hub/attachments/store.js.map +1 -1
  62. package/dist/hub/client.d.ts +10 -0
  63. package/dist/hub/client.js +72 -10
  64. package/dist/hub/client.js.map +1 -1
  65. package/dist/hub/compose/member.d.ts +20 -0
  66. package/dist/hub/compose/member.js +212 -17
  67. package/dist/hub/compose/member.js.map +1 -1
  68. package/dist/hub/compose/server.d.ts +8 -0
  69. package/dist/hub/compose/server.js +13 -2
  70. package/dist/hub/compose/server.js.map +1 -1
  71. package/dist/hub/display-name.d.ts +10 -0
  72. package/dist/hub/display-name.js +35 -0
  73. package/dist/hub/display-name.js.map +1 -0
  74. package/dist/hub/execution/service.d.ts +1 -0
  75. package/dist/hub/execution/service.js +1 -1
  76. package/dist/hub/execution/service.js.map +1 -1
  77. package/dist/hub/fleet-info.d.ts +12 -0
  78. package/dist/hub/fleet-info.js +14 -0
  79. package/dist/hub/fleet-info.js.map +1 -0
  80. package/dist/hub/fleet-update-model.d.ts +100 -0
  81. package/dist/hub/fleet-update-model.js +15 -0
  82. package/dist/hub/fleet-update-model.js.map +1 -0
  83. package/dist/hub/fleet-updates.d.ts +46 -0
  84. package/dist/hub/fleet-updates.js +282 -0
  85. package/dist/hub/fleet-updates.js.map +1 -0
  86. package/dist/hub/fleet-versions.d.ts +28 -0
  87. package/dist/hub/fleet-versions.js +80 -0
  88. package/dist/hub/fleet-versions.js.map +1 -0
  89. package/dist/hub/http/compose.d.ts +2 -0
  90. package/dist/hub/http/compose.js +192 -16
  91. package/dist/hub/http/compose.js.map +1 -1
  92. package/dist/hub/http/deps.d.ts +1 -0
  93. package/dist/hub/http/schema.js +13 -1
  94. package/dist/hub/http/schema.js.map +1 -1
  95. package/dist/hub/member/display-name.d.ts +9 -0
  96. package/dist/hub/member/display-name.js +71 -0
  97. package/dist/hub/member/display-name.js.map +1 -0
  98. package/dist/hub/member/exposure-api.d.ts +4 -0
  99. package/dist/hub/member/exposure-api.js +8 -3
  100. package/dist/hub/member/exposure-api.js.map +1 -1
  101. package/dist/hub/member/exposures.d.ts +4 -0
  102. package/dist/hub/member/exposures.js +20 -0
  103. package/dist/hub/member/exposures.js.map +1 -1
  104. package/dist/hub/member/pairing-api.js +3 -2
  105. package/dist/hub/member/pairing-api.js.map +1 -1
  106. package/dist/hub/member/recommendations.d.ts +37 -0
  107. package/dist/hub/member/recommendations.js +129 -0
  108. package/dist/hub/member/recommendations.js.map +1 -0
  109. package/dist/hub/member/room-ask.d.ts +60 -1
  110. package/dist/hub/member/room-ask.js +254 -24
  111. package/dist/hub/member/room-ask.js.map +1 -1
  112. package/dist/hub/member/room-post-answers.d.ts +52 -0
  113. package/dist/hub/member/room-post-answers.js +152 -0
  114. package/dist/hub/member/room-post-answers.js.map +1 -0
  115. package/dist/hub/member/room-post-receipt.d.ts +21 -0
  116. package/dist/hub/member/room-post-receipt.js +49 -0
  117. package/dist/hub/member/room-post-receipt.js.map +1 -0
  118. package/dist/hub/member/room-post.d.ts +100 -0
  119. package/dist/hub/member/room-post.js +223 -0
  120. package/dist/hub/member/room-post.js.map +1 -0
  121. package/dist/hub/member/updates.d.ts +92 -0
  122. package/dist/hub/member/updates.js +316 -0
  123. package/dist/hub/member/updates.js.map +1 -0
  124. package/dist/hub/protocol.d.ts +658 -1
  125. package/dist/hub/protocol.js +90 -13
  126. package/dist/hub/protocol.js.map +1 -1
  127. package/dist/hub/published-version.d.ts +3 -0
  128. package/dist/hub/published-version.js +35 -0
  129. package/dist/hub/published-version.js.map +1 -0
  130. package/dist/hub/recommendation-model.d.ts +36 -0
  131. package/dist/hub/recommendation-model.js +9 -0
  132. package/dist/hub/recommendation-model.js.map +1 -0
  133. package/dist/hub/recommendations.d.ts +58 -0
  134. package/dist/hub/recommendations.js +211 -0
  135. package/dist/hub/recommendations.js.map +1 -0
  136. package/dist/hub/representative.d.ts +3 -0
  137. package/dist/hub/representative.js +2 -1
  138. package/dist/hub/representative.js.map +1 -1
  139. package/dist/hub/room-context-model.d.ts +43 -0
  140. package/dist/hub/room-context-model.js +12 -0
  141. package/dist/hub/room-context-model.js.map +1 -0
  142. package/dist/hub/rooms/agents.d.ts +41 -9
  143. package/dist/hub/rooms/agents.js +183 -21
  144. package/dist/hub/rooms/agents.js.map +1 -1
  145. package/dist/hub/rooms/assistant.d.ts +1 -6
  146. package/dist/hub/rooms/assistant.js +7 -2
  147. package/dist/hub/rooms/assistant.js.map +1 -1
  148. package/dist/hub/rooms/automation.d.ts +24 -0
  149. package/dist/hub/rooms/automation.js +66 -0
  150. package/dist/hub/rooms/automation.js.map +1 -0
  151. package/dist/hub/rooms/buttons.d.ts +85 -0
  152. package/dist/hub/rooms/buttons.js +62 -0
  153. package/dist/hub/rooms/buttons.js.map +1 -0
  154. package/dist/hub/rooms/context-cursor.d.ts +18 -0
  155. package/dist/hub/rooms/context-cursor.js +61 -0
  156. package/dist/hub/rooms/context-cursor.js.map +1 -0
  157. package/dist/hub/rooms/context.d.ts +1 -1
  158. package/dist/hub/rooms/context.js +4 -4
  159. package/dist/hub/rooms/context.js.map +1 -1
  160. package/dist/hub/rooms/mentions.d.ts +15 -0
  161. package/dist/hub/rooms/mentions.js +43 -0
  162. package/dist/hub/rooms/mentions.js.map +1 -0
  163. package/dist/hub/rooms/post-replies.d.ts +23 -0
  164. package/dist/hub/rooms/post-replies.js +114 -0
  165. package/dist/hub/rooms/post-replies.js.map +1 -0
  166. package/dist/hub/rooms/schema.d.ts +9 -0
  167. package/dist/hub/rooms/schema.js +43 -0
  168. package/dist/hub/rooms/schema.js.map +1 -1
  169. package/dist/hub/rooms/service.d.ts +136 -1
  170. package/dist/hub/rooms/service.js +727 -18
  171. package/dist/hub/rooms/service.js.map +1 -1
  172. package/dist/hub/rooms/types.d.ts +27 -3
  173. package/dist/hub/rooms.js +1 -1
  174. package/dist/hub/rooms.js.map +1 -1
  175. package/dist/hub/runtime.d.ts +1 -1
  176. package/dist/hub/runtime.js +12 -0
  177. package/dist/hub/runtime.js.map +1 -1
  178. package/dist/hub/server.d.ts +6 -1
  179. package/dist/hub/server.js +75 -5
  180. package/dist/hub/server.js.map +1 -1
  181. package/dist/hub/settings-directory-proof.js +22 -1
  182. package/dist/hub/settings-directory-proof.js.map +1 -1
  183. package/dist/hub/types.d.ts +133 -2
  184. package/dist/hub-contact-windows.d.ts +11 -0
  185. package/dist/hub-contact-windows.js +56 -0
  186. package/dist/hub-contact-windows.js.map +1 -0
  187. package/dist/hub-pairing-summary.d.ts +1 -1
  188. package/dist/hub-room-conversation.d.ts +14 -0
  189. package/dist/hub-room-conversation.js +60 -0
  190. package/dist/hub-room-conversation.js.map +1 -0
  191. package/dist/hub-update-notice.d.ts +12 -0
  192. package/dist/hub-update-notice.js +35 -0
  193. package/dist/hub-update-notice.js.map +1 -0
  194. package/dist/locale.js +58 -2
  195. package/dist/locale.js.map +1 -1
  196. package/dist/native-mcp.js +9 -6
  197. package/dist/native-mcp.js.map +1 -1
  198. package/dist/outbound-handlers.d.ts +14 -4
  199. package/dist/outbound-handlers.js +54 -1
  200. package/dist/outbound-handlers.js.map +1 -1
  201. package/dist/outbound-schemas.d.ts +12 -0
  202. package/dist/outbound-schemas.js +12 -0
  203. package/dist/outbound-schemas.js.map +1 -1
  204. package/dist/pane-port.d.ts +2 -0
  205. package/dist/queued-handoffs.d.ts +16 -4
  206. package/dist/queued-handoffs.js +18 -1
  207. package/dist/queued-handoffs.js.map +1 -1
  208. package/dist/runtime-cli-install.js +13 -10
  209. package/dist/runtime-cli-install.js.map +1 -1
  210. package/dist/settings-api.d.ts +1 -0
  211. package/dist/settings-api.js +87 -0
  212. package/dist/settings-api.js.map +1 -1
  213. package/dist/tmux-manager.d.ts +2 -0
  214. package/dist/tmux-manager.js +2 -0
  215. package/dist/tmux-manager.js.map +1 -1
  216. package/dist/tool-permissions.js +3 -0
  217. package/dist/tool-permissions.js.map +1 -1
  218. package/dist/ui/chat-msg-actions.js +3 -222
  219. package/dist/ui/hub-admin-overview.js +189 -0
  220. package/dist/ui/hub-client.js +36 -4
  221. package/dist/ui/hub-fleet-versions.js +393 -0
  222. package/dist/ui/hub-room-agent-strings.js +28 -0
  223. package/dist/ui/hub-room-composer.js +16 -8
  224. package/dist/ui/hub-room-members-strings.js +2 -2
  225. package/dist/ui/hub-room-members.js +3 -2
  226. package/dist/ui/hub-room-notify.js +161 -0
  227. package/dist/ui/hub-room-search.js +126 -0
  228. package/dist/ui/hub-room-strings.js +47 -1
  229. package/dist/ui/hub-room-thread.js +243 -35
  230. package/dist/ui/hub-room-unread.js +2 -1
  231. package/dist/ui/hub-strings.js +8 -0
  232. package/dist/ui/image-annotate.js +2 -283
  233. package/dist/ui/image-lightbox.js +2 -176
  234. package/dist/ui/image-zoom.js +2 -242
  235. package/dist/ui/notice-hub-update.js +94 -0
  236. package/dist/ui/panel-chat.js +121 -12
  237. package/dist/ui/panel-hub.js +133 -19
  238. package/dist/ui/panel-notices.js +3 -1
  239. package/dist/ui/panel-settings.js +1 -1
  240. package/dist/ui/settings-hub-updates.js +67 -0
  241. package/dist/ui/settings-hub.js +28 -3
  242. package/dist/ui/settings-registry.js +1 -0
  243. package/dist/ui/settings-update.js +11 -5
  244. package/dist/ui/settings-web-authority.js +1 -1
  245. package/dist/ui/shared/app-i18n.js +2 -0
  246. package/dist/ui/shared/app-nav.js +6 -2
  247. package/dist/ui/shared/app-prefs.js +2 -1
  248. package/dist/ui/shared/app-shell.js +29 -4
  249. package/dist/ui/shared/app-update.js +90 -8
  250. package/dist/ui/shared/app.css +33 -0
  251. package/dist/ui/shared/chat-composer.js +6 -3
  252. package/dist/ui/shared/chat-msg-actions.js +225 -0
  253. package/dist/ui/shared/chat-thread.js +70 -5
  254. package/dist/ui/shared/chat-work-bar.css +48 -0
  255. package/dist/ui/shared/hub-chat.css +16 -2
  256. package/dist/ui/shared/hub-owner.css +104 -0
  257. package/dist/ui/shared/hub-rooms-u2.css +16 -0
  258. package/dist/ui/shared/hub.css +5 -0
  259. package/dist/ui/shared/image-annotate.js +306 -0
  260. package/dist/ui/shared/image-lightbox.js +183 -0
  261. package/dist/ui/shared/image-zoom.js +242 -0
  262. package/dist/ui/shared/instance-nav.js +36 -7
  263. package/dist/ui/shared/model-picker.css +4 -3
  264. package/dist/ui/shared/view-strings.js +8 -0
  265. package/dist/ui/shared/web-authorize.js +2 -2
  266. package/dist/update-dispatch.d.ts +8 -1
  267. package/dist/update-dispatch.js +16 -1
  268. package/dist/update-dispatch.js.map +1 -1
  269. package/dist/update-idle.d.ts +65 -0
  270. package/dist/update-idle.js +190 -0
  271. package/dist/update-idle.js.map +1 -0
  272. package/dist/update-launch.d.ts +1 -1
  273. package/dist/update-launch.js +9 -2
  274. package/dist/update-launch.js.map +1 -1
  275. package/dist/usage/i18n-keys.d.ts +1 -1
  276. package/dist/usage/i18n-keys.js +1 -1
  277. package/dist/usage/i18n-keys.js.map +1 -1
  278. package/dist/usage/profile-timeline.d.ts +2 -0
  279. package/dist/usage/profile-timeline.js +4 -0
  280. package/dist/usage/profile-timeline.js.map +1 -1
  281. package/dist/usage/providers.js +4 -4
  282. package/dist/usage/providers.js.map +1 -1
  283. package/dist/usage/quota-history.d.ts +1 -1
  284. package/dist/view-api.js +1 -1
  285. package/dist/view-api.js.map +1 -1
  286. package/dist/web-api.js +19 -2
  287. package/dist/web-api.js.map +1 -1
  288. package/dist/web-notices.d.ts +3 -0
  289. package/dist/web-notices.js +17 -2
  290. package/dist/web-notices.js.map +1 -1
  291. package/dist/web-prefs.js +1 -0
  292. package/dist/web-prefs.js.map +1 -1
  293. package/dist/web-update.d.ts +15 -1
  294. package/package.json +1 -1
@@ -0,0 +1,306 @@
1
+ // #3727 (M-2973): mark up a chat image and quote it to the agent. The image viewer's 「標註」 opens this editor in the
2
+ // viewer's own dialog: the picture on a canvas, and on top of it pen strokes, boxes, arrows and text in a few colours,
3
+ // with undo, redo and clear. 「引用給 Agent」 hands back the marked-up picture as a NEW PNG file (the original file is
4
+ // only read, never changed); the chat puts it in a composer as an attachment with a reply to the original message.
5
+ //
6
+ // Browser-only: the picture is the chat's own same-origin file (/ui/file/<hex>), drawn and encoded here — no server
7
+ // call, no other origin. No style attribute (#1300): classes only; the stylesheet is linked by this module (an older
8
+ // app.css lacks it). Pointer events, so a mouse, a pen and a finger draw the same way.
9
+ import { html, useEffect, useRef, useState } from "/assets/app-html.js";
10
+ import { register, t } from "/assets/app-i18n.js";
11
+ import { Icon } from "/assets/ui-icons.js";
12
+
13
+ export const annotateV1 = true;
14
+ register("annotate", {
15
+ en: {
16
+ title: "Annotate: {0}", titleNoName: "Annotate image", tools: "Tools", colours: "Colour",
17
+ pen: "Pen (P)", box: "Box (B)", arrow: "Arrow (A)", text: "Text (T)", undo: "Undo (Ctrl+Z)", redo: "Redo (Ctrl+Shift+Z)", clear: "Clear",
18
+ red: "Red", yellow: "Yellow", blue: "Blue", white: "White",
19
+ textField: "Text", textShort: "Type, then Enter", textHint: "Click the picture where the text goes, type it here, then press Enter.", textAdd: "Add",
20
+ close: "Close without sending", loading: "Loading the picture…",
21
+ failedLoad: "The picture could not be loaded for annotating.", failedSave: "The annotated picture could not be made.",
22
+ canvas: "Picture to annotate. Choose a tool, then draw on it.",
23
+ },
24
+ "zh-TW": {
25
+ title: "標註:{0}", titleNoName: "標註圖片", tools: "工具", colours: "顏色",
26
+ pen: "畫筆(P)", box: "方框(B)", arrow: "箭頭(A)", text: "文字(T)", undo: "復原(Ctrl+Z)", redo: "重做(Ctrl+Shift+Z)", clear: "清除",
27
+ red: "紅", yellow: "黃", blue: "藍", white: "白",
28
+ textField: "文字", textShort: "輸入後按 Enter", textHint: "先點圖片上要放文字的地方,在這裡輸入,再按 Enter。", textAdd: "加入",
29
+ close: "關閉,不送出", loading: "正在載入圖片…",
30
+ failedLoad: "無法載入這張圖片來標註。", failedSave: "無法產生標註後的圖片。",
31
+ canvas: "要標註的圖片。選一個工具,然後在上面畫。",
32
+ },
33
+ });
34
+
35
+ export const COLOURS = [["red", "#e5484d"], ["yellow", "#ffc53d"], ["blue", "#3e8eff"], ["white", "#ffffff"]];
36
+ export const TOOLS = ["pen", "box", "arrow", "text"];
37
+ const KEYS = { p: "pen", b: "box", a: "arrow", t: "text" };
38
+ /** The longest side a marked-up picture is drawn at (a larger original is scaled down; a smaller one is kept). */
39
+ export const MAX_SIDE = 2560;
40
+
41
+ /** Canvas size for a picture of w × h: its own size, scaled down to MAX_SIDE on its longest side. */
42
+ export function canvasSize(w, h) {
43
+ const k = Math.min(1, MAX_SIDE / Math.max(1, w, h));
44
+ return { w: Math.max(1, Math.round(w * k)), h: Math.max(1, Math.round(h * k)) };
45
+ }
46
+ /** Stroke width for a canvas of w × h: readable on a phone screenshot and on a wide one. */
47
+ export const strokeWidth = (w, h) => Math.max(3, Math.round(Math.max(w, h) / 320));
48
+
49
+ /**
50
+ * The marks as a history: `shapes` in drawing order (a "clear" is one too, so it can be undone) and `redo`, what undo
51
+ * took back. Pure, so the order of undo / redo / clear is tested without a canvas.
52
+ */
53
+ export function history() {
54
+ let shapes = [], redo = [];
55
+ return {
56
+ get shapes() { return shapes; },
57
+ /** What is drawn: everything after the last clear. */
58
+ visible() { const at = shapes.map(s => s.tool).lastIndexOf("clear"); return shapes.slice(at + 1); },
59
+ add(shape) { shapes = [...shapes, shape]; redo = []; },
60
+ clear() { if (this.visible().length) this.add({ tool: "clear" }); },
61
+ undo() { if (!shapes.length) return false; redo = [...redo, shapes[shapes.length - 1]]; shapes = shapes.slice(0, -1); return true; },
62
+ redo() { if (!redo.length) return false; shapes = [...shapes, redo[redo.length - 1]]; redo = redo.slice(0, -1); return true; },
63
+ get canUndo() { return shapes.length > 0; },
64
+ get canRedo() { return redo.length > 0; },
65
+ };
66
+ }
67
+
68
+ /** Draw one mark. `lw`: the stroke width for this canvas. */
69
+ export function drawShape(ctx, s, base) {
70
+ const lw = s.lw ?? base; // a mark keeps the width it was drawn with
71
+ ctx.save();
72
+ ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.lineWidth = lw; ctx.strokeStyle = s.colour; ctx.fillStyle = s.colour;
73
+ if (s.tool === "pen" && s.points.length) {
74
+ ctx.beginPath(); ctx.moveTo(s.points[0][0], s.points[0][1]);
75
+ for (const [x, y] of s.points.slice(1)) ctx.lineTo(x, y);
76
+ if (s.points.length === 1) ctx.lineTo(s.points[0][0] + 0.01, s.points[0][1]); // a dot
77
+ ctx.stroke();
78
+ } else if (s.tool === "box") {
79
+ ctx.strokeRect(Math.min(s.x0, s.x1), Math.min(s.y0, s.y1), Math.abs(s.x1 - s.x0), Math.abs(s.y1 - s.y0));
80
+ } else if (s.tool === "arrow") {
81
+ const angle = Math.atan2(s.y1 - s.y0, s.x1 - s.x0), head = lw * 4;
82
+ ctx.beginPath(); ctx.moveTo(s.x0, s.y0); ctx.lineTo(s.x1, s.y1); ctx.stroke();
83
+ ctx.beginPath(); ctx.moveTo(s.x1, s.y1);
84
+ ctx.lineTo(s.x1 - head * Math.cos(angle - Math.PI / 6), s.y1 - head * Math.sin(angle - Math.PI / 6));
85
+ ctx.lineTo(s.x1 - head * Math.cos(angle + Math.PI / 6), s.y1 - head * Math.sin(angle + Math.PI / 6));
86
+ ctx.closePath(); ctx.fill();
87
+ } else if (s.tool === "text" && s.text) {
88
+ ctx.font = `bold ${s.size ?? lw * 6}px system-ui, sans-serif`; ctx.textBaseline = "top";
89
+ // A dark outline, so a light colour reads on a light picture and the reverse.
90
+ ctx.lineWidth = Math.max(2, lw * 0.8); ctx.strokeStyle = s.colour === "#ffffff" ? "#000000" : "rgba(0,0,0,0.65)";
91
+ ctx.strokeText(s.text, s.x, s.y); ctx.fillText(s.text, s.x, s.y);
92
+ }
93
+ ctx.restore();
94
+ }
95
+
96
+ /** The marked-up picture's file name: the original's, before its extension, plus "-annotated.png". */
97
+ export function annotatedName(name) {
98
+ const base = String(name || "image").replace(/\.[A-Za-z0-9]{1,5}$/, "").replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").slice(0, 80) || "image";
99
+ return `${base}-annotated.png`;
100
+ }
101
+
102
+ /**
103
+ * Prism on #3735: the editor's colours are tokens (tokens.css). A tab whose cached tokens.css predates them would draw
104
+ * transparent swatches and lose the selected tool, so the editor's root sets any of them that resolve to nothing —
105
+ * CSSOM on its own element (#1300), the same values as tokens.css; a current tokens.css wins (nothing is set).
106
+ */
107
+ export const MEDIA_TOKENS = [["--media-ink", "#ffffff"], ["--media-bar", "rgba(0, 0, 0, 0.75)"], ["--media-panel", "rgba(0, 0, 0, 0.6)"],
108
+ ["--media-btn", "rgba(255, 255, 255, 0.12)"], ["--media-btn-on", "rgba(255, 255, 255, 0.32)"], ["--media-line", "rgba(255, 255, 255, 0.35)"],
109
+ ...COLOURS.map(([k, v]) => [`--mark-${k}`, v])];
110
+ export function fillMissingTokens(el) {
111
+ if (!el || typeof getComputedStyle !== "function") return;
112
+ const computed = getComputedStyle(el);
113
+ for (const [name, value] of MEDIA_TOKENS) if (!computed.getPropertyValue(name).trim()) el.style.setProperty(name, value);
114
+ }
115
+
116
+ /** The stylesheet, once per document. */
117
+ export function linkAnnotateCss(doc = typeof document !== "undefined" ? document : null) {
118
+ if (!doc || !doc.head || doc.querySelector('link[data-annotate-css="1"]')) return;
119
+ const link = doc.createElement("link");
120
+ link.setAttribute("rel", "stylesheet"); link.setAttribute("href", "/assets/image-annotate.css"); link.setAttribute("data-annotate-css", "1");
121
+ doc.head.appendChild(link);
122
+ }
123
+
124
+ /**
125
+ * M-3168: the stylesheet, linked once, and a promise that settles when it has arrived — loaded, failed, or after `wait` ms
126
+ * (a slow or missing stylesheet never keeps the editor shut). The viewer shows the editor only then, so its first open
127
+ * paints in its final layout; before, the first 「標註」 drew the bare editor (the picture at the far left) until the
128
+ * stylesheet arrived. Nothing is fetched before the first 「標註」: a page that never annotates loads none of it.
129
+ */
130
+ export function annotateCssReady(doc = typeof document !== "undefined" ? document : null, wait = 4000) {
131
+ if (!doc || !doc.head) return Promise.resolve();
132
+ linkAnnotateCss(doc);
133
+ const link = doc.querySelector('link[data-annotate-css="1"]');
134
+ // Already loaded (a second open, or another chat's), or already failed once (Fable #3977: a failed link never fires
135
+ // again, so later opens would each wait the full `wait`).
136
+ if (!link || link.sheet || link.getAttribute("data-annotate-css-failed") === "1") return Promise.resolve();
137
+ return new Promise((done) => {
138
+ let timer = null;
139
+ const settle = (e) => { if (timer === null) return; clearTimeout(timer); timer = null;
140
+ if (e?.type === "error") link.setAttribute("data-annotate-css-failed", "1");
141
+ link.removeEventListener("load", settle); link.removeEventListener("error", settle); done(); };
142
+ timer = setTimeout(settle, wait);
143
+ link.addEventListener("load", settle); link.addEventListener("error", settle);
144
+ });
145
+ }
146
+
147
+ /**
148
+ * The editor, inside the viewer's dialog. `src`, `name`: the picture. `targets`: [{ key, label, quote(file) }] — the first
149
+ * is this chat's composer, a second the other pane's; quote() answers true when the file went in. `onClose`: ✕ / Esc
150
+ * (the dialog's own cancel), and after a quote.
151
+ */
152
+ export function AnnotateEditor({ src, name, targets = [], onClose, onError }) {
153
+ const canvas = useRef(null), base = useRef(null), hist = useRef(history()), drag = useRef(null), textField = useRef(null);
154
+ const [size, setSize] = useState(null); // { w, h, lw } once the picture has loaded
155
+ const [failed, setFailed] = useState(false);
156
+ const [tool, setTool] = useState("pen");
157
+ const [colour, setColour] = useState(COLOURS[0][1]);
158
+ const [textAt, setTextAt] = useState(null); // where a text mark goes: [x, y] on the canvas
159
+ const [text, setText] = useState("");
160
+ const [, setTick] = useState(0);
161
+ const [busy, setBusy] = useState(false);
162
+ const refresh = () => setTick(n => n + 1);
163
+ // Prism on #3735: an export (toBlob is asynchronous) belongs to the live editor. Closing it, or the editor going
164
+ // away, retires one in flight: its file is never handed to a composer afterwards.
165
+ const live = useRef({ alive: true, op: 0 });
166
+ const close = () => { live.current.op++; onClose?.(); };
167
+ useEffect(() => () => { live.current.alive = false; live.current.op++; }, []);
168
+ useEffect(() => { linkAnnotateCss(); }, []);
169
+ useEffect(() => {
170
+ const img = new Image();
171
+ img.decoding = "async";
172
+ img.onload = () => {
173
+ const { w, h } = canvasSize(img.naturalWidth, img.naturalHeight);
174
+ base.current = img; setSize({ w, h, lw: strokeWidth(w, h) });
175
+ };
176
+ img.onerror = () => setFailed(true);
177
+ img.src = src; // the chat's own file: same origin, so the canvas can be read back
178
+ return () => { img.onload = null; img.onerror = null; };
179
+ }, [src]);
180
+ const paint = (extra, forExport = false) => {
181
+ const c = canvas.current, s = size;
182
+ if (!c || !s || !base.current) return;
183
+ const ctx = c.getContext("2d");
184
+ ctx.clearRect(0, 0, s.w, s.h);
185
+ ctx.drawImage(base.current, 0, 0, s.w, s.h);
186
+ for (const shape of hist.current.visible()) drawShape(ctx, shape, s.lw);
187
+ if (extra) drawShape(ctx, extra, s.lw);
188
+ if (textAt && !forExport) { // where the text will go: a small cross (never in the file)
189
+ ctx.save(); ctx.strokeStyle = colour; ctx.lineWidth = Math.max(2, s.lw / 2);
190
+ ctx.beginPath(); ctx.moveTo(textAt[0] - s.lw * 2, textAt[1]); ctx.lineTo(textAt[0] + s.lw * 2, textAt[1]);
191
+ ctx.moveTo(textAt[0], textAt[1] - s.lw * 2); ctx.lineTo(textAt[0], textAt[1] + s.lw * 2); ctx.stroke(); ctx.restore();
192
+ }
193
+ };
194
+ useEffect(() => { paint(); });
195
+ /** Canvas pixels per screen pixel now (a phone shows a big picture small): a mark is at least 3 screen px wide, and
196
+ * text at least 20 screen px tall, whatever the picture's own size. */
197
+ const perScreenPx = () => { const c = canvas.current, r = c?.getBoundingClientRect(); return c && r && r.width > 0 ? c.width / r.width : 1; };
198
+ const markWidth = () => Math.max(size.lw, Math.round(3 * perScreenPx()));
199
+ const textSize = () => Math.max(size.lw * 6, Math.round(20 * perScreenPx()));
200
+ const point = (e) => {
201
+ const c = canvas.current, r = c.getBoundingClientRect();
202
+ return [((e.clientX - r.left) / Math.max(1, r.width)) * c.width, ((e.clientY - r.top) / Math.max(1, r.height)) * c.height];
203
+ };
204
+ const onDown = (e) => {
205
+ if (!size || (e.button ?? 0) !== 0) return;
206
+ e.preventDefault();
207
+ const [x, y] = point(e);
208
+ if (tool === "text") { setTextAt([x, y]); textField.current?.focus(); return; }
209
+ canvas.current.setPointerCapture?.(e.pointerId);
210
+ const lw = markWidth();
211
+ drag.current = tool === "pen" ? { tool, colour, lw, points: [[x, y]] } : { tool, colour, lw, x0: x, y0: y, x1: x, y1: y };
212
+ paint(drag.current);
213
+ };
214
+ const onMove = (e) => {
215
+ const d = drag.current;
216
+ if (!d) return;
217
+ e.preventDefault();
218
+ const [x, y] = point(e);
219
+ if (d.tool === "pen") d.points.push([x, y]); else { d.x1 = x; d.y1 = y; }
220
+ paint(d);
221
+ };
222
+ const onUp = () => {
223
+ const d = drag.current;
224
+ drag.current = null;
225
+ if (!d) return;
226
+ const tiny = d.tool !== "pen" && Math.hypot(d.x1 - d.x0, d.y1 - d.y0) < 3;
227
+ if (!tiny) hist.current.add(d);
228
+ refresh();
229
+ };
230
+ const addText = () => {
231
+ const value = text.trim();
232
+ if (!value || !textAt) return;
233
+ hist.current.add({ tool: "text", colour, lw: markWidth(), size: textSize(), x: textAt[0], y: textAt[1], text: value.slice(0, 200) });
234
+ setText(""); setTextAt(null);
235
+ };
236
+ const undo = () => { if (hist.current.undo()) refresh(); };
237
+ const redo = () => { if (hist.current.redo()) refresh(); };
238
+ const clear = () => { hist.current.clear(); setTextAt(null); refresh(); };
239
+ const quote = async (target) => {
240
+ const c = canvas.current;
241
+ if (!c || busy) return;
242
+ const op = ++live.current.op, current = () => live.current.alive && live.current.op === op;
243
+ setBusy(true);
244
+ try {
245
+ paint(null, true); // without the text cross
246
+ const blob = await new Promise((resolve) => c.toBlob(resolve, "image/png"));
247
+ if (!current()) return; // closed or gone while encoding: nothing is added anywhere
248
+ if (!blob) throw new Error("no image");
249
+ const file = new File([blob], annotatedName(name), { type: "image/png" });
250
+ // The editor's own liveness travels with the file: a target that waits (the other pane's Chat mounting) checks it
251
+ // at its commit, so closing the editor meanwhile cancels the quote and the attachment there (Prism on #3735 r2).
252
+ if (await target.quote(file, current) && current()) onClose?.();
253
+ } catch { if (current()) onError?.(t("annotate.failedSave")); }
254
+ finally { if (live.current.alive) setBusy(false); }
255
+ };
256
+ useEffect(() => {
257
+ const onKey = (e) => {
258
+ const typing = e.target && (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA");
259
+ const mod = e.ctrlKey || e.metaKey;
260
+ if (mod && !e.altKey && (e.key === "z" || e.key === "Z")) { if (typing && !e.shiftKey && text) return; e.preventDefault(); if (e.shiftKey) redo(); else undo(); return; }
261
+ if (mod && !e.altKey && (e.key === "y" || e.key === "Y")) { e.preventDefault(); redo(); return; }
262
+ if (typing || mod || e.altKey) return;
263
+ const k = KEYS[e.key.toLowerCase()];
264
+ if (k) { e.preventDefault(); setTool(k); if (k !== "text") setTextAt(null); return; }
265
+ const n = Number(e.key);
266
+ if (n >= 1 && n <= COLOURS.length) { e.preventDefault(); setColour(COLOURS[n - 1][1]); }
267
+ };
268
+ document.addEventListener("keydown", onKey);
269
+ return () => document.removeEventListener("keydown", onKey);
270
+ });
271
+ const label = name ? t("annotate.title", name) : t("annotate.titleNoName");
272
+ return html`<div class="an" data-trust="annotate" role="group" aria-label=${label} ref=${fillMissingTokens}>
273
+ <div class="an-bar">
274
+ <span class="an-name" title=${name}>${label}</span>
275
+ <span class="an-tools" role="radiogroup" aria-label=${t("annotate.tools")}>
276
+ ${TOOLS.map((k) => html`<button type="button" role="radio" aria-checked=${tool === k ? "true" : "false"} class=${`btn btn-sm an-tool an-tool-${k}${tool === k ? " on" : ""}`}
277
+ title=${t(`annotate.${k}`)} aria-label=${t(`annotate.${k}`)} onClick=${() => { setTool(k); if (k !== "text") setTextAt(null); }}><span class="an-glyph" aria-hidden="true">${{ pen: "✎", box: "▭", arrow: "↗", text: "T" }[k]}</span></button>`)}
278
+ </span>
279
+ <span class="an-colours" role="radiogroup" aria-label=${t("annotate.colours")}>
280
+ ${COLOURS.map(([k, v], i) => html`<button type="button" role="radio" aria-checked=${colour === v ? "true" : "false"} class=${`an-colour${colour === v ? " on" : ""}`}
281
+ title=${`${t(`annotate.${k}`)} (${i + 1})`} aria-label=${t(`annotate.${k}`)} onClick=${() => setColour(v)}><span class=${`an-dot an-colour-${k}`} aria-hidden="true"></span></button>`)}
282
+ </span>
283
+ <span class="an-history">
284
+ <button type="button" class="btn btn-sm an-undo" disabled=${!hist.current.canUndo} title=${t("annotate.undo")} aria-label=${t("annotate.undo")} onClick=${undo}>↶</button>
285
+ <button type="button" class="btn btn-sm an-redo" disabled=${!hist.current.canRedo} title=${t("annotate.redo")} aria-label=${t("annotate.redo")} onClick=${redo}>↷</button>
286
+ <button type="button" class="btn btn-sm an-clear" disabled=${!hist.current.visible().length} onClick=${clear}>${t("annotate.clear")}</button>
287
+ </span>
288
+ <button type="button" class="icon-btn an-close" title=${t("annotate.close")} aria-label=${t("annotate.close")} onClick=${close}><${Icon} name="close" /></button>
289
+ </div>
290
+ ${tool === "text" ? html`<form class="an-text" onSubmit=${(e) => { e.preventDefault(); addText(); }}>
291
+ <label class="an-text-label"><span>${t("annotate.textField")}</span>
292
+ <input ref=${textField} type="text" maxlength="200" value=${text} placeholder=${t("annotate.textShort")} title=${t("annotate.textHint")} onInput=${(e) => setText(e.target.value)} /></label>
293
+ <button type="submit" class="btn btn-sm" disabled=${!text.trim() || !textAt}>${t("annotate.textAdd")}</button>
294
+ </form>` : null}
295
+ <div class="an-stage">
296
+ ${failed ? html`<p class="an-note" role="alert">${t("annotate.failedLoad")}</p>`
297
+ : size ? html`<canvas ref=${canvas} class=${`an-canvas an-cursor-${tool}`} width=${size.w} height=${size.h} role="img" aria-label=${t("annotate.canvas")}
298
+ onPointerDown=${onDown} onPointerMove=${onMove} onPointerUp=${onUp} onPointerCancel=${onUp} />`
299
+ : html`<p class="an-note" role="status">${t("annotate.loading")}</p>`}
300
+ </div>
301
+ <div class="an-actions">
302
+ ${targets.map((target, i) => html`<button type="button" class=${`btn ${i === 0 ? "btn-primary" : ""} an-quote`} disabled=${!size || busy}
303
+ data-target=${target.key} onClick=${() => quote(target)}>${target.label}</button>`)}
304
+ </div>
305
+ </div>`;
306
+ }
@@ -0,0 +1,183 @@
1
+ // A chat image, full size, in the page: a dark overlay with the image fitted to the viewport, ✕ to close, a click on
2
+ // the dark area or Esc closes it too, and focus goes back to the thumbnail. "Open original" opens the same URL in a
3
+ // new tab (the thumbnail's link, unchanged: a ctrl-, meta-, shift- or middle-click on it still does what the browser
4
+ // does). Several images in one message: previous / next, and the arrow keys.
5
+ //
6
+ // The native <dialog> opened with showModal(): the browser traps focus and makes the rest inert. No style attribute
7
+ // (#1300): classes only. Only a file URL the chat itself rendered (/ui/file/<32 hex>, or a Hub room's
8
+ // /hub/v1/rooms/<uuid>/files/<uuid>/inline) is ever shown.
9
+ //
10
+ // #2333: zoom and pan (image-zoom.js). The toolbar has −, the level (it toggles fit ↔ 100%), + and Fit width; the keys
11
+ // + / − / 0 (fit) / 1 (100%) / W (fit width). Each image opens fitted; stepping to another fits it again.
12
+ import { html, useEffect, useLayoutEffect, useRef, useState } from "/assets/app-html.js";
13
+ import { register, t } from "/assets/app-i18n.js";
14
+ import { createStore, useStore } from "/assets/app-store.js";
15
+ import { Icon } from "/assets/ui-icons.js";
16
+ import { createZoom, STEP } from "./image-zoom.js";
17
+
18
+ // M-3125 PR3: or a Hub room's own picture, at its inline route (the Hub's page only; the Fleet chat never renders one).
19
+ const UUID_RE = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
20
+ const FILE_URL = new RegExp(`^(?:/ui/file/[0-9a-f]{32}|/hub/v1/rooms/${UUID_RE}/files/${UUID_RE}/inline)$`);
21
+ // #3727: the viewer's own word for the annotate button (here, so an older cached chat dictionary is never shown a raw key).
22
+ register("lbAnnotate", { en: { open: "Annotate", failed: "The annotation tools could not be loaded. Reload this page to try again." },
23
+ "zh-TW": { open: "標註", failed: "無法載入標註工具。請重新整理頁面再試。" } });
24
+ /** The annotation editor, loaded on the first 「標註」 (its module and stylesheet stay out of every other page load). */
25
+ const loadAnnotate = () => import("./image-annotate.js");
26
+ /** What is shown: { items: [{ src, name }], index, opener } or null. One per page; the chat that shows it owns it. */
27
+ export const lightboxStore = createStore({ open: null });
28
+ let seq = 0;
29
+
30
+ /**
31
+ * The images of a message, from its thumbnails' links; `index` the one clicked. Anything that is not a chat file URL
32
+ * is left out (and nothing opens if the clicked one is not).
33
+ */
34
+ export function openLightbox(links, clicked, annotate = null) {
35
+ const items = [];
36
+ let index = -1;
37
+ for (const a of links) {
38
+ const src = a.getAttribute("href") || "";
39
+ if (!FILE_URL.test(src)) continue;
40
+ if (a === clicked) index = items.length;
41
+ const img = a.querySelector("img");
42
+ items.push({ src, name: (img && img.getAttribute("alt")) || "" });
43
+ }
44
+ if (index < 0) return false;
45
+ // #3727: `annotate` — { targets: [{ key, label, quote(file) }], notice(text) } — only from a chat that can quote.
46
+ lightboxStore.set({ open: { items, index, opener: clicked, seq: ++seq, annotate: annotate && annotate.targets?.length ? annotate : null } });
47
+ return true;
48
+ }
49
+ /**
50
+ * Close it — the one way every close goes: ✕, the dark area, Esc, the dialog's own close (the browser's, a form with
51
+ * method=dialog), the chat leaving. The store is the truth; unmounting the dialog is the one cleanup (scroll unlocked,
52
+ * focus back on the thumbnail). `seq`: only that lightbox — a late close of one already replaced closes nothing.
53
+ */
54
+ export function closeLightbox(seq) {
55
+ const open = lightboxStore.get().open;
56
+ if (open && (seq === undefined || open.seq === seq)) lightboxStore.set({ open: null });
57
+ }
58
+
59
+ /** Rendered by the chat; gone with it (another instance, another panel). */
60
+ export function LightboxHost({ owner } = {}) {
61
+ const { open } = useStore(lightboxStore);
62
+ const owned = useRef(null);
63
+ const mine = !owner || owner.current?.contains(open?.opener);
64
+ if (open && mine) owned.current = open.seq;
65
+ useEffect(() => () => {
66
+ if (!owner) closeLightbox();
67
+ else if (owned.current !== null) closeLightbox(owned.current);
68
+ }, []);
69
+ return open && mine ? html`<${ImageLightbox} key=${open.seq} items=${open.items} index=${open.index} opener=${open.opener} annotate=${open.annotate} onClose=${() => closeLightbox(open.seq)} />` : null;
70
+ }
71
+
72
+ function ImageLightbox({ items, index, opener, annotate = null, onClose }) {
73
+ const [at, setAt] = useState(index);
74
+ const ref = useRef(null);
75
+ const close = useRef(null);
76
+ const stage = useRef(null);
77
+ const img = useRef(null);
78
+ const zoom = useRef(null);
79
+ const [level, setLevel] = useState(null); // { scale, fit, mode } once the picture has loaded
80
+ const item = items[at] || items[0];
81
+ const many = items.length > 1;
82
+ // #3727: the editor's component once 「標註」 has loaded it; while it shows, the viewer's own keys stand aside.
83
+ const [Editor, setEditor] = useState(null);
84
+ const editing = !!Editor;
85
+ const startAnnotate = () => {
86
+ // M-3168: shown once its stylesheet has arrived too (annotateCssReady settles on load, error or a bounded wait), so the
87
+ // first open paints in its final layout. A module without it (an older cached one) opens as before.
88
+ loadAnnotate().then((m) => {
89
+ if (!(m && m.annotateV1 === true && typeof m.AnnotateEditor === "function")) throw new Error("old module");
90
+ return Promise.resolve(typeof m.annotateCssReady === "function" ? m.annotateCssReady() : null).then(() => setEditor(() => m.AnnotateEditor));
91
+ }).catch(() => annotate?.notice?.(t("lbAnnotate.failed")));
92
+ };
93
+ const step = (d) => setAt((n) => (n + d + items.length) % items.length);
94
+ useLayoutEffect(() => {
95
+ const d = ref.current;
96
+ const root = typeof document !== "undefined" ? document.documentElement : null;
97
+ if (root) root.classList.add("lb-open"); // the chat behind it does not scroll
98
+ if (d && typeof d.showModal === "function" && !d.open) d.showModal();
99
+ if (close.current && typeof close.current.focus === "function") close.current.focus();
100
+ return () => {
101
+ if (root) root.classList.remove("lb-open");
102
+ if (d && d.open && typeof d.close === "function") d.close();
103
+ if (opener && typeof opener.focus === "function" && document.contains?.(opener)) opener.focus();
104
+ };
105
+ }, []);
106
+ useEffect(() => {
107
+ if (!stage.current || !img.current) return undefined;
108
+ const z = createZoom({ stage: stage.current, img: img.current, onChange: setLevel });
109
+ zoom.current = z;
110
+ return () => { z.destroy(); zoom.current = null; };
111
+ }, []);
112
+ // Another image: hidden until it has loaded and been fitted (its load resets the zoom). A layout effect — in the same
113
+ // commit that set the new src, before any load can arrive: a picture already in the cache (every thumbnail above it
114
+ // has loaded) fires its load before a passive effect would run, and such an effect then hid it for good with the
115
+ // level at "…" (the report on beta.24: Next "flashes once, then the next image is not visible"). A picture that is
116
+ // already complete here (the same file again: no load comes) is fitted at once.
117
+ const first = useRef(true);
118
+ useLayoutEffect(() => {
119
+ if (first.current) { first.current = false; return; }
120
+ const el = img.current;
121
+ if (el) el.classList.remove("lb-ready");
122
+ setLevel(null);
123
+ if (el && el.complete && el.naturalWidth > 0 && zoom.current) zoom.current.reset();
124
+ }, [at]);
125
+ useEffect(() => {
126
+ const d = ref.current;
127
+ if (!d) return undefined;
128
+ // Esc: the browser fires "cancel"; closing goes through the store so its state stays the truth.
129
+ const onCancel = (e) => { e.preventDefault(); onClose(); };
130
+ // The dialog closed by itself — the browser (a close request it did not ask about) or a form with method=dialog:
131
+ // the same close as every other, so the store and the cleanup follow (#1558 review).
132
+ const onNativeClose = () => onClose();
133
+ // The dark area (the dialog itself, or the stage around the image) closes it; the image and the controls do not.
134
+ const onClick = (e) => { if (e.target === d || (e.target && e.target.classList && e.target.classList.contains("lb-stage"))) onClose(); };
135
+ const onKey = (e) => {
136
+ if (editing) return; // the editor's keys (tools, colours, undo) are its own
137
+ const z = zoom.current;
138
+ if (z && !e.ctrlKey && !e.metaKey && !e.altKey) {
139
+ const act = { "+": () => z.zoomBy(STEP), "=": () => z.zoomBy(STEP), "-": () => z.zoomBy(1 / STEP), "_": () => z.zoomBy(1 / STEP),
140
+ "0": () => z.fit(), "1": () => z.actual(), w: () => z.fitWidth(), W: () => z.fitWidth() }[e.key];
141
+ if (act) { e.preventDefault(); act(); return; }
142
+ }
143
+ if (!many) return;
144
+ if (e.key === "ArrowRight") { e.preventDefault(); step(1); } else if (e.key === "ArrowLeft") { e.preventDefault(); step(-1); }
145
+ };
146
+ d.addEventListener("cancel", onCancel);
147
+ d.addEventListener("close", onNativeClose);
148
+ d.addEventListener("click", onClick);
149
+ d.addEventListener("keydown", onKey);
150
+ return () => { d.removeEventListener("cancel", onCancel); d.removeEventListener("close", onNativeClose); d.removeEventListener("click", onClick); d.removeEventListener("keydown", onKey); };
151
+ }, [onClose, many, items.length, editing]);
152
+ const label = item.name ? t("chat.lbLabel", item.name) : t("chat.lbLabelNoName");
153
+ const pct = level ? Math.round(level.scale * 100) : null;
154
+ if (editing) {
155
+ return html`<dialog data-trust="lightbox" ref=${ref} class="lb lb-annotating" role="dialog" aria-modal="true" aria-label=${label}>
156
+ <${Editor} src=${item.src} name=${item.name} targets=${annotate.targets} onClose=${onClose} onError=${(text) => annotate.notice?.(text)} />
157
+ </dialog>`;
158
+ }
159
+ return html`<dialog data-trust="lightbox" ref=${ref} class="lb" role="dialog" aria-modal="true" aria-label=${label}>
160
+ <div class="lb-bar">
161
+ <span class="lb-name" title=${item.name}>${item.name}</span>
162
+ ${many ? html`<span class="lb-count">${t("chat.lbCount", at + 1, items.length)}</span>` : null}
163
+ <span class="lb-zoom" role="group">
164
+ <button type="button" class="icon-btn lb-zoom-out" disabled=${!level} aria-label=${t("chat.lbZoomOut")} title=${t("chat.lbZoomOut")}
165
+ onClick=${() => zoom.current && zoom.current.zoomBy(1 / STEP)}><${Icon} name="minus" /></button>
166
+ <button type="button" class="btn btn-sm lb-level" disabled=${!level} aria-label=${t("chat.lbZoomLevel", pct ?? "")} title=${t("chat.lbZoomLevel", pct ?? "")}
167
+ onClick=${() => zoom.current && zoom.current.toggle()}>${pct === null ? "…" : `${pct}%`}</button>
168
+ <button type="button" class="icon-btn lb-zoom-in" disabled=${!level} aria-label=${t("chat.lbZoomIn")} title=${t("chat.lbZoomIn")}
169
+ onClick=${() => zoom.current && zoom.current.zoomBy(STEP)}><${Icon} name="plus" /></button>
170
+ <button type="button" class=${`icon-btn lb-fit-width${level && level.mode === "width" ? " on" : ""}`} disabled=${!level} aria-pressed=${level && level.mode === "width" ? "true" : "false"}
171
+ aria-label=${t("chat.lbFitWidth")} title=${t("chat.lbFitWidth")} onClick=${() => zoom.current && zoom.current.fitWidth()}><${Icon} name="fitwidth" /></button>
172
+ </span>
173
+ ${annotate ? html`<button type="button" class="btn btn-sm lb-annotate" aria-label=${t("lbAnnotate.open")} title=${t("lbAnnotate.open")} onClick=${startAnnotate}><${Icon} name="edit" size=${14} /><span class="lbl">${t("lbAnnotate.open")}</span></button>` : null}
174
+ <a class="btn btn-sm lb-orig" href=${item.src} target="_blank" rel="noopener noreferrer"><${Icon} name="external" size=${14} /><span class="lbl">${t("chat.lbOpenOriginal")}</span></a>
175
+ <button type="button" class="icon-btn lb-close" ref=${close} aria-label=${t("chat.lbClose")} title=${t("chat.lbClose")} onClick=${onClose}><${Icon} name="close" /></button>
176
+ </div>
177
+ <div class="lb-stage" ref=${stage}><img class="lb-img" ref=${img} src=${item.src} alt=${item.name} draggable=${false} /></div>
178
+ ${many ? html`<button type="button" class="icon-btn lb-nav lb-prev" aria-label=${t("chat.lbPrev")} title=${t("chat.lbPrev")} onClick=${() => step(-1)}><${Icon} name="back" /></button>
179
+ <button type="button" class="icon-btn lb-nav lb-next" aria-label=${t("chat.lbNext")} title=${t("chat.lbNext")} onClick=${() => step(1)}><${Icon} name="forward" /></button>` : null}
180
+ </dialog>`;
181
+ }
182
+
183
+ LightboxHost.paneOwner = true;