@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,206 @@
1
+ // ---------- popover ----------
2
+ function positionPopover() {
3
+ popPositionFrame = 0;
4
+ if (!popOpen || !dom || !popAnchorEl || !popAnchorEl.isConnected) return;
5
+ const pop = dom.pop;
6
+ const rect = popAnchorEl.getBoundingClientRect();
7
+ const pw = pop.offsetWidth;
8
+ const ph = pop.offsetHeight;
9
+ const left = Math.max(8, Math.min(rect.left, window.innerWidth - pw - 8));
10
+ let top = rect.bottom + 8;
11
+ if (top + ph > window.innerHeight - 8 && rect.top - ph - 8 >= 8) top = rect.top - ph - 8;
12
+ top = Math.max(8, Math.min(top, window.innerHeight - ph - 8));
13
+ pop.style.left = left + 'px';
14
+ pop.style.top = top + 'px';
15
+ }
16
+
17
+ function schedulePositionPopover() {
18
+ if (!popOpen || popPositionFrame) return;
19
+ popPositionFrame = requestAnimationFrame(positionPopover);
20
+ }
21
+
22
+ function closePopover(reason = 'dismissed') {
23
+ if (!popOpen) return;
24
+ const closeHook = popCloseHook;
25
+ popOpen = false;
26
+ popSave = null;
27
+ popCloseHook = null;
28
+ popAnchorEl = null;
29
+ if (popPositionFrame) cancelAnimationFrame(popPositionFrame);
30
+ popPositionFrame = 0;
31
+ dom.pop.style.display = 'none';
32
+ dom.pop.replaceChildren();
33
+ if (closeHook) {
34
+ try { closeHook(reason); } catch (_) { /* lifecycle hooks are best-effort */ }
35
+ }
36
+ }
37
+
38
+ // ---------- delete a comment (with confirm) ----------
39
+ // The × that used to delete a comment read as "close the popup". Delete is now
40
+ // a distinct trash button that opens a confirm modal; "Don't ask again"
41
+ // (default OFF) suppresses future confirms for the session (persisted best-effort).
42
+ const ICON_TRASH =
43
+ '<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">' +
44
+ '<path d="M2.5 4h11M6 4V2.5h4V4M5 4l.5 9h5l.5-9"/></svg>';
45
+ const ICON_PENCIL =
46
+ '<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">' +
47
+ '<path d="M11.5 2.5l2 2L6 12l-2.5.5.5-2.5 7.5-7.5z"/></svg>';
48
+ const DEL_SKIP_KEY = 'relay-ann-del-skip';
49
+ let delConfirmSkip = false;
50
+ try { delConfirmSkip = localStorage.getItem(DEL_SKIP_KEY) === '1'; } catch { /* sandbox: no storage */ }
51
+
52
+ function requestDelete(id, after) {
53
+ if (!permissions.delete) return;
54
+ const done = () => { removeAnnotation(id); if (after) after(); };
55
+ if (delConfirmSkip) { done(); return; }
56
+ showDeleteConfirm(done);
57
+ }
58
+ function showDeleteConfirm(onConfirm) {
59
+ const scrim = el('div', { class: 'ann-confirm-scrim' });
60
+ const skip = el('input', { type: 'checkbox' });
61
+ const cancel = el('button', { class: 'ann-confirm-cancel', type: 'button' }, 'Cancel');
62
+ const del = el('button', { class: 'ann-confirm-del', type: 'button' }, 'Delete');
63
+ const close = () => { scrim.remove(); document.removeEventListener('keydown', onKey, true); };
64
+ const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); close(); } };
65
+ cancel.addEventListener('click', close);
66
+ scrim.addEventListener('mousedown', (e) => { if (e.target === scrim) close(); });
67
+ del.addEventListener('click', () => {
68
+ if (skip.checked) { delConfirmSkip = true; try { localStorage.setItem(DEL_SKIP_KEY, '1'); } catch { /* sandbox */ } }
69
+ close();
70
+ onConfirm();
71
+ });
72
+ scrim.append(el('div', { class: 'ann-confirm', role: 'alertdialog', 'aria-label': 'Delete comment' },
73
+ el('div', { class: 'ann-confirm-title' }, 'Delete this comment?'),
74
+ el('div', { class: 'ann-confirm-msg' }, 'This removes the comment and its replies. It can’t be undone.'),
75
+ el('label', { class: 'ann-confirm-skip' }, skip, el('span', {}, 'Don’t ask again')),
76
+ el('div', { class: 'ann-confirm-actions' }, cancel, del)
77
+ ));
78
+ document.body.append(scrim);
79
+ document.addEventListener('keydown', onKey, true);
80
+ setTimeout(() => { try { cancel.focus(); } catch { /* ignore */ } }, 0);
81
+ }
82
+
83
+ function openPopover(info, anchorEl) {
84
+ if (disabled) return;
85
+ ensureDom();
86
+ const hasExisting = matching(info).length > 0;
87
+ const draftKey = sigOf(info.blockId, info.target);
88
+ // Read-only viewers can open existing threads from their badges, but a
89
+ // target with no feedback has nothing to show and must not expose an empty
90
+ // add-comment dialog.
91
+ if (!permissions.add && !hasExisting) return;
92
+ closePopover();
93
+ popCloseHook = typeof info.onClose === 'function' ? info.onClose : null;
94
+ hidePin();
95
+ const pop = dom.pop;
96
+ // Header: target label + an explicit CLOSE button, so × always means "close".
97
+ const popClose = el('button', { class: 'ann-pop-close', type: 'button', title: 'Close', 'aria-label': 'Close' }, '×');
98
+ popClose.addEventListener('click', () => closePopover('dismissed'));
99
+ pop.replaceChildren(el('div', { class: 'ann-pop-head' }, el('div', { class: 'ann-pop-label' }, humanize(info.target)), popClose));
100
+
101
+ // Existing comments on this exact target, rendered as threads: author
102
+ // chip + time + delete, the comment text, its replies indented below,
103
+ // and a compact reply input per thread. Deleting a comment deletes its
104
+ // whole thread.
105
+ const existingWrap = el('div', { class: 'ann-pop-existing' });
106
+ const renderExisting = () => {
107
+ existingWrap.replaceChildren();
108
+ for (const a of matching(info)) {
109
+ const del = el('button', { class: 'ann-del', type: 'button', title: 'Delete comment', 'aria-label': 'Delete comment' });
110
+ del.innerHTML = ICON_TRASH;
111
+ del.addEventListener('click', () => requestDelete(a.id, renderExisting));
112
+ const edit = el('button', { class: 'ann-edit', type: 'button', title: 'Edit comment', 'aria-label': 'Edit comment' });
113
+ edit.innerHTML = ICON_PENCIL;
114
+ const textEl = el('div', { class: 'ann-pop-text' }, a.text);
115
+ // Inline edit: swap the text for a textarea + Save/Cancel; Save commits
116
+ // via editAnnotation, then re-renders. Only the user's own comment is editable.
117
+ edit.addEventListener('click', () => {
118
+ const ta = el('textarea', { class: 'ann-ta ann-edit-ta', rows: '3' });
119
+ ta.value = a.text;
120
+ const save = el('button', { class: 'ann-save', type: 'button' }, 'Save');
121
+ const cancel = el('button', { class: 'ann-cancel', type: 'button' }, 'Cancel');
122
+ save.addEventListener('click', () => { editAnnotation(a.id, ta.value); renderExisting(); });
123
+ cancel.addEventListener('click', renderExisting);
124
+ ta.addEventListener('keydown', (e) => {
125
+ if (e.key === 'Escape') { e.stopPropagation(); renderExisting(); }
126
+ else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); editAnnotation(a.id, ta.value); renderExisting(); }
127
+ });
128
+ textEl.replaceWith(el('div', { class: 'ann-edit-form' }, ta, el('div', { class: 'ann-pop-actions' }, save, cancel)));
129
+ ta.focus();
130
+ });
131
+ // agent replies aren't editable here — only the top-level user comment
132
+ const actions = el('div', { class: 'ann-thread-actions' },
133
+ permissions.edit && a.author === 'user' ? edit : null,
134
+ permissions.delete ? del : null
135
+ );
136
+ const thread = el('div', { class: 'ann-thread' },
137
+ el('div', { class: 'ann-thread-head' }, chip(a.author), timeEl(a.createdAt), actions),
138
+ textEl
139
+ );
140
+ if (Array.isArray(a.replies) && a.replies.length) {
141
+ const list = el('div', { class: 'ann-replies' });
142
+ for (const r of a.replies) {
143
+ list.append(el('div', { class: 'ann-reply' },
144
+ el('div', { class: 'ann-reply-head' }, chip(r.author), timeEl(r.createdAt)),
145
+ el('div', { class: 'ann-reply-text' }, r.text)
146
+ ));
147
+ }
148
+ thread.append(list);
149
+ }
150
+ const input = el('input', { class: 'ann-reply-input', type: 'text', placeholder: 'Reply…', 'aria-label': 'Reply' });
151
+ const btn = el('button', { class: 'ann-reply-btn', type: 'button' }, 'Reply');
152
+ const submitReply = () => {
153
+ const text = input.value.trim();
154
+ if (!text) return;
155
+ addReply(a.id, text);
156
+ renderExisting();
157
+ };
158
+ btn.addEventListener('click', submitReply);
159
+ input.addEventListener('keydown', (e) => {
160
+ if (e.key === 'Enter' && !e.metaKey && !e.ctrlKey) {
161
+ e.preventDefault();
162
+ submitReply();
163
+ }
164
+ });
165
+ if (permissions.reply) thread.append(el('div', { class: 'ann-reply-form' }, input, btn));
166
+ existingWrap.append(thread);
167
+ }
168
+ };
169
+ renderExisting();
170
+ pop.append(existingWrap);
171
+
172
+ const ta = el('textarea', { class: 'ann-ta', placeholder: 'Add a comment…', rows: '3' });
173
+ ta.value = commentDrafts.get(draftKey) || '';
174
+ ta.addEventListener('input', () => {
175
+ if (ta.value) commentDrafts.set(draftKey, ta.value);
176
+ else commentDrafts.delete(draftKey);
177
+ });
178
+ const save = el('button', { class: 'ann-save', type: 'button' }, 'Save');
179
+ const cancel = el('button', { class: 'ann-cancel', type: 'button' }, 'Cancel');
180
+ popSave = () => {
181
+ const text = ta.value.trim();
182
+ if (text) addAnnotation(info, text);
183
+ commentDrafts.delete(draftKey);
184
+ if (text) closePopover('saved');
185
+ else closePopover('empty');
186
+ };
187
+ save.addEventListener('click', () => popSave && popSave());
188
+ cancel.addEventListener('click', () => {
189
+ commentDrafts.delete(draftKey);
190
+ closePopover('cancelled');
191
+ });
192
+ if (permissions.add) pop.append(ta, el('div', { class: 'ann-pop-actions' }, save, cancel));
193
+
194
+ // Position: prefer below the anchor, flip above when out of room, and clamp
195
+ // to the viewport. Scroll/resize re-run this through one animation frame so
196
+ // the composer tracks browser scrolling smoothly without losing its draft.
197
+ pop.style.display = 'block';
198
+ pop.style.visibility = 'hidden';
199
+ popOpen = true;
200
+ popAnchorEl = anchorEl;
201
+ positionPopover();
202
+ pop.style.visibility = '';
203
+ if (permissions.add) ta.focus();
204
+ else popClose.focus();
205
+ }
206
+
@@ -0,0 +1,67 @@
1
+ // ---------- summary ----------
2
+ function renderSummaries() {
3
+ for (const t of summaryEls) {
4
+ if (!t.isConnected) {
5
+ summaryEls.delete(t);
6
+ continue;
7
+ }
8
+ renderSummaryInto(t);
9
+ }
10
+ }
11
+
12
+ function renderSummaryInto(target) {
13
+ const isRail = target.classList.contains('ann-rail-list');
14
+ target.classList.add('ann-summary');
15
+ target.replaceChildren();
16
+ if (!annotations.length) {
17
+ target.style.display = 'none';
18
+ return;
19
+ }
20
+ target.style.display = '';
21
+ // The rail has its own header chrome; standalone summaries get a heading.
22
+ if (!isRail) target.append(el('h3', { class: 'ann-sum-head' }, `Comments (${annotations.length})`));
23
+ for (const a of annotations) {
24
+ const del = el('button', { class: 'ann-del', type: 'button', title: 'Delete comment', 'aria-label': 'Delete comment' });
25
+ del.innerHTML = ICON_TRASH;
26
+ del.addEventListener('click', (e) => { e.stopPropagation(); requestDelete(a.id); });
27
+ // Thread meta: reply count, plus an "agent" chip when the latest entry
28
+ // in the thread (last reply, or the comment itself) is agent-authored.
29
+ const replyCount = Array.isArray(a.replies) ? a.replies.length : 0;
30
+ const latest = replyCount ? a.replies[replyCount - 1] : a;
31
+ const meta = [];
32
+ if (replyCount) meta.push(el('span', { class: 'ann-sum-replies' }, `${replyCount} ${replyCount === 1 ? 'reply' : 'replies'}`));
33
+ if (latest.author === 'agent') meta.push(chip('agent'));
34
+ const row = el('div', { class: 'ann-sum-row' },
35
+ el('div', { class: 'ann-sum-main' },
36
+ el('div', { class: 'ann-sum-target' }, humanize(a.target)),
37
+ el('div', { class: 'ann-sum-text' }, a.text),
38
+ meta.length ? el('div', { class: 'ann-sum-meta' }, meta) : null
39
+ ),
40
+ permissions.delete ? del : null
41
+ );
42
+ // Clicking a row jumps to (and flashes) the matching element: a
43
+ // registered block element, or the inline highlight for a text comment.
44
+ row.addEventListener('click', () => {
45
+ const entry = registered.find(
46
+ (r) => r.el.isConnected && sameBlock(r.info.blockId, a.blockId) && sameTarget(r.info.target, a.target)
47
+ );
48
+ let jump = entry ? entry.el : null;
49
+ if (!jump && a.target && a.target.kind === 'text') {
50
+ const marks = highlightMap.get(sigOf(a.blockId, a.target));
51
+ jump = marks && marks.find((m) => m.isConnected);
52
+ }
53
+ // Fallback for targets with no registered element (e.g. chart data
54
+ // points / whole-block comments): flash the whole block container.
55
+ if (!jump && a.blockId != null) {
56
+ jump = document.querySelector('[data-block-id="' + String(a.blockId).replace(/"/g, '\\"') + '"]');
57
+ }
58
+ if (!jump) return;
59
+ // On narrow screens the rail overlays the page — close it so the
60
+ // flashed target is actually visible.
61
+ if (isRail && window.matchMedia('(max-width: 1179px)').matches) closeRail();
62
+ flashEl(jump);
63
+ });
64
+ target.append(row);
65
+ }
66
+ }
67
+
@@ -0,0 +1,88 @@
1
+ // ---------- annotations ----------
2
+ // RelayAnnotate owns the live annotation list; mirror it into state on every
3
+ // change so payload()/autosave/submit carry it exactly like answers.
4
+ const Annotate = typeof window.RelayAnnotate !== 'undefined' ? window.RelayAnnotate : null;
5
+ if (Annotate && responseRequired) {
6
+ Annotate.init({
7
+ initial: state.annotations,
8
+ permissions: {
9
+ add: access.canComment !== false,
10
+ edit: access.canEditComments !== false,
11
+ delete: access.canDeleteComments !== false,
12
+ reply: access.canComment !== false,
13
+ },
14
+ onChange: (list) => {
15
+ state.annotations = list;
16
+ scheduleSave();
17
+ // Refresh per-element comment badges inside custom-HTML iframes (bridge
18
+ // sets this once the iframe annotate plumbing is wired below).
19
+ if (window.__relayBroadcastCounts) window.__relayBroadcastCounts();
20
+ },
21
+ });
22
+ } else if (Annotate && !responseRequired && typeof Annotate.teardown === 'function') {
23
+ Annotate.teardown();
24
+ }
25
+
26
+ // Editable-mermaid: record (or clear) the user's edit for a block, then
27
+ // autosave. A null/empty code clears the entry (block matches the original
28
+ // again — e.g. after Reset), so payload()/draft carry only real divergences.
29
+ function onBlockEdit(blockId, codeOrNull) {
30
+ if (codeOrNull === null || codeOrNull === undefined) delete state.blockEdits[blockId];
31
+ else state.blockEdits[blockId] = codeOrNull;
32
+ scheduleSave();
33
+ }
34
+
35
+ document.addEventListener('relay:block-edit', (e) => {
36
+ const d = e.detail || {};
37
+ if (!d.blockId) return;
38
+ onBlockEdit(d.blockId, d.value);
39
+ });
40
+
41
+ async function saveRegionArtifact(artifact) {
42
+ const res = await fetch('/api/artifact', {
43
+ method: 'POST',
44
+ headers: authHeaders({ 'content-type': 'application/json' }),
45
+ body: JSON.stringify(artifact),
46
+ });
47
+ const body = await res.json().catch(() => null);
48
+ if (!res.ok || !body || !body.path) throw new Error(body && body.error ? body.error : 'could not save image crop');
49
+ return body;
50
+ }
51
+
52
+ // ctx for RelayBlocks.render — theme()/htmlSrc per the shared contract, plus
53
+ // the editable-mermaid plumbing (edits map + onBlockEdit callback).
54
+ function blockCtx(questionId) {
55
+ return {
56
+ theme: effectiveTheme,
57
+ htmlSrc: (blockId) => {
58
+ const params = new URLSearchParams({ theme: effectiveTheme() });
59
+ if (access.token) params.set('token', access.token);
60
+ return '/html/b/' + encodeURIComponent(blockId) + '?' + params.toString();
61
+ },
62
+ questionId: questionId == null ? null : questionId,
63
+ annotate: responseRequired ? Annotate : null,
64
+ canComment: responseRequired && access.canComment !== false,
65
+ saveArtifact: responseRequired && access.canComment !== false ? saveRegionArtifact : null,
66
+ edits: state.blockEdits,
67
+ onBlockEdit,
68
+ canEditBlocks: access.canEditBlocks !== false,
69
+ };
70
+ }
71
+
72
+ // Renders blocks async without blocking the page; on rejection (or a missing
73
+ // RelayBlocks) shows a muted "failed to render" card in place.
74
+ function renderBlocks(container, blocks, questionId) {
75
+ if (!Array.isArray(blocks) || !blocks.length) return;
76
+ const target = el('div', { class: 'blocks' });
77
+ container.append(target);
78
+ if (typeof window.RelayBlocks === 'undefined' || !window.RelayBlocks) {
79
+ target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
80
+ return;
81
+ }
82
+ Promise.resolve()
83
+ .then(() => window.RelayBlocks.render(target, blocks, blockCtx(questionId)))
84
+ .catch(() => {
85
+ target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
86
+ });
87
+ }
88
+
@@ -0,0 +1,44 @@
1
+ // ---------- real-time autosave ----------
2
+ let saveTimer = null;
3
+ let saveSeq = 0;
4
+ let saveEl = null;
5
+ // Consecutive failed /api/draft saves. Two in a row triggers a confirming
6
+ // probe → block. Any success resets it.
7
+ let saveFailures = 0;
8
+ function scheduleSave() {
9
+ if (submitted || !canPersistFeedback) return;
10
+ // Mirror to localStorage SYNCHRONOUSLY on every edit, before (and regardless
11
+ // of) the network save. This is what survives a tab reload / crash / a new
12
+ // tab during a connection outage — it must happen even while blocked.
13
+ writeLocalDraft(payload());
14
+ if (persistenceLost) return; // network save is futile while disconnected
15
+ if (saveEl) saveEl.textContent = 'saving…';
16
+ clearTimeout(saveTimer);
17
+ saveTimer = setTimeout(saveDraft, 450);
18
+ }
19
+ async function saveDraft() {
20
+ if (!canPersistFeedback) return;
21
+ const seq = ++saveSeq;
22
+ // Keep the local mirror current on every flush too (covers programmatic
23
+ // saveDraft() calls that don't go through scheduleSave, e.g. recovery flush).
24
+ writeLocalDraft(payload());
25
+ try {
26
+ const r = await fetch('/api/draft', {
27
+ method: 'POST',
28
+ headers: authHeaders({ 'content-type': 'application/json' }),
29
+ body: JSON.stringify(payload()),
30
+ });
31
+ if (!r.ok) throw new Error('draft rejected');
32
+ const body = await r.json().catch(() => null);
33
+ if (body && typeof body.draftRev === 'number') seenDraftRev = body.draftRev;
34
+ saveFailures = 0;
35
+ if (seq === saveSeq && saveEl && !submitted && !persistenceLost) saveEl.textContent = 'draft saved ✓';
36
+ } catch {
37
+ if (seq === saveSeq && saveEl && !submitted && !persistenceLost) saveEl.textContent = 'draft save failed';
38
+ // A save couldn't be persisted to the SERVER — the core data-loss signal.
39
+ // (The local mirror above still captured it.) After two in a row, confirm
40
+ // with a probe and block so the user stops typing into the void.
41
+ if (++saveFailures >= 2) considerPersistenceLost(false);
42
+ }
43
+ }
44
+
@@ -0,0 +1,74 @@
1
+ const boot = JSON.parse(document.getElementById('boot').textContent);
2
+ const spec = boot.spec;
3
+ const responseRequired = spec.responseRequired !== false;
4
+ const access = boot.access || {
5
+ role: 'owner',
6
+ canShare: true,
7
+ canSubmit: true,
8
+ canEditAnswers: true,
9
+ canComment: true,
10
+ canEditComments: true,
11
+ canDeleteComments: true,
12
+ canEditBlocks: true,
13
+ canFinalize: true,
14
+ };
15
+ if (access.role) document.documentElement.dataset.accessRole = access.role;
16
+ const QS = spec.questions || [];
17
+ const app = document.getElementById('app');
18
+ const banner = document.getElementById('banner');
19
+ // Live-update baseline: the server's rev at page-build time. The heartbeat
20
+ // compares /api/status.rev to this and reloads the board when it advances
21
+ // (an agent ran `rly update`).
22
+ const bootRev = typeof boot.rev === 'number' ? boot.rev : null;
23
+ let seenDraftRev = typeof boot.draftRev === 'number' ? boot.draftRev : 0;
24
+
25
+ function authHeaders(extra = {}) {
26
+ const headers = access.token ? { ...extra, 'x-relay-share-token': access.token } : { ...extra };
27
+ if (access.reviewSessionId) headers['x-relay-review-session'] = access.reviewSessionId;
28
+ return headers;
29
+ }
30
+ const canPersistFeedback = responseRequired && Boolean(access.canEditAnswers || access.canComment || access.canEditBlocks);
31
+
32
+ // ---------- helpers ----------
33
+ function el(tag, attrs = {}, ...children) {
34
+ const n = document.createElement(tag);
35
+ for (const [k, v] of Object.entries(attrs)) {
36
+ if (v === undefined || v === null) continue;
37
+ if (k === 'class') n.className = v;
38
+ else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);
39
+ else n.setAttribute(k, v);
40
+ }
41
+ for (const c of children.flat()) {
42
+ if (c !== null && c !== undefined) n.append(c.nodeType ? c : document.createTextNode(c));
43
+ }
44
+ return n;
45
+ }
46
+
47
+ // Small, self-dismissing toast pinned to the top-center of the viewport.
48
+ // Used to flag a live `rly update` after the reload (accent-soft bg).
49
+ function showToast(message) {
50
+ const toast = el('div', { class: 'toast' }, message);
51
+ document.body.append(toast);
52
+ setTimeout(() => toast.remove(), 4000);
53
+ }
54
+
55
+ // True once the board has soft-timed-out (the agent stopped waiting) or the
56
+ // live connection dropped — used to tailor the post-submit message. The board
57
+ // stays fully usable either way; we never disable Submit.
58
+ let handedBack = false;
59
+ // Calm, persistent status notes (the #banner stack). tone 'info' is the
60
+ // default neutral style; 'warn' is a softer amber, NOT the old red error.
61
+ // Each message is shown at most once so the heartbeat can call it every tick.
62
+ const notesShown = new Set();
63
+ function showNotice(message, tone) {
64
+ if (notesShown.has(message)) return;
65
+ notesShown.add(message);
66
+ if (banner.dataset.ready !== '1') {
67
+ banner.replaceChildren();
68
+ banner.dataset.ready = '1';
69
+ }
70
+ banner.className = 'banner-stack';
71
+ banner.append(el('div', { class: 'banner-item ' + (tone === 'warn' ? 'warn' : 'info') }, message));
72
+ banner.style.display = 'block';
73
+ }
74
+