@khanglvm/relay 0.19.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 (131) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +4 -4
  3. package/src/cli/args.js +46 -0
  4. package/src/cli/ask.js +12 -0
  5. package/src/cli/boards.js +326 -0
  6. package/src/cli/config.js +56 -0
  7. package/src/cli/context.js +13 -0
  8. package/src/cli/git.js +183 -0
  9. package/src/cli/help.js +90 -0
  10. package/src/cli/index.js +103 -0
  11. package/src/cli/install.js +197 -0
  12. package/src/cli/io.js +186 -0
  13. package/src/cli/mcp.js +94 -0
  14. package/src/cli/share.js +45 -0
  15. package/src/cli/skill.js +192 -0
  16. package/src/cli/upgrade.js +130 -0
  17. package/src/cli/wait.js +172 -0
  18. package/src/file-preview.js +1 -1
  19. package/src/index.js +1 -1
  20. package/src/mcp-ui/board/block-ctx.js +43 -0
  21. package/src/mcp-ui/board/bridge.js +165 -0
  22. package/src/mcp-ui/board/controls.js +310 -0
  23. package/src/mcp-ui/board/core.js +20 -0
  24. package/src/mcp-ui/board/lifecycle.js +118 -0
  25. package/src/mcp-ui/board/normalize.js +95 -0
  26. package/src/mcp-ui/board/render.js +200 -0
  27. package/src/mcp-ui/board/state.js +106 -0
  28. package/src/mcp-ui/board/vendors.js +86 -0
  29. package/src/mcp.js +12 -18
  30. package/src/{server.js → server/board.js} +15 -778
  31. package/src/server/files.js +141 -0
  32. package/src/server/http.js +114 -0
  33. package/src/server/index.js +2 -0
  34. package/src/server/page.js +183 -0
  35. package/src/server/paths.js +7 -0
  36. package/src/server/result.js +58 -0
  37. package/src/server/reviews.js +41 -0
  38. package/src/server/sanitize.js +231 -0
  39. package/src/spec/blocks/a2ui.js +25 -0
  40. package/src/spec/blocks/chart.js +49 -0
  41. package/src/spec/blocks/code.js +38 -0
  42. package/src/spec/blocks/diagram.js +39 -0
  43. package/src/spec/blocks/git-conflict.js +106 -0
  44. package/src/spec/blocks/image.js +32 -0
  45. package/src/spec/blocks/index.js +33 -0
  46. package/src/spec/blocks/markdown.js +13 -0
  47. package/src/spec/blocks/pdf.js +38 -0
  48. package/src/spec/blocks/table.js +122 -0
  49. package/src/spec/blocks/video.js +68 -0
  50. package/src/spec/blocks/widgets.js +98 -0
  51. package/src/spec/constants.js +65 -0
  52. package/src/spec/index.js +5 -0
  53. package/src/spec/normalize.js +285 -0
  54. package/src/spec/ready.js +106 -0
  55. package/src/spec/schema.js +182 -0
  56. package/src/spec/sources.js +83 -0
  57. package/src/ui/annotate/api.js +149 -0
  58. package/src/ui/annotate/badges.js +77 -0
  59. package/src/ui/annotate/chrome.js +158 -0
  60. package/src/ui/annotate/core.js +134 -0
  61. package/src/ui/annotate/highlights.js +129 -0
  62. package/src/ui/annotate/mutations.js +127 -0
  63. package/src/ui/annotate/popover.js +206 -0
  64. package/src/ui/annotate/summary.js +67 -0
  65. package/src/ui/app/annotations.js +88 -0
  66. package/src/ui/app/autosave.js +44 -0
  67. package/src/ui/app/core.js +74 -0
  68. package/src/ui/app/drafts.js +201 -0
  69. package/src/ui/app/heartbeat.js +150 -0
  70. package/src/ui/app/iframe-bridge.js +64 -0
  71. package/src/ui/app/persistence.js +117 -0
  72. package/src/ui/app/prefilled.js +21 -0
  73. package/src/ui/app/presence.js +38 -0
  74. package/src/ui/app/question-color.js +67 -0
  75. package/src/ui/app/questions.js +360 -0
  76. package/src/ui/app/render.js +135 -0
  77. package/src/ui/app/share.js +108 -0
  78. package/src/ui/app/submit.js +109 -0
  79. package/src/ui/app/theme.js +63 -0
  80. package/src/ui/blocks/api.js +1 -0
  81. package/src/ui/blocks/chart.js +222 -0
  82. package/src/ui/blocks/code.js +138 -0
  83. package/src/ui/blocks/compare.js +82 -0
  84. package/src/ui/blocks/core.js +74 -0
  85. package/src/ui/blocks/diff.js +361 -0
  86. package/src/ui/blocks/dispatch.js +111 -0
  87. package/src/ui/blocks/file-links.js +180 -0
  88. package/src/ui/blocks/git-conflict.js +151 -0
  89. package/src/ui/blocks/graphviz.js +57 -0
  90. package/src/ui/blocks/html.js +45 -0
  91. package/src/ui/blocks/image.js +371 -0
  92. package/src/ui/blocks/kpi.js +26 -0
  93. package/src/ui/blocks/markdown.js +223 -0
  94. package/src/ui/blocks/mermaid.js +242 -0
  95. package/src/ui/blocks/palette.js +59 -0
  96. package/src/ui/blocks/pdf.js +21 -0
  97. package/src/ui/blocks/plantuml.js +152 -0
  98. package/src/ui/blocks/table.js +155 -0
  99. package/src/ui/blocks/typography.js +25 -0
  100. package/src/ui/blocks/vendor.js +43 -0
  101. package/src/ui/blocks/video.js +43 -0
  102. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  103. package/src/ui/blocks/viewer.js +324 -0
  104. package/src/ui/kit.js +1 -0
  105. package/src/ui/manifest.js +140 -0
  106. package/types/index.d.ts +1 -1
  107. package/types/spec/blocks/a2ui.d.ts +4 -0
  108. package/types/spec/blocks/chart.d.ts +4 -0
  109. package/types/spec/blocks/code.d.ts +10 -0
  110. package/types/spec/blocks/diagram.d.ts +15 -0
  111. package/types/spec/blocks/git-conflict.d.ts +7 -0
  112. package/types/spec/blocks/image.d.ts +5 -0
  113. package/types/spec/blocks/index.d.ts +30 -0
  114. package/types/spec/blocks/markdown.d.ts +5 -0
  115. package/types/spec/blocks/pdf.d.ts +4 -0
  116. package/types/spec/blocks/table.d.ts +9 -0
  117. package/types/spec/blocks/video.d.ts +4 -0
  118. package/types/spec/blocks/widgets.d.ts +21 -0
  119. package/types/spec/constants.d.ts +67 -0
  120. package/types/spec/index.d.ts +4 -0
  121. package/types/spec/normalize.d.ts +17 -0
  122. package/types/spec/ready.d.ts +1 -0
  123. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  124. package/types/spec/sources.d.ts +14 -0
  125. package/types/ui/manifest.d.ts +62 -0
  126. package/src/cli.js +0 -1767
  127. package/src/mcp-ui/board.js +0 -1162
  128. package/src/spec.js +0 -1224
  129. package/src/ui/annotate.js +0 -1055
  130. package/src/ui/app.js +0 -1643
  131. package/src/ui/blocks.js +0 -3260
@@ -0,0 +1,201 @@
1
+ // ---------- localStorage draft mirror ----------
2
+ // Every autosave is ALSO written to localStorage, keyed by board id + access
3
+ // role/session. This keeps a reviewer side draft from leaking into a
4
+ // collaborator/read-only tab on the same LAN origin.
5
+ // the durability layer the server file alone can't provide: if the connection
6
+ // drops and the user keeps typing, the in-memory state is mirrored locally, so
7
+ // even a tab reload / browser restart / a freshly opened tab on the same board
8
+ // prefills the LATEST input instead of a blank board or a stale server save.
9
+ // Guards (per design): newest-of-(local,server) wins; the mirror is discarded
10
+ // if the board's spec rev changed (agent edited it); cleared on submit.
11
+ const LOCAL_DRAFT_KEY = 'relay-draft-' + (boot.boardId || 'unknown') + '-' +
12
+ (access.role || 'owner') + (access.reviewSessionId ? '-' + access.reviewSessionId : '');
13
+ function writeLocalDraft(p, updatedAt) {
14
+ try {
15
+ localStorage.setItem(LOCAL_DRAFT_KEY, JSON.stringify({
16
+ v: 1,
17
+ boardId: boot.boardId,
18
+ rev: bootRev,
19
+ updatedAt: updatedAt || new Date().toISOString(),
20
+ payload: p,
21
+ }));
22
+ } catch {
23
+ // localStorage may be full or unavailable (privacy mode) — non-fatal; the
24
+ // server file remains the primary persistence path.
25
+ }
26
+ }
27
+ function clearLocalDraft() {
28
+ try { localStorage.removeItem(LOCAL_DRAFT_KEY); } catch { /* non-fatal */ }
29
+ }
30
+ // Returns the saved local mirror only if it's valid for THIS board+rev,
31
+ // otherwise null (and clears a now-stale entry). rev mismatch ⇒ the agent
32
+ // re-published the board, so old local answers may not map — discard them.
33
+ function loadLocalDraft() {
34
+ let raw;
35
+ try { raw = localStorage.getItem(LOCAL_DRAFT_KEY); } catch { return null; }
36
+ if (!raw) return null;
37
+ let obj;
38
+ try { obj = JSON.parse(raw); } catch { clearLocalDraft(); return null; }
39
+ if (!obj || obj.boardId !== boot.boardId || !obj.payload || typeof obj.payload !== 'object') {
40
+ clearLocalDraft();
41
+ return null;
42
+ }
43
+ // rev-guard: a changed spec rev means the local answers may reference a
44
+ // different question set — don't resurrect them.
45
+ if (bootRev !== null && obj.rev !== undefined && obj.rev !== null && obj.rev !== bootRev) {
46
+ clearLocalDraft();
47
+ return null;
48
+ }
49
+ return obj;
50
+ }
51
+
52
+ // Choose the prefill source: the NEWER of the server draft (boot.prefill) and
53
+ // the local mirror. The server draft shape mirrors a payload() plus updatedAt.
54
+ function chooseInitialPrefill() {
55
+ const server = boot.prefill || null;
56
+ const local = loadLocalDraft();
57
+ if (!local) return server;
58
+ if (!server) return { ...local.payload, __from: 'local' };
59
+ const sT = Date.parse(server.updatedAt || '') || 0;
60
+ const lT = Date.parse(local.updatedAt || '') || 0;
61
+ // Newest wins; ties favor local (the tab that was last typing into).
62
+ return lT >= sT ? { ...local.payload, __from: 'local' } : server;
63
+ }
64
+ const initialPrefill = chooseInitialPrefill();
65
+
66
+ // ---------- state ----------
67
+ // state.answers holds raw control state; state.other holds the "Other"
68
+ // free-text per question; getValue() derives the final answer value.
69
+ // state.annotations holds element-level comments (managed by RelayAnnotate).
70
+ const state = {
71
+ answers: {},
72
+ other: {},
73
+ notes: {},
74
+ comment: '',
75
+ annotations: (initialPrefill && initialPrefill.annotations) || [],
76
+ // Editable-mermaid edits: blockId -> edited source. Seeded from the live
77
+ // draft so a reload/reopen restores the user's edited diagram. Mutated via
78
+ // the blocks ctx.onBlockEdit callback below; returned in payload().
79
+ blockEdits: (initialPrefill && initialPrefill.blockEdits) || {},
80
+ };
81
+ let submitted = false;
82
+
83
+ function seedFromPrefill(prefill) {
84
+ state.comment = prefill.comment || '';
85
+ if (prefill.notes && typeof prefill.notes === 'object') state.notes = { ...prefill.notes };
86
+ const ans = prefill.answers || {};
87
+ for (const q of QS) {
88
+ const v = ans[q.id];
89
+ if (v === undefined || v === null) continue;
90
+ if (q.type === 'multi' && Array.isArray(v)) {
91
+ const known = new Set((q.options || []).map((o) => o.value));
92
+ state.answers[q.id] = v.filter((x) => known.has(x));
93
+ const extra = v.filter((x) => !known.has(x));
94
+ if (extra.length && q.other) state.other[q.id] = { on: true, text: extra.join(', ') };
95
+ } else if (q.type === 'single' && typeof v === 'string') {
96
+ if ((q.options || []).some((o) => o.value === v)) state.answers[q.id] = v;
97
+ else if (q.other) state.other[q.id] = { on: true, text: v };
98
+ } else {
99
+ state.answers[q.id] = v;
100
+ }
101
+ }
102
+ }
103
+ // Coerce any prior rank value (draft/default) into a complete, deduped
104
+ // permutation of the option values: keep the known ones in their given order,
105
+ // then append any options the prior list missed (in authored order).
106
+ function seedRankOrder(q, prior) {
107
+ const opts = (q.options || []).map((o) => o.value);
108
+ const arr = Array.isArray(prior) ? prior : [];
109
+ const order = arr.filter((v, i) => opts.includes(v) && arr.indexOf(v) === i);
110
+ for (const v of opts) if (!order.includes(v)) order.push(v);
111
+ return order;
112
+ }
113
+ // Allocate: a complete map {optionValue: number≥0}, seeded from a prior/default.
114
+ function seedAllocate(q, prior) {
115
+ const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
116
+ const out = {};
117
+ for (const o of q.options || []) out[o.value] = Math.max(0, Number(m[o.value]) || 0);
118
+ return out;
119
+ }
120
+ // Checklist: keep only {knownOption: knownStatus} entries from a prior/default.
121
+ function seedChecklist(q, prior) {
122
+ const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
123
+ const optVals = new Set((q.options || []).map((o) => o.value));
124
+ const stVals = new Set((q.statuses || []).map((s) => s.value));
125
+ const out = {};
126
+ for (const k of Object.keys(m)) if (optVals.has(k) && stVals.has(m[k])) out[k] = m[k];
127
+ return out;
128
+ }
129
+
130
+ if (initialPrefill) seedFromPrefill(initialPrefill);
131
+ else for (const q of QS) if (q.default !== undefined) state.answers[q.id] = q.default;
132
+ // Rank questions always carry a full, valid permutation of their option values
133
+ // (from a draft/default if present, else the authored order), so a never-touched
134
+ // rank still returns a meaningful ordering.
135
+ for (const q of QS) if (q.type === 'rank') state.answers[q.id] = seedRankOrder(q, state.answers[q.id]);
136
+ for (const q of QS) if (q.type === 'allocate') state.answers[q.id] = seedAllocate(q, state.answers[q.id]);
137
+ for (const q of QS) if (q.type === 'checklist') state.answers[q.id] = seedChecklist(q, state.answers[q.id]);
138
+ // If the local mirror was newer than the server (or the server had nothing),
139
+ // the in-memory state now holds input the server hasn't seen — flush it once
140
+ // the rest of the app is wired (see the post-init flush near the heartbeat).
141
+
142
+ function getValue(q) {
143
+ const v = state.answers[q.id];
144
+ const oth = state.other[q.id];
145
+ switch (q.type) {
146
+ case 'single': {
147
+ if (oth && oth.on) {
148
+ const t = (oth.text || '').trim();
149
+ return t || undefined;
150
+ }
151
+ return typeof v === 'string' && v ? v : undefined;
152
+ }
153
+ case 'multi': {
154
+ const arr = Array.isArray(v) ? [...v] : [];
155
+ if (oth && oth.on) {
156
+ const t = (oth.text || '').trim();
157
+ if (t) arr.push(t);
158
+ }
159
+ return arr.length ? arr : undefined;
160
+ }
161
+ case 'yesno':
162
+ return v === 'yes' || v === 'no' ? v : undefined;
163
+ case 'scale':
164
+ return typeof v === 'number' ? v : undefined;
165
+ case 'rank':
166
+ // always a full, valid permutation (seeded below) → always answered
167
+ return Array.isArray(v) && v.length ? [...v] : undefined;
168
+ case 'checklist': {
169
+ const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
170
+ return Object.keys(m).length ? { ...m } : undefined;
171
+ }
172
+ case 'allocate': {
173
+ const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
174
+ const sum = Object.values(m).reduce((a, n) => a + (Number(n) || 0), 0);
175
+ return sum > 0 ? { ...m } : undefined;
176
+ }
177
+ default: {
178
+ const t = typeof v === 'string' ? v.trim() : '';
179
+ return t || undefined;
180
+ }
181
+ }
182
+ }
183
+
184
+ function payload() {
185
+ const answers = {};
186
+ const notes = {};
187
+ for (const q of QS) {
188
+ const v = getValue(q);
189
+ if (v !== undefined) answers[q.id] = v;
190
+ const n = typeof state.notes[q.id] === 'string' ? state.notes[q.id].trim() : '';
191
+ if (n) notes[q.id] = n;
192
+ }
193
+ return {
194
+ answers,
195
+ comment: (state.comment || '').trim(),
196
+ notes,
197
+ annotations: state.annotations,
198
+ blockEdits: state.blockEdits,
199
+ };
200
+ }
201
+
@@ -0,0 +1,150 @@
1
+ // ---------- heartbeat ----------
2
+ // True when the user is actively typing — an open annotation comment popover,
3
+ // or focus in any text-entry field (comment box, notes, text/color answers,
4
+ // "Other" inputs). Used to defer the live-update reload so in-progress
5
+ // comments aren't destroyed mid-keystroke.
6
+ function isEditable(node) {
7
+ if (!node) return false;
8
+ if (node.tagName === 'TEXTAREA') return true;
9
+ if (node.tagName === 'INPUT') {
10
+ const t = (node.type || 'text').toLowerCase();
11
+ return ['text', 'search', 'email', 'url', 'tel', 'number', 'color'].includes(t);
12
+ }
13
+ return node.isContentEditable === true;
14
+ }
15
+ function userIsComposing() {
16
+ if (window.RelayAnnotate && typeof RelayAnnotate.isComposing === 'function' && RelayAnnotate.isComposing()) return true;
17
+ return isEditable(document.activeElement);
18
+ }
19
+
20
+ let misses = 0;
21
+ let reloading = false;
22
+ let hb = null;
23
+ async function heartbeatTick() {
24
+ // Piggyback presence on the heartbeat (best-effort; no-ops after submit).
25
+ pingPresence();
26
+ try {
27
+ const r = await fetch('/api/status', { cache: 'no-store', headers: authHeaders() });
28
+ if (!r.ok) throw new Error('bad status');
29
+ misses = 0;
30
+ // The heartbeat reaching the server is itself proof persistence is back —
31
+ // if we were blocked (saves had been failing), recover now and flush.
32
+ if (persistenceLost) {
33
+ unblockAfterRecovery();
34
+ return;
35
+ }
36
+ // Live update: the agent ran `rly update`, advancing the server rev.
37
+ // Flush whatever the user has typed so far (the reload re-prefills from
38
+ // the live draft — answers for now-removed question ids are ignored),
39
+ // then reload to render the new spec. Guarded so it fires once.
40
+ const body = await r.json().catch(() => null);
41
+ // Soft timeout: the board ran past its deadline so the agent was handed a
42
+ // result and stopped waiting — but the server is still up and the board
43
+ // stays fully usable. Surface a calm note (never disable Submit) so the
44
+ // user knows to prompt the agent after submitting.
45
+ if (body && body.softTimedOut && !submitted) {
46
+ handedBack = true;
47
+ if (access.role === 'review') {
48
+ showNotice('This remains a reference-only side review. Submit when ready; the owner still needs to provide the final answer.', 'info');
49
+ } else if (access.role !== 'read') {
50
+ showNotice(
51
+ 'You’ve had this open a while, so the agent stopped waiting. Your changes save automatically — submit when you’re ready, then prompt the agent to pick them up.',
52
+ 'info'
53
+ );
54
+ }
55
+ }
56
+ if (body && typeof body.rev === 'number' && bootRev !== null && body.rev !== bootRev && !submitted && !reloading) {
57
+ // Don't yank the board out from under someone mid-comment: an open
58
+ // annotation popover (its add-comment box + reply inputs) holds text
59
+ // that isn't in the draft until Save, so a reload would discard it —
60
+ // and reloading while any field is focused drops the user's cursor and
61
+ // last keystrokes. Defer until they're done; the heartbeat re-checks
62
+ // every tick, so the update applies the moment they close/blur.
63
+ if (userIsComposing()) {
64
+ showNotice('The agent updated this board — it’ll refresh as soon as you finish your comment.', 'info');
65
+ return;
66
+ }
67
+ reloading = true;
68
+ stopHeartbeat();
69
+ clearTimeout(saveTimer);
70
+ try {
71
+ await saveDraft();
72
+ } catch {
73
+ // a failed final save shouldn't block the reload to the new spec
74
+ }
75
+ try {
76
+ sessionStorage.setItem('relay-updated', '1');
77
+ } catch {
78
+ // sessionStorage may be unavailable — the reload still applies the update
79
+ }
80
+ location.reload();
81
+ return;
82
+ }
83
+ if (body && typeof body.draftRev === 'number' && body.draftRev > seenDraftRev && !submitted && !reloading) {
84
+ if (userIsComposing()) {
85
+ showNotice('Another viewer updated this board — it’ll refresh as soon as you finish typing.', 'info');
86
+ return;
87
+ }
88
+ reloading = true;
89
+ stopHeartbeat();
90
+ clearTimeout(saveTimer);
91
+ clearLocalDraft();
92
+ try {
93
+ sessionStorage.setItem('relay-draft-updated', '1');
94
+ } catch {
95
+ // sessionStorage may be unavailable — the reload still applies the update
96
+ }
97
+ location.reload();
98
+ }
99
+ } catch {
100
+ // Lost the live connection (the session ended, or the machine slept). Two
101
+ // consecutive misses means the local server is unreachable — so input can
102
+ // no longer be persisted. Hard-block: disable editing and overlay the
103
+ // unmissable "connection lost" scrim, so the user can't keep typing
104
+ // feedback that would be silently discarded. The block re-arms its own
105
+ // probe loop and the heartbeat recovers it once the server answers again.
106
+ if (++misses >= 2 && !submitted && !persistenceLost) {
107
+ handedBack = true;
108
+ stopHeartbeat();
109
+ // force=true: two heartbeat misses already confirm the server is gone,
110
+ // so block immediately without a redundant probe.
111
+ considerPersistenceLost(true);
112
+ // While blocked, keep probing so an automatic recovery (server back,
113
+ // machine woke) lifts the block even if the user never clicks Retry.
114
+ startBlockedProbeLoop();
115
+ }
116
+ }
117
+ }
118
+ function startHeartbeat() {
119
+ if (hb || submitted) return;
120
+ hb = setInterval(heartbeatTick, 3000);
121
+ }
122
+ function stopHeartbeat() {
123
+ if (hb) clearInterval(hb);
124
+ hb = null;
125
+ }
126
+
127
+ // While blocked, the heartbeat is stopped — so run a lightweight probe loop
128
+ // that lifts the block automatically the moment the server is reachable again
129
+ // (no Retry click needed). Stops itself on recovery or after submit.
130
+ let blockedProbe = null;
131
+ function startBlockedProbeLoop() {
132
+ if (blockedProbe) return;
133
+ blockedProbe = setInterval(async () => {
134
+ if (!persistenceLost || submitted) {
135
+ clearInterval(blockedProbe);
136
+ blockedProbe = null;
137
+ return;
138
+ }
139
+ if (probing) return;
140
+ probing = true;
141
+ const ok = await probeServer();
142
+ probing = false;
143
+ if (ok) {
144
+ clearInterval(blockedProbe);
145
+ blockedProbe = null;
146
+ unblockAfterRecovery();
147
+ }
148
+ }, 3000);
149
+ }
150
+ startHeartbeat();
@@ -0,0 +1,64 @@
1
+ // ---------- iframe annotate bridge ----------
2
+ // Custom-HTML iframes (via /kit.js relayKit.annotate, auto-injected by the
3
+ // server) talk to the parent over postMessage:
4
+ // iframe → {relay:'annotate-ready'} we send it counts
5
+ // iframe → {relay:'annotate-request', ref, label, detail?, rect}
6
+ // parent → {relay:'annotate-counts', counts:{ref:n}} it draws badges
7
+ // We own the annotation state, popover, and the submitted result; the iframe
8
+ // owns hover/pin/badges over its own (cross-origin) DOM.
9
+ if (Annotate && responseRequired) {
10
+ const frameOf = (source) => {
11
+ for (const f of document.querySelectorAll('iframe.viz')) {
12
+ if (f.contentWindow === source) return f;
13
+ }
14
+ return null;
15
+ };
16
+ // Per-element comment counts for one iframe, keyed by target.ref.
17
+ const postCountsTo = (frame) => {
18
+ if (!frame || !frame.contentWindow) return;
19
+ const blockId = frame.getAttribute('data-block-id') || null;
20
+ const counts = {};
21
+ for (const a of Annotate.list()) {
22
+ if ((a.blockId ?? null) !== (blockId ?? null)) continue;
23
+ const t = a.target || {};
24
+ if (t.kind !== 'html-element' || !t.ref) continue;
25
+ counts[t.ref] = (counts[t.ref] || 0) + 1;
26
+ }
27
+ try { frame.contentWindow.postMessage({ relay: 'annotate-counts', counts }, '*'); } catch {}
28
+ };
29
+ // Refresh badges in every html iframe (called whenever annotations change).
30
+ window.__relayBroadcastCounts = () => {
31
+ for (const f of document.querySelectorAll('iframe.viz')) postCountsTo(f);
32
+ };
33
+
34
+ window.addEventListener('message', (e) => {
35
+ const msg = e.data;
36
+ if (!msg || typeof msg !== 'object' || typeof msg.relay !== 'string') return;
37
+ const frame = frameOf(e.source);
38
+ if (!frame) return;
39
+ if (msg.relay === 'annotate-ready') { postCountsTo(frame); return; }
40
+ if (msg.relay !== 'annotate-request') return;
41
+
42
+ const blockId = frame.getAttribute('data-block-id') || null;
43
+ const questionId = frame.getAttribute('data-question-id') || null;
44
+ const target = { kind: 'html-element', label: typeof msg.label === 'string' ? msg.label : 'Element' };
45
+ if (typeof msg.ref === 'string') target.ref = msg.ref;
46
+ if (typeof msg.detail === 'string') target.detail = msg.detail;
47
+
48
+ // Anchor the popover to the actual element: translate the iframe-local
49
+ // viewport rect the iframe sent into page coords. Fall back to the iframe.
50
+ let anchor = frame;
51
+ if (msg.rect && typeof msg.rect === 'object') {
52
+ const fr = frame.getBoundingClientRect();
53
+ const r = msg.rect;
54
+ const left = fr.left + (r.left || 0);
55
+ const top = fr.top + (r.top || 0);
56
+ const width = r.width || 0;
57
+ const height = r.height || 0;
58
+ const pageRect = { left, top, width, height, right: left + width, bottom: top + height };
59
+ anchor = { getBoundingClientRect: () => pageRect };
60
+ }
61
+ Annotate.openExternal({ blockId, questionId: questionId || null, target }, anchor);
62
+ });
63
+ }
64
+
@@ -0,0 +1,117 @@
1
+ // ---------- persistence-lost block ----------
2
+ // The dead-end this guards against: the client can lose its connection to the
3
+ // board's local HTTP server (server gone, port taken over, socket dropped,
4
+ // machine slept). Autosaves then fail silently and the user keeps typing
5
+ // answers/comments that are never persisted, then Submit fails too — all of it
6
+ // thrown away. When persistence is CONFIRMED lost we DISABLE every control (and
7
+ // freeze new comments) and show a small, non-dismissable top-right notice with
8
+ // a Reconnect button — without blocking the page, so the user can still read
9
+ // and scroll. Local `state` is never touched, and a mid-typed comment is saved
10
+ // before the freeze, so nothing the user entered during the outage is lost; the
11
+ // moment the connection recovers we flush state and re-enable everything.
12
+ let persistenceLost = false;
13
+ let probing = false;
14
+ let lostNote = null;
15
+ let lostRetryBtn = null;
16
+
17
+ // A direct, side-effect-free reachability probe. Resolves true when the local
18
+ // server answers /api/status, false on any network/HTTP failure. Used to
19
+ // CONFIRM loss before blocking (so a single dropped request never blocks) and
20
+ // to detect recovery from the Retry button / heartbeat.
21
+ async function probeServer() {
22
+ try {
23
+ const r = await fetch('/api/status', { cache: 'no-store', headers: authHeaders() });
24
+ return r.ok;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ function buildLostNote() {
31
+ if (lostNote) return lostNote;
32
+ lostRetryBtn = el('button', { class: 'lost-retry', type: 'button' }, 'Reconnect');
33
+ lostRetryBtn.addEventListener('click', retryConnection);
34
+ lostNote = el('div', { class: 'lost-note', role: 'status', 'aria-live': 'polite' },
35
+ el('span', { class: 'lost-note-dot', 'aria-hidden': 'true' }),
36
+ el('div', { class: 'lost-note-body' },
37
+ el('div', { class: 'lost-note-title' }, 'Connection lost'),
38
+ el('div', { class: 'lost-note-sub' }, 'Editing paused — your input is kept.')
39
+ ),
40
+ lostRetryBtn
41
+ );
42
+ return lostNote;
43
+ }
44
+
45
+ // Enter the blocked state: save a mid-typed comment, freeze comments, disable
46
+ // controls, and pin the small notice. Idempotent. Does NOT block the page —
47
+ // the user can still read and scroll; only editing is paused.
48
+ function blockForLostPersistence() {
49
+ if (persistenceLost || submitted) return;
50
+ persistenceLost = true;
51
+ document.documentElement.classList.add('relay-blocked');
52
+ // Save whatever the user was typing into the comment popover BEFORE freezing
53
+ // it, so the in-progress comment is kept (in `state` + localStorage) instead
54
+ // of discarded; then stop any new comment from being started.
55
+ if (Annotate) {
56
+ if (typeof Annotate.flushOpen === 'function') { try { Annotate.flushOpen(); } catch { /* non-fatal */ } }
57
+ if (typeof Annotate.setDisabled === 'function') { try { Annotate.setDisabled(true); } catch { /* non-fatal */ } }
58
+ }
59
+ // Disable every interactive control inside the form. Values already entered
60
+ // stay in the DOM (and in `state`), so nothing typed so far is lost.
61
+ for (const node of app.querySelectorAll('input, textarea, button, select')) {
62
+ node.disabled = true;
63
+ }
64
+ document.body.append(buildLostNote());
65
+ if (saveEl) saveEl.textContent = 'connection lost — not saving';
66
+ }
67
+
68
+ // Leave the blocked state: re-enable controls + comments, drop the notice, and
69
+ // flush whatever the user typed during the outage so it's persisted right away.
70
+ function unblockAfterRecovery() {
71
+ if (!persistenceLost) return;
72
+ persistenceLost = false;
73
+ document.documentElement.classList.remove('relay-blocked');
74
+ if (Annotate && typeof Annotate.setDisabled === 'function') { try { Annotate.setDisabled(false); } catch { /* non-fatal */ } }
75
+ for (const node of app.querySelectorAll('input, textarea, button, select')) {
76
+ node.disabled = false;
77
+ }
78
+ applyAccessRestrictions();
79
+ if (lostNote) lostNote.remove();
80
+ // Re-arm the heartbeat (it stops itself when it confirms loss) and persist
81
+ // everything typed during the outage. saveDraft() updates the save label.
82
+ startHeartbeat();
83
+ misses = 0;
84
+ saveFailures = 0;
85
+ saveDraft();
86
+ }
87
+
88
+ // Retry button: probe once; recover on success, otherwise tell the user it's
89
+ // still down (without un-blocking).
90
+ async function retryConnection() {
91
+ if (probing) return;
92
+ probing = true;
93
+ if (lostRetryBtn) { lostRetryBtn.disabled = true; lostRetryBtn.textContent = 'Checking…'; }
94
+ const ok = await probeServer();
95
+ probing = false;
96
+ if (lostRetryBtn) { lostRetryBtn.disabled = false; lostRetryBtn.textContent = 'Retry connection'; }
97
+ if (ok) unblockAfterRecovery();
98
+ else if (lostRetryBtn) {
99
+ lostRetryBtn.textContent = 'Still unreachable — try again';
100
+ setTimeout(() => { if (lostRetryBtn && persistenceLost) lostRetryBtn.textContent = 'Retry connection'; }, 2500);
101
+ }
102
+ }
103
+
104
+ // Called when a save/heartbeat fails. Confirms loss with a probe (so one
105
+ // dropped request never blocks) before hard-blocking. `force` skips the probe
106
+ // for callers (the heartbeat) that already represent repeated failures.
107
+ async function considerPersistenceLost(force) {
108
+ if (persistenceLost || submitted || probing) return;
109
+ if (!force) {
110
+ probing = true;
111
+ const ok = await probeServer();
112
+ probing = false;
113
+ if (ok || persistenceLost || submitted) return; // recovered or already handled
114
+ }
115
+ blockForLostPersistence();
116
+ }
117
+
@@ -0,0 +1,21 @@
1
+ // ---------- prefilled load: jump past what's already answered ----------
2
+ // On reload/reopen with saved answers, scroll to the first unanswered
3
+ // question so the user doesn't re-scan questions they already did.
4
+ if (initialPrefill && QS.length) {
5
+ const answered = QS.filter((q) => getValue(q) !== undefined).length;
6
+ const firstOpen = QS.find((q) => getValue(q) === undefined);
7
+ if (answered > 0 && firstOpen) {
8
+ setTimeout(() => {
9
+ cards[firstOpen.id].scrollIntoView({ behavior: 'smooth', block: 'center' });
10
+ }, 350);
11
+ }
12
+ }
13
+
14
+ // If the chosen prefill came from the local mirror (newer than the server, or
15
+ // the server had nothing — e.g. a freshly reopened board the user had typed
16
+ // into in another tab during an outage), the server doesn't yet have this
17
+ // input. Flush it once so a brand-new tab's view is also the server's truth.
18
+ if (initialPrefill && initialPrefill.__from === 'local' && !submitted && canPersistFeedback) {
19
+ saveDraft();
20
+ }
21
+
@@ -0,0 +1,38 @@
1
+ // ---------- presence / awareness ----------
2
+ // Track the last time the user interacted with the page so the agent (via
3
+ // /api/presence) can tell whether someone is still actively viewing the board
4
+ // and keep waiting instead of timing out. Every existing 3s heartbeat tick
5
+ // also POSTs /api/ping {visible, focused, idleMs}; pinging stops after submit.
6
+ let lastInteractionAt = Date.now();
7
+ let lastMoveAt = 0;
8
+ function noteInteraction() {
9
+ lastInteractionAt = Date.now();
10
+ }
11
+ window.addEventListener('pointerdown', noteInteraction, { passive: true });
12
+ window.addEventListener('keydown', noteInteraction, { passive: true });
13
+ window.addEventListener('scroll', noteInteraction, { passive: true });
14
+ window.addEventListener('touchstart', noteInteraction, { passive: true });
15
+ // pointermove fires continuously — throttle to at most once per second.
16
+ window.addEventListener('pointermove', () => {
17
+ const now = Date.now();
18
+ if (now - lastMoveAt >= 1000) {
19
+ lastMoveAt = now;
20
+ lastInteractionAt = now;
21
+ }
22
+ }, { passive: true });
23
+
24
+ function pingPresence() {
25
+ if (submitted) return;
26
+ fetch('/api/ping', {
27
+ method: 'POST',
28
+ headers: authHeaders({ 'content-type': 'application/json' }),
29
+ body: JSON.stringify({
30
+ visible: !document.hidden,
31
+ focused: document.hasFocus(),
32
+ idleMs: Date.now() - lastInteractionAt,
33
+ }),
34
+ }).catch(() => {
35
+ // presence is best-effort — a failed ping must never surface to the user
36
+ });
37
+ }
38
+
@@ -0,0 +1,67 @@
1
+ function cssColorToHex(str) {
2
+ const s = String(str || '').trim();
3
+ let m = /^#?([0-9a-fA-F]{6})$/.exec(s);
4
+ if (m) return '#' + m[1].toLowerCase();
5
+ m = /^#?([0-9a-fA-F]{3})$/.exec(s);
6
+ if (m) return '#' + m[1].split('').map((x) => x + x).join('').toLowerCase();
7
+ try {
8
+ const d = document.createElement('div');
9
+ d.style.color = '';
10
+ d.style.color = s;
11
+ if (!d.style.color) return null; // browser rejected it → invalid color
12
+ d.style.display = 'none';
13
+ document.body.appendChild(d);
14
+ const rgb = getComputedStyle(d).color;
15
+ document.body.removeChild(d);
16
+ const mm = rgb.match(/(\d+)[,\s]+(\d+)[,\s]+(\d+)/);
17
+ if (!mm) return null;
18
+ const h = (n) => Math.max(0, Math.min(255, Number(n))).toString(16).padStart(2, '0');
19
+ return '#' + h(mm[1]) + h(mm[2]) + h(mm[3]);
20
+ } catch { return null; }
21
+ }
22
+ function toHex6(c) { return cssColorToHex(c) || '#000000'; }
23
+
24
+ function controlColor(q) {
25
+ const wrap = el('div', { class: 'colorpick' });
26
+ const init = (typeof state.answers[q.id] === 'string' && state.answers[q.id]) || (typeof q.default === 'string' ? q.default : '');
27
+ const swatch = el('input', { type: 'color', class: 'colorswatch' });
28
+ const hex = el('input', { type: 'text', class: 'colorhex', placeholder: q.placeholder || '#rrggbb / rgb() / name', spellcheck: 'false', autocapitalize: 'off' });
29
+ swatch.value = toHex6(init || '#888888');
30
+ if (init) { hex.value = init; state.answers[q.id] = init; }
31
+ let syncPaletteSel = () => {};
32
+ const set = (val) => { state.answers[q.id] = val; syncPaletteSel(); clearErr(q.id); scheduleSave(); };
33
+ swatch.addEventListener('input', () => { hex.value = swatch.value; set(swatch.value); });
34
+ hex.addEventListener('input', () => { const v = hex.value.trim(); const h = cssColorToHex(v); if (h) swatch.value = h; set(v); });
35
+
36
+ // "Pick from a palette" — labeled swatch cards. Click selects that color as
37
+ // the answer; each card is registered for annotation (per-color comments).
38
+ if (Array.isArray(q.palette) && q.palette.length) {
39
+ const grid = el('div', { class: 'colorpalette' });
40
+ const cards = [];
41
+ for (const p of q.palette) {
42
+ const labelled = p.label && p.label !== p.value;
43
+ const card = el('button', { type: 'button', class: 'colorpal-sw', style: 'background:' + p.value, title: (labelled ? p.label + ' · ' : '') + p.value });
44
+ if (labelled) card.append(el('span', { class: 'colorpal-label' }, p.label));
45
+ card.addEventListener('click', () => { const h = cssColorToHex(p.value); if (h) swatch.value = h; hex.value = p.value; set(p.value); });
46
+ if (Annotate) Annotate.register(card, { blockId: null, questionId: q.id, target: { kind: 'swatch', label: (labelled ? p.label + ' · ' : '') + p.value } });
47
+ cards.push({ card, val: p.value });
48
+ grid.append(card);
49
+ }
50
+ syncPaletteSel = () => { for (const c of cards) c.card.classList.toggle('sel', state.answers[q.id] === c.val); };
51
+ wrap.append(grid);
52
+ }
53
+
54
+ wrap.append(el('div', { class: 'colorrow' }, swatch, hex));
55
+ if (Array.isArray(q.presets) && q.presets.length) {
56
+ const presets = el('div', { class: 'colorpresets' });
57
+ for (const c of q.presets) {
58
+ const b = el('button', { type: 'button', class: 'colorpreset', style: 'background:' + c, title: c });
59
+ b.addEventListener('click', () => { const h = cssColorToHex(c); if (h) swatch.value = h; hex.value = c; set(c); });
60
+ presets.append(b);
61
+ }
62
+ wrap.append(presets);
63
+ }
64
+ syncPaletteSel();
65
+ return wrap;
66
+ }
67
+