@khanglvm/relay 0.18.0 → 0.20.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.
Files changed (138) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +39 -4
  3. package/schema/spec.v1.json +1368 -0
  4. package/src/a2ui/compile.js +2 -0
  5. package/src/cli/args.js +46 -0
  6. package/src/cli/ask.js +12 -0
  7. package/src/cli/boards.js +326 -0
  8. package/src/cli/config.js +56 -0
  9. package/src/cli/context.js +13 -0
  10. package/src/cli/git.js +183 -0
  11. package/src/cli/help.js +90 -0
  12. package/src/cli/index.js +103 -0
  13. package/src/cli/install.js +197 -0
  14. package/src/cli/io.js +186 -0
  15. package/src/cli/mcp.js +94 -0
  16. package/src/cli/share.js +45 -0
  17. package/src/cli/skill.js +192 -0
  18. package/src/cli/upgrade.js +130 -0
  19. package/src/cli/wait.js +172 -0
  20. package/src/file-preview.js +1 -1
  21. package/src/index.js +104 -0
  22. package/src/link.js +1 -0
  23. package/src/mcp-ui/board/block-ctx.js +43 -0
  24. package/src/mcp-ui/board/bridge.js +165 -0
  25. package/src/mcp-ui/board/controls.js +310 -0
  26. package/src/mcp-ui/board/core.js +20 -0
  27. package/src/mcp-ui/board/lifecycle.js +118 -0
  28. package/src/mcp-ui/board/normalize.js +95 -0
  29. package/src/mcp-ui/board/render.js +200 -0
  30. package/src/mcp-ui/board/state.js +106 -0
  31. package/src/mcp-ui/board/vendors.js +86 -0
  32. package/src/mcp.js +15 -21
  33. package/src/{server.js → server/board.js} +17 -781
  34. package/src/server/files.js +141 -0
  35. package/src/server/http.js +114 -0
  36. package/src/server/index.js +2 -0
  37. package/src/server/page.js +183 -0
  38. package/src/server/paths.js +7 -0
  39. package/src/server/result.js +58 -0
  40. package/src/server/reviews.js +41 -0
  41. package/src/server/sanitize.js +231 -0
  42. package/src/spec/blocks/a2ui.js +25 -0
  43. package/src/spec/blocks/chart.js +49 -0
  44. package/src/spec/blocks/code.js +38 -0
  45. package/src/spec/blocks/diagram.js +39 -0
  46. package/src/spec/blocks/git-conflict.js +106 -0
  47. package/src/spec/blocks/image.js +32 -0
  48. package/src/spec/blocks/index.js +33 -0
  49. package/src/spec/blocks/markdown.js +13 -0
  50. package/src/spec/blocks/pdf.js +38 -0
  51. package/src/spec/blocks/table.js +122 -0
  52. package/src/spec/blocks/video.js +68 -0
  53. package/src/spec/blocks/widgets.js +98 -0
  54. package/src/spec/constants.js +65 -0
  55. package/src/spec/index.js +5 -0
  56. package/src/spec/normalize.js +285 -0
  57. package/src/spec/ready.js +106 -0
  58. package/src/spec/schema.js +182 -0
  59. package/src/spec/sources.js +83 -0
  60. package/src/ui/annotate/api.js +149 -0
  61. package/src/ui/annotate/badges.js +77 -0
  62. package/src/ui/annotate/chrome.js +158 -0
  63. package/src/ui/annotate/core.js +134 -0
  64. package/src/ui/annotate/highlights.js +129 -0
  65. package/src/ui/annotate/mutations.js +127 -0
  66. package/src/ui/annotate/popover.js +206 -0
  67. package/src/ui/annotate/summary.js +67 -0
  68. package/src/ui/app/annotations.js +88 -0
  69. package/src/ui/app/autosave.js +44 -0
  70. package/src/ui/app/core.js +74 -0
  71. package/src/ui/app/drafts.js +201 -0
  72. package/src/ui/app/heartbeat.js +150 -0
  73. package/src/ui/app/iframe-bridge.js +64 -0
  74. package/src/ui/app/persistence.js +117 -0
  75. package/src/ui/app/prefilled.js +21 -0
  76. package/src/ui/app/presence.js +38 -0
  77. package/src/ui/app/question-color.js +67 -0
  78. package/src/ui/app/questions.js +360 -0
  79. package/src/ui/app/render.js +135 -0
  80. package/src/ui/app/share.js +108 -0
  81. package/src/ui/app/submit.js +109 -0
  82. package/src/ui/app/theme.js +63 -0
  83. package/src/ui/blocks/api.js +1 -0
  84. package/src/ui/blocks/chart.js +222 -0
  85. package/src/ui/blocks/code.js +138 -0
  86. package/src/ui/blocks/compare.js +82 -0
  87. package/src/ui/blocks/core.js +74 -0
  88. package/src/ui/blocks/diff.js +361 -0
  89. package/src/ui/blocks/dispatch.js +111 -0
  90. package/src/ui/blocks/file-links.js +180 -0
  91. package/src/ui/blocks/git-conflict.js +151 -0
  92. package/src/ui/blocks/graphviz.js +57 -0
  93. package/src/ui/blocks/html.js +45 -0
  94. package/src/ui/blocks/image.js +371 -0
  95. package/src/ui/blocks/kpi.js +26 -0
  96. package/src/ui/blocks/markdown.js +223 -0
  97. package/src/ui/blocks/mermaid.js +242 -0
  98. package/src/ui/blocks/palette.js +59 -0
  99. package/src/ui/blocks/pdf.js +21 -0
  100. package/src/ui/blocks/plantuml.js +152 -0
  101. package/src/ui/blocks/table.js +155 -0
  102. package/src/ui/blocks/typography.js +25 -0
  103. package/src/ui/blocks/vendor.js +43 -0
  104. package/src/ui/blocks/video.js +43 -0
  105. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  106. package/src/ui/blocks/viewer.js +324 -0
  107. package/src/ui/kit.js +1 -0
  108. package/src/ui/manifest.js +140 -0
  109. package/types/a2ui/compile.d.ts +40 -0
  110. package/types/index.d.ts +181 -0
  111. package/types/mcp.d.ts +31 -0
  112. package/types/spec/blocks/a2ui.d.ts +4 -0
  113. package/types/spec/blocks/chart.d.ts +4 -0
  114. package/types/spec/blocks/code.d.ts +10 -0
  115. package/types/spec/blocks/diagram.d.ts +15 -0
  116. package/types/spec/blocks/git-conflict.d.ts +7 -0
  117. package/types/spec/blocks/image.d.ts +5 -0
  118. package/types/spec/blocks/index.d.ts +30 -0
  119. package/types/spec/blocks/markdown.d.ts +5 -0
  120. package/types/spec/blocks/pdf.d.ts +4 -0
  121. package/types/spec/blocks/table.d.ts +9 -0
  122. package/types/spec/blocks/video.d.ts +4 -0
  123. package/types/spec/blocks/widgets.d.ts +21 -0
  124. package/types/spec/constants.d.ts +67 -0
  125. package/types/spec/index.d.ts +4 -0
  126. package/types/spec/normalize.d.ts +17 -0
  127. package/types/spec/ready.d.ts +1 -0
  128. package/types/spec/schema.d.ts +1171 -0
  129. package/types/spec/sources.d.ts +14 -0
  130. package/types/store.d.ts +29 -0
  131. package/types/ui/manifest.d.ts +62 -0
  132. package/types/util.d.ts +6 -0
  133. package/src/cli.js +0 -1766
  134. package/src/mcp-ui/board.js +0 -1162
  135. package/src/spec.js +0 -1222
  136. package/src/ui/annotate.js +0 -1055
  137. package/src/ui/app.js +0 -1643
  138. package/src/ui/blocks.js +0 -3260
@@ -1,1055 +0,0 @@
1
- /* relay annotate — element-level comments (window.RelayAnnotate).
2
- Self-contained vanilla JS: hover pin, count badges, comment popover,
3
- text-selection capture, and an editable summary list. Zero dependencies.
4
- Load order: blocks.js, annotate.js, app.js (all inlined by the server). */
5
- (() => {
6
- 'use strict';
7
-
8
- // ---------- helpers ----------
9
- function el(tag, attrs = {}, ...children) {
10
- const n = document.createElement(tag);
11
- for (const [k, v] of Object.entries(attrs)) {
12
- if (v === undefined || v === null) continue;
13
- if (k === 'class') n.className = v;
14
- else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);
15
- else n.setAttribute(k, v);
16
- }
17
- for (const c of children.flat()) {
18
- if (c !== null && c !== undefined) n.append(c.nodeType ? c : document.createTextNode(c));
19
- }
20
- return n;
21
- }
22
-
23
- function truncate(s, n) {
24
- s = String(s);
25
- return s.length > n ? s.slice(0, n - 1) + '…' : s;
26
- }
27
-
28
- // Humanized target label shown in the popover and the summary list.
29
- function humanize(t) {
30
- if (!t || typeof t !== 'object') return 'Element';
31
- switch (t.kind) {
32
- case 'chart-element': {
33
- const parts = [];
34
- if (t.label !== undefined && t.label !== null && t.label !== '') parts.push(truncate(t.label, 40));
35
- if (typeof t.datasetIndex === 'number') parts.push(`series ${t.datasetIndex + 1}`);
36
- if (t.value !== undefined && t.value !== null) {
37
- parts.push(truncate(typeof t.value === 'object' ? JSON.stringify(t.value) : t.value, 30));
38
- }
39
- return 'Chart · ' + (parts.join(' · ') || 'element');
40
- }
41
- case 'mermaid-node':
42
- return 'Diagram · ' + truncate(t.text || t.nodeId || 'node', 50);
43
- case 'graphviz-node':
44
- return 'Graph · ' + truncate(t.text || t.nodeId || 'node', 50);
45
- case 'plantuml-node':
46
- return 'Diagram · ' + truncate(t.text || 'element', 50);
47
- case 'image':
48
- return truncate(t.label || 'Image', 50);
49
- case 'image-point':
50
- return (t.label ? truncate(t.label, 30) + ' · ' : 'Image · ') + 'pin ' + Math.round((t.x || 0) * 100) + '%, ' + Math.round((t.y || 0) * 100) + '%';
51
- case 'image-region': {
52
- const source = t.side ? t.side.charAt(0).toUpperCase() + t.side.slice(1) + ' · ' : '';
53
- const area = `${Math.round((t.w || 0) * 100)}×${Math.round((t.h || 0) * 100)}% area`;
54
- return (t.label ? truncate(t.label, 30) + ' · ' : 'Image · ') + source + area;
55
- }
56
- case 'table-cell': {
57
- let s = `Table · row ${(Number(t.row) || 0) + 1} · ${t.col}`;
58
- if (t.value !== undefined && t.value !== null && t.value !== '') s += ` — “${truncate(t.value, 30)}”`;
59
- return s;
60
- }
61
- case 'code-line':
62
- return 'Line ' + t.line + (t.file ? ' · ' + truncate(t.file, 40) : '');
63
- case 'text':
64
- return `“${truncate(t.quote || '', 60)}”`;
65
- case 'html-element':
66
- return truncate(t.label || 'Element', 50) + (t.detail ? ` — ${truncate(t.detail, 40)}` : '');
67
- case 'block':
68
- return 'Whole ' + truncate(t.label || 'block', 40);
69
- default:
70
- return t.kind || 'Element';
71
- }
72
- }
73
-
74
- // Target equality for badge re-binding = stringify equality within a block.
75
- const sameTarget = (a, b) => JSON.stringify(a) === JSON.stringify(b);
76
- const sameBlock = (a, b) => (a ?? null) === (b ?? null);
77
-
78
- // Author chip: "you" (muted) for user comments, "agent" (accent) for agent.
79
- function chip(author) {
80
- const agent = author === 'agent';
81
- return el('span', { class: 'ann-chip' + (agent ? ' ann-chip-agent' : '') }, agent ? 'agent' : 'you');
82
- }
83
-
84
- // Short HH:MM timestamp (empty string when the date is unparsable).
85
- function fmtTime(iso) {
86
- const d = new Date(iso);
87
- if (isNaN(d.getTime())) return '';
88
- const p = (n) => String(n).padStart(2, '0');
89
- return p(d.getHours()) + ':' + p(d.getMinutes());
90
- }
91
-
92
- function timeEl(iso) {
93
- const t = fmtTime(iso);
94
- return t ? el('span', { class: 'ann-time' }, t) : null;
95
- }
96
-
97
- // ---------- state ----------
98
- let annotations = []; // contract annotation objects
99
- let idCounter = 0; // continues from max existing "aN"
100
- let onChange = null;
101
- let registered = []; // [{el, info: {blockId, questionId, target}}]
102
- const summaryEls = new Set();
103
- let badges = []; // live badge nodes (rebuilt on every refresh)
104
- let pendingSelection = null; // {info} captured at mouseup time
105
-
106
- // Text-selection comments are anchored back into the document as inline
107
- // <mark> highlights. textRoots maps a blockId (null = intro/board) to the
108
- // element whose text can be highlighted; highlightMap maps a target
109
- // signature to its live <mark> nodes so we can flash or unwrap them.
110
- const textRoots = new Map();
111
- const highlightMap = new Map();
112
-
113
- let dom = null; // {pin, selBtn, pop, rail, railList, railToggle, railScrim, ...}
114
- let pinTimer = null;
115
- let pinEntry = null;
116
- let popOpen = false;
117
- let popSave = null;
118
- let popCloseHook = null;
119
- let popAnchorEl = null;
120
- let popPositionFrame = 0;
121
- const commentDrafts = new Map();
122
- // Frozen by the host (e.g. relay's connection-lost block): suppress every way
123
- // to START a comment, so the user can't type feedback that won't be saved.
124
- let disabled = false;
125
- let permissions = { add: true, edit: true, delete: true, reply: true };
126
- let badgeTimer = 0;
127
- let railOpen = false;
128
-
129
- // Stable signature for a (blockId, target) pair — same key matching() groups by.
130
- const sigOf = (blockId, target) => JSON.stringify({ b: blockId ?? null, t: target });
131
-
132
- // Brief highlight pulse used by the rail's jump-to.
133
- function flashEl(target) {
134
- if (!target) return;
135
- target.scrollIntoView({ behavior: 'smooth', block: 'center' });
136
- target.classList.remove('ann-flash');
137
- void target.getBoundingClientRect(); // restart the animation
138
- target.classList.add('ann-flash');
139
- setTimeout(() => target.classList.remove('ann-flash'), 1000);
140
- }
141
-
142
- // ---------- text-selection highlights ----------
143
- // Re-locate a saved text quote inside a root using its prefix/suffix anchors,
144
- // returning a live Range (or null when the text can't be found anymore).
145
- function findRangeByQuote(root, target) {
146
- const quote = target && target.quote ? String(target.quote) : '';
147
- if (!quote) return null;
148
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
149
- const map = []; // [{ node, start }] start = offset in `full`
150
- let full = '';
151
- let node;
152
- while ((node = walker.nextNode())) {
153
- map.push({ node, start: full.length });
154
- full += node.nodeValue;
155
- }
156
- if (!map.length) return null;
157
- const prefix = target.prefix || '';
158
- const suffix = target.suffix || '';
159
- const hits = [];
160
- let from = 0;
161
- let idx;
162
- while ((idx = full.indexOf(quote, from)) !== -1) {
163
- hits.push(idx);
164
- from = idx + 1;
165
- }
166
- if (!hits.length) return null;
167
- let chosen = hits[0];
168
- for (const h of hits) {
169
- const before = full.slice(Math.max(0, h - prefix.length), h);
170
- const after = full.slice(h + quote.length, h + quote.length + suffix.length);
171
- if ((!prefix || before.endsWith(prefix)) && (!suffix || after.startsWith(suffix))) {
172
- chosen = h;
173
- break;
174
- }
175
- }
176
- const locate = (off) => {
177
- for (const m of map) {
178
- if (off <= m.start + m.node.nodeValue.length) return { node: m.node, offset: off - m.start };
179
- }
180
- const last = map[map.length - 1];
181
- return { node: last.node, offset: last.node.nodeValue.length };
182
- };
183
- const s = locate(chosen);
184
- const e = locate(chosen + quote.length);
185
- const range = document.createRange();
186
- try {
187
- range.setStart(s.node, s.offset);
188
- range.setEnd(e.node, e.offset);
189
- } catch {
190
- return null;
191
- }
192
- return range;
193
- }
194
-
195
- // Wrap every text-node segment inside `range` in its own <mark>; clicking a
196
- // mark opens the comment popover for that target. Returns the mark nodes.
197
- function wrapRange(range, sig, info) {
198
- const sC = range.startContainer;
199
- const sO = range.startOffset;
200
- const eC = range.endContainer;
201
- const eO = range.endOffset;
202
- const anc = range.commonAncestorContainer;
203
- const root = anc.nodeType === 1 ? anc : anc.parentNode;
204
- if (!root) return [];
205
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
206
- const all = [];
207
- let n;
208
- while ((n = walker.nextNode())) all.push(n);
209
- // Decide membership BEFORE mutating the DOM (splitText adds new siblings).
210
- const inRange = all.filter((node) => {
211
- try {
212
- return range.intersectsNode(node);
213
- } catch {
214
- return false;
215
- }
216
- });
217
- const marks = [];
218
- for (const orig of inRange) {
219
- let fromOff = 0;
220
- let toOff = orig.nodeValue.length;
221
- if (orig === sC) fromOff = sO;
222
- if (orig === eC) toOff = eO;
223
- if (fromOff >= toOff) continue;
224
- let seg = orig;
225
- if (fromOff > 0) seg = seg.splitText(fromOff);
226
- if (toOff - fromOff < seg.nodeValue.length) seg.splitText(toOff - fromOff);
227
- const mark = el('mark', { class: 'ann-hl', 'data-sig': sig });
228
- seg.parentNode.insertBefore(mark, seg);
229
- mark.appendChild(seg);
230
- mark.addEventListener('click', (ev) => {
231
- ev.stopPropagation();
232
- openPopover(info, mark);
233
- });
234
- marks.push(mark);
235
- }
236
- return marks;
237
- }
238
-
239
- function unwrapHighlight(sig) {
240
- const marks = highlightMap.get(sig);
241
- if (!marks) return;
242
- for (const m of marks) {
243
- if (!m.isConnected) continue;
244
- const parent = m.parentNode;
245
- while (m.firstChild) parent.insertBefore(m.firstChild, m);
246
- parent.removeChild(m);
247
- parent.normalize();
248
- }
249
- highlightMap.delete(sig);
250
- }
251
-
252
- // Highlight every saved text annotation whose blockId matches this root and
253
- // that isn't already wrapped (idempotent — safe to call on every register).
254
- function applyHighlightsForRoot(root, blockId) {
255
- const key = blockId ?? null;
256
- const seen = new Set();
257
- for (const a of annotations) {
258
- if (!a.target || a.target.kind !== 'text') continue;
259
- if ((a.blockId ?? null) !== key) continue;
260
- const sig = sigOf(a.blockId, a.target);
261
- if (seen.has(sig) || highlightMap.has(sig)) continue;
262
- seen.add(sig);
263
- const range = findRangeByQuote(root, a.target);
264
- if (!range) continue;
265
- const info = { blockId: a.blockId ?? null, questionId: a.questionId ?? null, target: a.target };
266
- const marks = wrapRange(range, sig, info);
267
- if (marks.length) highlightMap.set(sig, marks);
268
- }
269
- }
270
-
271
- // ---------- singleton DOM ----------
272
- function ensureDom() {
273
- if (dom) return;
274
- const pin = el('button', { class: 'ann-pin', type: 'button', title: 'Add a comment', 'aria-label': 'Add a comment' });
275
- pin.innerHTML =
276
- '<svg viewBox="0 0 16 16" width="11" height="11" aria-hidden="true">' +
277
- '<path d="M3 2.5h10A1.5 1.5 0 0 1 14.5 4v5a1.5 1.5 0 0 1-1.5 1.5H8.4L5 13.4v-2.9H3A1.5 1.5 0 0 1 1.5 9V4A1.5 1.5 0 0 1 3 2.5Z" fill="currentColor"/></svg>';
278
- pin.addEventListener('mouseenter', () => clearTimeout(pinTimer));
279
- pin.addEventListener('mouseleave', scheduleHidePin);
280
- pin.addEventListener('click', (e) => {
281
- e.stopPropagation();
282
- const entry = pinEntry;
283
- hidePin();
284
- if (entry) openPopover(entry.info, entry.el);
285
- });
286
-
287
- const selBtn = el('button', { class: 'ann-selbtn', type: 'button' }, 'Comment');
288
- // preventDefault keeps the text selection alive through the click.
289
- selBtn.addEventListener('mousedown', (e) => e.preventDefault());
290
- selBtn.addEventListener('click', (e) => {
291
- e.stopPropagation();
292
- const p = pendingSelection;
293
- if (p) openPopover(p.info, selBtn); // anchor rect read while still visible
294
- hideSelBtn();
295
- });
296
-
297
- const pop = el('div', { class: 'ann-pop', role: 'dialog', 'aria-label': 'Comment' });
298
- pop.addEventListener('keydown', (e) => {
299
- if (e.key === 'Escape') {
300
- e.stopPropagation();
301
- closePopover();
302
- } else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
303
- e.preventDefault();
304
- if (popSave) popSave();
305
- }
306
- });
307
-
308
- // Comments rail (Outline-style right sidebar) + its floating toggle and
309
- // narrow-screen scrim. The list is a summary target, so renderSummaries()
310
- // keeps it in sync; chrome (count, visibility) is refreshed separately.
311
- const railToggleCount = el('span', { class: 'ann-rail-toggle-count' }, '0');
312
- const railToggle = el('button', { class: 'ann-rail-toggle', type: 'button', 'aria-label': 'Comments' });
313
- railToggle.innerHTML =
314
- '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">' +
315
- '<path d="M3 2.5h10A1.5 1.5 0 0 1 14.5 4v5a1.5 1.5 0 0 1-1.5 1.5H8.4L5 13.4v-2.9H3A1.5 1.5 0 0 1 1.5 9V4A1.5 1.5 0 0 1 3 2.5Z" fill="currentColor"/></svg>';
316
- railToggle.append(el('span', { class: 'ann-rail-toggle-label' }, 'Comments'), railToggleCount);
317
- railToggle.addEventListener('click', toggleRail);
318
-
319
- const railScrim = el('div', { class: 'ann-rail-scrim' });
320
- railScrim.addEventListener('click', closeRail);
321
-
322
- const railClose = el('button', { class: 'ann-rail-close', type: 'button', 'aria-label': 'Close comments', title: 'Close' }, '×');
323
- railClose.addEventListener('click', closeRail);
324
- const railHeadCount = el('span', { class: 'ann-rail-headcount' }, '');
325
- const railList = el('div', { class: 'ann-rail-list' });
326
- const rail = el('aside', { class: 'ann-rail', 'aria-label': 'Comments' },
327
- el('div', { class: 'ann-rail-head' },
328
- el('span', { class: 'ann-rail-title' }, 'Comments'),
329
- railHeadCount,
330
- railClose
331
- ),
332
- railList
333
- );
334
-
335
- document.body.append(pin, selBtn, pop, railToggle, railScrim, rail);
336
- dom = { pin, selBtn, pop, railToggle, railToggleCount, railScrim, rail, railList, railHeadCount };
337
- summaryEls.add(railList);
338
-
339
- document.addEventListener('selectionchange', () => {
340
- if (dom.selBtn.style.display === '' || dom.selBtn.style.display === 'none') return;
341
- const sel = window.getSelection();
342
- const txt = sel && !sel.isCollapsed ? sel.toString() : '';
343
- if (!pendingSelection || txt.slice(0, 500) !== pendingSelection.info.target.quote) hideSelBtn();
344
- });
345
-
346
- document.addEventListener('mousedown', (e) => {
347
- if (popOpen && !dom.pop.contains(e.target)) closePopover();
348
- if (!dom.selBtn.contains(e.target)) hideSelBtn();
349
- });
350
-
351
- // Capture-phase: also fires for nested scroll containers (mermaid pane…).
352
- // Keep an open composer re-anchored instead of closing it: scrolling is a
353
- // normal review action, and DOM-only draft text must never disappear merely
354
- // because the user looked elsewhere on the board.
355
- window.addEventListener('scroll', (e) => {
356
- hidePin();
357
- hideSelBtn();
358
- if (!popOpen) return;
359
- if (dom.pop.contains(e.target)) return; // textarea scrolling inside
360
- schedulePositionPopover();
361
- }, true);
362
-
363
- window.addEventListener('resize', () => {
364
- scheduleBadgeRefresh();
365
- schedulePositionPopover();
366
- });
367
- }
368
-
369
- // ---------- comments rail ----------
370
- function openRail() {
371
- if (!dom || torndown || !annotations.length) return;
372
- railOpen = true;
373
- dom.rail.classList.add('open');
374
- dom.railScrim.classList.add('show');
375
- document.body.classList.add('ann-rail-open');
376
- }
377
- function closeRail() {
378
- railOpen = false;
379
- if (!dom) return;
380
- dom.rail.classList.remove('open');
381
- dom.railScrim.classList.remove('show');
382
- document.body.classList.remove('ann-rail-open');
383
- }
384
- function toggleRail() {
385
- if (railOpen) closeRail();
386
- else openRail();
387
- }
388
- // Briefly flash the floating Comments button (used when a comment is added so
389
- // the user sees it landed, without auto-opening the rail / shifting layout).
390
- function pulseToggle() {
391
- if (!dom || !dom.railToggle) return;
392
- dom.railToggle.classList.remove('pulse');
393
- void dom.railToggle.offsetWidth; // reflow so the animation restarts
394
- dom.railToggle.classList.add('pulse');
395
- }
396
- // Sync the toggle badge + rail count with the live list; hide the whole rail
397
- // affordance when there are no comments.
398
- function refreshRailChrome() {
399
- if (!dom) return;
400
- const n = annotations.length;
401
- dom.railToggleCount.textContent = String(n);
402
- dom.railHeadCount.textContent = n ? `${n}` : '';
403
- dom.railToggle.style.display = n ? 'inline-flex' : 'none';
404
- if (!n) closeRail();
405
- }
406
-
407
- // ---------- hover pin ----------
408
- function showPin(entry) {
409
- if (disabled || !permissions.add) return;
410
- clearTimeout(pinTimer);
411
- pinEntry = entry;
412
- const rect = entry.el.getBoundingClientRect();
413
- const w = 22;
414
- const pin = dom.pin;
415
- pin.style.display = 'flex';
416
- pin.style.left = Math.max(4, Math.min(rect.right - w / 2, window.innerWidth - w - 4)) + 'px';
417
- pin.style.top = Math.max(4, Math.min(rect.top - w / 2, window.innerHeight - w - 4)) + 'px';
418
- }
419
- function scheduleHidePin() {
420
- clearTimeout(pinTimer);
421
- pinTimer = setTimeout(hidePin, 250); // delay so the pin itself is clickable
422
- }
423
- function hidePin() {
424
- clearTimeout(pinTimer);
425
- pinEntry = null;
426
- if (dom) dom.pin.style.display = 'none';
427
- }
428
-
429
- // ---------- badges ----------
430
- function matching(info) {
431
- return annotations.filter((a) => sameBlock(a.blockId, info.blockId) && sameTarget(a.target, info.target));
432
- }
433
-
434
- function scheduleBadgeRefresh() {
435
- if (badgeTimer) return;
436
- badgeTimer = setTimeout(() => {
437
- badgeTimer = 0;
438
- refreshBadges();
439
- }, 0);
440
- }
441
-
442
- // Hosts (e.g. blocks.js chart badge / comment button) subscribe here to be
443
- // notified on every badge refresh — i.e. whenever annotations change — so
444
- // their own indicators stay in sync. Returns an unsubscribe fn.
445
- const badgeHooks = new Set();
446
- function onBadgeRefresh(fn) {
447
- if (typeof fn === 'function') badgeHooks.add(fn);
448
- return () => badgeHooks.delete(fn);
449
- }
450
-
451
- function refreshBadges() {
452
- for (const b of badges) b.remove();
453
- badges = [];
454
- if (torndown) { for (const fn of badgeHooks) { try { fn(); } catch (_) {} } return; }
455
- registered = registered.filter((r) => r.el.isConnected);
456
- // While a block is expanded full-screen, body-level overlay badges for
457
- // OTHER blocks would float above the overlay at stale positions — only
458
- // badge elements inside the expanded block.
459
- const fullEl = document.body.classList.contains('blk-full-open')
460
- ? document.querySelector('.blk-full')
461
- : null;
462
- for (const entry of registered) {
463
- if (fullEl && !fullEl.contains(entry.el)) continue;
464
- const count = matching(entry.info).length;
465
- if (!count) continue;
466
- const badge = el('span', { class: 'ann-badge', title: count + (count === 1 ? ' comment' : ' comments') }, String(count));
467
- badge.addEventListener('mousedown', (e) => e.stopPropagation());
468
- badge.addEventListener('click', (e) => {
469
- e.stopPropagation();
470
- e.preventDefault();
471
- hidePin();
472
- openPopover(entry.info, entry.el);
473
- });
474
- if (entry.el instanceof HTMLElement && !(entry.el instanceof HTMLImageElement)) {
475
- // a normal HTML element hosts the badge as a child — it tracks naturally
476
- if (getComputedStyle(entry.el).position === 'static') entry.el.classList.add('ann-rel');
477
- entry.el.append(badge);
478
- } else {
479
- // SVG node or <img> — neither can host an HTML child. Anchor the badge
480
- // INSIDE the scrollable diagram viewport in CONTENT coordinates: as an
481
- // absolutely-positioned child of the scroll box it rides with the content
482
- // on drag-pan / container-scroll / page-scroll, with no listener needed.
483
- // (A document-body overlay stayed put when the diagram itself scrolled.)
484
- badge.classList.add('ann-badge-overlay');
485
- const host = entry.el.closest ? entry.el.closest('.blk-viewer') : null;
486
- const r = entry.el.getBoundingClientRect();
487
- if (host) {
488
- const cr = host.getBoundingClientRect();
489
- const cs = getComputedStyle(host);
490
- const bL = parseFloat(cs.borderLeftWidth) || 0;
491
- const bT = parseFloat(cs.borderTopWidth) || 0;
492
- badge.style.left = (r.right - cr.left - bL + host.scrollLeft - 10) + 'px';
493
- badge.style.top = (r.top - cr.top - bT + host.scrollTop - 6) + 'px';
494
- host.append(badge);
495
- } else {
496
- badge.style.left = (r.right + window.scrollX - 10) + 'px';
497
- badge.style.top = (r.top + window.scrollY - 6) + 'px';
498
- document.body.append(badge);
499
- }
500
- }
501
- badges.push(badge);
502
- }
503
- for (const fn of badgeHooks) { try { fn(); } catch (_) {} }
504
- }
505
-
506
- // ---------- popover ----------
507
- function positionPopover() {
508
- popPositionFrame = 0;
509
- if (!popOpen || !dom || !popAnchorEl || !popAnchorEl.isConnected) return;
510
- const pop = dom.pop;
511
- const rect = popAnchorEl.getBoundingClientRect();
512
- const pw = pop.offsetWidth;
513
- const ph = pop.offsetHeight;
514
- const left = Math.max(8, Math.min(rect.left, window.innerWidth - pw - 8));
515
- let top = rect.bottom + 8;
516
- if (top + ph > window.innerHeight - 8 && rect.top - ph - 8 >= 8) top = rect.top - ph - 8;
517
- top = Math.max(8, Math.min(top, window.innerHeight - ph - 8));
518
- pop.style.left = left + 'px';
519
- pop.style.top = top + 'px';
520
- }
521
-
522
- function schedulePositionPopover() {
523
- if (!popOpen || popPositionFrame) return;
524
- popPositionFrame = requestAnimationFrame(positionPopover);
525
- }
526
-
527
- function closePopover(reason = 'dismissed') {
528
- if (!popOpen) return;
529
- const closeHook = popCloseHook;
530
- popOpen = false;
531
- popSave = null;
532
- popCloseHook = null;
533
- popAnchorEl = null;
534
- if (popPositionFrame) cancelAnimationFrame(popPositionFrame);
535
- popPositionFrame = 0;
536
- dom.pop.style.display = 'none';
537
- dom.pop.replaceChildren();
538
- if (closeHook) {
539
- try { closeHook(reason); } catch (_) { /* lifecycle hooks are best-effort */ }
540
- }
541
- }
542
-
543
- // ---------- delete a comment (with confirm) ----------
544
- // The × that used to delete a comment read as "close the popup". Delete is now
545
- // a distinct trash button that opens a confirm modal; "Don't ask again"
546
- // (default OFF) suppresses future confirms for the session (persisted best-effort).
547
- const ICON_TRASH =
548
- '<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
549
- '<path d="M2.5 4h11M6 4V2.5h4V4M5 4l.5 9h5l.5-9"/></svg>';
550
- const ICON_PENCIL =
551
- '<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
552
- '<path d="M11.5 2.5l2 2L6 12l-2.5.5.5-2.5 7.5-7.5z"/></svg>';
553
- const DEL_SKIP_KEY = 'relay-ann-del-skip';
554
- let delConfirmSkip = false;
555
- try { delConfirmSkip = localStorage.getItem(DEL_SKIP_KEY) === '1'; } catch { /* sandbox: no storage */ }
556
-
557
- function requestDelete(id, after) {
558
- if (!permissions.delete) return;
559
- const done = () => { removeAnnotation(id); if (after) after(); };
560
- if (delConfirmSkip) { done(); return; }
561
- showDeleteConfirm(done);
562
- }
563
- function showDeleteConfirm(onConfirm) {
564
- const scrim = el('div', { class: 'ann-confirm-scrim' });
565
- const skip = el('input', { type: 'checkbox' });
566
- const cancel = el('button', { class: 'ann-confirm-cancel', type: 'button' }, 'Cancel');
567
- const del = el('button', { class: 'ann-confirm-del', type: 'button' }, 'Delete');
568
- const close = () => { scrim.remove(); document.removeEventListener('keydown', onKey, true); };
569
- const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); close(); } };
570
- cancel.addEventListener('click', close);
571
- scrim.addEventListener('mousedown', (e) => { if (e.target === scrim) close(); });
572
- del.addEventListener('click', () => {
573
- if (skip.checked) { delConfirmSkip = true; try { localStorage.setItem(DEL_SKIP_KEY, '1'); } catch { /* sandbox */ } }
574
- close();
575
- onConfirm();
576
- });
577
- scrim.append(el('div', { class: 'ann-confirm', role: 'alertdialog', 'aria-label': 'Delete comment' },
578
- el('div', { class: 'ann-confirm-title' }, 'Delete this comment?'),
579
- el('div', { class: 'ann-confirm-msg' }, 'This removes the comment and its replies. It can’t be undone.'),
580
- el('label', { class: 'ann-confirm-skip' }, skip, el('span', {}, 'Don’t ask again')),
581
- el('div', { class: 'ann-confirm-actions' }, cancel, del)
582
- ));
583
- document.body.append(scrim);
584
- document.addEventListener('keydown', onKey, true);
585
- setTimeout(() => { try { cancel.focus(); } catch { /* ignore */ } }, 0);
586
- }
587
-
588
- function openPopover(info, anchorEl) {
589
- if (disabled) return;
590
- ensureDom();
591
- const hasExisting = matching(info).length > 0;
592
- const draftKey = sigOf(info.blockId, info.target);
593
- // Read-only viewers can open existing threads from their badges, but a
594
- // target with no feedback has nothing to show and must not expose an empty
595
- // add-comment dialog.
596
- if (!permissions.add && !hasExisting) return;
597
- closePopover();
598
- popCloseHook = typeof info.onClose === 'function' ? info.onClose : null;
599
- hidePin();
600
- const pop = dom.pop;
601
- // Header: target label + an explicit CLOSE button, so × always means "close".
602
- const popClose = el('button', { class: 'ann-pop-close', type: 'button', title: 'Close', 'aria-label': 'Close' }, '×');
603
- popClose.addEventListener('click', () => closePopover('dismissed'));
604
- pop.replaceChildren(el('div', { class: 'ann-pop-head' }, el('div', { class: 'ann-pop-label' }, humanize(info.target)), popClose));
605
-
606
- // Existing comments on this exact target, rendered as threads: author
607
- // chip + time + delete, the comment text, its replies indented below,
608
- // and a compact reply input per thread. Deleting a comment deletes its
609
- // whole thread.
610
- const existingWrap = el('div', { class: 'ann-pop-existing' });
611
- const renderExisting = () => {
612
- existingWrap.replaceChildren();
613
- for (const a of matching(info)) {
614
- const del = el('button', { class: 'ann-del', type: 'button', title: 'Delete comment', 'aria-label': 'Delete comment' });
615
- del.innerHTML = ICON_TRASH;
616
- del.addEventListener('click', () => requestDelete(a.id, renderExisting));
617
- const edit = el('button', { class: 'ann-edit', type: 'button', title: 'Edit comment', 'aria-label': 'Edit comment' });
618
- edit.innerHTML = ICON_PENCIL;
619
- const textEl = el('div', { class: 'ann-pop-text' }, a.text);
620
- // Inline edit: swap the text for a textarea + Save/Cancel; Save commits
621
- // via editAnnotation, then re-renders. Only the user's own comment is editable.
622
- edit.addEventListener('click', () => {
623
- const ta = el('textarea', { class: 'ann-ta ann-edit-ta', rows: '3' });
624
- ta.value = a.text;
625
- const save = el('button', { class: 'ann-save', type: 'button' }, 'Save');
626
- const cancel = el('button', { class: 'ann-cancel', type: 'button' }, 'Cancel');
627
- save.addEventListener('click', () => { editAnnotation(a.id, ta.value); renderExisting(); });
628
- cancel.addEventListener('click', renderExisting);
629
- ta.addEventListener('keydown', (e) => {
630
- if (e.key === 'Escape') { e.stopPropagation(); renderExisting(); }
631
- else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); editAnnotation(a.id, ta.value); renderExisting(); }
632
- });
633
- textEl.replaceWith(el('div', { class: 'ann-edit-form' }, ta, el('div', { class: 'ann-pop-actions' }, save, cancel)));
634
- ta.focus();
635
- });
636
- // agent replies aren't editable here — only the top-level user comment
637
- const actions = el('div', { class: 'ann-thread-actions' },
638
- permissions.edit && a.author === 'user' ? edit : null,
639
- permissions.delete ? del : null
640
- );
641
- const thread = el('div', { class: 'ann-thread' },
642
- el('div', { class: 'ann-thread-head' }, chip(a.author), timeEl(a.createdAt), actions),
643
- textEl
644
- );
645
- if (Array.isArray(a.replies) && a.replies.length) {
646
- const list = el('div', { class: 'ann-replies' });
647
- for (const r of a.replies) {
648
- list.append(el('div', { class: 'ann-reply' },
649
- el('div', { class: 'ann-reply-head' }, chip(r.author), timeEl(r.createdAt)),
650
- el('div', { class: 'ann-reply-text' }, r.text)
651
- ));
652
- }
653
- thread.append(list);
654
- }
655
- const input = el('input', { class: 'ann-reply-input', type: 'text', placeholder: 'Reply…', 'aria-label': 'Reply' });
656
- const btn = el('button', { class: 'ann-reply-btn', type: 'button' }, 'Reply');
657
- const submitReply = () => {
658
- const text = input.value.trim();
659
- if (!text) return;
660
- addReply(a.id, text);
661
- renderExisting();
662
- };
663
- btn.addEventListener('click', submitReply);
664
- input.addEventListener('keydown', (e) => {
665
- if (e.key === 'Enter' && !e.metaKey && !e.ctrlKey) {
666
- e.preventDefault();
667
- submitReply();
668
- }
669
- });
670
- if (permissions.reply) thread.append(el('div', { class: 'ann-reply-form' }, input, btn));
671
- existingWrap.append(thread);
672
- }
673
- };
674
- renderExisting();
675
- pop.append(existingWrap);
676
-
677
- const ta = el('textarea', { class: 'ann-ta', placeholder: 'Add a comment…', rows: '3' });
678
- ta.value = commentDrafts.get(draftKey) || '';
679
- ta.addEventListener('input', () => {
680
- if (ta.value) commentDrafts.set(draftKey, ta.value);
681
- else commentDrafts.delete(draftKey);
682
- });
683
- const save = el('button', { class: 'ann-save', type: 'button' }, 'Save');
684
- const cancel = el('button', { class: 'ann-cancel', type: 'button' }, 'Cancel');
685
- popSave = () => {
686
- const text = ta.value.trim();
687
- if (text) addAnnotation(info, text);
688
- commentDrafts.delete(draftKey);
689
- if (text) closePopover('saved');
690
- else closePopover('empty');
691
- };
692
- save.addEventListener('click', () => popSave && popSave());
693
- cancel.addEventListener('click', () => {
694
- commentDrafts.delete(draftKey);
695
- closePopover('cancelled');
696
- });
697
- if (permissions.add) pop.append(ta, el('div', { class: 'ann-pop-actions' }, save, cancel));
698
-
699
- // Position: prefer below the anchor, flip above when out of room, and clamp
700
- // to the viewport. Scroll/resize re-run this through one animation frame so
701
- // the composer tracks browser scrolling smoothly without losing its draft.
702
- pop.style.display = 'block';
703
- pop.style.visibility = 'hidden';
704
- popOpen = true;
705
- popAnchorEl = anchorEl;
706
- positionPopover();
707
- pop.style.visibility = '';
708
- if (permissions.add) ta.focus();
709
- else popClose.focus();
710
- }
711
-
712
- // ---------- mutations ----------
713
- function addAnnotation(info, text) {
714
- if (!permissions.add) return;
715
- annotations.push({
716
- id: 'a' + (++idCounter),
717
- questionId: info.questionId !== undefined ? info.questionId : null,
718
- blockId: info.blockId !== undefined ? info.blockId : null,
719
- target: info.target,
720
- text,
721
- createdAt: new Date().toISOString(),
722
- author: 'user',
723
- replies: [],
724
- });
725
- // Highlight the selected text in place (re-located via its quote anchors,
726
- // since the live selection is already gone by save time).
727
- if (info.target && info.target.kind === 'text') {
728
- const sig = sigOf(info.blockId, info.target);
729
- const root = textRoots.get(info.blockId ?? null);
730
- if (root && !highlightMap.has(sig)) {
731
- const range = findRangeByQuote(root, info.target);
732
- if (range) {
733
- const marks = wrapRange(range, sig, { blockId: info.blockId ?? null, questionId: info.questionId ?? null, target: info.target });
734
- if (marks.length) highlightMap.set(sig, marks);
735
- }
736
- }
737
- }
738
- changed();
739
- // Don't auto-open the rail — that shifts the board layout. Just flash the
740
- // floating Comments button so the user notices, and opens it when they want.
741
- pulseToggle();
742
- }
743
-
744
- // Append a user reply to a top-level annotation's thread (cap 50, like the
745
- // server). Empty text is ignored by callers.
746
- function addReply(id, text) {
747
- if (!permissions.reply) return;
748
- const a = annotations.find((x) => x.id === id);
749
- if (!a) return;
750
- if (!Array.isArray(a.replies)) a.replies = [];
751
- if (a.replies.length >= 50) return;
752
- a.replies.push({
753
- author: 'user',
754
- text: String(text).slice(0, 5000),
755
- createdAt: new Date().toISOString(),
756
- });
757
- changed();
758
- }
759
-
760
- // Edit a top-level comment's text in place (author edits their own comment).
761
- function editAnnotation(id, text) {
762
- if (!permissions.edit) return;
763
- const a = annotations.find((x) => x.id === id);
764
- if (!a) return;
765
- const t = String(text).slice(0, 5000).trim();
766
- if (!t) return;
767
- a.text = t;
768
- changed();
769
- }
770
-
771
- function removeAnnotation(id) {
772
- if (!permissions.delete) return;
773
- const i = annotations.findIndex((a) => a.id === id);
774
- if (i < 0) return;
775
- const removed = annotations[i];
776
- annotations.splice(i, 1);
777
- // Drop the inline highlight once the last comment on that text is gone.
778
- if (removed.target && removed.target.kind === 'text') {
779
- const sig = sigOf(removed.blockId, removed.target);
780
- if (!annotations.some((a) => sigOf(a.blockId, a.target) === sig)) unwrapHighlight(sig);
781
- }
782
- changed();
783
- }
784
-
785
- function changed() {
786
- scheduleBadgeRefresh();
787
- renderSummaries();
788
- refreshRailChrome();
789
- if (onChange) onChange(annotations.slice());
790
- }
791
-
792
- // ---------- text selection ----------
793
- function hideSelBtn() {
794
- pendingSelection = null;
795
- if (dom) dom.selBtn.style.display = 'none';
796
- }
797
-
798
- function maybeShowSelBtn(rootEl, baseInfo) {
799
- if (disabled || !permissions.add) return hideSelBtn();
800
- const sel = window.getSelection();
801
- if (!sel || sel.isCollapsed || !sel.rangeCount) return hideSelBtn();
802
- if (!rootEl.contains(sel.anchorNode) || !rootEl.contains(sel.focusNode)) return hideSelBtn();
803
- const range = sel.getRangeAt(0);
804
- const quote = range.toString();
805
- if (!quote.trim()) return hideSelBtn();
806
-
807
- const pre = document.createRange();
808
- pre.selectNodeContents(rootEl);
809
- pre.setEnd(range.startContainer, range.startOffset);
810
- const post = document.createRange();
811
- post.selectNodeContents(rootEl);
812
- post.setStart(range.endContainer, range.endOffset);
813
- pendingSelection = {
814
- info: {
815
- blockId: baseInfo.blockId !== undefined ? baseInfo.blockId : null,
816
- questionId: baseInfo.questionId !== undefined ? baseInfo.questionId : null,
817
- target: {
818
- kind: 'text',
819
- quote: quote.slice(0, 500),
820
- prefix: pre.toString().slice(-30),
821
- suffix: post.toString().slice(0, 30),
822
- },
823
- },
824
- };
825
-
826
- // Float the button near the end of the selection.
827
- const rects = range.getClientRects();
828
- const last = rects.length ? rects[rects.length - 1] : range.getBoundingClientRect();
829
- const btn = dom.selBtn;
830
- btn.style.display = 'block';
831
- const bw = btn.offsetWidth || 90;
832
- const bh = btn.offsetHeight || 30;
833
- let top = last.bottom + 6;
834
- if (top + bh > window.innerHeight - 8) top = last.top - bh - 6;
835
- btn.style.left = Math.max(8, Math.min(last.right - bw / 2, window.innerWidth - bw - 8)) + 'px';
836
- btn.style.top = Math.max(8, top) + 'px';
837
- }
838
-
839
- // ---------- summary ----------
840
- function renderSummaries() {
841
- for (const t of summaryEls) {
842
- if (!t.isConnected) {
843
- summaryEls.delete(t);
844
- continue;
845
- }
846
- renderSummaryInto(t);
847
- }
848
- }
849
-
850
- function renderSummaryInto(target) {
851
- const isRail = target.classList.contains('ann-rail-list');
852
- target.classList.add('ann-summary');
853
- target.replaceChildren();
854
- if (!annotations.length) {
855
- target.style.display = 'none';
856
- return;
857
- }
858
- target.style.display = '';
859
- // The rail has its own header chrome; standalone summaries get a heading.
860
- if (!isRail) target.append(el('h3', { class: 'ann-sum-head' }, `Comments (${annotations.length})`));
861
- for (const a of annotations) {
862
- const del = el('button', { class: 'ann-del', type: 'button', title: 'Delete comment', 'aria-label': 'Delete comment' });
863
- del.innerHTML = ICON_TRASH;
864
- del.addEventListener('click', (e) => { e.stopPropagation(); requestDelete(a.id); });
865
- // Thread meta: reply count, plus an "agent" chip when the latest entry
866
- // in the thread (last reply, or the comment itself) is agent-authored.
867
- const replyCount = Array.isArray(a.replies) ? a.replies.length : 0;
868
- const latest = replyCount ? a.replies[replyCount - 1] : a;
869
- const meta = [];
870
- if (replyCount) meta.push(el('span', { class: 'ann-sum-replies' }, `${replyCount} ${replyCount === 1 ? 'reply' : 'replies'}`));
871
- if (latest.author === 'agent') meta.push(chip('agent'));
872
- const row = el('div', { class: 'ann-sum-row' },
873
- el('div', { class: 'ann-sum-main' },
874
- el('div', { class: 'ann-sum-target' }, humanize(a.target)),
875
- el('div', { class: 'ann-sum-text' }, a.text),
876
- meta.length ? el('div', { class: 'ann-sum-meta' }, meta) : null
877
- ),
878
- permissions.delete ? del : null
879
- );
880
- // Clicking a row jumps to (and flashes) the matching element: a
881
- // registered block element, or the inline highlight for a text comment.
882
- row.addEventListener('click', () => {
883
- const entry = registered.find(
884
- (r) => r.el.isConnected && sameBlock(r.info.blockId, a.blockId) && sameTarget(r.info.target, a.target)
885
- );
886
- let jump = entry ? entry.el : null;
887
- if (!jump && a.target && a.target.kind === 'text') {
888
- const marks = highlightMap.get(sigOf(a.blockId, a.target));
889
- jump = marks && marks.find((m) => m.isConnected);
890
- }
891
- // Fallback for targets with no registered element (e.g. chart data
892
- // points / whole-block comments): flash the whole block container.
893
- if (!jump && a.blockId != null) {
894
- jump = document.querySelector('[data-block-id="' + String(a.blockId).replace(/"/g, '\\"') + '"]');
895
- }
896
- if (!jump) return;
897
- // On narrow screens the rail overlays the page — close it so the
898
- // flashed target is actually visible.
899
- if (isRail && window.matchMedia('(max-width: 1179px)').matches) closeRail();
900
- flashEl(jump);
901
- });
902
- target.append(row);
903
- }
904
- }
905
-
906
- // ---------- public API ----------
907
- function normalizeList(value) {
908
- return Array.isArray(value)
909
- ? value.map((a) => ({
910
- ...a,
911
- author: a.author === 'agent' ? 'agent' : 'user',
912
- replies: Array.isArray(a.replies)
913
- ? a.replies
914
- .filter((r) => r && typeof r === 'object' && typeof r.text === 'string')
915
- .map((r) => ({
916
- author: r.author === 'agent' ? 'agent' : 'user',
917
- text: r.text,
918
- createdAt: typeof r.createdAt === 'string' ? r.createdAt : '',
919
- }))
920
- : [],
921
- }))
922
- : [];
923
- }
924
-
925
- function resetCounter() {
926
- idCounter = 0;
927
- for (const a of annotations) {
928
- const m = /^a(\d+)$/.exec(String(a.id || ''));
929
- if (m) idCounter = Math.max(idCounter, parseInt(m[1], 10));
930
- }
931
- }
932
-
933
- function init(opts = {}) {
934
- ensureDom();
935
- // Normalize threads: missing author -> 'user', missing replies -> [].
936
- annotations = normalizeList(opts.initial);
937
- onChange = typeof opts.onChange === 'function' ? opts.onChange : null;
938
- permissions = {
939
- add: !(opts.permissions && opts.permissions.add === false),
940
- edit: !(opts.permissions && opts.permissions.edit === false),
941
- delete: !(opts.permissions && opts.permissions.delete === false),
942
- reply: !(opts.permissions && opts.permissions.reply === false),
943
- };
944
- resetCounter();
945
- scheduleBadgeRefresh();
946
- renderSummaries();
947
- refreshRailChrome();
948
- }
949
-
950
- // Remove every floating element (pin, badges, popover, selection button)
951
- // and stop reacting — called when the board reaches its submitted screen so
952
- // nothing leaks over it (they live on <body> with elevated z-index).
953
- let torndown = false;
954
- function teardown() {
955
- torndown = true;
956
- try {
957
- closePopover();
958
- } catch {
959
- // popover may not be open
960
- }
961
- hidePin();
962
- hideSelBtn();
963
- closeRail();
964
- for (const b of badges) b.remove();
965
- badges = [];
966
- registered = [];
967
- textRoots.clear();
968
- highlightMap.clear();
969
- commentDrafts.clear();
970
- if (dom) {
971
- dom.pin.remove();
972
- dom.selBtn.remove();
973
- dom.pop.remove();
974
- dom.railToggle.remove();
975
- dom.railScrim.remove();
976
- dom.rail.remove();
977
- summaryEls.delete(dom.railList);
978
- dom = null;
979
- }
980
- }
981
-
982
- function register(targetEl, info) {
983
- if (torndown) return;
984
- ensureDom();
985
- targetEl.classList.add('ann-target');
986
- const entry = { el: targetEl, info };
987
- registered.push(entry);
988
- targetEl.addEventListener('mouseenter', () => showPin(entry));
989
- targetEl.addEventListener('mouseleave', scheduleHidePin);
990
- scheduleBadgeRefresh();
991
- }
992
-
993
- function enableTextSelection(rootEl, baseInfo) {
994
- if (torndown) return;
995
- ensureDom();
996
- const blockId = (baseInfo && baseInfo.blockId != null) ? baseInfo.blockId : null;
997
- textRoots.set(blockId, rootEl);
998
- rootEl.addEventListener('mouseup', () => {
999
- if (torndown) return;
1000
- // defer: the selection settles after mouseup
1001
- setTimeout(() => maybeShowSelBtn(rootEl, baseInfo), 0);
1002
- });
1003
- // Re-anchor any saved text comments for this root (reload / prefill path).
1004
- applyHighlightsForRoot(rootEl, blockId);
1005
- }
1006
-
1007
- function openExternal(info, anchorEl) {
1008
- if (torndown) return;
1009
- openPopover(info, anchorEl);
1010
- }
1011
-
1012
- function list() {
1013
- return annotations.slice();
1014
- }
1015
-
1016
- function setList(next) {
1017
- annotations = normalizeList(next);
1018
- resetCounter();
1019
- scheduleBadgeRefresh();
1020
- renderSummaries();
1021
- refreshRailChrome();
1022
- }
1023
-
1024
- // True while the user is mid-comment: the popover is open, which hosts both
1025
- // the "Add a comment" box and every thread's reply input. That text lives
1026
- // only in the DOM until Save, so the board must not reload it away.
1027
- function isComposing() {
1028
- return popOpen;
1029
- }
1030
-
1031
- // Commit a mid-typed comment (the open popover's "Add a comment" box) as a
1032
- // saved annotation, then close it — so freezing the board doesn't throw away
1033
- // text the user was in the middle of writing. ponytail: only the main comment
1034
- // box is flushed, not an in-progress thread reply (the rare case).
1035
- function flushOpen() {
1036
- if (popOpen && popSave) { try { popSave(); } catch { closePopover(); } }
1037
- }
1038
-
1039
- // Freeze/unfreeze comment creation. While disabled, no pin, selection button,
1040
- // or popover appears, so the user can't start feedback that won't be saved.
1041
- function setDisabled(v) {
1042
- disabled = Boolean(v);
1043
- // Also close the rail flushOpen() may have just opened — otherwise it covers
1044
- // the host's top-right "connection lost" notice.
1045
- if (disabled) { closePopover(); hideSelBtn(); hidePin(); closeRail(); }
1046
- }
1047
-
1048
- function renderSummary(target) {
1049
- ensureDom();
1050
- summaryEls.add(target);
1051
- renderSummaryInto(target);
1052
- }
1053
-
1054
- window.RelayAnnotate = { init, register, enableTextSelection, openExternal, list, setList, renderSummary, onBadgeRefresh, teardown, isComposing, flushOpen, setDisabled };
1055
- })();