@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.
- package/bin/rly.js +1 -1
- package/package.json +39 -4
- package/schema/spec.v1.json +1368 -0
- package/src/a2ui/compile.js +2 -0
- package/src/cli/args.js +46 -0
- package/src/cli/ask.js +12 -0
- package/src/cli/boards.js +326 -0
- package/src/cli/config.js +56 -0
- package/src/cli/context.js +13 -0
- package/src/cli/git.js +183 -0
- package/src/cli/help.js +90 -0
- package/src/cli/index.js +103 -0
- package/src/cli/install.js +197 -0
- package/src/cli/io.js +186 -0
- package/src/cli/mcp.js +94 -0
- package/src/cli/share.js +45 -0
- package/src/cli/skill.js +192 -0
- package/src/cli/upgrade.js +130 -0
- package/src/cli/wait.js +172 -0
- package/src/file-preview.js +1 -1
- package/src/index.js +104 -0
- package/src/link.js +1 -0
- package/src/mcp-ui/board/block-ctx.js +43 -0
- package/src/mcp-ui/board/bridge.js +165 -0
- package/src/mcp-ui/board/controls.js +310 -0
- package/src/mcp-ui/board/core.js +20 -0
- package/src/mcp-ui/board/lifecycle.js +118 -0
- package/src/mcp-ui/board/normalize.js +95 -0
- package/src/mcp-ui/board/render.js +200 -0
- package/src/mcp-ui/board/state.js +106 -0
- package/src/mcp-ui/board/vendors.js +86 -0
- package/src/mcp.js +15 -21
- package/src/{server.js → server/board.js} +17 -781
- package/src/server/files.js +141 -0
- package/src/server/http.js +114 -0
- package/src/server/index.js +2 -0
- package/src/server/page.js +183 -0
- package/src/server/paths.js +7 -0
- package/src/server/result.js +58 -0
- package/src/server/reviews.js +41 -0
- package/src/server/sanitize.js +231 -0
- package/src/spec/blocks/a2ui.js +25 -0
- package/src/spec/blocks/chart.js +49 -0
- package/src/spec/blocks/code.js +38 -0
- package/src/spec/blocks/diagram.js +39 -0
- package/src/spec/blocks/git-conflict.js +106 -0
- package/src/spec/blocks/image.js +32 -0
- package/src/spec/blocks/index.js +33 -0
- package/src/spec/blocks/markdown.js +13 -0
- package/src/spec/blocks/pdf.js +38 -0
- package/src/spec/blocks/table.js +122 -0
- package/src/spec/blocks/video.js +68 -0
- package/src/spec/blocks/widgets.js +98 -0
- package/src/spec/constants.js +65 -0
- package/src/spec/index.js +5 -0
- package/src/spec/normalize.js +285 -0
- package/src/spec/ready.js +106 -0
- package/src/spec/schema.js +182 -0
- package/src/spec/sources.js +83 -0
- package/src/ui/annotate/api.js +149 -0
- package/src/ui/annotate/badges.js +77 -0
- package/src/ui/annotate/chrome.js +158 -0
- package/src/ui/annotate/core.js +134 -0
- package/src/ui/annotate/highlights.js +129 -0
- package/src/ui/annotate/mutations.js +127 -0
- package/src/ui/annotate/popover.js +206 -0
- package/src/ui/annotate/summary.js +67 -0
- package/src/ui/app/annotations.js +88 -0
- package/src/ui/app/autosave.js +44 -0
- package/src/ui/app/core.js +74 -0
- package/src/ui/app/drafts.js +201 -0
- package/src/ui/app/heartbeat.js +150 -0
- package/src/ui/app/iframe-bridge.js +64 -0
- package/src/ui/app/persistence.js +117 -0
- package/src/ui/app/prefilled.js +21 -0
- package/src/ui/app/presence.js +38 -0
- package/src/ui/app/question-color.js +67 -0
- package/src/ui/app/questions.js +360 -0
- package/src/ui/app/render.js +135 -0
- package/src/ui/app/share.js +108 -0
- package/src/ui/app/submit.js +109 -0
- package/src/ui/app/theme.js +63 -0
- package/src/ui/blocks/api.js +1 -0
- package/src/ui/blocks/chart.js +222 -0
- package/src/ui/blocks/code.js +138 -0
- package/src/ui/blocks/compare.js +82 -0
- package/src/ui/blocks/core.js +74 -0
- package/src/ui/blocks/diff.js +361 -0
- package/src/ui/blocks/dispatch.js +111 -0
- package/src/ui/blocks/file-links.js +180 -0
- package/src/ui/blocks/git-conflict.js +151 -0
- package/src/ui/blocks/graphviz.js +57 -0
- package/src/ui/blocks/html.js +45 -0
- package/src/ui/blocks/image.js +371 -0
- package/src/ui/blocks/kpi.js +26 -0
- package/src/ui/blocks/markdown.js +223 -0
- package/src/ui/blocks/mermaid.js +242 -0
- package/src/ui/blocks/palette.js +59 -0
- package/src/ui/blocks/pdf.js +21 -0
- package/src/ui/blocks/plantuml.js +152 -0
- package/src/ui/blocks/table.js +155 -0
- package/src/ui/blocks/typography.js +25 -0
- package/src/ui/blocks/vendor.js +43 -0
- package/src/ui/blocks/video.js +43 -0
- package/src/ui/blocks/viewer-fullscreen.js +146 -0
- package/src/ui/blocks/viewer.js +324 -0
- package/src/ui/kit.js +1 -0
- package/src/ui/manifest.js +140 -0
- package/types/a2ui/compile.d.ts +40 -0
- package/types/index.d.ts +181 -0
- package/types/mcp.d.ts +31 -0
- package/types/spec/blocks/a2ui.d.ts +4 -0
- package/types/spec/blocks/chart.d.ts +4 -0
- package/types/spec/blocks/code.d.ts +10 -0
- package/types/spec/blocks/diagram.d.ts +15 -0
- package/types/spec/blocks/git-conflict.d.ts +7 -0
- package/types/spec/blocks/image.d.ts +5 -0
- package/types/spec/blocks/index.d.ts +30 -0
- package/types/spec/blocks/markdown.d.ts +5 -0
- package/types/spec/blocks/pdf.d.ts +4 -0
- package/types/spec/blocks/table.d.ts +9 -0
- package/types/spec/blocks/video.d.ts +4 -0
- package/types/spec/blocks/widgets.d.ts +21 -0
- package/types/spec/constants.d.ts +67 -0
- package/types/spec/index.d.ts +4 -0
- package/types/spec/normalize.d.ts +17 -0
- package/types/spec/ready.d.ts +1 -0
- package/types/spec/schema.d.ts +1171 -0
- package/types/spec/sources.d.ts +14 -0
- package/types/store.d.ts +29 -0
- package/types/ui/manifest.d.ts +62 -0
- package/types/util.d.ts +6 -0
- package/src/cli.js +0 -1766
- package/src/mcp-ui/board.js +0 -1162
- package/src/spec.js +0 -1222
- package/src/ui/annotate.js +0 -1055
- package/src/ui/app.js +0 -1643
- package/src/ui/blocks.js +0 -3260
package/src/ui/app.js
DELETED
|
@@ -1,1643 +0,0 @@
|
|
|
1
|
-
(() => {
|
|
2
|
-
'use strict';
|
|
3
|
-
|
|
4
|
-
const boot = JSON.parse(document.getElementById('boot').textContent);
|
|
5
|
-
const spec = boot.spec;
|
|
6
|
-
const responseRequired = spec.responseRequired !== false;
|
|
7
|
-
const access = boot.access || {
|
|
8
|
-
role: 'owner',
|
|
9
|
-
canShare: true,
|
|
10
|
-
canSubmit: true,
|
|
11
|
-
canEditAnswers: true,
|
|
12
|
-
canComment: true,
|
|
13
|
-
canEditComments: true,
|
|
14
|
-
canDeleteComments: true,
|
|
15
|
-
canEditBlocks: true,
|
|
16
|
-
canFinalize: true,
|
|
17
|
-
};
|
|
18
|
-
if (access.role) document.documentElement.dataset.accessRole = access.role;
|
|
19
|
-
const QS = spec.questions || [];
|
|
20
|
-
const app = document.getElementById('app');
|
|
21
|
-
const banner = document.getElementById('banner');
|
|
22
|
-
// Live-update baseline: the server's rev at page-build time. The heartbeat
|
|
23
|
-
// compares /api/status.rev to this and reloads the board when it advances
|
|
24
|
-
// (an agent ran `rly update`).
|
|
25
|
-
const bootRev = typeof boot.rev === 'number' ? boot.rev : null;
|
|
26
|
-
let seenDraftRev = typeof boot.draftRev === 'number' ? boot.draftRev : 0;
|
|
27
|
-
|
|
28
|
-
function authHeaders(extra = {}) {
|
|
29
|
-
const headers = access.token ? { ...extra, 'x-relay-share-token': access.token } : { ...extra };
|
|
30
|
-
if (access.reviewSessionId) headers['x-relay-review-session'] = access.reviewSessionId;
|
|
31
|
-
return headers;
|
|
32
|
-
}
|
|
33
|
-
const canPersistFeedback = responseRequired && Boolean(access.canEditAnswers || access.canComment || access.canEditBlocks);
|
|
34
|
-
|
|
35
|
-
// ---------- helpers ----------
|
|
36
|
-
function el(tag, attrs = {}, ...children) {
|
|
37
|
-
const n = document.createElement(tag);
|
|
38
|
-
for (const [k, v] of Object.entries(attrs)) {
|
|
39
|
-
if (v === undefined || v === null) continue;
|
|
40
|
-
if (k === 'class') n.className = v;
|
|
41
|
-
else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);
|
|
42
|
-
else n.setAttribute(k, v);
|
|
43
|
-
}
|
|
44
|
-
for (const c of children.flat()) {
|
|
45
|
-
if (c !== null && c !== undefined) n.append(c.nodeType ? c : document.createTextNode(c));
|
|
46
|
-
}
|
|
47
|
-
return n;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Small, self-dismissing toast pinned to the top-center of the viewport.
|
|
51
|
-
// Used to flag a live `rly update` after the reload (accent-soft bg).
|
|
52
|
-
function showToast(message) {
|
|
53
|
-
const toast = el('div', { class: 'toast' }, message);
|
|
54
|
-
document.body.append(toast);
|
|
55
|
-
setTimeout(() => toast.remove(), 4000);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// True once the board has soft-timed-out (the agent stopped waiting) or the
|
|
59
|
-
// live connection dropped — used to tailor the post-submit message. The board
|
|
60
|
-
// stays fully usable either way; we never disable Submit.
|
|
61
|
-
let handedBack = false;
|
|
62
|
-
// Calm, persistent status notes (the #banner stack). tone 'info' is the
|
|
63
|
-
// default neutral style; 'warn' is a softer amber, NOT the old red error.
|
|
64
|
-
// Each message is shown at most once so the heartbeat can call it every tick.
|
|
65
|
-
const notesShown = new Set();
|
|
66
|
-
function showNotice(message, tone) {
|
|
67
|
-
if (notesShown.has(message)) return;
|
|
68
|
-
notesShown.add(message);
|
|
69
|
-
if (banner.dataset.ready !== '1') {
|
|
70
|
-
banner.replaceChildren();
|
|
71
|
-
banner.dataset.ready = '1';
|
|
72
|
-
}
|
|
73
|
-
banner.className = 'banner-stack';
|
|
74
|
-
banner.append(el('div', { class: 'banner-item ' + (tone === 'warn' ? 'warn' : 'info') }, message));
|
|
75
|
-
banner.style.display = 'block';
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// ---------- theme (auto -> light -> dark) ----------
|
|
79
|
-
// Server-side pref wins: boards run on random ports, so localStorage alone
|
|
80
|
-
// can't carry the choice across boards. The server persists it globally.
|
|
81
|
-
const THEME_KEY = 'qb-theme';
|
|
82
|
-
const THEMES = ['auto', 'light', 'dark'];
|
|
83
|
-
let theme = (boot.pref && boot.pref.theme) || localStorage.getItem(THEME_KEY);
|
|
84
|
-
if (!THEMES.includes(theme)) theme = 'auto';
|
|
85
|
-
function effectiveTheme() {
|
|
86
|
-
if (theme !== 'auto') return theme;
|
|
87
|
-
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
|
88
|
-
}
|
|
89
|
-
function applyTheme() {
|
|
90
|
-
if (theme === 'auto') delete document.documentElement.dataset.theme;
|
|
91
|
-
else document.documentElement.dataset.theme = theme;
|
|
92
|
-
if (themeBtn) themeBtn.textContent = { auto: '◐ auto', light: '☀ light', dark: '☾ dark' }[theme];
|
|
93
|
-
// Custom-HTML iframes get ?theme=light|dark so authors can match the theme.
|
|
94
|
-
for (const f of document.querySelectorAll('iframe.viz')) {
|
|
95
|
-
try {
|
|
96
|
-
const u = new URL(f.src);
|
|
97
|
-
if (u.searchParams.get('theme') !== effectiveTheme()) {
|
|
98
|
-
u.searchParams.set('theme', effectiveTheme());
|
|
99
|
-
f.src = u.toString();
|
|
100
|
-
}
|
|
101
|
-
} catch {
|
|
102
|
-
// ignore malformed src
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
// Re-theme native blocks (mermaid re-render, chart grid/tick restyle).
|
|
106
|
-
if (window.RelayBlocks && typeof RelayBlocks.onThemeChange === 'function') {
|
|
107
|
-
try {
|
|
108
|
-
RelayBlocks.onThemeChange(effectiveTheme());
|
|
109
|
-
} catch {
|
|
110
|
-
// blocks may not be rendered yet
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
let themeBtn = null;
|
|
115
|
-
|
|
116
|
-
// ---------- font scale (A− / A+) ----------
|
|
117
|
-
// A page-zoom knob: scales the root font-size (every rem) so the whole board
|
|
118
|
-
// grows/shrinks. Persists like the theme — server pref + localStorage mirror —
|
|
119
|
-
// so the choice carries across the random-port boards.
|
|
120
|
-
const FS_KEY = 'qb-fontscale';
|
|
121
|
-
const FS_MIN = 0.85, FS_MAX = 1.5, FS_STEP = 0.1;
|
|
122
|
-
let fontScale = Number((boot.pref && boot.pref.fontScale) || localStorage.getItem(FS_KEY));
|
|
123
|
-
if (!Number.isFinite(fontScale) || fontScale <= 0) fontScale = 1;
|
|
124
|
-
const clampFs = (n) => Math.min(FS_MAX, Math.max(FS_MIN, Math.round(n * 100) / 100));
|
|
125
|
-
fontScale = clampFs(fontScale);
|
|
126
|
-
function applyFontScale() {
|
|
127
|
-
document.documentElement.style.setProperty('--fs', String(fontScale));
|
|
128
|
-
}
|
|
129
|
-
function setFontScale(next) {
|
|
130
|
-
fontScale = clampFs(next);
|
|
131
|
-
applyFontScale();
|
|
132
|
-
try { localStorage.setItem(FS_KEY, String(fontScale)); } catch { /* private mode */ }
|
|
133
|
-
fetch('/api/pref', {
|
|
134
|
-
method: 'POST',
|
|
135
|
-
headers: { 'content-type': 'application/json' },
|
|
136
|
-
body: JSON.stringify({ fontScale }),
|
|
137
|
-
}).catch(() => {});
|
|
138
|
-
}
|
|
139
|
-
applyFontScale();
|
|
140
|
-
|
|
141
|
-
// ---------- localStorage draft mirror ----------
|
|
142
|
-
// Every autosave is ALSO written to localStorage, keyed by board id + access
|
|
143
|
-
// role/session. This keeps a reviewer side draft from leaking into a
|
|
144
|
-
// collaborator/read-only tab on the same LAN origin.
|
|
145
|
-
// the durability layer the server file alone can't provide: if the connection
|
|
146
|
-
// drops and the user keeps typing, the in-memory state is mirrored locally, so
|
|
147
|
-
// even a tab reload / browser restart / a freshly opened tab on the same board
|
|
148
|
-
// prefills the LATEST input instead of a blank board or a stale server save.
|
|
149
|
-
// Guards (per design): newest-of-(local,server) wins; the mirror is discarded
|
|
150
|
-
// if the board's spec rev changed (agent edited it); cleared on submit.
|
|
151
|
-
const LOCAL_DRAFT_KEY = 'relay-draft-' + (boot.boardId || 'unknown') + '-' +
|
|
152
|
-
(access.role || 'owner') + (access.reviewSessionId ? '-' + access.reviewSessionId : '');
|
|
153
|
-
function writeLocalDraft(p, updatedAt) {
|
|
154
|
-
try {
|
|
155
|
-
localStorage.setItem(LOCAL_DRAFT_KEY, JSON.stringify({
|
|
156
|
-
v: 1,
|
|
157
|
-
boardId: boot.boardId,
|
|
158
|
-
rev: bootRev,
|
|
159
|
-
updatedAt: updatedAt || new Date().toISOString(),
|
|
160
|
-
payload: p,
|
|
161
|
-
}));
|
|
162
|
-
} catch {
|
|
163
|
-
// localStorage may be full or unavailable (privacy mode) — non-fatal; the
|
|
164
|
-
// server file remains the primary persistence path.
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
function clearLocalDraft() {
|
|
168
|
-
try { localStorage.removeItem(LOCAL_DRAFT_KEY); } catch { /* non-fatal */ }
|
|
169
|
-
}
|
|
170
|
-
// Returns the saved local mirror only if it's valid for THIS board+rev,
|
|
171
|
-
// otherwise null (and clears a now-stale entry). rev mismatch ⇒ the agent
|
|
172
|
-
// re-published the board, so old local answers may not map — discard them.
|
|
173
|
-
function loadLocalDraft() {
|
|
174
|
-
let raw;
|
|
175
|
-
try { raw = localStorage.getItem(LOCAL_DRAFT_KEY); } catch { return null; }
|
|
176
|
-
if (!raw) return null;
|
|
177
|
-
let obj;
|
|
178
|
-
try { obj = JSON.parse(raw); } catch { clearLocalDraft(); return null; }
|
|
179
|
-
if (!obj || obj.boardId !== boot.boardId || !obj.payload || typeof obj.payload !== 'object') {
|
|
180
|
-
clearLocalDraft();
|
|
181
|
-
return null;
|
|
182
|
-
}
|
|
183
|
-
// rev-guard: a changed spec rev means the local answers may reference a
|
|
184
|
-
// different question set — don't resurrect them.
|
|
185
|
-
if (bootRev !== null && obj.rev !== undefined && obj.rev !== null && obj.rev !== bootRev) {
|
|
186
|
-
clearLocalDraft();
|
|
187
|
-
return null;
|
|
188
|
-
}
|
|
189
|
-
return obj;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// Choose the prefill source: the NEWER of the server draft (boot.prefill) and
|
|
193
|
-
// the local mirror. The server draft shape mirrors a payload() plus updatedAt.
|
|
194
|
-
function chooseInitialPrefill() {
|
|
195
|
-
const server = boot.prefill || null;
|
|
196
|
-
const local = loadLocalDraft();
|
|
197
|
-
if (!local) return server;
|
|
198
|
-
if (!server) return { ...local.payload, __from: 'local' };
|
|
199
|
-
const sT = Date.parse(server.updatedAt || '') || 0;
|
|
200
|
-
const lT = Date.parse(local.updatedAt || '') || 0;
|
|
201
|
-
// Newest wins; ties favor local (the tab that was last typing into).
|
|
202
|
-
return lT >= sT ? { ...local.payload, __from: 'local' } : server;
|
|
203
|
-
}
|
|
204
|
-
const initialPrefill = chooseInitialPrefill();
|
|
205
|
-
|
|
206
|
-
// ---------- state ----------
|
|
207
|
-
// state.answers holds raw control state; state.other holds the "Other"
|
|
208
|
-
// free-text per question; getValue() derives the final answer value.
|
|
209
|
-
// state.annotations holds element-level comments (managed by RelayAnnotate).
|
|
210
|
-
const state = {
|
|
211
|
-
answers: {},
|
|
212
|
-
other: {},
|
|
213
|
-
notes: {},
|
|
214
|
-
comment: '',
|
|
215
|
-
annotations: (initialPrefill && initialPrefill.annotations) || [],
|
|
216
|
-
// Editable-mermaid edits: blockId -> edited source. Seeded from the live
|
|
217
|
-
// draft so a reload/reopen restores the user's edited diagram. Mutated via
|
|
218
|
-
// the blocks ctx.onBlockEdit callback below; returned in payload().
|
|
219
|
-
blockEdits: (initialPrefill && initialPrefill.blockEdits) || {},
|
|
220
|
-
};
|
|
221
|
-
let submitted = false;
|
|
222
|
-
|
|
223
|
-
function seedFromPrefill(prefill) {
|
|
224
|
-
state.comment = prefill.comment || '';
|
|
225
|
-
if (prefill.notes && typeof prefill.notes === 'object') state.notes = { ...prefill.notes };
|
|
226
|
-
const ans = prefill.answers || {};
|
|
227
|
-
for (const q of QS) {
|
|
228
|
-
const v = ans[q.id];
|
|
229
|
-
if (v === undefined || v === null) continue;
|
|
230
|
-
if (q.type === 'multi' && Array.isArray(v)) {
|
|
231
|
-
const known = new Set((q.options || []).map((o) => o.value));
|
|
232
|
-
state.answers[q.id] = v.filter((x) => known.has(x));
|
|
233
|
-
const extra = v.filter((x) => !known.has(x));
|
|
234
|
-
if (extra.length && q.other) state.other[q.id] = { on: true, text: extra.join(', ') };
|
|
235
|
-
} else if (q.type === 'single' && typeof v === 'string') {
|
|
236
|
-
if ((q.options || []).some((o) => o.value === v)) state.answers[q.id] = v;
|
|
237
|
-
else if (q.other) state.other[q.id] = { on: true, text: v };
|
|
238
|
-
} else {
|
|
239
|
-
state.answers[q.id] = v;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
// Coerce any prior rank value (draft/default) into a complete, deduped
|
|
244
|
-
// permutation of the option values: keep the known ones in their given order,
|
|
245
|
-
// then append any options the prior list missed (in authored order).
|
|
246
|
-
function seedRankOrder(q, prior) {
|
|
247
|
-
const opts = (q.options || []).map((o) => o.value);
|
|
248
|
-
const arr = Array.isArray(prior) ? prior : [];
|
|
249
|
-
const order = arr.filter((v, i) => opts.includes(v) && arr.indexOf(v) === i);
|
|
250
|
-
for (const v of opts) if (!order.includes(v)) order.push(v);
|
|
251
|
-
return order;
|
|
252
|
-
}
|
|
253
|
-
// Allocate: a complete map {optionValue: number≥0}, seeded from a prior/default.
|
|
254
|
-
function seedAllocate(q, prior) {
|
|
255
|
-
const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
|
|
256
|
-
const out = {};
|
|
257
|
-
for (const o of q.options || []) out[o.value] = Math.max(0, Number(m[o.value]) || 0);
|
|
258
|
-
return out;
|
|
259
|
-
}
|
|
260
|
-
// Checklist: keep only {knownOption: knownStatus} entries from a prior/default.
|
|
261
|
-
function seedChecklist(q, prior) {
|
|
262
|
-
const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
|
|
263
|
-
const optVals = new Set((q.options || []).map((o) => o.value));
|
|
264
|
-
const stVals = new Set((q.statuses || []).map((s) => s.value));
|
|
265
|
-
const out = {};
|
|
266
|
-
for (const k of Object.keys(m)) if (optVals.has(k) && stVals.has(m[k])) out[k] = m[k];
|
|
267
|
-
return out;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
if (initialPrefill) seedFromPrefill(initialPrefill);
|
|
271
|
-
else for (const q of QS) if (q.default !== undefined) state.answers[q.id] = q.default;
|
|
272
|
-
// Rank questions always carry a full, valid permutation of their option values
|
|
273
|
-
// (from a draft/default if present, else the authored order), so a never-touched
|
|
274
|
-
// rank still returns a meaningful ordering.
|
|
275
|
-
for (const q of QS) if (q.type === 'rank') state.answers[q.id] = seedRankOrder(q, state.answers[q.id]);
|
|
276
|
-
for (const q of QS) if (q.type === 'allocate') state.answers[q.id] = seedAllocate(q, state.answers[q.id]);
|
|
277
|
-
for (const q of QS) if (q.type === 'checklist') state.answers[q.id] = seedChecklist(q, state.answers[q.id]);
|
|
278
|
-
// If the local mirror was newer than the server (or the server had nothing),
|
|
279
|
-
// the in-memory state now holds input the server hasn't seen — flush it once
|
|
280
|
-
// the rest of the app is wired (see the post-init flush near the heartbeat).
|
|
281
|
-
|
|
282
|
-
function getValue(q) {
|
|
283
|
-
const v = state.answers[q.id];
|
|
284
|
-
const oth = state.other[q.id];
|
|
285
|
-
switch (q.type) {
|
|
286
|
-
case 'single': {
|
|
287
|
-
if (oth && oth.on) {
|
|
288
|
-
const t = (oth.text || '').trim();
|
|
289
|
-
return t || undefined;
|
|
290
|
-
}
|
|
291
|
-
return typeof v === 'string' && v ? v : undefined;
|
|
292
|
-
}
|
|
293
|
-
case 'multi': {
|
|
294
|
-
const arr = Array.isArray(v) ? [...v] : [];
|
|
295
|
-
if (oth && oth.on) {
|
|
296
|
-
const t = (oth.text || '').trim();
|
|
297
|
-
if (t) arr.push(t);
|
|
298
|
-
}
|
|
299
|
-
return arr.length ? arr : undefined;
|
|
300
|
-
}
|
|
301
|
-
case 'yesno':
|
|
302
|
-
return v === 'yes' || v === 'no' ? v : undefined;
|
|
303
|
-
case 'scale':
|
|
304
|
-
return typeof v === 'number' ? v : undefined;
|
|
305
|
-
case 'rank':
|
|
306
|
-
// always a full, valid permutation (seeded below) → always answered
|
|
307
|
-
return Array.isArray(v) && v.length ? [...v] : undefined;
|
|
308
|
-
case 'checklist': {
|
|
309
|
-
const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
310
|
-
return Object.keys(m).length ? { ...m } : undefined;
|
|
311
|
-
}
|
|
312
|
-
case 'allocate': {
|
|
313
|
-
const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
314
|
-
const sum = Object.values(m).reduce((a, n) => a + (Number(n) || 0), 0);
|
|
315
|
-
return sum > 0 ? { ...m } : undefined;
|
|
316
|
-
}
|
|
317
|
-
default: {
|
|
318
|
-
const t = typeof v === 'string' ? v.trim() : '';
|
|
319
|
-
return t || undefined;
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
function payload() {
|
|
325
|
-
const answers = {};
|
|
326
|
-
const notes = {};
|
|
327
|
-
for (const q of QS) {
|
|
328
|
-
const v = getValue(q);
|
|
329
|
-
if (v !== undefined) answers[q.id] = v;
|
|
330
|
-
const n = typeof state.notes[q.id] === 'string' ? state.notes[q.id].trim() : '';
|
|
331
|
-
if (n) notes[q.id] = n;
|
|
332
|
-
}
|
|
333
|
-
return {
|
|
334
|
-
answers,
|
|
335
|
-
comment: (state.comment || '').trim(),
|
|
336
|
-
notes,
|
|
337
|
-
annotations: state.annotations,
|
|
338
|
-
blockEdits: state.blockEdits,
|
|
339
|
-
};
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
// ---------- persistence-lost block ----------
|
|
343
|
-
// The dead-end this guards against: the client can lose its connection to the
|
|
344
|
-
// board's local HTTP server (server gone, port taken over, socket dropped,
|
|
345
|
-
// machine slept). Autosaves then fail silently and the user keeps typing
|
|
346
|
-
// answers/comments that are never persisted, then Submit fails too — all of it
|
|
347
|
-
// thrown away. When persistence is CONFIRMED lost we DISABLE every control (and
|
|
348
|
-
// freeze new comments) and show a small, non-dismissable top-right notice with
|
|
349
|
-
// a Reconnect button — without blocking the page, so the user can still read
|
|
350
|
-
// and scroll. Local `state` is never touched, and a mid-typed comment is saved
|
|
351
|
-
// before the freeze, so nothing the user entered during the outage is lost; the
|
|
352
|
-
// moment the connection recovers we flush state and re-enable everything.
|
|
353
|
-
let persistenceLost = false;
|
|
354
|
-
let probing = false;
|
|
355
|
-
let lostNote = null;
|
|
356
|
-
let lostRetryBtn = null;
|
|
357
|
-
|
|
358
|
-
// A direct, side-effect-free reachability probe. Resolves true when the local
|
|
359
|
-
// server answers /api/status, false on any network/HTTP failure. Used to
|
|
360
|
-
// CONFIRM loss before blocking (so a single dropped request never blocks) and
|
|
361
|
-
// to detect recovery from the Retry button / heartbeat.
|
|
362
|
-
async function probeServer() {
|
|
363
|
-
try {
|
|
364
|
-
const r = await fetch('/api/status', { cache: 'no-store', headers: authHeaders() });
|
|
365
|
-
return r.ok;
|
|
366
|
-
} catch {
|
|
367
|
-
return false;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
function buildLostNote() {
|
|
372
|
-
if (lostNote) return lostNote;
|
|
373
|
-
lostRetryBtn = el('button', { class: 'lost-retry', type: 'button' }, 'Reconnect');
|
|
374
|
-
lostRetryBtn.addEventListener('click', retryConnection);
|
|
375
|
-
lostNote = el('div', { class: 'lost-note', role: 'status', 'aria-live': 'polite' },
|
|
376
|
-
el('span', { class: 'lost-note-dot', 'aria-hidden': 'true' }),
|
|
377
|
-
el('div', { class: 'lost-note-body' },
|
|
378
|
-
el('div', { class: 'lost-note-title' }, 'Connection lost'),
|
|
379
|
-
el('div', { class: 'lost-note-sub' }, 'Editing paused — your input is kept.')
|
|
380
|
-
),
|
|
381
|
-
lostRetryBtn
|
|
382
|
-
);
|
|
383
|
-
return lostNote;
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// Enter the blocked state: save a mid-typed comment, freeze comments, disable
|
|
387
|
-
// controls, and pin the small notice. Idempotent. Does NOT block the page —
|
|
388
|
-
// the user can still read and scroll; only editing is paused.
|
|
389
|
-
function blockForLostPersistence() {
|
|
390
|
-
if (persistenceLost || submitted) return;
|
|
391
|
-
persistenceLost = true;
|
|
392
|
-
document.documentElement.classList.add('relay-blocked');
|
|
393
|
-
// Save whatever the user was typing into the comment popover BEFORE freezing
|
|
394
|
-
// it, so the in-progress comment is kept (in `state` + localStorage) instead
|
|
395
|
-
// of discarded; then stop any new comment from being started.
|
|
396
|
-
if (Annotate) {
|
|
397
|
-
if (typeof Annotate.flushOpen === 'function') { try { Annotate.flushOpen(); } catch { /* non-fatal */ } }
|
|
398
|
-
if (typeof Annotate.setDisabled === 'function') { try { Annotate.setDisabled(true); } catch { /* non-fatal */ } }
|
|
399
|
-
}
|
|
400
|
-
// Disable every interactive control inside the form. Values already entered
|
|
401
|
-
// stay in the DOM (and in `state`), so nothing typed so far is lost.
|
|
402
|
-
for (const node of app.querySelectorAll('input, textarea, button, select')) {
|
|
403
|
-
node.disabled = true;
|
|
404
|
-
}
|
|
405
|
-
document.body.append(buildLostNote());
|
|
406
|
-
if (saveEl) saveEl.textContent = 'connection lost — not saving';
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
// Leave the blocked state: re-enable controls + comments, drop the notice, and
|
|
410
|
-
// flush whatever the user typed during the outage so it's persisted right away.
|
|
411
|
-
function unblockAfterRecovery() {
|
|
412
|
-
if (!persistenceLost) return;
|
|
413
|
-
persistenceLost = false;
|
|
414
|
-
document.documentElement.classList.remove('relay-blocked');
|
|
415
|
-
if (Annotate && typeof Annotate.setDisabled === 'function') { try { Annotate.setDisabled(false); } catch { /* non-fatal */ } }
|
|
416
|
-
for (const node of app.querySelectorAll('input, textarea, button, select')) {
|
|
417
|
-
node.disabled = false;
|
|
418
|
-
}
|
|
419
|
-
applyAccessRestrictions();
|
|
420
|
-
if (lostNote) lostNote.remove();
|
|
421
|
-
// Re-arm the heartbeat (it stops itself when it confirms loss) and persist
|
|
422
|
-
// everything typed during the outage. saveDraft() updates the save label.
|
|
423
|
-
startHeartbeat();
|
|
424
|
-
misses = 0;
|
|
425
|
-
saveFailures = 0;
|
|
426
|
-
saveDraft();
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
// Retry button: probe once; recover on success, otherwise tell the user it's
|
|
430
|
-
// still down (without un-blocking).
|
|
431
|
-
async function retryConnection() {
|
|
432
|
-
if (probing) return;
|
|
433
|
-
probing = true;
|
|
434
|
-
if (lostRetryBtn) { lostRetryBtn.disabled = true; lostRetryBtn.textContent = 'Checking…'; }
|
|
435
|
-
const ok = await probeServer();
|
|
436
|
-
probing = false;
|
|
437
|
-
if (lostRetryBtn) { lostRetryBtn.disabled = false; lostRetryBtn.textContent = 'Retry connection'; }
|
|
438
|
-
if (ok) unblockAfterRecovery();
|
|
439
|
-
else if (lostRetryBtn) {
|
|
440
|
-
lostRetryBtn.textContent = 'Still unreachable — try again';
|
|
441
|
-
setTimeout(() => { if (lostRetryBtn && persistenceLost) lostRetryBtn.textContent = 'Retry connection'; }, 2500);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
// Called when a save/heartbeat fails. Confirms loss with a probe (so one
|
|
446
|
-
// dropped request never blocks) before hard-blocking. `force` skips the probe
|
|
447
|
-
// for callers (the heartbeat) that already represent repeated failures.
|
|
448
|
-
async function considerPersistenceLost(force) {
|
|
449
|
-
if (persistenceLost || submitted || probing) return;
|
|
450
|
-
if (!force) {
|
|
451
|
-
probing = true;
|
|
452
|
-
const ok = await probeServer();
|
|
453
|
-
probing = false;
|
|
454
|
-
if (ok || persistenceLost || submitted) return; // recovered or already handled
|
|
455
|
-
}
|
|
456
|
-
blockForLostPersistence();
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
// ---------- real-time autosave ----------
|
|
460
|
-
let saveTimer = null;
|
|
461
|
-
let saveSeq = 0;
|
|
462
|
-
let saveEl = null;
|
|
463
|
-
// Consecutive failed /api/draft saves. Two in a row triggers a confirming
|
|
464
|
-
// probe → block. Any success resets it.
|
|
465
|
-
let saveFailures = 0;
|
|
466
|
-
function scheduleSave() {
|
|
467
|
-
if (submitted || !canPersistFeedback) return;
|
|
468
|
-
// Mirror to localStorage SYNCHRONOUSLY on every edit, before (and regardless
|
|
469
|
-
// of) the network save. This is what survives a tab reload / crash / a new
|
|
470
|
-
// tab during a connection outage — it must happen even while blocked.
|
|
471
|
-
writeLocalDraft(payload());
|
|
472
|
-
if (persistenceLost) return; // network save is futile while disconnected
|
|
473
|
-
if (saveEl) saveEl.textContent = 'saving…';
|
|
474
|
-
clearTimeout(saveTimer);
|
|
475
|
-
saveTimer = setTimeout(saveDraft, 450);
|
|
476
|
-
}
|
|
477
|
-
async function saveDraft() {
|
|
478
|
-
if (!canPersistFeedback) return;
|
|
479
|
-
const seq = ++saveSeq;
|
|
480
|
-
// Keep the local mirror current on every flush too (covers programmatic
|
|
481
|
-
// saveDraft() calls that don't go through scheduleSave, e.g. recovery flush).
|
|
482
|
-
writeLocalDraft(payload());
|
|
483
|
-
try {
|
|
484
|
-
const r = await fetch('/api/draft', {
|
|
485
|
-
method: 'POST',
|
|
486
|
-
headers: authHeaders({ 'content-type': 'application/json' }),
|
|
487
|
-
body: JSON.stringify(payload()),
|
|
488
|
-
});
|
|
489
|
-
if (!r.ok) throw new Error('draft rejected');
|
|
490
|
-
const body = await r.json().catch(() => null);
|
|
491
|
-
if (body && typeof body.draftRev === 'number') seenDraftRev = body.draftRev;
|
|
492
|
-
saveFailures = 0;
|
|
493
|
-
if (seq === saveSeq && saveEl && !submitted && !persistenceLost) saveEl.textContent = 'draft saved ✓';
|
|
494
|
-
} catch {
|
|
495
|
-
if (seq === saveSeq && saveEl && !submitted && !persistenceLost) saveEl.textContent = 'draft save failed';
|
|
496
|
-
// A save couldn't be persisted to the SERVER — the core data-loss signal.
|
|
497
|
-
// (The local mirror above still captured it.) After two in a row, confirm
|
|
498
|
-
// with a probe and block so the user stops typing into the void.
|
|
499
|
-
if (++saveFailures >= 2) considerPersistenceLost(false);
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
// ---------- presence / awareness ----------
|
|
504
|
-
// Track the last time the user interacted with the page so the agent (via
|
|
505
|
-
// /api/presence) can tell whether someone is still actively viewing the board
|
|
506
|
-
// and keep waiting instead of timing out. Every existing 3s heartbeat tick
|
|
507
|
-
// also POSTs /api/ping {visible, focused, idleMs}; pinging stops after submit.
|
|
508
|
-
let lastInteractionAt = Date.now();
|
|
509
|
-
let lastMoveAt = 0;
|
|
510
|
-
function noteInteraction() {
|
|
511
|
-
lastInteractionAt = Date.now();
|
|
512
|
-
}
|
|
513
|
-
window.addEventListener('pointerdown', noteInteraction, { passive: true });
|
|
514
|
-
window.addEventListener('keydown', noteInteraction, { passive: true });
|
|
515
|
-
window.addEventListener('scroll', noteInteraction, { passive: true });
|
|
516
|
-
window.addEventListener('touchstart', noteInteraction, { passive: true });
|
|
517
|
-
// pointermove fires continuously — throttle to at most once per second.
|
|
518
|
-
window.addEventListener('pointermove', () => {
|
|
519
|
-
const now = Date.now();
|
|
520
|
-
if (now - lastMoveAt >= 1000) {
|
|
521
|
-
lastMoveAt = now;
|
|
522
|
-
lastInteractionAt = now;
|
|
523
|
-
}
|
|
524
|
-
}, { passive: true });
|
|
525
|
-
|
|
526
|
-
function pingPresence() {
|
|
527
|
-
if (submitted) return;
|
|
528
|
-
fetch('/api/ping', {
|
|
529
|
-
method: 'POST',
|
|
530
|
-
headers: authHeaders({ 'content-type': 'application/json' }),
|
|
531
|
-
body: JSON.stringify({
|
|
532
|
-
visible: !document.hidden,
|
|
533
|
-
focused: document.hasFocus(),
|
|
534
|
-
idleMs: Date.now() - lastInteractionAt,
|
|
535
|
-
}),
|
|
536
|
-
}).catch(() => {
|
|
537
|
-
// presence is best-effort — a failed ping must never surface to the user
|
|
538
|
-
});
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
// ---------- annotations ----------
|
|
542
|
-
// RelayAnnotate owns the live annotation list; mirror it into state on every
|
|
543
|
-
// change so payload()/autosave/submit carry it exactly like answers.
|
|
544
|
-
const Annotate = typeof window.RelayAnnotate !== 'undefined' ? window.RelayAnnotate : null;
|
|
545
|
-
if (Annotate && responseRequired) {
|
|
546
|
-
Annotate.init({
|
|
547
|
-
initial: state.annotations,
|
|
548
|
-
permissions: {
|
|
549
|
-
add: access.canComment !== false,
|
|
550
|
-
edit: access.canEditComments !== false,
|
|
551
|
-
delete: access.canDeleteComments !== false,
|
|
552
|
-
reply: access.canComment !== false,
|
|
553
|
-
},
|
|
554
|
-
onChange: (list) => {
|
|
555
|
-
state.annotations = list;
|
|
556
|
-
scheduleSave();
|
|
557
|
-
// Refresh per-element comment badges inside custom-HTML iframes (bridge
|
|
558
|
-
// sets this once the iframe annotate plumbing is wired below).
|
|
559
|
-
if (window.__relayBroadcastCounts) window.__relayBroadcastCounts();
|
|
560
|
-
},
|
|
561
|
-
});
|
|
562
|
-
} else if (Annotate && !responseRequired && typeof Annotate.teardown === 'function') {
|
|
563
|
-
Annotate.teardown();
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// Editable-mermaid: record (or clear) the user's edit for a block, then
|
|
567
|
-
// autosave. A null/empty code clears the entry (block matches the original
|
|
568
|
-
// again — e.g. after Reset), so payload()/draft carry only real divergences.
|
|
569
|
-
function onBlockEdit(blockId, codeOrNull) {
|
|
570
|
-
if (codeOrNull === null || codeOrNull === undefined) delete state.blockEdits[blockId];
|
|
571
|
-
else state.blockEdits[blockId] = codeOrNull;
|
|
572
|
-
scheduleSave();
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
document.addEventListener('relay:block-edit', (e) => {
|
|
576
|
-
const d = e.detail || {};
|
|
577
|
-
if (!d.blockId) return;
|
|
578
|
-
onBlockEdit(d.blockId, d.value);
|
|
579
|
-
});
|
|
580
|
-
|
|
581
|
-
async function saveRegionArtifact(artifact) {
|
|
582
|
-
const res = await fetch('/api/artifact', {
|
|
583
|
-
method: 'POST',
|
|
584
|
-
headers: authHeaders({ 'content-type': 'application/json' }),
|
|
585
|
-
body: JSON.stringify(artifact),
|
|
586
|
-
});
|
|
587
|
-
const body = await res.json().catch(() => null);
|
|
588
|
-
if (!res.ok || !body || !body.path) throw new Error(body && body.error ? body.error : 'could not save image crop');
|
|
589
|
-
return body;
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
// ctx for RelayBlocks.render — theme()/htmlSrc per the shared contract, plus
|
|
593
|
-
// the editable-mermaid plumbing (edits map + onBlockEdit callback).
|
|
594
|
-
function blockCtx(questionId) {
|
|
595
|
-
return {
|
|
596
|
-
theme: effectiveTheme,
|
|
597
|
-
htmlSrc: (blockId) => {
|
|
598
|
-
const params = new URLSearchParams({ theme: effectiveTheme() });
|
|
599
|
-
if (access.token) params.set('token', access.token);
|
|
600
|
-
return '/html/b/' + encodeURIComponent(blockId) + '?' + params.toString();
|
|
601
|
-
},
|
|
602
|
-
questionId: questionId == null ? null : questionId,
|
|
603
|
-
annotate: responseRequired ? Annotate : null,
|
|
604
|
-
canComment: responseRequired && access.canComment !== false,
|
|
605
|
-
saveArtifact: responseRequired && access.canComment !== false ? saveRegionArtifact : null,
|
|
606
|
-
edits: state.blockEdits,
|
|
607
|
-
onBlockEdit,
|
|
608
|
-
canEditBlocks: access.canEditBlocks !== false,
|
|
609
|
-
};
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
// Renders blocks async without blocking the page; on rejection (or a missing
|
|
613
|
-
// RelayBlocks) shows a muted "failed to render" card in place.
|
|
614
|
-
function renderBlocks(container, blocks, questionId) {
|
|
615
|
-
if (!Array.isArray(blocks) || !blocks.length) return;
|
|
616
|
-
const target = el('div', { class: 'blocks' });
|
|
617
|
-
container.append(target);
|
|
618
|
-
if (typeof window.RelayBlocks === 'undefined' || !window.RelayBlocks) {
|
|
619
|
-
target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
|
|
620
|
-
return;
|
|
621
|
-
}
|
|
622
|
-
Promise.resolve()
|
|
623
|
-
.then(() => window.RelayBlocks.render(target, blocks, blockCtx(questionId)))
|
|
624
|
-
.catch(() => {
|
|
625
|
-
target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
|
|
626
|
-
});
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
// ---------- controls ----------
|
|
630
|
-
const cards = {};
|
|
631
|
-
|
|
632
|
-
function clearErr(qid) {
|
|
633
|
-
if (cards[qid]) cards[qid].classList.remove('error');
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
function syncOptSel(group) {
|
|
637
|
-
for (const lab of group.querySelectorAll('label.opt')) {
|
|
638
|
-
const input = lab.querySelector('input');
|
|
639
|
-
lab.classList.toggle('sel', input.checked);
|
|
640
|
-
// options with visuals: the bordered card is the wrapper, not the label
|
|
641
|
-
const wrap = lab.closest('.optwrap');
|
|
642
|
-
if (wrap) wrap.classList.toggle('sel', input.checked);
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
// Options may carry their own blocks (visual examples of the choice). The
|
|
647
|
-
// blocks render in a wrapper card OUTSIDE the <label> so interacting with a
|
|
648
|
-
// chart/diagram/image doesn't toggle the option.
|
|
649
|
-
function withOptionBlocks(labelEl, o, questionId) {
|
|
650
|
-
if (!Array.isArray(o.blocks) || !o.blocks.length) return labelEl;
|
|
651
|
-
const wrap = el('div', { class: 'optwrap' + (labelEl.classList.contains('sel') ? ' sel' : '') }, labelEl);
|
|
652
|
-
renderBlocks(wrap, o.blocks, questionId);
|
|
653
|
-
return wrap;
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
function controlSingle(q) {
|
|
657
|
-
const group = el('div');
|
|
658
|
-
const entries = [];
|
|
659
|
-
let otherRadio = null;
|
|
660
|
-
const otherOn = () => Boolean(state.other[q.id] && state.other[q.id].on);
|
|
661
|
-
const syncSingle = () => {
|
|
662
|
-
for (const { input, value } of entries) input.checked = state.answers[q.id] === value && !otherOn();
|
|
663
|
-
if (otherRadio) otherRadio.checked = otherOn();
|
|
664
|
-
syncOptSel(group);
|
|
665
|
-
clearErr(q.id);
|
|
666
|
-
scheduleSave();
|
|
667
|
-
};
|
|
668
|
-
for (const o of q.options) {
|
|
669
|
-
const input = el('input', { type: 'radio', name: q.id });
|
|
670
|
-
entries.push({ input, value: o.value });
|
|
671
|
-
input.checked = state.answers[q.id] === o.value && !otherOn();
|
|
672
|
-
// Click-to-toggle: clicking the selected option unselects it (answers
|
|
673
|
-
// are optional by default). preventDefault keeps `checked` ours to set.
|
|
674
|
-
input.addEventListener('click', (e) => {
|
|
675
|
-
e.preventDefault();
|
|
676
|
-
if (state.answers[q.id] === o.value && !otherOn()) {
|
|
677
|
-
delete state.answers[q.id];
|
|
678
|
-
} else {
|
|
679
|
-
state.answers[q.id] = o.value;
|
|
680
|
-
if (state.other[q.id]) state.other[q.id].on = false;
|
|
681
|
-
}
|
|
682
|
-
// Defer: after a canceled activation the browser restores the
|
|
683
|
-
// pre-click checked state AFTER this handler, clobbering direct sets.
|
|
684
|
-
setTimeout(syncSingle, 0);
|
|
685
|
-
});
|
|
686
|
-
input.addEventListener('change', () => {
|
|
687
|
-
// keyboard path (arrow keys / space) — no click event fires
|
|
688
|
-
if (!input.checked) return;
|
|
689
|
-
state.answers[q.id] = o.value;
|
|
690
|
-
if (state.other[q.id]) state.other[q.id].on = false;
|
|
691
|
-
syncSingle();
|
|
692
|
-
});
|
|
693
|
-
group.append(
|
|
694
|
-
withOptionBlocks(
|
|
695
|
-
el('label', { class: 'opt' + (input.checked ? ' sel' : '') },
|
|
696
|
-
input,
|
|
697
|
-
el('div', {},
|
|
698
|
-
el('div', { class: 'ol' }, o.label),
|
|
699
|
-
o.description ? el('div', { class: 'od' }, o.description) : null
|
|
700
|
-
)
|
|
701
|
-
),
|
|
702
|
-
o,
|
|
703
|
-
q.id
|
|
704
|
-
)
|
|
705
|
-
);
|
|
706
|
-
}
|
|
707
|
-
if (q.other) {
|
|
708
|
-
otherRadio = el('input', { type: 'radio', name: q.id });
|
|
709
|
-
const text = el('textarea', { class: 'otherinput', rows: '2', placeholder: 'your own answer…' });
|
|
710
|
-
text.value = (state.other[q.id] && state.other[q.id].text) || '';
|
|
711
|
-
otherRadio.checked = otherOn();
|
|
712
|
-
const ensureOther = () => state.other[q.id] || (state.other[q.id] = { on: false, text: text.value });
|
|
713
|
-
otherRadio.addEventListener('click', (e) => {
|
|
714
|
-
e.preventDefault();
|
|
715
|
-
const oth = ensureOther();
|
|
716
|
-
oth.on = !oth.on;
|
|
717
|
-
if (oth.on) delete state.answers[q.id];
|
|
718
|
-
setTimeout(syncSingle, 0);
|
|
719
|
-
});
|
|
720
|
-
otherRadio.addEventListener('change', () => {
|
|
721
|
-
if (!otherRadio.checked) return;
|
|
722
|
-
const oth = ensureOther();
|
|
723
|
-
oth.on = true;
|
|
724
|
-
delete state.answers[q.id];
|
|
725
|
-
syncSingle();
|
|
726
|
-
});
|
|
727
|
-
text.addEventListener('input', () => {
|
|
728
|
-
const oth = ensureOther();
|
|
729
|
-
oth.text = text.value;
|
|
730
|
-
if (!oth.on) {
|
|
731
|
-
oth.on = true;
|
|
732
|
-
delete state.answers[q.id];
|
|
733
|
-
}
|
|
734
|
-
syncSingle();
|
|
735
|
-
});
|
|
736
|
-
group.append(
|
|
737
|
-
el('label', { class: 'opt' + (otherRadio.checked ? ' sel' : '') },
|
|
738
|
-
otherRadio,
|
|
739
|
-
el('div', { style: 'flex:1' }, el('div', { class: 'ol' }, 'Other'), el('div', { class: 'otherbox' }, text))
|
|
740
|
-
)
|
|
741
|
-
);
|
|
742
|
-
}
|
|
743
|
-
return group;
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
function controlMulti(q) {
|
|
747
|
-
const group = el('div');
|
|
748
|
-
const selected = new Set(Array.isArray(state.answers[q.id]) ? state.answers[q.id] : []);
|
|
749
|
-
const readChecked = () => {
|
|
750
|
-
state.answers[q.id] = [...group.querySelectorAll('input[data-val]')]
|
|
751
|
-
.filter((i) => i.checked)
|
|
752
|
-
.map((i) => i.dataset.val);
|
|
753
|
-
syncOptSel(group);
|
|
754
|
-
clearErr(q.id);
|
|
755
|
-
scheduleSave();
|
|
756
|
-
};
|
|
757
|
-
for (const o of q.options) {
|
|
758
|
-
const input = el('input', { type: 'checkbox', 'data-val': o.value });
|
|
759
|
-
input.checked = selected.has(o.value);
|
|
760
|
-
input.addEventListener('change', readChecked);
|
|
761
|
-
group.append(
|
|
762
|
-
withOptionBlocks(
|
|
763
|
-
el('label', { class: 'opt' + (input.checked ? ' sel' : '') },
|
|
764
|
-
input,
|
|
765
|
-
el('div', {},
|
|
766
|
-
el('div', { class: 'ol' }, o.label),
|
|
767
|
-
o.description ? el('div', { class: 'od' }, o.description) : null
|
|
768
|
-
)
|
|
769
|
-
),
|
|
770
|
-
o,
|
|
771
|
-
q.id
|
|
772
|
-
)
|
|
773
|
-
);
|
|
774
|
-
}
|
|
775
|
-
if (q.other) {
|
|
776
|
-
const oth = state.other[q.id];
|
|
777
|
-
const box = el('input', { type: 'checkbox' });
|
|
778
|
-
const text = el('textarea', { class: 'otherinput', rows: '2', placeholder: 'your own answer…' });
|
|
779
|
-
box.checked = Boolean(oth && oth.on);
|
|
780
|
-
text.value = (oth && oth.text) || '';
|
|
781
|
-
const sync = () => {
|
|
782
|
-
state.other[q.id] = { on: box.checked, text: text.value };
|
|
783
|
-
syncOptSel(group);
|
|
784
|
-
clearErr(q.id);
|
|
785
|
-
scheduleSave();
|
|
786
|
-
};
|
|
787
|
-
box.addEventListener('change', sync);
|
|
788
|
-
text.addEventListener('input', () => {
|
|
789
|
-
if (!box.checked) box.checked = true;
|
|
790
|
-
sync();
|
|
791
|
-
});
|
|
792
|
-
group.append(
|
|
793
|
-
el('label', { class: 'opt' + (box.checked ? ' sel' : '') },
|
|
794
|
-
box,
|
|
795
|
-
el('div', { style: 'flex:1' }, el('div', { class: 'ol' }, 'Other'), el('div', { class: 'otherbox' }, text))
|
|
796
|
-
)
|
|
797
|
-
);
|
|
798
|
-
}
|
|
799
|
-
return group;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
function segButtons(q, values, labels) {
|
|
803
|
-
const seg = el('div', { class: q.type === 'scale' ? 'scale' : 'seg' });
|
|
804
|
-
const buttons = [];
|
|
805
|
-
values.forEach((v, i) => {
|
|
806
|
-
const b = el('button', { type: 'button' }, labels[i]);
|
|
807
|
-
if (state.answers[q.id] === v) b.classList.add('sel');
|
|
808
|
-
b.addEventListener('click', () => {
|
|
809
|
-
// click again to unselect (everything is optional by default)
|
|
810
|
-
if (state.answers[q.id] === v) delete state.answers[q.id];
|
|
811
|
-
else state.answers[q.id] = v;
|
|
812
|
-
for (const x of buttons) x.classList.toggle('sel', state.answers[q.id] === values[buttons.indexOf(x)]);
|
|
813
|
-
clearErr(q.id);
|
|
814
|
-
scheduleSave();
|
|
815
|
-
});
|
|
816
|
-
buttons.push(b);
|
|
817
|
-
seg.append(b);
|
|
818
|
-
});
|
|
819
|
-
return seg;
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
function controlScale(q) {
|
|
823
|
-
const values = [];
|
|
824
|
-
for (let i = q.min; i <= q.max; i++) values.push(i);
|
|
825
|
-
const seg = segButtons(q, values, values.map(String));
|
|
826
|
-
const row = el('div', { class: 'scale' });
|
|
827
|
-
if (q.minLabel) row.append(el('span', { class: 'slabel' }, q.minLabel));
|
|
828
|
-
row.append(...seg.children);
|
|
829
|
-
if (q.maxLabel) row.append(el('span', { class: 'slabel' }, q.maxLabel));
|
|
830
|
-
return row;
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
// Reorderable priority list. The user drags an item or uses ↑/↓; the answer is
|
|
834
|
-
// the ordered array of option values (highest priority first). state.answers[q.id]
|
|
835
|
-
// is kept a full, valid permutation by seedRankOrder so it's always submittable.
|
|
836
|
-
function controlRank(q) {
|
|
837
|
-
const wrap = el('div', { class: 'rank' });
|
|
838
|
-
const byVal = new Map(q.options.map((o) => [o.value, o]));
|
|
839
|
-
let dragFrom = null;
|
|
840
|
-
function move(from, to) {
|
|
841
|
-
if (!access.canEditAnswers) return;
|
|
842
|
-
const arr = state.answers[q.id];
|
|
843
|
-
if (!Array.isArray(arr) || to < 0 || to >= arr.length || from === to) return;
|
|
844
|
-
const [x] = arr.splice(from, 1);
|
|
845
|
-
arr.splice(to, 0, x);
|
|
846
|
-
paint();
|
|
847
|
-
clearErr(q.id);
|
|
848
|
-
scheduleSave();
|
|
849
|
-
}
|
|
850
|
-
function paint() {
|
|
851
|
-
wrap.replaceChildren();
|
|
852
|
-
const order = state.answers[q.id] || [];
|
|
853
|
-
order.forEach((val, i) => {
|
|
854
|
-
const o = byVal.get(val);
|
|
855
|
-
if (!o) return;
|
|
856
|
-
const up = el('button', { type: 'button', class: 'rank-btn', title: 'Move up', 'aria-label': `Move "${o.label}" up` }, '↑');
|
|
857
|
-
const down = el('button', { type: 'button', class: 'rank-btn', title: 'Move down', 'aria-label': `Move "${o.label}" down` }, '↓');
|
|
858
|
-
up.disabled = i === 0;
|
|
859
|
-
down.disabled = i === order.length - 1;
|
|
860
|
-
up.addEventListener('click', () => move(i, i - 1));
|
|
861
|
-
down.addEventListener('click', () => move(i, i + 1));
|
|
862
|
-
const item = el('div', { class: 'rank-item', draggable: access.canEditAnswers ? 'true' : 'false' },
|
|
863
|
-
el('span', { class: 'rank-badge', 'aria-hidden': 'true' }, String(i + 1)),
|
|
864
|
-
el('div', { class: 'rank-body' },
|
|
865
|
-
el('div', { class: 'ol' }, o.label),
|
|
866
|
-
o.description ? el('div', { class: 'od' }, o.description) : null),
|
|
867
|
-
el('div', { class: 'rank-ctrls' }, up, down)
|
|
868
|
-
);
|
|
869
|
-
item.addEventListener('dragstart', (e) => {
|
|
870
|
-
if (!access.canEditAnswers) { e.preventDefault(); return; }
|
|
871
|
-
dragFrom = i; item.classList.add('dragging');
|
|
872
|
-
try { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', String(i)); } catch (_) {}
|
|
873
|
-
});
|
|
874
|
-
item.addEventListener('dragend', () => { dragFrom = null; item.classList.remove('dragging'); });
|
|
875
|
-
item.addEventListener('dragover', (e) => { if (dragFrom !== null) { e.preventDefault(); item.classList.add('drop-into'); } });
|
|
876
|
-
item.addEventListener('dragleave', () => item.classList.remove('drop-into'));
|
|
877
|
-
item.addEventListener('drop', (e) => {
|
|
878
|
-
e.preventDefault();
|
|
879
|
-
const from = dragFrom; dragFrom = null;
|
|
880
|
-
if (from !== null && from !== i) move(from, i);
|
|
881
|
-
});
|
|
882
|
-
wrap.append(item);
|
|
883
|
-
});
|
|
884
|
-
}
|
|
885
|
-
paint();
|
|
886
|
-
return wrap;
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
// Checklist: each option is a row with a segmented status control (Pass/Fail/
|
|
890
|
-
// N/A by default). Answer is a map {optionValue: statusValue} for set rows.
|
|
891
|
-
function controlChecklist(q) {
|
|
892
|
-
const wrap = el('div', { class: 'checklist' });
|
|
893
|
-
const cur = () => (state.answers[q.id] && typeof state.answers[q.id] === 'object' && !Array.isArray(state.answers[q.id])
|
|
894
|
-
? state.answers[q.id]
|
|
895
|
-
: (state.answers[q.id] = {}));
|
|
896
|
-
for (const o of q.options) {
|
|
897
|
-
const seg = el('div', { class: 'chk-seg' });
|
|
898
|
-
const buttons = [];
|
|
899
|
-
for (const s of q.statuses) {
|
|
900
|
-
const b = el('button', { type: 'button', class: 'chk-status' + (s.tone ? ' tone-' + s.tone : '') }, s.label);
|
|
901
|
-
if (cur()[o.value] === s.value) b.classList.add('sel');
|
|
902
|
-
b.addEventListener('click', () => {
|
|
903
|
-
const m = cur();
|
|
904
|
-
if (m[o.value] === s.value) delete m[o.value];
|
|
905
|
-
else m[o.value] = s.value;
|
|
906
|
-
for (const x of buttons) x.btn.classList.toggle('sel', m[o.value] === x.val);
|
|
907
|
-
clearErr(q.id);
|
|
908
|
-
scheduleSave();
|
|
909
|
-
});
|
|
910
|
-
buttons.push({ btn: b, val: s.value });
|
|
911
|
-
seg.append(b);
|
|
912
|
-
}
|
|
913
|
-
wrap.append(el('div', { class: 'chk-row' },
|
|
914
|
-
el('div', { class: 'chk-body' },
|
|
915
|
-
el('div', { class: 'ol' }, o.label),
|
|
916
|
-
o.description ? el('div', { class: 'od' }, o.description) : null),
|
|
917
|
-
seg
|
|
918
|
-
));
|
|
919
|
-
}
|
|
920
|
-
return wrap;
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
// Allocate: distribute q.total across the options with per-option sliders; a
|
|
924
|
-
// live total bar shows the running sum / remaining / overage. Answer is a map
|
|
925
|
-
// {optionValue: number}; an all-zero allocation submits as unanswered.
|
|
926
|
-
function controlAllocate(q) {
|
|
927
|
-
const wrap = el('div', { class: 'allocate' });
|
|
928
|
-
const total = q.total || 100;
|
|
929
|
-
const unit = q.unit ? ' ' + q.unit : '';
|
|
930
|
-
const cur = () => (state.answers[q.id] = seedAllocate(q, state.answers[q.id]));
|
|
931
|
-
const sumEl = el('span', { class: 'alloc-sum' });
|
|
932
|
-
const fill = el('div', { class: 'alloc-bar-fill' });
|
|
933
|
-
const nums = [];
|
|
934
|
-
const refresh = () => {
|
|
935
|
-
const m = cur();
|
|
936
|
-
const sum = (q.options || []).reduce((a, o) => a + (Number(m[o.value]) || 0), 0);
|
|
937
|
-
const tail = sum > total ? ` (over by ${sum - total})` : sum < total ? ` (${total - sum} left)` : ' ✓';
|
|
938
|
-
sumEl.textContent = `${sum} / ${total}${unit}${tail}`;
|
|
939
|
-
sumEl.classList.toggle('over', sum > total);
|
|
940
|
-
sumEl.classList.toggle('exact', sum === total);
|
|
941
|
-
fill.style.width = Math.min(100, (sum / total) * 100) + '%';
|
|
942
|
-
fill.classList.toggle('over', sum > total);
|
|
943
|
-
for (const n of nums) n.el.textContent = String(m[n.value] || 0);
|
|
944
|
-
};
|
|
945
|
-
for (const o of q.options) {
|
|
946
|
-
const m = cur();
|
|
947
|
-
const range = el('input', { type: 'range', min: '0', max: String(total), step: '1', class: 'alloc-range', 'aria-label': o.label });
|
|
948
|
-
range.value = String(m[o.value] || 0);
|
|
949
|
-
const num = el('span', { class: 'alloc-num' }, String(m[o.value] || 0));
|
|
950
|
-
range.addEventListener('input', () => {
|
|
951
|
-
cur()[o.value] = Number(range.value) || 0;
|
|
952
|
-
refresh();
|
|
953
|
-
clearErr(q.id);
|
|
954
|
-
scheduleSave();
|
|
955
|
-
});
|
|
956
|
-
nums.push({ value: o.value, el: num });
|
|
957
|
-
wrap.append(el('div', { class: 'alloc-row' },
|
|
958
|
-
el('div', { class: 'alloc-rowhead' },
|
|
959
|
-
el('div', { class: 'ol' }, o.label),
|
|
960
|
-
num),
|
|
961
|
-
range,
|
|
962
|
-
o.description ? el('div', { class: 'od' }, o.description) : null
|
|
963
|
-
));
|
|
964
|
-
}
|
|
965
|
-
wrap.append(el('div', { class: 'alloc-total' },
|
|
966
|
-
el('div', { class: 'alloc-bar' }, fill),
|
|
967
|
-
el('div', { class: 'alloc-sumwrap' }, 'Total: ', sumEl)
|
|
968
|
-
));
|
|
969
|
-
refresh();
|
|
970
|
-
return wrap;
|
|
971
|
-
}
|
|
972
|
-
|
|
973
|
-
function controlText(q, multiline) {
|
|
974
|
-
const input = multiline
|
|
975
|
-
? el('textarea', { placeholder: q.placeholder || '' })
|
|
976
|
-
: el('input', { type: 'text', placeholder: q.placeholder || '' });
|
|
977
|
-
input.value = typeof state.answers[q.id] === 'string' ? state.answers[q.id] : '';
|
|
978
|
-
input.addEventListener('input', () => {
|
|
979
|
-
state.answers[q.id] = input.value;
|
|
980
|
-
clearErr(q.id);
|
|
981
|
-
scheduleSave();
|
|
982
|
-
});
|
|
983
|
-
return input;
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
// Resolve ANY CSS color (named / rgb() / hsl() / hex) to #rrggbb for the
|
|
987
|
-
// native <input type=color>, using the browser's own parser — multi color-
|
|
988
|
-
// system support with no library. Returns null for an unparseable color.
|
|
989
|
-
function cssColorToHex(str) {
|
|
990
|
-
const s = String(str || '').trim();
|
|
991
|
-
let m = /^#?([0-9a-fA-F]{6})$/.exec(s);
|
|
992
|
-
if (m) return '#' + m[1].toLowerCase();
|
|
993
|
-
m = /^#?([0-9a-fA-F]{3})$/.exec(s);
|
|
994
|
-
if (m) return '#' + m[1].split('').map((x) => x + x).join('').toLowerCase();
|
|
995
|
-
try {
|
|
996
|
-
const d = document.createElement('div');
|
|
997
|
-
d.style.color = '';
|
|
998
|
-
d.style.color = s;
|
|
999
|
-
if (!d.style.color) return null; // browser rejected it → invalid color
|
|
1000
|
-
d.style.display = 'none';
|
|
1001
|
-
document.body.appendChild(d);
|
|
1002
|
-
const rgb = getComputedStyle(d).color;
|
|
1003
|
-
document.body.removeChild(d);
|
|
1004
|
-
const mm = rgb.match(/(\d+)[,\s]+(\d+)[,\s]+(\d+)/);
|
|
1005
|
-
if (!mm) return null;
|
|
1006
|
-
const h = (n) => Math.max(0, Math.min(255, Number(n))).toString(16).padStart(2, '0');
|
|
1007
|
-
return '#' + h(mm[1]) + h(mm[2]) + h(mm[3]);
|
|
1008
|
-
} catch { return null; }
|
|
1009
|
-
}
|
|
1010
|
-
function toHex6(c) { return cssColorToHex(c) || '#000000'; }
|
|
1011
|
-
|
|
1012
|
-
function controlColor(q) {
|
|
1013
|
-
const wrap = el('div', { class: 'colorpick' });
|
|
1014
|
-
const init = (typeof state.answers[q.id] === 'string' && state.answers[q.id]) || (typeof q.default === 'string' ? q.default : '');
|
|
1015
|
-
const swatch = el('input', { type: 'color', class: 'colorswatch' });
|
|
1016
|
-
const hex = el('input', { type: 'text', class: 'colorhex', placeholder: q.placeholder || '#rrggbb / rgb() / name', spellcheck: 'false', autocapitalize: 'off' });
|
|
1017
|
-
swatch.value = toHex6(init || '#888888');
|
|
1018
|
-
if (init) { hex.value = init; state.answers[q.id] = init; }
|
|
1019
|
-
let syncPaletteSel = () => {};
|
|
1020
|
-
const set = (val) => { state.answers[q.id] = val; syncPaletteSel(); clearErr(q.id); scheduleSave(); };
|
|
1021
|
-
swatch.addEventListener('input', () => { hex.value = swatch.value; set(swatch.value); });
|
|
1022
|
-
hex.addEventListener('input', () => { const v = hex.value.trim(); const h = cssColorToHex(v); if (h) swatch.value = h; set(v); });
|
|
1023
|
-
|
|
1024
|
-
// "Pick from a palette" — labeled swatch cards. Click selects that color as
|
|
1025
|
-
// the answer; each card is registered for annotation (per-color comments).
|
|
1026
|
-
if (Array.isArray(q.palette) && q.palette.length) {
|
|
1027
|
-
const grid = el('div', { class: 'colorpalette' });
|
|
1028
|
-
const cards = [];
|
|
1029
|
-
for (const p of q.palette) {
|
|
1030
|
-
const labelled = p.label && p.label !== p.value;
|
|
1031
|
-
const card = el('button', { type: 'button', class: 'colorpal-sw', style: 'background:' + p.value, title: (labelled ? p.label + ' · ' : '') + p.value });
|
|
1032
|
-
if (labelled) card.append(el('span', { class: 'colorpal-label' }, p.label));
|
|
1033
|
-
card.addEventListener('click', () => { const h = cssColorToHex(p.value); if (h) swatch.value = h; hex.value = p.value; set(p.value); });
|
|
1034
|
-
if (Annotate) Annotate.register(card, { blockId: null, questionId: q.id, target: { kind: 'swatch', label: (labelled ? p.label + ' · ' : '') + p.value } });
|
|
1035
|
-
cards.push({ card, val: p.value });
|
|
1036
|
-
grid.append(card);
|
|
1037
|
-
}
|
|
1038
|
-
syncPaletteSel = () => { for (const c of cards) c.card.classList.toggle('sel', state.answers[q.id] === c.val); };
|
|
1039
|
-
wrap.append(grid);
|
|
1040
|
-
}
|
|
1041
|
-
|
|
1042
|
-
wrap.append(el('div', { class: 'colorrow' }, swatch, hex));
|
|
1043
|
-
if (Array.isArray(q.presets) && q.presets.length) {
|
|
1044
|
-
const presets = el('div', { class: 'colorpresets' });
|
|
1045
|
-
for (const c of q.presets) {
|
|
1046
|
-
const b = el('button', { type: 'button', class: 'colorpreset', style: 'background:' + c, title: c });
|
|
1047
|
-
b.addEventListener('click', () => { const h = cssColorToHex(c); if (h) swatch.value = h; hex.value = c; set(c); });
|
|
1048
|
-
presets.append(b);
|
|
1049
|
-
}
|
|
1050
|
-
wrap.append(presets);
|
|
1051
|
-
}
|
|
1052
|
-
syncPaletteSel();
|
|
1053
|
-
return wrap;
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
// ---------- render ----------
|
|
1057
|
-
themeBtn = el('button', { class: 'theme-btn', type: 'button' }, '');
|
|
1058
|
-
themeBtn.addEventListener('click', () => {
|
|
1059
|
-
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
|
|
1060
|
-
localStorage.setItem(THEME_KEY, theme);
|
|
1061
|
-
fetch('/api/pref', {
|
|
1062
|
-
method: 'POST',
|
|
1063
|
-
headers: { 'content-type': 'application/json' },
|
|
1064
|
-
body: JSON.stringify({ theme }),
|
|
1065
|
-
}).catch(() => {});
|
|
1066
|
-
applyTheme();
|
|
1067
|
-
});
|
|
1068
|
-
applyTheme();
|
|
1069
|
-
|
|
1070
|
-
const fsDown = el('button', { class: 'fs-btn', type: 'button', title: 'Smaller text', 'aria-label': 'Decrease text size' }, 'A−');
|
|
1071
|
-
const fsUp = el('button', { class: 'fs-btn', type: 'button', title: 'Larger text', 'aria-label': 'Increase text size' }, 'A+');
|
|
1072
|
-
fsDown.addEventListener('click', () => setFontScale(fontScale - FS_STEP));
|
|
1073
|
-
fsUp.addEventListener('click', () => setFontScale(fontScale + FS_STEP));
|
|
1074
|
-
const fsCtrl = el('div', { class: 'fs-ctrl' }, fsDown, fsUp);
|
|
1075
|
-
|
|
1076
|
-
function buildShareControl() {
|
|
1077
|
-
if (!access.canShare) return null;
|
|
1078
|
-
const wrap = el('span', { class: 'share-wrap' });
|
|
1079
|
-
const shareBtn = el('button', { class: 'share-btn icon-btn', type: 'button', title: 'Share board', 'aria-label': 'Share board' });
|
|
1080
|
-
shareBtn.innerHTML =
|
|
1081
|
-
'<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' +
|
|
1082
|
-
'<path d="M6.5 9.5 9.5 11.2M9.5 4.8 6.5 6.5"/>' +
|
|
1083
|
-
'<circle cx="4.5" cy="8" r="2"/><circle cx="11.5" cy="4" r="2"/><circle cx="11.5" cy="12" r="2"/>' +
|
|
1084
|
-
'</svg>';
|
|
1085
|
-
shareBtn.addEventListener('click', () => {
|
|
1086
|
-
const existing = wrap.querySelector('.share-panel');
|
|
1087
|
-
if (existing) existing.remove();
|
|
1088
|
-
else openSharePanel(wrap);
|
|
1089
|
-
});
|
|
1090
|
-
wrap.append(shareBtn);
|
|
1091
|
-
return wrap;
|
|
1092
|
-
}
|
|
1093
|
-
|
|
1094
|
-
// Just reloaded after a live `rly update`? Flag set before reload below.
|
|
1095
|
-
try {
|
|
1096
|
-
if (sessionStorage.getItem('relay-updated') === '1') {
|
|
1097
|
-
sessionStorage.removeItem('relay-updated');
|
|
1098
|
-
showToast('Board updated by the agent');
|
|
1099
|
-
}
|
|
1100
|
-
if (sessionStorage.getItem('relay-draft-updated') === '1') {
|
|
1101
|
-
sessionStorage.removeItem('relay-draft-updated');
|
|
1102
|
-
showToast('Board refreshed with shared changes');
|
|
1103
|
-
}
|
|
1104
|
-
} catch {
|
|
1105
|
-
// sessionStorage may be unavailable (privacy mode) — non-fatal
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
const titleEl = el('h1', {}, spec.title);
|
|
1109
|
-
app.append(el('header', { class: 'qb-header' }, titleEl, el('div', { class: 'qb-controls' }, fsCtrl, buildShareControl(), themeBtn)));
|
|
1110
|
-
// The board title is commentable too: hovering it shows the pin, like the
|
|
1111
|
-
// intro and every other content element. (themeBtn stays out of it.)
|
|
1112
|
-
if (spec.title) {
|
|
1113
|
-
Annotate?.register(titleEl, { blockId: null, questionId: null, target: { kind: 'html-element', label: spec.title } });
|
|
1114
|
-
}
|
|
1115
|
-
if (spec.intro) {
|
|
1116
|
-
// Render the intro as markdown (bold/italic/code/links/lists) — agents write
|
|
1117
|
-
// markdown here by default. Falls back to plain text if blocks.js is absent.
|
|
1118
|
-
// The .blk-markdown class scopes the shared markdown typography to it.
|
|
1119
|
-
const md = typeof window.RelayBlocks !== 'undefined' && window.RelayBlocks.renderMarkdown;
|
|
1120
|
-
const intro = md
|
|
1121
|
-
? el('div', { class: 'intro blk-markdown' }, window.RelayBlocks.renderMarkdown(spec.intro))
|
|
1122
|
-
: el('p', { class: 'intro' }, spec.intro);
|
|
1123
|
-
app.append(intro);
|
|
1124
|
-
Annotate?.enableTextSelection(intro, { blockId: null, questionId: null });
|
|
1125
|
-
}
|
|
1126
|
-
// Board-level blocks render above the questions (async; never blocks submit).
|
|
1127
|
-
renderBlocks(app, spec.blocks || [], null);
|
|
1128
|
-
|
|
1129
|
-
QS.forEach((q, idx) => {
|
|
1130
|
-
const required = q.required || !spec.allowPartial;
|
|
1131
|
-
const card = el('div', { class: 'card' },
|
|
1132
|
-
el('div', { class: 'qnum' }, `Q${idx + 1}`),
|
|
1133
|
-
el('p', { class: 'qlabel' }, q.label, required ? el('span', { class: 'req' }, ' *') : null),
|
|
1134
|
-
q.description ? el('p', { class: 'qdesc' }, q.description) : null
|
|
1135
|
-
);
|
|
1136
|
-
// Per-question blocks render between the description and the control.
|
|
1137
|
-
renderBlocks(card, q.blocks || [], q.id);
|
|
1138
|
-
const control = el('div', { class: 'control' });
|
|
1139
|
-
if (q.type === 'single') control.append(controlSingle(q));
|
|
1140
|
-
else if (q.type === 'multi') control.append(controlMulti(q));
|
|
1141
|
-
else if (q.type === 'yesno') control.append(segButtons(q, ['yes', 'no'], ['Yes', 'No']));
|
|
1142
|
-
else if (q.type === 'scale') control.append(controlScale(q));
|
|
1143
|
-
else if (q.type === 'color') control.append(controlColor(q));
|
|
1144
|
-
else if (q.type === 'rank') control.append(controlRank(q));
|
|
1145
|
-
else if (q.type === 'checklist') control.append(controlChecklist(q));
|
|
1146
|
-
else if (q.type === 'allocate') control.append(controlAllocate(q));
|
|
1147
|
-
else control.append(controlText(q, q.type === 'textarea'));
|
|
1148
|
-
card.append(control);
|
|
1149
|
-
if (q.note) {
|
|
1150
|
-
const noteInput = el('textarea', { class: 'qnote', rows: 2, placeholder: 'optional note about this answer…' });
|
|
1151
|
-
noteInput.value = typeof state.notes[q.id] === 'string' ? state.notes[q.id] : '';
|
|
1152
|
-
noteInput.addEventListener('input', () => {
|
|
1153
|
-
state.notes[q.id] = noteInput.value;
|
|
1154
|
-
scheduleSave();
|
|
1155
|
-
});
|
|
1156
|
-
card.append(el('div', { class: 'qnotewrap' }, noteInput));
|
|
1157
|
-
}
|
|
1158
|
-
card.append(el('p', { class: 'errmsg' }, 'This question is required.'));
|
|
1159
|
-
cards[q.id] = card;
|
|
1160
|
-
app.append(card);
|
|
1161
|
-
});
|
|
1162
|
-
|
|
1163
|
-
if (spec.note && responseRequired) {
|
|
1164
|
-
const note = el('textarea', { placeholder: 'optional note back to the agent…' });
|
|
1165
|
-
note.value = state.comment || '';
|
|
1166
|
-
note.addEventListener('input', () => {
|
|
1167
|
-
state.comment = note.value;
|
|
1168
|
-
scheduleSave();
|
|
1169
|
-
});
|
|
1170
|
-
app.append(el('div', { class: 'card' },
|
|
1171
|
-
el('p', { class: 'qlabel' }, 'Anything else?'),
|
|
1172
|
-
el('p', { class: 'qdesc' }, 'Free-text note returned to the agent along with your answers.'),
|
|
1173
|
-
el('div', { class: 'control' }, note)
|
|
1174
|
-
));
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
// Element-level comments live in the Outline-style right rail (created and
|
|
1178
|
-
// managed by RelayAnnotate); no inline summary list here anymore.
|
|
1179
|
-
|
|
1180
|
-
const submitBtn = el('button', { class: 'submit', type: 'button' }, spec.submitLabel);
|
|
1181
|
-
saveEl = el('span', { class: 'savestate' }, '');
|
|
1182
|
-
const hint = el('span', { class: 'hint' },
|
|
1183
|
-
QS.length && spec.allowPartial ? 'Unanswered questions are returned as skipped.' : '');
|
|
1184
|
-
const submitbar = el('div', { class: 'submitbar' }, submitBtn, hint, saveEl);
|
|
1185
|
-
if (!responseRequired) {
|
|
1186
|
-
submitbar.replaceChildren(el('span', { class: 'hint' }, 'Display only · no response requested'));
|
|
1187
|
-
submitbar.classList.add('display-only');
|
|
1188
|
-
}
|
|
1189
|
-
app.append(submitbar);
|
|
1190
|
-
|
|
1191
|
-
function copyText(text, btn) {
|
|
1192
|
-
const done = () => {
|
|
1193
|
-
if (!btn) return;
|
|
1194
|
-
const old = btn.textContent;
|
|
1195
|
-
btn.textContent = 'Copied';
|
|
1196
|
-
setTimeout(() => { btn.textContent = old; }, 1800);
|
|
1197
|
-
};
|
|
1198
|
-
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
1199
|
-
navigator.clipboard.writeText(text).then(done).catch(() => {});
|
|
1200
|
-
return;
|
|
1201
|
-
}
|
|
1202
|
-
const ta = document.createElement('textarea');
|
|
1203
|
-
ta.value = text;
|
|
1204
|
-
ta.style.position = 'fixed';
|
|
1205
|
-
ta.style.opacity = '0';
|
|
1206
|
-
document.body.append(ta);
|
|
1207
|
-
ta.select();
|
|
1208
|
-
try { document.execCommand('copy'); done(); } catch {}
|
|
1209
|
-
ta.remove();
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
function openSharePanel(host) {
|
|
1213
|
-
const panel = el('div', { class: 'share-panel' },
|
|
1214
|
-
el('div', { class: 'share-title' }, 'Share this board'),
|
|
1215
|
-
el('div', { class: 'share-desc' }, 'Choose a permission. The link starts working immediately.'),
|
|
1216
|
-
el('button', { class: 'share-choice', type: 'button', 'data-role': 'collab' },
|
|
1217
|
-
el('span', { class: 'share-choice-title' }, 'Collaborator'),
|
|
1218
|
-
el('span', { class: 'share-choice-sub' }, 'Can edit answers, comment, and submit as owner.')
|
|
1219
|
-
),
|
|
1220
|
-
el('button', { class: 'share-choice', type: 'button', 'data-role': 'review' },
|
|
1221
|
-
el('span', { class: 'share-choice-title' }, 'Reviewer'),
|
|
1222
|
-
el('span', { class: 'share-choice-sub' }, 'Can answer, comment, and submit a reference-only side review. Does not finalize the board.')
|
|
1223
|
-
),
|
|
1224
|
-
el('button', { class: 'share-choice', type: 'button', 'data-role': 'read' },
|
|
1225
|
-
el('span', { class: 'share-choice-title' }, 'Read only'),
|
|
1226
|
-
el('span', { class: 'share-choice-sub' }, 'Can view the board and existing feedback. Cannot answer, comment, edit, or submit.')
|
|
1227
|
-
),
|
|
1228
|
-
el('div', { class: 'share-result' })
|
|
1229
|
-
);
|
|
1230
|
-
const close = () => panel.remove();
|
|
1231
|
-
const closeBtn = el('button', { class: 'share-close', type: 'button', 'aria-label': 'Close share panel' }, '×');
|
|
1232
|
-
closeBtn.addEventListener('click', close);
|
|
1233
|
-
panel.prepend(closeBtn);
|
|
1234
|
-
const result = panel.querySelector('.share-result');
|
|
1235
|
-
for (const btn of panel.querySelectorAll('.share-choice')) {
|
|
1236
|
-
btn.addEventListener('click', async () => {
|
|
1237
|
-
const role = btn.getAttribute('data-role');
|
|
1238
|
-
btn.disabled = true;
|
|
1239
|
-
result.textContent = 'Activating...';
|
|
1240
|
-
try {
|
|
1241
|
-
const res = await fetch('/api/share', {
|
|
1242
|
-
method: 'POST',
|
|
1243
|
-
headers: { 'content-type': 'application/json' },
|
|
1244
|
-
body: JSON.stringify({ role }),
|
|
1245
|
-
});
|
|
1246
|
-
const body = await res.json().catch(() => null);
|
|
1247
|
-
if (!res.ok || !body || !body.url) throw new Error(body && body.error ? body.error : 'share failed');
|
|
1248
|
-
const copy = el('button', { class: 'share-copy', type: 'button' }, 'Copy link');
|
|
1249
|
-
copy.addEventListener('click', () => copyText(body.url, copy));
|
|
1250
|
-
result.replaceChildren(
|
|
1251
|
-
el('div', { class: 'share-ready' }, role === 'collab' ? 'Collaborator link active' : role === 'review' ? 'Reviewer link active' : 'Read-only link active'),
|
|
1252
|
-
el('a', { class: 'share-url', href: body.url, target: '_blank', rel: 'noreferrer' }, body.url),
|
|
1253
|
-
copy
|
|
1254
|
-
);
|
|
1255
|
-
} catch (err) {
|
|
1256
|
-
result.textContent = err && err.message ? err.message : 'Could not activate sharing.';
|
|
1257
|
-
} finally {
|
|
1258
|
-
btn.disabled = false;
|
|
1259
|
-
}
|
|
1260
|
-
});
|
|
1261
|
-
}
|
|
1262
|
-
host.append(panel);
|
|
1263
|
-
}
|
|
1264
|
-
|
|
1265
|
-
function buildFooter() {
|
|
1266
|
-
const footer = el('footer', { class: 'qb-footer' }, el('span', {}, `relay · ${boot.boardId}`));
|
|
1267
|
-
return footer;
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
function applyAccessRestrictions() {
|
|
1271
|
-
if (!access.canSubmit) submitbar.style.display = 'none';
|
|
1272
|
-
if (!access.canEditAnswers) {
|
|
1273
|
-
for (const node of app.querySelectorAll('.card input, .card textarea, .card button, .card select')) {
|
|
1274
|
-
// Viewer controls inside question/option blocks remain useful in a
|
|
1275
|
-
// read-only board (zoom, fit, full-screen, filtering, diff view). Block
|
|
1276
|
-
// mutation controls are independently gated by canEditBlocks.
|
|
1277
|
-
if (node.closest('.blocks')) continue;
|
|
1278
|
-
node.disabled = true;
|
|
1279
|
-
}
|
|
1280
|
-
for (const item of app.querySelectorAll('.rank-item')) {
|
|
1281
|
-
item.draggable = false;
|
|
1282
|
-
item.setAttribute('aria-disabled', 'true');
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
document.documentElement.classList.toggle('relay-review', access.canEditComments === false || access.canDeleteComments === false);
|
|
1286
|
-
}
|
|
1287
|
-
if (access.role === 'review') {
|
|
1288
|
-
submitBtn.textContent = 'Submit side review';
|
|
1289
|
-
hint.textContent = 'Reference only — the owner still submits the final answer.';
|
|
1290
|
-
showNotice('Reviewer mode: your answers and comments are saved separately as a reference-only side review. Submitting here does not finalize the board or notify the waiting agent.', 'info');
|
|
1291
|
-
} else if (access.role === 'read') {
|
|
1292
|
-
showNotice('Read-only mode: you can view the board and existing feedback, but answers, comments, edits, and submission are disabled.', 'info');
|
|
1293
|
-
} else if (access.role === 'collab') {
|
|
1294
|
-
showNotice('Editor mode: answers, comments, and final submission are enabled for this shared board.', 'info');
|
|
1295
|
-
}
|
|
1296
|
-
applyAccessRestrictions();
|
|
1297
|
-
app.append(buildFooter());
|
|
1298
|
-
|
|
1299
|
-
// ---------- validation & submit ----------
|
|
1300
|
-
function validate() {
|
|
1301
|
-
let firstBad = null;
|
|
1302
|
-
for (const q of QS) {
|
|
1303
|
-
const required = q.required || !spec.allowPartial;
|
|
1304
|
-
const bad = required && getValue(q) === undefined;
|
|
1305
|
-
cards[q.id].classList.toggle('error', bad);
|
|
1306
|
-
if (bad && !firstBad) firstBad = cards[q.id];
|
|
1307
|
-
}
|
|
1308
|
-
if (firstBad) firstBad.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
1309
|
-
return !firstBad;
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
function showDone(closing, sideReview = false) {
|
|
1313
|
-
stopHeartbeat();
|
|
1314
|
-
// Annotation pins/badges/popover float on <body> with elevated z-index —
|
|
1315
|
-
// remove them so they don't leak over the submitted screen.
|
|
1316
|
-
if (window.RelayAnnotate && typeof RelayAnnotate.teardown === 'function') {
|
|
1317
|
-
try {
|
|
1318
|
-
RelayAnnotate.teardown();
|
|
1319
|
-
} catch {
|
|
1320
|
-
// best effort
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1323
|
-
// If the agent already stopped waiting (soft timeout / dropped connection),
|
|
1324
|
-
// the submission won't be picked up automatically — tell the user to nudge
|
|
1325
|
-
// the agent. Otherwise the normal hand-back copy applies.
|
|
1326
|
-
const note = sideReview
|
|
1327
|
-
? 'Saved for reference. This did not finalize the board or notify the waiting agent; the owner still needs to submit the final answer.'
|
|
1328
|
-
: handedBack
|
|
1329
|
-
? 'Saved. Your agent had stopped waiting — send it a message so it picks up your answers.'
|
|
1330
|
-
: closing
|
|
1331
|
-
? 'Handing back to your agent — this tab will close itself…'
|
|
1332
|
-
: 'Handed back to your agent. You can close this tab.';
|
|
1333
|
-
app.replaceChildren(
|
|
1334
|
-
el('div', { class: 'done' },
|
|
1335
|
-
el('div', { class: 'mark' }, '✓'),
|
|
1336
|
-
el('h2', {}, sideReview ? 'Side review saved' : QS.length ? 'Submitted' : 'Acknowledged'),
|
|
1337
|
-
el('p', { id: 'done-note' }, note)
|
|
1338
|
-
)
|
|
1339
|
-
);
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
submitBtn.addEventListener('click', async () => {
|
|
1343
|
-
if (!validate()) return;
|
|
1344
|
-
submitBtn.disabled = true;
|
|
1345
|
-
submitBtn.textContent = 'Submitting…';
|
|
1346
|
-
clearTimeout(saveTimer);
|
|
1347
|
-
let reached = true;
|
|
1348
|
-
try {
|
|
1349
|
-
let res;
|
|
1350
|
-
try {
|
|
1351
|
-
res = await fetch('/api/submit', {
|
|
1352
|
-
method: 'POST',
|
|
1353
|
-
headers: authHeaders({ 'content-type': 'application/json' }),
|
|
1354
|
-
body: JSON.stringify(payload()),
|
|
1355
|
-
});
|
|
1356
|
-
} catch (netErr) {
|
|
1357
|
-
// A thrown fetch (vs. an HTTP error response) means we never reached the
|
|
1358
|
-
// server — the connection is gone, so this submit was never delivered.
|
|
1359
|
-
reached = false;
|
|
1360
|
-
throw netErr;
|
|
1361
|
-
}
|
|
1362
|
-
if (!res.ok) throw new Error('submit rejected');
|
|
1363
|
-
const submitResult = await res.json().catch(() => null);
|
|
1364
|
-
const sideReview = Boolean(submitResult && submitResult.sideReview === true && submitResult.final === false);
|
|
1365
|
-
submitted = true;
|
|
1366
|
-
// Submitted successfully → the local mirror is no longer needed and would
|
|
1367
|
-
// otherwise resurrect stale answers on a future reopen. Clear it.
|
|
1368
|
-
clearLocalDraft();
|
|
1369
|
-
// Don't auto-close when the agent had stopped waiting — the user needs to
|
|
1370
|
-
// read the "send your agent a message" note and act on it.
|
|
1371
|
-
const autoClose = !sideReview && spec.autoClose && !handedBack;
|
|
1372
|
-
showDone(autoClose, sideReview);
|
|
1373
|
-
if (autoClose) {
|
|
1374
|
-
setTimeout(() => {
|
|
1375
|
-
window.close();
|
|
1376
|
-
// window.close() is best-effort (browsers may block it for
|
|
1377
|
-
// user-opened tabs) — fall back to the "close this tab" note.
|
|
1378
|
-
setTimeout(() => {
|
|
1379
|
-
const note = document.getElementById('done-note');
|
|
1380
|
-
if (note) note.textContent = 'Handed back to your agent. You can close this tab.';
|
|
1381
|
-
}, 400);
|
|
1382
|
-
}, 700);
|
|
1383
|
-
}
|
|
1384
|
-
} catch {
|
|
1385
|
-
// Restore the button so the user can retry.
|
|
1386
|
-
submitBtn.disabled = false;
|
|
1387
|
-
submitBtn.textContent = access.role === 'review' ? 'Submit side review' : spec.submitLabel;
|
|
1388
|
-
if (!reached) {
|
|
1389
|
-
// The connection is gone — the submit (and any further input) can't be
|
|
1390
|
-
// persisted. Block hard so the user stops adding feedback that would be
|
|
1391
|
-
// lost; the block's probe loop / heartbeat lifts it on recovery, and the
|
|
1392
|
-
// user can then submit. force=true: the failed submit already confirms
|
|
1393
|
-
// the server is unreachable.
|
|
1394
|
-
stopHeartbeat();
|
|
1395
|
-
considerPersistenceLost(true);
|
|
1396
|
-
startBlockedProbeLoop();
|
|
1397
|
-
} else {
|
|
1398
|
-
// The server answered with an error (e.g. 409 board already finished) —
|
|
1399
|
-
// it's reachable, so don't show the scary block; just guide the user.
|
|
1400
|
-
showNotice(
|
|
1401
|
-
'Couldn’t submit — the board may have already closed. Prompt the agent to reopen this board so your input isn’t lost.',
|
|
1402
|
-
'warn'
|
|
1403
|
-
);
|
|
1404
|
-
}
|
|
1405
|
-
}
|
|
1406
|
-
});
|
|
1407
|
-
|
|
1408
|
-
// ---------- prefilled load: jump past what's already answered ----------
|
|
1409
|
-
// On reload/reopen with saved answers, scroll to the first unanswered
|
|
1410
|
-
// question so the user doesn't re-scan questions they already did.
|
|
1411
|
-
if (initialPrefill && QS.length) {
|
|
1412
|
-
const answered = QS.filter((q) => getValue(q) !== undefined).length;
|
|
1413
|
-
const firstOpen = QS.find((q) => getValue(q) === undefined);
|
|
1414
|
-
if (answered > 0 && firstOpen) {
|
|
1415
|
-
setTimeout(() => {
|
|
1416
|
-
cards[firstOpen.id].scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
1417
|
-
}, 350);
|
|
1418
|
-
}
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
// If the chosen prefill came from the local mirror (newer than the server, or
|
|
1422
|
-
// the server had nothing — e.g. a freshly reopened board the user had typed
|
|
1423
|
-
// into in another tab during an outage), the server doesn't yet have this
|
|
1424
|
-
// input. Flush it once so a brand-new tab's view is also the server's truth.
|
|
1425
|
-
if (initialPrefill && initialPrefill.__from === 'local' && !submitted && canPersistFeedback) {
|
|
1426
|
-
saveDraft();
|
|
1427
|
-
}
|
|
1428
|
-
|
|
1429
|
-
// ---------- iframe annotate bridge ----------
|
|
1430
|
-
// Custom-HTML iframes (via /kit.js relayKit.annotate, auto-injected by the
|
|
1431
|
-
// server) talk to the parent over postMessage:
|
|
1432
|
-
// iframe → {relay:'annotate-ready'} we send it counts
|
|
1433
|
-
// iframe → {relay:'annotate-request', ref, label, detail?, rect}
|
|
1434
|
-
// parent → {relay:'annotate-counts', counts:{ref:n}} it draws badges
|
|
1435
|
-
// We own the annotation state, popover, and the submitted result; the iframe
|
|
1436
|
-
// owns hover/pin/badges over its own (cross-origin) DOM.
|
|
1437
|
-
if (Annotate && responseRequired) {
|
|
1438
|
-
const frameOf = (source) => {
|
|
1439
|
-
for (const f of document.querySelectorAll('iframe.viz')) {
|
|
1440
|
-
if (f.contentWindow === source) return f;
|
|
1441
|
-
}
|
|
1442
|
-
return null;
|
|
1443
|
-
};
|
|
1444
|
-
// Per-element comment counts for one iframe, keyed by target.ref.
|
|
1445
|
-
const postCountsTo = (frame) => {
|
|
1446
|
-
if (!frame || !frame.contentWindow) return;
|
|
1447
|
-
const blockId = frame.getAttribute('data-block-id') || null;
|
|
1448
|
-
const counts = {};
|
|
1449
|
-
for (const a of Annotate.list()) {
|
|
1450
|
-
if ((a.blockId ?? null) !== (blockId ?? null)) continue;
|
|
1451
|
-
const t = a.target || {};
|
|
1452
|
-
if (t.kind !== 'html-element' || !t.ref) continue;
|
|
1453
|
-
counts[t.ref] = (counts[t.ref] || 0) + 1;
|
|
1454
|
-
}
|
|
1455
|
-
try { frame.contentWindow.postMessage({ relay: 'annotate-counts', counts }, '*'); } catch {}
|
|
1456
|
-
};
|
|
1457
|
-
// Refresh badges in every html iframe (called whenever annotations change).
|
|
1458
|
-
window.__relayBroadcastCounts = () => {
|
|
1459
|
-
for (const f of document.querySelectorAll('iframe.viz')) postCountsTo(f);
|
|
1460
|
-
};
|
|
1461
|
-
|
|
1462
|
-
window.addEventListener('message', (e) => {
|
|
1463
|
-
const msg = e.data;
|
|
1464
|
-
if (!msg || typeof msg !== 'object' || typeof msg.relay !== 'string') return;
|
|
1465
|
-
const frame = frameOf(e.source);
|
|
1466
|
-
if (!frame) return;
|
|
1467
|
-
if (msg.relay === 'annotate-ready') { postCountsTo(frame); return; }
|
|
1468
|
-
if (msg.relay !== 'annotate-request') return;
|
|
1469
|
-
|
|
1470
|
-
const blockId = frame.getAttribute('data-block-id') || null;
|
|
1471
|
-
const questionId = frame.getAttribute('data-question-id') || null;
|
|
1472
|
-
const target = { kind: 'html-element', label: typeof msg.label === 'string' ? msg.label : 'Element' };
|
|
1473
|
-
if (typeof msg.ref === 'string') target.ref = msg.ref;
|
|
1474
|
-
if (typeof msg.detail === 'string') target.detail = msg.detail;
|
|
1475
|
-
|
|
1476
|
-
// Anchor the popover to the actual element: translate the iframe-local
|
|
1477
|
-
// viewport rect the iframe sent into page coords. Fall back to the iframe.
|
|
1478
|
-
let anchor = frame;
|
|
1479
|
-
if (msg.rect && typeof msg.rect === 'object') {
|
|
1480
|
-
const fr = frame.getBoundingClientRect();
|
|
1481
|
-
const r = msg.rect;
|
|
1482
|
-
const left = fr.left + (r.left || 0);
|
|
1483
|
-
const top = fr.top + (r.top || 0);
|
|
1484
|
-
const width = r.width || 0;
|
|
1485
|
-
const height = r.height || 0;
|
|
1486
|
-
const pageRect = { left, top, width, height, right: left + width, bottom: top + height };
|
|
1487
|
-
anchor = { getBoundingClientRect: () => pageRect };
|
|
1488
|
-
}
|
|
1489
|
-
Annotate.openExternal({ blockId, questionId: questionId || null, target }, anchor);
|
|
1490
|
-
});
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
// ---------- heartbeat ----------
|
|
1494
|
-
// True when the user is actively typing — an open annotation comment popover,
|
|
1495
|
-
// or focus in any text-entry field (comment box, notes, text/color answers,
|
|
1496
|
-
// "Other" inputs). Used to defer the live-update reload so in-progress
|
|
1497
|
-
// comments aren't destroyed mid-keystroke.
|
|
1498
|
-
function isEditable(node) {
|
|
1499
|
-
if (!node) return false;
|
|
1500
|
-
if (node.tagName === 'TEXTAREA') return true;
|
|
1501
|
-
if (node.tagName === 'INPUT') {
|
|
1502
|
-
const t = (node.type || 'text').toLowerCase();
|
|
1503
|
-
return ['text', 'search', 'email', 'url', 'tel', 'number', 'color'].includes(t);
|
|
1504
|
-
}
|
|
1505
|
-
return node.isContentEditable === true;
|
|
1506
|
-
}
|
|
1507
|
-
function userIsComposing() {
|
|
1508
|
-
if (window.RelayAnnotate && typeof RelayAnnotate.isComposing === 'function' && RelayAnnotate.isComposing()) return true;
|
|
1509
|
-
return isEditable(document.activeElement);
|
|
1510
|
-
}
|
|
1511
|
-
|
|
1512
|
-
let misses = 0;
|
|
1513
|
-
let reloading = false;
|
|
1514
|
-
let hb = null;
|
|
1515
|
-
async function heartbeatTick() {
|
|
1516
|
-
// Piggyback presence on the heartbeat (best-effort; no-ops after submit).
|
|
1517
|
-
pingPresence();
|
|
1518
|
-
try {
|
|
1519
|
-
const r = await fetch('/api/status', { cache: 'no-store', headers: authHeaders() });
|
|
1520
|
-
if (!r.ok) throw new Error('bad status');
|
|
1521
|
-
misses = 0;
|
|
1522
|
-
// The heartbeat reaching the server is itself proof persistence is back —
|
|
1523
|
-
// if we were blocked (saves had been failing), recover now and flush.
|
|
1524
|
-
if (persistenceLost) {
|
|
1525
|
-
unblockAfterRecovery();
|
|
1526
|
-
return;
|
|
1527
|
-
}
|
|
1528
|
-
// Live update: the agent ran `rly update`, advancing the server rev.
|
|
1529
|
-
// Flush whatever the user has typed so far (the reload re-prefills from
|
|
1530
|
-
// the live draft — answers for now-removed question ids are ignored),
|
|
1531
|
-
// then reload to render the new spec. Guarded so it fires once.
|
|
1532
|
-
const body = await r.json().catch(() => null);
|
|
1533
|
-
// Soft timeout: the board ran past its deadline so the agent was handed a
|
|
1534
|
-
// result and stopped waiting — but the server is still up and the board
|
|
1535
|
-
// stays fully usable. Surface a calm note (never disable Submit) so the
|
|
1536
|
-
// user knows to prompt the agent after submitting.
|
|
1537
|
-
if (body && body.softTimedOut && !submitted) {
|
|
1538
|
-
handedBack = true;
|
|
1539
|
-
if (access.role === 'review') {
|
|
1540
|
-
showNotice('This remains a reference-only side review. Submit when ready; the owner still needs to provide the final answer.', 'info');
|
|
1541
|
-
} else if (access.role !== 'read') {
|
|
1542
|
-
showNotice(
|
|
1543
|
-
'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.',
|
|
1544
|
-
'info'
|
|
1545
|
-
);
|
|
1546
|
-
}
|
|
1547
|
-
}
|
|
1548
|
-
if (body && typeof body.rev === 'number' && bootRev !== null && body.rev !== bootRev && !submitted && !reloading) {
|
|
1549
|
-
// Don't yank the board out from under someone mid-comment: an open
|
|
1550
|
-
// annotation popover (its add-comment box + reply inputs) holds text
|
|
1551
|
-
// that isn't in the draft until Save, so a reload would discard it —
|
|
1552
|
-
// and reloading while any field is focused drops the user's cursor and
|
|
1553
|
-
// last keystrokes. Defer until they're done; the heartbeat re-checks
|
|
1554
|
-
// every tick, so the update applies the moment they close/blur.
|
|
1555
|
-
if (userIsComposing()) {
|
|
1556
|
-
showNotice('The agent updated this board — it’ll refresh as soon as you finish your comment.', 'info');
|
|
1557
|
-
return;
|
|
1558
|
-
}
|
|
1559
|
-
reloading = true;
|
|
1560
|
-
stopHeartbeat();
|
|
1561
|
-
clearTimeout(saveTimer);
|
|
1562
|
-
try {
|
|
1563
|
-
await saveDraft();
|
|
1564
|
-
} catch {
|
|
1565
|
-
// a failed final save shouldn't block the reload to the new spec
|
|
1566
|
-
}
|
|
1567
|
-
try {
|
|
1568
|
-
sessionStorage.setItem('relay-updated', '1');
|
|
1569
|
-
} catch {
|
|
1570
|
-
// sessionStorage may be unavailable — the reload still applies the update
|
|
1571
|
-
}
|
|
1572
|
-
location.reload();
|
|
1573
|
-
return;
|
|
1574
|
-
}
|
|
1575
|
-
if (body && typeof body.draftRev === 'number' && body.draftRev > seenDraftRev && !submitted && !reloading) {
|
|
1576
|
-
if (userIsComposing()) {
|
|
1577
|
-
showNotice('Another viewer updated this board — it’ll refresh as soon as you finish typing.', 'info');
|
|
1578
|
-
return;
|
|
1579
|
-
}
|
|
1580
|
-
reloading = true;
|
|
1581
|
-
stopHeartbeat();
|
|
1582
|
-
clearTimeout(saveTimer);
|
|
1583
|
-
clearLocalDraft();
|
|
1584
|
-
try {
|
|
1585
|
-
sessionStorage.setItem('relay-draft-updated', '1');
|
|
1586
|
-
} catch {
|
|
1587
|
-
// sessionStorage may be unavailable — the reload still applies the update
|
|
1588
|
-
}
|
|
1589
|
-
location.reload();
|
|
1590
|
-
}
|
|
1591
|
-
} catch {
|
|
1592
|
-
// Lost the live connection (the session ended, or the machine slept). Two
|
|
1593
|
-
// consecutive misses means the local server is unreachable — so input can
|
|
1594
|
-
// no longer be persisted. Hard-block: disable editing and overlay the
|
|
1595
|
-
// unmissable "connection lost" scrim, so the user can't keep typing
|
|
1596
|
-
// feedback that would be silently discarded. The block re-arms its own
|
|
1597
|
-
// probe loop and the heartbeat recovers it once the server answers again.
|
|
1598
|
-
if (++misses >= 2 && !submitted && !persistenceLost) {
|
|
1599
|
-
handedBack = true;
|
|
1600
|
-
stopHeartbeat();
|
|
1601
|
-
// force=true: two heartbeat misses already confirm the server is gone,
|
|
1602
|
-
// so block immediately without a redundant probe.
|
|
1603
|
-
considerPersistenceLost(true);
|
|
1604
|
-
// While blocked, keep probing so an automatic recovery (server back,
|
|
1605
|
-
// machine woke) lifts the block even if the user never clicks Retry.
|
|
1606
|
-
startBlockedProbeLoop();
|
|
1607
|
-
}
|
|
1608
|
-
}
|
|
1609
|
-
}
|
|
1610
|
-
function startHeartbeat() {
|
|
1611
|
-
if (hb || submitted) return;
|
|
1612
|
-
hb = setInterval(heartbeatTick, 3000);
|
|
1613
|
-
}
|
|
1614
|
-
function stopHeartbeat() {
|
|
1615
|
-
if (hb) clearInterval(hb);
|
|
1616
|
-
hb = null;
|
|
1617
|
-
}
|
|
1618
|
-
|
|
1619
|
-
// While blocked, the heartbeat is stopped — so run a lightweight probe loop
|
|
1620
|
-
// that lifts the block automatically the moment the server is reachable again
|
|
1621
|
-
// (no Retry click needed). Stops itself on recovery or after submit.
|
|
1622
|
-
let blockedProbe = null;
|
|
1623
|
-
function startBlockedProbeLoop() {
|
|
1624
|
-
if (blockedProbe) return;
|
|
1625
|
-
blockedProbe = setInterval(async () => {
|
|
1626
|
-
if (!persistenceLost || submitted) {
|
|
1627
|
-
clearInterval(blockedProbe);
|
|
1628
|
-
blockedProbe = null;
|
|
1629
|
-
return;
|
|
1630
|
-
}
|
|
1631
|
-
if (probing) return;
|
|
1632
|
-
probing = true;
|
|
1633
|
-
const ok = await probeServer();
|
|
1634
|
-
probing = false;
|
|
1635
|
-
if (ok) {
|
|
1636
|
-
clearInterval(blockedProbe);
|
|
1637
|
-
blockedProbe = null;
|
|
1638
|
-
unblockAfterRecovery();
|
|
1639
|
-
}
|
|
1640
|
-
}, 3000);
|
|
1641
|
-
}
|
|
1642
|
-
startHeartbeat();
|
|
1643
|
-
})();
|