@khanglvm/relay 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +39 -4
  3. package/schema/spec.v1.json +1368 -0
  4. package/src/a2ui/compile.js +2 -0
  5. package/src/cli/args.js +46 -0
  6. package/src/cli/ask.js +12 -0
  7. package/src/cli/boards.js +326 -0
  8. package/src/cli/config.js +56 -0
  9. package/src/cli/context.js +13 -0
  10. package/src/cli/git.js +183 -0
  11. package/src/cli/help.js +90 -0
  12. package/src/cli/index.js +103 -0
  13. package/src/cli/install.js +197 -0
  14. package/src/cli/io.js +186 -0
  15. package/src/cli/mcp.js +94 -0
  16. package/src/cli/share.js +45 -0
  17. package/src/cli/skill.js +192 -0
  18. package/src/cli/upgrade.js +130 -0
  19. package/src/cli/wait.js +172 -0
  20. package/src/file-preview.js +1 -1
  21. package/src/index.js +104 -0
  22. package/src/link.js +1 -0
  23. package/src/mcp-ui/board/block-ctx.js +43 -0
  24. package/src/mcp-ui/board/bridge.js +165 -0
  25. package/src/mcp-ui/board/controls.js +310 -0
  26. package/src/mcp-ui/board/core.js +20 -0
  27. package/src/mcp-ui/board/lifecycle.js +118 -0
  28. package/src/mcp-ui/board/normalize.js +95 -0
  29. package/src/mcp-ui/board/render.js +200 -0
  30. package/src/mcp-ui/board/state.js +106 -0
  31. package/src/mcp-ui/board/vendors.js +86 -0
  32. package/src/mcp.js +15 -21
  33. package/src/{server.js → server/board.js} +17 -781
  34. package/src/server/files.js +141 -0
  35. package/src/server/http.js +114 -0
  36. package/src/server/index.js +2 -0
  37. package/src/server/page.js +183 -0
  38. package/src/server/paths.js +7 -0
  39. package/src/server/result.js +58 -0
  40. package/src/server/reviews.js +41 -0
  41. package/src/server/sanitize.js +231 -0
  42. package/src/spec/blocks/a2ui.js +25 -0
  43. package/src/spec/blocks/chart.js +49 -0
  44. package/src/spec/blocks/code.js +38 -0
  45. package/src/spec/blocks/diagram.js +39 -0
  46. package/src/spec/blocks/git-conflict.js +106 -0
  47. package/src/spec/blocks/image.js +32 -0
  48. package/src/spec/blocks/index.js +33 -0
  49. package/src/spec/blocks/markdown.js +13 -0
  50. package/src/spec/blocks/pdf.js +38 -0
  51. package/src/spec/blocks/table.js +122 -0
  52. package/src/spec/blocks/video.js +68 -0
  53. package/src/spec/blocks/widgets.js +98 -0
  54. package/src/spec/constants.js +65 -0
  55. package/src/spec/index.js +5 -0
  56. package/src/spec/normalize.js +285 -0
  57. package/src/spec/ready.js +106 -0
  58. package/src/spec/schema.js +182 -0
  59. package/src/spec/sources.js +83 -0
  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/a2ui/compile.d.ts +40 -0
  110. package/types/index.d.ts +181 -0
  111. package/types/mcp.d.ts +31 -0
  112. package/types/spec/blocks/a2ui.d.ts +4 -0
  113. package/types/spec/blocks/chart.d.ts +4 -0
  114. package/types/spec/blocks/code.d.ts +10 -0
  115. package/types/spec/blocks/diagram.d.ts +15 -0
  116. package/types/spec/blocks/git-conflict.d.ts +7 -0
  117. package/types/spec/blocks/image.d.ts +5 -0
  118. package/types/spec/blocks/index.d.ts +30 -0
  119. package/types/spec/blocks/markdown.d.ts +5 -0
  120. package/types/spec/blocks/pdf.d.ts +4 -0
  121. package/types/spec/blocks/table.d.ts +9 -0
  122. package/types/spec/blocks/video.d.ts +4 -0
  123. package/types/spec/blocks/widgets.d.ts +21 -0
  124. package/types/spec/constants.d.ts +67 -0
  125. package/types/spec/index.d.ts +4 -0
  126. package/types/spec/normalize.d.ts +17 -0
  127. package/types/spec/ready.d.ts +1 -0
  128. package/types/spec/schema.d.ts +1171 -0
  129. package/types/spec/sources.d.ts +14 -0
  130. package/types/store.d.ts +29 -0
  131. package/types/ui/manifest.d.ts +62 -0
  132. package/types/util.d.ts +6 -0
  133. package/src/cli.js +0 -1766
  134. package/src/mcp-ui/board.js +0 -1162
  135. package/src/spec.js +0 -1222
  136. package/src/ui/annotate.js +0 -1055
  137. package/src/ui/app.js +0 -1643
  138. package/src/ui/blocks.js +0 -3260
@@ -0,0 +1,43 @@
1
+ // ---------- lazy vendor loaders (cached promises) ----------
2
+ let chartPromise = null;
3
+ function loadChart() {
4
+ if (window.Chart) return Promise.resolve(window.Chart);
5
+ if (chartPromise) return chartPromise;
6
+ chartPromise = new Promise((resolve, reject) => {
7
+ const s = document.createElement('script');
8
+ s.src = '/vendor/chart.umd.js';
9
+ s.onload = () => (window.Chart ? resolve(window.Chart) : reject(new Error('Chart.js failed to load')));
10
+ s.onerror = () => reject(new Error('Chart.js failed to load'));
11
+ document.head.appendChild(s);
12
+ });
13
+ return chartPromise;
14
+ }
15
+
16
+ let mermaidPromise = null;
17
+ function loadMermaid() {
18
+ if (window.mermaid) return Promise.resolve(window.mermaid);
19
+ if (mermaidPromise) return mermaidPromise;
20
+ mermaidPromise = new Promise((resolve, reject) => {
21
+ const s = document.createElement('script');
22
+ s.src = '/vendor/mermaid.min.js';
23
+ s.onload = () => (window.mermaid ? resolve(window.mermaid) : reject(new Error('Mermaid failed to load')));
24
+ s.onerror = () => reject(new Error('Mermaid failed to load'));
25
+ document.head.appendChild(s);
26
+ });
27
+ return mermaidPromise;
28
+ }
29
+
30
+ let vizPromise = null;
31
+ function loadViz() {
32
+ if (window.Viz) return Promise.resolve(window.Viz);
33
+ if (vizPromise) return vizPromise;
34
+ vizPromise = new Promise((resolve, reject) => {
35
+ const s = document.createElement('script');
36
+ s.src = '/vendor/viz-standalone.js';
37
+ s.onload = () => (window.Viz ? resolve(window.Viz) : reject(new Error('Graphviz failed to load')));
38
+ s.onerror = () => reject(new Error('Graphviz failed to load'));
39
+ document.head.appendChild(s);
40
+ });
41
+ return vizPromise;
42
+ }
43
+
@@ -0,0 +1,43 @@
1
+ // ---------- video (YouTube/Vimeo embed, local stream, or direct URL) ----------
2
+ function renderVideo(block, ctx, blockId) {
3
+ const wrap = el('div', { class: 'blk-videowrap' });
4
+ let media;
5
+ if (block.provider === 'youtube') {
6
+ const q = block.start ? '?start=' + block.start : '';
7
+ media = el('iframe', {
8
+ class: 'blk-video-embed',
9
+ src: 'https://www.youtube-nocookie.com/embed/' + encodeURIComponent(block.videoId) + q,
10
+ title: block.title || 'YouTube video',
11
+ frameborder: '0',
12
+ allow: 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share',
13
+ referrerpolicy: 'strict-origin-when-cross-origin',
14
+ allowfullscreen: 'true',
15
+ loading: 'lazy',
16
+ });
17
+ } else if (block.provider === 'vimeo') {
18
+ media = el('iframe', {
19
+ class: 'blk-video-embed',
20
+ src: 'https://player.vimeo.com/video/' + encodeURIComponent(block.videoId),
21
+ title: block.title || 'Vimeo video',
22
+ frameborder: '0',
23
+ allow: 'autoplay; fullscreen; picture-in-picture',
24
+ allowfullscreen: 'true',
25
+ loading: 'lazy',
26
+ });
27
+ } else {
28
+ // local file (served via /video/b/<id>) or a direct http(s) media URL
29
+ const src = block.hasFile ? '/video/b/' + encodeURIComponent(blockId) : block.src;
30
+ media = el('video', { class: 'blk-video', controls: 'true', preload: 'metadata', playsinline: 'true' });
31
+ if (block.title) media.setAttribute('title', block.title);
32
+ const source = el('source', { src });
33
+ if (block.mime) source.setAttribute('type', block.mime);
34
+ media.append(source);
35
+ media.append(document.createTextNode('Your browser cannot play this video.'));
36
+ }
37
+ wrap.append(media);
38
+ if (block.title) wrap.append(el('div', { class: 'blk-videocap' }, block.title));
39
+ // whole-block comment + the comment pin (no zoom/full-screen for media)
40
+ attachViewer(wrap, { zoomEl: null, label: 'video', comment: wholeBlockComment(ctx, blockId, 'video') });
41
+ return wrap;
42
+ }
43
+
@@ -0,0 +1,146 @@
1
+ // ---------- viewer controls (zoom / fit / full-screen) ----------
2
+ // Large diagrams get squeezed to the column width; these controls let the
3
+ // user zoom (buttons or cmd/ctrl+wheel) and expand any visual block into a
4
+ // full-screen overlay. An overlay — NOT the native Fullscreen API — keeps
5
+ // the annotation pins/badges/popover usable while expanded (they live on
6
+ // <body>, which native fullscreen would hide).
7
+ let fullOpen = null; // container currently expanded
8
+ // full-screen content insets — must mirror the .blk-full padding in blocks.css
9
+ // so the fit-to-screen scale clears the fixed toolbar + leaves a small margin.
10
+ const FULL_PAD_X = 24, FULL_PAD_TOP = 44, FULL_PAD_BOTTOM = 24;
11
+ // Wheel/pinch zoom is delta-proportional and animated. The old fixed 15% jump
12
+ // ran once for every wheel event, so a high-frequency trackpad gesture could
13
+ // compound to several hundred percent almost instantly. Cap the contribution
14
+ // of one event (mouse wheels often report ±100px) and ease toward the gesture's
15
+ // accumulated target at most once per animation frame.
16
+ const WHEEL_ZOOM_SENSITIVITY = 0.003;
17
+ const WHEEL_ZOOM_MAX_DELTA = 20;
18
+ const WHEEL_ZOOM_EASE = 0.24;
19
+ const WHEEL_ZOOM_EPSILON = 0.001;
20
+
21
+ // Toolbar icons: full-screen (4-corner expand) and a speech-bubble for the
22
+ // "comment on the whole block" button. Zoom is both cmd/ctrl+wheel AND
23
+ // explicit −/+ buttons (the % doubles as a reset-to-fit button).
24
+ const ICON_EXPAND =
25
+ '<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">' +
26
+ '<path d="M3 9V3h6M10 10 3 3M15 3h6v6M14 10l7-7M9 21H3v-6M10 14l-7 7M21 15v6h-6M14 14l7 7"/></svg>';
27
+ const ICON_COMMENT =
28
+ '<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">' +
29
+ '<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>';
30
+ const ICON_REGION =
31
+ '<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">' +
32
+ '<rect x="3" y="4" width="14" height="12" rx="2" stroke-dasharray="3 2"/>' +
33
+ '<path d="M14 14.5h6.5v4H18l-2.5 2v-2H14z" fill="currentColor" stroke="none"/></svg>';
34
+ const ICON_EYE =
35
+ '<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">' +
36
+ '<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>';
37
+
38
+ function exitFull() {
39
+ if (!fullOpen) return;
40
+ const c = fullOpen;
41
+ if (c._rlyStopWheelZoom) c._rlyStopWheelZoom();
42
+ c.classList.remove('blk-full');
43
+ document.body.classList.remove('blk-full-open');
44
+ const btn = c.querySelector('.blk-tools .tool-full');
45
+ if (btn) btn.innerHTML = ICON_EXPAND;
46
+ fullOpen = null;
47
+ window.dispatchEvent(new Event('resize'));
48
+ if (c._rlyZoom) c._rlyZoom.reapply(); // restore the compact inline height cap
49
+ }
50
+ document.addEventListener('keydown', (e) => {
51
+ if (e.key === 'Escape' && fullOpen && !document.querySelector('.rly-file-dialog[open]')) exitFull();
52
+ });
53
+
54
+ // Enter full-screen for a viewer container (shared by the toolbar button and
55
+ // the markdown reference-link → modal path).
56
+ function enterFull(container) {
57
+ if (fullOpen === container) return;
58
+ exitFull();
59
+ if (container._rlyStopWheelZoom) container._rlyStopWheelZoom();
60
+ container.classList.add('blk-full');
61
+ document.body.classList.add('blk-full-open');
62
+ fullOpen = container;
63
+ const btn = container.querySelector('.blk-tools .tool-full');
64
+ if (btn) btn.textContent = '✕';
65
+ window.dispatchEvent(new Event('resize'));
66
+ if (container._rlyZoom) container._rlyZoom.reapply();
67
+ }
68
+
69
+ // CSS.escape fallback for attribute-selector building from a block id/ref.
70
+ function cssEsc(s) {
71
+ return window.CSS && CSS.escape ? CSS.escape(String(s)) : String(s).replace(/["\\\]]/g, '\\$&');
72
+ }
73
+
74
+ // Open a block as a modal: full-screen its viewer if it has one (chart, image,
75
+ // diagram, table, compare, code…); otherwise scroll to it and flash. `host` is
76
+ // the .blk[data-block-id] wrapper. Returns true if it found something to show.
77
+ function openFullEl(host) {
78
+ if (!host) return false;
79
+ const viewer = host.classList.contains('blk-viewer') ? host : host.querySelector('.blk-viewer');
80
+ // Visuals open as a full-screen modal — context-safe (an overlay; × returns
81
+ // to the exact spot). Non-modal blocks (kpi/markdown/table-less) have no
82
+ // viewer, so we jump + highlight AND show a "↩ Back" button so the user can
83
+ // return after the jump — no lost context across the data↔question distance.
84
+ if (viewer && viewer._rlyTools) { enterFull(viewer); return true; }
85
+ const fromY = window.scrollY || window.pageYOffset || 0;
86
+ host.scrollIntoView({ behavior: 'smooth', block: 'center' });
87
+ host.classList.remove('rly-refflash');
88
+ void host.offsetWidth;
89
+ host.classList.add('rly-refflash');
90
+ setTimeout(() => host.classList.remove('rly-refflash'), 1200);
91
+ showRefBack(fromY);
92
+ return true;
93
+ }
94
+
95
+ // A floating "↩ Back" pill that returns to the pre-jump scroll position. Self-
96
+ // removes once the user is back near where they started, or after a timeout.
97
+ let refBackBtn = null;
98
+ function showRefBack(fromY) {
99
+ if (refBackBtn) refBackBtn.remove();
100
+ const btn = el('button', { class: 'rly-refback', type: 'button', title: 'Back to where you were' }, '↩ Back');
101
+ const cleanup = () => { btn.remove(); window.removeEventListener('scroll', onScroll); if (refBackBtn === btn) refBackBtn = null; };
102
+ const onScroll = () => { if (Math.abs((window.scrollY || 0) - fromY) < 120) cleanup(); };
103
+ btn.addEventListener('click', () => { window.scrollTo({ top: fromY, behavior: 'smooth' }); cleanup(); });
104
+ window.addEventListener('scroll', onScroll, { passive: true });
105
+ document.body.append(btn);
106
+ refBackBtn = btn;
107
+ setTimeout(() => { if (refBackBtn === btn) cleanup(); }, 12000);
108
+ }
109
+ function openFull(blockId) {
110
+ return openFullEl(document.querySelector('[data-block-id="' + cssEsc(blockId) + '"]'));
111
+ }
112
+
113
+ // Delegated handler for markdown reference links (data-rly-ref / data-rly-refid).
114
+ function initRefLinks() {
115
+ if (window.__relayRefLinksReady) return;
116
+ window.__relayRefLinksReady = true;
117
+ const open = (a) => {
118
+ const host = a.dataset.rlyRefid
119
+ ? document.querySelector('[data-block-id="' + cssEsc(a.dataset.rlyRefid) + '"]')
120
+ : document.querySelector('[data-block-ref="' + cssEsc(a.dataset.rlyRef) + '"]');
121
+ if (host) openFullEl(host);
122
+ else fileToast('Referenced visual not found on this board', 'err');
123
+ };
124
+ document.addEventListener('click', (e) => {
125
+ const a = e.target.closest ? e.target.closest('a.rly-reflink') : null;
126
+ if (!a) return;
127
+ e.preventDefault();
128
+ open(a);
129
+ });
130
+ document.addEventListener('keydown', (e) => {
131
+ if (e.key !== 'Enter' && e.key !== ' ' && e.key !== 'Spacebar') return;
132
+ const a = e.target.closest ? e.target.closest('a.rly-reflink') : null;
133
+ if (!a) return;
134
+ e.preventDefault();
135
+ open(a);
136
+ });
137
+ }
138
+
139
+ // Drag-to-pan: grab anywhere on a scrollable visual (a tall/zoomed diagram or
140
+ // oversized image) and drag to move across it, instead of hunting for the
141
+ // scrollbars. Self-gates on overflow, so charts and html iframes — which are
142
+ // always sized to fit — never engage. Annotation on diagrams/images is
143
+ // hover-pin based (not a node click), so a pan can't create a stray
144
+ // annotation; a real drag still swallows the trailing click as a guard.
145
+ // Returns a refresh() the viewer calls whenever content size changes (zoom,
146
+ // full-screen, re-render) so the grab affordance tracks pannability.
@@ -0,0 +1,324 @@
1
+ function enablePan(scrollEl) {
2
+ let pending = false, active = false;
3
+ let sx = 0, sy = 0, sl = 0, st = 0, pid = null;
4
+ const THRESH = 4; // px before a press becomes a drag (keeps clicks clickable)
5
+
6
+ const pannable = () =>
7
+ scrollEl.scrollWidth - scrollEl.clientWidth > 1 ||
8
+ scrollEl.scrollHeight - scrollEl.clientHeight > 1;
9
+ const refresh = () => scrollEl.classList.toggle('blk-pannable', pannable());
10
+
11
+ scrollEl.addEventListener('pointerdown', (e) => {
12
+ const panGesture = e.button === 1 || (e.button === 0 && (!scrollEl._rlyHasRegions || viewerSpacePan));
13
+ if (!panGesture || scrollEl._rlyRegionMode || !pannable()) return;
14
+ // leave the toolbar, the diagram editor, and real controls interactive
15
+ if (e.target.closest && e.target.closest('.blk-tools, .blk-editor, button, a, input, textarea, select')) return;
16
+ pending = true; active = false;
17
+ sx = e.clientX; sy = e.clientY;
18
+ sl = scrollEl.scrollLeft; st = scrollEl.scrollTop;
19
+ pid = e.pointerId;
20
+ });
21
+ scrollEl.addEventListener('pointermove', (e) => {
22
+ if (!pending) return;
23
+ if (scrollEl._rlyRegionMode || scrollEl._rlyRegionSelecting) { pending = false; active = false; return; }
24
+ const dx = e.clientX - sx, dy = e.clientY - sy;
25
+ if (!active) {
26
+ if (Math.abs(dx) < THRESH && Math.abs(dy) < THRESH) return;
27
+ active = true;
28
+ scrollEl.classList.add('blk-panning');
29
+ try { scrollEl.setPointerCapture(pid); } catch (_) {}
30
+ }
31
+ e.preventDefault();
32
+ scrollEl.scrollLeft = sl - dx;
33
+ scrollEl.scrollTop = st - dy;
34
+ });
35
+ const end = () => {
36
+ if (active) {
37
+ scrollEl.classList.remove('blk-panning');
38
+ try { scrollEl.releasePointerCapture(pid); } catch (_) {}
39
+ // a drag ends in a click on whatever was under the release — swallow it
40
+ // once so it can't trigger anything the user didn't mean to click
41
+ const swallow = (ev) => { ev.stopPropagation(); ev.preventDefault(); };
42
+ scrollEl.addEventListener('click', swallow, { capture: true, once: true });
43
+ setTimeout(() => scrollEl.removeEventListener('click', swallow, true), 0);
44
+ }
45
+ pending = false; active = false; pid = null;
46
+ };
47
+ scrollEl.addEventListener('pointerup', end);
48
+ scrollEl.addEventListener('pointercancel', end);
49
+ window.addEventListener('resize', refresh);
50
+ return refresh;
51
+ }
52
+
53
+ // Build the onComment thunk for attachViewer: opens the annotation popover
54
+ // with a block-scoped target ("Whole chart/diagram/…") so a user can comment
55
+ // on the visual as a whole. null when annotation is off (omits the button).
56
+ function wholeBlockComment(ctx, blockId, label) {
57
+ if (!ctx || !ctx.annotate || ctx.canComment === false) return null;
58
+ const a = ctx.annotate;
59
+ return {
60
+ open: (anchorEl) =>
61
+ a.openExternal({ blockId, questionId: ctx.questionId, target: { kind: 'block', label } }, anchorEl),
62
+ // true once this block carries a whole-block comment
63
+ active: () => a.list().some((x) => x.blockId === blockId && x.target && x.target.kind === 'block'),
64
+ // fires on any annotation change; returns an unsubscribe
65
+ subscribe: (fn) => (a.onBadgeRefresh ? a.onBadgeRefresh(fn) : () => {}),
66
+ };
67
+ }
68
+
69
+ // opts: { zoomEl, natural, comment, label } — zoomEl null means no pixel
70
+ // zoom (charts/html/code: full-screen + comment only, no zoom buttons).
71
+ // comment (optional) = { open(anchor), active(), subscribe(fn) } wiring the
72
+ // "comment on the whole block" button + its already-commented style.
73
+ function attachViewer(container, opts) {
74
+ if (container._rlyRegionHook) {
75
+ try { container._rlyRegionHook(); } catch (_) {}
76
+ container._rlyRegionHook = null;
77
+ }
78
+ if (container._rlyTools) container._rlyTools.remove();
79
+ container.classList.add('blk-viewer');
80
+ const zoomable = Boolean(opts && opts.zoomEl);
81
+ const label = (opts && opts.label) || 'visual';
82
+
83
+ // pan listeners bind once per container; mermaid re-renders re-call
84
+ // attachViewer, so reuse the existing refresh() instead of re-binding
85
+ if (!container._rlyPan) container._rlyPan = enablePan(container);
86
+ const refreshPan = container._rlyPan;
87
+
88
+ // zoom level persists across re-renders; the wheel handler (bound once)
89
+ // delegates through container._rlyZoom so it never holds a stale zoomEl
90
+ if (container._rlyZ === undefined) container._rlyZ = null; // null = fit-to-width
91
+ // Fluid visuals (currently Chart.js) fit the live container width. Capture
92
+ // that rendered size only when leaving fit mode so zoom remains proportional
93
+ // without freezing later fit-mode viewport growth to an old width.
94
+ let fluidZoomNatural = null;
95
+ const pct = el('span', { class: 'tool-pct' }, 'fit');
96
+ function apply() {
97
+ if (!zoomable) return;
98
+ const target = opts.zoomEl;
99
+ const nat = opts.natural();
100
+ const z = container._rlyZ;
101
+ const full = container.classList.contains('blk-full');
102
+ // A per-block height caps only the compact inline preview. The moment the
103
+ // user zooms in (z !== null) or goes full-screen they want pixel detail, so
104
+ // lift the cap there; restore it when back to the inline fit view.
105
+ if (opts.fitMaxHeight != null) {
106
+ target.style.maxHeight = z === null && !full ? opts.fitMaxHeight + 'px' : 'none';
107
+ }
108
+ if (z === null && full && nat && nat.w && nat.h) {
109
+ // Full-screen default: scale the diagram/image to fill the viewport
110
+ // (contain — enlarge a small one, shrink a big one) so it's readable at
111
+ // a glance without reaching for the zoom buttons. CSS margin:auto centers
112
+ // it; it stays pannable once the user zooms past this fit.
113
+ // subtract the docked comment rail (≥980px) so the fit doesn't run under it
114
+ const railInset = (document.body.classList.contains('ann-rail-open') && window.innerWidth >= 980) ? 340 : 0;
115
+ const availW = window.innerWidth - railInset - FULL_PAD_X * 2;
116
+ const availH = window.innerHeight - FULL_PAD_TOP - FULL_PAD_BOTTOM;
117
+ const scale = Math.min(availW / nat.w, availH / nat.h);
118
+ target.style.maxWidth = 'none';
119
+ target.style.width = Math.max(1, Math.round(nat.w * scale)) + 'px';
120
+ target.style.height = opts.scaleHeight ? Math.max(1, Math.round(nat.h * scale)) + 'px' : 'auto';
121
+ pct.textContent = 'fit';
122
+ } else if (z === null || !nat || !nat.w) {
123
+ target.style.width = '100%';
124
+ target.style.maxWidth = opts.fluidFit ? '100%' : (nat && nat.w ? Math.ceil(nat.w) + 'px' : '100%');
125
+ target.style.height = opts.scaleHeight ? '100%' : 'auto';
126
+ pct.textContent = 'fit';
127
+ } else {
128
+ const zoomNat = fluidZoomNatural || nat;
129
+ target.style.maxWidth = 'none';
130
+ target.style.width = Math.round(zoomNat.w * z) + 'px';
131
+ target.style.height = opts.scaleHeight && zoomNat && zoomNat.h ? Math.round(zoomNat.h * z) + 'px' : 'auto';
132
+ pct.textContent = Math.round(z * 100) + '%';
133
+ }
134
+ window.dispatchEvent(new Event('resize')); // annotation badges reposition
135
+ refreshPan(); // content size → grab affordance
136
+ }
137
+ function currentZ() {
138
+ if (container._rlyZ !== null) return container._rlyZ;
139
+ if (opts.fluidFit) return 1;
140
+ const nat = opts.natural();
141
+ if (!nat || !nat.w) return 1;
142
+ const shown = opts.zoomEl.getBoundingClientRect().width;
143
+ return shown > 0 ? shown / nat.w : 1;
144
+ }
145
+ function setZoom(next) {
146
+ if (next === null) {
147
+ fluidZoomNatural = null;
148
+ } else if (opts.fluidFit && container._rlyZ === null) {
149
+ const shown = opts.zoomEl.getBoundingClientRect();
150
+ fluidZoomNatural = {
151
+ w: Math.max(1, shown.width),
152
+ h: Math.max(1, shown.height),
153
+ };
154
+ }
155
+ container._rlyZ = next === null ? null : Math.min(8, Math.max(0.2, next));
156
+ apply();
157
+ }
158
+ container._rlyZoom = { setZoom, currentZ, reapply: apply };
159
+
160
+ // Stop any in-flight wheel easing before an explicit toolbar/full-screen
161
+ // action. This prevents an older gesture target from overriding that action
162
+ // on the next animation frame.
163
+ if (!container._rlyStopWheelZoom) {
164
+ container._rlyStopWheelZoom = () => {
165
+ if (container._rlyWheelFrame) cancelAnimationFrame(container._rlyWheelFrame);
166
+ container._rlyWheelFrame = null;
167
+ container._rlyWheelTarget = null;
168
+ };
169
+ }
170
+
171
+ const tools = el('div', { class: 'blk-tools' });
172
+
173
+ // comment on the whole block (leftmost) — opens the annotation popover with
174
+ // a block-scoped target so a user can comment without picking an element.
175
+ // The button gains a .has-comment style once the block carries one, kept in
176
+ // sync via the annotate badge-refresh subscription (bound once per container).
177
+ if (opts && opts.comment) {
178
+ const cmt = opts.comment;
179
+ const cBtn = el('button', { class: 'tool-comment', type: 'button', title: 'Comment on this whole ' + label });
180
+ cBtn.innerHTML = ICON_COMMENT;
181
+ cBtn.addEventListener('click', (e) => { e.stopPropagation(); cmt.open(container); });
182
+ tools.append(cBtn);
183
+ container._rlyCmtSync = () => {
184
+ const b = container._rlyTools && container._rlyTools.querySelector('.tool-comment');
185
+ if (b && cmt.active) b.classList.toggle('has-comment', !!cmt.active());
186
+ };
187
+ if (!container._rlyCmtHook && cmt.subscribe) {
188
+ container._rlyCmtHook = cmt.subscribe(() => container._rlyCmtSync && container._rlyCmtSync());
189
+ }
190
+ }
191
+
192
+ if (opts && opts.comment && opts.hoverComments) {
193
+ const hoverCtl = opts.hoverComments;
194
+ const hoverBtn = el('button', {
195
+ class: 'tool-hover-comments',
196
+ type: 'button',
197
+ 'aria-label': 'Show element comment overlays',
198
+ });
199
+ hoverBtn.innerHTML = ICON_EYE;
200
+ hoverBtn.append(el('span', { class: 'tool-hover-label' }, 'Hover comments'));
201
+ const syncHoverMode = () => {
202
+ const enabled = hoverCtl.isEnabled();
203
+ hoverBtn.classList.toggle('is-active', enabled);
204
+ hoverBtn.setAttribute('aria-pressed', String(enabled));
205
+ hoverBtn.title = enabled ? 'Hide element comment overlays' : 'Show element comment overlays';
206
+ };
207
+ hoverBtn.addEventListener('click', (e) => {
208
+ e.stopPropagation();
209
+ hoverCtl.setEnabled(!hoverCtl.isEnabled());
210
+ syncHoverMode();
211
+ });
212
+ syncHoverMode();
213
+ tools.append(hoverBtn);
214
+ }
215
+
216
+ if (opts && opts.region) {
217
+ const regionCtl = opts.region;
218
+ const regionLabel = el('span', { class: 'tool-region-label' }, 'Area');
219
+ const regionBtn = el('button', {
220
+ class: 'tool-region',
221
+ type: 'button',
222
+ title: 'Draw an area comment',
223
+ 'aria-label': 'Draw an area comment',
224
+ 'aria-pressed': 'false',
225
+ });
226
+ regionBtn.innerHTML = ICON_REGION;
227
+ regionBtn.append(regionLabel);
228
+ const syncRegionMode = (enabled) => {
229
+ regionBtn.classList.toggle('is-active', enabled);
230
+ regionBtn.setAttribute('aria-pressed', enabled ? 'true' : 'false');
231
+ regionBtn.title = enabled ? 'Cancel area comment' : 'Draw an area comment';
232
+ regionBtn.setAttribute('aria-label', regionBtn.title);
233
+ regionLabel.textContent = enabled ? 'Drawing' : 'Area';
234
+ };
235
+ regionBtn.addEventListener('click', (e) => {
236
+ e.stopPropagation();
237
+ regionCtl.setModeActive(!regionCtl.isModeActive());
238
+ });
239
+ container._rlyRegionHook = regionCtl.onModeChange(syncRegionMode);
240
+ syncRegionMode(regionCtl.isModeActive());
241
+ tools.append(regionBtn);
242
+ }
243
+
244
+ if (zoomable) {
245
+ // cmd/ctrl+wheel zoom, bound ONCE (re-binding per render would stack);
246
+ // delegates to the current controller so it never uses a stale zoomEl
247
+ if (!container._rlyWheel) {
248
+ const onWheel = (e) => {
249
+ if (!(e.ctrlKey || e.metaKey) || !container._rlyZoom) return;
250
+ e.preventDefault();
251
+ // Normalize line/page-mode devices to pixel-like units, then cap a
252
+ // single event. Exponential scaling makes equal motion reversible and
253
+ // lets tiny trackpad deltas stay tiny instead of becoming fixed jumps.
254
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? window.innerHeight : 1;
255
+ const delta = Math.max(-WHEEL_ZOOM_MAX_DELTA, Math.min(WHEEL_ZOOM_MAX_DELTA, e.deltaY * unit));
256
+ const base = Number.isFinite(container._rlyWheelTarget)
257
+ ? container._rlyWheelTarget
258
+ : container._rlyZoom.currentZ();
259
+ container._rlyWheelTarget = Math.min(8, Math.max(0.2, base * Math.exp(-delta * WHEEL_ZOOM_SENSITIVITY)));
260
+
261
+ // Respect reduced-motion while retaining the gentler delta-based step.
262
+ if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
263
+ container._rlyZoom.setZoom(container._rlyWheelTarget);
264
+ container._rlyWheelTarget = null;
265
+ return;
266
+ }
267
+ if (container._rlyWheelFrame) return; // coalesce bursty input to one rAF loop
268
+ const tick = () => {
269
+ const zoom = container._rlyZoom;
270
+ const target = container._rlyWheelTarget;
271
+ if (!zoom || !Number.isFinite(target)) {
272
+ container._rlyWheelFrame = null;
273
+ return;
274
+ }
275
+ const current = zoom.currentZ();
276
+ const gap = target - current;
277
+ if (Math.abs(gap) <= WHEEL_ZOOM_EPSILON) {
278
+ zoom.setZoom(target);
279
+ container._rlyWheelFrame = null;
280
+ container._rlyWheelTarget = null;
281
+ return;
282
+ }
283
+ zoom.setZoom(current + gap * WHEEL_ZOOM_EASE);
284
+ container._rlyWheelFrame = requestAnimationFrame(tick);
285
+ };
286
+ container._rlyWheelFrame = requestAnimationFrame(tick);
287
+ };
288
+ container.addEventListener('wheel', onWheel, { passive: false });
289
+ container._rlyWheel = onWheel;
290
+ }
291
+ const zoomOut = el('button', { class: 'tool-zoom', type: 'button', title: 'Zoom out' }, '−');
292
+ const zoomIn = el('button', { class: 'tool-zoom', type: 'button', title: 'Zoom in' }, '+');
293
+ zoomOut.addEventListener('click', (e) => { e.stopPropagation(); container._rlyStopWheelZoom(); setZoom(currentZ() / 1.2); });
294
+ zoomIn.addEventListener('click', (e) => { e.stopPropagation(); container._rlyStopWheelZoom(); setZoom(currentZ() * 1.2); });
295
+ pct.classList.add('is-btn');
296
+ pct.title = 'Reset to fit';
297
+ pct.addEventListener('click', (e) => { e.stopPropagation(); container._rlyStopWheelZoom(); setZoom(null); });
298
+ tools.append(zoomOut, pct, zoomIn);
299
+ }
300
+
301
+ const fullBtn = el('button', { class: 'tool-full', type: 'button', title: 'Full screen (Esc closes; ⌘/Ctrl+wheel zooms)' });
302
+ fullBtn.innerHTML = ICON_EXPAND;
303
+ fullBtn.addEventListener('click', (e) => {
304
+ e.stopPropagation();
305
+ if (fullOpen === container) exitFull();
306
+ else enterFull(container);
307
+ });
308
+ tools.append(fullBtn);
309
+
310
+ container.prepend(tools);
311
+ container._rlyTools = tools;
312
+ if (zoomable) apply();
313
+ // non-zoomable diagrams (tall mermaid, oversized image) can still overflow
314
+ refreshPan();
315
+ if (container._rlyCmtSync) container._rlyCmtSync(); // reflect existing comment
316
+ }
317
+
318
+ function svgNatural(svgEl) {
319
+ return () => {
320
+ const vb = svgEl.viewBox && svgEl.viewBox.baseVal;
321
+ return vb && vb.width > 0 ? { w: vb.width, h: vb.height } : null;
322
+ };
323
+ }
324
+
package/src/ui/kit.js CHANGED
@@ -1,3 +1,4 @@
1
+ // code-craft: allow-size the browser kit is served whole as /kit.js; its helpers share one scope.
1
2
  /**
2
3
  * relay kit.js — loaded INSIDE sandboxed custom-HTML iframes via <script src="/kit.js">.
3
4
  * NO access to the parent DOM (sandbox without allow-same-origin) — only postMessage.