@khanglvm/relay 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +4 -4
  3. package/src/cli/args.js +46 -0
  4. package/src/cli/ask.js +12 -0
  5. package/src/cli/boards.js +326 -0
  6. package/src/cli/config.js +56 -0
  7. package/src/cli/context.js +13 -0
  8. package/src/cli/git.js +183 -0
  9. package/src/cli/help.js +90 -0
  10. package/src/cli/index.js +103 -0
  11. package/src/cli/install.js +197 -0
  12. package/src/cli/io.js +186 -0
  13. package/src/cli/mcp.js +94 -0
  14. package/src/cli/share.js +45 -0
  15. package/src/cli/skill.js +192 -0
  16. package/src/cli/upgrade.js +130 -0
  17. package/src/cli/wait.js +172 -0
  18. package/src/file-preview.js +1 -1
  19. package/src/index.js +1 -1
  20. package/src/mcp-ui/board/block-ctx.js +43 -0
  21. package/src/mcp-ui/board/bridge.js +165 -0
  22. package/src/mcp-ui/board/controls.js +310 -0
  23. package/src/mcp-ui/board/core.js +20 -0
  24. package/src/mcp-ui/board/lifecycle.js +118 -0
  25. package/src/mcp-ui/board/normalize.js +95 -0
  26. package/src/mcp-ui/board/render.js +200 -0
  27. package/src/mcp-ui/board/state.js +106 -0
  28. package/src/mcp-ui/board/vendors.js +86 -0
  29. package/src/mcp.js +12 -18
  30. package/src/{server.js → server/board.js} +15 -778
  31. package/src/server/files.js +141 -0
  32. package/src/server/http.js +114 -0
  33. package/src/server/index.js +2 -0
  34. package/src/server/page.js +183 -0
  35. package/src/server/paths.js +7 -0
  36. package/src/server/result.js +58 -0
  37. package/src/server/reviews.js +41 -0
  38. package/src/server/sanitize.js +231 -0
  39. package/src/spec/blocks/a2ui.js +25 -0
  40. package/src/spec/blocks/chart.js +49 -0
  41. package/src/spec/blocks/code.js +38 -0
  42. package/src/spec/blocks/diagram.js +39 -0
  43. package/src/spec/blocks/git-conflict.js +106 -0
  44. package/src/spec/blocks/image.js +32 -0
  45. package/src/spec/blocks/index.js +33 -0
  46. package/src/spec/blocks/markdown.js +13 -0
  47. package/src/spec/blocks/pdf.js +38 -0
  48. package/src/spec/blocks/table.js +122 -0
  49. package/src/spec/blocks/video.js +68 -0
  50. package/src/spec/blocks/widgets.js +98 -0
  51. package/src/spec/constants.js +65 -0
  52. package/src/spec/index.js +5 -0
  53. package/src/spec/normalize.js +285 -0
  54. package/src/spec/ready.js +106 -0
  55. package/src/spec/schema.js +182 -0
  56. package/src/spec/sources.js +83 -0
  57. package/src/ui/annotate/api.js +149 -0
  58. package/src/ui/annotate/badges.js +77 -0
  59. package/src/ui/annotate/chrome.js +158 -0
  60. package/src/ui/annotate/core.js +134 -0
  61. package/src/ui/annotate/highlights.js +129 -0
  62. package/src/ui/annotate/mutations.js +127 -0
  63. package/src/ui/annotate/popover.js +206 -0
  64. package/src/ui/annotate/summary.js +67 -0
  65. package/src/ui/app/annotations.js +88 -0
  66. package/src/ui/app/autosave.js +44 -0
  67. package/src/ui/app/core.js +74 -0
  68. package/src/ui/app/drafts.js +201 -0
  69. package/src/ui/app/heartbeat.js +150 -0
  70. package/src/ui/app/iframe-bridge.js +64 -0
  71. package/src/ui/app/persistence.js +117 -0
  72. package/src/ui/app/prefilled.js +21 -0
  73. package/src/ui/app/presence.js +38 -0
  74. package/src/ui/app/question-color.js +67 -0
  75. package/src/ui/app/questions.js +360 -0
  76. package/src/ui/app/render.js +135 -0
  77. package/src/ui/app/share.js +108 -0
  78. package/src/ui/app/submit.js +109 -0
  79. package/src/ui/app/theme.js +63 -0
  80. package/src/ui/blocks/api.js +1 -0
  81. package/src/ui/blocks/chart.js +222 -0
  82. package/src/ui/blocks/code.js +138 -0
  83. package/src/ui/blocks/compare.js +82 -0
  84. package/src/ui/blocks/core.js +74 -0
  85. package/src/ui/blocks/diff.js +361 -0
  86. package/src/ui/blocks/dispatch.js +111 -0
  87. package/src/ui/blocks/file-links.js +180 -0
  88. package/src/ui/blocks/git-conflict.js +151 -0
  89. package/src/ui/blocks/graphviz.js +57 -0
  90. package/src/ui/blocks/html.js +45 -0
  91. package/src/ui/blocks/image.js +371 -0
  92. package/src/ui/blocks/kpi.js +26 -0
  93. package/src/ui/blocks/markdown.js +223 -0
  94. package/src/ui/blocks/mermaid.js +242 -0
  95. package/src/ui/blocks/palette.js +59 -0
  96. package/src/ui/blocks/pdf.js +21 -0
  97. package/src/ui/blocks/plantuml.js +152 -0
  98. package/src/ui/blocks/table.js +155 -0
  99. package/src/ui/blocks/typography.js +25 -0
  100. package/src/ui/blocks/vendor.js +43 -0
  101. package/src/ui/blocks/video.js +43 -0
  102. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  103. package/src/ui/blocks/viewer.js +324 -0
  104. package/src/ui/kit.js +1 -0
  105. package/src/ui/manifest.js +140 -0
  106. package/types/index.d.ts +1 -1
  107. package/types/spec/blocks/a2ui.d.ts +4 -0
  108. package/types/spec/blocks/chart.d.ts +4 -0
  109. package/types/spec/blocks/code.d.ts +10 -0
  110. package/types/spec/blocks/diagram.d.ts +15 -0
  111. package/types/spec/blocks/git-conflict.d.ts +7 -0
  112. package/types/spec/blocks/image.d.ts +5 -0
  113. package/types/spec/blocks/index.d.ts +30 -0
  114. package/types/spec/blocks/markdown.d.ts +5 -0
  115. package/types/spec/blocks/pdf.d.ts +4 -0
  116. package/types/spec/blocks/table.d.ts +9 -0
  117. package/types/spec/blocks/video.d.ts +4 -0
  118. package/types/spec/blocks/widgets.d.ts +21 -0
  119. package/types/spec/constants.d.ts +67 -0
  120. package/types/spec/index.d.ts +4 -0
  121. package/types/spec/normalize.d.ts +17 -0
  122. package/types/spec/ready.d.ts +1 -0
  123. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  124. package/types/spec/sources.d.ts +14 -0
  125. package/types/ui/manifest.d.ts +62 -0
  126. package/src/cli.js +0 -1767
  127. package/src/mcp-ui/board.js +0 -1162
  128. package/src/spec.js +0 -1224
  129. package/src/ui/annotate.js +0 -1055
  130. package/src/ui/app.js +0 -1643
  131. package/src/ui/blocks.js +0 -3260
@@ -0,0 +1,242 @@
1
+ // ---------- mermaid ----------
2
+ let mermaidSeq = 0;
3
+ // Registries so a live theme toggle can re-render diagrams and restyle
4
+ // charts without a page reload.
5
+ const mermaidRegistry = [];
6
+ const chartRegistry = [];
7
+
8
+ // Effective code = the user's edit if present, else the authored block.code.
9
+ // Used by the initial render, the editor's live preview, and the theme
10
+ // re-render registry path so an edit survives a theme toggle.
11
+ function effectiveMermaidCode(entry) {
12
+ const { block, ctx, blockId } = entry;
13
+ const edited = ctx.edits ? ctx.edits[blockId] : undefined;
14
+ if (edited !== undefined && edited !== null) return edited;
15
+ // The live editor keeps entry.code as the source of truth; if the host's
16
+ // ctx.edits hasn't been updated yet but the user has diverged from the
17
+ // original, preserve that divergence (don't snap back to block.code).
18
+ if (entry.code !== undefined && entry.code !== (block.code || '')) return entry.code;
19
+ return block.code || '';
20
+ }
21
+
22
+ function renderMermaid(block, ctx, blockId) {
23
+ const container = el('div', { class: 'blk-mermaid' });
24
+ // Honor an authored height as the scrollable viewport: a diagram taller than
25
+ // this overflows and becomes drag-pannable in place (was silently ignored —
26
+ // diagrams only ever fit-to-width). No height keeps the 1200px CSS cap.
27
+ if (block.height != null) container.style.maxHeight = clampHeight(block.height, 1200) + 'px';
28
+ const entry = { container, block, ctx, blockId };
29
+ entry.code = effectiveMermaidCode(entry);
30
+ mermaidRegistry.push(entry);
31
+
32
+ if (!block.editable || ctx.canEditBlocks === false) {
33
+ drawMermaid(entry);
34
+ return container;
35
+ }
36
+
37
+ // Editable: wrap the diagram + an editor below it. The wrapper is what the
38
+ // dispatcher appends; the registry still tracks `container` (the diagram).
39
+ const wrap = el('div', { class: 'blk-mermaid-wrap' });
40
+ wrap.append(container);
41
+ wrap.append(buildMermaidEditor(entry));
42
+ drawMermaid(entry);
43
+ return wrap;
44
+ }
45
+
46
+ // Editor: toggle button + collapsible panel (textarea + Reset + status line).
47
+ // Live re-render is debounced 600ms; errors show inline WITHOUT destroying the
48
+ // last good diagram. Each accepted change calls ctx.onBlockEdit(blockId, code)
49
+ // (null when the value matches the original block.code again).
50
+ function buildMermaidEditor(entry) {
51
+ const { block, ctx, blockId, container } = entry;
52
+ const original = block.code || '';
53
+
54
+ const toggleBtn = el('button', { type: 'button', class: 'blk-edit-btn' }, 'Edit diagram');
55
+ const panel = el('div', { class: 'blk-editor', hidden: '' });
56
+
57
+ const ta = el('textarea', { class: 'blk-editor-ta', spellcheck: 'false' });
58
+ ta.value = entry.code;
59
+
60
+ const status = el('div', { class: 'blk-editor-status' }, '');
61
+ const resetBtn = el('button', { type: 'button', class: 'blk-editor-reset' }, 'Reset');
62
+ const row = el('div', { class: 'blk-editor-row' }, resetBtn, status);
63
+ panel.append(ta, row);
64
+
65
+ let open = false;
66
+ toggleBtn.addEventListener('click', () => {
67
+ open = !open;
68
+ panel.hidden = !open;
69
+ toggleBtn.classList.toggle('is-open', open);
70
+ if (open) ta.focus();
71
+ });
72
+
73
+ let timer = null;
74
+ function reportEdit(code) {
75
+ // Only report a real divergence; equal-to-original clears the edit (null).
76
+ try {
77
+ if (code === original) ctx.onBlockEdit(blockId, null);
78
+ else ctx.onBlockEdit(blockId, code);
79
+ } catch {
80
+ // host callback failures must not break editing
81
+ }
82
+ }
83
+
84
+ // Try to render `code`; on success swap the diagram + re-register annotation
85
+ // targets (via drawMermaid) and report the edit; on failure keep the last
86
+ // good diagram and show the error inline.
87
+ function applyCode(code) {
88
+ previewMermaid(entry, code)
89
+ .then(() => {
90
+ status.textContent = '';
91
+ status.classList.remove('has-error');
92
+ entry.code = code;
93
+ reportEdit(code);
94
+ })
95
+ .catch((err) => {
96
+ status.textContent = 'diagram error: ' + (err && err.message ? err.message : String(err));
97
+ status.classList.add('has-error');
98
+ });
99
+ }
100
+
101
+ ta.addEventListener('input', () => {
102
+ if (timer) clearTimeout(timer);
103
+ const code = ta.value;
104
+ timer = setTimeout(() => applyCode(code), 600);
105
+ });
106
+
107
+ resetBtn.addEventListener('click', () => {
108
+ if (timer) { clearTimeout(timer); timer = null; }
109
+ ta.value = original;
110
+ applyCode(original);
111
+ });
112
+
113
+ return el('div', { class: 'blk-mermaid-edit' }, toggleBtn, panel);
114
+ }
115
+
116
+ // Render `code` for the editor preview WITHOUT mutating entry.code on failure.
117
+ // Resolves once the diagram is swapped into the container (annotation targets
118
+ // re-registered by drawMermaid); rejects with the render error so the caller
119
+ // can show it inline and keep the last good diagram.
120
+ function previewMermaid(entry, code) {
121
+ const prev = entry.code;
122
+ entry.code = code;
123
+ return new Promise((resolve, reject) => {
124
+ drawMermaid(entry, { onDone: resolve, onError: reject });
125
+ }).catch((err) => {
126
+ entry.code = prev;
127
+ throw err;
128
+ });
129
+ }
130
+
131
+ function drawMermaid(entry, hooks) {
132
+ const { container, ctx, blockId } = entry;
133
+ const onError = hooks && hooks.onError ? hooks.onError : null;
134
+ const onDone = hooks && hooks.onDone ? hooks.onDone : null;
135
+ const fail = (err) => {
136
+ if (onError) onError(err);
137
+ else showMermaidErr(container, err);
138
+ };
139
+ loadMermaid().then((mermaid) => {
140
+ try {
141
+ mermaid.initialize({
142
+ startOnLoad: false,
143
+ theme: ctx.theme() === 'dark' ? 'dark' : 'neutral',
144
+ securityLevel: 'strict',
145
+ });
146
+ } catch {
147
+ // ignore re-init issues
148
+ }
149
+ const id = 'rly-mmd-' + (++mermaidSeq);
150
+ const code = entry.code !== undefined ? entry.code : effectiveMermaidCode(entry);
151
+ const onSvg = (svg) => {
152
+ container.innerHTML = svg;
153
+ const svgEl = container.querySelector('svg');
154
+ if (svgEl) {
155
+ svgEl.removeAttribute('height');
156
+ svgEl.removeAttribute('width');
157
+ const vb = svgEl.viewBox && svgEl.viewBox.baseVal;
158
+ if (vb && vb.width > 0) {
159
+ // never upscale past the diagram's natural size; still shrink on
160
+ // narrow screens (a 112px-wide graph must not stretch to 820px)
161
+ svgEl.style.width = '100%';
162
+ svgEl.style.maxWidth = Math.ceil(vb.width) + 'px';
163
+ svgEl.style.height = 'auto';
164
+ } else {
165
+ svgEl.style.maxWidth = '100%';
166
+ }
167
+ }
168
+ if (ctx.annotate) {
169
+ const nodes = container.querySelectorAll('.node, .edgeLabel');
170
+ nodes.forEach((g) => {
171
+ ctx.annotate.register(g, {
172
+ blockId,
173
+ questionId: ctx.questionId,
174
+ target: {
175
+ kind: 'mermaid-node',
176
+ nodeId: g.id || '',
177
+ text: (g.textContent || '').trim().slice(0, 120),
178
+ },
179
+ });
180
+ });
181
+ }
182
+ // re-attach per render: innerHTML replacement above wiped the old bar
183
+ if (svgEl) attachViewer(container, { zoomEl: svgEl, natural: svgNatural(svgEl), label: 'diagram', comment: wholeBlockComment(ctx, blockId, 'diagram') });
184
+ if (onDone) onDone();
185
+ };
186
+ try {
187
+ const ret = mermaid.render(id, code);
188
+ if (ret && typeof ret.then === 'function') {
189
+ ret.then((r) => onSvg(r.svg)).catch((err) => fail(err));
190
+ } else if (ret && ret.svg) {
191
+ onSvg(ret.svg);
192
+ } else if (typeof ret === 'string') {
193
+ onSvg(ret);
194
+ } else {
195
+ // legacy callback signature: render(id, code, cb)
196
+ mermaid.render(id, code, (svg) => onSvg(svg));
197
+ }
198
+ } catch (err) {
199
+ fail(err);
200
+ }
201
+ }).catch((err) => fail(err));
202
+ }
203
+
204
+ // Live theme toggle: re-render mermaid diagrams with the new mermaid theme
205
+ // and restyle existing charts' grid/tick/legend colors in place.
206
+ function onThemeChange() {
207
+ for (const entry of mermaidRegistry) {
208
+ try {
209
+ // re-render with the effective code so an edit survives the toggle
210
+ entry.code = effectiveMermaidCode(entry);
211
+ drawMermaid(entry);
212
+ } catch {
213
+ // keep the previous svg on failure
214
+ }
215
+ }
216
+ const { grid, tick } = themeDefaults();
217
+ for (const { chart } of chartRegistry) {
218
+ try {
219
+ const o = chart.options || {};
220
+ if (o.plugins && o.plugins.legend && o.plugins.legend.labels) o.plugins.legend.labels.color = tick;
221
+ if (o.plugins && o.plugins.title) o.plugins.title.color = tick;
222
+ if (o.scales) {
223
+ for (const k of Object.keys(o.scales)) {
224
+ const ax = o.scales[k];
225
+ if (!ax) continue;
226
+ if (ax.grid) ax.grid.color = grid;
227
+ if (ax.ticks) ax.ticks.color = tick;
228
+ }
229
+ }
230
+ chart.update('none');
231
+ } catch {
232
+ // chart may already be destroyed
233
+ }
234
+ }
235
+ }
236
+
237
+ function showMermaidErr(container, err) {
238
+ container.replaceChildren(
239
+ el('div', { class: 'blk-error' }, 'Diagram error: ' + (err && err.message ? err.message : String(err)))
240
+ );
241
+ }
242
+
@@ -0,0 +1,59 @@
1
+ // ---------- palette ----------
2
+ // Color palettes as swatch cards: hover a swatch to reveal its hex, click to
3
+ // copy it. One palette may be {featured:true} → a larger spotlight row. Lets
4
+ // an agent present a curated palette with one structured block instead of
5
+ // hand-writing HTML. Swatches and the whole block are commentable.
6
+ function copyColor(text, btn) {
7
+ const done = () => {
8
+ btn.classList.add('copied');
9
+ setTimeout(() => btn.classList.remove('copied'), 900);
10
+ };
11
+ try {
12
+ if (navigator.clipboard && navigator.clipboard.writeText) {
13
+ navigator.clipboard.writeText(text).then(done, () => {});
14
+ return;
15
+ }
16
+ } catch { /* fall through */ }
17
+ done(); // no clipboard (sandbox) — still flash feedback
18
+ }
19
+
20
+ function paletteCard(p, big, ctx, blockId) {
21
+ const card = el('div', { class: 'pal-card' + (big ? ' pal-spotlight' : '') });
22
+ const row = el('div', { class: 'pal-swatches' });
23
+ for (const c of p.colors) {
24
+ const sw = el('button', { class: 'pal-sw', type: 'button', style: 'background:' + c, title: 'Copy ' + c });
25
+ sw.append(el('span', { class: 'pal-hex' }, c));
26
+ sw.addEventListener('click', () => copyColor(c, sw));
27
+ if (ctx.annotate) {
28
+ ctx.annotate.register(sw, {
29
+ blockId,
30
+ questionId: ctx.questionId,
31
+ target: { kind: 'swatch', label: (p.name ? p.name + ' · ' : '') + c },
32
+ });
33
+ }
34
+ row.append(sw);
35
+ }
36
+ card.append(row);
37
+ const info = el('div', { class: 'pal-info' });
38
+ const meta = el('div', { class: 'pal-meta' });
39
+ if (p.name) meta.append(el('div', { class: 'pal-name' }, p.name));
40
+ if (p.sub) meta.append(el('div', { class: 'pal-sub' }, p.sub));
41
+ info.append(meta);
42
+ if (p.tag) info.append(el('span', { class: 'pal-tag' + (p.tagTone ? ' tone-' + p.tagTone : '') }, p.tag));
43
+ if (p.name || p.sub || p.tag) card.append(info);
44
+ return card;
45
+ }
46
+
47
+ function renderPalette(block, ctx, blockId) {
48
+ const wrap = el('div', { class: 'blk-palette' });
49
+ const palettes = Array.isArray(block.palettes) ? block.palettes : [];
50
+ if (block.title) wrap.append(el('div', { class: 'pal-title' }, block.title));
51
+ const grid = el('div', { class: 'pal-grid' });
52
+ for (const p of palettes) {
53
+ if (p.featured) wrap.append(paletteCard(p, true, ctx, blockId));
54
+ else grid.append(paletteCard(p, false, ctx, blockId));
55
+ }
56
+ if (grid.childNodes.length) wrap.append(grid);
57
+ return wrap;
58
+ }
59
+
@@ -0,0 +1,21 @@
1
+ // ---------- PDF (local stream or direct URL) ----------
2
+ function renderPdf(block, ctx, blockId) {
3
+ const wrap = el('div', { class: 'blk-pdfwrap' });
4
+ const src = block.hasFile ? '/pdf/b/' + encodeURIComponent(blockId) : block.src;
5
+ const title = block.title || 'PDF';
6
+ const frame = el('iframe', {
7
+ class: 'blk-pdf',
8
+ src,
9
+ title,
10
+ loading: 'lazy',
11
+ });
12
+ if (block.height != null) frame.style.height = clampHeight(block.height, 900) + 'px';
13
+ frame.addEventListener('error', () => {
14
+ wrap.replaceChildren(el('div', { class: 'blk-error' }, 'PDF failed to load'));
15
+ });
16
+ wrap.append(frame);
17
+ if (block.title) wrap.append(el('div', { class: 'blk-videocap' }, block.title));
18
+ attachViewer(wrap, { zoomEl: null, label: 'pdf', comment: wholeBlockComment(ctx, blockId, 'pdf') });
19
+ return wrap;
20
+ }
21
+
@@ -0,0 +1,152 @@
1
+ // ---------- plantuml (server-rendered; client deflate-raw + base64 variant) ----------
2
+ const PLANTUML_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
3
+
4
+ // PlantUML's base64 variant: 3 bytes -> 4 chars using PLANTUML_ALPHABET.
5
+ function encode64(bytes) {
6
+ let out = '';
7
+ for (let i = 0; i < bytes.length; i += 3) {
8
+ const b1 = bytes[i];
9
+ const b2 = i + 1 < bytes.length ? bytes[i + 1] : 0;
10
+ const b3 = i + 2 < bytes.length ? bytes[i + 2] : 0;
11
+ out += PLANTUML_ALPHABET[b1 >> 2];
12
+ out += PLANTUML_ALPHABET[((b1 & 0x3) << 4) | (b2 >> 4)];
13
+ if (i + 1 < bytes.length) out += PLANTUML_ALPHABET[((b2 & 0xf) << 2) | (b3 >> 6)];
14
+ if (i + 2 < bytes.length) out += PLANTUML_ALPHABET[b3 & 0x3f];
15
+ }
16
+ return out;
17
+ }
18
+
19
+ async function encodePlantUml(code) {
20
+ if (typeof CompressionStream === 'undefined') {
21
+ throw new Error('CompressionStream unavailable');
22
+ }
23
+ const bytes = new TextEncoder().encode(String(code));
24
+ const blob = new Blob([bytes]);
25
+ const compressed = await new Response(
26
+ blob.stream().pipeThrough(new CompressionStream('deflate-raw'))
27
+ ).arrayBuffer();
28
+ return encode64(new Uint8Array(compressed));
29
+ }
30
+
31
+ // Fetch a remote SVG and return a sanitized inline <svg> element, so its parts
32
+ // become annotatable. Rejects on network/CORS failure (caller falls back to an
33
+ // <img>). The SVG is sanitized — it comes from a remote, author-set server, so
34
+ // strip scripts / foreignObject / on* handlers / javascript: links before it
35
+ // ever touches the document.
36
+ function fetchInlineSvg(url) {
37
+ return fetch(url, { credentials: 'omit', mode: 'cors' })
38
+ .then((r) => {
39
+ if (!r.ok) throw new Error('http ' + r.status);
40
+ // only trust a declared SVG/XML payload; anything else → <img> fallback
41
+ const ct = (r.headers.get('content-type') || '').toLowerCase();
42
+ if (ct && !ct.includes('svg') && !ct.includes('xml')) throw new Error('not svg: ' + ct);
43
+ return r.text();
44
+ })
45
+ .then((text) => {
46
+ const doc = new DOMParser().parseFromString(text, 'image/svg+xml');
47
+ if (doc.querySelector('parsererror')) throw new Error('bad svg');
48
+ const svg = doc.querySelector('svg');
49
+ if (!svg) throw new Error('no svg');
50
+ sanitizeSvg(svg);
51
+ return document.importNode(svg, true);
52
+ });
53
+ }
54
+
55
+ // The SVG comes from a remote, author-set server, so strip everything active
56
+ // or capable of fetching an external resource before it touches the document.
57
+ // Script execution is already impossible here (DOMParser doesn't run scripts;
58
+ // importNode+appendChild never starts an SVG <script>), but we still drop
59
+ // <script>/<foreignObject>/<style>, on* handlers, non-fragment href/xlink:href
60
+ // (<use>/<image>/<a>), and any url(...) that doesn't point at a #fragment —
61
+ // those are client-side SSRF / beacon vectors and there is no CSP backstop.
62
+ function sanitizeSvg(root) {
63
+ root.querySelectorAll('script, foreignObject, style').forEach((n) => n.remove());
64
+ const walk = (n) => {
65
+ if (n.nodeType === 1) {
66
+ for (const attr of Array.from(n.attributes)) {
67
+ const name = attr.name.toLowerCase();
68
+ const val = (attr.value || '').replace(/\s+/g, '').toLowerCase();
69
+ const isHref = name === 'href' || name.endsWith(':href');
70
+ if (
71
+ name.startsWith('on') || // event handlers
72
+ (isHref && !val.startsWith('#')) || // only same-document fragment refs
73
+ /url\((?!['"]?#)/.test(val) // url() to anything but a #fragment
74
+ ) {
75
+ n.removeAttribute(attr.name);
76
+ }
77
+ }
78
+ }
79
+ n.childNodes.forEach(walk);
80
+ };
81
+ walk(root);
82
+ }
83
+
84
+ function renderPlantuml(block, ctx, blockId) {
85
+ const container = el('div', { class: 'blk-plantuml' });
86
+ const fail = () =>
87
+ container.replaceChildren(
88
+ el('div', { class: 'blk-error' }, 'PlantUML needs network access and a modern browser')
89
+ );
90
+ encodePlantUml(block.code || '')
91
+ .then((encoded) => {
92
+ const server = block.server || 'https://www.plantuml.com/plantuml';
93
+ const url = server + '/svg/' + encoded;
94
+ // Prefer inline SVG (per-element annotation); fall back to an opaque
95
+ // <img> if the server blocks cross-origin fetch or anything fails.
96
+ fetchInlineSvg(url)
97
+ .then((svg) => mountPlantumlSvg(container, svg, block, ctx, blockId))
98
+ .catch(() => mountPlantumlImg(container, url, fail, block, ctx, blockId));
99
+ })
100
+ .catch(fail);
101
+ return container;
102
+ }
103
+
104
+ function mountPlantumlSvg(container, svg, block, ctx, blockId) {
105
+ if (block.height != null) container.style.maxHeight = clampHeight(block.height, 1200) + 'px';
106
+ sizeDiagramSvg(svg);
107
+ container.replaceChildren(svg);
108
+ attachViewer(container, {
109
+ zoomEl: svg,
110
+ natural: svgNatural(svg),
111
+ label: 'diagram',
112
+ comment: wholeBlockComment(ctx, blockId, 'diagram'),
113
+ });
114
+ if (!ctx.annotate) return;
115
+ // register the text labels as annotation targets (participant boxes, message
116
+ // labels, …) — the meaningful, clickable parts of a PlantUML diagram.
117
+ // `idx` disambiguates: PlantUML repeats participant labels top AND bottom,
118
+ // so without a unique key one comment would badge BOTH identical-text nodes.
119
+ svg.querySelectorAll('text').forEach((t, idx) => {
120
+ const text = (t.textContent || '').trim();
121
+ if (!text) return;
122
+ ctx.annotate.register(t, {
123
+ blockId,
124
+ questionId: ctx.questionId,
125
+ target: { kind: 'plantuml-node', idx, text: text.slice(0, 120) },
126
+ });
127
+ });
128
+ }
129
+
130
+ function mountPlantumlImg(container, url, fail, block, ctx, blockId) {
131
+ const img = el('img', { class: 'blk-plantuml-img', src: url, alt: 'PlantUML diagram', loading: 'lazy' });
132
+ if (block.height != null) img.style.height = clampHeight(block.height, 360) + 'px';
133
+ img.addEventListener('error', fail);
134
+ container.replaceChildren(img);
135
+ const attachImgViewer = () =>
136
+ attachViewer(container, {
137
+ zoomEl: img,
138
+ natural: () => (img.naturalWidth > 0 ? { w: img.naturalWidth, h: img.naturalHeight } : null),
139
+ label: 'diagram',
140
+ comment: wholeBlockComment(ctx, blockId, 'diagram'),
141
+ });
142
+ if (img.complete && img.naturalWidth > 0) attachImgViewer();
143
+ else img.addEventListener('load', attachImgViewer, { once: true });
144
+ if (ctx.annotate) {
145
+ ctx.annotate.register(img, {
146
+ blockId,
147
+ questionId: ctx.questionId,
148
+ target: { kind: 'image', label: 'PlantUML diagram' },
149
+ });
150
+ }
151
+ }
152
+
@@ -0,0 +1,155 @@
1
+ // ---------- table ----------
2
+ function normalizeColumns(columns) {
3
+ return (columns || []).map((c, idx) => {
4
+ if (c && typeof c === 'object') {
5
+ return { key: c.key !== undefined ? c.key : idx, label: c.label !== undefined ? c.label : String(c.key), align: c.align || null };
6
+ }
7
+ return { key: idx, label: String(c), align: null };
8
+ });
9
+ }
10
+
11
+ function cellValue(row, col) {
12
+ if (Array.isArray(row)) return row[col.key];
13
+ return row[col.key];
14
+ }
15
+
16
+ function numericAware(a, b) {
17
+ const na = parseFloat(a);
18
+ const nb = parseFloat(b);
19
+ const aNum = a !== '' && a !== null && a !== undefined && !Number.isNaN(na) && String(na) === String(a).trim();
20
+ const bNum = b !== '' && b !== null && b !== undefined && !Number.isNaN(nb) && String(nb) === String(b).trim();
21
+ if (aNum && bNum) return na - nb;
22
+ return String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: 'base' });
23
+ }
24
+
25
+ // CSV-encode a value (quote when it contains a comma/quote/newline).
26
+ function csvCell(v) {
27
+ const s = v === undefined || v === null ? '' : String(v);
28
+ return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
29
+ }
30
+ // Trigger a client-side download of `text` as `filename` (browser board). In a
31
+ // sandboxed/MCP host this may be blocked — best effort, no error if it no-ops.
32
+ function downloadText(filename, text, mime) {
33
+ try {
34
+ const blob = new Blob([text], { type: mime || 'text/plain' });
35
+ const url = URL.createObjectURL(blob);
36
+ const a = el('a', { href: url, download: filename });
37
+ document.body.append(a);
38
+ a.click();
39
+ a.remove();
40
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
41
+ } catch (_) { /* sandbox without download permission */ }
42
+ }
43
+
44
+ function renderTable(block, ctx, blockId) {
45
+ const cols = normalizeColumns(block.columns);
46
+ const rows = block.rows || [];
47
+ const sortable = block.sortable === true;
48
+ const filterable = block.filterable === true;
49
+ const exportable = block.exportable === true;
50
+ let filterText = '';
51
+ // sortState: column index in cols (-1 none) + dir
52
+ let sortCol = -1;
53
+ let sortDir = 0; // 0 none, 1 asc, -1 desc
54
+
55
+ const table = el('table', { class: 'blk-table' });
56
+ const thead = el('thead');
57
+ const trHead = el('tr');
58
+ const headCells = [];
59
+ cols.forEach((col, ci) => {
60
+ const th = el('th', { class: sortable ? 'sortable' : null });
61
+ if (col.align) th.style.textAlign = col.align;
62
+ const labelSpan = el('span', {}, col.label);
63
+ const arrow = el('span', { class: 'sort-arrow' }, '');
64
+ th.append(labelSpan, arrow);
65
+ if (sortable) {
66
+ th.addEventListener('click', () => {
67
+ if (sortCol === ci) sortDir = sortDir === 1 ? -1 : sortDir === -1 ? 0 : 1;
68
+ else { sortCol = ci; sortDir = 1; }
69
+ rebuild();
70
+ });
71
+ }
72
+ headCells.push({ th, arrow });
73
+ trHead.append(th);
74
+ });
75
+ thead.append(trHead);
76
+ const tbody = el('tbody');
77
+ table.append(thead, tbody);
78
+
79
+ // rows (as original indices) passing the current filter — used by both the
80
+ // table body and the CSV export so export honors the visible/filtered set.
81
+ function filteredOrder() {
82
+ let order = rows.map((_r, idx) => idx);
83
+ if (filterText) {
84
+ const q = filterText.toLowerCase();
85
+ order = order.filter((idx) => cols.some((col) => {
86
+ const v = cellValue(rows[idx], col);
87
+ return v !== undefined && v !== null && String(v).toLowerCase().includes(q);
88
+ }));
89
+ }
90
+ if (sortable && sortCol >= 0 && sortDir !== 0) {
91
+ const col = cols[sortCol];
92
+ order.sort((ia, ib) => {
93
+ const r = numericAware(cellValue(rows[ia], col), cellValue(rows[ib], col));
94
+ return sortDir === 1 ? r : -r;
95
+ });
96
+ }
97
+ return order;
98
+ }
99
+
100
+ function rebuild() {
101
+ const order = filteredOrder();
102
+ headCells.forEach((hc, ci) => {
103
+ hc.arrow.textContent = sortable && ci === sortCol && sortDir !== 0 ? (sortDir === 1 ? ' ↑' : ' ↓') : '';
104
+ });
105
+ tbody.replaceChildren();
106
+ for (const origIdx of order) {
107
+ const row = rows[origIdx];
108
+ const tr = el('tr');
109
+ for (const col of cols) {
110
+ const raw = cellValue(row, col);
111
+ const td = el('td', {}, raw === undefined || raw === null ? '' : String(raw));
112
+ if (col.align) td.style.textAlign = col.align;
113
+ ctx.annotate?.register(td, {
114
+ blockId,
115
+ questionId: ctx.questionId,
116
+ target: { kind: 'table-cell', row: origIdx, col: col.key, value: String(raw === undefined || raw === null ? '' : raw) },
117
+ });
118
+ tr.append(td);
119
+ }
120
+ tbody.append(tr);
121
+ }
122
+ }
123
+ rebuild();
124
+ // Tables are visual too: wrap so they get the full-screen viewer like
125
+ // every other visual block (wide tables squeeze in the column).
126
+ const wrap = el('div', { class: 'blk-tablewrap' });
127
+ // Optional toolbar: live filter box + CSV export of the filtered rows.
128
+ if (filterable || exportable) {
129
+ const bar = el('div', { class: 'blk-tablebar' });
130
+ if (filterable) {
131
+ const input = el('input', { type: 'text', class: 'blk-tablefilter', placeholder: 'Filter rows…', 'aria-label': 'Filter table rows' });
132
+ input.addEventListener('input', () => { filterText = input.value.trim(); rebuild(); });
133
+ // don't let a click in the filter start a drag-pan / full-screen
134
+ input.addEventListener('mousedown', (e) => e.stopPropagation());
135
+ bar.append(input);
136
+ }
137
+ if (exportable) {
138
+ const btn = el('button', { type: 'button', class: 'blk-tableexport', title: 'Download the filtered rows as CSV' }, 'CSV');
139
+ btn.addEventListener('mousedown', (e) => e.stopPropagation());
140
+ btn.addEventListener('click', (e) => {
141
+ e.stopPropagation();
142
+ const order = filteredOrder();
143
+ const head = cols.map((c) => csvCell(c.label)).join(',');
144
+ const body = order.map((idx) => cols.map((c) => csvCell(cellValue(rows[idx], c))).join(',')).join('\n');
145
+ downloadText('table.csv', head + '\n' + body + '\n', 'text/csv');
146
+ });
147
+ bar.append(btn);
148
+ }
149
+ wrap.append(bar);
150
+ }
151
+ wrap.append(table);
152
+ attachViewer(wrap, { zoomEl: null });
153
+ return wrap;
154
+ }
155
+
@@ -0,0 +1,25 @@
1
+ // ---------- typography (type specimens) ----------
2
+ function renderTypography(block, ctx, blockId) {
3
+ const wrap = el('div', { class: 'blk-typography' });
4
+ if (block.title) wrap.append(el('div', { class: 'typo-title' }, block.title));
5
+ for (const s of block.specimens || []) {
6
+ const meta = [];
7
+ if (s.label) meta.push(s.label);
8
+ if (s.size) meta.push(s.size);
9
+ if (s.weight) meta.push('w' + s.weight);
10
+ const sample = el('div', { class: 'typo-sample' }, s.text);
11
+ // set via DOM style props (browser ignores invalid values — no injection)
12
+ if (s.size) sample.style.fontSize = s.size;
13
+ if (s.weight) sample.style.fontWeight = s.weight;
14
+ if (s.font || block.font) sample.style.fontFamily = s.font || block.font;
15
+ if (s.lineHeight) sample.style.lineHeight = s.lineHeight;
16
+ if (s.letterSpacing) sample.style.letterSpacing = s.letterSpacing;
17
+ wrap.append(el('div', { class: 'typo-row' },
18
+ meta.length ? el('div', { class: 'typo-meta' }, meta.join(' · ')) : null,
19
+ sample
20
+ ));
21
+ }
22
+ ctx.annotate && ctx.annotate.enableTextSelection(wrap, { blockId, questionId: ctx.questionId });
23
+ return wrap;
24
+ }
25
+