@khanglvm/relay 0.19.0 → 0.20.1

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 (134) hide show
  1. package/README.md +11 -4
  2. package/bin/rly.js +1 -1
  3. package/package.json +4 -4
  4. package/src/cli/args.js +46 -0
  5. package/src/cli/ask.js +12 -0
  6. package/src/cli/boards.js +326 -0
  7. package/src/cli/config.js +56 -0
  8. package/src/cli/context.js +13 -0
  9. package/src/cli/git.js +183 -0
  10. package/src/cli/help.js +91 -0
  11. package/src/cli/index.js +103 -0
  12. package/src/cli/install.js +197 -0
  13. package/src/cli/io.js +186 -0
  14. package/src/cli/mcp.js +94 -0
  15. package/src/cli/share.js +45 -0
  16. package/src/cli/skill.js +192 -0
  17. package/src/cli/upgrade.js +130 -0
  18. package/src/cli/wait.js +172 -0
  19. package/src/file-preview.js +1 -1
  20. package/src/index.js +1 -1
  21. package/src/link.js +57 -9
  22. package/src/mcp-ui/board/block-ctx.js +43 -0
  23. package/src/mcp-ui/board/bridge.js +165 -0
  24. package/src/mcp-ui/board/controls.js +310 -0
  25. package/src/mcp-ui/board/core.js +20 -0
  26. package/src/mcp-ui/board/lifecycle.js +118 -0
  27. package/src/mcp-ui/board/normalize.js +95 -0
  28. package/src/mcp-ui/board/render.js +200 -0
  29. package/src/mcp-ui/board/state.js +106 -0
  30. package/src/mcp-ui/board/vendors.js +86 -0
  31. package/src/mcp.js +12 -18
  32. package/src/{server.js → server/board.js} +16 -779
  33. package/src/server/files.js +141 -0
  34. package/src/server/http.js +114 -0
  35. package/src/server/index.js +2 -0
  36. package/src/server/page.js +183 -0
  37. package/src/server/paths.js +7 -0
  38. package/src/server/result.js +58 -0
  39. package/src/server/reviews.js +41 -0
  40. package/src/server/sanitize.js +231 -0
  41. package/src/spec/blocks/a2ui.js +25 -0
  42. package/src/spec/blocks/chart.js +49 -0
  43. package/src/spec/blocks/code.js +38 -0
  44. package/src/spec/blocks/diagram.js +39 -0
  45. package/src/spec/blocks/git-conflict.js +106 -0
  46. package/src/spec/blocks/image.js +32 -0
  47. package/src/spec/blocks/index.js +33 -0
  48. package/src/spec/blocks/markdown.js +13 -0
  49. package/src/spec/blocks/pdf.js +38 -0
  50. package/src/spec/blocks/table.js +122 -0
  51. package/src/spec/blocks/video.js +68 -0
  52. package/src/spec/blocks/widgets.js +98 -0
  53. package/src/spec/constants.js +65 -0
  54. package/src/spec/index.js +5 -0
  55. package/src/spec/normalize.js +285 -0
  56. package/src/spec/ready.js +106 -0
  57. package/src/spec/schema.js +182 -0
  58. package/src/spec/sources.js +83 -0
  59. package/src/store.js +1 -1
  60. package/src/ui/annotate/api.js +149 -0
  61. package/src/ui/annotate/badges.js +77 -0
  62. package/src/ui/annotate/chrome.js +158 -0
  63. package/src/ui/annotate/core.js +134 -0
  64. package/src/ui/annotate/highlights.js +129 -0
  65. package/src/ui/annotate/mutations.js +127 -0
  66. package/src/ui/annotate/popover.js +206 -0
  67. package/src/ui/annotate/summary.js +67 -0
  68. package/src/ui/app/annotations.js +88 -0
  69. package/src/ui/app/autosave.js +44 -0
  70. package/src/ui/app/core.js +74 -0
  71. package/src/ui/app/drafts.js +201 -0
  72. package/src/ui/app/heartbeat.js +150 -0
  73. package/src/ui/app/iframe-bridge.js +64 -0
  74. package/src/ui/app/persistence.js +117 -0
  75. package/src/ui/app/prefilled.js +21 -0
  76. package/src/ui/app/presence.js +38 -0
  77. package/src/ui/app/question-color.js +67 -0
  78. package/src/ui/app/questions.js +360 -0
  79. package/src/ui/app/render.js +135 -0
  80. package/src/ui/app/share.js +108 -0
  81. package/src/ui/app/submit.js +109 -0
  82. package/src/ui/app/theme.js +63 -0
  83. package/src/ui/blocks/api.js +1 -0
  84. package/src/ui/blocks/chart.js +222 -0
  85. package/src/ui/blocks/code.js +138 -0
  86. package/src/ui/blocks/compare.js +82 -0
  87. package/src/ui/blocks/core.js +74 -0
  88. package/src/ui/blocks/diff.js +361 -0
  89. package/src/ui/blocks/dispatch.js +111 -0
  90. package/src/ui/blocks/file-links.js +180 -0
  91. package/src/ui/blocks/git-conflict.js +151 -0
  92. package/src/ui/blocks/graphviz.js +57 -0
  93. package/src/ui/blocks/html.js +45 -0
  94. package/src/ui/blocks/image.js +371 -0
  95. package/src/ui/blocks/kpi.js +26 -0
  96. package/src/ui/blocks/markdown.js +223 -0
  97. package/src/ui/blocks/mermaid.js +242 -0
  98. package/src/ui/blocks/palette.js +59 -0
  99. package/src/ui/blocks/pdf.js +21 -0
  100. package/src/ui/blocks/plantuml.js +152 -0
  101. package/src/ui/blocks/table.js +155 -0
  102. package/src/ui/blocks/typography.js +25 -0
  103. package/src/ui/blocks/vendor.js +43 -0
  104. package/src/ui/blocks/video.js +43 -0
  105. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  106. package/src/ui/blocks/viewer.js +324 -0
  107. package/src/ui/kit.js +1 -0
  108. package/src/ui/manifest.js +140 -0
  109. package/types/index.d.ts +1 -1
  110. package/types/spec/blocks/a2ui.d.ts +4 -0
  111. package/types/spec/blocks/chart.d.ts +4 -0
  112. package/types/spec/blocks/code.d.ts +10 -0
  113. package/types/spec/blocks/diagram.d.ts +15 -0
  114. package/types/spec/blocks/git-conflict.d.ts +7 -0
  115. package/types/spec/blocks/image.d.ts +5 -0
  116. package/types/spec/blocks/index.d.ts +30 -0
  117. package/types/spec/blocks/markdown.d.ts +5 -0
  118. package/types/spec/blocks/pdf.d.ts +4 -0
  119. package/types/spec/blocks/table.d.ts +9 -0
  120. package/types/spec/blocks/video.d.ts +4 -0
  121. package/types/spec/blocks/widgets.d.ts +21 -0
  122. package/types/spec/constants.d.ts +67 -0
  123. package/types/spec/index.d.ts +4 -0
  124. package/types/spec/normalize.d.ts +17 -0
  125. package/types/spec/ready.d.ts +1 -0
  126. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  127. package/types/spec/sources.d.ts +14 -0
  128. package/types/ui/manifest.d.ts +62 -0
  129. package/src/cli.js +0 -1767
  130. package/src/mcp-ui/board.js +0 -1162
  131. package/src/spec.js +0 -1224
  132. package/src/ui/annotate.js +0 -1055
  133. package/src/ui/app.js +0 -1643
  134. package/src/ui/blocks.js +0 -3260
@@ -0,0 +1,109 @@
1
+ // ---------- validation & submit ----------
2
+ function validate() {
3
+ let firstBad = null;
4
+ for (const q of QS) {
5
+ const required = q.required || !spec.allowPartial;
6
+ const bad = required && getValue(q) === undefined;
7
+ cards[q.id].classList.toggle('error', bad);
8
+ if (bad && !firstBad) firstBad = cards[q.id];
9
+ }
10
+ if (firstBad) firstBad.scrollIntoView({ behavior: 'smooth', block: 'center' });
11
+ return !firstBad;
12
+ }
13
+
14
+ function showDone(closing, sideReview = false) {
15
+ stopHeartbeat();
16
+ // Annotation pins/badges/popover float on <body> with elevated z-index —
17
+ // remove them so they don't leak over the submitted screen.
18
+ if (window.RelayAnnotate && typeof RelayAnnotate.teardown === 'function') {
19
+ try {
20
+ RelayAnnotate.teardown();
21
+ } catch {
22
+ // best effort
23
+ }
24
+ }
25
+ // If the agent already stopped waiting (soft timeout / dropped connection),
26
+ // the submission won't be picked up automatically — tell the user to nudge
27
+ // the agent. Otherwise the normal hand-back copy applies.
28
+ const note = sideReview
29
+ ? 'Saved for reference. This did not finalize the board or notify the waiting agent; the owner still needs to submit the final answer.'
30
+ : handedBack
31
+ ? 'Saved. Your agent had stopped waiting — send it a message so it picks up your answers.'
32
+ : closing
33
+ ? 'Handing back to your agent — this tab will close itself…'
34
+ : 'Handed back to your agent. You can close this tab.';
35
+ app.replaceChildren(
36
+ el('div', { class: 'done' },
37
+ el('div', { class: 'mark' }, '✓'),
38
+ el('h2', {}, sideReview ? 'Side review saved' : QS.length ? 'Submitted' : 'Acknowledged'),
39
+ el('p', { id: 'done-note' }, note)
40
+ )
41
+ );
42
+ }
43
+
44
+ submitBtn.addEventListener('click', async () => {
45
+ if (!validate()) return;
46
+ submitBtn.disabled = true;
47
+ submitBtn.textContent = 'Submitting…';
48
+ clearTimeout(saveTimer);
49
+ let reached = true;
50
+ try {
51
+ let res;
52
+ try {
53
+ res = await fetch('/api/submit', {
54
+ method: 'POST',
55
+ headers: authHeaders({ 'content-type': 'application/json' }),
56
+ body: JSON.stringify(payload()),
57
+ });
58
+ } catch (netErr) {
59
+ // A thrown fetch (vs. an HTTP error response) means we never reached the
60
+ // server — the connection is gone, so this submit was never delivered.
61
+ reached = false;
62
+ throw netErr;
63
+ }
64
+ if (!res.ok) throw new Error('submit rejected');
65
+ const submitResult = await res.json().catch(() => null);
66
+ const sideReview = Boolean(submitResult && submitResult.sideReview === true && submitResult.final === false);
67
+ submitted = true;
68
+ // Submitted successfully → the local mirror is no longer needed and would
69
+ // otherwise resurrect stale answers on a future reopen. Clear it.
70
+ clearLocalDraft();
71
+ // Don't auto-close when the agent had stopped waiting — the user needs to
72
+ // read the "send your agent a message" note and act on it.
73
+ const autoClose = !sideReview && spec.autoClose && !handedBack;
74
+ showDone(autoClose, sideReview);
75
+ if (autoClose) {
76
+ setTimeout(() => {
77
+ window.close();
78
+ // window.close() is best-effort (browsers may block it for
79
+ // user-opened tabs) — fall back to the "close this tab" note.
80
+ setTimeout(() => {
81
+ const note = document.getElementById('done-note');
82
+ if (note) note.textContent = 'Handed back to your agent. You can close this tab.';
83
+ }, 400);
84
+ }, 700);
85
+ }
86
+ } catch {
87
+ // Restore the button so the user can retry.
88
+ submitBtn.disabled = false;
89
+ submitBtn.textContent = access.role === 'review' ? 'Submit side review' : spec.submitLabel;
90
+ if (!reached) {
91
+ // The connection is gone — the submit (and any further input) can't be
92
+ // persisted. Block hard so the user stops adding feedback that would be
93
+ // lost; the block's probe loop / heartbeat lifts it on recovery, and the
94
+ // user can then submit. force=true: the failed submit already confirms
95
+ // the server is unreachable.
96
+ stopHeartbeat();
97
+ considerPersistenceLost(true);
98
+ startBlockedProbeLoop();
99
+ } else {
100
+ // The server answered with an error (e.g. 409 board already finished) —
101
+ // it's reachable, so don't show the scary block; just guide the user.
102
+ showNotice(
103
+ 'Couldn’t submit — the board may have already closed. Prompt the agent to reopen this board so your input isn’t lost.',
104
+ 'warn'
105
+ );
106
+ }
107
+ }
108
+ });
109
+
@@ -0,0 +1,63 @@
1
+ // ---------- theme (auto -> light -> dark) ----------
2
+ // Server-side pref wins: boards run on random ports, so localStorage alone
3
+ // can't carry the choice across boards. The server persists it globally.
4
+ const THEME_KEY = 'qb-theme';
5
+ const THEMES = ['auto', 'light', 'dark'];
6
+ let theme = (boot.pref && boot.pref.theme) || localStorage.getItem(THEME_KEY);
7
+ if (!THEMES.includes(theme)) theme = 'auto';
8
+ function effectiveTheme() {
9
+ if (theme !== 'auto') return theme;
10
+ return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
11
+ }
12
+ function applyTheme() {
13
+ if (theme === 'auto') delete document.documentElement.dataset.theme;
14
+ else document.documentElement.dataset.theme = theme;
15
+ if (themeBtn) themeBtn.textContent = { auto: '◐ auto', light: '☀ light', dark: '☾ dark' }[theme];
16
+ // Custom-HTML iframes get ?theme=light|dark so authors can match the theme.
17
+ for (const f of document.querySelectorAll('iframe.viz')) {
18
+ try {
19
+ const u = new URL(f.src);
20
+ if (u.searchParams.get('theme') !== effectiveTheme()) {
21
+ u.searchParams.set('theme', effectiveTheme());
22
+ f.src = u.toString();
23
+ }
24
+ } catch {
25
+ // ignore malformed src
26
+ }
27
+ }
28
+ // Re-theme native blocks (mermaid re-render, chart grid/tick restyle).
29
+ if (window.RelayBlocks && typeof RelayBlocks.onThemeChange === 'function') {
30
+ try {
31
+ RelayBlocks.onThemeChange(effectiveTheme());
32
+ } catch {
33
+ // blocks may not be rendered yet
34
+ }
35
+ }
36
+ }
37
+ let themeBtn = null;
38
+
39
+ // ---------- font scale (A− / A+) ----------
40
+ // A page-zoom knob: scales the root font-size (every rem) so the whole board
41
+ // grows/shrinks. Persists like the theme — server pref + localStorage mirror —
42
+ // so the choice carries across the random-port boards.
43
+ const FS_KEY = 'qb-fontscale';
44
+ const FS_MIN = 0.85, FS_MAX = 1.5, FS_STEP = 0.1;
45
+ let fontScale = Number((boot.pref && boot.pref.fontScale) || localStorage.getItem(FS_KEY));
46
+ if (!Number.isFinite(fontScale) || fontScale <= 0) fontScale = 1;
47
+ const clampFs = (n) => Math.min(FS_MAX, Math.max(FS_MIN, Math.round(n * 100) / 100));
48
+ fontScale = clampFs(fontScale);
49
+ function applyFontScale() {
50
+ document.documentElement.style.setProperty('--fs', String(fontScale));
51
+ }
52
+ function setFontScale(next) {
53
+ fontScale = clampFs(next);
54
+ applyFontScale();
55
+ try { localStorage.setItem(FS_KEY, String(fontScale)); } catch { /* private mode */ }
56
+ fetch('/api/pref', {
57
+ method: 'POST',
58
+ headers: { 'content-type': 'application/json' },
59
+ body: JSON.stringify({ fontScale }),
60
+ }).catch(() => {});
61
+ }
62
+ applyFontScale();
63
+
@@ -0,0 +1 @@
1
+ window.RelayBlocks = { render, onThemeChange, renderMarkdown, openFull };
@@ -0,0 +1,222 @@
1
+ // ---------- chart ----------
2
+ function clampHeight(h, def) {
3
+ const n = Number(h);
4
+ if (!Number.isFinite(n)) return def;
5
+ return Math.max(100, Math.min(2400, n));
6
+ }
7
+
8
+ function palette() {
9
+ return (document.documentElement.dataset.theme === 'dark' ||
10
+ (!document.documentElement.dataset.theme && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches))
11
+ ? PALETTE_DARK
12
+ : PALETTE_LIGHT;
13
+ }
14
+
15
+ function themeDefaults(ctx) {
16
+ const grid = cssVar('--border') || '#ece9e4';
17
+ // axis/legend/title text: --fg-2 reads clearly on dark; --muted was too dim
18
+ const tick = cssVar('--fg-2') || '#57534e';
19
+ const fontFamily = cssVar('--sans') || 'sans-serif';
20
+ return { grid, tick, fontFamily };
21
+ }
22
+
23
+ // Apply theme defaults only where unset (deep, conservative).
24
+ function applyChartTheme(config, ctx) {
25
+ const { grid, tick, fontFamily } = themeDefaults(ctx);
26
+ config.options = config.options || {};
27
+ const o = config.options;
28
+ if (o.responsive === undefined) o.responsive = true;
29
+ if (o.maintainAspectRatio === undefined) o.maintainAspectRatio = false;
30
+ if (o.animation === undefined) o.animation = false;
31
+ o.plugins = o.plugins || {};
32
+ o.plugins.legend = o.plugins.legend || {};
33
+ o.plugins.legend.labels = o.plugins.legend.labels || {};
34
+ if (o.plugins.legend.labels.color === undefined) o.plugins.legend.labels.color = tick;
35
+ if (o.plugins.legend.labels.font === undefined) o.plugins.legend.labels.font = { family: fontFamily, size: 12 };
36
+ if (o.plugins.title && o.plugins.title.color === undefined) o.plugins.title.color = tick;
37
+
38
+ const styleAxis = (ax) => {
39
+ if (!ax || typeof ax !== 'object') return;
40
+ ax.grid = ax.grid || {};
41
+ if (ax.grid.color === undefined) ax.grid.color = grid;
42
+ ax.ticks = ax.ticks || {};
43
+ if (ax.ticks.color === undefined) ax.ticks.color = tick;
44
+ if (ax.ticks.font === undefined) ax.ticks.font = { family: fontFamily, size: 12 };
45
+ };
46
+ o.scales = o.scales || {};
47
+ // Chart.js v3+ uses named scales (x/y/r). Style any present; for simplified
48
+ // configs we pre-create x/y below.
49
+ for (const key of Object.keys(o.scales)) styleAxis(o.scales[key]);
50
+ return config;
51
+ }
52
+
53
+ function simplifiedToConfig(block, ctx) {
54
+ const pal = palette();
55
+ const kind = block.kind || 'bar';
56
+ const series = block.series || [];
57
+ const datasets = series.map((s, i) => {
58
+ const color = s.color || pal[i % pal.length];
59
+ const ds = {
60
+ label: s.label !== undefined ? s.label : `Series ${i + 1}`,
61
+ data: s.data || [],
62
+ };
63
+ if (kind === 'line') {
64
+ ds.borderColor = color;
65
+ ds.backgroundColor = color;
66
+ ds.tension = 0.25;
67
+ ds.pointRadius = 3;
68
+ } else if (kind === 'pie' || kind === 'doughnut') {
69
+ ds.backgroundColor = (s.data || []).map((_d, di) => s.color || pal[di % pal.length]);
70
+ ds.borderColor = cssVar('--card') || '#fff';
71
+ ds.borderWidth = 2;
72
+ } else if (kind === 'radar') {
73
+ ds.borderColor = color;
74
+ ds.backgroundColor = color + '33';
75
+ ds.pointBackgroundColor = color;
76
+ } else {
77
+ ds.backgroundColor = color;
78
+ ds.borderColor = color;
79
+ }
80
+ return ds;
81
+ });
82
+ const config = {
83
+ type: kind,
84
+ data: { labels: block.labels || [], datasets },
85
+ options: {},
86
+ };
87
+ if (block.title) {
88
+ config.options.plugins = { title: { display: true, text: block.title } };
89
+ }
90
+ // pre-create x/y scales for cartesian kinds so theme styling applies
91
+ if (kind === 'bar' || kind === 'line' || kind === 'scatter') {
92
+ config.options.scales = { x: {}, y: {} };
93
+ }
94
+ return config;
95
+ }
96
+
97
+ function renderChart(block, ctx, blockId) {
98
+ const height = clampHeight(block.height, 320);
99
+ const wrap = el('div', { class: 'blk-chart' });
100
+ wrap.style.height = height + 'px';
101
+ const stage = el('div', { class: 'blk-chart-stage' });
102
+ const canvas = el('canvas');
103
+ stage.append(canvas);
104
+ wrap.append(stage);
105
+
106
+ let chartInst = null;
107
+ let chartBadges = [];
108
+ let naturalSize = null;
109
+
110
+ const openFor = (target) => (anchor) =>
111
+ ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, anchor);
112
+ function makeBadge(count, cls, onClick) {
113
+ const b = el('span', { class: 'blk-chart-badge ' + cls }, String(count));
114
+ b.addEventListener('mousedown', (e) => e.stopPropagation());
115
+ b.addEventListener('click', (e) => { e.stopPropagation(); e.preventDefault(); onClick(b); });
116
+ return b;
117
+ }
118
+ // Rebuild the chart's comment badges: one at each annotated DATA POINT
119
+ // (positioned from the Chart.js element geometry) plus a top-right badge for
120
+ // whole-chart comments. Each badge opens that comment's popover on click.
121
+ // Runs on annotation change (onBadgeRefresh) and on chart (re)render/resize
122
+ // (afterRender plugin), so badges stay pinned to their points.
123
+ function syncChartBadges() {
124
+ if (!ctx.annotate) return;
125
+ for (const b of chartBadges) b.remove();
126
+ chartBadges = [];
127
+ const groups = new Map(); // "di:index" -> { target, count }
128
+ let blockCount = 0, blockTarget = null;
129
+ for (const a of ctx.annotate.list()) {
130
+ if (a.blockId !== blockId) continue;
131
+ const t = a.target || {};
132
+ if (t.kind === 'chart-element' && typeof t.datasetIndex === 'number' && typeof t.index === 'number') {
133
+ const k = t.datasetIndex + ':' + t.index;
134
+ const g = groups.get(k) || { target: t, count: 0 };
135
+ g.count++; groups.set(k, g);
136
+ } else {
137
+ blockCount++; blockTarget = blockTarget || t;
138
+ }
139
+ }
140
+ if (chartInst) {
141
+ for (const { target, count } of groups.values()) {
142
+ let elem;
143
+ try { const m = chartInst.getDatasetMeta(target.datasetIndex); elem = m && m.data[target.index]; } catch (_) {}
144
+ if (!elem) continue;
145
+ let pos; try { pos = elem.tooltipPosition(); } catch (_) { pos = { x: elem.x, y: elem.y }; }
146
+ if (!pos || !Number.isFinite(pos.x) || !Number.isFinite(pos.y)) continue;
147
+ const badge = makeBadge(count, 'blk-chart-badge-pt', openFor(target));
148
+ badge.style.left = (canvas.offsetLeft + pos.x) + 'px';
149
+ badge.style.top = (canvas.offsetTop + pos.y) + 'px';
150
+ stage.append(badge);
151
+ chartBadges.push(badge);
152
+ }
153
+ }
154
+ if (blockCount > 0) {
155
+ const badge = makeBadge(blockCount, 'blk-chart-badge-corner', openFor(blockTarget || { kind: 'block', label: 'chart' }));
156
+ wrap.append(badge);
157
+ chartBadges.push(badge);
158
+ }
159
+ }
160
+
161
+ if (ctx.annotate && ctx.annotate.onBadgeRefresh) ctx.annotate.onBadgeRefresh(syncChartBadges);
162
+ loadChart().then((Chart) => {
163
+ let config = block.config
164
+ ? JSON.parse(JSON.stringify(block.config))
165
+ : simplifiedToConfig(block, ctx);
166
+ config = applyChartTheme(config, ctx);
167
+ // reposition our DOM badges after every (re)render/resize of the chart
168
+ config.plugins = Array.isArray(config.plugins) ? config.plugins : [];
169
+ config.plugins.push({ id: 'relayChartBadges', afterRender: () => syncChartBadges() });
170
+ try {
171
+ chartInst = new Chart(canvas.getContext('2d'), config);
172
+ chartRegistry.push({ chart: chartInst });
173
+ // Chart.js stays responsive inside a stage whose dimensions the shared
174
+ // viewer controls. This gives charts the same bounded, eased wheel zoom
175
+ // as diagrams/images while retaining sharp redraws at every scale.
176
+ naturalSize = {
177
+ w: Math.max(1, Math.round(stage.getBoundingClientRect().width || wrap.clientWidth || 640)),
178
+ h: height,
179
+ };
180
+ attachViewer(wrap, {
181
+ zoomEl: stage,
182
+ natural: () => naturalSize,
183
+ fluidFit: true,
184
+ scaleHeight: true,
185
+ label: 'chart',
186
+ comment: wholeBlockComment(ctx, blockId, 'chart'),
187
+ });
188
+ } catch (err) {
189
+ wrap.replaceChildren(el('div', { class: 'blk-error' }, 'Chart error: ' + (err && err.message ? err.message : String(err))));
190
+ return;
191
+ }
192
+ // hover -> pointer cursor on a hit
193
+ canvas.addEventListener('mousemove', (e) => {
194
+ if (ctx.canComment === false) { canvas.style.cursor = 'default'; return; }
195
+ const hits = chartInst.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
196
+ canvas.style.cursor = hits.length ? 'pointer' : 'default';
197
+ });
198
+ canvas.addEventListener('click', (e) => {
199
+ if (!ctx.annotate || ctx.canComment === false) return;
200
+ const hits = chartInst.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
201
+ if (!hits.length) return;
202
+ const { datasetIndex, index } = hits[0];
203
+ const ds = config.data.datasets[datasetIndex] || {};
204
+ const label = config.data.labels ? config.data.labels[index] : undefined;
205
+ const value = Array.isArray(ds.data) ? ds.data[index] : undefined;
206
+ ctx.annotate.openExternal(
207
+ {
208
+ blockId,
209
+ questionId: ctx.questionId,
210
+ target: { kind: 'chart-element', datasetIndex, index, label: label !== undefined ? String(label) : '', value },
211
+ },
212
+ wrap
213
+ );
214
+ });
215
+ syncChartBadges();
216
+ }).catch((err) => {
217
+ wrap.replaceChildren(el('div', { class: 'blk-error' }, 'Chart error: ' + (err && err.message ? err.message : String(err))));
218
+ });
219
+
220
+ return wrap;
221
+ }
222
+
@@ -0,0 +1,138 @@
1
+ // ---------- code tinter (lightweight, zero-dependency, offline) ----------
2
+ // Per language we record its comment style(s), whether it has backtick
3
+ // strings, and its keyword set. From those a single alternation regex tints
4
+ // comments / strings / numbers / keywords in one pass. Unknown languages
5
+ // render as plain escaped text; css / html / xml get bespoke patterns.
6
+ // Mirrors the wide-compat goal: no library, works in every browser offline.
7
+ const LANGS = {
8
+ 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' },
9
+ 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' },
10
+ json: { kw: 'true false null' },
11
+ 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' },
12
+ 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' },
13
+ 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' },
14
+ 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' },
15
+ 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' },
16
+ 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' },
17
+ 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' },
18
+ 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' },
19
+ 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' },
20
+ 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' },
21
+ 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' },
22
+ 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' },
23
+ yaml: { hash: true, kw: 'true false null yes no on off' },
24
+ toml: { hash: true, kw: 'true false' },
25
+ 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' },
26
+ css: { special: 'css' },
27
+ html: { special: 'html' },
28
+ };
29
+ const LANG_ALIAS = {
30
+ javascript: 'js', node: 'js', mjs: 'js', cjs: 'js', jsx: 'js',
31
+ typescript: 'ts', tsx: 'ts',
32
+ shell: 'sh', bash: 'sh', zsh: 'sh', console: 'sh',
33
+ python: 'py', py3: 'py',
34
+ golang: 'go', rs: 'rust', 'c++': 'cpp', cc: 'cpp', cxx: 'cpp', hpp: 'cpp', 'c#': 'csharp', cs: 'csharp',
35
+ rb: 'ruby', kt: 'kotlin',
36
+ yml: 'yaml', xml: 'html', svg: 'html', htm: 'html',
37
+ jsonc: 'json', json5: 'json',
38
+ };
39
+
40
+ function tintCode(code, lang) {
41
+ const key0 = (lang || '').toLowerCase().trim();
42
+ const cfg = LANGS[LANG_ALIAS[key0] || key0];
43
+ if (!cfg) return esc(code); // unknown lang -> plain
44
+
45
+ // Build ONE alternation regex with a parallel classes[] so group g (1-based)
46
+ // maps to classes[g-1]. Each pushed source is wrapped in exactly one
47
+ // capturing group; the source bodies use only non-capturing groups.
48
+ const parts = [];
49
+ const classes = [];
50
+ const push = (src, cls) => { parts.push('(' + src + ')'); classes.push(cls); };
51
+ if (cfg.special === 'css') {
52
+ push(/\/\*[\s\S]*?\*\//.source, 'com');
53
+ push(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/.source, 'str');
54
+ push(/[A-Za-z-]+(?=\s*:)/.source, 'kw');
55
+ push(/\b\d+(?:\.\d+)?(?:px|em|rem|%|vh|vw|s|ms|deg)?\b/.source, 'num');
56
+ } else if (cfg.special === 'html') {
57
+ push(/<!--[\s\S]*?-->/.source, 'com');
58
+ push(/<\/?[A-Za-z][\w-]*|\/?>/.source, 'kw');
59
+ push(/"[^"]*"/.source, 'str');
60
+ } else {
61
+ if (cfg.c) { push(/\/\*[\s\S]*?\*\//.source, 'com'); push(/\/\/[^\n]*/.source, 'com'); }
62
+ if (cfg.hash) push(/#[^\n]*/.source, 'com');
63
+ if (cfg.sql) push(/--[^\n]*/.source, 'com');
64
+ push((cfg.tmpl
65
+ ? /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/
66
+ : /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/).source, 'str');
67
+ push(/\b(?:0x[\da-fA-F]+|\d+(?:\.\d+)?)\b/.source, 'num');
68
+ let kws = (cfg.kw || '').split(' ').filter(Boolean);
69
+ if (cfg.kwi) kws = kws.concat(kws.map((k) => k.toUpperCase())); // SQL: also UPPERCASE
70
+ if (kws.length) push('\\b(?:' + kws.join('|') + ')\\b', 'kw');
71
+ }
72
+ const rx = new RegExp(parts.join('|'), 'g');
73
+ let out = '';
74
+ let last = 0;
75
+ let m;
76
+ while ((m = rx.exec(code))) {
77
+ out += esc(code.slice(last, m.index));
78
+ let cls = null;
79
+ for (let g = 1; g < m.length; g++) {
80
+ if (m[g] !== undefined) {
81
+ cls = classes[g - 1];
82
+ break;
83
+ }
84
+ }
85
+ out += cls ? '<span class="tok-' + cls + '">' + esc(m[0]) + '</span>' : esc(m[0]);
86
+ last = m.index + m[0].length;
87
+ if (m[0].length === 0) rx.lastIndex++;
88
+ }
89
+ out += esc(code.slice(last));
90
+ return out;
91
+ }
92
+
93
+ // A line-number gutter for `text` (non-selectable so a select-to-comment grabs
94
+ // only the code, not the numbers). When annotation is on, each number becomes a
95
+ // hover/click target to comment on that exact line (kind:'code-line'); the
96
+ // numbers still don't enter a text selection. `startAt` default 1.
97
+ function lineGutter(text, startAt, ctx, blockId, filename) {
98
+ const n = Math.max(1, String(text).replace(/\n+$/, '').split('\n').length);
99
+ const annotate = ctx && ctx.annotate;
100
+ const g = el('div', { class: 'blk-gutter' + (annotate ? ' blk-gutter-c' : ''), 'aria-hidden': annotate ? null : 'true' });
101
+ for (let i = 0; i < n; i++) {
102
+ const ln = (startAt || 1) + i;
103
+ const lineEl = el('div', { class: 'blk-gutterline' }, String(ln));
104
+ if (annotate) {
105
+ annotate.register(lineEl, {
106
+ blockId, questionId: ctx.questionId,
107
+ target: { kind: 'code-line', line: ln, file: filename || '' },
108
+ });
109
+ }
110
+ g.append(lineEl);
111
+ }
112
+ return g;
113
+ }
114
+
115
+ function renderCode(block, ctx, blockId) {
116
+ // Drop a single trailing newline so the last source line isn't rendered as
117
+ // an empty row the gutter has no number for (files usually end in "\n").
118
+ const raw = (block.code || '').replace(/\n$/, '');
119
+ const code = el('code');
120
+ code.innerHTML = tintCode(raw, block.lang);
121
+ const pre = el('pre', { class: 'blk-pre', 'data-lang': block.lang || '' }, code);
122
+ const row = el('div', { class: 'blk-coderow' }, lineGutter(raw, 1, ctx, blockId, block.filename), pre);
123
+ const wrap = el('div', { class: 'blk-codewrap' });
124
+ // Optional file-name + language header above the code.
125
+ if (block.filename || block.lang) {
126
+ wrap.append(el('div', { class: 'blk-codehead' },
127
+ el('span', { class: 'blk-codename' }, block.filename || ''),
128
+ el('span', { class: 'blk-codelang' }, block.lang || '')
129
+ ));
130
+ }
131
+ wrap.append(row);
132
+ // select-to-comment on the code text (like markdown), plus a whole-block
133
+ // comment + full-screen via the shared viewer toolbar
134
+ ctx && ctx.annotate && ctx.annotate.enableTextSelection(pre, { blockId, questionId: ctx.questionId });
135
+ attachViewer(wrap, { zoomEl: null, label: 'code', comment: wholeBlockComment(ctx, blockId, 'code') });
136
+ return wrap;
137
+ }
138
+
@@ -0,0 +1,82 @@
1
+ // ---------- compare (before/after image slider) ----------
2
+ // The "after" image is the base layer (defines the frame size); the "before"
3
+ // image sits in an overflow-clipped layer whose width the divider drives, so
4
+ // dragging reveals more of one image and less of the other.
5
+ function renderCompare(block, ctx, blockId) {
6
+ const wrap = el('div', { class: 'blk-comparewrap' });
7
+ const frame = el('div', { class: 'cmp-frame' });
8
+ if (block.height) frame.style.maxHeight = clampHeight(block.height, 1200) + 'px';
9
+ const afterImg = el('img', { class: 'cmp-img', src: block.after, alt: block.afterLabel || 'after', draggable: 'false', loading: 'lazy' });
10
+ const beforeImg = el('img', { class: 'cmp-img cmp-img-before', src: block.before, alt: block.beforeLabel || 'before', draggable: 'false', loading: 'lazy' });
11
+ const beforeLayer = el('div', { class: 'cmp-before' }, beforeImg);
12
+ const handle = el('div', { class: 'cmp-handle', tabindex: '0', role: 'slider', 'aria-label': 'Compare before and after' },
13
+ el('div', { class: 'cmp-handle-grip' }, '⟺'));
14
+ frame.append(
15
+ afterImg, beforeLayer, handle,
16
+ el('span', { class: 'cmp-tag cmp-tag-before' }, block.beforeLabel || 'Before'),
17
+ el('span', { class: 'cmp-tag cmp-tag-after' }, block.afterLabel || 'After')
18
+ );
19
+ wrap.append(frame);
20
+
21
+ let pos = 50;
22
+ const apply = () => { beforeLayer.style.width = pos + '%'; handle.style.left = pos + '%'; };
23
+ // pin the before image to the frame's pixel width so the clip reveals it in
24
+ // place (rather than squishing it as the clip narrows)
25
+ const sizeBefore = () => { beforeImg.style.width = frame.clientWidth + 'px'; };
26
+ const refresh = () => { sizeBefore(); apply(); };
27
+ if (afterImg.complete && afterImg.naturalWidth) refresh();
28
+ else afterImg.addEventListener('load', refresh, { once: true });
29
+ window.addEventListener('resize', sizeBefore);
30
+
31
+ let dragging = false;
32
+ let dragMoved = false;
33
+ let dragStartX = 0;
34
+ const setFromX = (clientX) => {
35
+ const r = frame.getBoundingClientRect();
36
+ if (r.width) { pos = Math.max(0, Math.min(100, ((clientX - r.left) / r.width) * 100)); apply(); }
37
+ };
38
+ frame.addEventListener('pointerdown', (e) => {
39
+ const handleTarget = e.target.closest('.cmp-handle');
40
+ if (!handleTarget || frame._rlyRegionMode) return;
41
+ dragging = true;
42
+ dragMoved = false;
43
+ dragStartX = e.clientX;
44
+ try { frame.setPointerCapture(e.pointerId); } catch (_) {}
45
+ });
46
+ frame.addEventListener('pointermove', (e) => {
47
+ if (!dragging || frame._rlyRegionMode || frame._rlyRegionSelecting) return;
48
+ if (Math.abs(e.clientX - dragStartX) > 3) dragMoved = true;
49
+ if (dragMoved) { setFromX(e.clientX); e.preventDefault(); }
50
+ });
51
+ frame.addEventListener('pointerup', (e) => {
52
+ if (dragging && !dragMoved && !frame._rlyRegionMode && !frame._rlyRegionSelecting) setFromX(e.clientX);
53
+ dragging = false;
54
+ });
55
+ frame.addEventListener('pointercancel', () => { dragging = false; dragMoved = false; });
56
+ handle.addEventListener('keydown', (e) => {
57
+ if (e.key === 'ArrowLeft') { pos = Math.max(0, pos - 2); apply(); e.preventDefault(); }
58
+ else if (e.key === 'ArrowRight') { pos = Math.min(100, pos + 2); apply(); e.preventDefault(); }
59
+ });
60
+ let region = null;
61
+ if (ctx.annotate && ctx.canComment !== false) {
62
+ frame.title = 'Drag to draw a comment area · drag the divider handle to compare';
63
+ region = enableImageRegions({
64
+ host: frame,
65
+ surface: frame,
66
+ panHost: frame,
67
+ sourceForSide: (side) => side === 'before' ? beforeImg : afterImg,
68
+ sideAtPoint: (x) => (x * 100 <= pos ? 'before' : 'after'),
69
+ ctx,
70
+ blockId,
71
+ label: 'Comparison',
72
+ });
73
+ }
74
+ attachViewer(wrap, {
75
+ zoomEl: null,
76
+ label: 'comparison',
77
+ comment: wholeBlockComment(ctx, blockId, 'comparison'),
78
+ region,
79
+ });
80
+ return wrap;
81
+ }
82
+