@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
@@ -0,0 +1,371 @@
1
+ // ---------- image ----------
2
+ let activeRegionMode = null;
3
+ let viewerSpacePan = false;
4
+ const setViewerSpacePan = (enabled) => {
5
+ viewerSpacePan = Boolean(enabled);
6
+ document.body.classList.toggle('blk-space-pan', viewerSpacePan);
7
+ };
8
+ document.addEventListener('keydown', (e) => {
9
+ const tag = e.target && e.target.tagName ? e.target.tagName.toLowerCase() : '';
10
+ if (e.code === 'Space' && !e.repeat && !['input', 'textarea', 'select'].includes(tag)) {
11
+ setViewerSpacePan(true);
12
+ e.preventDefault();
13
+ }
14
+ });
15
+ document.addEventListener('keyup', (e) => {
16
+ if (e.code === 'Space') setViewerSpacePan(false);
17
+ });
18
+ window.addEventListener('blur', () => setViewerSpacePan(false));
19
+
20
+ // src is a remote URL, or absent for embedded local files (served by the
21
+ // board server at /img/b/<id>). Same sizing rule as diagrams: never upscale
22
+ // past natural width; zoom/full-screen viewer attached once loaded.
23
+ function renderImage(block, ctx, blockId) {
24
+ const container = el('div', { class: 'blk-imagewrap' });
25
+ const src = typeof block.src === 'string' && block.src
26
+ ? block.src
27
+ : '/img/b/' + encodeURIComponent(blockId);
28
+ const img = el('img', {
29
+ class: 'blk-img',
30
+ src,
31
+ alt: block.alt || 'image',
32
+ loading: 'lazy',
33
+ draggable: 'false',
34
+ title: ctx.canComment === false ? '' : 'Drag to draw a comment area · Space-drag to pan',
35
+ });
36
+ img.addEventListener('dragstart', (e) => e.preventDefault());
37
+ const stage = el('div', { class: 'blk-imgstage' }, img);
38
+ // Inline default: the image fills its full width (container width, never
39
+ // upscaled past natural) so it's readable without manual zoom; the CONTAINER
40
+ // caps the height (default 800 via CSS, or block.height) and SCROLLS — we
41
+ // never cap the image's own height, which would shrink its width. Full-screen
42
+ // lifts the cap (the .blk-full rule).
43
+ if (block.height != null) container.style.maxHeight = clampHeight(block.height, 800) + 'px';
44
+ img.addEventListener('error', () => {
45
+ container.replaceChildren(el('div', { class: 'blk-error' }, 'Image failed to load'));
46
+ });
47
+ container.append(stage);
48
+ const region = ctx.annotate && ctx.canComment !== false
49
+ ? enableImageRegions({
50
+ host: stage,
51
+ surface: img,
52
+ panHost: container,
53
+ sourceForSide: () => img,
54
+ sideAtPoint: () => null,
55
+ ctx,
56
+ blockId,
57
+ label: block.alt || 'Image',
58
+ })
59
+ : null;
60
+ const attachImgViewer = () =>
61
+ attachViewer(container, {
62
+ zoomEl: stage,
63
+ natural: () => (img.naturalWidth > 0 ? { w: img.naturalWidth, h: img.naturalHeight } : null),
64
+ label: 'image',
65
+ comment: wholeBlockComment(ctx, blockId, 'image'),
66
+ region,
67
+ });
68
+ if (img.complete && img.naturalWidth > 0) attachImgViewer();
69
+ else img.addEventListener('load', attachImgViewer, { once: true });
70
+ if (ctx.annotate && block.pins === true) {
71
+ enableImagePins(stage, img, ctx, blockId, block.alt || 'Image');
72
+ } else if (ctx.annotate) {
73
+ ctx.annotate.register(img, {
74
+ blockId,
75
+ questionId: ctx.questionId,
76
+ target: { kind: 'image', label: block.alt || 'Image' },
77
+ });
78
+ }
79
+ return container;
80
+ }
81
+
82
+ // Coordinate pin-comments on an image (block.pins): click any point to drop a
83
+ // comment anchored to that (x,y) fraction; a numbered pin marks each one and
84
+ // tracks the image as it scales/scrolls (positions are % of the displayed img,
85
+ // so they ride zoom/full-screen/pan for free). Mirrors the chart-badge model.
86
+ function enableImagePins(container, img, ctx, blockId, label) {
87
+ const layer = el('div', { class: 'blk-imgpins' });
88
+ container.append(layer);
89
+ if (ctx.canComment !== false) img.classList.add('blk-img-pinnable');
90
+ let down = null; // {x,y} at pointerdown — used to reject drags (pan) as clicks
91
+ img.addEventListener('pointerdown', (e) => { down = { x: e.clientX, y: e.clientY }; });
92
+ img.addEventListener('click', (e) => {
93
+ if (ctx.canComment === false) return;
94
+ if (img._rlySuppressPointClick) { img._rlySuppressPointClick = false; down = null; return; }
95
+ if (down && (Math.abs(e.clientX - down.x) > 4 || Math.abs(e.clientY - down.y) > 4)) { down = null; return; }
96
+ const r = img.getBoundingClientRect();
97
+ if (!r.width || !r.height) return;
98
+ const x = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
99
+ const y = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height));
100
+ ctx.annotate.openExternal(
101
+ { blockId, questionId: ctx.questionId, target: { kind: 'image-point', x: Math.round(x * 1000) / 1000, y: Math.round(y * 1000) / 1000, label } },
102
+ img
103
+ );
104
+ });
105
+ const syncPins = () => {
106
+ layer.replaceChildren();
107
+ const groups = new Map(); // "x:y" -> {target, count}
108
+ let n = 0;
109
+ for (const a of ctx.annotate.list()) {
110
+ if (a.blockId !== blockId) continue;
111
+ const t = a.target || {};
112
+ if (t.kind !== 'image-point') continue;
113
+ const k = t.x + ':' + t.y;
114
+ const g = groups.get(k) || { target: t, count: 0 };
115
+ g.count++; groups.set(k, g);
116
+ }
117
+ for (const { target, count } of groups.values()) {
118
+ n++;
119
+ const pin = el('button', { class: 'blk-imgpin', type: 'button', title: count + (count === 1 ? ' comment' : ' comments') }, String(count));
120
+ pin.style.left = (target.x * 100) + '%';
121
+ pin.style.top = (target.y * 100) + '%';
122
+ pin.addEventListener('mousedown', (e) => e.stopPropagation());
123
+ pin.addEventListener('click', (e) => {
124
+ e.stopPropagation(); e.preventDefault();
125
+ ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, pin);
126
+ });
127
+ layer.append(pin);
128
+ }
129
+ };
130
+ if (ctx.annotate.onBadgeRefresh) ctx.annotate.onBadgeRefresh(syncPins);
131
+ syncPins();
132
+ }
133
+
134
+ // Hold, then drag, to select a rectangular image area. A short move remains
135
+ // native viewer pan / comparison-slider input; the hold threshold makes the
136
+ // two gestures coexist without a mode switch. Region coordinates are stored
137
+ // as normalized fractions, while a pixel crop is uploaded through the host
138
+ // context so the result gives the agent an actual viewable image artifact.
139
+ function enableImageRegions({ host, surface, panHost, sourceForSide, sideAtPoint, ctx, blockId, label }) {
140
+ const layer = el('div', { class: 'blk-region-layer' });
141
+ const selection = el('div', { class: 'blk-region-selection' });
142
+ layer.append(selection);
143
+ host.append(layer);
144
+ panHost._rlyHasRegions = true;
145
+ panHost.classList.add('blk-has-regions');
146
+ let pending = null;
147
+ let active = false;
148
+ let status = null;
149
+ let modeActive = false;
150
+ const modeHooks = new Set();
151
+ let controller = null;
152
+ const MIN_REGION = 0.012;
153
+
154
+ const localPoint = (e) => {
155
+ const r = host.getBoundingClientRect();
156
+ return {
157
+ x: r.width ? Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)) : 0,
158
+ y: r.height ? Math.max(0, Math.min(1, (e.clientY - r.top) / r.height)) : 0,
159
+ };
160
+ };
161
+ const clearStatus = () => { if (status) status.remove(); status = null; };
162
+ const showStatus = (text) => {
163
+ clearStatus();
164
+ status = el('div', { class: 'blk-region-status', role: 'status' }, text);
165
+ host.append(status);
166
+ };
167
+ const reset = () => {
168
+ active = false;
169
+ pending = null;
170
+ panHost._rlyRegionSelecting = false;
171
+ host.classList.remove('blk-region-arming', 'blk-region-selecting');
172
+ selection.style.display = 'none';
173
+ clearStatus();
174
+ };
175
+ const setModeActive = (next) => {
176
+ const enabled = Boolean(next);
177
+ if (enabled && activeRegionMode && activeRegionMode !== controller) {
178
+ activeRegionMode.setModeActive(false);
179
+ }
180
+ if (!enabled && pending) reset();
181
+ if (modeActive === enabled) return;
182
+ modeActive = enabled;
183
+ panHost._rlyRegionMode = enabled;
184
+ host.classList.toggle('blk-region-mode', enabled);
185
+ activeRegionMode = enabled ? controller : (activeRegionMode === controller ? null : activeRegionMode);
186
+ for (const fn of modeHooks) { try { fn(enabled); } catch (_) {} }
187
+ };
188
+ controller = {
189
+ setModeActive,
190
+ isModeActive: () => modeActive,
191
+ onModeChange: (fn) => {
192
+ if (typeof fn === 'function') modeHooks.add(fn);
193
+ return () => modeHooks.delete(fn);
194
+ },
195
+ };
196
+ document.addEventListener('keydown', (e) => {
197
+ if (e.key === 'Escape' && modeActive) setModeActive(false);
198
+ });
199
+ const draw = (a, b) => {
200
+ const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
201
+ const w = Math.abs(a.x - b.x), h = Math.abs(a.y - b.y);
202
+ selection.style.left = (x * 100) + '%';
203
+ selection.style.top = (y * 100) + '%';
204
+ selection.style.width = (w * 100) + '%';
205
+ selection.style.height = (h * 100) + '%';
206
+ return { x, y, w, h };
207
+ };
208
+ const createRegionZone = (target, count, provisional = false) => {
209
+ const badge = el('span', { class: 'blk-imgregion-badge', 'aria-hidden': 'true' });
210
+ badge.innerHTML = ICON_COMMENT;
211
+ badge.append(el('span', { class: 'blk-imgregion-count' }, String(count)));
212
+ const sideLabel = target.side ? target.side + ' ' : '';
213
+ const region = el('button', {
214
+ class: 'blk-imgregion' + (provisional ? ' blk-imgregion-provisional' : ''),
215
+ type: 'button',
216
+ title: provisional
217
+ ? `Add a comment to this ${sideLabel}area`
218
+ : `${target.side ? target.side + ' · ' : ''}${count} ${count === 1 ? 'comment' : 'comments'}`,
219
+ 'aria-label': provisional
220
+ ? `New ${sideLabel}image area comment`
221
+ : `${sideLabel}image area with ${count} ${count === 1 ? 'comment' : 'comments'}`,
222
+ }, badge);
223
+ region.style.left = (target.x * 100) + '%';
224
+ region.style.top = (target.y * 100) + '%';
225
+ region.style.width = (target.w * 100) + '%';
226
+ region.style.height = (target.h * 100) + '%';
227
+ region.addEventListener('pointerdown', (e) => e.stopPropagation());
228
+ if (!provisional) {
229
+ region.addEventListener('click', (e) => {
230
+ e.stopPropagation();
231
+ ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, region);
232
+ });
233
+ }
234
+ return region;
235
+ };
236
+ const beginSelection = (pointerId) => {
237
+ if (!pending || active) return;
238
+ active = true;
239
+ panHost._rlyRegionSelecting = true;
240
+ host.classList.remove('blk-region-arming');
241
+ host.classList.add('blk-region-selecting');
242
+ selection.style.display = 'block';
243
+ draw(pending.start, pending.start);
244
+ showStatus((pending.side ? pending.side.charAt(0).toUpperCase() + pending.side.slice(1) + ' · ' : '') + 'drag to select an area');
245
+ try { surface.setPointerCapture(pointerId); } catch (_) {}
246
+ };
247
+
248
+ async function cropRegion(img, region) {
249
+ if (!img || !img.naturalWidth || !img.naturalHeight) throw new Error('image is not ready');
250
+ const sx = Math.max(0, Math.floor(region.x * img.naturalWidth));
251
+ const sy = Math.max(0, Math.floor(region.y * img.naturalHeight));
252
+ const sw = Math.max(1, Math.min(img.naturalWidth - sx, Math.round(region.w * img.naturalWidth)));
253
+ const sh = Math.max(1, Math.min(img.naturalHeight - sy, Math.round(region.h * img.naturalHeight)));
254
+ const scale = Math.min(1, 1400 / sw, 1400 / sh);
255
+ const width = Math.max(1, Math.round(sw * scale));
256
+ const height = Math.max(1, Math.round(sh * scale));
257
+ const canvas = document.createElement('canvas');
258
+ canvas.width = width;
259
+ canvas.height = height;
260
+ const g = canvas.getContext('2d');
261
+ if (!g) throw new Error('canvas unavailable');
262
+ g.drawImage(img, sx, sy, sw, sh, 0, 0, width, height);
263
+ const dataUrl = canvas.toDataURL('image/png');
264
+ if (!/^data:image\/png;base64,/.test(dataUrl)) throw new Error('crop unavailable');
265
+ if (ctx.saveArtifact) return ctx.saveArtifact({ dataUrl, mime: 'image/png', width, height, blockId });
266
+ return { data: dataUrl.slice(dataUrl.indexOf(',') + 1), mime: 'image/png', width, height };
267
+ }
268
+
269
+ const finishRegion = async (region, side) => {
270
+ const target = {
271
+ kind: 'image-region',
272
+ x: Math.round(region.x * 10000) / 10000,
273
+ y: Math.round(region.y * 10000) / 10000,
274
+ w: Math.round(region.w * 10000) / 10000,
275
+ h: Math.round(region.h * 10000) / 10000,
276
+ side: side || undefined,
277
+ label,
278
+ };
279
+ const provisional = createRegionZone(target, 0, true);
280
+ layer.append(provisional);
281
+ showStatus('Saving selected area…');
282
+ try {
283
+ target.crop = await cropRegion(sourceForSide(side), region);
284
+ } catch {
285
+ target.cropUnavailable = true;
286
+ }
287
+ clearStatus();
288
+ ctx.annotate.openExternal({
289
+ blockId,
290
+ questionId: ctx.questionId,
291
+ target,
292
+ onClose: () => provisional.remove(),
293
+ }, provisional);
294
+ };
295
+
296
+ surface.addEventListener('pointerdown', (e) => {
297
+ if (e.button !== 0 || viewerSpacePan || ctx.canComment === false) return;
298
+ if (e.target.closest && e.target.closest('.cmp-handle, .blk-imgregion, .blk-tools')) return;
299
+ if (modeActive) {
300
+ e.preventDefault();
301
+ e.stopPropagation();
302
+ }
303
+ const p = localPoint(e);
304
+ pending = {
305
+ start: p,
306
+ last: p,
307
+ clientX: e.clientX,
308
+ clientY: e.clientY,
309
+ pointerId: e.pointerId,
310
+ explicitMode: modeActive,
311
+ side: sideAtPoint(p.x),
312
+ };
313
+ host.classList.add('blk-region-arming');
314
+ if (modeActive) beginSelection(e.pointerId);
315
+ });
316
+ surface.addEventListener('pointermove', (e) => {
317
+ if (!pending) return;
318
+ const moved = Math.hypot(e.clientX - pending.clientX, e.clientY - pending.clientY);
319
+ if (!active && moved > 5) beginSelection(pending.pointerId);
320
+ if (!active) {
321
+ return;
322
+ }
323
+ e.preventDefault();
324
+ e.stopPropagation();
325
+ pending.last = localPoint(e);
326
+ draw(pending.start, pending.last);
327
+ });
328
+ const end = (e) => {
329
+ if (!pending) return;
330
+ if (!active) { reset(); return; }
331
+ e.preventDefault();
332
+ const region = draw(pending.start, pending.last || localPoint(e));
333
+ const side = pending.side;
334
+ const explicitMode = pending.explicitMode;
335
+ surface._rlySuppressPointClick = true;
336
+ reset();
337
+ clearStatus();
338
+ if (region.w >= MIN_REGION && region.h >= MIN_REGION) {
339
+ if (explicitMode) setModeActive(false);
340
+ finishRegion(region, side);
341
+ } else if (explicitMode) {
342
+ showStatus('Drag a larger area');
343
+ setTimeout(clearStatus, 1200);
344
+ }
345
+ };
346
+ surface.addEventListener('pointerup', end);
347
+ // Some Chromium/CDP paths emit pointercancel immediately after granting
348
+ // capture on the first dragged frame. Once area mode is active, keep the
349
+ // last drawn rectangle instead of throwing the user's deliberate hold away.
350
+ surface.addEventListener('pointercancel', (e) => active ? end(e) : reset());
351
+
352
+ const syncRegions = () => {
353
+ for (const node of Array.from(layer.querySelectorAll('.blk-imgregion:not(.blk-imgregion-provisional)'))) node.remove();
354
+ const groups = new Map();
355
+ for (const a of ctx.annotate.list()) {
356
+ if (a.blockId !== blockId || !a.target || a.target.kind !== 'image-region') continue;
357
+ const t = a.target;
358
+ const key = [t.side || '', t.x, t.y, t.w, t.h].join(':');
359
+ const group = groups.get(key) || { target: t, count: 0 };
360
+ group.count++;
361
+ groups.set(key, group);
362
+ }
363
+ for (const { target, count } of groups.values()) {
364
+ layer.append(createRegionZone(target, count));
365
+ }
366
+ };
367
+ if (ctx.annotate.onBadgeRefresh) ctx.annotate.onBadgeRefresh(syncRegions);
368
+ syncRegions();
369
+ return controller;
370
+ }
371
+
@@ -0,0 +1,26 @@
1
+ // ---------- kpi (stat cards) ----------
2
+ function renderKpi(block, ctx, blockId) {
3
+ const wrap = el('div', { class: 'blk-kpi' });
4
+ if (block.title) wrap.append(el('div', { class: 'kpi-title' }, block.title));
5
+ const grid = el('div', { class: 'kpi-grid' });
6
+ for (const it of block.items || []) {
7
+ const card = el('div', { class: 'kpi-card' });
8
+ if (it.label) card.append(el('div', { class: 'kpi-label' }, it.label));
9
+ card.append(el('div', { class: 'kpi-value' }, it.value || ''));
10
+ if (it.delta) {
11
+ const glyph = it.dir === 'up' ? '▲ ' : it.dir === 'down' ? '▼ ' : it.dir === 'flat' ? '▬ ' : '';
12
+ card.append(el('div', { class: 'kpi-delta' + (it.dir ? ' kpi-' + it.dir : '') }, glyph + it.delta));
13
+ }
14
+ if (it.sub) card.append(el('div', { class: 'kpi-sub' }, it.sub));
15
+ if (ctx.annotate) {
16
+ ctx.annotate.register(card, {
17
+ blockId, questionId: ctx.questionId,
18
+ target: { kind: 'html-element', label: ((it.label ? it.label + ' · ' : '') + (it.value || 'KPI')) },
19
+ });
20
+ }
21
+ grid.append(card);
22
+ }
23
+ wrap.append(grid);
24
+ return wrap;
25
+ }
26
+
@@ -0,0 +1,223 @@
1
+ // ---------- markdown mini renderer (NO library) ----------
2
+ // Escape FIRST, then apply transforms on the already-escaped text. Because
3
+ // <, >, & are gone, our generated tags are the only real tags in the output.
4
+ function mdInline(escaped) {
5
+ // Stash code/link/file-link HTML behind \0-delimited placeholders so the
6
+ // later path-autolink and bold/italic passes can't re-tokenize inside them.
7
+ // \0 never appears in real text, so the placeholders can't collide with it.
8
+ const stash = [];
9
+ const keep = (html) => '\0' + (stash.push(html) - 1) + '\0';
10
+
11
+ let s = escaped;
12
+ // inline code first so its contents aren't treated as bold/italic/links —
13
+ // a backtick span that is ITSELF a lone path opens instead of just showing.
14
+ s = s.replace(/`([^`]+)`/g, (_m, c) =>
15
+ looksLikeLocalPath(c) ? keep(fileLinkHtml(c.trim(), c, true)) : keep(`<code>${c}</code>`)
16
+ );
17
+ // reference links [label](#ref:name) / [label](#block:id) open the named/identified
18
+ // block in a full-screen modal — so a question can point back to a chart/image
19
+ // shown earlier without the user scrolling up. Runs before the generic link
20
+ // pass so the #ref:/#block: target isn't rendered as a plain href.
21
+ s = s.replace(/\[([^\]]+)\]\(#(ref|block):([^)\s]+)\)/g, (_m, label, kind, target) =>
22
+ keep(`<a class="rly-reflink" role="button" tabindex="0" data-rly-${kind === 'block' ? 'refid' : 'ref'}="${target}" title="Open this visual">` +
23
+ `<span class="rly-reflink-ico" aria-hidden="true"></span><span>${label}</span></a>`));
24
+ // images ![alt](src) BEFORE links so the leading "!" isn't stranded as text.
25
+ // A remote/data image embeds inline; a local path stays a click-to-open link
26
+ // (the board server doesn't serve the source file's directory).
27
+ // ponytail: remote/data images embed; local-relative images open in the app
28
+ // rather than render — add directory serving only if users need inline locals.
29
+ s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_m, alt, url) => {
30
+ if (/^(https?:|data:image\/)/i.test(url)) return keep(`<img class="md-img" src="${url}" alt="${alt}" loading="lazy">`);
31
+ if (looksLikeLocalPath(url)) return keep(fileLinkHtml(url, alt || url, false));
32
+ return `![${alt}](${url})`; // unknown scheme — leave literal, don't link
33
+ });
34
+ // links [text](url) — url is already escaped; a local-path target becomes a
35
+ // click-to-open link, otherwise a normal link (guarding odd schemes).
36
+ s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_m, text, url) => {
37
+ if (looksLikeLocalPath(url)) return keep(fileLinkHtml(url, text, false));
38
+ const safe = /^(https?:|mailto:|\/|#|\.)/i.test(url) ? url : '#';
39
+ return keep(`<a href="${safe}" target="_blank" rel="noopener">${text}</a>`);
40
+ });
41
+ // bare paths in running text (the common case: the agent just typed a path)
42
+ s = s.replace(FILE_PATH_RE, (m) => (looksLikeLocalPath(m) ? keep(fileLinkHtml(m, m, false)) : m));
43
+ // bold then italic (bold uses ** so must run before single *)
44
+ s = s.replace(/\*\*([^*]+)\*\*/g, (_m, c) => `<strong>${c}</strong>`);
45
+ s = s.replace(/\*([^*]+)\*/g, (_m, c) => `<em>${c}</em>`);
46
+ // underscore emphasis __bold__ / _italic_, only at word boundaries so
47
+ // snake_case and RLY_BOARD_ID are left alone (CommonMark intraword rule).
48
+ s = s.replace(/(^|[^A-Za-z0-9_])__([^_]+)__(?![A-Za-z0-9_])/g, (_m, p, c) => `${p}<strong>${c}</strong>`);
49
+ s = s.replace(/(^|[^A-Za-z0-9_])_([^_]+)_(?![A-Za-z0-9_])/g, (_m, p, c) => `${p}<em>${c}</em>`);
50
+ // restore the stashed HTML — loop so a placeholder nested inside another
51
+ // stashed fragment (e.g. a code span inside a link's text) is also resolved.
52
+ let guard = 0;
53
+ while (s.indexOf('\0') !== -1 && guard++ < 6) {
54
+ s = s.replace(/\0(\d+)\0/g, (_m, i) => (stash[Number(i)] !== undefined ? stash[Number(i)] : ''));
55
+ }
56
+ return s;
57
+ }
58
+
59
+ function renderMarkdown(md) {
60
+ const root = el('div', { class: 'md' });
61
+ const lines = String(md).replace(/\r\n?/g, '\n').split('\n');
62
+ let html = '';
63
+ let i = 0;
64
+
65
+ // list-stack rendering supports one nesting level (indent >= 2 spaces)
66
+ function consumeList() {
67
+ const blocks = []; // {ordered, items:[{html, sub:[...]}]}
68
+ let cur = null;
69
+ while (i < lines.length) {
70
+ const line = lines[i];
71
+ const m = line.match(/^(\s*)([-*]|\d+\.)\s+(.*)$/);
72
+ if (!m) break;
73
+ const indent = m[1].length;
74
+ const ordered = /\d+\./.test(m[2]);
75
+ const content = mdInline(esc(m[3]));
76
+ if (indent >= 2 && cur && cur.items.length) {
77
+ // nested under the previous top-level item
78
+ const parent = cur.items[cur.items.length - 1];
79
+ if (!parent.sub) parent.sub = { ordered, items: [] };
80
+ parent.sub.items.push(content);
81
+ } else {
82
+ if (!cur || cur.ordered !== ordered) {
83
+ cur = { ordered, items: [] };
84
+ blocks.push(cur);
85
+ }
86
+ cur.items.push({ html: content, sub: null });
87
+ }
88
+ i++;
89
+ }
90
+ let out = '';
91
+ for (const b of blocks) {
92
+ const tag = b.ordered ? 'ol' : 'ul';
93
+ out += `<${tag}>`;
94
+ for (const it of b.items) {
95
+ out += `<li>${it.html}`;
96
+ if (it.sub) {
97
+ const st = it.sub.ordered ? 'ol' : 'ul';
98
+ out += `<${st}>` + it.sub.items.map((x) => `<li>${x}</li>`).join('') + `</${st}>`;
99
+ }
100
+ out += '</li>';
101
+ }
102
+ out += `</${tag}>`;
103
+ }
104
+ return out;
105
+ }
106
+
107
+ // GFM pipe tables — a header row of "| a | b |" cells immediately followed
108
+ // by a separator row of dashes (with optional ":" alignment markers).
109
+ // Rendered as a real .blk-table so it matches the dedicated table block.
110
+ function splitRow(row) {
111
+ const trimmed = row.trim().replace(/^\|/, '').replace(/\|$/, '');
112
+ return trimmed.split(/(?<!\\)\|/).map((c) => c.replace(/\\\|/g, '|').trim());
113
+ }
114
+ function isSepRow(row) {
115
+ if (!row || row.indexOf('|') === -1) return false;
116
+ const cells = splitRow(row);
117
+ return cells.length > 0 && cells.every((c) => /^:?-{1,}:?$/.test(c));
118
+ }
119
+ function isTableStart(idx) {
120
+ const head = lines[idx];
121
+ return (
122
+ idx + 1 < lines.length &&
123
+ head.indexOf('|') !== -1 &&
124
+ !isSepRow(head) &&
125
+ isSepRow(lines[idx + 1])
126
+ );
127
+ }
128
+ function consumeTable() {
129
+ const headers = splitRow(lines[i]);
130
+ const aligns = splitRow(lines[i + 1]).map((c) => {
131
+ const left = c.startsWith(':');
132
+ const right = c.endsWith(':');
133
+ return left && right ? 'center' : right ? 'right' : left ? 'left' : '';
134
+ });
135
+ i += 2;
136
+ const body = [];
137
+ while (i < lines.length && !/^\s*$/.test(lines[i]) && lines[i].indexOf('|') !== -1 && !isSepRow(lines[i])) {
138
+ body.push(splitRow(lines[i]));
139
+ i++;
140
+ }
141
+ const ncols = headers.length;
142
+ const alignAttr = (ci) => (aligns[ci] ? ` style="text-align:${aligns[ci]}"` : '');
143
+ const cell = (tag, ci, text) => `<${tag}${alignAttr(ci)}>${mdInline(esc(text == null ? '' : text))}</${tag}>`;
144
+ let out = '<div class="md-tablewrap"><table class="blk-table md-table"><thead><tr>';
145
+ for (let c = 0; c < ncols; c++) out += cell('th', c, headers[c]);
146
+ out += '</tr></thead><tbody>';
147
+ for (const r of body) {
148
+ out += '<tr>';
149
+ for (let c = 0; c < ncols; c++) out += cell('td', c, r[c]);
150
+ out += '</tr>';
151
+ }
152
+ out += '</tbody></table></div>';
153
+ return out;
154
+ }
155
+
156
+ while (i < lines.length) {
157
+ const line = lines[i];
158
+
159
+ // fenced code block ```lang
160
+ const fence = line.match(/^```\s*([\w+-]*)\s*$/);
161
+ if (fence) {
162
+ i++;
163
+ const buf = [];
164
+ while (i < lines.length && !/^```\s*$/.test(lines[i])) buf.push(lines[i++]);
165
+ if (i < lines.length) i++; // closing fence
166
+ html += `<pre class="md-pre"><code>${esc(buf.join('\n'))}</code></pre>`;
167
+ continue;
168
+ }
169
+
170
+ // horizontal rule
171
+ if (/^\s*---+\s*$/.test(line)) { html += '<hr>'; i++; continue; }
172
+
173
+ // headings
174
+ const h = line.match(/^(#{1,3})\s+(.*)$/);
175
+ if (h) {
176
+ const lvl = h[1].length;
177
+ html += `<h${lvl}>${mdInline(esc(h[2]))}</h${lvl}>`;
178
+ i++;
179
+ continue;
180
+ }
181
+
182
+ // blockquote (collapse consecutive > lines)
183
+ if (/^\s*>\s?/.test(line)) {
184
+ const buf = [];
185
+ while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
186
+ buf.push(lines[i].replace(/^\s*>\s?/, ''));
187
+ i++;
188
+ }
189
+ html += `<blockquote>${mdInline(esc(buf.join(' ')))}</blockquote>`;
190
+ continue;
191
+ }
192
+
193
+ // GFM pipe table (header row + dash separator)
194
+ if (isTableStart(i)) { html += consumeTable(); continue; }
195
+
196
+ // lists
197
+ if (/^(\s*)([-*]|\d+\.)\s+/.test(line)) { html += consumeList(); continue; }
198
+
199
+ // blank line
200
+ if (/^\s*$/.test(line)) { i++; continue; }
201
+
202
+ // paragraph — accumulate until blank / block boundary
203
+ const buf = [];
204
+ while (
205
+ i < lines.length &&
206
+ !/^\s*$/.test(lines[i]) &&
207
+ !/^```/.test(lines[i]) &&
208
+ !/^\s*---+\s*$/.test(lines[i]) &&
209
+ !/^#{1,3}\s+/.test(lines[i]) &&
210
+ !/^\s*>\s?/.test(lines[i]) &&
211
+ !/^(\s*)([-*]|\d+\.)\s+/.test(lines[i]) &&
212
+ !isTableStart(i)
213
+ ) {
214
+ buf.push(lines[i]);
215
+ i++;
216
+ }
217
+ html += `<p>${mdInline(esc(buf.join('\n'))).replace(/\n/g, '<br>')}</p>`;
218
+ }
219
+
220
+ root.innerHTML = html;
221
+ return root;
222
+ }
223
+