@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.
- package/bin/rly.js +1 -1
- package/package.json +4 -4
- 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 +1 -1
- 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 +12 -18
- package/src/{server.js → server/board.js} +15 -778
- 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/index.d.ts +1 -1
- 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.d.ts → spec/schema.d.ts} +0 -20
- package/types/spec/sources.d.ts +14 -0
- package/types/ui/manifest.d.ts +62 -0
- package/src/cli.js +0 -1767
- package/src/mcp-ui/board.js +0 -1162
- package/src/spec.js +0 -1224
- package/src/ui/annotate.js +0 -1055
- package/src/ui/app.js +0 -1643
- package/src/ui/blocks.js +0 -3260
package/src/ui/blocks.js
DELETED
|
@@ -1,3260 +0,0 @@
|
|
|
1
|
-
// blocks.js — window.RelayBlocks: renders normalized "blocks" (markdown,
|
|
2
|
-
// table, code, chart, mermaid, html) into a container. Zero runtime deps;
|
|
3
|
-
// vanilla DOM. Chart.js / Mermaid are vendored and lazy-loaded on demand.
|
|
4
|
-
// XSS-safe: all source text is HTML-escaped before any markdown transform.
|
|
5
|
-
(() => {
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
// ---------- tiny DOM helper (mirrors app.js idiom) ----------
|
|
9
|
-
function el(tag, attrs = {}, ...children) {
|
|
10
|
-
const n = document.createElement(tag);
|
|
11
|
-
for (const [k, v] of Object.entries(attrs)) {
|
|
12
|
-
if (v === undefined || v === null) continue;
|
|
13
|
-
if (k === 'class') n.className = v;
|
|
14
|
-
else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);
|
|
15
|
-
else n.setAttribute(k, v);
|
|
16
|
-
}
|
|
17
|
-
for (const c of children.flat()) {
|
|
18
|
-
if (c !== null && c !== undefined) n.append(c.nodeType ? c : document.createTextNode(c));
|
|
19
|
-
}
|
|
20
|
-
return n;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function esc(s) {
|
|
24
|
-
return String(s)
|
|
25
|
-
.replace(/&/g, '&')
|
|
26
|
-
.replace(/</g, '<')
|
|
27
|
-
.replace(/>/g, '>')
|
|
28
|
-
.replace(/"/g, '"')
|
|
29
|
-
.replace(/'/g, ''');
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// ---------- chart palette (from contract) ----------
|
|
33
|
-
const PALETTE_LIGHT = ['#c2674b', '#4d8a66', '#5a7ca8', '#b9913f', '#8a6da3', '#57534e'];
|
|
34
|
-
// Brighter/more saturated than the surfaces behind them so series stay legible
|
|
35
|
-
// on the dark card (#282624) — the muted set washed out at a glance.
|
|
36
|
-
const PALETTE_DARK = ['#e8a07a', '#74cfa0', '#88b4e8', '#e3c46a', '#c4a0db', '#c2b9ad'];
|
|
37
|
-
|
|
38
|
-
function cssVar(name) {
|
|
39
|
-
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// ---------- local file paths → click-to-open links ----------
|
|
43
|
-
// Agents routinely write a path (~/clip.mp4, ./src/app.js, /abs/file) and the
|
|
44
|
-
// user expects to click it open, not copy it into a terminal. We turn such
|
|
45
|
-
// paths into links that preview files in a dialog, with an explicit app-open
|
|
46
|
-
// fallback. FILE_PATH_RE / looksLikeLocalPath MUST match the same logic
|
|
47
|
-
// in server.js so the page only links what the server will agree to open.
|
|
48
|
-
// The body class also excludes \0 (the placeholder delimiter mdInline uses
|
|
49
|
-
// below) so a path butted against a stashed span can't swallow it; \0 never
|
|
50
|
-
// appears in real text, so this doesn't change which real paths match.
|
|
51
|
-
const FILE_PATH_RE =
|
|
52
|
-
/(?<![\w@:./])(?:file:\/\/\/?[^\s)<>"'`*\0]+|~\/[^\s)<>"'`*\0]+|\.{1,2}\/[^\s)<>"'`*\0]+|\/[^\s)<>"'`*\0]+|[A-Za-z]:[\\/][^\s)<>"'`*\0]+)/g;
|
|
53
|
-
|
|
54
|
-
// Note: candidates here are HTML-escaped (esc() ran first), but escaping only
|
|
55
|
-
// touches & < > " ' — none of which appear in a path's structural prefix, so
|
|
56
|
-
// these tests are safe to run on the escaped text. Mirrors server.js.
|
|
57
|
-
function looksLikeLocalPath(s) {
|
|
58
|
-
if (typeof s !== 'string') return false;
|
|
59
|
-
const t = s.trim();
|
|
60
|
-
if (!t || /\s/.test(t)) return false;
|
|
61
|
-
if (/^file:\/\//i.test(t)) return true;
|
|
62
|
-
if (/^[A-Za-z]:[\\/]/.test(t)) return true; // windows drive
|
|
63
|
-
if (t === '~' || /^~\//.test(t)) return true;
|
|
64
|
-
if (/^\.\.?\//.test(t)) return true; // ./ or ../
|
|
65
|
-
if (t.startsWith('/')) return /\/[^/]+\/[^/]/.test(t) || /\.[A-Za-z0-9]{1,8}$/.test(t);
|
|
66
|
-
return false;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Builds the <a> for a file path. `raw` and `label` are already escaped, so
|
|
70
|
-
// they embed safely inside the attribute and text. codeStyle keeps the
|
|
71
|
-
// monospace look when the path came from a `backtick` span.
|
|
72
|
-
function fileLinkHtml(raw, label, codeStyle) {
|
|
73
|
-
const cls = 'rly-filelink' + (codeStyle ? ' rly-filelink-code' : '');
|
|
74
|
-
return (
|
|
75
|
-
`<a class="${cls}" role="link" tabindex="0" data-rly-open="${raw}" ` +
|
|
76
|
-
`title="Preview ${raw}" aria-haspopup="dialog">` +
|
|
77
|
-
`<span class="rly-filelink-ico" aria-hidden="true"></span>` +
|
|
78
|
-
`<span class="rly-filelink-txt">${label}</span></a>`
|
|
79
|
-
);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// ---------- markdown mini renderer (NO library) ----------
|
|
83
|
-
// Escape FIRST, then apply transforms on the already-escaped text. Because
|
|
84
|
-
// <, >, & are gone, our generated tags are the only real tags in the output.
|
|
85
|
-
function mdInline(escaped) {
|
|
86
|
-
// Stash code/link/file-link HTML behind \0-delimited placeholders so the
|
|
87
|
-
// later path-autolink and bold/italic passes can't re-tokenize inside them.
|
|
88
|
-
// \0 never appears in real text, so the placeholders can't collide with it.
|
|
89
|
-
const stash = [];
|
|
90
|
-
const keep = (html) => '\0' + (stash.push(html) - 1) + '\0';
|
|
91
|
-
|
|
92
|
-
let s = escaped;
|
|
93
|
-
// inline code first so its contents aren't treated as bold/italic/links —
|
|
94
|
-
// a backtick span that is ITSELF a lone path opens instead of just showing.
|
|
95
|
-
s = s.replace(/`([^`]+)`/g, (_m, c) =>
|
|
96
|
-
looksLikeLocalPath(c) ? keep(fileLinkHtml(c.trim(), c, true)) : keep(`<code>${c}</code>`)
|
|
97
|
-
);
|
|
98
|
-
// reference links [label](#ref:name) / [label](#block:id) open the named/identified
|
|
99
|
-
// block in a full-screen modal — so a question can point back to a chart/image
|
|
100
|
-
// shown earlier without the user scrolling up. Runs before the generic link
|
|
101
|
-
// pass so the #ref:/#block: target isn't rendered as a plain href.
|
|
102
|
-
s = s.replace(/\[([^\]]+)\]\(#(ref|block):([^)\s]+)\)/g, (_m, label, kind, target) =>
|
|
103
|
-
keep(`<a class="rly-reflink" role="button" tabindex="0" data-rly-${kind === 'block' ? 'refid' : 'ref'}="${target}" title="Open this visual">` +
|
|
104
|
-
`<span class="rly-reflink-ico" aria-hidden="true"></span><span>${label}</span></a>`));
|
|
105
|
-
// images  BEFORE links so the leading "!" isn't stranded as text.
|
|
106
|
-
// A remote/data image embeds inline; a local path stays a click-to-open link
|
|
107
|
-
// (the board server doesn't serve the source file's directory).
|
|
108
|
-
// ponytail: remote/data images embed; local-relative images open in the app
|
|
109
|
-
// rather than render — add directory serving only if users need inline locals.
|
|
110
|
-
s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_m, alt, url) => {
|
|
111
|
-
if (/^(https?:|data:image\/)/i.test(url)) return keep(`<img class="md-img" src="${url}" alt="${alt}" loading="lazy">`);
|
|
112
|
-
if (looksLikeLocalPath(url)) return keep(fileLinkHtml(url, alt || url, false));
|
|
113
|
-
return ``; // unknown scheme — leave literal, don't link
|
|
114
|
-
});
|
|
115
|
-
// links [text](url) — url is already escaped; a local-path target becomes a
|
|
116
|
-
// click-to-open link, otherwise a normal link (guarding odd schemes).
|
|
117
|
-
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_m, text, url) => {
|
|
118
|
-
if (looksLikeLocalPath(url)) return keep(fileLinkHtml(url, text, false));
|
|
119
|
-
const safe = /^(https?:|mailto:|\/|#|\.)/i.test(url) ? url : '#';
|
|
120
|
-
return keep(`<a href="${safe}" target="_blank" rel="noopener">${text}</a>`);
|
|
121
|
-
});
|
|
122
|
-
// bare paths in running text (the common case: the agent just typed a path)
|
|
123
|
-
s = s.replace(FILE_PATH_RE, (m) => (looksLikeLocalPath(m) ? keep(fileLinkHtml(m, m, false)) : m));
|
|
124
|
-
// bold then italic (bold uses ** so must run before single *)
|
|
125
|
-
s = s.replace(/\*\*([^*]+)\*\*/g, (_m, c) => `<strong>${c}</strong>`);
|
|
126
|
-
s = s.replace(/\*([^*]+)\*/g, (_m, c) => `<em>${c}</em>`);
|
|
127
|
-
// underscore emphasis __bold__ / _italic_, only at word boundaries so
|
|
128
|
-
// snake_case and RLY_BOARD_ID are left alone (CommonMark intraword rule).
|
|
129
|
-
s = s.replace(/(^|[^A-Za-z0-9_])__([^_]+)__(?![A-Za-z0-9_])/g, (_m, p, c) => `${p}<strong>${c}</strong>`);
|
|
130
|
-
s = s.replace(/(^|[^A-Za-z0-9_])_([^_]+)_(?![A-Za-z0-9_])/g, (_m, p, c) => `${p}<em>${c}</em>`);
|
|
131
|
-
// restore the stashed HTML — loop so a placeholder nested inside another
|
|
132
|
-
// stashed fragment (e.g. a code span inside a link's text) is also resolved.
|
|
133
|
-
let guard = 0;
|
|
134
|
-
while (s.indexOf('\0') !== -1 && guard++ < 6) {
|
|
135
|
-
s = s.replace(/\0(\d+)\0/g, (_m, i) => (stash[Number(i)] !== undefined ? stash[Number(i)] : ''));
|
|
136
|
-
}
|
|
137
|
-
return s;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function renderMarkdown(md) {
|
|
141
|
-
const root = el('div', { class: 'md' });
|
|
142
|
-
const lines = String(md).replace(/\r\n?/g, '\n').split('\n');
|
|
143
|
-
let html = '';
|
|
144
|
-
let i = 0;
|
|
145
|
-
|
|
146
|
-
// list-stack rendering supports one nesting level (indent >= 2 spaces)
|
|
147
|
-
function consumeList() {
|
|
148
|
-
const blocks = []; // {ordered, items:[{html, sub:[...]}]}
|
|
149
|
-
let cur = null;
|
|
150
|
-
while (i < lines.length) {
|
|
151
|
-
const line = lines[i];
|
|
152
|
-
const m = line.match(/^(\s*)([-*]|\d+\.)\s+(.*)$/);
|
|
153
|
-
if (!m) break;
|
|
154
|
-
const indent = m[1].length;
|
|
155
|
-
const ordered = /\d+\./.test(m[2]);
|
|
156
|
-
const content = mdInline(esc(m[3]));
|
|
157
|
-
if (indent >= 2 && cur && cur.items.length) {
|
|
158
|
-
// nested under the previous top-level item
|
|
159
|
-
const parent = cur.items[cur.items.length - 1];
|
|
160
|
-
if (!parent.sub) parent.sub = { ordered, items: [] };
|
|
161
|
-
parent.sub.items.push(content);
|
|
162
|
-
} else {
|
|
163
|
-
if (!cur || cur.ordered !== ordered) {
|
|
164
|
-
cur = { ordered, items: [] };
|
|
165
|
-
blocks.push(cur);
|
|
166
|
-
}
|
|
167
|
-
cur.items.push({ html: content, sub: null });
|
|
168
|
-
}
|
|
169
|
-
i++;
|
|
170
|
-
}
|
|
171
|
-
let out = '';
|
|
172
|
-
for (const b of blocks) {
|
|
173
|
-
const tag = b.ordered ? 'ol' : 'ul';
|
|
174
|
-
out += `<${tag}>`;
|
|
175
|
-
for (const it of b.items) {
|
|
176
|
-
out += `<li>${it.html}`;
|
|
177
|
-
if (it.sub) {
|
|
178
|
-
const st = it.sub.ordered ? 'ol' : 'ul';
|
|
179
|
-
out += `<${st}>` + it.sub.items.map((x) => `<li>${x}</li>`).join('') + `</${st}>`;
|
|
180
|
-
}
|
|
181
|
-
out += '</li>';
|
|
182
|
-
}
|
|
183
|
-
out += `</${tag}>`;
|
|
184
|
-
}
|
|
185
|
-
return out;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// GFM pipe tables — a header row of "| a | b |" cells immediately followed
|
|
189
|
-
// by a separator row of dashes (with optional ":" alignment markers).
|
|
190
|
-
// Rendered as a real .blk-table so it matches the dedicated table block.
|
|
191
|
-
function splitRow(row) {
|
|
192
|
-
const trimmed = row.trim().replace(/^\|/, '').replace(/\|$/, '');
|
|
193
|
-
return trimmed.split(/(?<!\\)\|/).map((c) => c.replace(/\\\|/g, '|').trim());
|
|
194
|
-
}
|
|
195
|
-
function isSepRow(row) {
|
|
196
|
-
if (!row || row.indexOf('|') === -1) return false;
|
|
197
|
-
const cells = splitRow(row);
|
|
198
|
-
return cells.length > 0 && cells.every((c) => /^:?-{1,}:?$/.test(c));
|
|
199
|
-
}
|
|
200
|
-
function isTableStart(idx) {
|
|
201
|
-
const head = lines[idx];
|
|
202
|
-
return (
|
|
203
|
-
idx + 1 < lines.length &&
|
|
204
|
-
head.indexOf('|') !== -1 &&
|
|
205
|
-
!isSepRow(head) &&
|
|
206
|
-
isSepRow(lines[idx + 1])
|
|
207
|
-
);
|
|
208
|
-
}
|
|
209
|
-
function consumeTable() {
|
|
210
|
-
const headers = splitRow(lines[i]);
|
|
211
|
-
const aligns = splitRow(lines[i + 1]).map((c) => {
|
|
212
|
-
const left = c.startsWith(':');
|
|
213
|
-
const right = c.endsWith(':');
|
|
214
|
-
return left && right ? 'center' : right ? 'right' : left ? 'left' : '';
|
|
215
|
-
});
|
|
216
|
-
i += 2;
|
|
217
|
-
const body = [];
|
|
218
|
-
while (i < lines.length && !/^\s*$/.test(lines[i]) && lines[i].indexOf('|') !== -1 && !isSepRow(lines[i])) {
|
|
219
|
-
body.push(splitRow(lines[i]));
|
|
220
|
-
i++;
|
|
221
|
-
}
|
|
222
|
-
const ncols = headers.length;
|
|
223
|
-
const alignAttr = (ci) => (aligns[ci] ? ` style="text-align:${aligns[ci]}"` : '');
|
|
224
|
-
const cell = (tag, ci, text) => `<${tag}${alignAttr(ci)}>${mdInline(esc(text == null ? '' : text))}</${tag}>`;
|
|
225
|
-
let out = '<div class="md-tablewrap"><table class="blk-table md-table"><thead><tr>';
|
|
226
|
-
for (let c = 0; c < ncols; c++) out += cell('th', c, headers[c]);
|
|
227
|
-
out += '</tr></thead><tbody>';
|
|
228
|
-
for (const r of body) {
|
|
229
|
-
out += '<tr>';
|
|
230
|
-
for (let c = 0; c < ncols; c++) out += cell('td', c, r[c]);
|
|
231
|
-
out += '</tr>';
|
|
232
|
-
}
|
|
233
|
-
out += '</tbody></table></div>';
|
|
234
|
-
return out;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
while (i < lines.length) {
|
|
238
|
-
const line = lines[i];
|
|
239
|
-
|
|
240
|
-
// fenced code block ```lang
|
|
241
|
-
const fence = line.match(/^```\s*([\w+-]*)\s*$/);
|
|
242
|
-
if (fence) {
|
|
243
|
-
i++;
|
|
244
|
-
const buf = [];
|
|
245
|
-
while (i < lines.length && !/^```\s*$/.test(lines[i])) buf.push(lines[i++]);
|
|
246
|
-
if (i < lines.length) i++; // closing fence
|
|
247
|
-
html += `<pre class="md-pre"><code>${esc(buf.join('\n'))}</code></pre>`;
|
|
248
|
-
continue;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// horizontal rule
|
|
252
|
-
if (/^\s*---+\s*$/.test(line)) { html += '<hr>'; i++; continue; }
|
|
253
|
-
|
|
254
|
-
// headings
|
|
255
|
-
const h = line.match(/^(#{1,3})\s+(.*)$/);
|
|
256
|
-
if (h) {
|
|
257
|
-
const lvl = h[1].length;
|
|
258
|
-
html += `<h${lvl}>${mdInline(esc(h[2]))}</h${lvl}>`;
|
|
259
|
-
i++;
|
|
260
|
-
continue;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// blockquote (collapse consecutive > lines)
|
|
264
|
-
if (/^\s*>\s?/.test(line)) {
|
|
265
|
-
const buf = [];
|
|
266
|
-
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
|
|
267
|
-
buf.push(lines[i].replace(/^\s*>\s?/, ''));
|
|
268
|
-
i++;
|
|
269
|
-
}
|
|
270
|
-
html += `<blockquote>${mdInline(esc(buf.join(' ')))}</blockquote>`;
|
|
271
|
-
continue;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// GFM pipe table (header row + dash separator)
|
|
275
|
-
if (isTableStart(i)) { html += consumeTable(); continue; }
|
|
276
|
-
|
|
277
|
-
// lists
|
|
278
|
-
if (/^(\s*)([-*]|\d+\.)\s+/.test(line)) { html += consumeList(); continue; }
|
|
279
|
-
|
|
280
|
-
// blank line
|
|
281
|
-
if (/^\s*$/.test(line)) { i++; continue; }
|
|
282
|
-
|
|
283
|
-
// paragraph — accumulate until blank / block boundary
|
|
284
|
-
const buf = [];
|
|
285
|
-
while (
|
|
286
|
-
i < lines.length &&
|
|
287
|
-
!/^\s*$/.test(lines[i]) &&
|
|
288
|
-
!/^```/.test(lines[i]) &&
|
|
289
|
-
!/^\s*---+\s*$/.test(lines[i]) &&
|
|
290
|
-
!/^#{1,3}\s+/.test(lines[i]) &&
|
|
291
|
-
!/^\s*>\s?/.test(lines[i]) &&
|
|
292
|
-
!/^(\s*)([-*]|\d+\.)\s+/.test(lines[i]) &&
|
|
293
|
-
!isTableStart(i)
|
|
294
|
-
) {
|
|
295
|
-
buf.push(lines[i]);
|
|
296
|
-
i++;
|
|
297
|
-
}
|
|
298
|
-
html += `<p>${mdInline(esc(buf.join('\n'))).replace(/\n/g, '<br>')}</p>`;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
root.innerHTML = html;
|
|
302
|
-
return root;
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// ---------- code tinter (lightweight, zero-dependency, offline) ----------
|
|
306
|
-
// Per language we record its comment style(s), whether it has backtick
|
|
307
|
-
// strings, and its keyword set. From those a single alternation regex tints
|
|
308
|
-
// comments / strings / numbers / keywords in one pass. Unknown languages
|
|
309
|
-
// render as plain escaped text; css / html / xml get bespoke patterns.
|
|
310
|
-
// Mirrors the wide-compat goal: no library, works in every browser offline.
|
|
311
|
-
const LANGS = {
|
|
312
|
-
js: { c: true, tmpl: true, kw: 'await async break case catch class const continue debugger default delete do else export extends false finally for from function get if import in instanceof let new null of return set static super switch this throw true try typeof undefined var void while yield' },
|
|
313
|
-
ts: { c: true, tmpl: true, kw: 'abstract any as asserts async await boolean break case catch class const continue declare default delete do else enum export extends false finally for from function get if implements import in infer instanceof interface is keyof let namespace never new null number object of private protected public readonly return satisfies set static string super switch this throw true try type typeof undefined unknown var void while yield' },
|
|
314
|
-
json: { kw: 'true false null' },
|
|
315
|
-
py: { hash: true, kw: 'and as assert async await break case class continue def del elif else except False finally for from global if import in is lambda match None nonlocal not or pass raise return self True try while with yield' },
|
|
316
|
-
sh: { hash: true, kw: 'if then else elif fi for while until do done case esac function in return export local readonly echo cd set unset source eval exec trap exit' },
|
|
317
|
-
go: { c: true, tmpl: true, kw: 'break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var nil true false iota' },
|
|
318
|
-
rust: { c: true, kw: 'as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while' },
|
|
319
|
-
java: { c: true, kw: 'abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true false try void volatile while var record sealed' },
|
|
320
|
-
c: { c: true, kw: 'auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while bool true false NULL' },
|
|
321
|
-
cpp: { c: true, kw: 'alignas alignof auto bool break case catch char class const constexpr continue decltype default delete do double else enum explicit export extern false float for friend goto if inline int long mutable namespace new noexcept nullptr operator private protected public register return short signed sizeof static struct switch template this throw true try typedef typename union unsigned using virtual void volatile while' },
|
|
322
|
-
csharp: { c: true, kw: 'abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using var virtual void volatile while async await yield' },
|
|
323
|
-
ruby: { hash: true, kw: 'alias and begin break case class def defined do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true unless until when while yield require attr_accessor' },
|
|
324
|
-
php: { c: true, hash: true, kw: 'abstract and array as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum extends false final finally fn for foreach function global goto if implements include instanceof insteadof interface isset list match namespace new null or print private protected public readonly return static switch throw trait true try unset use var while xor yield' },
|
|
325
|
-
swift: { c: true, kw: 'associatedtype class deinit enum extension fileprivate func import init inout internal let open operator private protocol public rethrows static struct subscript typealias var break case continue default defer do else fallthrough for guard if in repeat return switch where while as catch false is nil super self throw throws true try' },
|
|
326
|
-
kotlin: { c: true, kw: 'abstract actual annotation as break by catch class companion const constructor continue crossinline data delegate do dynamic else enum external false final finally for fun get if import in infix init inline inner interface internal is lateinit lazy null object open operator out override package private protected public reified return sealed set super suspend this throw true try typealias val var vararg when where while' },
|
|
327
|
-
yaml: { hash: true, kw: 'true false null yes no on off' },
|
|
328
|
-
toml: { hash: true, kw: 'true false' },
|
|
329
|
-
sql: { c: true, sql: true, kwi: true, kw: 'select from where insert into values update set delete create table alter drop index view join inner left right outer full on as and or not null is in like between group by order having limit offset union all distinct count sum avg min max case when then else end primary key foreign references default unique constraint cascade asc desc returning with' },
|
|
330
|
-
css: { special: 'css' },
|
|
331
|
-
html: { special: 'html' },
|
|
332
|
-
};
|
|
333
|
-
const LANG_ALIAS = {
|
|
334
|
-
javascript: 'js', node: 'js', mjs: 'js', cjs: 'js', jsx: 'js',
|
|
335
|
-
typescript: 'ts', tsx: 'ts',
|
|
336
|
-
shell: 'sh', bash: 'sh', zsh: 'sh', console: 'sh',
|
|
337
|
-
python: 'py', py3: 'py',
|
|
338
|
-
golang: 'go', rs: 'rust', 'c++': 'cpp', cc: 'cpp', cxx: 'cpp', hpp: 'cpp', 'c#': 'csharp', cs: 'csharp',
|
|
339
|
-
rb: 'ruby', kt: 'kotlin',
|
|
340
|
-
yml: 'yaml', xml: 'html', svg: 'html', htm: 'html',
|
|
341
|
-
jsonc: 'json', json5: 'json',
|
|
342
|
-
};
|
|
343
|
-
|
|
344
|
-
function tintCode(code, lang) {
|
|
345
|
-
const key0 = (lang || '').toLowerCase().trim();
|
|
346
|
-
const cfg = LANGS[LANG_ALIAS[key0] || key0];
|
|
347
|
-
if (!cfg) return esc(code); // unknown lang -> plain
|
|
348
|
-
|
|
349
|
-
// Build ONE alternation regex with a parallel classes[] so group g (1-based)
|
|
350
|
-
// maps to classes[g-1]. Each pushed source is wrapped in exactly one
|
|
351
|
-
// capturing group; the source bodies use only non-capturing groups.
|
|
352
|
-
const parts = [];
|
|
353
|
-
const classes = [];
|
|
354
|
-
const push = (src, cls) => { parts.push('(' + src + ')'); classes.push(cls); };
|
|
355
|
-
if (cfg.special === 'css') {
|
|
356
|
-
push(/\/\*[\s\S]*?\*\//.source, 'com');
|
|
357
|
-
push(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/.source, 'str');
|
|
358
|
-
push(/[A-Za-z-]+(?=\s*:)/.source, 'kw');
|
|
359
|
-
push(/\b\d+(?:\.\d+)?(?:px|em|rem|%|vh|vw|s|ms|deg)?\b/.source, 'num');
|
|
360
|
-
} else if (cfg.special === 'html') {
|
|
361
|
-
push(/<!--[\s\S]*?-->/.source, 'com');
|
|
362
|
-
push(/<\/?[A-Za-z][\w-]*|\/?>/.source, 'kw');
|
|
363
|
-
push(/"[^"]*"/.source, 'str');
|
|
364
|
-
} else {
|
|
365
|
-
if (cfg.c) { push(/\/\*[\s\S]*?\*\//.source, 'com'); push(/\/\/[^\n]*/.source, 'com'); }
|
|
366
|
-
if (cfg.hash) push(/#[^\n]*/.source, 'com');
|
|
367
|
-
if (cfg.sql) push(/--[^\n]*/.source, 'com');
|
|
368
|
-
push((cfg.tmpl
|
|
369
|
-
? /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/
|
|
370
|
-
: /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/).source, 'str');
|
|
371
|
-
push(/\b(?:0x[\da-fA-F]+|\d+(?:\.\d+)?)\b/.source, 'num');
|
|
372
|
-
let kws = (cfg.kw || '').split(' ').filter(Boolean);
|
|
373
|
-
if (cfg.kwi) kws = kws.concat(kws.map((k) => k.toUpperCase())); // SQL: also UPPERCASE
|
|
374
|
-
if (kws.length) push('\\b(?:' + kws.join('|') + ')\\b', 'kw');
|
|
375
|
-
}
|
|
376
|
-
const rx = new RegExp(parts.join('|'), 'g');
|
|
377
|
-
let out = '';
|
|
378
|
-
let last = 0;
|
|
379
|
-
let m;
|
|
380
|
-
while ((m = rx.exec(code))) {
|
|
381
|
-
out += esc(code.slice(last, m.index));
|
|
382
|
-
let cls = null;
|
|
383
|
-
for (let g = 1; g < m.length; g++) {
|
|
384
|
-
if (m[g] !== undefined) {
|
|
385
|
-
cls = classes[g - 1];
|
|
386
|
-
break;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
out += cls ? '<span class="tok-' + cls + '">' + esc(m[0]) + '</span>' : esc(m[0]);
|
|
390
|
-
last = m.index + m[0].length;
|
|
391
|
-
if (m[0].length === 0) rx.lastIndex++;
|
|
392
|
-
}
|
|
393
|
-
out += esc(code.slice(last));
|
|
394
|
-
return out;
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
// A line-number gutter for `text` (non-selectable so a select-to-comment grabs
|
|
398
|
-
// only the code, not the numbers). When annotation is on, each number becomes a
|
|
399
|
-
// hover/click target to comment on that exact line (kind:'code-line'); the
|
|
400
|
-
// numbers still don't enter a text selection. `startAt` default 1.
|
|
401
|
-
function lineGutter(text, startAt, ctx, blockId, filename) {
|
|
402
|
-
const n = Math.max(1, String(text).replace(/\n+$/, '').split('\n').length);
|
|
403
|
-
const annotate = ctx && ctx.annotate;
|
|
404
|
-
const g = el('div', { class: 'blk-gutter' + (annotate ? ' blk-gutter-c' : ''), 'aria-hidden': annotate ? null : 'true' });
|
|
405
|
-
for (let i = 0; i < n; i++) {
|
|
406
|
-
const ln = (startAt || 1) + i;
|
|
407
|
-
const lineEl = el('div', { class: 'blk-gutterline' }, String(ln));
|
|
408
|
-
if (annotate) {
|
|
409
|
-
annotate.register(lineEl, {
|
|
410
|
-
blockId, questionId: ctx.questionId,
|
|
411
|
-
target: { kind: 'code-line', line: ln, file: filename || '' },
|
|
412
|
-
});
|
|
413
|
-
}
|
|
414
|
-
g.append(lineEl);
|
|
415
|
-
}
|
|
416
|
-
return g;
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
function renderCode(block, ctx, blockId) {
|
|
420
|
-
// Drop a single trailing newline so the last source line isn't rendered as
|
|
421
|
-
// an empty row the gutter has no number for (files usually end in "\n").
|
|
422
|
-
const raw = (block.code || '').replace(/\n$/, '');
|
|
423
|
-
const code = el('code');
|
|
424
|
-
code.innerHTML = tintCode(raw, block.lang);
|
|
425
|
-
const pre = el('pre', { class: 'blk-pre', 'data-lang': block.lang || '' }, code);
|
|
426
|
-
const row = el('div', { class: 'blk-coderow' }, lineGutter(raw, 1, ctx, blockId, block.filename), pre);
|
|
427
|
-
const wrap = el('div', { class: 'blk-codewrap' });
|
|
428
|
-
// Optional file-name + language header above the code.
|
|
429
|
-
if (block.filename || block.lang) {
|
|
430
|
-
wrap.append(el('div', { class: 'blk-codehead' },
|
|
431
|
-
el('span', { class: 'blk-codename' }, block.filename || ''),
|
|
432
|
-
el('span', { class: 'blk-codelang' }, block.lang || '')
|
|
433
|
-
));
|
|
434
|
-
}
|
|
435
|
-
wrap.append(row);
|
|
436
|
-
// select-to-comment on the code text (like markdown), plus a whole-block
|
|
437
|
-
// comment + full-screen via the shared viewer toolbar
|
|
438
|
-
ctx && ctx.annotate && ctx.annotate.enableTextSelection(pre, { blockId, questionId: ctx.questionId });
|
|
439
|
-
attachViewer(wrap, { zoomEl: null, label: 'code', comment: wholeBlockComment(ctx, blockId, 'code') });
|
|
440
|
-
return wrap;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
// ---------- diff (unified / git diff) ----------
|
|
444
|
-
// No git is involved — the agent supplies the diff text. Parsed once into
|
|
445
|
-
// rows, then rendered either UNIFIED (one column, +/- signs) or SPLIT (old |
|
|
446
|
-
// new side-by-side). A header toggle flips between the two live; the block's
|
|
447
|
-
// "view" sets the initial mode. Each code line is tinted by lang.
|
|
448
|
-
|
|
449
|
-
// Parse a unified diff into a flat row list: {kind, text, oldNo, newNo}
|
|
450
|
-
// (line numbers stored 0-based; rendered +1).
|
|
451
|
-
function parseDiff(text) {
|
|
452
|
-
const lines = String(text || '').replace(/\r\n?/g, '\n').split('\n');
|
|
453
|
-
const rows = [];
|
|
454
|
-
let oldNo = 0;
|
|
455
|
-
let newNo = 0;
|
|
456
|
-
// Diff content (+/-/context) only has meaning INSIDE a hunk. Lines before the
|
|
457
|
-
// first @@ are either recognized headers (handled below) or the commit
|
|
458
|
-
// header/message of `git show`/`git log -p` output — skip the latter so it
|
|
459
|
-
// isn't rendered as bogus context rows (which split view duplicates on both
|
|
460
|
-
// sides as long unwrapped lines, shoving the new side off-screen).
|
|
461
|
-
let inHunk = false;
|
|
462
|
-
for (const line of lines) {
|
|
463
|
-
if (/^@@/.test(line)) {
|
|
464
|
-
const m = line.match(/@@\s*-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);
|
|
465
|
-
if (m) { oldNo = Number(m[1]) - 1; newNo = Number(m[2]) - 1; }
|
|
466
|
-
inHunk = true;
|
|
467
|
-
rows.push({ kind: 'hunk', text: line });
|
|
468
|
-
} else if (/^(diff |index |--- |\+\+\+ |new file|deleted file|old mode|new mode|similarity|rename |copy )/.test(line)) {
|
|
469
|
-
rows.push({ kind: 'meta', text: line });
|
|
470
|
-
} else if (!inHunk) {
|
|
471
|
-
continue; // commit header/message preamble before the first hunk — drop it
|
|
472
|
-
} else if (line[0] === '+') {
|
|
473
|
-
rows.push({ kind: 'add', text: line.slice(1), newNo: newNo++ });
|
|
474
|
-
} else if (line[0] === '-') {
|
|
475
|
-
rows.push({ kind: 'del', text: line.slice(1), oldNo: oldNo++ });
|
|
476
|
-
} else {
|
|
477
|
-
rows.push({ kind: 'ctx', text: line[0] === ' ' ? line.slice(1) : line, oldNo: oldNo++, newNo: newNo++ });
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
return rows;
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
function diffNoTd(n, extraClass) {
|
|
484
|
-
const td = el('td', { class: 'diff-no' + (extraClass ? ' ' + extraClass : ''), 'aria-hidden': 'true' });
|
|
485
|
-
if (n !== undefined && n !== null) td.textContent = String(n + 1);
|
|
486
|
-
return td;
|
|
487
|
-
}
|
|
488
|
-
function diffCodeTd(html, extraClass) {
|
|
489
|
-
const c = el('code');
|
|
490
|
-
c.innerHTML = html || ' ';
|
|
491
|
-
return el('td', { class: 'diff-code' + (extraClass ? ' ' + extraClass : '') }, c);
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
// Unified: oldNo | newNo | sign | code
|
|
495
|
-
function buildUnifiedDiff(rows, lang) {
|
|
496
|
-
const tbody = el('tbody');
|
|
497
|
-
for (const r of rows) {
|
|
498
|
-
const full = r.kind === 'hunk' || r.kind === 'meta';
|
|
499
|
-
const codeHtml = full ? esc(r.text) : tintCode(r.text, lang);
|
|
500
|
-
const sign = r.kind === 'add' ? '+' : r.kind === 'del' ? '−' : '';
|
|
501
|
-
tbody.append(el('tr', { class: 'diff-row diff-' + r.kind },
|
|
502
|
-
diffNoTd(r.oldNo),
|
|
503
|
-
diffNoTd(r.newNo),
|
|
504
|
-
el('td', { class: 'diff-sign', 'aria-hidden': 'true' }, sign),
|
|
505
|
-
diffCodeTd(codeHtml)
|
|
506
|
-
));
|
|
507
|
-
}
|
|
508
|
-
return el('table', { class: 'blk-difftable' }, tbody);
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
// Split: oldNo | old code || newNo | new code. A run of removed lines is
|
|
512
|
-
// paired row-by-row with the following run of added lines; the shorter side
|
|
513
|
-
// gets filler cells. Context shows identically on both sides.
|
|
514
|
-
function buildSplitDiff(rows, lang) {
|
|
515
|
-
const tbody = el('tbody');
|
|
516
|
-
const fullRow = (cls, text) => {
|
|
517
|
-
const c = el('code');
|
|
518
|
-
c.innerHTML = esc(text) || ' ';
|
|
519
|
-
tbody.append(el('tr', { class: 'diff-row diff-' + cls }, el('td', { class: 'diff-code', colspan: '4' }, c)));
|
|
520
|
-
};
|
|
521
|
-
let dels = [];
|
|
522
|
-
let adds = [];
|
|
523
|
-
const flush = () => {
|
|
524
|
-
const n = Math.max(dels.length, adds.length);
|
|
525
|
-
for (let i = 0; i < n; i++) {
|
|
526
|
-
const d = dels[i];
|
|
527
|
-
const a = adds[i];
|
|
528
|
-
const left = d
|
|
529
|
-
? [diffNoTd(d.oldNo, 'diff-del'), diffCodeTd(tintCode(d.text, lang), 'diff-del')]
|
|
530
|
-
: [diffNoTd(null, 'diff-fill'), diffCodeTd(' ', 'diff-fill')];
|
|
531
|
-
const right = a
|
|
532
|
-
? [diffNoTd(a.newNo, 'diff-newside diff-add'), diffCodeTd(tintCode(a.text, lang), 'diff-add')]
|
|
533
|
-
: [diffNoTd(null, 'diff-fill diff-newside'), diffCodeTd(' ', 'diff-fill')];
|
|
534
|
-
tbody.append(el('tr', { class: 'diff-row' }, left[0], left[1], right[0], right[1]));
|
|
535
|
-
}
|
|
536
|
-
dels = [];
|
|
537
|
-
adds = [];
|
|
538
|
-
};
|
|
539
|
-
for (const r of rows) {
|
|
540
|
-
if (r.kind === 'del') { dels.push(r); continue; }
|
|
541
|
-
if (r.kind === 'add') { adds.push(r); continue; }
|
|
542
|
-
flush();
|
|
543
|
-
if (r.kind === 'hunk') fullRow('hunk', r.text);
|
|
544
|
-
else if (r.kind === 'meta') fullRow('meta', r.text);
|
|
545
|
-
else {
|
|
546
|
-
const html = tintCode(r.text, lang);
|
|
547
|
-
tbody.append(el('tr', { class: 'diff-row diff-ctx' },
|
|
548
|
-
diffNoTd(r.oldNo), diffCodeTd(html),
|
|
549
|
-
diffNoTd(r.newNo, 'diff-newside'), diffCodeTd(html)
|
|
550
|
-
));
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
flush();
|
|
554
|
-
return el('table', { class: 'blk-difftable blk-difftable-split' }, tbody);
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
// Split a (possibly multi-file) unified diff into per-file chunks. Each
|
|
558
|
-
// `diff --git a/x b/x` starts a new file; the name comes from that line (or a
|
|
559
|
-
// following `+++ b/...`). A plain hunk-only diff (no `diff --git`) is one
|
|
560
|
-
// unnamed file, preserving the single-file path that uses block.filename.
|
|
561
|
-
function splitDiffFiles(text) {
|
|
562
|
-
const lines = String(text || '').replace(/\r\n?/g, '\n').split('\n');
|
|
563
|
-
const files = [];
|
|
564
|
-
let cur = null;
|
|
565
|
-
for (const line of lines) {
|
|
566
|
-
if (/^diff --git /.test(line)) {
|
|
567
|
-
const m = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
|
|
568
|
-
cur = { name: m ? m[2] : 'file', lines: [line] };
|
|
569
|
-
files.push(cur);
|
|
570
|
-
} else {
|
|
571
|
-
if (!cur) { cur = { name: null, lines: [] }; files.push(cur); }
|
|
572
|
-
cur.lines.push(line);
|
|
573
|
-
if (cur.name === null) {
|
|
574
|
-
const pm = line.match(/^\+\+\+ b?\/(.+)$/);
|
|
575
|
-
if (pm) cur.name = pm[1];
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
return files.map((f) => ({ name: f.name, text: f.lines.join('\n') }));
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
// Per-file header lines are redundant once we render a filename header bar.
|
|
583
|
-
const DIFF_NOISE = /^(diff --git |index |--- |\+\+\+ )/;
|
|
584
|
-
|
|
585
|
-
function buildDiffReviewHunks(files, block) {
|
|
586
|
-
const hunks = [];
|
|
587
|
-
files.forEach((f) => {
|
|
588
|
-
const name = f.name || (files.length === 1 ? (block.filename || '') : '') || 'file';
|
|
589
|
-
let rows = parseDiff(f.text);
|
|
590
|
-
if (name) rows = rows.filter((r) => !(r.kind === 'meta' && DIFF_NOISE.test(r.text)));
|
|
591
|
-
let current = null;
|
|
592
|
-
const push = () => {
|
|
593
|
-
if (!current) return;
|
|
594
|
-
const hasChange = current.rows.some((r) => r.kind === 'add' || r.kind === 'del');
|
|
595
|
-
if (hasChange) hunks.push(current);
|
|
596
|
-
current = null;
|
|
597
|
-
};
|
|
598
|
-
rows.forEach((r) => {
|
|
599
|
-
if (r.kind === 'hunk') {
|
|
600
|
-
push();
|
|
601
|
-
current = { id: 'h' + (hunks.length + 1), file: name, header: r.text, rows: [r] };
|
|
602
|
-
} else if (current) {
|
|
603
|
-
current.rows.push(r);
|
|
604
|
-
} else if (r.kind === 'add' || r.kind === 'del' || r.kind === 'ctx') {
|
|
605
|
-
current = { id: 'h' + (hunks.length + 1), file: name, header: 'Change', rows: [r] };
|
|
606
|
-
}
|
|
607
|
-
});
|
|
608
|
-
push();
|
|
609
|
-
});
|
|
610
|
-
return hunks;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
function renderDiffReview(block, ctx, blockId, files) {
|
|
614
|
-
const hunks = buildDiffReviewHunks(files, block);
|
|
615
|
-
let view = block.view === 'split' ? 'split' : 'unified';
|
|
616
|
-
const prior = ctx && ctx.edits && ctx.edits[blockId] && typeof ctx.edits[blockId] === 'object'
|
|
617
|
-
? ctx.edits[blockId]
|
|
618
|
-
: {};
|
|
619
|
-
const choices = prior.hunks && typeof prior.hunks === 'object' ? { ...prior.hunks } : {};
|
|
620
|
-
const buttonsByHunk = new Map();
|
|
621
|
-
const wrap = el('div', { class: 'blk-codewrap blk-diffwrap diff-review' });
|
|
622
|
-
const status = el('span', { class: 'diff-review-status' }, '');
|
|
623
|
-
const list = el('div', { class: 'diff-review-list' });
|
|
624
|
-
|
|
625
|
-
const emit = () => {
|
|
626
|
-
const picked = {};
|
|
627
|
-
hunks.forEach((h) => {
|
|
628
|
-
const r = choices[h.id];
|
|
629
|
-
if (!r || !['apply', 'skip', 'hold'].includes(r.choice)) return;
|
|
630
|
-
picked[h.id] = { choice: r.choice, file: h.file, header: h.header };
|
|
631
|
-
});
|
|
632
|
-
const touched = Object.keys(picked).length;
|
|
633
|
-
const payload = touched
|
|
634
|
-
? {
|
|
635
|
-
type: 'diff-review',
|
|
636
|
-
reviewKind: block.reviewKind || '',
|
|
637
|
-
commit: block.commit || '',
|
|
638
|
-
title: block.title || block.filename || '',
|
|
639
|
-
resolved: touched === hunks.length,
|
|
640
|
-
hunks: picked,
|
|
641
|
-
}
|
|
642
|
-
: null;
|
|
643
|
-
if (ctx && typeof ctx.onBlockEdit === 'function') ctx.onBlockEdit(blockId, payload);
|
|
644
|
-
wrap.dispatchEvent(new CustomEvent('relay:block-edit', {
|
|
645
|
-
bubbles: true,
|
|
646
|
-
detail: { blockId, value: payload },
|
|
647
|
-
}));
|
|
648
|
-
status.textContent = `${touched}/${hunks.length} reviewed`;
|
|
649
|
-
status.classList.toggle('is-complete', hunks.length > 0 && touched === hunks.length);
|
|
650
|
-
for (const h of hunks) {
|
|
651
|
-
const set = buttonsByHunk.get(h.id) || [];
|
|
652
|
-
const chosen = choices[h.id] && choices[h.id].choice;
|
|
653
|
-
set.forEach((b) => b.el.classList.toggle('sel', b.choice === chosen));
|
|
654
|
-
}
|
|
655
|
-
};
|
|
656
|
-
|
|
657
|
-
const setChoice = (h, choice) => {
|
|
658
|
-
choices[h.id] = { choice, file: h.file, header: h.header };
|
|
659
|
-
emit();
|
|
660
|
-
};
|
|
661
|
-
|
|
662
|
-
const setAll = (choice) => {
|
|
663
|
-
hunks.forEach((h) => {
|
|
664
|
-
choices[h.id] = { choice, file: h.file, header: h.header };
|
|
665
|
-
});
|
|
666
|
-
emit();
|
|
667
|
-
};
|
|
668
|
-
|
|
669
|
-
const makeReviewButton = (label, onClick, extraClass = '') => {
|
|
670
|
-
const b = el('button', { type: 'button', class: 'diff-review-btn' + (extraClass ? ' ' + extraClass : '') }, label);
|
|
671
|
-
b.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
672
|
-
b.addEventListener('click', (e) => {
|
|
673
|
-
e.preventDefault();
|
|
674
|
-
e.stopPropagation();
|
|
675
|
-
onClick();
|
|
676
|
-
});
|
|
677
|
-
return b;
|
|
678
|
-
};
|
|
679
|
-
|
|
680
|
-
const repaint = () => {
|
|
681
|
-
list.replaceChildren();
|
|
682
|
-
hunks.forEach((h) => {
|
|
683
|
-
const actionbar = el('div', { class: 'diff-review-hunkbar' },
|
|
684
|
-
el('div', { class: 'diff-review-hunkmeta' },
|
|
685
|
-
el('span', { class: 'diff-review-file' }, h.file),
|
|
686
|
-
el('span', { class: 'diff-review-header' }, h.header)
|
|
687
|
-
)
|
|
688
|
-
);
|
|
689
|
-
const rowButtons = [
|
|
690
|
-
{ choice: 'apply', label: 'Apply hunk' },
|
|
691
|
-
{ choice: 'skip', label: 'Skip hunk' },
|
|
692
|
-
{ choice: 'hold', label: 'Hold' },
|
|
693
|
-
].map((item) => ({
|
|
694
|
-
choice: item.choice,
|
|
695
|
-
el: makeReviewButton(item.label, () => setChoice(h, item.choice), 'diff-review-choice'),
|
|
696
|
-
}));
|
|
697
|
-
buttonsByHunk.set(h.id, rowButtons);
|
|
698
|
-
actionbar.append(el('div', { class: 'diff-review-actions' }, rowButtons.map((b) => b.el)));
|
|
699
|
-
list.append(el('section', { class: 'diff-review-hunk' },
|
|
700
|
-
actionbar,
|
|
701
|
-
view === 'split' ? buildSplitDiff(h.rows, block.lang) : buildUnifiedDiff(h.rows, block.lang)
|
|
702
|
-
));
|
|
703
|
-
});
|
|
704
|
-
emit();
|
|
705
|
-
};
|
|
706
|
-
|
|
707
|
-
const toggle = makeReviewButton('', () => {
|
|
708
|
-
view = view === 'split' ? 'unified' : 'split';
|
|
709
|
-
wrap.classList.toggle('is-split', view === 'split');
|
|
710
|
-
toggle.textContent = view === 'split' ? 'Unified view' : 'Split view';
|
|
711
|
-
repaint();
|
|
712
|
-
}, 'blk-difftoggle');
|
|
713
|
-
toggle.title = 'Toggle side-by-side view';
|
|
714
|
-
toggle.textContent = view === 'split' ? 'Unified view' : 'Split view';
|
|
715
|
-
|
|
716
|
-
const title = block.title || block.filename || (files.length > 1 ? `${files.length} files changed` : 'Diff review');
|
|
717
|
-
wrap.append(el('div', { class: 'blk-codehead diff-review-head' },
|
|
718
|
-
el('span', { class: 'blk-codename' }, title),
|
|
719
|
-
el('div', { class: 'diff-review-topactions' },
|
|
720
|
-
status,
|
|
721
|
-
makeReviewButton('Apply all', () => setAll('apply')),
|
|
722
|
-
makeReviewButton('Skip all', () => setAll('skip')),
|
|
723
|
-
makeReviewButton('Hold all', () => setAll('hold')),
|
|
724
|
-
toggle
|
|
725
|
-
)
|
|
726
|
-
));
|
|
727
|
-
wrap.classList.toggle('is-split', view === 'split');
|
|
728
|
-
wrap.append(list);
|
|
729
|
-
repaint();
|
|
730
|
-
ctx && ctx.annotate && ctx.annotate.enableTextSelection(list, { blockId, questionId: ctx.questionId });
|
|
731
|
-
attachViewer(wrap, { zoomEl: null, label: 'diff review', comment: wholeBlockComment(ctx, blockId, 'diff review') });
|
|
732
|
-
return wrap;
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
function renderDiff(block, ctx, blockId) {
|
|
736
|
-
const files = splitDiffFiles(block.diff);
|
|
737
|
-
if (block.review === true && ctx.canEditBlocks !== false) return renderDiffReview(block, ctx, blockId, files);
|
|
738
|
-
const named = files.filter((f) => f.name);
|
|
739
|
-
const multi = named.length > 1;
|
|
740
|
-
let view = block.view === 'split' ? 'split' : 'unified';
|
|
741
|
-
const scroll = el('div', { class: 'blk-diffscroll' });
|
|
742
|
-
const sections = [];
|
|
743
|
-
|
|
744
|
-
const paint = () => {
|
|
745
|
-
scroll.replaceChildren();
|
|
746
|
-
sections.length = 0;
|
|
747
|
-
files.forEach((f) => {
|
|
748
|
-
const name = f.name || (files.length === 1 ? (block.filename || '') : '');
|
|
749
|
-
let rows = parseDiff(f.text);
|
|
750
|
-
// drop the pure file-header noise when we show a filename bar
|
|
751
|
-
if (name) rows = rows.filter((r) => !(r.kind === 'meta' && DIFF_NOISE.test(r.text)));
|
|
752
|
-
if (!rows.length) return;
|
|
753
|
-
const sec = el('div', { class: 'diff-file' });
|
|
754
|
-
if (name) sec.append(el('div', { class: 'diff-filehead' }, name));
|
|
755
|
-
sec.append(view === 'split' ? buildSplitDiff(rows, block.lang) : buildUnifiedDiff(rows, block.lang));
|
|
756
|
-
scroll.append(sec);
|
|
757
|
-
sections.push({ name, el: sec });
|
|
758
|
-
});
|
|
759
|
-
};
|
|
760
|
-
paint();
|
|
761
|
-
|
|
762
|
-
const wrap = el('div', { class: 'blk-codewrap blk-diffwrap' });
|
|
763
|
-
// header: file count / single name (left) + a Unified/Split view toggle (right)
|
|
764
|
-
const toggle = el('button', { class: 'blk-difftoggle', type: 'button', title: 'Toggle side-by-side view' });
|
|
765
|
-
const syncToggle = () => { toggle.textContent = view === 'split' ? 'Unified view' : 'Split view'; };
|
|
766
|
-
syncToggle();
|
|
767
|
-
toggle.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
768
|
-
toggle.addEventListener('click', (e) => {
|
|
769
|
-
e.preventDefault();
|
|
770
|
-
e.stopPropagation();
|
|
771
|
-
view = view === 'split' ? 'unified' : 'split';
|
|
772
|
-
wrap.classList.toggle('is-split', view === 'split');
|
|
773
|
-
syncToggle();
|
|
774
|
-
paint();
|
|
775
|
-
});
|
|
776
|
-
const headLabel = multi ? `${named.length} files changed` : (named[0] && named[0].name) || block.filename || '';
|
|
777
|
-
wrap.append(el('div', { class: 'blk-codehead' },
|
|
778
|
-
el('span', { class: 'blk-codename' }, headLabel),
|
|
779
|
-
toggle
|
|
780
|
-
));
|
|
781
|
-
// jump bar of file chips for a multi-file diff (click scrolls to that file)
|
|
782
|
-
if (multi) {
|
|
783
|
-
const bar = el('div', { class: 'diff-files' });
|
|
784
|
-
named.forEach((f) => {
|
|
785
|
-
const chip = el('button', { type: 'button', class: 'diff-file-chip' }, f.name);
|
|
786
|
-
chip.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
787
|
-
chip.addEventListener('click', (e) => {
|
|
788
|
-
e.stopPropagation();
|
|
789
|
-
const s = sections.find((x) => x.name === f.name);
|
|
790
|
-
if (s) s.el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
|
791
|
-
});
|
|
792
|
-
bar.append(chip);
|
|
793
|
-
});
|
|
794
|
-
wrap.append(bar);
|
|
795
|
-
}
|
|
796
|
-
wrap.classList.toggle('is-split', view === 'split');
|
|
797
|
-
wrap.append(scroll);
|
|
798
|
-
// select-to-comment stays bound to the stable scroll container across toggles
|
|
799
|
-
ctx && ctx.annotate && ctx.annotate.enableTextSelection(scroll, { blockId, questionId: ctx.questionId });
|
|
800
|
-
attachViewer(wrap, { zoomEl: null, label: 'diff', comment: wholeBlockComment(ctx, blockId, 'diff') });
|
|
801
|
-
return wrap;
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
// ---------- git conflict resolver ----------
|
|
805
|
-
function markerConflictText(h) {
|
|
806
|
-
const chunks = [
|
|
807
|
-
'<<<<<<< ' + (h.oursLabel || 'ours'),
|
|
808
|
-
h.ours || '',
|
|
809
|
-
];
|
|
810
|
-
if (h.baseLabel) chunks.push('||||||| ' + h.baseLabel, h.base || '');
|
|
811
|
-
chunks.push('=======', h.theirs || '', '>>>>>>> ' + (h.theirsLabel || 'theirs'));
|
|
812
|
-
return chunks.join('\n');
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
function conflictChoiceText(h, choice, custom) {
|
|
816
|
-
if (choice === 'ours') return h.ours || '';
|
|
817
|
-
if (choice === 'theirs') return h.theirs || '';
|
|
818
|
-
if (choice === 'both') {
|
|
819
|
-
const left = h.ours || '';
|
|
820
|
-
const right = h.theirs || '';
|
|
821
|
-
return left && right ? left + '\n' + right : left || right;
|
|
822
|
-
}
|
|
823
|
-
if (choice === 'custom') return custom || '';
|
|
824
|
-
return markerConflictText(h);
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
function joinResolvedParts(block, resolutions) {
|
|
828
|
-
const byId = new Map((block.conflicts || []).map((h) => [h.id, h]));
|
|
829
|
-
return (block.parts || []).map((part) => {
|
|
830
|
-
if (!part || part.type === 'text') return part && part.text ? part.text : '';
|
|
831
|
-
const h = byId.get(part.conflictId);
|
|
832
|
-
if (!h) return '';
|
|
833
|
-
const r = resolutions && resolutions[h.id] ? resolutions[h.id] : {};
|
|
834
|
-
return conflictChoiceText(h, r.choice, r.value);
|
|
835
|
-
}).join('\n');
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
function renderConflictCode(text, lang) {
|
|
839
|
-
const pre = el('pre', { class: 'gitconf-pre' });
|
|
840
|
-
const code = el('code');
|
|
841
|
-
code.innerHTML = tintCode(text || ' ', lang);
|
|
842
|
-
pre.append(code);
|
|
843
|
-
return pre;
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
function renderGitConflict(block, ctx, blockId) {
|
|
847
|
-
const editable = ctx.canEditBlocks !== false;
|
|
848
|
-
const conflicts = Array.isArray(block.conflicts) ? block.conflicts : [];
|
|
849
|
-
const prior = ctx && ctx.edits && ctx.edits[blockId] && typeof ctx.edits[blockId] === 'object'
|
|
850
|
-
? ctx.edits[blockId]
|
|
851
|
-
: {};
|
|
852
|
-
const resolutions = prior.resolutions && typeof prior.resolutions === 'object' ? { ...prior.resolutions } : {};
|
|
853
|
-
const wrap = el('div', { class: 'gitconf' });
|
|
854
|
-
const count = conflicts.length;
|
|
855
|
-
const title = block.title || block.filename || 'Git conflict';
|
|
856
|
-
const status = el('span', { class: 'gitconf-status' }, `${count} conflict${count === 1 ? '' : 's'}`);
|
|
857
|
-
const resolvedPreview = el('pre', { class: 'gitconf-resolved' }, el('code'));
|
|
858
|
-
|
|
859
|
-
function emit() {
|
|
860
|
-
const touched = Object.keys(resolutions).filter((id) => resolutions[id] && resolutions[id].choice);
|
|
861
|
-
const payload = touched.length
|
|
862
|
-
? {
|
|
863
|
-
type: 'git-conflict-resolution',
|
|
864
|
-
filename: block.filename || '',
|
|
865
|
-
file: block.file || '',
|
|
866
|
-
resolved: touched.length === count,
|
|
867
|
-
resolutions,
|
|
868
|
-
content: joinResolvedParts(block, resolutions),
|
|
869
|
-
}
|
|
870
|
-
: null;
|
|
871
|
-
if (ctx && typeof ctx.onBlockEdit === 'function') ctx.onBlockEdit(blockId, payload);
|
|
872
|
-
wrap.dispatchEvent(new CustomEvent('relay:block-edit', {
|
|
873
|
-
bubbles: true,
|
|
874
|
-
detail: { blockId, value: payload },
|
|
875
|
-
}));
|
|
876
|
-
resolvedPreview.querySelector('code').textContent = joinResolvedParts(block, resolutions);
|
|
877
|
-
status.textContent = `${touched.length}/${count} resolved`;
|
|
878
|
-
status.classList.toggle('is-complete', touched.length === count);
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
wrap.append(el('div', { class: 'gitconf-head' },
|
|
882
|
-
el('div', {},
|
|
883
|
-
el('div', { class: 'gitconf-title' }, title),
|
|
884
|
-
block.file ? el('div', { class: 'gitconf-file' }, block.file) : null),
|
|
885
|
-
status
|
|
886
|
-
));
|
|
887
|
-
|
|
888
|
-
conflicts.forEach((h, idx) => {
|
|
889
|
-
const body = el('div', { class: 'gitconf-body' });
|
|
890
|
-
const custom = el('textarea', {
|
|
891
|
-
class: 'gitconf-custom',
|
|
892
|
-
spellcheck: 'false',
|
|
893
|
-
rows: '5',
|
|
894
|
-
placeholder: 'Write the resolved content for this hunk',
|
|
895
|
-
disabled: editable ? null : '',
|
|
896
|
-
});
|
|
897
|
-
const buttons = [];
|
|
898
|
-
const setChoice = (choice) => {
|
|
899
|
-
const current = resolutions[h.id] || {};
|
|
900
|
-
const next = { choice, value: choice === 'custom' ? custom.value : conflictChoiceText(h, choice, custom.value) };
|
|
901
|
-
resolutions[h.id] = next;
|
|
902
|
-
for (const b of buttons) b.el.classList.toggle('sel', b.choice === choice);
|
|
903
|
-
body.classList.toggle('is-custom', choice === 'custom');
|
|
904
|
-
emit();
|
|
905
|
-
};
|
|
906
|
-
const makeButton = (choice, label) => {
|
|
907
|
-
const b = el('button', { type: 'button', class: 'gitconf-choice', disabled: editable ? null : '' }, label);
|
|
908
|
-
b.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
909
|
-
b.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); setChoice(choice); });
|
|
910
|
-
buttons.push({ choice, el: b });
|
|
911
|
-
return b;
|
|
912
|
-
};
|
|
913
|
-
const existing = resolutions[h.id] || {};
|
|
914
|
-
if (existing.choice === 'custom') custom.value = existing.value || '';
|
|
915
|
-
else custom.value = conflictChoiceText(h, existing.choice || 'ours', '');
|
|
916
|
-
custom.addEventListener('input', () => setChoice('custom'));
|
|
917
|
-
|
|
918
|
-
body.append(el('div', { class: 'gitconf-choicebar' },
|
|
919
|
-
makeButton('ours', 'Use ours'),
|
|
920
|
-
makeButton('theirs', 'Use theirs'),
|
|
921
|
-
makeButton('both', 'Keep both'),
|
|
922
|
-
makeButton('custom', 'Custom')
|
|
923
|
-
));
|
|
924
|
-
body.append(el('div', { class: 'gitconf-sides' },
|
|
925
|
-
el('section', { class: 'gitconf-side gitconf-ours' },
|
|
926
|
-
el('div', { class: 'gitconf-label' }, h.oursLabel || 'ours'),
|
|
927
|
-
renderConflictCode(h.ours || '', block.lang)),
|
|
928
|
-
h.baseLabel ? el('section', { class: 'gitconf-side gitconf-base' },
|
|
929
|
-
el('div', { class: 'gitconf-label' }, h.baseLabel),
|
|
930
|
-
renderConflictCode(h.base || '', block.lang)) : null,
|
|
931
|
-
el('section', { class: 'gitconf-side gitconf-theirs' },
|
|
932
|
-
el('div', { class: 'gitconf-label' }, h.theirsLabel || 'theirs'),
|
|
933
|
-
renderConflictCode(h.theirs || '', block.lang))
|
|
934
|
-
));
|
|
935
|
-
body.append(custom);
|
|
936
|
-
|
|
937
|
-
const card = el('section', { class: 'gitconf-card' },
|
|
938
|
-
el('div', { class: 'gitconf-cardhead' },
|
|
939
|
-
el('span', { class: 'gitconf-badge' }, `Conflict ${idx + 1}`),
|
|
940
|
-
el('span', { class: 'gitconf-hint' }, 'Choose a side, keep both, or write the final hunk.')),
|
|
941
|
-
body
|
|
942
|
-
);
|
|
943
|
-
wrap.append(card);
|
|
944
|
-
if (existing.choice) setChoice(existing.choice);
|
|
945
|
-
});
|
|
946
|
-
|
|
947
|
-
wrap.append(el('details', { class: 'gitconf-preview' },
|
|
948
|
-
el('summary', {}, 'Resolved file preview'),
|
|
949
|
-
resolvedPreview
|
|
950
|
-
));
|
|
951
|
-
emit();
|
|
952
|
-
ctx && ctx.annotate && ctx.annotate.enableTextSelection(wrap, { blockId, questionId: ctx.questionId });
|
|
953
|
-
return wrap;
|
|
954
|
-
}
|
|
955
|
-
// ---------- video (YouTube/Vimeo embed, local stream, or direct URL) ----------
|
|
956
|
-
function renderVideo(block, ctx, blockId) {
|
|
957
|
-
const wrap = el('div', { class: 'blk-videowrap' });
|
|
958
|
-
let media;
|
|
959
|
-
if (block.provider === 'youtube') {
|
|
960
|
-
const q = block.start ? '?start=' + block.start : '';
|
|
961
|
-
media = el('iframe', {
|
|
962
|
-
class: 'blk-video-embed',
|
|
963
|
-
src: 'https://www.youtube-nocookie.com/embed/' + encodeURIComponent(block.videoId) + q,
|
|
964
|
-
title: block.title || 'YouTube video',
|
|
965
|
-
frameborder: '0',
|
|
966
|
-
allow: 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share',
|
|
967
|
-
referrerpolicy: 'strict-origin-when-cross-origin',
|
|
968
|
-
allowfullscreen: 'true',
|
|
969
|
-
loading: 'lazy',
|
|
970
|
-
});
|
|
971
|
-
} else if (block.provider === 'vimeo') {
|
|
972
|
-
media = el('iframe', {
|
|
973
|
-
class: 'blk-video-embed',
|
|
974
|
-
src: 'https://player.vimeo.com/video/' + encodeURIComponent(block.videoId),
|
|
975
|
-
title: block.title || 'Vimeo video',
|
|
976
|
-
frameborder: '0',
|
|
977
|
-
allow: 'autoplay; fullscreen; picture-in-picture',
|
|
978
|
-
allowfullscreen: 'true',
|
|
979
|
-
loading: 'lazy',
|
|
980
|
-
});
|
|
981
|
-
} else {
|
|
982
|
-
// local file (served via /video/b/<id>) or a direct http(s) media URL
|
|
983
|
-
const src = block.hasFile ? '/video/b/' + encodeURIComponent(blockId) : block.src;
|
|
984
|
-
media = el('video', { class: 'blk-video', controls: 'true', preload: 'metadata', playsinline: 'true' });
|
|
985
|
-
if (block.title) media.setAttribute('title', block.title);
|
|
986
|
-
const source = el('source', { src });
|
|
987
|
-
if (block.mime) source.setAttribute('type', block.mime);
|
|
988
|
-
media.append(source);
|
|
989
|
-
media.append(document.createTextNode('Your browser cannot play this video.'));
|
|
990
|
-
}
|
|
991
|
-
wrap.append(media);
|
|
992
|
-
if (block.title) wrap.append(el('div', { class: 'blk-videocap' }, block.title));
|
|
993
|
-
// whole-block comment + the comment pin (no zoom/full-screen for media)
|
|
994
|
-
attachViewer(wrap, { zoomEl: null, label: 'video', comment: wholeBlockComment(ctx, blockId, 'video') });
|
|
995
|
-
return wrap;
|
|
996
|
-
}
|
|
997
|
-
|
|
998
|
-
// ---------- PDF (local stream or direct URL) ----------
|
|
999
|
-
function renderPdf(block, ctx, blockId) {
|
|
1000
|
-
const wrap = el('div', { class: 'blk-pdfwrap' });
|
|
1001
|
-
const src = block.hasFile ? '/pdf/b/' + encodeURIComponent(blockId) : block.src;
|
|
1002
|
-
const title = block.title || 'PDF';
|
|
1003
|
-
const frame = el('iframe', {
|
|
1004
|
-
class: 'blk-pdf',
|
|
1005
|
-
src,
|
|
1006
|
-
title,
|
|
1007
|
-
loading: 'lazy',
|
|
1008
|
-
});
|
|
1009
|
-
if (block.height != null) frame.style.height = clampHeight(block.height, 900) + 'px';
|
|
1010
|
-
frame.addEventListener('error', () => {
|
|
1011
|
-
wrap.replaceChildren(el('div', { class: 'blk-error' }, 'PDF failed to load'));
|
|
1012
|
-
});
|
|
1013
|
-
wrap.append(frame);
|
|
1014
|
-
if (block.title) wrap.append(el('div', { class: 'blk-videocap' }, block.title));
|
|
1015
|
-
attachViewer(wrap, { zoomEl: null, label: 'pdf', comment: wholeBlockComment(ctx, blockId, 'pdf') });
|
|
1016
|
-
return wrap;
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
// ---------- table ----------
|
|
1020
|
-
function normalizeColumns(columns) {
|
|
1021
|
-
return (columns || []).map((c, idx) => {
|
|
1022
|
-
if (c && typeof c === 'object') {
|
|
1023
|
-
return { key: c.key !== undefined ? c.key : idx, label: c.label !== undefined ? c.label : String(c.key), align: c.align || null };
|
|
1024
|
-
}
|
|
1025
|
-
return { key: idx, label: String(c), align: null };
|
|
1026
|
-
});
|
|
1027
|
-
}
|
|
1028
|
-
|
|
1029
|
-
function cellValue(row, col) {
|
|
1030
|
-
if (Array.isArray(row)) return row[col.key];
|
|
1031
|
-
return row[col.key];
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
function numericAware(a, b) {
|
|
1035
|
-
const na = parseFloat(a);
|
|
1036
|
-
const nb = parseFloat(b);
|
|
1037
|
-
const aNum = a !== '' && a !== null && a !== undefined && !Number.isNaN(na) && String(na) === String(a).trim();
|
|
1038
|
-
const bNum = b !== '' && b !== null && b !== undefined && !Number.isNaN(nb) && String(nb) === String(b).trim();
|
|
1039
|
-
if (aNum && bNum) return na - nb;
|
|
1040
|
-
return String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: 'base' });
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
// CSV-encode a value (quote when it contains a comma/quote/newline).
|
|
1044
|
-
function csvCell(v) {
|
|
1045
|
-
const s = v === undefined || v === null ? '' : String(v);
|
|
1046
|
-
return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
|
|
1047
|
-
}
|
|
1048
|
-
// Trigger a client-side download of `text` as `filename` (browser board). In a
|
|
1049
|
-
// sandboxed/MCP host this may be blocked — best effort, no error if it no-ops.
|
|
1050
|
-
function downloadText(filename, text, mime) {
|
|
1051
|
-
try {
|
|
1052
|
-
const blob = new Blob([text], { type: mime || 'text/plain' });
|
|
1053
|
-
const url = URL.createObjectURL(blob);
|
|
1054
|
-
const a = el('a', { href: url, download: filename });
|
|
1055
|
-
document.body.append(a);
|
|
1056
|
-
a.click();
|
|
1057
|
-
a.remove();
|
|
1058
|
-
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
1059
|
-
} catch (_) { /* sandbox without download permission */ }
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
function renderTable(block, ctx, blockId) {
|
|
1063
|
-
const cols = normalizeColumns(block.columns);
|
|
1064
|
-
const rows = block.rows || [];
|
|
1065
|
-
const sortable = block.sortable === true;
|
|
1066
|
-
const filterable = block.filterable === true;
|
|
1067
|
-
const exportable = block.exportable === true;
|
|
1068
|
-
let filterText = '';
|
|
1069
|
-
// sortState: column index in cols (-1 none) + dir
|
|
1070
|
-
let sortCol = -1;
|
|
1071
|
-
let sortDir = 0; // 0 none, 1 asc, -1 desc
|
|
1072
|
-
|
|
1073
|
-
const table = el('table', { class: 'blk-table' });
|
|
1074
|
-
const thead = el('thead');
|
|
1075
|
-
const trHead = el('tr');
|
|
1076
|
-
const headCells = [];
|
|
1077
|
-
cols.forEach((col, ci) => {
|
|
1078
|
-
const th = el('th', { class: sortable ? 'sortable' : null });
|
|
1079
|
-
if (col.align) th.style.textAlign = col.align;
|
|
1080
|
-
const labelSpan = el('span', {}, col.label);
|
|
1081
|
-
const arrow = el('span', { class: 'sort-arrow' }, '');
|
|
1082
|
-
th.append(labelSpan, arrow);
|
|
1083
|
-
if (sortable) {
|
|
1084
|
-
th.addEventListener('click', () => {
|
|
1085
|
-
if (sortCol === ci) sortDir = sortDir === 1 ? -1 : sortDir === -1 ? 0 : 1;
|
|
1086
|
-
else { sortCol = ci; sortDir = 1; }
|
|
1087
|
-
rebuild();
|
|
1088
|
-
});
|
|
1089
|
-
}
|
|
1090
|
-
headCells.push({ th, arrow });
|
|
1091
|
-
trHead.append(th);
|
|
1092
|
-
});
|
|
1093
|
-
thead.append(trHead);
|
|
1094
|
-
const tbody = el('tbody');
|
|
1095
|
-
table.append(thead, tbody);
|
|
1096
|
-
|
|
1097
|
-
// rows (as original indices) passing the current filter — used by both the
|
|
1098
|
-
// table body and the CSV export so export honors the visible/filtered set.
|
|
1099
|
-
function filteredOrder() {
|
|
1100
|
-
let order = rows.map((_r, idx) => idx);
|
|
1101
|
-
if (filterText) {
|
|
1102
|
-
const q = filterText.toLowerCase();
|
|
1103
|
-
order = order.filter((idx) => cols.some((col) => {
|
|
1104
|
-
const v = cellValue(rows[idx], col);
|
|
1105
|
-
return v !== undefined && v !== null && String(v).toLowerCase().includes(q);
|
|
1106
|
-
}));
|
|
1107
|
-
}
|
|
1108
|
-
if (sortable && sortCol >= 0 && sortDir !== 0) {
|
|
1109
|
-
const col = cols[sortCol];
|
|
1110
|
-
order.sort((ia, ib) => {
|
|
1111
|
-
const r = numericAware(cellValue(rows[ia], col), cellValue(rows[ib], col));
|
|
1112
|
-
return sortDir === 1 ? r : -r;
|
|
1113
|
-
});
|
|
1114
|
-
}
|
|
1115
|
-
return order;
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
function rebuild() {
|
|
1119
|
-
const order = filteredOrder();
|
|
1120
|
-
headCells.forEach((hc, ci) => {
|
|
1121
|
-
hc.arrow.textContent = sortable && ci === sortCol && sortDir !== 0 ? (sortDir === 1 ? ' ↑' : ' ↓') : '';
|
|
1122
|
-
});
|
|
1123
|
-
tbody.replaceChildren();
|
|
1124
|
-
for (const origIdx of order) {
|
|
1125
|
-
const row = rows[origIdx];
|
|
1126
|
-
const tr = el('tr');
|
|
1127
|
-
for (const col of cols) {
|
|
1128
|
-
const raw = cellValue(row, col);
|
|
1129
|
-
const td = el('td', {}, raw === undefined || raw === null ? '' : String(raw));
|
|
1130
|
-
if (col.align) td.style.textAlign = col.align;
|
|
1131
|
-
ctx.annotate?.register(td, {
|
|
1132
|
-
blockId,
|
|
1133
|
-
questionId: ctx.questionId,
|
|
1134
|
-
target: { kind: 'table-cell', row: origIdx, col: col.key, value: String(raw === undefined || raw === null ? '' : raw) },
|
|
1135
|
-
});
|
|
1136
|
-
tr.append(td);
|
|
1137
|
-
}
|
|
1138
|
-
tbody.append(tr);
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
rebuild();
|
|
1142
|
-
// Tables are visual too: wrap so they get the full-screen viewer like
|
|
1143
|
-
// every other visual block (wide tables squeeze in the column).
|
|
1144
|
-
const wrap = el('div', { class: 'blk-tablewrap' });
|
|
1145
|
-
// Optional toolbar: live filter box + CSV export of the filtered rows.
|
|
1146
|
-
if (filterable || exportable) {
|
|
1147
|
-
const bar = el('div', { class: 'blk-tablebar' });
|
|
1148
|
-
if (filterable) {
|
|
1149
|
-
const input = el('input', { type: 'text', class: 'blk-tablefilter', placeholder: 'Filter rows…', 'aria-label': 'Filter table rows' });
|
|
1150
|
-
input.addEventListener('input', () => { filterText = input.value.trim(); rebuild(); });
|
|
1151
|
-
// don't let a click in the filter start a drag-pan / full-screen
|
|
1152
|
-
input.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
1153
|
-
bar.append(input);
|
|
1154
|
-
}
|
|
1155
|
-
if (exportable) {
|
|
1156
|
-
const btn = el('button', { type: 'button', class: 'blk-tableexport', title: 'Download the filtered rows as CSV' }, 'CSV');
|
|
1157
|
-
btn.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
1158
|
-
btn.addEventListener('click', (e) => {
|
|
1159
|
-
e.stopPropagation();
|
|
1160
|
-
const order = filteredOrder();
|
|
1161
|
-
const head = cols.map((c) => csvCell(c.label)).join(',');
|
|
1162
|
-
const body = order.map((idx) => cols.map((c) => csvCell(cellValue(rows[idx], c))).join(',')).join('\n');
|
|
1163
|
-
downloadText('table.csv', head + '\n' + body + '\n', 'text/csv');
|
|
1164
|
-
});
|
|
1165
|
-
bar.append(btn);
|
|
1166
|
-
}
|
|
1167
|
-
wrap.append(bar);
|
|
1168
|
-
}
|
|
1169
|
-
wrap.append(table);
|
|
1170
|
-
attachViewer(wrap, { zoomEl: null });
|
|
1171
|
-
return wrap;
|
|
1172
|
-
}
|
|
1173
|
-
|
|
1174
|
-
// ---------- lazy vendor loaders (cached promises) ----------
|
|
1175
|
-
let chartPromise = null;
|
|
1176
|
-
function loadChart() {
|
|
1177
|
-
if (window.Chart) return Promise.resolve(window.Chart);
|
|
1178
|
-
if (chartPromise) return chartPromise;
|
|
1179
|
-
chartPromise = new Promise((resolve, reject) => {
|
|
1180
|
-
const s = document.createElement('script');
|
|
1181
|
-
s.src = '/vendor/chart.umd.js';
|
|
1182
|
-
s.onload = () => (window.Chart ? resolve(window.Chart) : reject(new Error('Chart.js failed to load')));
|
|
1183
|
-
s.onerror = () => reject(new Error('Chart.js failed to load'));
|
|
1184
|
-
document.head.appendChild(s);
|
|
1185
|
-
});
|
|
1186
|
-
return chartPromise;
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
let mermaidPromise = null;
|
|
1190
|
-
function loadMermaid() {
|
|
1191
|
-
if (window.mermaid) return Promise.resolve(window.mermaid);
|
|
1192
|
-
if (mermaidPromise) return mermaidPromise;
|
|
1193
|
-
mermaidPromise = new Promise((resolve, reject) => {
|
|
1194
|
-
const s = document.createElement('script');
|
|
1195
|
-
s.src = '/vendor/mermaid.min.js';
|
|
1196
|
-
s.onload = () => (window.mermaid ? resolve(window.mermaid) : reject(new Error('Mermaid failed to load')));
|
|
1197
|
-
s.onerror = () => reject(new Error('Mermaid failed to load'));
|
|
1198
|
-
document.head.appendChild(s);
|
|
1199
|
-
});
|
|
1200
|
-
return mermaidPromise;
|
|
1201
|
-
}
|
|
1202
|
-
|
|
1203
|
-
let vizPromise = null;
|
|
1204
|
-
function loadViz() {
|
|
1205
|
-
if (window.Viz) return Promise.resolve(window.Viz);
|
|
1206
|
-
if (vizPromise) return vizPromise;
|
|
1207
|
-
vizPromise = new Promise((resolve, reject) => {
|
|
1208
|
-
const s = document.createElement('script');
|
|
1209
|
-
s.src = '/vendor/viz-standalone.js';
|
|
1210
|
-
s.onload = () => (window.Viz ? resolve(window.Viz) : reject(new Error('Graphviz failed to load')));
|
|
1211
|
-
s.onerror = () => reject(new Error('Graphviz failed to load'));
|
|
1212
|
-
document.head.appendChild(s);
|
|
1213
|
-
});
|
|
1214
|
-
return vizPromise;
|
|
1215
|
-
}
|
|
1216
|
-
|
|
1217
|
-
// ---------- chart ----------
|
|
1218
|
-
function clampHeight(h, def) {
|
|
1219
|
-
const n = Number(h);
|
|
1220
|
-
if (!Number.isFinite(n)) return def;
|
|
1221
|
-
return Math.max(100, Math.min(2400, n));
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
function palette() {
|
|
1225
|
-
return (document.documentElement.dataset.theme === 'dark' ||
|
|
1226
|
-
(!document.documentElement.dataset.theme && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches))
|
|
1227
|
-
? PALETTE_DARK
|
|
1228
|
-
: PALETTE_LIGHT;
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
function themeDefaults(ctx) {
|
|
1232
|
-
const grid = cssVar('--border') || '#ece9e4';
|
|
1233
|
-
// axis/legend/title text: --fg-2 reads clearly on dark; --muted was too dim
|
|
1234
|
-
const tick = cssVar('--fg-2') || '#57534e';
|
|
1235
|
-
const fontFamily = cssVar('--sans') || 'sans-serif';
|
|
1236
|
-
return { grid, tick, fontFamily };
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
// Apply theme defaults only where unset (deep, conservative).
|
|
1240
|
-
function applyChartTheme(config, ctx) {
|
|
1241
|
-
const { grid, tick, fontFamily } = themeDefaults(ctx);
|
|
1242
|
-
config.options = config.options || {};
|
|
1243
|
-
const o = config.options;
|
|
1244
|
-
if (o.responsive === undefined) o.responsive = true;
|
|
1245
|
-
if (o.maintainAspectRatio === undefined) o.maintainAspectRatio = false;
|
|
1246
|
-
if (o.animation === undefined) o.animation = false;
|
|
1247
|
-
o.plugins = o.plugins || {};
|
|
1248
|
-
o.plugins.legend = o.plugins.legend || {};
|
|
1249
|
-
o.plugins.legend.labels = o.plugins.legend.labels || {};
|
|
1250
|
-
if (o.plugins.legend.labels.color === undefined) o.plugins.legend.labels.color = tick;
|
|
1251
|
-
if (o.plugins.legend.labels.font === undefined) o.plugins.legend.labels.font = { family: fontFamily, size: 12 };
|
|
1252
|
-
if (o.plugins.title && o.plugins.title.color === undefined) o.plugins.title.color = tick;
|
|
1253
|
-
|
|
1254
|
-
const styleAxis = (ax) => {
|
|
1255
|
-
if (!ax || typeof ax !== 'object') return;
|
|
1256
|
-
ax.grid = ax.grid || {};
|
|
1257
|
-
if (ax.grid.color === undefined) ax.grid.color = grid;
|
|
1258
|
-
ax.ticks = ax.ticks || {};
|
|
1259
|
-
if (ax.ticks.color === undefined) ax.ticks.color = tick;
|
|
1260
|
-
if (ax.ticks.font === undefined) ax.ticks.font = { family: fontFamily, size: 12 };
|
|
1261
|
-
};
|
|
1262
|
-
o.scales = o.scales || {};
|
|
1263
|
-
// Chart.js v3+ uses named scales (x/y/r). Style any present; for simplified
|
|
1264
|
-
// configs we pre-create x/y below.
|
|
1265
|
-
for (const key of Object.keys(o.scales)) styleAxis(o.scales[key]);
|
|
1266
|
-
return config;
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
function simplifiedToConfig(block, ctx) {
|
|
1270
|
-
const pal = palette();
|
|
1271
|
-
const kind = block.kind || 'bar';
|
|
1272
|
-
const series = block.series || [];
|
|
1273
|
-
const datasets = series.map((s, i) => {
|
|
1274
|
-
const color = s.color || pal[i % pal.length];
|
|
1275
|
-
const ds = {
|
|
1276
|
-
label: s.label !== undefined ? s.label : `Series ${i + 1}`,
|
|
1277
|
-
data: s.data || [],
|
|
1278
|
-
};
|
|
1279
|
-
if (kind === 'line') {
|
|
1280
|
-
ds.borderColor = color;
|
|
1281
|
-
ds.backgroundColor = color;
|
|
1282
|
-
ds.tension = 0.25;
|
|
1283
|
-
ds.pointRadius = 3;
|
|
1284
|
-
} else if (kind === 'pie' || kind === 'doughnut') {
|
|
1285
|
-
ds.backgroundColor = (s.data || []).map((_d, di) => s.color || pal[di % pal.length]);
|
|
1286
|
-
ds.borderColor = cssVar('--card') || '#fff';
|
|
1287
|
-
ds.borderWidth = 2;
|
|
1288
|
-
} else if (kind === 'radar') {
|
|
1289
|
-
ds.borderColor = color;
|
|
1290
|
-
ds.backgroundColor = color + '33';
|
|
1291
|
-
ds.pointBackgroundColor = color;
|
|
1292
|
-
} else {
|
|
1293
|
-
ds.backgroundColor = color;
|
|
1294
|
-
ds.borderColor = color;
|
|
1295
|
-
}
|
|
1296
|
-
return ds;
|
|
1297
|
-
});
|
|
1298
|
-
const config = {
|
|
1299
|
-
type: kind,
|
|
1300
|
-
data: { labels: block.labels || [], datasets },
|
|
1301
|
-
options: {},
|
|
1302
|
-
};
|
|
1303
|
-
if (block.title) {
|
|
1304
|
-
config.options.plugins = { title: { display: true, text: block.title } };
|
|
1305
|
-
}
|
|
1306
|
-
// pre-create x/y scales for cartesian kinds so theme styling applies
|
|
1307
|
-
if (kind === 'bar' || kind === 'line' || kind === 'scatter') {
|
|
1308
|
-
config.options.scales = { x: {}, y: {} };
|
|
1309
|
-
}
|
|
1310
|
-
return config;
|
|
1311
|
-
}
|
|
1312
|
-
|
|
1313
|
-
function renderChart(block, ctx, blockId) {
|
|
1314
|
-
const height = clampHeight(block.height, 320);
|
|
1315
|
-
const wrap = el('div', { class: 'blk-chart' });
|
|
1316
|
-
wrap.style.height = height + 'px';
|
|
1317
|
-
const stage = el('div', { class: 'blk-chart-stage' });
|
|
1318
|
-
const canvas = el('canvas');
|
|
1319
|
-
stage.append(canvas);
|
|
1320
|
-
wrap.append(stage);
|
|
1321
|
-
|
|
1322
|
-
let chartInst = null;
|
|
1323
|
-
let chartBadges = [];
|
|
1324
|
-
let naturalSize = null;
|
|
1325
|
-
|
|
1326
|
-
const openFor = (target) => (anchor) =>
|
|
1327
|
-
ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, anchor);
|
|
1328
|
-
function makeBadge(count, cls, onClick) {
|
|
1329
|
-
const b = el('span', { class: 'blk-chart-badge ' + cls }, String(count));
|
|
1330
|
-
b.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
1331
|
-
b.addEventListener('click', (e) => { e.stopPropagation(); e.preventDefault(); onClick(b); });
|
|
1332
|
-
return b;
|
|
1333
|
-
}
|
|
1334
|
-
// Rebuild the chart's comment badges: one at each annotated DATA POINT
|
|
1335
|
-
// (positioned from the Chart.js element geometry) plus a top-right badge for
|
|
1336
|
-
// whole-chart comments. Each badge opens that comment's popover on click.
|
|
1337
|
-
// Runs on annotation change (onBadgeRefresh) and on chart (re)render/resize
|
|
1338
|
-
// (afterRender plugin), so badges stay pinned to their points.
|
|
1339
|
-
function syncChartBadges() {
|
|
1340
|
-
if (!ctx.annotate) return;
|
|
1341
|
-
for (const b of chartBadges) b.remove();
|
|
1342
|
-
chartBadges = [];
|
|
1343
|
-
const groups = new Map(); // "di:index" -> { target, count }
|
|
1344
|
-
let blockCount = 0, blockTarget = null;
|
|
1345
|
-
for (const a of ctx.annotate.list()) {
|
|
1346
|
-
if (a.blockId !== blockId) continue;
|
|
1347
|
-
const t = a.target || {};
|
|
1348
|
-
if (t.kind === 'chart-element' && typeof t.datasetIndex === 'number' && typeof t.index === 'number') {
|
|
1349
|
-
const k = t.datasetIndex + ':' + t.index;
|
|
1350
|
-
const g = groups.get(k) || { target: t, count: 0 };
|
|
1351
|
-
g.count++; groups.set(k, g);
|
|
1352
|
-
} else {
|
|
1353
|
-
blockCount++; blockTarget = blockTarget || t;
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
if (chartInst) {
|
|
1357
|
-
for (const { target, count } of groups.values()) {
|
|
1358
|
-
let elem;
|
|
1359
|
-
try { const m = chartInst.getDatasetMeta(target.datasetIndex); elem = m && m.data[target.index]; } catch (_) {}
|
|
1360
|
-
if (!elem) continue;
|
|
1361
|
-
let pos; try { pos = elem.tooltipPosition(); } catch (_) { pos = { x: elem.x, y: elem.y }; }
|
|
1362
|
-
if (!pos || !Number.isFinite(pos.x) || !Number.isFinite(pos.y)) continue;
|
|
1363
|
-
const badge = makeBadge(count, 'blk-chart-badge-pt', openFor(target));
|
|
1364
|
-
badge.style.left = (canvas.offsetLeft + pos.x) + 'px';
|
|
1365
|
-
badge.style.top = (canvas.offsetTop + pos.y) + 'px';
|
|
1366
|
-
stage.append(badge);
|
|
1367
|
-
chartBadges.push(badge);
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
if (blockCount > 0) {
|
|
1371
|
-
const badge = makeBadge(blockCount, 'blk-chart-badge-corner', openFor(blockTarget || { kind: 'block', label: 'chart' }));
|
|
1372
|
-
wrap.append(badge);
|
|
1373
|
-
chartBadges.push(badge);
|
|
1374
|
-
}
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1377
|
-
if (ctx.annotate && ctx.annotate.onBadgeRefresh) ctx.annotate.onBadgeRefresh(syncChartBadges);
|
|
1378
|
-
loadChart().then((Chart) => {
|
|
1379
|
-
let config = block.config
|
|
1380
|
-
? JSON.parse(JSON.stringify(block.config))
|
|
1381
|
-
: simplifiedToConfig(block, ctx);
|
|
1382
|
-
config = applyChartTheme(config, ctx);
|
|
1383
|
-
// reposition our DOM badges after every (re)render/resize of the chart
|
|
1384
|
-
config.plugins = Array.isArray(config.plugins) ? config.plugins : [];
|
|
1385
|
-
config.plugins.push({ id: 'relayChartBadges', afterRender: () => syncChartBadges() });
|
|
1386
|
-
try {
|
|
1387
|
-
chartInst = new Chart(canvas.getContext('2d'), config);
|
|
1388
|
-
chartRegistry.push({ chart: chartInst });
|
|
1389
|
-
// Chart.js stays responsive inside a stage whose dimensions the shared
|
|
1390
|
-
// viewer controls. This gives charts the same bounded, eased wheel zoom
|
|
1391
|
-
// as diagrams/images while retaining sharp redraws at every scale.
|
|
1392
|
-
naturalSize = {
|
|
1393
|
-
w: Math.max(1, Math.round(stage.getBoundingClientRect().width || wrap.clientWidth || 640)),
|
|
1394
|
-
h: height,
|
|
1395
|
-
};
|
|
1396
|
-
attachViewer(wrap, {
|
|
1397
|
-
zoomEl: stage,
|
|
1398
|
-
natural: () => naturalSize,
|
|
1399
|
-
fluidFit: true,
|
|
1400
|
-
scaleHeight: true,
|
|
1401
|
-
label: 'chart',
|
|
1402
|
-
comment: wholeBlockComment(ctx, blockId, 'chart'),
|
|
1403
|
-
});
|
|
1404
|
-
} catch (err) {
|
|
1405
|
-
wrap.replaceChildren(el('div', { class: 'blk-error' }, 'Chart error: ' + (err && err.message ? err.message : String(err))));
|
|
1406
|
-
return;
|
|
1407
|
-
}
|
|
1408
|
-
// hover -> pointer cursor on a hit
|
|
1409
|
-
canvas.addEventListener('mousemove', (e) => {
|
|
1410
|
-
if (ctx.canComment === false) { canvas.style.cursor = 'default'; return; }
|
|
1411
|
-
const hits = chartInst.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
|
|
1412
|
-
canvas.style.cursor = hits.length ? 'pointer' : 'default';
|
|
1413
|
-
});
|
|
1414
|
-
canvas.addEventListener('click', (e) => {
|
|
1415
|
-
if (!ctx.annotate || ctx.canComment === false) return;
|
|
1416
|
-
const hits = chartInst.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
|
|
1417
|
-
if (!hits.length) return;
|
|
1418
|
-
const { datasetIndex, index } = hits[0];
|
|
1419
|
-
const ds = config.data.datasets[datasetIndex] || {};
|
|
1420
|
-
const label = config.data.labels ? config.data.labels[index] : undefined;
|
|
1421
|
-
const value = Array.isArray(ds.data) ? ds.data[index] : undefined;
|
|
1422
|
-
ctx.annotate.openExternal(
|
|
1423
|
-
{
|
|
1424
|
-
blockId,
|
|
1425
|
-
questionId: ctx.questionId,
|
|
1426
|
-
target: { kind: 'chart-element', datasetIndex, index, label: label !== undefined ? String(label) : '', value },
|
|
1427
|
-
},
|
|
1428
|
-
wrap
|
|
1429
|
-
);
|
|
1430
|
-
});
|
|
1431
|
-
syncChartBadges();
|
|
1432
|
-
}).catch((err) => {
|
|
1433
|
-
wrap.replaceChildren(el('div', { class: 'blk-error' }, 'Chart error: ' + (err && err.message ? err.message : String(err))));
|
|
1434
|
-
});
|
|
1435
|
-
|
|
1436
|
-
return wrap;
|
|
1437
|
-
}
|
|
1438
|
-
|
|
1439
|
-
// ---------- mermaid ----------
|
|
1440
|
-
let mermaidSeq = 0;
|
|
1441
|
-
// Registries so a live theme toggle can re-render diagrams and restyle
|
|
1442
|
-
// charts without a page reload.
|
|
1443
|
-
const mermaidRegistry = [];
|
|
1444
|
-
const chartRegistry = [];
|
|
1445
|
-
|
|
1446
|
-
// Effective code = the user's edit if present, else the authored block.code.
|
|
1447
|
-
// Used by the initial render, the editor's live preview, and the theme
|
|
1448
|
-
// re-render registry path so an edit survives a theme toggle.
|
|
1449
|
-
function effectiveMermaidCode(entry) {
|
|
1450
|
-
const { block, ctx, blockId } = entry;
|
|
1451
|
-
const edited = ctx.edits ? ctx.edits[blockId] : undefined;
|
|
1452
|
-
if (edited !== undefined && edited !== null) return edited;
|
|
1453
|
-
// The live editor keeps entry.code as the source of truth; if the host's
|
|
1454
|
-
// ctx.edits hasn't been updated yet but the user has diverged from the
|
|
1455
|
-
// original, preserve that divergence (don't snap back to block.code).
|
|
1456
|
-
if (entry.code !== undefined && entry.code !== (block.code || '')) return entry.code;
|
|
1457
|
-
return block.code || '';
|
|
1458
|
-
}
|
|
1459
|
-
|
|
1460
|
-
function renderMermaid(block, ctx, blockId) {
|
|
1461
|
-
const container = el('div', { class: 'blk-mermaid' });
|
|
1462
|
-
// Honor an authored height as the scrollable viewport: a diagram taller than
|
|
1463
|
-
// this overflows and becomes drag-pannable in place (was silently ignored —
|
|
1464
|
-
// diagrams only ever fit-to-width). No height keeps the 1200px CSS cap.
|
|
1465
|
-
if (block.height != null) container.style.maxHeight = clampHeight(block.height, 1200) + 'px';
|
|
1466
|
-
const entry = { container, block, ctx, blockId };
|
|
1467
|
-
entry.code = effectiveMermaidCode(entry);
|
|
1468
|
-
mermaidRegistry.push(entry);
|
|
1469
|
-
|
|
1470
|
-
if (!block.editable || ctx.canEditBlocks === false) {
|
|
1471
|
-
drawMermaid(entry);
|
|
1472
|
-
return container;
|
|
1473
|
-
}
|
|
1474
|
-
|
|
1475
|
-
// Editable: wrap the diagram + an editor below it. The wrapper is what the
|
|
1476
|
-
// dispatcher appends; the registry still tracks `container` (the diagram).
|
|
1477
|
-
const wrap = el('div', { class: 'blk-mermaid-wrap' });
|
|
1478
|
-
wrap.append(container);
|
|
1479
|
-
wrap.append(buildMermaidEditor(entry));
|
|
1480
|
-
drawMermaid(entry);
|
|
1481
|
-
return wrap;
|
|
1482
|
-
}
|
|
1483
|
-
|
|
1484
|
-
// Editor: toggle button + collapsible panel (textarea + Reset + status line).
|
|
1485
|
-
// Live re-render is debounced 600ms; errors show inline WITHOUT destroying the
|
|
1486
|
-
// last good diagram. Each accepted change calls ctx.onBlockEdit(blockId, code)
|
|
1487
|
-
// (null when the value matches the original block.code again).
|
|
1488
|
-
function buildMermaidEditor(entry) {
|
|
1489
|
-
const { block, ctx, blockId, container } = entry;
|
|
1490
|
-
const original = block.code || '';
|
|
1491
|
-
|
|
1492
|
-
const toggleBtn = el('button', { type: 'button', class: 'blk-edit-btn' }, 'Edit diagram');
|
|
1493
|
-
const panel = el('div', { class: 'blk-editor', hidden: '' });
|
|
1494
|
-
|
|
1495
|
-
const ta = el('textarea', { class: 'blk-editor-ta', spellcheck: 'false' });
|
|
1496
|
-
ta.value = entry.code;
|
|
1497
|
-
|
|
1498
|
-
const status = el('div', { class: 'blk-editor-status' }, '');
|
|
1499
|
-
const resetBtn = el('button', { type: 'button', class: 'blk-editor-reset' }, 'Reset');
|
|
1500
|
-
const row = el('div', { class: 'blk-editor-row' }, resetBtn, status);
|
|
1501
|
-
panel.append(ta, row);
|
|
1502
|
-
|
|
1503
|
-
let open = false;
|
|
1504
|
-
toggleBtn.addEventListener('click', () => {
|
|
1505
|
-
open = !open;
|
|
1506
|
-
panel.hidden = !open;
|
|
1507
|
-
toggleBtn.classList.toggle('is-open', open);
|
|
1508
|
-
if (open) ta.focus();
|
|
1509
|
-
});
|
|
1510
|
-
|
|
1511
|
-
let timer = null;
|
|
1512
|
-
function reportEdit(code) {
|
|
1513
|
-
// Only report a real divergence; equal-to-original clears the edit (null).
|
|
1514
|
-
try {
|
|
1515
|
-
if (code === original) ctx.onBlockEdit(blockId, null);
|
|
1516
|
-
else ctx.onBlockEdit(blockId, code);
|
|
1517
|
-
} catch {
|
|
1518
|
-
// host callback failures must not break editing
|
|
1519
|
-
}
|
|
1520
|
-
}
|
|
1521
|
-
|
|
1522
|
-
// Try to render `code`; on success swap the diagram + re-register annotation
|
|
1523
|
-
// targets (via drawMermaid) and report the edit; on failure keep the last
|
|
1524
|
-
// good diagram and show the error inline.
|
|
1525
|
-
function applyCode(code) {
|
|
1526
|
-
previewMermaid(entry, code)
|
|
1527
|
-
.then(() => {
|
|
1528
|
-
status.textContent = '';
|
|
1529
|
-
status.classList.remove('has-error');
|
|
1530
|
-
entry.code = code;
|
|
1531
|
-
reportEdit(code);
|
|
1532
|
-
})
|
|
1533
|
-
.catch((err) => {
|
|
1534
|
-
status.textContent = 'diagram error: ' + (err && err.message ? err.message : String(err));
|
|
1535
|
-
status.classList.add('has-error');
|
|
1536
|
-
});
|
|
1537
|
-
}
|
|
1538
|
-
|
|
1539
|
-
ta.addEventListener('input', () => {
|
|
1540
|
-
if (timer) clearTimeout(timer);
|
|
1541
|
-
const code = ta.value;
|
|
1542
|
-
timer = setTimeout(() => applyCode(code), 600);
|
|
1543
|
-
});
|
|
1544
|
-
|
|
1545
|
-
resetBtn.addEventListener('click', () => {
|
|
1546
|
-
if (timer) { clearTimeout(timer); timer = null; }
|
|
1547
|
-
ta.value = original;
|
|
1548
|
-
applyCode(original);
|
|
1549
|
-
});
|
|
1550
|
-
|
|
1551
|
-
return el('div', { class: 'blk-mermaid-edit' }, toggleBtn, panel);
|
|
1552
|
-
}
|
|
1553
|
-
|
|
1554
|
-
// Render `code` for the editor preview WITHOUT mutating entry.code on failure.
|
|
1555
|
-
// Resolves once the diagram is swapped into the container (annotation targets
|
|
1556
|
-
// re-registered by drawMermaid); rejects with the render error so the caller
|
|
1557
|
-
// can show it inline and keep the last good diagram.
|
|
1558
|
-
function previewMermaid(entry, code) {
|
|
1559
|
-
const prev = entry.code;
|
|
1560
|
-
entry.code = code;
|
|
1561
|
-
return new Promise((resolve, reject) => {
|
|
1562
|
-
drawMermaid(entry, { onDone: resolve, onError: reject });
|
|
1563
|
-
}).catch((err) => {
|
|
1564
|
-
entry.code = prev;
|
|
1565
|
-
throw err;
|
|
1566
|
-
});
|
|
1567
|
-
}
|
|
1568
|
-
|
|
1569
|
-
function drawMermaid(entry, hooks) {
|
|
1570
|
-
const { container, ctx, blockId } = entry;
|
|
1571
|
-
const onError = hooks && hooks.onError ? hooks.onError : null;
|
|
1572
|
-
const onDone = hooks && hooks.onDone ? hooks.onDone : null;
|
|
1573
|
-
const fail = (err) => {
|
|
1574
|
-
if (onError) onError(err);
|
|
1575
|
-
else showMermaidErr(container, err);
|
|
1576
|
-
};
|
|
1577
|
-
loadMermaid().then((mermaid) => {
|
|
1578
|
-
try {
|
|
1579
|
-
mermaid.initialize({
|
|
1580
|
-
startOnLoad: false,
|
|
1581
|
-
theme: ctx.theme() === 'dark' ? 'dark' : 'neutral',
|
|
1582
|
-
securityLevel: 'strict',
|
|
1583
|
-
});
|
|
1584
|
-
} catch {
|
|
1585
|
-
// ignore re-init issues
|
|
1586
|
-
}
|
|
1587
|
-
const id = 'rly-mmd-' + (++mermaidSeq);
|
|
1588
|
-
const code = entry.code !== undefined ? entry.code : effectiveMermaidCode(entry);
|
|
1589
|
-
const onSvg = (svg) => {
|
|
1590
|
-
container.innerHTML = svg;
|
|
1591
|
-
const svgEl = container.querySelector('svg');
|
|
1592
|
-
if (svgEl) {
|
|
1593
|
-
svgEl.removeAttribute('height');
|
|
1594
|
-
svgEl.removeAttribute('width');
|
|
1595
|
-
const vb = svgEl.viewBox && svgEl.viewBox.baseVal;
|
|
1596
|
-
if (vb && vb.width > 0) {
|
|
1597
|
-
// never upscale past the diagram's natural size; still shrink on
|
|
1598
|
-
// narrow screens (a 112px-wide graph must not stretch to 820px)
|
|
1599
|
-
svgEl.style.width = '100%';
|
|
1600
|
-
svgEl.style.maxWidth = Math.ceil(vb.width) + 'px';
|
|
1601
|
-
svgEl.style.height = 'auto';
|
|
1602
|
-
} else {
|
|
1603
|
-
svgEl.style.maxWidth = '100%';
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
if (ctx.annotate) {
|
|
1607
|
-
const nodes = container.querySelectorAll('.node, .edgeLabel');
|
|
1608
|
-
nodes.forEach((g) => {
|
|
1609
|
-
ctx.annotate.register(g, {
|
|
1610
|
-
blockId,
|
|
1611
|
-
questionId: ctx.questionId,
|
|
1612
|
-
target: {
|
|
1613
|
-
kind: 'mermaid-node',
|
|
1614
|
-
nodeId: g.id || '',
|
|
1615
|
-
text: (g.textContent || '').trim().slice(0, 120),
|
|
1616
|
-
},
|
|
1617
|
-
});
|
|
1618
|
-
});
|
|
1619
|
-
}
|
|
1620
|
-
// re-attach per render: innerHTML replacement above wiped the old bar
|
|
1621
|
-
if (svgEl) attachViewer(container, { zoomEl: svgEl, natural: svgNatural(svgEl), label: 'diagram', comment: wholeBlockComment(ctx, blockId, 'diagram') });
|
|
1622
|
-
if (onDone) onDone();
|
|
1623
|
-
};
|
|
1624
|
-
try {
|
|
1625
|
-
const ret = mermaid.render(id, code);
|
|
1626
|
-
if (ret && typeof ret.then === 'function') {
|
|
1627
|
-
ret.then((r) => onSvg(r.svg)).catch((err) => fail(err));
|
|
1628
|
-
} else if (ret && ret.svg) {
|
|
1629
|
-
onSvg(ret.svg);
|
|
1630
|
-
} else if (typeof ret === 'string') {
|
|
1631
|
-
onSvg(ret);
|
|
1632
|
-
} else {
|
|
1633
|
-
// legacy callback signature: render(id, code, cb)
|
|
1634
|
-
mermaid.render(id, code, (svg) => onSvg(svg));
|
|
1635
|
-
}
|
|
1636
|
-
} catch (err) {
|
|
1637
|
-
fail(err);
|
|
1638
|
-
}
|
|
1639
|
-
}).catch((err) => fail(err));
|
|
1640
|
-
}
|
|
1641
|
-
|
|
1642
|
-
// Live theme toggle: re-render mermaid diagrams with the new mermaid theme
|
|
1643
|
-
// and restyle existing charts' grid/tick/legend colors in place.
|
|
1644
|
-
function onThemeChange() {
|
|
1645
|
-
for (const entry of mermaidRegistry) {
|
|
1646
|
-
try {
|
|
1647
|
-
// re-render with the effective code so an edit survives the toggle
|
|
1648
|
-
entry.code = effectiveMermaidCode(entry);
|
|
1649
|
-
drawMermaid(entry);
|
|
1650
|
-
} catch {
|
|
1651
|
-
// keep the previous svg on failure
|
|
1652
|
-
}
|
|
1653
|
-
}
|
|
1654
|
-
const { grid, tick } = themeDefaults();
|
|
1655
|
-
for (const { chart } of chartRegistry) {
|
|
1656
|
-
try {
|
|
1657
|
-
const o = chart.options || {};
|
|
1658
|
-
if (o.plugins && o.plugins.legend && o.plugins.legend.labels) o.plugins.legend.labels.color = tick;
|
|
1659
|
-
if (o.plugins && o.plugins.title) o.plugins.title.color = tick;
|
|
1660
|
-
if (o.scales) {
|
|
1661
|
-
for (const k of Object.keys(o.scales)) {
|
|
1662
|
-
const ax = o.scales[k];
|
|
1663
|
-
if (!ax) continue;
|
|
1664
|
-
if (ax.grid) ax.grid.color = grid;
|
|
1665
|
-
if (ax.ticks) ax.ticks.color = tick;
|
|
1666
|
-
}
|
|
1667
|
-
}
|
|
1668
|
-
chart.update('none');
|
|
1669
|
-
} catch {
|
|
1670
|
-
// chart may already be destroyed
|
|
1671
|
-
}
|
|
1672
|
-
}
|
|
1673
|
-
}
|
|
1674
|
-
|
|
1675
|
-
function showMermaidErr(container, err) {
|
|
1676
|
-
container.replaceChildren(
|
|
1677
|
-
el('div', { class: 'blk-error' }, 'Diagram error: ' + (err && err.message ? err.message : String(err)))
|
|
1678
|
-
);
|
|
1679
|
-
}
|
|
1680
|
-
|
|
1681
|
-
// ---------- graphviz (offline, vendored Viz.js -> SVG) ----------
|
|
1682
|
-
// Same sizing rule as mermaid: never upscale past the diagram's natural
|
|
1683
|
-
// width; shrink on narrow screens. Authors set their own colors so there is
|
|
1684
|
-
// no theme re-render.
|
|
1685
|
-
function sizeDiagramSvg(svgEl) {
|
|
1686
|
-
if (!svgEl) return;
|
|
1687
|
-
svgEl.removeAttribute('height');
|
|
1688
|
-
svgEl.removeAttribute('width');
|
|
1689
|
-
const vb = svgEl.viewBox && svgEl.viewBox.baseVal;
|
|
1690
|
-
if (vb && vb.width > 0) {
|
|
1691
|
-
svgEl.style.width = '100%';
|
|
1692
|
-
svgEl.style.maxWidth = Math.ceil(vb.width) + 'px';
|
|
1693
|
-
svgEl.style.height = 'auto';
|
|
1694
|
-
} else {
|
|
1695
|
-
svgEl.style.maxWidth = '100%';
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
|
|
1699
|
-
function renderGraphviz(block, ctx, blockId) {
|
|
1700
|
-
const container = el('div', { class: 'blk-graphviz' });
|
|
1701
|
-
// honor authored height as the scrollable viewport (see renderMermaid)
|
|
1702
|
-
if (block.height != null) container.style.maxHeight = clampHeight(block.height, 1200) + 'px';
|
|
1703
|
-
loadViz()
|
|
1704
|
-
.then((Viz) => Viz.instance())
|
|
1705
|
-
.then((viz) => {
|
|
1706
|
-
const svgEl = viz.renderSVGElement(block.dot || '');
|
|
1707
|
-
sizeDiagramSvg(svgEl);
|
|
1708
|
-
container.replaceChildren(svgEl);
|
|
1709
|
-
attachViewer(container, { zoomEl: svgEl, natural: svgNatural(svgEl), label: 'graph', comment: wholeBlockComment(ctx, blockId, 'graph') });
|
|
1710
|
-
if (!ctx.annotate) return;
|
|
1711
|
-
const parts = svgEl.querySelectorAll('g.node, g.edge');
|
|
1712
|
-
parts.forEach((g) => {
|
|
1713
|
-
const titleEl = g.querySelector('title');
|
|
1714
|
-
const nodeId = (g.id || (titleEl && titleEl.textContent) || '').trim();
|
|
1715
|
-
// Label text lives in <text> elements; g.textContent would also
|
|
1716
|
-
// include the <title> child and duplicate the label.
|
|
1717
|
-
const labels = Array.from(g.querySelectorAll('text')).map((t) => t.textContent.trim()).filter(Boolean);
|
|
1718
|
-
const text = (labels.join(' ') || (titleEl && titleEl.textContent) || '').trim().slice(0, 120);
|
|
1719
|
-
ctx.annotate.register(g, {
|
|
1720
|
-
blockId,
|
|
1721
|
-
questionId: ctx.questionId,
|
|
1722
|
-
target: {
|
|
1723
|
-
kind: 'graphviz-node',
|
|
1724
|
-
nodeId,
|
|
1725
|
-
text,
|
|
1726
|
-
},
|
|
1727
|
-
});
|
|
1728
|
-
});
|
|
1729
|
-
})
|
|
1730
|
-
.catch((err) => {
|
|
1731
|
-
container.replaceChildren(
|
|
1732
|
-
el('div', { class: 'blk-error' }, 'Graphviz error: ' + (err && err.message ? err.message : String(err)))
|
|
1733
|
-
);
|
|
1734
|
-
});
|
|
1735
|
-
return container;
|
|
1736
|
-
}
|
|
1737
|
-
|
|
1738
|
-
// ---------- plantuml (server-rendered; client deflate-raw + base64 variant) ----------
|
|
1739
|
-
const PLANTUML_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
|
|
1740
|
-
|
|
1741
|
-
// PlantUML's base64 variant: 3 bytes -> 4 chars using PLANTUML_ALPHABET.
|
|
1742
|
-
function encode64(bytes) {
|
|
1743
|
-
let out = '';
|
|
1744
|
-
for (let i = 0; i < bytes.length; i += 3) {
|
|
1745
|
-
const b1 = bytes[i];
|
|
1746
|
-
const b2 = i + 1 < bytes.length ? bytes[i + 1] : 0;
|
|
1747
|
-
const b3 = i + 2 < bytes.length ? bytes[i + 2] : 0;
|
|
1748
|
-
out += PLANTUML_ALPHABET[b1 >> 2];
|
|
1749
|
-
out += PLANTUML_ALPHABET[((b1 & 0x3) << 4) | (b2 >> 4)];
|
|
1750
|
-
if (i + 1 < bytes.length) out += PLANTUML_ALPHABET[((b2 & 0xf) << 2) | (b3 >> 6)];
|
|
1751
|
-
if (i + 2 < bytes.length) out += PLANTUML_ALPHABET[b3 & 0x3f];
|
|
1752
|
-
}
|
|
1753
|
-
return out;
|
|
1754
|
-
}
|
|
1755
|
-
|
|
1756
|
-
async function encodePlantUml(code) {
|
|
1757
|
-
if (typeof CompressionStream === 'undefined') {
|
|
1758
|
-
throw new Error('CompressionStream unavailable');
|
|
1759
|
-
}
|
|
1760
|
-
const bytes = new TextEncoder().encode(String(code));
|
|
1761
|
-
const blob = new Blob([bytes]);
|
|
1762
|
-
const compressed = await new Response(
|
|
1763
|
-
blob.stream().pipeThrough(new CompressionStream('deflate-raw'))
|
|
1764
|
-
).arrayBuffer();
|
|
1765
|
-
return encode64(new Uint8Array(compressed));
|
|
1766
|
-
}
|
|
1767
|
-
|
|
1768
|
-
// Fetch a remote SVG and return a sanitized inline <svg> element, so its parts
|
|
1769
|
-
// become annotatable. Rejects on network/CORS failure (caller falls back to an
|
|
1770
|
-
// <img>). The SVG is sanitized — it comes from a remote, author-set server, so
|
|
1771
|
-
// strip scripts / foreignObject / on* handlers / javascript: links before it
|
|
1772
|
-
// ever touches the document.
|
|
1773
|
-
function fetchInlineSvg(url) {
|
|
1774
|
-
return fetch(url, { credentials: 'omit', mode: 'cors' })
|
|
1775
|
-
.then((r) => {
|
|
1776
|
-
if (!r.ok) throw new Error('http ' + r.status);
|
|
1777
|
-
// only trust a declared SVG/XML payload; anything else → <img> fallback
|
|
1778
|
-
const ct = (r.headers.get('content-type') || '').toLowerCase();
|
|
1779
|
-
if (ct && !ct.includes('svg') && !ct.includes('xml')) throw new Error('not svg: ' + ct);
|
|
1780
|
-
return r.text();
|
|
1781
|
-
})
|
|
1782
|
-
.then((text) => {
|
|
1783
|
-
const doc = new DOMParser().parseFromString(text, 'image/svg+xml');
|
|
1784
|
-
if (doc.querySelector('parsererror')) throw new Error('bad svg');
|
|
1785
|
-
const svg = doc.querySelector('svg');
|
|
1786
|
-
if (!svg) throw new Error('no svg');
|
|
1787
|
-
sanitizeSvg(svg);
|
|
1788
|
-
return document.importNode(svg, true);
|
|
1789
|
-
});
|
|
1790
|
-
}
|
|
1791
|
-
|
|
1792
|
-
// The SVG comes from a remote, author-set server, so strip everything active
|
|
1793
|
-
// or capable of fetching an external resource before it touches the document.
|
|
1794
|
-
// Script execution is already impossible here (DOMParser doesn't run scripts;
|
|
1795
|
-
// importNode+appendChild never starts an SVG <script>), but we still drop
|
|
1796
|
-
// <script>/<foreignObject>/<style>, on* handlers, non-fragment href/xlink:href
|
|
1797
|
-
// (<use>/<image>/<a>), and any url(...) that doesn't point at a #fragment —
|
|
1798
|
-
// those are client-side SSRF / beacon vectors and there is no CSP backstop.
|
|
1799
|
-
function sanitizeSvg(root) {
|
|
1800
|
-
root.querySelectorAll('script, foreignObject, style').forEach((n) => n.remove());
|
|
1801
|
-
const walk = (n) => {
|
|
1802
|
-
if (n.nodeType === 1) {
|
|
1803
|
-
for (const attr of Array.from(n.attributes)) {
|
|
1804
|
-
const name = attr.name.toLowerCase();
|
|
1805
|
-
const val = (attr.value || '').replace(/\s+/g, '').toLowerCase();
|
|
1806
|
-
const isHref = name === 'href' || name.endsWith(':href');
|
|
1807
|
-
if (
|
|
1808
|
-
name.startsWith('on') || // event handlers
|
|
1809
|
-
(isHref && !val.startsWith('#')) || // only same-document fragment refs
|
|
1810
|
-
/url\((?!['"]?#)/.test(val) // url() to anything but a #fragment
|
|
1811
|
-
) {
|
|
1812
|
-
n.removeAttribute(attr.name);
|
|
1813
|
-
}
|
|
1814
|
-
}
|
|
1815
|
-
}
|
|
1816
|
-
n.childNodes.forEach(walk);
|
|
1817
|
-
};
|
|
1818
|
-
walk(root);
|
|
1819
|
-
}
|
|
1820
|
-
|
|
1821
|
-
function renderPlantuml(block, ctx, blockId) {
|
|
1822
|
-
const container = el('div', { class: 'blk-plantuml' });
|
|
1823
|
-
const fail = () =>
|
|
1824
|
-
container.replaceChildren(
|
|
1825
|
-
el('div', { class: 'blk-error' }, 'PlantUML needs network access and a modern browser')
|
|
1826
|
-
);
|
|
1827
|
-
encodePlantUml(block.code || '')
|
|
1828
|
-
.then((encoded) => {
|
|
1829
|
-
const server = block.server || 'https://www.plantuml.com/plantuml';
|
|
1830
|
-
const url = server + '/svg/' + encoded;
|
|
1831
|
-
// Prefer inline SVG (per-element annotation); fall back to an opaque
|
|
1832
|
-
// <img> if the server blocks cross-origin fetch or anything fails.
|
|
1833
|
-
fetchInlineSvg(url)
|
|
1834
|
-
.then((svg) => mountPlantumlSvg(container, svg, block, ctx, blockId))
|
|
1835
|
-
.catch(() => mountPlantumlImg(container, url, fail, block, ctx, blockId));
|
|
1836
|
-
})
|
|
1837
|
-
.catch(fail);
|
|
1838
|
-
return container;
|
|
1839
|
-
}
|
|
1840
|
-
|
|
1841
|
-
function mountPlantumlSvg(container, svg, block, ctx, blockId) {
|
|
1842
|
-
if (block.height != null) container.style.maxHeight = clampHeight(block.height, 1200) + 'px';
|
|
1843
|
-
sizeDiagramSvg(svg);
|
|
1844
|
-
container.replaceChildren(svg);
|
|
1845
|
-
attachViewer(container, {
|
|
1846
|
-
zoomEl: svg,
|
|
1847
|
-
natural: svgNatural(svg),
|
|
1848
|
-
label: 'diagram',
|
|
1849
|
-
comment: wholeBlockComment(ctx, blockId, 'diagram'),
|
|
1850
|
-
});
|
|
1851
|
-
if (!ctx.annotate) return;
|
|
1852
|
-
// register the text labels as annotation targets (participant boxes, message
|
|
1853
|
-
// labels, …) — the meaningful, clickable parts of a PlantUML diagram.
|
|
1854
|
-
// `idx` disambiguates: PlantUML repeats participant labels top AND bottom,
|
|
1855
|
-
// so without a unique key one comment would badge BOTH identical-text nodes.
|
|
1856
|
-
svg.querySelectorAll('text').forEach((t, idx) => {
|
|
1857
|
-
const text = (t.textContent || '').trim();
|
|
1858
|
-
if (!text) return;
|
|
1859
|
-
ctx.annotate.register(t, {
|
|
1860
|
-
blockId,
|
|
1861
|
-
questionId: ctx.questionId,
|
|
1862
|
-
target: { kind: 'plantuml-node', idx, text: text.slice(0, 120) },
|
|
1863
|
-
});
|
|
1864
|
-
});
|
|
1865
|
-
}
|
|
1866
|
-
|
|
1867
|
-
function mountPlantumlImg(container, url, fail, block, ctx, blockId) {
|
|
1868
|
-
const img = el('img', { class: 'blk-plantuml-img', src: url, alt: 'PlantUML diagram', loading: 'lazy' });
|
|
1869
|
-
if (block.height != null) img.style.height = clampHeight(block.height, 360) + 'px';
|
|
1870
|
-
img.addEventListener('error', fail);
|
|
1871
|
-
container.replaceChildren(img);
|
|
1872
|
-
const attachImgViewer = () =>
|
|
1873
|
-
attachViewer(container, {
|
|
1874
|
-
zoomEl: img,
|
|
1875
|
-
natural: () => (img.naturalWidth > 0 ? { w: img.naturalWidth, h: img.naturalHeight } : null),
|
|
1876
|
-
label: 'diagram',
|
|
1877
|
-
comment: wholeBlockComment(ctx, blockId, 'diagram'),
|
|
1878
|
-
});
|
|
1879
|
-
if (img.complete && img.naturalWidth > 0) attachImgViewer();
|
|
1880
|
-
else img.addEventListener('load', attachImgViewer, { once: true });
|
|
1881
|
-
if (ctx.annotate) {
|
|
1882
|
-
ctx.annotate.register(img, {
|
|
1883
|
-
blockId,
|
|
1884
|
-
questionId: ctx.questionId,
|
|
1885
|
-
target: { kind: 'image', label: 'PlantUML diagram' },
|
|
1886
|
-
});
|
|
1887
|
-
}
|
|
1888
|
-
}
|
|
1889
|
-
|
|
1890
|
-
// ---------- image ----------
|
|
1891
|
-
let activeRegionMode = null;
|
|
1892
|
-
let viewerSpacePan = false;
|
|
1893
|
-
const setViewerSpacePan = (enabled) => {
|
|
1894
|
-
viewerSpacePan = Boolean(enabled);
|
|
1895
|
-
document.body.classList.toggle('blk-space-pan', viewerSpacePan);
|
|
1896
|
-
};
|
|
1897
|
-
document.addEventListener('keydown', (e) => {
|
|
1898
|
-
const tag = e.target && e.target.tagName ? e.target.tagName.toLowerCase() : '';
|
|
1899
|
-
if (e.code === 'Space' && !e.repeat && !['input', 'textarea', 'select'].includes(tag)) {
|
|
1900
|
-
setViewerSpacePan(true);
|
|
1901
|
-
e.preventDefault();
|
|
1902
|
-
}
|
|
1903
|
-
});
|
|
1904
|
-
document.addEventListener('keyup', (e) => {
|
|
1905
|
-
if (e.code === 'Space') setViewerSpacePan(false);
|
|
1906
|
-
});
|
|
1907
|
-
window.addEventListener('blur', () => setViewerSpacePan(false));
|
|
1908
|
-
|
|
1909
|
-
// src is a remote URL, or absent for embedded local files (served by the
|
|
1910
|
-
// board server at /img/b/<id>). Same sizing rule as diagrams: never upscale
|
|
1911
|
-
// past natural width; zoom/full-screen viewer attached once loaded.
|
|
1912
|
-
function renderImage(block, ctx, blockId) {
|
|
1913
|
-
const container = el('div', { class: 'blk-imagewrap' });
|
|
1914
|
-
const src = typeof block.src === 'string' && block.src
|
|
1915
|
-
? block.src
|
|
1916
|
-
: '/img/b/' + encodeURIComponent(blockId);
|
|
1917
|
-
const img = el('img', {
|
|
1918
|
-
class: 'blk-img',
|
|
1919
|
-
src,
|
|
1920
|
-
alt: block.alt || 'image',
|
|
1921
|
-
loading: 'lazy',
|
|
1922
|
-
draggable: 'false',
|
|
1923
|
-
title: ctx.canComment === false ? '' : 'Drag to draw a comment area · Space-drag to pan',
|
|
1924
|
-
});
|
|
1925
|
-
img.addEventListener('dragstart', (e) => e.preventDefault());
|
|
1926
|
-
const stage = el('div', { class: 'blk-imgstage' }, img);
|
|
1927
|
-
// Inline default: the image fills its full width (container width, never
|
|
1928
|
-
// upscaled past natural) so it's readable without manual zoom; the CONTAINER
|
|
1929
|
-
// caps the height (default 800 via CSS, or block.height) and SCROLLS — we
|
|
1930
|
-
// never cap the image's own height, which would shrink its width. Full-screen
|
|
1931
|
-
// lifts the cap (the .blk-full rule).
|
|
1932
|
-
if (block.height != null) container.style.maxHeight = clampHeight(block.height, 800) + 'px';
|
|
1933
|
-
img.addEventListener('error', () => {
|
|
1934
|
-
container.replaceChildren(el('div', { class: 'blk-error' }, 'Image failed to load'));
|
|
1935
|
-
});
|
|
1936
|
-
container.append(stage);
|
|
1937
|
-
const region = ctx.annotate && ctx.canComment !== false
|
|
1938
|
-
? enableImageRegions({
|
|
1939
|
-
host: stage,
|
|
1940
|
-
surface: img,
|
|
1941
|
-
panHost: container,
|
|
1942
|
-
sourceForSide: () => img,
|
|
1943
|
-
sideAtPoint: () => null,
|
|
1944
|
-
ctx,
|
|
1945
|
-
blockId,
|
|
1946
|
-
label: block.alt || 'Image',
|
|
1947
|
-
})
|
|
1948
|
-
: null;
|
|
1949
|
-
const attachImgViewer = () =>
|
|
1950
|
-
attachViewer(container, {
|
|
1951
|
-
zoomEl: stage,
|
|
1952
|
-
natural: () => (img.naturalWidth > 0 ? { w: img.naturalWidth, h: img.naturalHeight } : null),
|
|
1953
|
-
label: 'image',
|
|
1954
|
-
comment: wholeBlockComment(ctx, blockId, 'image'),
|
|
1955
|
-
region,
|
|
1956
|
-
});
|
|
1957
|
-
if (img.complete && img.naturalWidth > 0) attachImgViewer();
|
|
1958
|
-
else img.addEventListener('load', attachImgViewer, { once: true });
|
|
1959
|
-
if (ctx.annotate && block.pins === true) {
|
|
1960
|
-
enableImagePins(stage, img, ctx, blockId, block.alt || 'Image');
|
|
1961
|
-
} else if (ctx.annotate) {
|
|
1962
|
-
ctx.annotate.register(img, {
|
|
1963
|
-
blockId,
|
|
1964
|
-
questionId: ctx.questionId,
|
|
1965
|
-
target: { kind: 'image', label: block.alt || 'Image' },
|
|
1966
|
-
});
|
|
1967
|
-
}
|
|
1968
|
-
return container;
|
|
1969
|
-
}
|
|
1970
|
-
|
|
1971
|
-
// Coordinate pin-comments on an image (block.pins): click any point to drop a
|
|
1972
|
-
// comment anchored to that (x,y) fraction; a numbered pin marks each one and
|
|
1973
|
-
// tracks the image as it scales/scrolls (positions are % of the displayed img,
|
|
1974
|
-
// so they ride zoom/full-screen/pan for free). Mirrors the chart-badge model.
|
|
1975
|
-
function enableImagePins(container, img, ctx, blockId, label) {
|
|
1976
|
-
const layer = el('div', { class: 'blk-imgpins' });
|
|
1977
|
-
container.append(layer);
|
|
1978
|
-
if (ctx.canComment !== false) img.classList.add('blk-img-pinnable');
|
|
1979
|
-
let down = null; // {x,y} at pointerdown — used to reject drags (pan) as clicks
|
|
1980
|
-
img.addEventListener('pointerdown', (e) => { down = { x: e.clientX, y: e.clientY }; });
|
|
1981
|
-
img.addEventListener('click', (e) => {
|
|
1982
|
-
if (ctx.canComment === false) return;
|
|
1983
|
-
if (img._rlySuppressPointClick) { img._rlySuppressPointClick = false; down = null; return; }
|
|
1984
|
-
if (down && (Math.abs(e.clientX - down.x) > 4 || Math.abs(e.clientY - down.y) > 4)) { down = null; return; }
|
|
1985
|
-
const r = img.getBoundingClientRect();
|
|
1986
|
-
if (!r.width || !r.height) return;
|
|
1987
|
-
const x = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
|
|
1988
|
-
const y = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height));
|
|
1989
|
-
ctx.annotate.openExternal(
|
|
1990
|
-
{ blockId, questionId: ctx.questionId, target: { kind: 'image-point', x: Math.round(x * 1000) / 1000, y: Math.round(y * 1000) / 1000, label } },
|
|
1991
|
-
img
|
|
1992
|
-
);
|
|
1993
|
-
});
|
|
1994
|
-
const syncPins = () => {
|
|
1995
|
-
layer.replaceChildren();
|
|
1996
|
-
const groups = new Map(); // "x:y" -> {target, count}
|
|
1997
|
-
let n = 0;
|
|
1998
|
-
for (const a of ctx.annotate.list()) {
|
|
1999
|
-
if (a.blockId !== blockId) continue;
|
|
2000
|
-
const t = a.target || {};
|
|
2001
|
-
if (t.kind !== 'image-point') continue;
|
|
2002
|
-
const k = t.x + ':' + t.y;
|
|
2003
|
-
const g = groups.get(k) || { target: t, count: 0 };
|
|
2004
|
-
g.count++; groups.set(k, g);
|
|
2005
|
-
}
|
|
2006
|
-
for (const { target, count } of groups.values()) {
|
|
2007
|
-
n++;
|
|
2008
|
-
const pin = el('button', { class: 'blk-imgpin', type: 'button', title: count + (count === 1 ? ' comment' : ' comments') }, String(count));
|
|
2009
|
-
pin.style.left = (target.x * 100) + '%';
|
|
2010
|
-
pin.style.top = (target.y * 100) + '%';
|
|
2011
|
-
pin.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
2012
|
-
pin.addEventListener('click', (e) => {
|
|
2013
|
-
e.stopPropagation(); e.preventDefault();
|
|
2014
|
-
ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, pin);
|
|
2015
|
-
});
|
|
2016
|
-
layer.append(pin);
|
|
2017
|
-
}
|
|
2018
|
-
};
|
|
2019
|
-
if (ctx.annotate.onBadgeRefresh) ctx.annotate.onBadgeRefresh(syncPins);
|
|
2020
|
-
syncPins();
|
|
2021
|
-
}
|
|
2022
|
-
|
|
2023
|
-
// Hold, then drag, to select a rectangular image area. A short move remains
|
|
2024
|
-
// native viewer pan / comparison-slider input; the hold threshold makes the
|
|
2025
|
-
// two gestures coexist without a mode switch. Region coordinates are stored
|
|
2026
|
-
// as normalized fractions, while a pixel crop is uploaded through the host
|
|
2027
|
-
// context so the result gives the agent an actual viewable image artifact.
|
|
2028
|
-
function enableImageRegions({ host, surface, panHost, sourceForSide, sideAtPoint, ctx, blockId, label }) {
|
|
2029
|
-
const layer = el('div', { class: 'blk-region-layer' });
|
|
2030
|
-
const selection = el('div', { class: 'blk-region-selection' });
|
|
2031
|
-
layer.append(selection);
|
|
2032
|
-
host.append(layer);
|
|
2033
|
-
panHost._rlyHasRegions = true;
|
|
2034
|
-
panHost.classList.add('blk-has-regions');
|
|
2035
|
-
let pending = null;
|
|
2036
|
-
let active = false;
|
|
2037
|
-
let status = null;
|
|
2038
|
-
let modeActive = false;
|
|
2039
|
-
const modeHooks = new Set();
|
|
2040
|
-
let controller = null;
|
|
2041
|
-
const MIN_REGION = 0.012;
|
|
2042
|
-
|
|
2043
|
-
const localPoint = (e) => {
|
|
2044
|
-
const r = host.getBoundingClientRect();
|
|
2045
|
-
return {
|
|
2046
|
-
x: r.width ? Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)) : 0,
|
|
2047
|
-
y: r.height ? Math.max(0, Math.min(1, (e.clientY - r.top) / r.height)) : 0,
|
|
2048
|
-
};
|
|
2049
|
-
};
|
|
2050
|
-
const clearStatus = () => { if (status) status.remove(); status = null; };
|
|
2051
|
-
const showStatus = (text) => {
|
|
2052
|
-
clearStatus();
|
|
2053
|
-
status = el('div', { class: 'blk-region-status', role: 'status' }, text);
|
|
2054
|
-
host.append(status);
|
|
2055
|
-
};
|
|
2056
|
-
const reset = () => {
|
|
2057
|
-
active = false;
|
|
2058
|
-
pending = null;
|
|
2059
|
-
panHost._rlyRegionSelecting = false;
|
|
2060
|
-
host.classList.remove('blk-region-arming', 'blk-region-selecting');
|
|
2061
|
-
selection.style.display = 'none';
|
|
2062
|
-
clearStatus();
|
|
2063
|
-
};
|
|
2064
|
-
const setModeActive = (next) => {
|
|
2065
|
-
const enabled = Boolean(next);
|
|
2066
|
-
if (enabled && activeRegionMode && activeRegionMode !== controller) {
|
|
2067
|
-
activeRegionMode.setModeActive(false);
|
|
2068
|
-
}
|
|
2069
|
-
if (!enabled && pending) reset();
|
|
2070
|
-
if (modeActive === enabled) return;
|
|
2071
|
-
modeActive = enabled;
|
|
2072
|
-
panHost._rlyRegionMode = enabled;
|
|
2073
|
-
host.classList.toggle('blk-region-mode', enabled);
|
|
2074
|
-
activeRegionMode = enabled ? controller : (activeRegionMode === controller ? null : activeRegionMode);
|
|
2075
|
-
for (const fn of modeHooks) { try { fn(enabled); } catch (_) {} }
|
|
2076
|
-
};
|
|
2077
|
-
controller = {
|
|
2078
|
-
setModeActive,
|
|
2079
|
-
isModeActive: () => modeActive,
|
|
2080
|
-
onModeChange: (fn) => {
|
|
2081
|
-
if (typeof fn === 'function') modeHooks.add(fn);
|
|
2082
|
-
return () => modeHooks.delete(fn);
|
|
2083
|
-
},
|
|
2084
|
-
};
|
|
2085
|
-
document.addEventListener('keydown', (e) => {
|
|
2086
|
-
if (e.key === 'Escape' && modeActive) setModeActive(false);
|
|
2087
|
-
});
|
|
2088
|
-
const draw = (a, b) => {
|
|
2089
|
-
const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
|
|
2090
|
-
const w = Math.abs(a.x - b.x), h = Math.abs(a.y - b.y);
|
|
2091
|
-
selection.style.left = (x * 100) + '%';
|
|
2092
|
-
selection.style.top = (y * 100) + '%';
|
|
2093
|
-
selection.style.width = (w * 100) + '%';
|
|
2094
|
-
selection.style.height = (h * 100) + '%';
|
|
2095
|
-
return { x, y, w, h };
|
|
2096
|
-
};
|
|
2097
|
-
const createRegionZone = (target, count, provisional = false) => {
|
|
2098
|
-
const badge = el('span', { class: 'blk-imgregion-badge', 'aria-hidden': 'true' });
|
|
2099
|
-
badge.innerHTML = ICON_COMMENT;
|
|
2100
|
-
badge.append(el('span', { class: 'blk-imgregion-count' }, String(count)));
|
|
2101
|
-
const sideLabel = target.side ? target.side + ' ' : '';
|
|
2102
|
-
const region = el('button', {
|
|
2103
|
-
class: 'blk-imgregion' + (provisional ? ' blk-imgregion-provisional' : ''),
|
|
2104
|
-
type: 'button',
|
|
2105
|
-
title: provisional
|
|
2106
|
-
? `Add a comment to this ${sideLabel}area`
|
|
2107
|
-
: `${target.side ? target.side + ' · ' : ''}${count} ${count === 1 ? 'comment' : 'comments'}`,
|
|
2108
|
-
'aria-label': provisional
|
|
2109
|
-
? `New ${sideLabel}image area comment`
|
|
2110
|
-
: `${sideLabel}image area with ${count} ${count === 1 ? 'comment' : 'comments'}`,
|
|
2111
|
-
}, badge);
|
|
2112
|
-
region.style.left = (target.x * 100) + '%';
|
|
2113
|
-
region.style.top = (target.y * 100) + '%';
|
|
2114
|
-
region.style.width = (target.w * 100) + '%';
|
|
2115
|
-
region.style.height = (target.h * 100) + '%';
|
|
2116
|
-
region.addEventListener('pointerdown', (e) => e.stopPropagation());
|
|
2117
|
-
if (!provisional) {
|
|
2118
|
-
region.addEventListener('click', (e) => {
|
|
2119
|
-
e.stopPropagation();
|
|
2120
|
-
ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, region);
|
|
2121
|
-
});
|
|
2122
|
-
}
|
|
2123
|
-
return region;
|
|
2124
|
-
};
|
|
2125
|
-
const beginSelection = (pointerId) => {
|
|
2126
|
-
if (!pending || active) return;
|
|
2127
|
-
active = true;
|
|
2128
|
-
panHost._rlyRegionSelecting = true;
|
|
2129
|
-
host.classList.remove('blk-region-arming');
|
|
2130
|
-
host.classList.add('blk-region-selecting');
|
|
2131
|
-
selection.style.display = 'block';
|
|
2132
|
-
draw(pending.start, pending.start);
|
|
2133
|
-
showStatus((pending.side ? pending.side.charAt(0).toUpperCase() + pending.side.slice(1) + ' · ' : '') + 'drag to select an area');
|
|
2134
|
-
try { surface.setPointerCapture(pointerId); } catch (_) {}
|
|
2135
|
-
};
|
|
2136
|
-
|
|
2137
|
-
async function cropRegion(img, region) {
|
|
2138
|
-
if (!img || !img.naturalWidth || !img.naturalHeight) throw new Error('image is not ready');
|
|
2139
|
-
const sx = Math.max(0, Math.floor(region.x * img.naturalWidth));
|
|
2140
|
-
const sy = Math.max(0, Math.floor(region.y * img.naturalHeight));
|
|
2141
|
-
const sw = Math.max(1, Math.min(img.naturalWidth - sx, Math.round(region.w * img.naturalWidth)));
|
|
2142
|
-
const sh = Math.max(1, Math.min(img.naturalHeight - sy, Math.round(region.h * img.naturalHeight)));
|
|
2143
|
-
const scale = Math.min(1, 1400 / sw, 1400 / sh);
|
|
2144
|
-
const width = Math.max(1, Math.round(sw * scale));
|
|
2145
|
-
const height = Math.max(1, Math.round(sh * scale));
|
|
2146
|
-
const canvas = document.createElement('canvas');
|
|
2147
|
-
canvas.width = width;
|
|
2148
|
-
canvas.height = height;
|
|
2149
|
-
const g = canvas.getContext('2d');
|
|
2150
|
-
if (!g) throw new Error('canvas unavailable');
|
|
2151
|
-
g.drawImage(img, sx, sy, sw, sh, 0, 0, width, height);
|
|
2152
|
-
const dataUrl = canvas.toDataURL('image/png');
|
|
2153
|
-
if (!/^data:image\/png;base64,/.test(dataUrl)) throw new Error('crop unavailable');
|
|
2154
|
-
if (ctx.saveArtifact) return ctx.saveArtifact({ dataUrl, mime: 'image/png', width, height, blockId });
|
|
2155
|
-
return { data: dataUrl.slice(dataUrl.indexOf(',') + 1), mime: 'image/png', width, height };
|
|
2156
|
-
}
|
|
2157
|
-
|
|
2158
|
-
const finishRegion = async (region, side) => {
|
|
2159
|
-
const target = {
|
|
2160
|
-
kind: 'image-region',
|
|
2161
|
-
x: Math.round(region.x * 10000) / 10000,
|
|
2162
|
-
y: Math.round(region.y * 10000) / 10000,
|
|
2163
|
-
w: Math.round(region.w * 10000) / 10000,
|
|
2164
|
-
h: Math.round(region.h * 10000) / 10000,
|
|
2165
|
-
side: side || undefined,
|
|
2166
|
-
label,
|
|
2167
|
-
};
|
|
2168
|
-
const provisional = createRegionZone(target, 0, true);
|
|
2169
|
-
layer.append(provisional);
|
|
2170
|
-
showStatus('Saving selected area…');
|
|
2171
|
-
try {
|
|
2172
|
-
target.crop = await cropRegion(sourceForSide(side), region);
|
|
2173
|
-
} catch {
|
|
2174
|
-
target.cropUnavailable = true;
|
|
2175
|
-
}
|
|
2176
|
-
clearStatus();
|
|
2177
|
-
ctx.annotate.openExternal({
|
|
2178
|
-
blockId,
|
|
2179
|
-
questionId: ctx.questionId,
|
|
2180
|
-
target,
|
|
2181
|
-
onClose: () => provisional.remove(),
|
|
2182
|
-
}, provisional);
|
|
2183
|
-
};
|
|
2184
|
-
|
|
2185
|
-
surface.addEventListener('pointerdown', (e) => {
|
|
2186
|
-
if (e.button !== 0 || viewerSpacePan || ctx.canComment === false) return;
|
|
2187
|
-
if (e.target.closest && e.target.closest('.cmp-handle, .blk-imgregion, .blk-tools')) return;
|
|
2188
|
-
if (modeActive) {
|
|
2189
|
-
e.preventDefault();
|
|
2190
|
-
e.stopPropagation();
|
|
2191
|
-
}
|
|
2192
|
-
const p = localPoint(e);
|
|
2193
|
-
pending = {
|
|
2194
|
-
start: p,
|
|
2195
|
-
last: p,
|
|
2196
|
-
clientX: e.clientX,
|
|
2197
|
-
clientY: e.clientY,
|
|
2198
|
-
pointerId: e.pointerId,
|
|
2199
|
-
explicitMode: modeActive,
|
|
2200
|
-
side: sideAtPoint(p.x),
|
|
2201
|
-
};
|
|
2202
|
-
host.classList.add('blk-region-arming');
|
|
2203
|
-
if (modeActive) beginSelection(e.pointerId);
|
|
2204
|
-
});
|
|
2205
|
-
surface.addEventListener('pointermove', (e) => {
|
|
2206
|
-
if (!pending) return;
|
|
2207
|
-
const moved = Math.hypot(e.clientX - pending.clientX, e.clientY - pending.clientY);
|
|
2208
|
-
if (!active && moved > 5) beginSelection(pending.pointerId);
|
|
2209
|
-
if (!active) {
|
|
2210
|
-
return;
|
|
2211
|
-
}
|
|
2212
|
-
e.preventDefault();
|
|
2213
|
-
e.stopPropagation();
|
|
2214
|
-
pending.last = localPoint(e);
|
|
2215
|
-
draw(pending.start, pending.last);
|
|
2216
|
-
});
|
|
2217
|
-
const end = (e) => {
|
|
2218
|
-
if (!pending) return;
|
|
2219
|
-
if (!active) { reset(); return; }
|
|
2220
|
-
e.preventDefault();
|
|
2221
|
-
const region = draw(pending.start, pending.last || localPoint(e));
|
|
2222
|
-
const side = pending.side;
|
|
2223
|
-
const explicitMode = pending.explicitMode;
|
|
2224
|
-
surface._rlySuppressPointClick = true;
|
|
2225
|
-
reset();
|
|
2226
|
-
clearStatus();
|
|
2227
|
-
if (region.w >= MIN_REGION && region.h >= MIN_REGION) {
|
|
2228
|
-
if (explicitMode) setModeActive(false);
|
|
2229
|
-
finishRegion(region, side);
|
|
2230
|
-
} else if (explicitMode) {
|
|
2231
|
-
showStatus('Drag a larger area');
|
|
2232
|
-
setTimeout(clearStatus, 1200);
|
|
2233
|
-
}
|
|
2234
|
-
};
|
|
2235
|
-
surface.addEventListener('pointerup', end);
|
|
2236
|
-
// Some Chromium/CDP paths emit pointercancel immediately after granting
|
|
2237
|
-
// capture on the first dragged frame. Once area mode is active, keep the
|
|
2238
|
-
// last drawn rectangle instead of throwing the user's deliberate hold away.
|
|
2239
|
-
surface.addEventListener('pointercancel', (e) => active ? end(e) : reset());
|
|
2240
|
-
|
|
2241
|
-
const syncRegions = () => {
|
|
2242
|
-
for (const node of Array.from(layer.querySelectorAll('.blk-imgregion:not(.blk-imgregion-provisional)'))) node.remove();
|
|
2243
|
-
const groups = new Map();
|
|
2244
|
-
for (const a of ctx.annotate.list()) {
|
|
2245
|
-
if (a.blockId !== blockId || !a.target || a.target.kind !== 'image-region') continue;
|
|
2246
|
-
const t = a.target;
|
|
2247
|
-
const key = [t.side || '', t.x, t.y, t.w, t.h].join(':');
|
|
2248
|
-
const group = groups.get(key) || { target: t, count: 0 };
|
|
2249
|
-
group.count++;
|
|
2250
|
-
groups.set(key, group);
|
|
2251
|
-
}
|
|
2252
|
-
for (const { target, count } of groups.values()) {
|
|
2253
|
-
layer.append(createRegionZone(target, count));
|
|
2254
|
-
}
|
|
2255
|
-
};
|
|
2256
|
-
if (ctx.annotate.onBadgeRefresh) ctx.annotate.onBadgeRefresh(syncRegions);
|
|
2257
|
-
syncRegions();
|
|
2258
|
-
return controller;
|
|
2259
|
-
}
|
|
2260
|
-
|
|
2261
|
-
// ---------- palette ----------
|
|
2262
|
-
// Color palettes as swatch cards: hover a swatch to reveal its hex, click to
|
|
2263
|
-
// copy it. One palette may be {featured:true} → a larger spotlight row. Lets
|
|
2264
|
-
// an agent present a curated palette with one structured block instead of
|
|
2265
|
-
// hand-writing HTML. Swatches and the whole block are commentable.
|
|
2266
|
-
function copyColor(text, btn) {
|
|
2267
|
-
const done = () => {
|
|
2268
|
-
btn.classList.add('copied');
|
|
2269
|
-
setTimeout(() => btn.classList.remove('copied'), 900);
|
|
2270
|
-
};
|
|
2271
|
-
try {
|
|
2272
|
-
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
2273
|
-
navigator.clipboard.writeText(text).then(done, () => {});
|
|
2274
|
-
return;
|
|
2275
|
-
}
|
|
2276
|
-
} catch { /* fall through */ }
|
|
2277
|
-
done(); // no clipboard (sandbox) — still flash feedback
|
|
2278
|
-
}
|
|
2279
|
-
|
|
2280
|
-
function paletteCard(p, big, ctx, blockId) {
|
|
2281
|
-
const card = el('div', { class: 'pal-card' + (big ? ' pal-spotlight' : '') });
|
|
2282
|
-
const row = el('div', { class: 'pal-swatches' });
|
|
2283
|
-
for (const c of p.colors) {
|
|
2284
|
-
const sw = el('button', { class: 'pal-sw', type: 'button', style: 'background:' + c, title: 'Copy ' + c });
|
|
2285
|
-
sw.append(el('span', { class: 'pal-hex' }, c));
|
|
2286
|
-
sw.addEventListener('click', () => copyColor(c, sw));
|
|
2287
|
-
if (ctx.annotate) {
|
|
2288
|
-
ctx.annotate.register(sw, {
|
|
2289
|
-
blockId,
|
|
2290
|
-
questionId: ctx.questionId,
|
|
2291
|
-
target: { kind: 'swatch', label: (p.name ? p.name + ' · ' : '') + c },
|
|
2292
|
-
});
|
|
2293
|
-
}
|
|
2294
|
-
row.append(sw);
|
|
2295
|
-
}
|
|
2296
|
-
card.append(row);
|
|
2297
|
-
const info = el('div', { class: 'pal-info' });
|
|
2298
|
-
const meta = el('div', { class: 'pal-meta' });
|
|
2299
|
-
if (p.name) meta.append(el('div', { class: 'pal-name' }, p.name));
|
|
2300
|
-
if (p.sub) meta.append(el('div', { class: 'pal-sub' }, p.sub));
|
|
2301
|
-
info.append(meta);
|
|
2302
|
-
if (p.tag) info.append(el('span', { class: 'pal-tag' + (p.tagTone ? ' tone-' + p.tagTone : '') }, p.tag));
|
|
2303
|
-
if (p.name || p.sub || p.tag) card.append(info);
|
|
2304
|
-
return card;
|
|
2305
|
-
}
|
|
2306
|
-
|
|
2307
|
-
function renderPalette(block, ctx, blockId) {
|
|
2308
|
-
const wrap = el('div', { class: 'blk-palette' });
|
|
2309
|
-
const palettes = Array.isArray(block.palettes) ? block.palettes : [];
|
|
2310
|
-
if (block.title) wrap.append(el('div', { class: 'pal-title' }, block.title));
|
|
2311
|
-
const grid = el('div', { class: 'pal-grid' });
|
|
2312
|
-
for (const p of palettes) {
|
|
2313
|
-
if (p.featured) wrap.append(paletteCard(p, true, ctx, blockId));
|
|
2314
|
-
else grid.append(paletteCard(p, false, ctx, blockId));
|
|
2315
|
-
}
|
|
2316
|
-
if (grid.childNodes.length) wrap.append(grid);
|
|
2317
|
-
return wrap;
|
|
2318
|
-
}
|
|
2319
|
-
|
|
2320
|
-
// ---------- kpi (stat cards) ----------
|
|
2321
|
-
function renderKpi(block, ctx, blockId) {
|
|
2322
|
-
const wrap = el('div', { class: 'blk-kpi' });
|
|
2323
|
-
if (block.title) wrap.append(el('div', { class: 'kpi-title' }, block.title));
|
|
2324
|
-
const grid = el('div', { class: 'kpi-grid' });
|
|
2325
|
-
for (const it of block.items || []) {
|
|
2326
|
-
const card = el('div', { class: 'kpi-card' });
|
|
2327
|
-
if (it.label) card.append(el('div', { class: 'kpi-label' }, it.label));
|
|
2328
|
-
card.append(el('div', { class: 'kpi-value' }, it.value || ''));
|
|
2329
|
-
if (it.delta) {
|
|
2330
|
-
const glyph = it.dir === 'up' ? '▲ ' : it.dir === 'down' ? '▼ ' : it.dir === 'flat' ? '▬ ' : '';
|
|
2331
|
-
card.append(el('div', { class: 'kpi-delta' + (it.dir ? ' kpi-' + it.dir : '') }, glyph + it.delta));
|
|
2332
|
-
}
|
|
2333
|
-
if (it.sub) card.append(el('div', { class: 'kpi-sub' }, it.sub));
|
|
2334
|
-
if (ctx.annotate) {
|
|
2335
|
-
ctx.annotate.register(card, {
|
|
2336
|
-
blockId, questionId: ctx.questionId,
|
|
2337
|
-
target: { kind: 'html-element', label: ((it.label ? it.label + ' · ' : '') + (it.value || 'KPI')) },
|
|
2338
|
-
});
|
|
2339
|
-
}
|
|
2340
|
-
grid.append(card);
|
|
2341
|
-
}
|
|
2342
|
-
wrap.append(grid);
|
|
2343
|
-
return wrap;
|
|
2344
|
-
}
|
|
2345
|
-
|
|
2346
|
-
// ---------- typography (type specimens) ----------
|
|
2347
|
-
function renderTypography(block, ctx, blockId) {
|
|
2348
|
-
const wrap = el('div', { class: 'blk-typography' });
|
|
2349
|
-
if (block.title) wrap.append(el('div', { class: 'typo-title' }, block.title));
|
|
2350
|
-
for (const s of block.specimens || []) {
|
|
2351
|
-
const meta = [];
|
|
2352
|
-
if (s.label) meta.push(s.label);
|
|
2353
|
-
if (s.size) meta.push(s.size);
|
|
2354
|
-
if (s.weight) meta.push('w' + s.weight);
|
|
2355
|
-
const sample = el('div', { class: 'typo-sample' }, s.text);
|
|
2356
|
-
// set via DOM style props (browser ignores invalid values — no injection)
|
|
2357
|
-
if (s.size) sample.style.fontSize = s.size;
|
|
2358
|
-
if (s.weight) sample.style.fontWeight = s.weight;
|
|
2359
|
-
if (s.font || block.font) sample.style.fontFamily = s.font || block.font;
|
|
2360
|
-
if (s.lineHeight) sample.style.lineHeight = s.lineHeight;
|
|
2361
|
-
if (s.letterSpacing) sample.style.letterSpacing = s.letterSpacing;
|
|
2362
|
-
wrap.append(el('div', { class: 'typo-row' },
|
|
2363
|
-
meta.length ? el('div', { class: 'typo-meta' }, meta.join(' · ')) : null,
|
|
2364
|
-
sample
|
|
2365
|
-
));
|
|
2366
|
-
}
|
|
2367
|
-
ctx.annotate && ctx.annotate.enableTextSelection(wrap, { blockId, questionId: ctx.questionId });
|
|
2368
|
-
return wrap;
|
|
2369
|
-
}
|
|
2370
|
-
|
|
2371
|
-
// ---------- compare (before/after image slider) ----------
|
|
2372
|
-
// The "after" image is the base layer (defines the frame size); the "before"
|
|
2373
|
-
// image sits in an overflow-clipped layer whose width the divider drives, so
|
|
2374
|
-
// dragging reveals more of one image and less of the other.
|
|
2375
|
-
function renderCompare(block, ctx, blockId) {
|
|
2376
|
-
const wrap = el('div', { class: 'blk-comparewrap' });
|
|
2377
|
-
const frame = el('div', { class: 'cmp-frame' });
|
|
2378
|
-
if (block.height) frame.style.maxHeight = clampHeight(block.height, 1200) + 'px';
|
|
2379
|
-
const afterImg = el('img', { class: 'cmp-img', src: block.after, alt: block.afterLabel || 'after', draggable: 'false', loading: 'lazy' });
|
|
2380
|
-
const beforeImg = el('img', { class: 'cmp-img cmp-img-before', src: block.before, alt: block.beforeLabel || 'before', draggable: 'false', loading: 'lazy' });
|
|
2381
|
-
const beforeLayer = el('div', { class: 'cmp-before' }, beforeImg);
|
|
2382
|
-
const handle = el('div', { class: 'cmp-handle', tabindex: '0', role: 'slider', 'aria-label': 'Compare before and after' },
|
|
2383
|
-
el('div', { class: 'cmp-handle-grip' }, '⟺'));
|
|
2384
|
-
frame.append(
|
|
2385
|
-
afterImg, beforeLayer, handle,
|
|
2386
|
-
el('span', { class: 'cmp-tag cmp-tag-before' }, block.beforeLabel || 'Before'),
|
|
2387
|
-
el('span', { class: 'cmp-tag cmp-tag-after' }, block.afterLabel || 'After')
|
|
2388
|
-
);
|
|
2389
|
-
wrap.append(frame);
|
|
2390
|
-
|
|
2391
|
-
let pos = 50;
|
|
2392
|
-
const apply = () => { beforeLayer.style.width = pos + '%'; handle.style.left = pos + '%'; };
|
|
2393
|
-
// pin the before image to the frame's pixel width so the clip reveals it in
|
|
2394
|
-
// place (rather than squishing it as the clip narrows)
|
|
2395
|
-
const sizeBefore = () => { beforeImg.style.width = frame.clientWidth + 'px'; };
|
|
2396
|
-
const refresh = () => { sizeBefore(); apply(); };
|
|
2397
|
-
if (afterImg.complete && afterImg.naturalWidth) refresh();
|
|
2398
|
-
else afterImg.addEventListener('load', refresh, { once: true });
|
|
2399
|
-
window.addEventListener('resize', sizeBefore);
|
|
2400
|
-
|
|
2401
|
-
let dragging = false;
|
|
2402
|
-
let dragMoved = false;
|
|
2403
|
-
let dragStartX = 0;
|
|
2404
|
-
const setFromX = (clientX) => {
|
|
2405
|
-
const r = frame.getBoundingClientRect();
|
|
2406
|
-
if (r.width) { pos = Math.max(0, Math.min(100, ((clientX - r.left) / r.width) * 100)); apply(); }
|
|
2407
|
-
};
|
|
2408
|
-
frame.addEventListener('pointerdown', (e) => {
|
|
2409
|
-
const handleTarget = e.target.closest('.cmp-handle');
|
|
2410
|
-
if (!handleTarget || frame._rlyRegionMode) return;
|
|
2411
|
-
dragging = true;
|
|
2412
|
-
dragMoved = false;
|
|
2413
|
-
dragStartX = e.clientX;
|
|
2414
|
-
try { frame.setPointerCapture(e.pointerId); } catch (_) {}
|
|
2415
|
-
});
|
|
2416
|
-
frame.addEventListener('pointermove', (e) => {
|
|
2417
|
-
if (!dragging || frame._rlyRegionMode || frame._rlyRegionSelecting) return;
|
|
2418
|
-
if (Math.abs(e.clientX - dragStartX) > 3) dragMoved = true;
|
|
2419
|
-
if (dragMoved) { setFromX(e.clientX); e.preventDefault(); }
|
|
2420
|
-
});
|
|
2421
|
-
frame.addEventListener('pointerup', (e) => {
|
|
2422
|
-
if (dragging && !dragMoved && !frame._rlyRegionMode && !frame._rlyRegionSelecting) setFromX(e.clientX);
|
|
2423
|
-
dragging = false;
|
|
2424
|
-
});
|
|
2425
|
-
frame.addEventListener('pointercancel', () => { dragging = false; dragMoved = false; });
|
|
2426
|
-
handle.addEventListener('keydown', (e) => {
|
|
2427
|
-
if (e.key === 'ArrowLeft') { pos = Math.max(0, pos - 2); apply(); e.preventDefault(); }
|
|
2428
|
-
else if (e.key === 'ArrowRight') { pos = Math.min(100, pos + 2); apply(); e.preventDefault(); }
|
|
2429
|
-
});
|
|
2430
|
-
let region = null;
|
|
2431
|
-
if (ctx.annotate && ctx.canComment !== false) {
|
|
2432
|
-
frame.title = 'Drag to draw a comment area · drag the divider handle to compare';
|
|
2433
|
-
region = enableImageRegions({
|
|
2434
|
-
host: frame,
|
|
2435
|
-
surface: frame,
|
|
2436
|
-
panHost: frame,
|
|
2437
|
-
sourceForSide: (side) => side === 'before' ? beforeImg : afterImg,
|
|
2438
|
-
sideAtPoint: (x) => (x * 100 <= pos ? 'before' : 'after'),
|
|
2439
|
-
ctx,
|
|
2440
|
-
blockId,
|
|
2441
|
-
label: 'Comparison',
|
|
2442
|
-
});
|
|
2443
|
-
}
|
|
2444
|
-
attachViewer(wrap, {
|
|
2445
|
-
zoomEl: null,
|
|
2446
|
-
label: 'comparison',
|
|
2447
|
-
comment: wholeBlockComment(ctx, blockId, 'comparison'),
|
|
2448
|
-
region,
|
|
2449
|
-
});
|
|
2450
|
-
return wrap;
|
|
2451
|
-
}
|
|
2452
|
-
|
|
2453
|
-
// ---------- viewer controls (zoom / fit / full-screen) ----------
|
|
2454
|
-
// Large diagrams get squeezed to the column width; these controls let the
|
|
2455
|
-
// user zoom (buttons or cmd/ctrl+wheel) and expand any visual block into a
|
|
2456
|
-
// full-screen overlay. An overlay — NOT the native Fullscreen API — keeps
|
|
2457
|
-
// the annotation pins/badges/popover usable while expanded (they live on
|
|
2458
|
-
// <body>, which native fullscreen would hide).
|
|
2459
|
-
let fullOpen = null; // container currently expanded
|
|
2460
|
-
// full-screen content insets — must mirror the .blk-full padding in blocks.css
|
|
2461
|
-
// so the fit-to-screen scale clears the fixed toolbar + leaves a small margin.
|
|
2462
|
-
const FULL_PAD_X = 24, FULL_PAD_TOP = 44, FULL_PAD_BOTTOM = 24;
|
|
2463
|
-
// Wheel/pinch zoom is delta-proportional and animated. The old fixed 15% jump
|
|
2464
|
-
// ran once for every wheel event, so a high-frequency trackpad gesture could
|
|
2465
|
-
// compound to several hundred percent almost instantly. Cap the contribution
|
|
2466
|
-
// of one event (mouse wheels often report ±100px) and ease toward the gesture's
|
|
2467
|
-
// accumulated target at most once per animation frame.
|
|
2468
|
-
const WHEEL_ZOOM_SENSITIVITY = 0.003;
|
|
2469
|
-
const WHEEL_ZOOM_MAX_DELTA = 20;
|
|
2470
|
-
const WHEEL_ZOOM_EASE = 0.24;
|
|
2471
|
-
const WHEEL_ZOOM_EPSILON = 0.001;
|
|
2472
|
-
|
|
2473
|
-
// Toolbar icons: full-screen (4-corner expand) and a speech-bubble for the
|
|
2474
|
-
// "comment on the whole block" button. Zoom is both cmd/ctrl+wheel AND
|
|
2475
|
-
// explicit −/+ buttons (the % doubles as a reset-to-fit button).
|
|
2476
|
-
const ICON_EXPAND =
|
|
2477
|
-
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
|
|
2478
|
-
'<path d="M3 9V3h6M10 10 3 3M15 3h6v6M14 10l7-7M9 21H3v-6M10 14l-7 7M21 15v6h-6M14 14l7 7"/></svg>';
|
|
2479
|
-
const ICON_COMMENT =
|
|
2480
|
-
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
|
|
2481
|
-
'<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z"/></svg>';
|
|
2482
|
-
const ICON_REGION =
|
|
2483
|
-
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
|
|
2484
|
-
'<rect x="3" y="4" width="14" height="12" rx="2" stroke-dasharray="3 2"/>' +
|
|
2485
|
-
'<path d="M14 14.5h6.5v4H18l-2.5 2v-2H14z" fill="currentColor" stroke="none"/></svg>';
|
|
2486
|
-
const ICON_EYE =
|
|
2487
|
-
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
|
|
2488
|
-
'<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>';
|
|
2489
|
-
|
|
2490
|
-
function exitFull() {
|
|
2491
|
-
if (!fullOpen) return;
|
|
2492
|
-
const c = fullOpen;
|
|
2493
|
-
if (c._rlyStopWheelZoom) c._rlyStopWheelZoom();
|
|
2494
|
-
c.classList.remove('blk-full');
|
|
2495
|
-
document.body.classList.remove('blk-full-open');
|
|
2496
|
-
const btn = c.querySelector('.blk-tools .tool-full');
|
|
2497
|
-
if (btn) btn.innerHTML = ICON_EXPAND;
|
|
2498
|
-
fullOpen = null;
|
|
2499
|
-
window.dispatchEvent(new Event('resize'));
|
|
2500
|
-
if (c._rlyZoom) c._rlyZoom.reapply(); // restore the compact inline height cap
|
|
2501
|
-
}
|
|
2502
|
-
document.addEventListener('keydown', (e) => {
|
|
2503
|
-
if (e.key === 'Escape' && fullOpen && !document.querySelector('.rly-file-dialog[open]')) exitFull();
|
|
2504
|
-
});
|
|
2505
|
-
|
|
2506
|
-
// Enter full-screen for a viewer container (shared by the toolbar button and
|
|
2507
|
-
// the markdown reference-link → modal path).
|
|
2508
|
-
function enterFull(container) {
|
|
2509
|
-
if (fullOpen === container) return;
|
|
2510
|
-
exitFull();
|
|
2511
|
-
if (container._rlyStopWheelZoom) container._rlyStopWheelZoom();
|
|
2512
|
-
container.classList.add('blk-full');
|
|
2513
|
-
document.body.classList.add('blk-full-open');
|
|
2514
|
-
fullOpen = container;
|
|
2515
|
-
const btn = container.querySelector('.blk-tools .tool-full');
|
|
2516
|
-
if (btn) btn.textContent = '✕';
|
|
2517
|
-
window.dispatchEvent(new Event('resize'));
|
|
2518
|
-
if (container._rlyZoom) container._rlyZoom.reapply();
|
|
2519
|
-
}
|
|
2520
|
-
|
|
2521
|
-
// CSS.escape fallback for attribute-selector building from a block id/ref.
|
|
2522
|
-
function cssEsc(s) {
|
|
2523
|
-
return window.CSS && CSS.escape ? CSS.escape(String(s)) : String(s).replace(/["\\\]]/g, '\\$&');
|
|
2524
|
-
}
|
|
2525
|
-
|
|
2526
|
-
// Open a block as a modal: full-screen its viewer if it has one (chart, image,
|
|
2527
|
-
// diagram, table, compare, code…); otherwise scroll to it and flash. `host` is
|
|
2528
|
-
// the .blk[data-block-id] wrapper. Returns true if it found something to show.
|
|
2529
|
-
function openFullEl(host) {
|
|
2530
|
-
if (!host) return false;
|
|
2531
|
-
const viewer = host.classList.contains('blk-viewer') ? host : host.querySelector('.blk-viewer');
|
|
2532
|
-
// Visuals open as a full-screen modal — context-safe (an overlay; × returns
|
|
2533
|
-
// to the exact spot). Non-modal blocks (kpi/markdown/table-less) have no
|
|
2534
|
-
// viewer, so we jump + highlight AND show a "↩ Back" button so the user can
|
|
2535
|
-
// return after the jump — no lost context across the data↔question distance.
|
|
2536
|
-
if (viewer && viewer._rlyTools) { enterFull(viewer); return true; }
|
|
2537
|
-
const fromY = window.scrollY || window.pageYOffset || 0;
|
|
2538
|
-
host.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
2539
|
-
host.classList.remove('rly-refflash');
|
|
2540
|
-
void host.offsetWidth;
|
|
2541
|
-
host.classList.add('rly-refflash');
|
|
2542
|
-
setTimeout(() => host.classList.remove('rly-refflash'), 1200);
|
|
2543
|
-
showRefBack(fromY);
|
|
2544
|
-
return true;
|
|
2545
|
-
}
|
|
2546
|
-
|
|
2547
|
-
// A floating "↩ Back" pill that returns to the pre-jump scroll position. Self-
|
|
2548
|
-
// removes once the user is back near where they started, or after a timeout.
|
|
2549
|
-
let refBackBtn = null;
|
|
2550
|
-
function showRefBack(fromY) {
|
|
2551
|
-
if (refBackBtn) refBackBtn.remove();
|
|
2552
|
-
const btn = el('button', { class: 'rly-refback', type: 'button', title: 'Back to where you were' }, '↩ Back');
|
|
2553
|
-
const cleanup = () => { btn.remove(); window.removeEventListener('scroll', onScroll); if (refBackBtn === btn) refBackBtn = null; };
|
|
2554
|
-
const onScroll = () => { if (Math.abs((window.scrollY || 0) - fromY) < 120) cleanup(); };
|
|
2555
|
-
btn.addEventListener('click', () => { window.scrollTo({ top: fromY, behavior: 'smooth' }); cleanup(); });
|
|
2556
|
-
window.addEventListener('scroll', onScroll, { passive: true });
|
|
2557
|
-
document.body.append(btn);
|
|
2558
|
-
refBackBtn = btn;
|
|
2559
|
-
setTimeout(() => { if (refBackBtn === btn) cleanup(); }, 12000);
|
|
2560
|
-
}
|
|
2561
|
-
function openFull(blockId) {
|
|
2562
|
-
return openFullEl(document.querySelector('[data-block-id="' + cssEsc(blockId) + '"]'));
|
|
2563
|
-
}
|
|
2564
|
-
|
|
2565
|
-
// Delegated handler for markdown reference links (data-rly-ref / data-rly-refid).
|
|
2566
|
-
function initRefLinks() {
|
|
2567
|
-
if (window.__relayRefLinksReady) return;
|
|
2568
|
-
window.__relayRefLinksReady = true;
|
|
2569
|
-
const open = (a) => {
|
|
2570
|
-
const host = a.dataset.rlyRefid
|
|
2571
|
-
? document.querySelector('[data-block-id="' + cssEsc(a.dataset.rlyRefid) + '"]')
|
|
2572
|
-
: document.querySelector('[data-block-ref="' + cssEsc(a.dataset.rlyRef) + '"]');
|
|
2573
|
-
if (host) openFullEl(host);
|
|
2574
|
-
else fileToast('Referenced visual not found on this board', 'err');
|
|
2575
|
-
};
|
|
2576
|
-
document.addEventListener('click', (e) => {
|
|
2577
|
-
const a = e.target.closest ? e.target.closest('a.rly-reflink') : null;
|
|
2578
|
-
if (!a) return;
|
|
2579
|
-
e.preventDefault();
|
|
2580
|
-
open(a);
|
|
2581
|
-
});
|
|
2582
|
-
document.addEventListener('keydown', (e) => {
|
|
2583
|
-
if (e.key !== 'Enter' && e.key !== ' ' && e.key !== 'Spacebar') return;
|
|
2584
|
-
const a = e.target.closest ? e.target.closest('a.rly-reflink') : null;
|
|
2585
|
-
if (!a) return;
|
|
2586
|
-
e.preventDefault();
|
|
2587
|
-
open(a);
|
|
2588
|
-
});
|
|
2589
|
-
}
|
|
2590
|
-
|
|
2591
|
-
// Drag-to-pan: grab anywhere on a scrollable visual (a tall/zoomed diagram or
|
|
2592
|
-
// oversized image) and drag to move across it, instead of hunting for the
|
|
2593
|
-
// scrollbars. Self-gates on overflow, so charts and html iframes — which are
|
|
2594
|
-
// always sized to fit — never engage. Annotation on diagrams/images is
|
|
2595
|
-
// hover-pin based (not a node click), so a pan can't create a stray
|
|
2596
|
-
// annotation; a real drag still swallows the trailing click as a guard.
|
|
2597
|
-
// Returns a refresh() the viewer calls whenever content size changes (zoom,
|
|
2598
|
-
// full-screen, re-render) so the grab affordance tracks pannability.
|
|
2599
|
-
function enablePan(scrollEl) {
|
|
2600
|
-
let pending = false, active = false;
|
|
2601
|
-
let sx = 0, sy = 0, sl = 0, st = 0, pid = null;
|
|
2602
|
-
const THRESH = 4; // px before a press becomes a drag (keeps clicks clickable)
|
|
2603
|
-
|
|
2604
|
-
const pannable = () =>
|
|
2605
|
-
scrollEl.scrollWidth - scrollEl.clientWidth > 1 ||
|
|
2606
|
-
scrollEl.scrollHeight - scrollEl.clientHeight > 1;
|
|
2607
|
-
const refresh = () => scrollEl.classList.toggle('blk-pannable', pannable());
|
|
2608
|
-
|
|
2609
|
-
scrollEl.addEventListener('pointerdown', (e) => {
|
|
2610
|
-
const panGesture = e.button === 1 || (e.button === 0 && (!scrollEl._rlyHasRegions || viewerSpacePan));
|
|
2611
|
-
if (!panGesture || scrollEl._rlyRegionMode || !pannable()) return;
|
|
2612
|
-
// leave the toolbar, the diagram editor, and real controls interactive
|
|
2613
|
-
if (e.target.closest && e.target.closest('.blk-tools, .blk-editor, button, a, input, textarea, select')) return;
|
|
2614
|
-
pending = true; active = false;
|
|
2615
|
-
sx = e.clientX; sy = e.clientY;
|
|
2616
|
-
sl = scrollEl.scrollLeft; st = scrollEl.scrollTop;
|
|
2617
|
-
pid = e.pointerId;
|
|
2618
|
-
});
|
|
2619
|
-
scrollEl.addEventListener('pointermove', (e) => {
|
|
2620
|
-
if (!pending) return;
|
|
2621
|
-
if (scrollEl._rlyRegionMode || scrollEl._rlyRegionSelecting) { pending = false; active = false; return; }
|
|
2622
|
-
const dx = e.clientX - sx, dy = e.clientY - sy;
|
|
2623
|
-
if (!active) {
|
|
2624
|
-
if (Math.abs(dx) < THRESH && Math.abs(dy) < THRESH) return;
|
|
2625
|
-
active = true;
|
|
2626
|
-
scrollEl.classList.add('blk-panning');
|
|
2627
|
-
try { scrollEl.setPointerCapture(pid); } catch (_) {}
|
|
2628
|
-
}
|
|
2629
|
-
e.preventDefault();
|
|
2630
|
-
scrollEl.scrollLeft = sl - dx;
|
|
2631
|
-
scrollEl.scrollTop = st - dy;
|
|
2632
|
-
});
|
|
2633
|
-
const end = () => {
|
|
2634
|
-
if (active) {
|
|
2635
|
-
scrollEl.classList.remove('blk-panning');
|
|
2636
|
-
try { scrollEl.releasePointerCapture(pid); } catch (_) {}
|
|
2637
|
-
// a drag ends in a click on whatever was under the release — swallow it
|
|
2638
|
-
// once so it can't trigger anything the user didn't mean to click
|
|
2639
|
-
const swallow = (ev) => { ev.stopPropagation(); ev.preventDefault(); };
|
|
2640
|
-
scrollEl.addEventListener('click', swallow, { capture: true, once: true });
|
|
2641
|
-
setTimeout(() => scrollEl.removeEventListener('click', swallow, true), 0);
|
|
2642
|
-
}
|
|
2643
|
-
pending = false; active = false; pid = null;
|
|
2644
|
-
};
|
|
2645
|
-
scrollEl.addEventListener('pointerup', end);
|
|
2646
|
-
scrollEl.addEventListener('pointercancel', end);
|
|
2647
|
-
window.addEventListener('resize', refresh);
|
|
2648
|
-
return refresh;
|
|
2649
|
-
}
|
|
2650
|
-
|
|
2651
|
-
// Build the onComment thunk for attachViewer: opens the annotation popover
|
|
2652
|
-
// with a block-scoped target ("Whole chart/diagram/…") so a user can comment
|
|
2653
|
-
// on the visual as a whole. null when annotation is off (omits the button).
|
|
2654
|
-
function wholeBlockComment(ctx, blockId, label) {
|
|
2655
|
-
if (!ctx || !ctx.annotate || ctx.canComment === false) return null;
|
|
2656
|
-
const a = ctx.annotate;
|
|
2657
|
-
return {
|
|
2658
|
-
open: (anchorEl) =>
|
|
2659
|
-
a.openExternal({ blockId, questionId: ctx.questionId, target: { kind: 'block', label } }, anchorEl),
|
|
2660
|
-
// true once this block carries a whole-block comment
|
|
2661
|
-
active: () => a.list().some((x) => x.blockId === blockId && x.target && x.target.kind === 'block'),
|
|
2662
|
-
// fires on any annotation change; returns an unsubscribe
|
|
2663
|
-
subscribe: (fn) => (a.onBadgeRefresh ? a.onBadgeRefresh(fn) : () => {}),
|
|
2664
|
-
};
|
|
2665
|
-
}
|
|
2666
|
-
|
|
2667
|
-
// opts: { zoomEl, natural, comment, label } — zoomEl null means no pixel
|
|
2668
|
-
// zoom (charts/html/code: full-screen + comment only, no zoom buttons).
|
|
2669
|
-
// comment (optional) = { open(anchor), active(), subscribe(fn) } wiring the
|
|
2670
|
-
// "comment on the whole block" button + its already-commented style.
|
|
2671
|
-
function attachViewer(container, opts) {
|
|
2672
|
-
if (container._rlyRegionHook) {
|
|
2673
|
-
try { container._rlyRegionHook(); } catch (_) {}
|
|
2674
|
-
container._rlyRegionHook = null;
|
|
2675
|
-
}
|
|
2676
|
-
if (container._rlyTools) container._rlyTools.remove();
|
|
2677
|
-
container.classList.add('blk-viewer');
|
|
2678
|
-
const zoomable = Boolean(opts && opts.zoomEl);
|
|
2679
|
-
const label = (opts && opts.label) || 'visual';
|
|
2680
|
-
|
|
2681
|
-
// pan listeners bind once per container; mermaid re-renders re-call
|
|
2682
|
-
// attachViewer, so reuse the existing refresh() instead of re-binding
|
|
2683
|
-
if (!container._rlyPan) container._rlyPan = enablePan(container);
|
|
2684
|
-
const refreshPan = container._rlyPan;
|
|
2685
|
-
|
|
2686
|
-
// zoom level persists across re-renders; the wheel handler (bound once)
|
|
2687
|
-
// delegates through container._rlyZoom so it never holds a stale zoomEl
|
|
2688
|
-
if (container._rlyZ === undefined) container._rlyZ = null; // null = fit-to-width
|
|
2689
|
-
// Fluid visuals (currently Chart.js) fit the live container width. Capture
|
|
2690
|
-
// that rendered size only when leaving fit mode so zoom remains proportional
|
|
2691
|
-
// without freezing later fit-mode viewport growth to an old width.
|
|
2692
|
-
let fluidZoomNatural = null;
|
|
2693
|
-
const pct = el('span', { class: 'tool-pct' }, 'fit');
|
|
2694
|
-
function apply() {
|
|
2695
|
-
if (!zoomable) return;
|
|
2696
|
-
const target = opts.zoomEl;
|
|
2697
|
-
const nat = opts.natural();
|
|
2698
|
-
const z = container._rlyZ;
|
|
2699
|
-
const full = container.classList.contains('blk-full');
|
|
2700
|
-
// A per-block height caps only the compact inline preview. The moment the
|
|
2701
|
-
// user zooms in (z !== null) or goes full-screen they want pixel detail, so
|
|
2702
|
-
// lift the cap there; restore it when back to the inline fit view.
|
|
2703
|
-
if (opts.fitMaxHeight != null) {
|
|
2704
|
-
target.style.maxHeight = z === null && !full ? opts.fitMaxHeight + 'px' : 'none';
|
|
2705
|
-
}
|
|
2706
|
-
if (z === null && full && nat && nat.w && nat.h) {
|
|
2707
|
-
// Full-screen default: scale the diagram/image to fill the viewport
|
|
2708
|
-
// (contain — enlarge a small one, shrink a big one) so it's readable at
|
|
2709
|
-
// a glance without reaching for the zoom buttons. CSS margin:auto centers
|
|
2710
|
-
// it; it stays pannable once the user zooms past this fit.
|
|
2711
|
-
// subtract the docked comment rail (≥980px) so the fit doesn't run under it
|
|
2712
|
-
const railInset = (document.body.classList.contains('ann-rail-open') && window.innerWidth >= 980) ? 340 : 0;
|
|
2713
|
-
const availW = window.innerWidth - railInset - FULL_PAD_X * 2;
|
|
2714
|
-
const availH = window.innerHeight - FULL_PAD_TOP - FULL_PAD_BOTTOM;
|
|
2715
|
-
const scale = Math.min(availW / nat.w, availH / nat.h);
|
|
2716
|
-
target.style.maxWidth = 'none';
|
|
2717
|
-
target.style.width = Math.max(1, Math.round(nat.w * scale)) + 'px';
|
|
2718
|
-
target.style.height = opts.scaleHeight ? Math.max(1, Math.round(nat.h * scale)) + 'px' : 'auto';
|
|
2719
|
-
pct.textContent = 'fit';
|
|
2720
|
-
} else if (z === null || !nat || !nat.w) {
|
|
2721
|
-
target.style.width = '100%';
|
|
2722
|
-
target.style.maxWidth = opts.fluidFit ? '100%' : (nat && nat.w ? Math.ceil(nat.w) + 'px' : '100%');
|
|
2723
|
-
target.style.height = opts.scaleHeight ? '100%' : 'auto';
|
|
2724
|
-
pct.textContent = 'fit';
|
|
2725
|
-
} else {
|
|
2726
|
-
const zoomNat = fluidZoomNatural || nat;
|
|
2727
|
-
target.style.maxWidth = 'none';
|
|
2728
|
-
target.style.width = Math.round(zoomNat.w * z) + 'px';
|
|
2729
|
-
target.style.height = opts.scaleHeight && zoomNat && zoomNat.h ? Math.round(zoomNat.h * z) + 'px' : 'auto';
|
|
2730
|
-
pct.textContent = Math.round(z * 100) + '%';
|
|
2731
|
-
}
|
|
2732
|
-
window.dispatchEvent(new Event('resize')); // annotation badges reposition
|
|
2733
|
-
refreshPan(); // content size → grab affordance
|
|
2734
|
-
}
|
|
2735
|
-
function currentZ() {
|
|
2736
|
-
if (container._rlyZ !== null) return container._rlyZ;
|
|
2737
|
-
if (opts.fluidFit) return 1;
|
|
2738
|
-
const nat = opts.natural();
|
|
2739
|
-
if (!nat || !nat.w) return 1;
|
|
2740
|
-
const shown = opts.zoomEl.getBoundingClientRect().width;
|
|
2741
|
-
return shown > 0 ? shown / nat.w : 1;
|
|
2742
|
-
}
|
|
2743
|
-
function setZoom(next) {
|
|
2744
|
-
if (next === null) {
|
|
2745
|
-
fluidZoomNatural = null;
|
|
2746
|
-
} else if (opts.fluidFit && container._rlyZ === null) {
|
|
2747
|
-
const shown = opts.zoomEl.getBoundingClientRect();
|
|
2748
|
-
fluidZoomNatural = {
|
|
2749
|
-
w: Math.max(1, shown.width),
|
|
2750
|
-
h: Math.max(1, shown.height),
|
|
2751
|
-
};
|
|
2752
|
-
}
|
|
2753
|
-
container._rlyZ = next === null ? null : Math.min(8, Math.max(0.2, next));
|
|
2754
|
-
apply();
|
|
2755
|
-
}
|
|
2756
|
-
container._rlyZoom = { setZoom, currentZ, reapply: apply };
|
|
2757
|
-
|
|
2758
|
-
// Stop any in-flight wheel easing before an explicit toolbar/full-screen
|
|
2759
|
-
// action. This prevents an older gesture target from overriding that action
|
|
2760
|
-
// on the next animation frame.
|
|
2761
|
-
if (!container._rlyStopWheelZoom) {
|
|
2762
|
-
container._rlyStopWheelZoom = () => {
|
|
2763
|
-
if (container._rlyWheelFrame) cancelAnimationFrame(container._rlyWheelFrame);
|
|
2764
|
-
container._rlyWheelFrame = null;
|
|
2765
|
-
container._rlyWheelTarget = null;
|
|
2766
|
-
};
|
|
2767
|
-
}
|
|
2768
|
-
|
|
2769
|
-
const tools = el('div', { class: 'blk-tools' });
|
|
2770
|
-
|
|
2771
|
-
// comment on the whole block (leftmost) — opens the annotation popover with
|
|
2772
|
-
// a block-scoped target so a user can comment without picking an element.
|
|
2773
|
-
// The button gains a .has-comment style once the block carries one, kept in
|
|
2774
|
-
// sync via the annotate badge-refresh subscription (bound once per container).
|
|
2775
|
-
if (opts && opts.comment) {
|
|
2776
|
-
const cmt = opts.comment;
|
|
2777
|
-
const cBtn = el('button', { class: 'tool-comment', type: 'button', title: 'Comment on this whole ' + label });
|
|
2778
|
-
cBtn.innerHTML = ICON_COMMENT;
|
|
2779
|
-
cBtn.addEventListener('click', (e) => { e.stopPropagation(); cmt.open(container); });
|
|
2780
|
-
tools.append(cBtn);
|
|
2781
|
-
container._rlyCmtSync = () => {
|
|
2782
|
-
const b = container._rlyTools && container._rlyTools.querySelector('.tool-comment');
|
|
2783
|
-
if (b && cmt.active) b.classList.toggle('has-comment', !!cmt.active());
|
|
2784
|
-
};
|
|
2785
|
-
if (!container._rlyCmtHook && cmt.subscribe) {
|
|
2786
|
-
container._rlyCmtHook = cmt.subscribe(() => container._rlyCmtSync && container._rlyCmtSync());
|
|
2787
|
-
}
|
|
2788
|
-
}
|
|
2789
|
-
|
|
2790
|
-
if (opts && opts.comment && opts.hoverComments) {
|
|
2791
|
-
const hoverCtl = opts.hoverComments;
|
|
2792
|
-
const hoverBtn = el('button', {
|
|
2793
|
-
class: 'tool-hover-comments',
|
|
2794
|
-
type: 'button',
|
|
2795
|
-
'aria-label': 'Show element comment overlays',
|
|
2796
|
-
});
|
|
2797
|
-
hoverBtn.innerHTML = ICON_EYE;
|
|
2798
|
-
hoverBtn.append(el('span', { class: 'tool-hover-label' }, 'Hover comments'));
|
|
2799
|
-
const syncHoverMode = () => {
|
|
2800
|
-
const enabled = hoverCtl.isEnabled();
|
|
2801
|
-
hoverBtn.classList.toggle('is-active', enabled);
|
|
2802
|
-
hoverBtn.setAttribute('aria-pressed', String(enabled));
|
|
2803
|
-
hoverBtn.title = enabled ? 'Hide element comment overlays' : 'Show element comment overlays';
|
|
2804
|
-
};
|
|
2805
|
-
hoverBtn.addEventListener('click', (e) => {
|
|
2806
|
-
e.stopPropagation();
|
|
2807
|
-
hoverCtl.setEnabled(!hoverCtl.isEnabled());
|
|
2808
|
-
syncHoverMode();
|
|
2809
|
-
});
|
|
2810
|
-
syncHoverMode();
|
|
2811
|
-
tools.append(hoverBtn);
|
|
2812
|
-
}
|
|
2813
|
-
|
|
2814
|
-
if (opts && opts.region) {
|
|
2815
|
-
const regionCtl = opts.region;
|
|
2816
|
-
const regionLabel = el('span', { class: 'tool-region-label' }, 'Area');
|
|
2817
|
-
const regionBtn = el('button', {
|
|
2818
|
-
class: 'tool-region',
|
|
2819
|
-
type: 'button',
|
|
2820
|
-
title: 'Draw an area comment',
|
|
2821
|
-
'aria-label': 'Draw an area comment',
|
|
2822
|
-
'aria-pressed': 'false',
|
|
2823
|
-
});
|
|
2824
|
-
regionBtn.innerHTML = ICON_REGION;
|
|
2825
|
-
regionBtn.append(regionLabel);
|
|
2826
|
-
const syncRegionMode = (enabled) => {
|
|
2827
|
-
regionBtn.classList.toggle('is-active', enabled);
|
|
2828
|
-
regionBtn.setAttribute('aria-pressed', enabled ? 'true' : 'false');
|
|
2829
|
-
regionBtn.title = enabled ? 'Cancel area comment' : 'Draw an area comment';
|
|
2830
|
-
regionBtn.setAttribute('aria-label', regionBtn.title);
|
|
2831
|
-
regionLabel.textContent = enabled ? 'Drawing' : 'Area';
|
|
2832
|
-
};
|
|
2833
|
-
regionBtn.addEventListener('click', (e) => {
|
|
2834
|
-
e.stopPropagation();
|
|
2835
|
-
regionCtl.setModeActive(!regionCtl.isModeActive());
|
|
2836
|
-
});
|
|
2837
|
-
container._rlyRegionHook = regionCtl.onModeChange(syncRegionMode);
|
|
2838
|
-
syncRegionMode(regionCtl.isModeActive());
|
|
2839
|
-
tools.append(regionBtn);
|
|
2840
|
-
}
|
|
2841
|
-
|
|
2842
|
-
if (zoomable) {
|
|
2843
|
-
// cmd/ctrl+wheel zoom, bound ONCE (re-binding per render would stack);
|
|
2844
|
-
// delegates to the current controller so it never uses a stale zoomEl
|
|
2845
|
-
if (!container._rlyWheel) {
|
|
2846
|
-
const onWheel = (e) => {
|
|
2847
|
-
if (!(e.ctrlKey || e.metaKey) || !container._rlyZoom) return;
|
|
2848
|
-
e.preventDefault();
|
|
2849
|
-
// Normalize line/page-mode devices to pixel-like units, then cap a
|
|
2850
|
-
// single event. Exponential scaling makes equal motion reversible and
|
|
2851
|
-
// lets tiny trackpad deltas stay tiny instead of becoming fixed jumps.
|
|
2852
|
-
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? window.innerHeight : 1;
|
|
2853
|
-
const delta = Math.max(-WHEEL_ZOOM_MAX_DELTA, Math.min(WHEEL_ZOOM_MAX_DELTA, e.deltaY * unit));
|
|
2854
|
-
const base = Number.isFinite(container._rlyWheelTarget)
|
|
2855
|
-
? container._rlyWheelTarget
|
|
2856
|
-
: container._rlyZoom.currentZ();
|
|
2857
|
-
container._rlyWheelTarget = Math.min(8, Math.max(0.2, base * Math.exp(-delta * WHEEL_ZOOM_SENSITIVITY)));
|
|
2858
|
-
|
|
2859
|
-
// Respect reduced-motion while retaining the gentler delta-based step.
|
|
2860
|
-
if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
|
2861
|
-
container._rlyZoom.setZoom(container._rlyWheelTarget);
|
|
2862
|
-
container._rlyWheelTarget = null;
|
|
2863
|
-
return;
|
|
2864
|
-
}
|
|
2865
|
-
if (container._rlyWheelFrame) return; // coalesce bursty input to one rAF loop
|
|
2866
|
-
const tick = () => {
|
|
2867
|
-
const zoom = container._rlyZoom;
|
|
2868
|
-
const target = container._rlyWheelTarget;
|
|
2869
|
-
if (!zoom || !Number.isFinite(target)) {
|
|
2870
|
-
container._rlyWheelFrame = null;
|
|
2871
|
-
return;
|
|
2872
|
-
}
|
|
2873
|
-
const current = zoom.currentZ();
|
|
2874
|
-
const gap = target - current;
|
|
2875
|
-
if (Math.abs(gap) <= WHEEL_ZOOM_EPSILON) {
|
|
2876
|
-
zoom.setZoom(target);
|
|
2877
|
-
container._rlyWheelFrame = null;
|
|
2878
|
-
container._rlyWheelTarget = null;
|
|
2879
|
-
return;
|
|
2880
|
-
}
|
|
2881
|
-
zoom.setZoom(current + gap * WHEEL_ZOOM_EASE);
|
|
2882
|
-
container._rlyWheelFrame = requestAnimationFrame(tick);
|
|
2883
|
-
};
|
|
2884
|
-
container._rlyWheelFrame = requestAnimationFrame(tick);
|
|
2885
|
-
};
|
|
2886
|
-
container.addEventListener('wheel', onWheel, { passive: false });
|
|
2887
|
-
container._rlyWheel = onWheel;
|
|
2888
|
-
}
|
|
2889
|
-
const zoomOut = el('button', { class: 'tool-zoom', type: 'button', title: 'Zoom out' }, '−');
|
|
2890
|
-
const zoomIn = el('button', { class: 'tool-zoom', type: 'button', title: 'Zoom in' }, '+');
|
|
2891
|
-
zoomOut.addEventListener('click', (e) => { e.stopPropagation(); container._rlyStopWheelZoom(); setZoom(currentZ() / 1.2); });
|
|
2892
|
-
zoomIn.addEventListener('click', (e) => { e.stopPropagation(); container._rlyStopWheelZoom(); setZoom(currentZ() * 1.2); });
|
|
2893
|
-
pct.classList.add('is-btn');
|
|
2894
|
-
pct.title = 'Reset to fit';
|
|
2895
|
-
pct.addEventListener('click', (e) => { e.stopPropagation(); container._rlyStopWheelZoom(); setZoom(null); });
|
|
2896
|
-
tools.append(zoomOut, pct, zoomIn);
|
|
2897
|
-
}
|
|
2898
|
-
|
|
2899
|
-
const fullBtn = el('button', { class: 'tool-full', type: 'button', title: 'Full screen (Esc closes; ⌘/Ctrl+wheel zooms)' });
|
|
2900
|
-
fullBtn.innerHTML = ICON_EXPAND;
|
|
2901
|
-
fullBtn.addEventListener('click', (e) => {
|
|
2902
|
-
e.stopPropagation();
|
|
2903
|
-
if (fullOpen === container) exitFull();
|
|
2904
|
-
else enterFull(container);
|
|
2905
|
-
});
|
|
2906
|
-
tools.append(fullBtn);
|
|
2907
|
-
|
|
2908
|
-
container.prepend(tools);
|
|
2909
|
-
container._rlyTools = tools;
|
|
2910
|
-
if (zoomable) apply();
|
|
2911
|
-
// non-zoomable diagrams (tall mermaid, oversized image) can still overflow
|
|
2912
|
-
refreshPan();
|
|
2913
|
-
if (container._rlyCmtSync) container._rlyCmtSync(); // reflect existing comment
|
|
2914
|
-
}
|
|
2915
|
-
|
|
2916
|
-
function svgNatural(svgEl) {
|
|
2917
|
-
return () => {
|
|
2918
|
-
const vb = svgEl.viewBox && svgEl.viewBox.baseVal;
|
|
2919
|
-
return vb && vb.width > 0 ? { w: vb.width, h: vb.height } : null;
|
|
2920
|
-
};
|
|
2921
|
-
}
|
|
2922
|
-
|
|
2923
|
-
// ---------- html (sandboxed iframe) ----------
|
|
2924
|
-
function syncHtmlHoverComments(frame) {
|
|
2925
|
-
try {
|
|
2926
|
-
frame.contentWindow.postMessage({ relay: 'annotate-hover', enabled: frame.dataset.relayHoverComments !== 'off' }, '*');
|
|
2927
|
-
} catch (_) {}
|
|
2928
|
-
}
|
|
2929
|
-
|
|
2930
|
-
// The kit can load after the iframe's load event; its ready message also
|
|
2931
|
-
// restores the current toggle when the embedded page reloads.
|
|
2932
|
-
window.addEventListener('message', (e) => {
|
|
2933
|
-
if (!e.data || e.data.relay !== 'annotate-ready') return;
|
|
2934
|
-
for (const frame of document.querySelectorAll('iframe.viz[data-relay-hover-comments]')) {
|
|
2935
|
-
if (frame.contentWindow === e.source) { syncHtmlHoverComments(frame); break; }
|
|
2936
|
-
}
|
|
2937
|
-
});
|
|
2938
|
-
|
|
2939
|
-
function renderHtml(block, ctx, blockId) {
|
|
2940
|
-
const height = clampHeight(block.height, 360);
|
|
2941
|
-
const iframe = el('iframe', {
|
|
2942
|
-
class: 'viz',
|
|
2943
|
-
'data-block-id': blockId,
|
|
2944
|
-
'data-question-id': ctx.questionId || '',
|
|
2945
|
-
'data-relay-hover-comments': 'on',
|
|
2946
|
-
src: ctx.htmlSrc(blockId),
|
|
2947
|
-
height: String(height),
|
|
2948
|
-
sandbox: 'allow-scripts allow-forms allow-popups allow-modals',
|
|
2949
|
-
loading: 'lazy',
|
|
2950
|
-
});
|
|
2951
|
-
iframe.addEventListener('load', () => syncHtmlHoverComments(iframe));
|
|
2952
|
-
const wrap = el('div', { class: 'blk-htmlwrap' }, iframe);
|
|
2953
|
-
attachViewer(wrap, {
|
|
2954
|
-
zoomEl: null,
|
|
2955
|
-
label: 'embed',
|
|
2956
|
-
comment: wholeBlockComment(ctx, blockId, 'embed'),
|
|
2957
|
-
hoverComments: {
|
|
2958
|
-
isEnabled: () => iframe.dataset.relayHoverComments !== 'off',
|
|
2959
|
-
setEnabled: (enabled) => {
|
|
2960
|
-
iframe.dataset.relayHoverComments = enabled ? 'on' : 'off';
|
|
2961
|
-
syncHtmlHoverComments(iframe);
|
|
2962
|
-
},
|
|
2963
|
-
},
|
|
2964
|
-
});
|
|
2965
|
-
return wrap;
|
|
2966
|
-
}
|
|
2967
|
-
|
|
2968
|
-
// ---------- dispatch ----------
|
|
2969
|
-
function renderBlock(block, ctx) {
|
|
2970
|
-
const blockId = block.id;
|
|
2971
|
-
const wrapper = el('div', { class: 'blk blk-' + block.type, 'data-block-id': blockId });
|
|
2972
|
-
if (block.ref) wrapper.setAttribute('data-block-ref', block.ref);
|
|
2973
|
-
let inner = null;
|
|
2974
|
-
switch (block.type) {
|
|
2975
|
-
case 'markdown': {
|
|
2976
|
-
inner = renderMarkdown(block.md || '');
|
|
2977
|
-
wrapper.append(inner);
|
|
2978
|
-
ctx.annotate?.enableTextSelection(inner, { blockId, questionId: ctx.questionId });
|
|
2979
|
-
break;
|
|
2980
|
-
}
|
|
2981
|
-
case 'table':
|
|
2982
|
-
inner = renderTable(block, ctx, blockId);
|
|
2983
|
-
wrapper.append(inner);
|
|
2984
|
-
break;
|
|
2985
|
-
case 'code':
|
|
2986
|
-
inner = renderCode(block, ctx, blockId);
|
|
2987
|
-
wrapper.append(inner);
|
|
2988
|
-
break;
|
|
2989
|
-
case 'diff':
|
|
2990
|
-
inner = renderDiff(block, ctx, blockId);
|
|
2991
|
-
wrapper.append(inner);
|
|
2992
|
-
break;
|
|
2993
|
-
case 'git-conflict':
|
|
2994
|
-
inner = renderGitConflict(block, ctx, blockId);
|
|
2995
|
-
wrapper.append(inner);
|
|
2996
|
-
break;
|
|
2997
|
-
case 'video':
|
|
2998
|
-
inner = renderVideo(block, ctx, blockId);
|
|
2999
|
-
wrapper.append(inner);
|
|
3000
|
-
break;
|
|
3001
|
-
case 'pdf':
|
|
3002
|
-
inner = renderPdf(block, ctx, blockId);
|
|
3003
|
-
wrapper.append(inner);
|
|
3004
|
-
break;
|
|
3005
|
-
case 'chart':
|
|
3006
|
-
inner = renderChart(block, ctx, blockId);
|
|
3007
|
-
wrapper.append(inner);
|
|
3008
|
-
break;
|
|
3009
|
-
case 'mermaid':
|
|
3010
|
-
inner = renderMermaid(block, ctx, blockId);
|
|
3011
|
-
wrapper.append(inner);
|
|
3012
|
-
break;
|
|
3013
|
-
case 'graphviz':
|
|
3014
|
-
inner = renderGraphviz(block, ctx, blockId);
|
|
3015
|
-
wrapper.append(inner);
|
|
3016
|
-
break;
|
|
3017
|
-
case 'plantuml':
|
|
3018
|
-
inner = renderPlantuml(block, ctx, blockId);
|
|
3019
|
-
wrapper.append(inner);
|
|
3020
|
-
break;
|
|
3021
|
-
case 'html':
|
|
3022
|
-
inner = renderHtml(block, ctx, blockId);
|
|
3023
|
-
wrapper.append(inner);
|
|
3024
|
-
break;
|
|
3025
|
-
case 'image':
|
|
3026
|
-
inner = renderImage(block, ctx, blockId);
|
|
3027
|
-
wrapper.append(inner);
|
|
3028
|
-
break;
|
|
3029
|
-
case 'palette':
|
|
3030
|
-
inner = renderPalette(block, ctx, blockId);
|
|
3031
|
-
wrapper.append(inner);
|
|
3032
|
-
break;
|
|
3033
|
-
case 'kpi':
|
|
3034
|
-
inner = renderKpi(block, ctx, blockId);
|
|
3035
|
-
wrapper.append(inner);
|
|
3036
|
-
break;
|
|
3037
|
-
case 'typography':
|
|
3038
|
-
inner = renderTypography(block, ctx, blockId);
|
|
3039
|
-
wrapper.append(inner);
|
|
3040
|
-
break;
|
|
3041
|
-
case 'compare':
|
|
3042
|
-
inner = renderCompare(block, ctx, blockId);
|
|
3043
|
-
wrapper.append(inner);
|
|
3044
|
-
break;
|
|
3045
|
-
case 'a2ui':
|
|
3046
|
-
inner = window.RelayA2ui ? window.RelayA2ui.render(block, ctx, blockId) : el('div', { class: 'blk-error' }, 'A2UI renderer is not loaded.');
|
|
3047
|
-
wrapper.append(inner);
|
|
3048
|
-
break;
|
|
3049
|
-
default:
|
|
3050
|
-
wrapper.append(el('div', { class: 'blk-error' }, 'Unknown block type: ' + esc(String(block.type))));
|
|
3051
|
-
}
|
|
3052
|
-
return wrapper;
|
|
3053
|
-
}
|
|
3054
|
-
|
|
3055
|
-
// ---------- public API ----------
|
|
3056
|
-
async function render(container, blocks, ctx) {
|
|
3057
|
-
const list = Array.isArray(blocks) ? blocks : [];
|
|
3058
|
-
const safeCtx = {
|
|
3059
|
-
theme: ctx && ctx.theme ? ctx.theme : () => 'light',
|
|
3060
|
-
htmlSrc: ctx && ctx.htmlSrc ? ctx.htmlSrc : (id) => '/html/b/' + id,
|
|
3061
|
-
questionId: ctx && ctx.questionId !== undefined ? ctx.questionId : null,
|
|
3062
|
-
annotate: ctx && ctx.annotate ? ctx.annotate : null,
|
|
3063
|
-
// editable-mermaid plumbing: edits maps blockId -> edited code; onBlockEdit
|
|
3064
|
-
// reports an accepted change (or null to clear back to the original).
|
|
3065
|
-
edits: ctx && ctx.edits ? ctx.edits : {},
|
|
3066
|
-
canComment: !ctx || ctx.canComment !== false,
|
|
3067
|
-
saveArtifact:
|
|
3068
|
-
ctx && typeof ctx.saveArtifact === 'function' ? ctx.saveArtifact : null,
|
|
3069
|
-
canEditBlocks: !ctx || ctx.canEditBlocks !== false,
|
|
3070
|
-
onBlockEdit:
|
|
3071
|
-
ctx && typeof ctx.onBlockEdit === 'function' ? ctx.onBlockEdit : () => {},
|
|
3072
|
-
};
|
|
3073
|
-
for (const block of list) {
|
|
3074
|
-
if (!block || !block.type) continue;
|
|
3075
|
-
container.append(renderBlock(block, safeCtx));
|
|
3076
|
-
}
|
|
3077
|
-
}
|
|
3078
|
-
|
|
3079
|
-
// ---------- file-link open behavior ----------
|
|
3080
|
-
let fileDialog = null;
|
|
3081
|
-
const fileAuthHeaders = () => {
|
|
3082
|
-
const token = new URLSearchParams(location.search).get('token');
|
|
3083
|
-
return token ? { 'x-relay-share-token': token } : {};
|
|
3084
|
-
};
|
|
3085
|
-
|
|
3086
|
-
async function previewFilePath(a) {
|
|
3087
|
-
const p = a.dataset.rlyOpen;
|
|
3088
|
-
if (!p) return;
|
|
3089
|
-
if (fileDialog) fileDialog.close();
|
|
3090
|
-
const dialog = el('dialog', { class: 'rly-file-dialog', 'aria-label': 'File preview' });
|
|
3091
|
-
const title = el('h2', {}, p.split(/[\\/]/).pop());
|
|
3092
|
-
const pathLabel = el('div', { class: 'rly-file-location', title: p }, p);
|
|
3093
|
-
const close = el('button', { type: 'button', class: 'btn', autofocus: '', 'aria-label': 'Close file preview' }, 'Close');
|
|
3094
|
-
const open = el('button', { type: 'button', class: 'btn' }, 'Open in app');
|
|
3095
|
-
open.dataset.rlyOpen = p;
|
|
3096
|
-
open.addEventListener('click', () => openFilePath(open));
|
|
3097
|
-
const actions = el('div', { class: 'rly-file-actions' }, open, close);
|
|
3098
|
-
const body = el('div', { class: 'rly-file-body', tabindex: '0', 'aria-busy': 'true' });
|
|
3099
|
-
const status = el('p', { role: 'status' }, 'Loading preview…');
|
|
3100
|
-
body.append(status);
|
|
3101
|
-
dialog.append(el('header', { class: 'rly-file-header' }, el('div', { class: 'rly-file-heading' }, title, pathLabel), actions), body);
|
|
3102
|
-
const controller = new AbortController();
|
|
3103
|
-
const previousFocus = document.activeElement;
|
|
3104
|
-
close.addEventListener('click', () => dialog.close());
|
|
3105
|
-
dialog.addEventListener('close', () => {
|
|
3106
|
-
controller.abort();
|
|
3107
|
-
dialog.querySelectorAll('video,audio').forEach((media) => { media.pause(); media.removeAttribute('src'); media.load(); });
|
|
3108
|
-
dialog.remove();
|
|
3109
|
-
if (fileDialog === dialog) fileDialog = null;
|
|
3110
|
-
if (previousFocus && previousFocus.isConnected) previousFocus.focus({ preventScroll: true });
|
|
3111
|
-
});
|
|
3112
|
-
document.body.append(dialog);
|
|
3113
|
-
fileDialog = dialog;
|
|
3114
|
-
dialog.showModal();
|
|
3115
|
-
try {
|
|
3116
|
-
const response = await fetch('/api/file-preview', {
|
|
3117
|
-
method: 'POST', headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
|
|
3118
|
-
body: JSON.stringify({ path: p }), signal: controller.signal,
|
|
3119
|
-
});
|
|
3120
|
-
let data;
|
|
3121
|
-
try { data = await response.json(); }
|
|
3122
|
-
catch { throw new Error('File previews need a current Relay browser board. Reconnect this board with the updated CLI.'); }
|
|
3123
|
-
if (!response.ok || !data.ok) {
|
|
3124
|
-
if (response.status === 403) open.disabled = true;
|
|
3125
|
-
throw new Error(data.error || 'Preview unavailable. Reconnect this board with the updated CLI.');
|
|
3126
|
-
}
|
|
3127
|
-
if (!dialog.open) return;
|
|
3128
|
-
title.textContent = data.name;
|
|
3129
|
-
dialog.setAttribute('aria-label', 'File preview: ' + data.name);
|
|
3130
|
-
body.replaceChildren();
|
|
3131
|
-
const source = () => {
|
|
3132
|
-
body.replaceChildren();
|
|
3133
|
-
const lines = String(data.text || '').replace(/\r\n?/g, '\n').replace(/\n$/, '').split('\n');
|
|
3134
|
-
const list = el('div', { class: 'rly-file-source' });
|
|
3135
|
-
lines.forEach((line, i) => {
|
|
3136
|
-
const number = i + 1;
|
|
3137
|
-
const code = el('code');
|
|
3138
|
-
code.innerHTML = tintCode(line, data.lang) || ' ';
|
|
3139
|
-
const row = el('div', { class: 'rly-file-line', 'data-line': String(number) },
|
|
3140
|
-
el('span', { class: 'rly-file-line-number', 'aria-hidden': 'true' }, String(number)), code);
|
|
3141
|
-
if (data.line && number >= data.line && number <= data.endLine) row.classList.add('is-target');
|
|
3142
|
-
list.append(row);
|
|
3143
|
-
});
|
|
3144
|
-
if (data.line > lines.length) body.append(el('p', { role: 'status' }, 'Line ' + data.line + ' is beyond this file’s ' + lines.length + ' lines.'));
|
|
3145
|
-
body.append(list);
|
|
3146
|
-
requestAnimationFrame(() => {
|
|
3147
|
-
const target = list.querySelector('.is-target');
|
|
3148
|
-
if (!target || !dialog.open) return;
|
|
3149
|
-
body.scrollTop += target.getBoundingClientRect().top - body.getBoundingClientRect().top - body.clientHeight / 2 + target.clientHeight / 2;
|
|
3150
|
-
body.scrollLeft = 0;
|
|
3151
|
-
});
|
|
3152
|
-
};
|
|
3153
|
-
const rendered = () => {
|
|
3154
|
-
body.replaceChildren();
|
|
3155
|
-
if (data.kind === 'markdown') {
|
|
3156
|
-
const md = el('div', { class: 'blk-markdown' });
|
|
3157
|
-
md.append(renderMarkdown(data.text));
|
|
3158
|
-
body.append(md);
|
|
3159
|
-
} else if (data.kind === 'table') {
|
|
3160
|
-
body.append(renderTable(data.block, { canComment: false }, 'file-preview'));
|
|
3161
|
-
} else if (data.kind === 'html') {
|
|
3162
|
-
// Empty sandbox prevents scripts, forms and same-origin access. CSP
|
|
3163
|
-
// also prevents authored markup from fetching local or remote URLs.
|
|
3164
|
-
const frame = el('iframe', { class: 'rly-file-frame', title: data.name, sandbox: '', referrerpolicy: 'no-referrer' });
|
|
3165
|
-
frame.srcdoc = '<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:">' + data.text;
|
|
3166
|
-
body.append(frame);
|
|
3167
|
-
}
|
|
3168
|
-
};
|
|
3169
|
-
if (['markdown', 'html', 'table'].includes(data.kind)) {
|
|
3170
|
-
let viewingSource = !!data.line;
|
|
3171
|
-
const toggle = el('button', { type: 'button', class: 'btn' }, viewingSource ? 'Preview' : 'Source');
|
|
3172
|
-
toggle.addEventListener('click', () => {
|
|
3173
|
-
viewingSource = !viewingSource;
|
|
3174
|
-
toggle.textContent = viewingSource ? 'Preview' : 'Source';
|
|
3175
|
-
viewingSource ? source() : rendered();
|
|
3176
|
-
});
|
|
3177
|
-
actions.prepend(toggle);
|
|
3178
|
-
viewingSource ? source() : rendered();
|
|
3179
|
-
} else if (data.kind === 'code') source();
|
|
3180
|
-
else if (data.kind === 'unsupported') body.append(el('p', { role: 'status' }, data.reason));
|
|
3181
|
-
else {
|
|
3182
|
-
const params = new URLSearchParams({ path: p });
|
|
3183
|
-
const token = new URLSearchParams(location.search).get('token');
|
|
3184
|
-
if (token) params.set('token', token);
|
|
3185
|
-
const url = '/api/file-content?' + params;
|
|
3186
|
-
const tag = { image: 'img', pdf: 'iframe', video: 'video', audio: 'audio' }[data.kind];
|
|
3187
|
-
if (!tag) throw new Error('This file type cannot be previewed.');
|
|
3188
|
-
const media = el(tag, { class: 'rly-file-media rly-file-' + data.kind, src: url, title: data.name });
|
|
3189
|
-
if (tag === 'img') media.alt = data.name;
|
|
3190
|
-
if (tag === 'video' || tag === 'audio') { media.controls = true; media.preload = 'metadata'; }
|
|
3191
|
-
media.addEventListener('error', () => body.append(el('p', { role: 'status' }, 'Your browser could not display this file. Use Open in app.')), { once: true });
|
|
3192
|
-
body.append(media);
|
|
3193
|
-
}
|
|
3194
|
-
} catch (err) {
|
|
3195
|
-
if (err.name !== 'AbortError' && dialog.open) body.replaceChildren(el('p', { role: 'alert' }, err.message || 'Could not reach the board server.'));
|
|
3196
|
-
} finally { body.setAttribute('aria-busy', 'false'); }
|
|
3197
|
-
}
|
|
3198
|
-
|
|
3199
|
-
// A small toast pinned top-center (reuses the .toast style from style.css).
|
|
3200
|
-
// tone 'err' adds .toast-err so failures read as a problem, not a success.
|
|
3201
|
-
function fileToast(message, tone) {
|
|
3202
|
-
const t = el('div', { class: 'toast' + (tone === 'err' ? ' toast-err' : '') }, message);
|
|
3203
|
-
document.body.append(t);
|
|
3204
|
-
setTimeout(() => t.remove(), 3500);
|
|
3205
|
-
}
|
|
3206
|
-
|
|
3207
|
-
// POST the clicked path to /api/open; the server opens it in the OS default
|
|
3208
|
-
// app. The link is disabled mid-flight so a double-click can't double-open.
|
|
3209
|
-
async function openFilePath(a) {
|
|
3210
|
-
const p = a.dataset.rlyOpen;
|
|
3211
|
-
if (!p || a.classList.contains('is-opening')) return;
|
|
3212
|
-
a.classList.add('is-opening');
|
|
3213
|
-
try {
|
|
3214
|
-
const r = await fetch('/api/open', {
|
|
3215
|
-
method: 'POST',
|
|
3216
|
-
headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
|
|
3217
|
-
body: JSON.stringify({ path: p }),
|
|
3218
|
-
});
|
|
3219
|
-
let data = {};
|
|
3220
|
-
try {
|
|
3221
|
-
data = await r.json();
|
|
3222
|
-
} catch {
|
|
3223
|
-
data = {};
|
|
3224
|
-
}
|
|
3225
|
-
if (r.ok && data.ok) fileToast('Opened ' + (data.name || p));
|
|
3226
|
-
else fileToast((data.error || 'Could not open') + ' — ' + p, 'err');
|
|
3227
|
-
} catch {
|
|
3228
|
-
fileToast('Could not reach the server to open ' + p, 'err');
|
|
3229
|
-
} finally {
|
|
3230
|
-
a.classList.remove('is-opening');
|
|
3231
|
-
}
|
|
3232
|
-
}
|
|
3233
|
-
|
|
3234
|
-
// Delegated once on the document so it catches file-links anywhere they are
|
|
3235
|
-
// rendered — the intro, any markdown block, or a markdown pipe-table cell.
|
|
3236
|
-
// Keyboard-activatable (Enter/Space) since the links are role="link" anchors
|
|
3237
|
-
// with no href (the open happens via fetch, not navigation).
|
|
3238
|
-
function initFileLinks() {
|
|
3239
|
-
if (window.__relayFileLinksReady) return;
|
|
3240
|
-
window.__relayFileLinksReady = true;
|
|
3241
|
-
const hit = (e) => (e.target.closest ? e.target.closest('a.rly-filelink') : null);
|
|
3242
|
-
document.addEventListener('click', (e) => {
|
|
3243
|
-
const a = hit(e);
|
|
3244
|
-
if (!a) return;
|
|
3245
|
-
e.preventDefault();
|
|
3246
|
-
previewFilePath(a);
|
|
3247
|
-
});
|
|
3248
|
-
document.addEventListener('keydown', (e) => {
|
|
3249
|
-
if (e.key !== 'Enter' && e.key !== ' ' && e.key !== 'Spacebar') return;
|
|
3250
|
-
const a = hit(e);
|
|
3251
|
-
if (!a) return;
|
|
3252
|
-
e.preventDefault();
|
|
3253
|
-
previewFilePath(a);
|
|
3254
|
-
});
|
|
3255
|
-
}
|
|
3256
|
-
initFileLinks();
|
|
3257
|
-
initRefLinks();
|
|
3258
|
-
|
|
3259
|
-
window.RelayBlocks = { render, onThemeChange, renderMarkdown, openFull };
|
|
3260
|
-
})();
|