@khanglvm/relay 0.17.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/spec.js CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import vm from 'node:vm';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { CliError } from './util.js';
6
+ import { assertSafeJson, guardExpress, resolveA2uiBlock, validateSurface } from './a2ui/compile.js';
6
7
 
7
8
  export const TYPES = ['single', 'multi', 'yesno', 'text', 'textarea', 'scale', 'color', 'rank', 'checklist', 'allocate'];
8
9
 
@@ -41,7 +42,7 @@ const HTML_HEIGHT = { min: 100, max: 2400, boardDefault: 400, questionDefault: 3
41
42
 
42
43
  // Block heights clamp to the same window; defaults vary per block type.
43
44
  const BLOCK_HEIGHT = { min: 100, max: 2400 };
44
- export const BLOCK_TYPES = ['markdown', 'mermaid', 'graphviz', 'plantuml', 'chart', 'table', 'code', 'diff', 'git-conflict', 'video', 'pdf', 'html', 'image', 'palette', 'kpi', 'typography', 'compare'];
45
+ export const BLOCK_TYPES = ['markdown', 'mermaid', 'graphviz', 'plantuml', 'chart', 'table', 'code', 'diff', 'git-conflict', 'video', 'pdf', 'html', 'image', 'palette', 'kpi', 'typography', 'compare', 'a2ui'];
45
46
  const CHART_KINDS = ['bar', 'line', 'pie', 'doughnut', 'radar', 'scatter'];
46
47
 
47
48
  // code/diff blocks may load their text from a local file (like htmlFile). Caps
@@ -412,6 +413,7 @@ export async function assertSpecReady(spec) {
412
413
  if (spec.__relayReady === true) return spec;
413
414
  for (const { block, where } of allBlocks(spec)) {
414
415
  if (block && block.type === 'mermaid') await assertMermaidSyntax(block.code || '', where);
416
+ if (block && block.type === 'a2ui') await resolveA2uiBlock(block, `${where} (a2ui)`);
415
417
  }
416
418
  Object.defineProperty(spec, '__relayReady', { value: true, enumerable: false, configurable: true });
417
419
  return spec;
@@ -761,6 +763,25 @@ function normalizeBlock(rawBlock, id, cwd, where) {
761
763
  return block;
762
764
  }
763
765
 
766
+ if (type === 'a2ui') {
767
+ // A live A2UI v1.0 widget: Express text (compiled in assertSpecReady) or
768
+ // ready JSON components, checked against Relay's catalog either way.
769
+ const hasExpress = rawBlock.express !== undefined && rawBlock.express !== null;
770
+ const hasComponents = rawBlock.components !== undefined && rawBlock.components !== null;
771
+ if (hasExpress === hasComponents) throw new CliError(`${where}: a2ui block needs exactly one of "express" (A2UI Express text) or "components" (JSON list).`);
772
+ const block = { id, type: 'a2ui' };
773
+ if (rawBlock.title !== undefined) block.title = asStr(rawBlock.title);
774
+ if (hasHeight) block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, undefined);
775
+ if (hasExpress) {
776
+ if (rawBlock.dataModel !== undefined) throw new CliError(`${where}: with "express", set data with \`$/path = value\` lines, not "dataModel".`);
777
+ block.express = guardExpress(rawBlock.express, where);
778
+ return block;
779
+ }
780
+ assertSafeJson(rawBlock.components, where);
781
+ const surface = validateSurface({ components: rawBlock.components, dataModel: rawBlock.dataModel }, where);
782
+ return Object.assign(block, surface);
783
+ }
784
+
764
785
  if (type === 'palette') {
765
786
  // Accept either { palettes: [{name, colors:[…]}, …] } or a single-palette
766
787
  // shorthand { name?, colors:[…] }. Each palette needs a non-empty colors
@@ -1046,6 +1067,9 @@ const BLOCK_SCHEMA = {
1046
1067
  review: { type: 'boolean', description: 'diff: when true, render per-hunk Apply / Skip / Hold controls and return choices in result.blockEdits[blockId] as {type:"diff-review", hunks:{...}}. Used by `rly git cherry-pick --code`.' },
1047
1068
  reviewKind: { type: 'string', description: 'diff review: optional label for the review workflow, such as "cherry-pick" or "pick".' },
1048
1069
  commit: { type: 'string', description: 'diff review: optional commit SHA associated with this diff.' },
1070
+ express: { type: 'string', description: 'a2ui: a live widget in A2UI Express, e.g. `$/jobs = [{title:"Build",tone:"ok"}]` then `root = Card("CI", [List($/jobs), Button("Retry", action=Event("retry"))])`. Compiled by the A2UI SDK against Relay\'s catalog (run `rly a2ui` for the grammar and every component). Button events, input values come back in result.blockEdits[blockId] as {type:"a2ui", data, events}.' },
1071
+ components: { type: 'array', description: 'a2ui: the same widget as flat A2UI v1.0 JSON components (root id "root", a Card) instead of "express".', items: { type: 'object' } },
1072
+ dataModel: { type: 'object', description: 'a2ui: the data model for "components" (use `$/path = value` lines with "express" instead).' },
1049
1073
  content: { type: 'string', description: 'git-conflict: inline file content containing conflict markers (<<<<<<< / ======= / >>>>>>>). The board auto-detects each hunk and returns resolutions in result.blockEdits[blockId].' },
1050
1074
  text: { type: 'string', description: 'git-conflict: alias for inline "content".' },
1051
1075
  file: { type: 'string', description: 'git-conflict: local conflicted file path to load, parse, and resolve. Resolved against the CWD.' },
@@ -1191,7 +1215,7 @@ export const SPEC_SCHEMA = {
1191
1215
  type: 'object',
1192
1216
  readOnly: true,
1193
1217
  description:
1194
- 'Returned in the result (not part of the input spec). A map blockId→edited block payload. Editable mermaid blocks return edited source strings. git-conflict blocks return {type:"git-conflict-resolution", resolutions, content, resolved, filename, file}. diff review blocks return {type:"diff-review", hunks, resolved, commit}. null when the user made no edits.',
1218
+ 'Returned in the result (not part of the input spec). A map blockId→edited block payload. Editable mermaid blocks return edited source strings. git-conflict blocks return {type:"git-conflict-resolution", resolutions, content, resolved, filename, file}. diff review blocks return {type:"diff-review", hunks, resolved, commit}. a2ui blocks return {type:"a2ui", data (the widget data model with the user input values), events:[{name, context, at}] (each button click, in order)}. null when the user made no edits.',
1195
1219
  },
1196
1220
  },
1197
1221
  anyOf: [{ required: ['questions'] }, { required: ['blocks'] }, { required: ['html'] }, { required: ['htmlFile'] }],
package/src/store.js CHANGED
@@ -121,6 +121,12 @@ export function loadRunning(id) {
121
121
  }
122
122
  }
123
123
 
124
+ // The URL this machine uses to talk to a running board. `url` may be a
125
+ // cross-device link (devlink, a proxy) that only people open.
126
+ export function controlUrl(running) {
127
+ return running.localUrl || running.url;
128
+ }
129
+
124
130
  export function removeRunning(id) {
125
131
  try {
126
132
  fs.unlinkSync(runningPath(id));
@@ -0,0 +1,89 @@
1
+ // a2ui-state.js — window.RelayA2uiState: the data model and event log behind one
2
+ // a2ui block. Pure data, no DOM, so it is testable on its own. a2ui.js draws it.
3
+ (() => {
4
+ 'use strict';
5
+
6
+ const UNSAFE = new Set(['__proto__', 'constructor', 'prototype']);
7
+ const MAX_EVENTS = 50;
8
+
9
+ // '/a/b' -> ['a','b'], '' or '/' -> [], null when a segment could reach the prototype chain.
10
+ function segments(pointer) {
11
+ if (typeof pointer !== 'string' || (pointer && pointer[0] !== '/')) return null;
12
+ const parts = pointer.split('/').slice(1).filter((s) => s !== '');
13
+ return parts.some((s) => UNSAFE.has(s)) ? null : parts;
14
+ }
15
+
16
+ const isContainer = (v) => v !== null && typeof v === 'object';
17
+
18
+ function get(data, pointer) {
19
+ const parts = segments(pointer);
20
+ if (!parts) return undefined;
21
+ let cur = data;
22
+ for (const key of parts) {
23
+ if (!isContainer(cur) || !Object.hasOwn(cur, key)) return undefined;
24
+ cur = cur[key];
25
+ }
26
+ return cur;
27
+ }
28
+
29
+ // Writes value at pointer, creating plain objects on the way. Returns false for an unsafe path.
30
+ function set(data, pointer, value) {
31
+ const parts = segments(pointer);
32
+ if (!parts || !parts.length) return false;
33
+ let cur = data;
34
+ for (const key of parts.slice(0, -1)) {
35
+ if (!isContainer(cur[key]) || !Object.hasOwn(cur, key)) cur[key] = {};
36
+ cur = cur[key];
37
+ }
38
+ cur[parts[parts.length - 1]] = value;
39
+ return true;
40
+ }
41
+
42
+ const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
43
+ const isBinding = (v) => isContainer(v) && !Array.isArray(v) && typeof v['@path'] === 'string';
44
+
45
+ // A prop that is a literal or a {"@path": "/x"} binding, read against the current data.
46
+ function resolve(data, value) {
47
+ return isBinding(value) ? get(data, value['@path']) : value;
48
+ }
49
+
50
+ /**
51
+ * The state of one block. `restored` is the {data, events} the board saved
52
+ * before (a page reload); `onChange(snapshot)` runs after the user changes an
53
+ * input or fires an event, never for the first render.
54
+ */
55
+ function createStore(initialData, restored, onChange) {
56
+ const data = clone(restored && restored.data && typeof restored.data === 'object' ? restored.data : initialData) || {};
57
+ const events = restored && Array.isArray(restored.events) ? restored.events.slice(-MAX_EVENTS) : [];
58
+ const listeners = [];
59
+ const snapshot = () => ({ type: 'a2ui', data: clone(data), events: clone(events) });
60
+ const touch = () => {
61
+ listeners.forEach((fn) => fn());
62
+ if (onChange) onChange(snapshot());
63
+ };
64
+ return {
65
+ data,
66
+ get: (pointer) => get(data, pointer),
67
+ resolve: (value) => resolve(data, value),
68
+ subscribe: (fn) => listeners.push(fn),
69
+ set(pointer, value) {
70
+ if (set(data, pointer, value)) touch();
71
+ },
72
+ // An Event(name, {context}) action: context bindings are read now, so the agent sees the values at click time.
73
+ fire(name, context) {
74
+ const resolved = {};
75
+ for (const [key, value] of Object.entries(context || {})) {
76
+ if (!UNSAFE.has(key)) resolved[key] = clone(resolve(data, value));
77
+ }
78
+ events.push({ name, context: resolved, at: new Date().toISOString() });
79
+ if (events.length > MAX_EVENTS) events.shift();
80
+ touch();
81
+ },
82
+ eventCount: () => events.length,
83
+ snapshot,
84
+ };
85
+ }
86
+
87
+ const api = { get, set, clone, resolve, isBinding, createStore };
88
+ (typeof window !== 'undefined' ? window : globalThis).RelayA2uiState = api;
89
+ })();
@@ -0,0 +1,106 @@
1
+ /* a2ui.css — the `a2ui` block: A2UI components drawn in the board's own theme. */
2
+ .a2 {
3
+ --a2-ok: var(--ok);
4
+ --a2-info: #4a6c98;
5
+ --a2-warn: #946a1c;
6
+ --a2-error: var(--danger);
7
+ --a2-needs: var(--accent);
8
+ }
9
+ [data-theme="dark"] .a2 { --a2-info: #88b4e8; --a2-warn: #e3c46a; }
10
+ @media (prefers-color-scheme: dark) {
11
+ :root:not([data-theme="light"]) .a2 { --a2-info: #88b4e8; --a2-warn: #e3c46a; }
12
+ }
13
+ .a2-tone-ok { --a2-tone: var(--a2-ok); }
14
+ .a2-tone-info { --a2-tone: var(--a2-info); }
15
+ .a2-tone-warn { --a2-tone: var(--a2-warn); }
16
+ .a2-tone-error { --a2-tone: var(--a2-error); }
17
+ .a2-tone-needs { --a2-tone: var(--a2-needs); }
18
+
19
+ .blk-a2ui { margin: 4px 0; }
20
+ .a2-card {
21
+ display: flex; flex-direction: column; gap: 12px; padding: 16px;
22
+ background: var(--card); border-radius: 14px; box-shadow: var(--shadow-card);
23
+ }
24
+ .a2-card-title { font-weight: 650; font-size: 1.05rem; }
25
+ .a2-stack { display: flex; min-width: 0; }
26
+ .a2-col { flex-direction: column; }
27
+ .a2-row { flex-direction: row; flex-wrap: wrap; align-items: center; }
28
+ .a2-grid { display: grid; min-width: 0; }
29
+ .a2-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
30
+ .a2-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
31
+ .a2-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
32
+ @media (max-width: 480px) {
33
+ .a2-cols-3, .a2-cols-4 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
34
+ }
35
+ .a2-muted { color: var(--muted); font-size: 0.82rem; }
36
+ .a2-text-body { line-height: 1.5; overflow-wrap: anywhere; }
37
+ .a2-text-title { font-weight: 600; }
38
+ .a2-text-muted { color: var(--muted); font-size: 0.88rem; }
39
+
40
+ .a2-pill {
41
+ display: inline-block; max-width: 100%; padding: 2px 10px; border-radius: 999px;
42
+ font-size: 0.8rem; font-weight: 600; line-height: 1.5; white-space: nowrap;
43
+ color: var(--a2-tone, var(--fg-2)); background: color-mix(in srgb, var(--a2-tone, var(--fg-2)) 14%, transparent);
44
+ }
45
+
46
+ .a2-metric { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; border-radius: 10px; background: var(--bg-sunken); min-width: 0; }
47
+ .a2-metric-label { color: var(--muted); font-size: 0.82rem; }
48
+ .a2-metric-value { font-family: var(--serif); font-size: 1.6rem; line-height: 1.1; letter-spacing: -0.02em; overflow-wrap: anywhere; }
49
+
50
+ .a2-list { display: flex; flex-direction: column; }
51
+ .a2-item {
52
+ display: flex; flex-direction: row; align-items: center; justify-content: space-between; gap: 12px;
53
+ padding: 10px 0; border-top: 1px solid var(--border); min-height: 44px;
54
+ }
55
+ .a2-item:first-child { border-top: 0; }
56
+ .a2-row-main { min-width: 0; flex: 1; }
57
+ .a2-row-title { font-weight: 550; overflow-wrap: anywhere; color: var(--fg); text-decoration: none; }
58
+ a.a2-row-title { text-decoration: underline; text-decoration-color: var(--border-strong); text-underline-offset: 3px; }
59
+ .a2-row-sub { color: var(--muted); font-size: 0.84rem; overflow-wrap: anywhere; }
60
+ .a2-row-trail { color: var(--fg-2); font-size: 0.88rem; white-space: nowrap; }
61
+ .a2-row-more { color: var(--muted); font-size: 0.84rem; padding-top: 8px; }
62
+
63
+ .a2-progress { display: flex; flex-direction: column; gap: 6px; }
64
+ .a2-progress-head { display: flex; justify-content: space-between; gap: 12px; font-weight: 550; }
65
+ .a2-bar { height: 8px; border-radius: 999px; background: var(--bg-sunken); overflow: hidden; }
66
+ .a2-bar-fill { height: 100%; border-radius: 999px; background: var(--a2-tone, var(--accent)); transition: width 0.25s var(--ease); }
67
+
68
+ .a2-table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
69
+ .a2-table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
70
+ .a2-table th, .a2-table td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); white-space: nowrap; }
71
+ .a2-table th { color: var(--muted); font-weight: 600; font-size: 0.8rem; }
72
+
73
+ .a2-code { margin: 0; padding: 12px; border-radius: 10px; background: var(--bg-sunken); overflow-x: auto; font-size: 0.85rem; line-height: 1.5; }
74
+ .a2-image { max-width: 100%; height: auto; border-radius: 10px; }
75
+ .a2-divider { border: 0; border-top: 1px solid var(--border); margin: 0; width: 100%; }
76
+ .a2-icon { width: 18px; height: 18px; flex: none; color: var(--a2-tone, currentColor); }
77
+
78
+ .a2-field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
79
+ .a2-field-inline { flex-direction: row; align-items: center; min-height: 44px; }
80
+ .a2-field-inline .a2-field-label { order: 2; }
81
+ .a2-field-label { font-size: 0.85rem; color: var(--fg-2); }
82
+ /* 16px keeps iOS Safari from zooming the page when an input takes focus. */
83
+ .a2-input {
84
+ font: inherit; font-size: 16px; color: var(--fg); background: var(--bg-sunken);
85
+ border: 1px solid var(--border-strong); border-radius: 10px; padding: 10px 12px; min-height: 44px; width: 100%;
86
+ }
87
+ .a2-input:focus-visible, .a2-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
88
+ .a2-check { width: 22px; height: 22px; accent-color: var(--accent); }
89
+ .a2-range { width: 100%; min-height: 44px; accent-color: var(--accent); }
90
+
91
+ .a2-btn {
92
+ display: inline-flex; align-items: center; gap: 6px; justify-content: center;
93
+ font: inherit; font-size: 0.95rem; font-weight: 600; color: var(--fg); background: var(--bg-sunken);
94
+ border: 1px solid var(--border-strong); border-radius: 10px; padding: 10px 16px; min-height: 44px; cursor: pointer;
95
+ transition: background 0.15s var(--ease), transform 0.1s var(--ease);
96
+ }
97
+ .a2-btn:active { transform: scale(0.97); }
98
+ .a2-btn-primary { color: var(--accent-fg); background: var(--accent); border-color: transparent; }
99
+ .a2-btn-primary:hover { background: var(--accent-hover); }
100
+ .a2-btn-sent { box-shadow: 0 0 0 2px var(--a2-ok); }
101
+ .a2-btn:disabled, .a2-input:disabled { opacity: 0.55; cursor: not-allowed; }
102
+ .a2-status:empty { display: none; }
103
+ .a2-status { margin-top: 6px; }
104
+ @media (prefers-reduced-motion: reduce) {
105
+ .a2-btn, .a2-bar-fill { transition: none; }
106
+ }
package/src/ui/a2ui.js ADDED
@@ -0,0 +1,289 @@
1
+ // a2ui.js — window.RelayA2ui.render(block, ctx, blockId): draws one `a2ui`
2
+ // block (A2UI v1.0 components from Relay's catalog) as plain DOM. Every string
3
+ // goes in through textContent and every link is https-only, so agent text can
4
+ // never become markup. State and event logging live in a2ui-state.js.
5
+ (() => {
6
+ 'use strict';
7
+
8
+ const SVG_NS = 'http://www.w3.org/2000/svg';
9
+ const TONES = ['info', 'ok', 'warn', 'error', 'needs'];
10
+ const TONE_WORDS = { info: 'Info', ok: 'OK', warn: 'Warning', error: 'Failed', needs: 'Needs you' };
11
+ const HTTPS = /^https:\/\//i;
12
+
13
+ // Lucide-style 24x24 stroke paths for the catalog's Icon set.
14
+ const ICONS = {
15
+ check: 'M20 6 9 17l-5-5',
16
+ alert: 'M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z',
17
+ info: 'M12 16v-4M12 8h.01M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0Z',
18
+ x: 'M18 6 6 18M6 6l12 12',
19
+ clock: 'M12 6v6l4 2M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0Z',
20
+ file: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6',
21
+ folder: 'M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9l-.8-1.2A2 2 0 0 0 7.9 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z',
22
+ 'git-branch': 'M6 3v12M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM18 9a9 9 0 0 1-9 9',
23
+ play: 'm6 3 14 9-14 9z',
24
+ star: 'm12 2 3.1 6.3 6.9 1-5 4.9 1.2 6.8L12 17.8 5.8 21l1.2-6.8-5-4.9 6.9-1z',
25
+ link: 'M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7',
26
+ user: 'M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0Z',
27
+ bell: 'M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.9 1.9 0 0 0 3.4 0',
28
+ lock: 'M7 11V7a5 5 0 0 1 10 0v4M5 11h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1Z',
29
+ external: 'M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6',
30
+ };
31
+
32
+ function el(tag, cls, text) {
33
+ const n = document.createElement(tag);
34
+ if (cls) n.className = cls;
35
+ if (text !== undefined && text !== null) n.textContent = String(text);
36
+ return n;
37
+ }
38
+
39
+ function icon(name, label) {
40
+ const svg = document.createElementNS(SVG_NS, 'svg');
41
+ svg.setAttribute('viewBox', '0 0 24 24');
42
+ svg.setAttribute('class', 'a2-icon');
43
+ for (const [k, v] of Object.entries({ fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' })) svg.setAttribute(k, v);
44
+ if (label) { svg.setAttribute('role', 'img'); svg.setAttribute('aria-label', label); } else svg.setAttribute('aria-hidden', 'true');
45
+ const path = document.createElementNS(SVG_NS, 'path');
46
+ path.setAttribute('d', ICONS[name] || ICONS.info);
47
+ svg.append(path);
48
+ return svg;
49
+ }
50
+
51
+ const text = (v) => (v === undefined || v === null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v));
52
+ const toneOf = (v) => (TONES.includes(v) ? v : '');
53
+
54
+ function pill(label, tone) {
55
+ return el('span', 'a2-pill' + (toneOf(tone) ? ' a2-tone-' + tone : ''), label);
56
+ }
57
+
58
+ // Runs `paint` now and again after every state change, so bound props stay live.
59
+ function live(store, paint) {
60
+ paint();
61
+ store.subscribe(paint);
62
+ }
63
+
64
+ function renderList(c, store) {
65
+ const wrap = el('div', 'a2-list');
66
+ live(store, () => {
67
+ const rows = store.resolve(c.items);
68
+ const list = Array.isArray(rows) ? rows.filter((r) => r && typeof r === 'object') : [];
69
+ const max = c.max || list.length;
70
+ wrap.replaceChildren();
71
+ for (const row of list.slice(0, max)) {
72
+ const item = el('div', 'a2-item');
73
+ const main = el('div', 'a2-row-main');
74
+ const title = HTTPS.test(text(row.url)) ? Object.assign(el('a', 'a2-row-title', text(row.title)), { href: row.url, target: '_blank', rel: 'noopener noreferrer' }) : el('div', 'a2-row-title', text(row.title));
75
+ main.append(title);
76
+ if (row.subtitle) main.append(el('div', 'a2-row-sub', text(row.subtitle)));
77
+ item.append(main);
78
+ const tone = toneOf(row.tone);
79
+ if (tone) item.append(pill(row.trailing ? text(row.trailing) : TONE_WORDS[tone], tone));
80
+ else if (row.trailing) item.append(el('div', 'a2-row-trail', text(row.trailing)));
81
+ wrap.append(item);
82
+ }
83
+ if (list.length > max) wrap.append(el('div', 'a2-row-more', `${list.length - max} more`));
84
+ if (!list.length) wrap.append(el('div', 'a2-row-more', 'Nothing here yet'));
85
+ });
86
+ return wrap;
87
+ }
88
+
89
+ function renderTable(c, store) {
90
+ const scroller = el('div', 'a2-table-wrap');
91
+ const table = el('table', 'a2-table');
92
+ scroller.append(table);
93
+ live(store, () => {
94
+ const rows = store.resolve(c.rows);
95
+ const list = Array.isArray(rows) ? rows.filter((r) => r && typeof r === 'object') : [];
96
+ table.replaceChildren();
97
+ const head = el('tr');
98
+ for (const col of c.columns) head.append(el('th', '', col.label));
99
+ const thead = el('thead');
100
+ thead.append(head);
101
+ table.append(thead);
102
+ const body = el('tbody');
103
+ for (const row of list.slice(0, c.max || list.length)) {
104
+ const tr = el('tr');
105
+ for (const col of c.columns) tr.append(el('td', '', Object.hasOwn(row, col.key) ? text(row[col.key]) : ''));
106
+ body.append(tr);
107
+ }
108
+ table.append(body);
109
+ });
110
+ return scroller;
111
+ }
112
+
113
+ function renderProgress(c, store) {
114
+ const wrap = el('div', 'a2-progress');
115
+ const head = el('div', 'a2-progress-head');
116
+ const label = el('span', '');
117
+ const figure = el('span', 'a2-muted');
118
+ head.append(label, figure);
119
+ const bar = el('div', 'a2-bar');
120
+ bar.setAttribute('role', 'progressbar');
121
+ const fill = el('div', 'a2-bar-fill');
122
+ bar.append(fill);
123
+ const note = el('div', 'a2-muted');
124
+ wrap.append(head, bar, note);
125
+ live(store, () => {
126
+ const value = Number(store.resolve(c.value)) || 0;
127
+ const total = Number(store.resolve(c.total)) || 0;
128
+ const pct = total > 0 ? Math.max(0, Math.min(100, (value / total) * 100)) : 0;
129
+ label.textContent = text(store.resolve(c.label));
130
+ figure.textContent = `${value} of ${total}`;
131
+ fill.style.width = pct + '%';
132
+ bar.className = 'a2-bar' + (toneOf(c.tone) ? ' a2-tone-' + c.tone : '');
133
+ bar.setAttribute('aria-valuenow', String(Math.round(pct)));
134
+ bar.setAttribute('aria-valuemin', '0');
135
+ bar.setAttribute('aria-valuemax', '100');
136
+ bar.setAttribute('aria-label', text(store.resolve(c.label)));
137
+ note.textContent = text(store.resolve(c.note));
138
+ note.hidden = !note.textContent;
139
+ });
140
+ return wrap;
141
+ }
142
+
143
+ // A labelled input bound to `c.path`; `read` and `write` adapt the control's value.
144
+ function field(c, store, control, { read, write, event = 'input' }) {
145
+ const wrap = el('label', 'a2-field');
146
+ const caption = el('span', 'a2-field-label');
147
+ wrap.append(caption, control);
148
+ live(store, () => {
149
+ caption.textContent = text(store.resolve(c.label));
150
+ const value = store.get(c.path);
151
+ if (document.activeElement !== control) write(control, value);
152
+ });
153
+ control.addEventListener(event, () => store.set(c.path, read(control)));
154
+ return wrap;
155
+ }
156
+
157
+ function renderInput(c, store, interactive) {
158
+ let wrap;
159
+ if (c.component === 'TextField') {
160
+ const input = c.multiline ? el('textarea', 'a2-input') : Object.assign(el('input', 'a2-input'), { type: 'text' });
161
+ if (c.multiline) input.rows = 3;
162
+ if (c.placeholder) input.placeholder = text(store.resolve(c.placeholder));
163
+ wrap = field(c, store, input, { read: (n) => n.value, write: (n, v) => { n.value = text(v); } });
164
+ } else if (c.component === 'Toggle') {
165
+ const box = Object.assign(el('input', 'a2-check'), { type: 'checkbox' });
166
+ wrap = field(c, store, box, { read: (n) => n.checked, write: (n, v) => { n.checked = v === true; }, event: 'change' });
167
+ wrap.classList.add('a2-field-inline');
168
+ } else if (c.component === 'Select') {
169
+ const select = el('select', 'a2-input');
170
+ for (const o of c.options) select.append(Object.assign(el('option', '', o.label), { value: o.key }));
171
+ // An untouched Select still answers with its first option, as the control shows it.
172
+ if (store.get(c.path) === undefined) window.RelayA2uiState.set(store.data, c.path, c.options[0].key);
173
+ wrap = field(c, store, select, { read: (n) => n.value, write: (n, v) => { n.value = text(v); }, event: 'change' });
174
+ } else {
175
+ const range = Object.assign(el('input', 'a2-range'), { type: 'range', min: c.min, max: c.max, step: c.step || 'any' });
176
+ const readout = el('span', 'a2-muted');
177
+ wrap = field(c, store, range, { read: (n) => Number(n.value), write: (n, v) => { n.value = typeof v === 'number' ? v : c.min; readout.textContent = n.value; } });
178
+ wrap.append(readout);
179
+ range.addEventListener('input', () => { readout.textContent = range.value; });
180
+ }
181
+ wrap.querySelectorAll('input,select,textarea').forEach((n) => { n.disabled = !interactive; });
182
+ return wrap;
183
+ }
184
+
185
+ function renderButton(c, store, interactive, onFired) {
186
+ const button = el('button', 'a2-btn' + (c.style === 'primary' ? ' a2-btn-primary' : ''));
187
+ button.type = 'button';
188
+ live(store, () => { button.textContent = text(store.resolve(c.label)); });
189
+ const call = c.action.functionCall;
190
+ if (call) {
191
+ button.addEventListener('click', () => { if (HTTPS.test(call.args.url)) window.open(call.args.url, '_blank', 'noopener,noreferrer'); });
192
+ button.prepend(icon('external'));
193
+ return button;
194
+ }
195
+ button.disabled = !interactive;
196
+ button.addEventListener('click', () => {
197
+ store.fire(c.action.event.name, c.action.event.context);
198
+ onFired(button);
199
+ });
200
+ return button;
201
+ }
202
+
203
+ const GAPS = { xs: '4px', sm: '8px', md: '12px', lg: '16px' };
204
+
205
+ function build(c, byId, store, env) {
206
+ const kids = () => (c.children || []).map((id) => byId.has(id) ? build(byId.get(id), byId, store, env) : null).filter(Boolean);
207
+ switch (c.component) {
208
+ case 'Card': {
209
+ const card = el('div', 'a2-card');
210
+ if (c.title) { const t = el('div', 'a2-card-title'); live(store, () => { t.textContent = text(store.resolve(c.title)); }); card.append(t); }
211
+ card.append(...kids());
212
+ return card;
213
+ }
214
+ case 'Stack': {
215
+ const s = el('div', 'a2-stack a2-' + (c.direction === 'row' ? 'row' : 'col'));
216
+ s.style.gap = GAPS[c.gap] || GAPS.sm;
217
+ if (c.align) s.style.alignItems = { start: 'flex-start', end: 'flex-end', center: 'center', stretch: 'stretch' }[c.align];
218
+ s.append(...kids());
219
+ return s;
220
+ }
221
+ case 'Grid': {
222
+ const g = el('div', 'a2-grid a2-cols-' + c.columns);
223
+ g.style.gap = GAPS[c.gap] || GAPS.sm;
224
+ g.append(...kids());
225
+ return g;
226
+ }
227
+ case 'Text': {
228
+ const t = el('div', 'a2-text a2-text-' + (['title', 'muted'].includes(c.variant) ? c.variant : 'body'));
229
+ live(store, () => { t.textContent = text(store.resolve(c.text)); });
230
+ return t;
231
+ }
232
+ case 'Pill': {
233
+ const p = pill('', c.tone);
234
+ live(store, () => { p.textContent = text(store.resolve(c.text)); });
235
+ return p;
236
+ }
237
+ case 'Metric': {
238
+ const m = el('div', 'a2-metric');
239
+ const [l, v, n] = [el('div', 'a2-metric-label'), el('div', 'a2-metric-value'), el('div', 'a2-muted')];
240
+ m.append(l, v, n);
241
+ live(store, () => { l.textContent = text(store.resolve(c.label)); v.textContent = text(store.resolve(c.value)); n.textContent = text(store.resolve(c.note)); n.hidden = !n.textContent; });
242
+ return m;
243
+ }
244
+ case 'List': return renderList(c, store);
245
+ case 'Table': return renderTable(c, store);
246
+ case 'Progress': return renderProgress(c, store);
247
+ case 'Code': {
248
+ const pre = el('pre', 'a2-code');
249
+ const code = el('code');
250
+ pre.append(code);
251
+ live(store, () => { code.textContent = text(store.resolve(c.code)); });
252
+ return pre;
253
+ }
254
+ case 'Image': {
255
+ const img = el('img', 'a2-image');
256
+ img.loading = 'lazy';
257
+ img.alt = text(store.resolve(c.alt));
258
+ if (HTTPS.test(c.url)) img.src = c.url;
259
+ return img;
260
+ }
261
+ case 'Icon': { const i = icon(c.name, text(store.resolve(c.label))); if (toneOf(c.tone)) i.classList.add('a2-tone-' + c.tone); return i; }
262
+ case 'Divider': return el('hr', 'a2-divider');
263
+ case 'Button': return renderButton(c, store, env.interactive, env.onFired);
264
+ default: return renderInput(c, store, env.interactive);
265
+ }
266
+ }
267
+
268
+ function render(block, ctx, blockId) {
269
+ const wrap = el('div', 'blk-a2ui a2');
270
+ const components = Array.isArray(block.components) ? block.components : [];
271
+ const byId = new Map(components.map((c) => [c.id, c]));
272
+ const root = byId.get('root');
273
+ if (!root) { wrap.append(el('div', 'blk-error', 'This A2UI widget has no root.')); return wrap; }
274
+ const prior = ctx.edits && ctx.edits[blockId] && ctx.edits[blockId].type === 'a2ui' ? ctx.edits[blockId] : null;
275
+ const store = window.RelayA2uiState.createStore(block.dataModel || {}, prior, (snapshot) => ctx.onBlockEdit(blockId, snapshot));
276
+ const interactive = ctx.canEditBlocks !== false && ctx.canComment !== false;
277
+ const status = el('div', 'a2-status a2-muted');
278
+ status.setAttribute('role', 'status');
279
+ const showSent = () => { status.textContent = 'Recorded. It goes back with your answer when you submit.'; };
280
+ if (store.eventCount()) showSent();
281
+ const onFired = (button) => { showSent(); button.classList.add('a2-btn-sent'); setTimeout(() => button.classList.remove('a2-btn-sent'), 1200); };
282
+ const card = build(root, byId, store, { interactive, onFired });
283
+ wrap.append(card, status);
284
+ if (ctx.annotate) ctx.annotate.register(card, { blockId, questionId: ctx.questionId, target: { kind: 'html-element', label: text(block.title || root.title || 'A2UI widget') } });
285
+ return wrap;
286
+ }
287
+
288
+ window.RelayA2ui = { render };
289
+ })();
package/src/ui/blocks.js CHANGED
@@ -3042,6 +3042,10 @@
3042
3042
  inner = renderCompare(block, ctx, blockId);
3043
3043
  wrapper.append(inner);
3044
3044
  break;
3045
+ case 'a2ui':
3046
+ inner = window.RelayA2ui ? window.RelayA2ui.render(block, ctx, blockId) : el('div', { class: 'blk-error' }, 'A2UI renderer is not loaded.');
3047
+ wrapper.append(inner);
3048
+ break;
3045
3049
  default:
3046
3050
  wrapper.append(el('div', { class: 'blk-error' }, 'Unknown block type: ' + esc(String(block.type))));
3047
3051
  }