reifyui 0.11.1 → 0.13.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 (85) hide show
  1. package/README.md +31 -2
  2. package/dist/chart.js +2 -0
  3. package/dist/chart.js.map +1 -1
  4. package/dist/chunk-EL2DHWOH.js +1710 -0
  5. package/dist/chunk-EL2DHWOH.js.map +1 -0
  6. package/dist/chunk-J633KV57.js +41 -0
  7. package/dist/chunk-J633KV57.js.map +1 -0
  8. package/dist/chunk-J7SECRIG.js +295 -0
  9. package/dist/chunk-J7SECRIG.js.map +1 -0
  10. package/dist/chunk-PIRPLH2Z.js +231 -0
  11. package/dist/chunk-PIRPLH2Z.js.map +1 -0
  12. package/dist/chunk-PZ5AY32C.js +10 -0
  13. package/dist/chunk-PZ5AY32C.js.map +1 -0
  14. package/dist/chunk-UKG4Z6QK.js +130 -0
  15. package/dist/chunk-UKG4Z6QK.js.map +1 -0
  16. package/dist/chunk-ZYWE47EO.js +19 -0
  17. package/dist/chunk-ZYWE47EO.js.map +1 -0
  18. package/dist/collab.cjs +169 -0
  19. package/dist/collab.cjs.map +1 -0
  20. package/dist/collab.d.ts +30 -0
  21. package/dist/collab.js +18 -0
  22. package/dist/collab.js.map +1 -0
  23. package/dist/graph.cjs +2244 -0
  24. package/dist/graph.cjs.map +1 -0
  25. package/dist/graph.d.ts +41 -0
  26. package/dist/graph.js +1870 -0
  27. package/dist/graph.js.map +1 -0
  28. package/dist/harness.js +1 -0
  29. package/dist/harness.js.map +1 -1
  30. package/dist/index.cjs +2044 -867
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.ts +20 -2
  33. package/dist/index.js +892 -1686
  34. package/dist/index.js.map +1 -1
  35. package/dist/sheet-doc.cjs +235 -0
  36. package/dist/sheet-doc.cjs.map +1 -0
  37. package/dist/sheet-doc.d.ts +16 -0
  38. package/dist/sheet-doc.js +20 -0
  39. package/dist/sheet-doc.js.map +1 -0
  40. package/dist/sheet.cjs +2322 -0
  41. package/dist/sheet.cjs.map +1 -0
  42. package/dist/sheet.d.ts +23 -0
  43. package/dist/sheet.js +237 -0
  44. package/dist/sheet.js.map +1 -0
  45. package/dist/slides.js +2 -0
  46. package/dist/slides.js.map +1 -1
  47. package/package.json +35 -3
  48. package/src/auth/client.js +4 -2
  49. package/src/collab/colors.js +18 -0
  50. package/src/collab/index.d.ts +30 -0
  51. package/src/collab/index.js +8 -0
  52. package/src/collab/keepAlive.js +34 -0
  53. package/src/collab/useLiveDoc.js +76 -0
  54. package/src/components/CascadeMenu.jsx +216 -0
  55. package/src/components/ChatMessages.jsx +30 -9
  56. package/src/components/Chip.jsx +37 -10
  57. package/src/components/Composer.jsx +80 -2
  58. package/src/components/resizable.jsx +82 -12
  59. package/src/graph/ConnectPane.jsx +634 -0
  60. package/src/graph/ConnectToolDetail.jsx +565 -0
  61. package/src/graph/LogsPane.jsx +328 -0
  62. package/src/graph/Skeleton.jsx +13 -0
  63. package/src/graph/draft.js +108 -0
  64. package/src/graph/format.js +37 -0
  65. package/src/graph/index.d.ts +41 -0
  66. package/src/graph/index.js +14 -0
  67. package/src/graph/useGraphCollab.js +299 -0
  68. package/src/graph/vgraph.js +215 -0
  69. package/src/index.d.ts +20 -2
  70. package/src/index.js +6 -1
  71. package/src/mention/MentionInput.jsx +420 -0
  72. package/src/mention/mentionModel.js +177 -0
  73. package/src/sheet/RunStrip.jsx +57 -0
  74. package/src/sheet/SheetGrid.jsx +444 -353
  75. package/src/sheet/doc.d.ts +16 -0
  76. package/src/sheet/index.d.ts +23 -0
  77. package/src/sheet/index.js +10 -0
  78. package/src/sheet/sheetDoc.js +203 -0
  79. package/src/sheet/useSheetCollab.js +102 -0
  80. package/src/sheet/useSheetRun.js +80 -0
  81. package/styles/chat.css +47 -5
  82. package/styles/chip.css +36 -0
  83. package/styles/graph.css +395 -0
  84. package/styles/mention.css +79 -0
  85. package/styles/sheet.css +156 -112
@@ -1,64 +1,47 @@
1
- // SheetGrid — the reusable AI-spreadsheet grid.
1
+ // SheetGrid — the reusable AI-spreadsheet grid (UI Core).
2
2
  //
3
- // Product-agnostic: it renders a sheet JSON and calls back for edits/runs. All I/O is injected —
4
- // this file has no product API.
3
+ // Product-agnostic: it renders a sheet JSON and calls back for edits/runs.
4
+ // The Sheets product (frontend-sheets) AND agentstudio studio Spaces both
5
+ // mount it via @ui-core, so a Space can nest a sheet-typed element with the
6
+ // same component. All I/O is injected — this file has no product API.
5
7
  //
6
- // Sheet shape:
7
- // { meta{title}, columns[{id,name,type,options?,width?}],
8
- // rows[{id,height?}], cells{ "<rowId>:<colId>": {value,…} } }
8
+ // Sheet shape (see backend/sheets sheet_model):
9
+ // { meta{title,rev}, columns[{id,name,type,options?,compute?}],
10
+ // rows[{id}], cells{ "<rowId>:<colId>": {value,status,error} } }
9
11
  //
10
12
  // Props:
11
13
  // sheet — the sheet JSON (required)
12
- // onChange(next) — persist an edited sheet (add/edit/delete col/row/cell)
13
14
  // onRunCell(rowId, colId) — run one computed cell (optional)
15
+ // ops — the document ops (useSheetCollab's sheetOps); every
16
+ // edit is one op on this tab, never a whole-sheet replace
14
17
  // onRunColumn(colId) — batch-run a computed column (optional)
18
+ // peers — this tab's other people: [{id, name, color, sel, typing}] (from
19
+ // useSheetCollab); their selection is outlined and tinted in
20
+ // their color, their in-progress text shows in the cell as they type
21
+ // onPresence — ({sel, typing}) what THIS person selects and types, for peers
15
22
  // readOnly — no editing/running (template previews / embedded read views)
16
- // fetchBlobUrl(path) — async product-authed fetch -> object URL, for inline images
17
- // whose url is a product path
23
+ // fetchBlobUrl(path) — async product-authed fetch -> object URL, for
24
+ // inline images whose url is a product path
18
25
  // onOpenResource(ref) — open a referenced artifact (sheet/slides/…)
19
- // columnTypes — the column vocabulary (see SheetColumnType below). Defaults to
20
- // this file's own set, so existing hosts need not pass it.
21
- // renderCell(ctx) — replace a cell's body. Return undefined to fall through.
22
- // renderColumnConfig(ctx) — replace the column popover's body. Return undefined to fall through.
23
26
  //
24
- // Editing is optimistic: local edits call onChange with the next sheet; the host persists and
25
- // hands truth back through `sheet`.
26
- import { useEffect, useRef, useState } from 'react';
27
+ // Editing goes straight to the document: local edits are ops on it; the
28
+ // host persists + (via realtime) rebroadcasts truth back through `sheet`.
29
+ import { useEffect, useMemo, useRef, useState } from 'react';
30
+ import { MentionInput } from '../mention/MentionInput.jsx';
27
31
  import { createPortal } from 'react-dom';
32
+ import { withAlpha } from '../collab/colors.js';
28
33
 
29
34
  const cellKey = (rowId, colId) => `${rowId}:${colId}`;
30
35
  const uid = (p) => `${p}_${Math.random().toString(36).slice(2, 10)}`;
31
36
 
32
- // A column type is a descriptor, not a hardcoded literal. This grid used to test
33
- // `col.type === 'compute'` in twelve places, which meant a host could not add a column kind
34
- // without forking the file — and a fork is how two copies of one component start.
35
- //
36
- // type the value stored in column.type
37
- // label what the type menu and the header sub-label show
38
- // computed the app fills these cells, not the person: status dot, tint, run affordances
39
- // editable defaults to !computed
40
- // configKey the column's config object for this type; dropped when the type changes
41
- // badge(col) an extra header sub-label, e.g. which kind of compute this is
42
- // configWidth / configHeight how much room this type's config popover needs. A type whose
43
- // config is a prompt editor does not fit in the width a Type select needs.
44
- const DEFAULT_COLUMN_TYPES = [
45
- { type: 'text', label: 'Text' },
46
- { type: 'number', label: 'Number' },
47
- { type: 'select', label: 'Select' },
48
- { type: 'tags', label: 'Tags' },
49
- { type: 'checkbox', label: 'Checkbox' },
50
- { type: 'date', label: 'Date' },
51
- { type: 'url', label: 'Link' },
52
- { type: 'resource', label: 'Resource' },
53
- {
54
- type: 'compute',
55
- label: 'Computed',
56
- computed: true,
57
- configKey: 'compute',
58
- badge: (col) => col.compute?.kind,
59
- },
60
- ];
37
+ const TYPE_LABEL = {
38
+ text: 'Text', number: 'Number', select: 'Select', tags: 'Tags',
39
+ checkbox: 'Checkbox', date: 'Date', url: 'Link', resource: 'Resource', compute: 'Computed',
40
+ };
41
+ // A one-glyph mark per column type, for pills and pickers.
42
+ const TYPE_GLYPH = { text: 'Aa', number: '#', select: '▾', tags: '#', checkbox: '✓', date: '▦', url: '↗', resource: '◫', compute: '✦' };
61
43
 
44
+ const MANUAL_TYPES = ['text', 'number', 'select', 'tags', 'checkbox', 'date', 'url', 'resource'];
62
45
  const COMPUTE_KINDS = [
63
46
  { kind: 'prompt', label: 'AI prompt' },
64
47
  { kind: 'harness', label: 'Agent (harness)' },
@@ -68,34 +51,24 @@ const COMPUTE_KINDS = [
68
51
  const RESOURCE_KINDS = ['image', 'sheet', 'slides', 'workflow', 'graph'];
69
52
  const RESOURCE_ICON = { image: '🖼', sheet: '▦', slides: '▤', workflow: '⚙', graph: '◉' };
70
53
 
71
- // Popovers render through a body portal with FIXED positioning — inside the grid they'd be
72
- // clipped by the scroll container and out-stacked by the sticky header/row-number cells. anchor
73
- // is a DOMRect captured at open time; the box clamps to the viewport and flips above the anchor
74
- // when the bottom would overflow. Any scroll closes it (the anchor moved).
54
+ // Popovers render through a body portal with FIXED positioning — inside the
55
+ // grid they'd be clipped by the scroll container and out-stacked by the
56
+ // sticky header/row-number cells. anchor is a DOMRect captured at open time;
57
+ // the box clamps to the viewport and flips above the anchor when the bottom
58
+ // would overflow. A scroll OUTSIDE the box closes it (the anchor moved);
59
+ // scrolling inside it (a long prompt, a long option list) is the box's own.
75
60
  function PopPortal({ anchor, width = 250, estHeight = 300, className, children, onClose }) {
76
61
  const boxRef = useRef(null);
77
62
  useEffect(() => {
78
63
  if (!onClose) return undefined;
79
- const close = () => onClose();
80
- // mousedown, not click: React 18 flushes a listener attached in this effect synchronously
81
- // during the very discrete event that opened the popover, so a `click` listener closes the
82
- // box before it paints. A press inside the anchor is also ignored — that is the trigger's
83
- // own toggle, and closing here would race it into staying open.
84
- const onDown = (e) => {
85
- if (boxRef.current && boxRef.current.contains(e.target)) return;
86
- if (anchor && e.clientX >= anchor.left && e.clientX <= anchor.right
87
- && e.clientY >= anchor.top && e.clientY <= anchor.bottom) return;
64
+ const close = (e) => {
65
+ if (e?.type === 'scroll' && boxRef.current && e.target instanceof Node && boxRef.current.contains(e.target)) return;
88
66
  onClose();
89
67
  };
90
- window.addEventListener('mousedown', onDown);
91
68
  window.addEventListener('scroll', close, true);
92
69
  window.addEventListener('resize', close);
93
- return () => {
94
- window.removeEventListener('mousedown', onDown);
95
- window.removeEventListener('scroll', close, true);
96
- window.removeEventListener('resize', close);
97
- };
98
- }, [onClose, anchor]);
70
+ return () => { window.removeEventListener('scroll', close, true); window.removeEventListener('resize', close); };
71
+ }, [onClose]);
99
72
  if (!anchor) return null;
100
73
  const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8));
101
74
  let top = anchor.bottom + 6;
@@ -108,19 +81,37 @@ function PopPortal({ anchor, width = 250, estHeight = 300, className, children,
108
81
  );
109
82
  }
110
83
 
111
- // A muted rotation for select/tag pills when an option declares no color.
84
+ // Value styling. A column's `options` are its value vocabulary: each option is
85
+ // a value and a color. A select column offers them as choices; EVERY column
86
+ // type paints a cell whose value matches one as a pill in that color, so an
87
+ // enumerated result (CORRECT / WRONG, HEALTHY / AT RISK) reads at a glance.
88
+ // The palette is named so a color can mean something; an option that declares
89
+ // no color takes the muted rotation.
90
+ export const PILL_PALETTE = [
91
+ { name: 'green', color: '#D1FAE5' }, { name: 'red', color: '#FEE2E2' },
92
+ { name: 'amber', color: '#FEF3C7' }, { name: 'blue', color: '#DBEAFE' },
93
+ { name: 'purple', color: '#EDE9FE' }, { name: 'pink', color: '#FCE7F3' },
94
+ { name: 'teal', color: '#CCFBF1' }, { name: 'gray', color: '#E5E7EB' },
95
+ ];
112
96
  const PILL_FALLBACKS = ['#E0E7FF', '#FCE7F3', '#D1FAE5', '#FEF3C7', '#E0F2FE', '#F3E8FF', '#FFE4E6'];
113
97
 
114
- function normOptions(options) {
98
+ export function normOptions(options) {
115
99
  return (options || []).map((o, i) => {
116
100
  if (typeof o === 'string') return { label: o, color: PILL_FALLBACKS[i % PILL_FALLBACKS.length] };
117
101
  return { label: o.label ?? String(o.value ?? ''), color: o.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] };
118
102
  });
119
103
  }
120
104
 
105
+ const sameValue = (a, b) => String(a).trim().toLowerCase() === String(b).trim().toLowerCase();
106
+
107
+ /** The option a value matches (trimmed, case-insensitive), or null. */
108
+ function optionFor(value, options) {
109
+ if (value === undefined || value === null || value === '') return null;
110
+ return normOptions(options).find((o) => sameValue(o.label, value)) || null;
111
+ }
112
+
121
113
  function pillColor(label, options) {
122
- const opts = normOptions(options);
123
- const hit = opts.find((o) => o.label === label);
114
+ const hit = optionFor(label, options);
124
115
  if (hit) return hit.color;
125
116
  // stable fallback by hash so ad-hoc tags keep their color
126
117
  let h = 0;
@@ -153,21 +144,24 @@ function ResourceChip({ refVal, onOpen }) {
153
144
  );
154
145
  }
155
146
 
156
- // A small status dot for computed cells.
147
+ // A small status dot for computed cells while work is pending or went wrong;
148
+ // a finished cell is its value.
157
149
  function StatusDot({ status }) {
158
- if (!status || status === 'empty') return null;
150
+ if (!status || status === 'empty' || status === 'done') return null;
159
151
  return <span className={`shg-dot shg-dot-${status}`} title={status} />;
160
152
  }
161
153
 
162
154
  function CellValue({ cell, col, fetchBlobUrl, onOpenResource }) {
163
155
  const v = cell?.value;
164
156
  if (v === undefined || v === null || v === '') return <span className="shg-val-txt" />;
165
- // A typed artifact ref renders the same whether hand-set (resource column) or produced by a
166
- // compute kind (e.g. Generate image).
157
+ // A typed artifact ref renders the same whether hand-set (resource column)
158
+ // or produced by a compute kind (e.g. Generate image).
167
159
  if (v && typeof v === 'object' && !Array.isArray(v) && v.kind) {
168
160
  if (v.kind === 'image') return <RefImage refVal={v} fetchBlobUrl={fetchBlobUrl} />;
169
161
  return <ResourceChip refVal={v} onOpen={onOpenResource} />;
170
162
  }
163
+ const styled = col.type !== 'tags' && optionFor(v, col.options);
164
+ if (styled) return <span className="shg-pill" style={{ background: styled.color }}>{styled.label}</span>;
171
165
  switch (col.type) {
172
166
  case 'select':
173
167
  return <span className="shg-pill" style={{ background: pillColor(String(v), col.options) }}>{String(v)}</span>;
@@ -194,13 +188,12 @@ function CellValue({ cell, col, fetchBlobUrl, onOpenResource }) {
194
188
  }
195
189
  }
196
190
 
197
- export function SheetGrid({
198
- sheet, onChange, onRunCell, onRunColumn, readOnly = false, fetchBlobUrl, onOpenResource,
199
- peerMarks, onActiveCell, columnTypes = DEFAULT_COLUMN_TYPES, renderCell, renderColumnConfig,
200
- }) {
191
+ export function SheetGrid({ sheet, ops, onRunCell, onRunColumn, readOnly = false, fetchBlobUrl, onOpenResource, peers, onPresence }) {
201
192
  const columns = sheet?.columns || [];
202
193
  const rows = sheet?.rows || [];
203
194
  const cells = sheet?.cells || {};
195
+ const tabId = sheet?.id;
196
+ const canEdit = !readOnly && !!ops && !!tabId;
204
197
  const [editing, setEditing] = useState(null); // {rowId, colId, type}
205
198
  const [draft, setDraft] = useState('');
206
199
  const [menuCol, setMenuCol] = useState(null); // {id, rect} of the open column menu
@@ -209,15 +202,60 @@ export function SheetGrid({
209
202
  const [dropAt, setDropAt] = useState(null); // {kind, id, after} current drop slot
210
203
  const inputRef = useRef(null);
211
204
  const dragRef = useRef(null);
212
-
213
- // An unknown type still renders — as plain text, editable. Refusing to draw a column because
214
- // its type is unfamiliar would hide the person's data from them.
215
- const descOf = (type) => columnTypes.find((t) => t.type === type) || { type, label: type };
216
- const isComputed = (col) => !!descOf(col?.type).computed;
217
- const isEditable = (col) => {
218
- const d = descOf(col?.type);
219
- return d.editable ?? !d.computed;
220
- };
205
+ // Selection, Google Sheets style: a click selects, a drag or Shift extends
206
+ // the range, a double click / Enter / typing edits the focus cell. Indexes
207
+ // into this tab's rows and columns; presence carries the ids.
208
+ const [sel, setSel] = useState(null); // {a:{r,c}, f:{r,c}}
209
+ const dragSel = useRef(false);
210
+ const rootRef = useRef(null);
211
+ const presenceRef = useRef(onPresence);
212
+ presenceRef.current = onPresence;
213
+ const range = sel ? { r0: Math.min(sel.a.r, sel.f.r), r1: Math.max(sel.a.r, sel.f.r),
214
+ c0: Math.min(sel.a.c, sel.f.c), c1: Math.max(sel.a.c, sel.f.c) } : null;
215
+ const inSel = (ri, ci) => !!range && ri >= range.r0 && ri <= range.r1 && ci >= range.c0 && ci <= range.c1;
216
+ const isFocus = (ri, ci) => !!sel && sel.f.r === ri && sel.f.c === ci;
217
+ const clampSel = (p) => ({ r: Math.max(0, Math.min(p.r, rows.length - 1)), c: Math.max(0, Math.min(p.c, columns.length - 1)) });
218
+ const moveFocus = (dr, dc, extend) => setSel((cur) => {
219
+ if (!cur || !rows.length || !columns.length) return cur;
220
+ const f = clampSel({ r: cur.f.r + dr, c: cur.f.c + dc });
221
+ return { a: extend ? cur.a : f, f };
222
+ });
223
+ useEffect(() => {
224
+ const up = () => { dragSel.current = false; };
225
+ window.addEventListener('mouseup', up);
226
+ return () => window.removeEventListener('mouseup', up);
227
+ }, []);
228
+ // Tell peers what this person selects and types.
229
+ useEffect(() => {
230
+ const fn = presenceRef.current;
231
+ if (!fn) return;
232
+ const ids = (p) => [rows[p.r]?.id, columns[p.c]?.id];
233
+ fn({
234
+ sel: sel && rows[sel.f.r] && columns[sel.f.c] ? { a: ids(sel.a), f: ids(sel.f) } : null,
235
+ typing: editing && typeof draft === 'string' ? { key: cellKey(editing.rowId, editing.colId), text: draft } : null,
236
+ });
237
+ }, [sel, editing, draft, rows, columns]);
238
+ // Peers on this tab: who has which cell in focus, which cells sit in their
239
+ // ranges, and what they are typing where.
240
+ const peerLayer = useMemo(() => {
241
+ const focus = {}, tint = {}, typing = {};
242
+ const rIdx = new Map(rows.map((r, i) => [r.id, i]));
243
+ const cIdx = new Map(columns.map((c, i) => [c.id, i]));
244
+ for (const p of peers || []) {
245
+ if (p.typing && p.typing.key) typing[p.typing.key] = { text: p.typing.text, color: p.color, name: p.name };
246
+ if (!p.sel || !p.sel.a || !p.sel.f) continue;
247
+ const a = { r: rIdx.get(p.sel.a[0]), c: cIdx.get(p.sel.a[1]) }, f = { r: rIdx.get(p.sel.f[0]), c: cIdx.get(p.sel.f[1]) };
248
+ if ([a.r, a.c, f.r, f.c].some((v) => v === undefined)) continue;
249
+ focus[cellKey(p.sel.f[0], p.sel.f[1])] = p;
250
+ for (let r = Math.min(a.r, f.r); r <= Math.max(a.r, f.r); r++) {
251
+ for (let c = Math.min(a.c, f.c); c <= Math.max(a.c, f.c); c++) {
252
+ const k = cellKey(rows[r].id, columns[c].id);
253
+ if (!tint[k]) tint[k] = p.color;
254
+ }
255
+ }
256
+ }
257
+ return { focus, tint, typing };
258
+ }, [peers, rows, columns]);
221
259
 
222
260
  // Drag-to-resize: live via sizeDraft, persisted into the sheet on release.
223
261
  const startResize = (e, kind, id, start) => {
@@ -239,10 +277,9 @@ export function SheetGrid({
239
277
  document.body.style.cursor = '';
240
278
  if (!d) return;
241
279
  setSizeDraft({});
242
- mutate((n) => {
243
- if (d.kind === 'col') { const c = n.columns.find((x) => x.id === d.id); if (c) c.width = Math.round(d.last); }
244
- else { const r = n.rows.find((x) => x.id === d.id); if (r) r.height = Math.round(d.last); }
245
- });
280
+ if (!canEdit) return;
281
+ if (d.kind === 'col') { const c = columns.find((x) => x.id === d.id); if (c) ops.setColumn(tabId, { ...c, width: Math.round(d.last) }); }
282
+ else { const r = rows.find((x) => x.id === d.id); if (r) ops.setRow(tabId, { ...r, height: Math.round(d.last) }); }
246
283
  };
247
284
  window.addEventListener('mousemove', onMove);
248
285
  window.addEventListener('mouseup', onUp);
@@ -251,16 +288,17 @@ export function SheetGrid({
251
288
  const colWidth = (col) => (sizeDraft.col && sizeDraft.col[col.id]) || col.width || undefined;
252
289
 
253
290
  // Drag-to-reorder (columns by their header, rows by their number cell).
254
- const reorder = (kind, fromId, toId, after) => mutate((n) => {
255
- const arr = kind === 'col' ? n.columns : n.rows;
256
- const i = arr.findIndex((x) => x.id === fromId);
257
- if (i < 0 || fromId === toId) return;
258
- const [item] = arr.splice(i, 1);
259
- let j = arr.findIndex((x) => x.id === toId);
260
- if (j < 0) { arr.splice(i, 0, item); return; }
291
+ const reorder = (kind, fromId, toId, after) => {
292
+ if (!canEdit || fromId === toId) return;
293
+ const arr = (kind === 'col' ? columns : rows).map((x) => x.id);
294
+ const i = arr.indexOf(fromId);
295
+ if (i < 0) return;
296
+ arr.splice(i, 1);
297
+ let j = arr.indexOf(toId);
298
+ if (j < 0) return;
261
299
  if (after) j += 1;
262
- arr.splice(j, 0, item);
263
- });
300
+ if (kind === 'col') ops.moveColumn(tabId, fromId, j); else ops.moveRow(tabId, fromId, j);
301
+ };
264
302
  const dndProps = (kind, id) => (readOnly ? {} : {
265
303
  draggable: true,
266
304
  onDragStart: (e) => {
@@ -296,54 +334,36 @@ export function SheetGrid({
296
334
  }
297
335
  return cls;
298
336
  };
299
- // The number gutter is FIXED: sized by the digit count of the row total so it never stretches
300
- // (an empty grid otherwise splits the table width). Wide enough for the number AND the delete
301
- // button beside it, both at a size worth aiming at.
302
- const numW = Math.max(48, 30 + String(rows.length || 1).length * 9);
337
+ // The number gutter is FIXED: sized by the digit count of the row total so
338
+ // it never stretches (an empty grid otherwise splits the table width).
339
+ const numW = Math.max(40, 24 + String(rows.length || 1).length * 9);
303
340
  const numStyle = { width: numW, minWidth: numW, maxWidth: numW };
304
341
  const rowHeight = (row) => (sizeDraft.row && sizeDraft.row[row.id]) || row.height || undefined;
305
342
 
306
343
  useEffect(() => { if (editing && inputRef.current) inputRef.current.focus(); }, [editing]);
307
344
 
308
- const mutate = (fn) => {
309
- if (readOnly || !onChange) return;
310
- const next = JSON.parse(JSON.stringify(sheet));
311
- fn(next);
312
- onChange(next);
345
+ const setCell = (rowId, colId, value) => {
346
+ if (!canEdit) return;
347
+ ops.setCell(tabId, cellKey(rowId, colId), { value, status: 'done', updated_at: Math.floor(Date.now() / 1000) });
313
348
  };
314
349
 
315
- // A manual edit writes the value and nothing else. It used to stamp `status:'done'`, which
316
- // made every hand-typed cell claim to be the output of a run that never happened — and forced
317
- // status rendering to be gated on the column type rather than on the cell. On a computed
318
- // column the surrounding run record is kept, because there an override sits on top of a real
319
- // run and the link to that run is still true.
320
- const setCell = (rowId, colId, value) => mutate((n) => {
321
- n.cells = n.cells || {};
322
- const k = cellKey(rowId, colId);
323
- const col = (n.columns || []).find((c) => c.id === colId);
324
- const prev = n.cells[k];
325
- n.cells[k] = isComputed(col) && prev ? { ...prev, value } : { value };
326
- });
327
-
328
- const openEdit = (rowId, col, anchorEl) => {
329
- if (readOnly) return;
330
- if (!isEditable(col)) return;
331
- if (col.type === 'checkbox') { // click toggles directly
350
+ const openEdit = (rowId, col, anchorEl, initial) => {
351
+ if (!canEdit) return;
352
+ if (col.type === 'compute') return; // computed cells aren't hand-edited
353
+ if (col.type === 'checkbox') { // toggles directly
332
354
  const cur = cells[cellKey(rowId, col.id)];
333
355
  setCell(rowId, col.id, !(cur && cur.value));
334
356
  return;
335
357
  }
336
358
  const c = cells[cellKey(rowId, col.id)];
337
359
  const v = c?.value;
338
- if (col.type === 'tags') setDraft(Array.isArray(v) ? v.join(', ') : (v || ''));
360
+ if (col.type === 'tags') setDraft(initial ?? (Array.isArray(v) ? v.join(', ') : (v || '')));
339
361
  else if (col.type === 'resource') setDraft(v && typeof v === 'object' ? v : { kind: 'sheet', name: '', id: '', url: '' });
340
- else setDraft(v == null ? '' : String(v));
362
+ else setDraft(initial ?? (v == null ? '' : String(v)));
341
363
  setEditing({ rowId, colId: col.id, type: col.type, rect: anchorEl?.getBoundingClientRect?.() || null });
342
- onActiveCell && onActiveCell(cellKey(rowId, col.id));
343
364
  };
344
365
 
345
366
  const commitEdit = () => {
346
- onActiveCell && onActiveCell(null);
347
367
  if (!editing) return;
348
368
  const { rowId, colId, type } = editing;
349
369
  let value = draft;
@@ -353,30 +373,104 @@ export function SheetGrid({
353
373
  setEditing(null);
354
374
  };
355
375
 
356
- const addColumn = () => mutate((n) => {
357
- n.columns.push({ id: uid('col'), name: `Column ${n.columns.length + 1}`, type: 'text' });
358
- });
359
- const addRow = () => mutate((n) => { n.rows.push({ id: uid('row') }); });
360
- const deleteColumn = (colId) => mutate((n) => {
361
- n.columns = n.columns.filter((c) => c.id !== colId);
362
- for (const k of Object.keys(n.cells || {})) if (k.endsWith(`:${colId}`)) delete n.cells[k];
363
- });
364
- const deleteRow = (rowId) => mutate((n) => {
365
- n.rows = n.rows.filter((r) => r.id !== rowId);
366
- for (const k of Object.keys(n.cells || {})) if (k.startsWith(`${rowId}:`)) delete n.cells[k];
367
- });
368
- const renameColumn = (colId, name) => mutate((n) => {
369
- const c = n.columns.find((x) => x.id === colId); if (c) c.name = name;
370
- });
371
- const configureColumn = (colId, patch) => mutate((n) => {
372
- const c = n.columns.find((x) => x.id === colId); if (!c) return;
373
- Object.assign(c, patch);
374
- // A column carries the config of its own type and no other. Changing the type takes the old
375
- // config with it, so a harness column that becomes a text column stops carrying a prompt.
376
- if (patch.type) {
377
- for (const d of columnTypes) if (d.configKey && d.type !== patch.type) delete c[d.configKey];
376
+ const addColumn = () => canEdit && ops.setColumn(tabId, { id: uid('col'), name: `Column ${columns.length + 1}`, type: 'text' });
377
+ const addRow = () => canEdit && ops.setRow(tabId, { id: uid('row') });
378
+ const deleteColumn = (colId) => canEdit && ops.deleteColumn(tabId, colId);
379
+ const deleteRow = (rowId) => canEdit && ops.deleteRow(tabId, rowId);
380
+ const renameColumn = (colId, name) => {
381
+ const c = columns.find((x) => x.id === colId);
382
+ if (canEdit && c) ops.setColumn(tabId, { ...c, name });
383
+ };
384
+ const configureColumn = (colId, patch) => {
385
+ const c = columns.find((x) => x.id === colId);
386
+ if (!canEdit || !c) return;
387
+ const next = { ...c, ...patch };
388
+ if (patch.type && patch.type !== 'compute') delete next.compute;
389
+ ops.setColumn(tabId, next);
390
+ };
391
+
392
+ // The selection as text: one line per row, tab between cells.
393
+ const cellText = (c) => {
394
+ const v = c?.value;
395
+ if (v === undefined || v === null) return '';
396
+ if (Array.isArray(v)) return v.join(', ');
397
+ if (typeof v === 'object') return v.name || v.url || v.id || '';
398
+ return String(v);
399
+ };
400
+ const copySelection = (e) => {
401
+ if (!range || editing) return;
402
+ const lines = [];
403
+ for (let r = range.r0; r <= range.r1; r++) {
404
+ const parts = [];
405
+ for (let c = range.c0; c <= range.c1; c++) parts.push(cellText(cells[cellKey(rows[r].id, columns[c].id)]));
406
+ lines.push(parts.join('\t'));
378
407
  }
379
- });
408
+ e.clipboardData.setData('text/plain', lines.join('\n'));
409
+ e.preventDefault();
410
+ };
411
+ const pasteAt = (e) => {
412
+ if (!sel || editing || !canEdit) return;
413
+ const text = e.clipboardData.getData('text/plain');
414
+ if (!text) return;
415
+ e.preventDefault();
416
+ const now = Math.floor(Date.now() / 1000);
417
+ const patch = {};
418
+ const lines = text.replace(/\r/g, '').split('\n');
419
+ if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
420
+ lines.forEach((line, dr) => line.split('\t').forEach((raw, dc) => {
421
+ const row = rows[sel.f.r + dr], col = columns[sel.f.c + dc];
422
+ if (!row || !col || col.type === 'compute') return;
423
+ let value = raw;
424
+ if (col.type === 'number') value = raw === '' ? null : Number(raw);
425
+ else if (col.type === 'checkbox') value = /^(true|yes|1|✓)$/i.test(raw.trim());
426
+ else if (col.type === 'tags') value = raw ? raw.split(',').map((x) => x.trim()).filter(Boolean) : [];
427
+ patch[cellKey(row.id, col.id)] = value === null || value === '' ? null : { value, status: 'done', updated_at: now };
428
+ }));
429
+ if (Object.keys(patch).length) ops.setCells(tabId, patch);
430
+ setSel({ a: sel.f, f: clampSel({ r: sel.f.r + lines.length - 1, c: sel.f.c + Math.max(...lines.map((l) => l.split('\t').length)) - 1 }) });
431
+ };
432
+ const clearSelection = () => {
433
+ if (!range || !canEdit) return;
434
+ const patch = {};
435
+ for (let r = range.r0; r <= range.r1; r++) {
436
+ for (let c = range.c0; c <= range.c1; c++) {
437
+ if (columns[c].type === 'compute') continue;
438
+ const k = cellKey(rows[r].id, columns[c].id);
439
+ if (cells[k]) patch[k] = null;
440
+ }
441
+ }
442
+ if (Object.keys(patch).length) ops.setCells(tabId, patch);
443
+ };
444
+ const onKeyDown = (e) => {
445
+ if (editing || menuCol) return;
446
+ if (!sel) return;
447
+ const meta = e.metaKey || e.ctrlKey;
448
+ if (meta && (e.key === 'c' || e.key === 'v' || e.key === 'x')) return; // copy/paste events handle these
449
+ const focusCell = () => ({ row: rows[sel.f.r], col: columns[sel.f.c] });
450
+ switch (e.key) {
451
+ case 'ArrowUp': e.preventDefault(); moveFocus(-1, 0, e.shiftKey); return;
452
+ case 'ArrowDown': e.preventDefault(); moveFocus(1, 0, e.shiftKey); return;
453
+ case 'ArrowLeft': e.preventDefault(); moveFocus(0, -1, e.shiftKey); return;
454
+ case 'ArrowRight': e.preventDefault(); moveFocus(0, 1, e.shiftKey); return;
455
+ case 'Tab': e.preventDefault(); moveFocus(0, e.shiftKey ? -1 : 1, false); return;
456
+ case 'Escape': setSel(null); return;
457
+ case 'Enter': case 'F2': {
458
+ e.preventDefault();
459
+ const { row, col } = focusCell();
460
+ if (row && col) openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell="${cellKey(row.id, col.id)}"]`));
461
+ return;
462
+ }
463
+ case 'Delete': case 'Backspace': e.preventDefault(); clearSelection(); return;
464
+ default:
465
+ }
466
+ if (!meta && !e.altKey && e.key.length === 1) {
467
+ const { row, col } = focusCell();
468
+ if (row && col && col.type !== 'compute' && col.type !== 'checkbox') {
469
+ e.preventDefault();
470
+ openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell="${cellKey(row.id, col.id)}"]`), e.key);
471
+ }
472
+ }
473
+ };
380
474
 
381
475
  // The inline editor for the editing cell, by type.
382
476
  const renderEditor = (col) => {
@@ -426,12 +520,16 @@ export function SheetGrid({
426
520
  placeholder={col.type === 'tags' ? 'tag, tag, …' : ''}
427
521
  onChange={(e) => setDraft(e.target.value)}
428
522
  onBlur={commitEdit}
429
- onKeyDown={(e) => { if (e.key === 'Enter') commitEdit(); if (e.key === 'Escape') setEditing(null); }} />
523
+ onKeyDown={(e) => {
524
+ if (e.key === 'Enter') { e.preventDefault(); commitEdit(); moveFocus(1, 0, false); rootRef.current?.focus(); }
525
+ else if (e.key === 'Tab') { e.preventDefault(); commitEdit(); moveFocus(0, e.shiftKey ? -1 : 1, false); rootRef.current?.focus(); }
526
+ else if (e.key === 'Escape') { setEditing(null); rootRef.current?.focus(); }
527
+ }} />
430
528
  );
431
529
  };
432
530
 
433
531
  return (
434
- <div className="shg">
532
+ <div className="shg" ref={rootRef} tabIndex={0} onKeyDown={onKeyDown} onCopy={copySelection} onPaste={pasteAt}>
435
533
  <div className="shg-scroll">
436
534
  <table className="shg-table">
437
535
  <thead>
@@ -439,7 +537,7 @@ export function SheetGrid({
439
537
  <th className="shg-corner" style={numStyle} />
440
538
  {columns.map((col) => (
441
539
  <th key={col.id}
442
- className={'shg-col' + (isComputed(col) ? ' shg-col-compute' : '') + dndClass('col', col.id)}
540
+ className={'shg-col' + (col.type === 'compute' ? ' shg-col-compute' : '') + dndClass('col', col.id)}
443
541
  style={colWidth(col) ? { width: colWidth(col), minWidth: colWidth(col), maxWidth: colWidth(col) } : undefined}
444
542
  {...dndProps('col', col.id)}>
445
543
  {!readOnly && (
@@ -448,8 +546,6 @@ export function SheetGrid({
448
546
  <div className="shg-col-h">
449
547
  <ColumnHeader
450
548
  col={col} columns={columns} readOnly={readOnly}
451
- desc={descOf(col.type)} columnTypes={columnTypes}
452
- renderColumnConfig={renderColumnConfig}
453
549
  menuOpen={menuCol?.id === col.id}
454
550
  menuAnchor={menuCol?.id === col.id ? menuCol.rect : null}
455
551
  onMenu={(e) => setMenuCol(menuCol?.id === col.id ? null
@@ -458,7 +554,8 @@ export function SheetGrid({
458
554
  onRename={renameColumn}
459
555
  onConfigure={configureColumn}
460
556
  onDelete={() => { setMenuCol(null); deleteColumn(col.id); }}
461
- onRun={isComputed(col) && onRunColumn ? () => onRunColumn(col.id) : null} />
557
+ onRun={col.type === 'compute' && onRunColumn ? () => onRunColumn(col.id) : null}
558
+ width={colWidth(col)} />
462
559
  </div>
463
560
  </th>
464
561
  ))}
@@ -469,7 +566,7 @@ export function SheetGrid({
469
566
  </thead>
470
567
  <tbody>
471
568
  {rows.map((row, ri) => (
472
- <tr key={row.id} data-row-id={row.id}
569
+ <tr key={row.id}
473
570
  style={{
474
571
  ...(rowHeight(row) ? { height: rowHeight(row) } : null),
475
572
  '--shg-clamp': Math.max(1, Math.floor(((rowHeight(row) || 34) - 10) / 18)),
@@ -482,56 +579,51 @@ export function SheetGrid({
482
579
  <span className="shg-resize-row" onMouseDown={(e) => startResize(e, 'row', row.id, rowHeight(row) || e.currentTarget.closest('tr').offsetHeight)} />
483
580
  )}
484
581
  </td>
485
- {columns.map((col) => {
486
- const c = cells[cellKey(row.id, col.id)] || {};
487
- const computed = isComputed(col);
582
+ {columns.map((col, ci) => {
583
+ const key = cellKey(row.id, col.id);
584
+ const c = cells[key] || {};
488
585
  const isEditing = editing && editing.rowId === row.id && editing.colId === col.id;
489
- const peer = peerMarks && peerMarks[cellKey(row.id, col.id)];
490
- // A host owns the whole cell body when it wants to: a running cell's live text
491
- // lives in the host's run store, not in the sheet JSON, so only a closure can
492
- // reach it. Returning undefined falls through to the built-in rendering.
493
- const custom = renderCell && renderCell({
494
- cell: c, column: col, row, rowIndex: ri, sheet, computed,
495
- width: colWidth(col), height: rowHeight(row), editing: !!isEditing, readOnly,
496
- setCell: (v) => setCell(row.id, col.id, v),
497
- runCell: onRunCell && !readOnly ? () => onRunCell(row.id, col.id) : null,
498
- });
586
+ const peer = peerLayer.focus[key];
587
+ const ghost = !isEditing && peerLayer.typing[key];
588
+ const selected = inSel(ri, ci), focused = isFocus(ri, ci);
589
+ const shadows = [];
590
+ if (focused) shadows.push('inset 0 0 0 2px var(--brand, #0E7490)');
591
+ if (peer) shadows.push(`inset 0 0 0 2px ${peer.color}`);
592
+ const tint = !selected && peerLayer.tint[key];
499
593
  return (
500
- <td key={col.id} data-col-id={col.id}
501
- className={'shg-cell' + (computed ? ' shg-cell-compute' : '')
502
- + (c.status && computed ? ` shg-cell-${c.status}` : '')
594
+ <td key={col.id} data-cell={key}
595
+ className={'shg-cell' + (col.type === 'compute' ? ' shg-cell-compute' : '')
596
+ + (c.status && col.type === 'compute' ? ` shg-cell-${c.status}` : '')
597
+ + (selected ? ' shg-sel' : '') + (focused ? ' shg-focus' : '')
503
598
  + (peer ? ' shg-cell-peer' : '')}
504
- style={peer ? { boxShadow: `inset 0 0 0 2px ${peer.color}` } : undefined}
505
- onClick={(e) => { if (!isEditing) openEdit(row.id, col, e.currentTarget); }}
599
+ style={{ ...(shadows.length ? { boxShadow: shadows.join(', ') } : null),
600
+ ...(tint ? { background: withAlpha(tint, 0.10) } : null) }}
601
+ onMouseDown={(e) => {
602
+ if (e.button !== 0 || isEditing) return;
603
+ if (editing) commitEdit();
604
+ const p = { r: ri, c: ci };
605
+ setSel((cur) => (e.shiftKey && cur ? { a: cur.a, f: p } : { a: p, f: p }));
606
+ dragSel.current = true;
607
+ e.preventDefault();
608
+ rootRef.current?.focus();
609
+ }}
610
+ onMouseEnter={() => { if (dragSel.current) setSel((cur) => (cur ? { a: cur.a, f: { r: ri, c: ci } } : cur)); }}
611
+ onClick={(e) => { if (col.type === 'checkbox' && !isEditing) openEdit(row.id, col, e.currentTarget); }}
612
+ onDoubleClick={(e) => { if (!isEditing) openEdit(row.id, col, e.currentTarget); }}
506
613
  title={c.error || ''}>
507
- {/* The boundaries a spreadsheet lets you grab are the ones you can see, and
508
- from row 20 the header is scrolled away. Both edges of every cell resize
509
- the same column and row the header and the gutter do — same handler,
510
- same drag, just reachable where the person already is. */}
511
- {!readOnly && (
512
- <>
513
- <span className="shg-resize-col shg-resize-in-cell"
514
- onClick={(e) => e.stopPropagation()}
515
- onMouseDown={(e) => startResize(e, 'col', col.id,
516
- colWidth(col) || e.currentTarget.closest('td').offsetWidth)} />
517
- <span className="shg-resize-row shg-resize-in-cell"
518
- onClick={(e) => e.stopPropagation()}
519
- onMouseDown={(e) => startResize(e, 'row', row.id,
520
- rowHeight(row) || e.currentTarget.closest('tr').offsetHeight)} />
521
- </>
522
- )}
523
614
  {peer && <span className="shg-peer-flag" style={{ background: peer.color }}>{peer.name}</span>}
524
615
  {isEditing ? renderEditor(col) : (
525
- <div className="shg-val">
526
- {custom !== undefined ? custom : (
527
- <>
528
- {computed && <StatusDot status={c.status} />}
529
- <CellValue cell={c} col={col} fetchBlobUrl={fetchBlobUrl} onOpenResource={onOpenResource} />
530
- {computed && !readOnly && onRunCell && (
531
- <button className="shg-runcell" title="Run this cell"
532
- onClick={(e) => { e.stopPropagation(); onRunCell(row.id, col.id); }}>▶</button>
533
- )}
534
- </>
616
+ <div className="shg-val"
617
+ style={{ maxWidth: (colWidth(col) ? colWidth(col) - 20 : 400) }}>
618
+ {col.type === 'compute' && <StatusDot status={c.status} />}
619
+ {ghost ? (
620
+ <span className="shg-ghost" style={{ color: ghost.color }} title={`${ghost.name} is typing`}>{ghost.text}</span>
621
+ ) : (
622
+ <CellValue cell={c} col={col} fetchBlobUrl={fetchBlobUrl} onOpenResource={onOpenResource} />
623
+ )}
624
+ {col.type === 'compute' && !readOnly && onRunCell && (
625
+ <button className="shg-runcell" title="Run this cell"
626
+ onClick={(e) => { e.stopPropagation(); onRunCell(row.id, col.id); }}>▶</button>
535
627
  )}
536
628
  </div>
537
629
  )}
@@ -554,16 +646,15 @@ export function SheetGrid({
554
646
  );
555
647
  }
556
648
 
557
- function ColumnHeader({
558
- col, columns, readOnly, desc, columnTypes, renderColumnConfig,
559
- menuOpen, menuAnchor, onMenu, onCloseMenu, onRename, onConfigure, onDelete, onRun,
560
- }) {
649
+ function ColumnHeader({ col, columns, readOnly, menuOpen, menuAnchor, onMenu, onCloseMenu, onRename, onConfigure, onDelete, onRun, width }) {
561
650
  const [editing, setEditing] = useState(false);
562
651
  const [name, setName] = useState(col.name);
563
652
  useEffect(() => setName(col.name), [col.name]);
564
- const badge = desc.badge ? desc.badge(col) : undefined;
653
+ // A narrow column keeps its name: the caption goes first, then the Run label.
654
+ const w = Number(width) || 0;
655
+ const fit = w && w < 160 ? ' tight' : w && w < 200 ? ' narrow' : '';
565
656
  return (
566
- <div className="shg-colhdr">
657
+ <div className={'shg-colhdr' + fit}>
567
658
  <div className="shg-colhdr-main">
568
659
  {editing && !readOnly ? (
569
660
  <input className="shg-colname-input" value={name} autoFocus
@@ -573,20 +664,19 @@ function ColumnHeader({
573
664
  ) : (
574
665
  <span className="shg-colname" onDoubleClick={() => !readOnly && setEditing(true)} title={col.name}>{col.name}</span>
575
666
  )}
576
- <span className={'shg-coltype' + (desc.computed ? ' compute' : '')}>
577
- {desc.label || col.type}
578
- {badge ? ` · ${badge}` : ''}
667
+ <span className={'shg-coltype' + (col.type === 'compute' ? ' compute' : '')}>
668
+ {TYPE_LABEL[col.type] || col.type}
669
+ {col.type === 'compute' && col.compute?.kind ? ` · ${col.compute.kind}` : ''}
579
670
  </span>
580
671
  </div>
581
672
  {!readOnly && (
582
673
  <div className="shg-colhdr-tools">
583
- {onRun && <button className="shg-colrun" onClick={onRun} title="Run this column">▶ Run</button>}
674
+ {onRun && <button className="shg-colrun" onClick={onRun} title="Run this column" aria-label="Run this column">▶<span className="shg-colrun-label"> Run</span></button>}
584
675
  <button className="shg-colmenu-btn" onClick={(e) => onMenu(e)} title="Column settings">⋯</button>
585
676
  </div>
586
677
  )}
587
678
  {menuOpen && !readOnly && (
588
679
  <ColumnMenu col={col} columns={columns} anchor={menuAnchor}
589
- columnTypes={columnTypes} renderColumnConfig={renderColumnConfig}
590
680
  onApply={(patch) => { onConfigure(col.id, patch); onCloseMenu(); }}
591
681
  onDelete={onDelete} onClose={onCloseMenu} />
592
682
  )}
@@ -594,13 +684,64 @@ function ColumnHeader({
594
684
  );
595
685
  }
596
686
 
597
- // The column configuration popover: type, options (select/tags), and the type's own config body.
598
- // Product-agnostic — plain controlled inputs, applied as one patch. A host that adds a column
599
- // type supplies renderColumnConfig and owns the body below the Type select.
600
- function ColumnMenu({ col, columns, anchor, columnTypes, renderColumnConfig, onApply, onDelete, onClose }) {
687
+ // The column's values as pills in one field: type a value and press Enter or
688
+ // comma to add it, Backspace on an empty field removes the last, and clicking
689
+ // a pill opens the palette to pick its color. Select and tags columns offer
690
+ // these as choices; every column paints a matching value in its color.
691
+ function ValuePills({ values, onChange }) {
692
+ const [text, setText] = useState('');
693
+ const [picking, setPicking] = useState(null); // index of the pill whose palette is open
694
+ const add = () => {
695
+ const label = text.trim();
696
+ if (!label) return;
697
+ if (!values.some((v) => sameValue(v.label, label))) onChange([...values, { label }]);
698
+ setText('');
699
+ };
700
+ const remove = (i) => { onChange(values.filter((_, j) => j !== i)); setPicking(null); };
701
+ const paint = (i, color) => { onChange(values.map((v, j) => (j === i ? { ...v, color } : v))); setPicking(null); };
702
+ return (
703
+ <div className="shg-values" onClick={(e) => { if (e.target === e.currentTarget) e.currentTarget.querySelector('input')?.focus(); }}>
704
+ {values.map((v, i) => (
705
+ <span key={v.label} className="shg-value">
706
+ <button type="button" className="shg-pill shg-pill-btn"
707
+ style={{ background: v.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] }}
708
+ title="Pick a color" aria-expanded={picking === i}
709
+ onClick={(e) => { e.stopPropagation(); setPicking(picking === i ? null : i); }}>
710
+ {v.label}
711
+ <span className="shg-value-x" role="button" aria-label={`Remove ${v.label}`}
712
+ onClick={(e) => { e.stopPropagation(); remove(i); }}>×</span>
713
+ </button>
714
+ {picking === i && (
715
+ <span className="shg-swatches" role="listbox" aria-label={`Color for ${v.label}`}>
716
+ {PILL_PALETTE.map((p) => (
717
+ <button key={p.name} type="button" role="option" aria-selected={v.color === p.color}
718
+ className={'shg-swatch' + (v.color === p.color ? ' on' : '')}
719
+ style={{ background: p.color }} title={p.name}
720
+ onClick={(e) => { e.stopPropagation(); paint(i, p.color); }} />
721
+ ))}
722
+ </span>
723
+ )}
724
+ </span>
725
+ ))}
726
+ <input className="shg-values-input" value={text} placeholder={values.length ? '' : 'Type a value, press Enter'}
727
+ onChange={(e) => setText(e.target.value)}
728
+ onKeyDown={(e) => {
729
+ if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add(); }
730
+ else if (e.key === 'Backspace' && !text && values.length) remove(values.length - 1);
731
+ }}
732
+ onBlur={add} />
733
+ </div>
734
+ );
735
+ }
736
+
737
+ // The column configuration popover: type, options (select/tags), and the
738
+ // compute mount (prompt / harness / workflow + deps). Product-agnostic —
739
+ // plain controlled inputs, applied as one patch.
740
+ function ColumnMenu({ col, columns, anchor, onApply, onDelete, onClose }) {
601
741
  const [type, setType] = useState(col.type || 'text');
602
- const [optText, setOptText] = useState(
603
- normOptions(col.options).map((o) => o.label).join('\n'));
742
+ // The column's values, in order, each with the color it was given (or none).
743
+ const [values, setValues] = useState(() => (col.options || []).map((o) =>
744
+ (typeof o === 'string' ? { label: o } : { label: o.label ?? String(o.value ?? ''), ...(o.color ? { color: o.color } : {}) })));
604
745
  const comp = col.compute || {};
605
746
  const [kind, setKind] = useState(comp.kind || 'prompt');
606
747
  const [prompt, setPrompt] = useState(comp.prompt || '');
@@ -608,20 +749,37 @@ function ColumnMenu({ col, columns, anchor, columnTypes, renderColumnConfig, onA
608
749
  const [wfSlug, setWfSlug] = useState(comp.workflow_slug || '');
609
750
  const [outKey, setOutKey] = useState(comp.output_key || '');
610
751
  const [deps, setDeps] = useState(new Set(comp.deps || []));
752
+ const ref = useRef(null);
611
753
 
612
- const others = columns.filter((c) => c.id !== col.id);
613
- const toggleDep = (id) => setDeps((s) => {
614
- const n = new Set(s);
615
- if (n.has(id)) n.delete(id); else n.add(id);
616
- return n;
617
- });
754
+ useEffect(() => {
755
+ // a press inside the prompt's mention menu (a portal on the body) is not "outside"
756
+ const onDown = (e) => {
757
+ if (ref.current && !ref.current.contains(e.target) && !(e.target.closest && e.target.closest('.uic-pop'))) onClose();
758
+ };
759
+ window.addEventListener('mousedown', onDown);
760
+ return () => window.removeEventListener('mousedown', onDown);
761
+ }, [onClose]);
762
+
763
+ // What the prompt may read: the columns to the LEFT of this one (a row fills left to right,
764
+ // so those hold values when this cell computes). The rest are shown, but say why not.
765
+ const promptItems = useMemo(() => {
766
+ const at = columns.findIndex((c) => c.id === col.id);
767
+ return columns.filter((c) => c.id !== col.id).map((c) => {
768
+ const idx = columns.findIndex((x) => x.id === c.id);
769
+ const right = at >= 0 && idx > at;
770
+ return {
771
+ id: c.id, name: c.name, kind: c.type, section: right ? 'Fills after this column' : 'Columns',
772
+ icon: TYPE_GLYPH[c.type] || 'Aa', description: TYPE_LABEL[c.type] || c.type,
773
+ color: c.type === 'compute' ? '#7C3AED' : undefined,
774
+ disabled: right ? 'to the right' : false,
775
+ };
776
+ });
777
+ }, [columns, col.id]);
618
778
 
619
779
  const apply = () => {
620
780
  const patch = { type };
621
- if (type === 'select' || type === 'tags') {
622
- patch.options = optText.split('\n').map((s) => s.trim()).filter(Boolean);
623
- }
624
- // The built-in 'compute' type's own editor. Any other type's config comes from the host.
781
+ // A value with a chosen color travels as {label, color}; the rest as labels.
782
+ patch.options = values.map((v) => (v.color ? { label: v.label, color: v.color } : v.label));
625
783
  if (type === 'compute') {
626
784
  const compute = { kind, deps: [...deps] };
627
785
  if (kind === 'prompt') compute.prompt = prompt;
@@ -632,161 +790,94 @@ function ColumnMenu({ col, columns, anchor, columnTypes, renderColumnConfig, onA
632
790
  onApply(patch);
633
791
  };
634
792
 
635
- // A custom body owns its own primary action, because only it knows when its config is
636
- // complete. It gets applyPatch to commit and close in one call.
637
- const custom = renderColumnConfig && renderColumnConfig({
638
- column: col, columns, type,
639
- applyPatch: (patch) => onApply({ type, ...patch }),
640
- deleteColumn: onDelete,
641
- close: onClose,
642
- });
643
-
644
- const desc = columnTypes.find((t) => t.type === type) || {};
645
793
  return (
646
- <PopPortal anchor={anchor} width={desc.configWidth || 250} estHeight={desc.configHeight || 340}
647
- className="shg-menu" onClose={onClose}>
648
- <div onClick={(e) => e.stopPropagation()}>
794
+ <PopPortal anchor={anchor} width={250} estHeight={340} className="shg-menu" onClose={onClose}>
795
+ <div ref={ref} onClick={(e) => e.stopPropagation()}>
649
796
  <label className="shg-menu-lbl">Type
650
797
  <select className="shg-menu-input" value={type} onChange={(e) => setType(e.target.value)}>
651
- {columnTypes.map((t) => <option key={t.type} value={t.type}>{t.label}</option>)}
798
+ {MANUAL_TYPES.map((t) => <option key={t} value={t}>{TYPE_LABEL[t]}</option>)}
799
+ <option value="compute">Computed</option>
652
800
  </select>
653
801
  </label>
654
802
 
655
- {(type === 'select' || type === 'tags') && (
656
- <label className="shg-menu-lbl">Options (one per line)
657
- <textarea className="shg-menu-input" rows={3} value={optText}
658
- onChange={(e) => setOptText(e.target.value)} placeholder={'Todo\nDoing\nDone'} />
659
- </label>
660
- )}
803
+ <div className="shg-menu-lbl">{type === 'select' || type === 'tags' ? 'Options' : 'Values'}
804
+ <ValuePills values={values} onChange={setValues} />
805
+ </div>
661
806
 
662
- {custom !== undefined ? custom : (
807
+ {type === 'compute' && (
663
808
  <>
664
- {type === 'compute' && (
809
+ <label className="shg-menu-lbl">Runs
810
+ <select className="shg-menu-input" value={kind} onChange={(e) => setKind(e.target.value)}>
811
+ {COMPUTE_KINDS.map((k) => <option key={k.kind} value={k.kind}>{k.label}</option>)}
812
+ </select>
813
+ </label>
814
+ {(kind === 'prompt' || kind === 'harness') && (
815
+ <div className="shg-menu-lbl">Prompt
816
+ <div className="shg-menu-input shg-menu-prompt">
817
+ <MentionInput
818
+ value={prompt}
819
+ onChange={(v, ms) => { setPrompt(v); setDeps(new Set(ms.map((m) => m.id))); }}
820
+ items={promptItems}
821
+ placeholder="Summarize @Company in one line"
822
+ menuTitle="Columns this cell can read"
823
+ emptyText="No column by that name"
824
+ label="Prompt"
825
+ />
826
+ </div>
827
+ <div className="shg-menu-hint">Type @ to add a column from this row. Columns to the left fill first.</div>
828
+ </div>
829
+ )}
830
+ {kind === 'harness' && (
831
+ <label className="shg-menu-lbl">Agent id
832
+ <input className="shg-menu-input" value={harnessId} onChange={(e) => setHarnessId(e.target.value)} placeholder="chrn_…" />
833
+ </label>
834
+ )}
835
+ {kind === 'workflow' && (
665
836
  <>
666
- <label className="shg-menu-lbl">Runs
667
- <select className="shg-menu-input" value={kind} onChange={(e) => setKind(e.target.value)}>
668
- {COMPUTE_KINDS.map((k) => <option key={k.kind} value={k.kind}>{k.label}</option>)}
669
- </select>
837
+ <label className="shg-menu-lbl">Workflow id
838
+ <input className="shg-menu-input" value={wfSlug} onChange={(e) => setWfSlug(e.target.value)} placeholder="my-workflow" />
839
+ </label>
840
+ <label className="shg-menu-lbl">Output key (optional)
841
+ <input className="shg-menu-input" value={outKey} onChange={(e) => setOutKey(e.target.value)} placeholder="summary" />
670
842
  </label>
671
- {(kind === 'prompt' || kind === 'harness') && (
672
- <label className="shg-menu-lbl">Prompt — reference columns as {'{{Name}}'}
673
- <textarea className="shg-menu-input" rows={3} value={prompt}
674
- onChange={(e) => setPrompt(e.target.value)}
675
- placeholder="Summarize {{Company}} in one line" />
676
- </label>
677
- )}
678
- {kind === 'harness' && (
679
- <label className="shg-menu-lbl">Agent id
680
- <input className="shg-menu-input" value={harnessId} onChange={(e) => setHarnessId(e.target.value)} placeholder="chrn_…" />
681
- </label>
682
- )}
683
- {kind === 'workflow' && (
684
- <>
685
- <label className="shg-menu-lbl">Workflow id
686
- <input className="shg-menu-input" value={wfSlug} onChange={(e) => setWfSlug(e.target.value)} placeholder="my-workflow" />
687
- </label>
688
- <label className="shg-menu-lbl">Output key (optional)
689
- <input className="shg-menu-input" value={outKey} onChange={(e) => setOutKey(e.target.value)} placeholder="summary" />
690
- </label>
691
- </>
692
- )}
693
- {others.length > 0 && (
694
- <div className="shg-menu-lbl">Reads columns
695
- <div className="shg-menu-deps">
696
- {others.map((c) => (
697
- <label key={c.id} className="shg-menu-dep">
698
- <input type="checkbox" checked={deps.has(c.id)} onChange={() => toggleDep(c.id)} /> {c.name}
699
- </label>
700
- ))}
701
- </div>
702
- </div>
703
- )}
704
843
  </>
705
844
  )}
706
- <div className="shg-menu-actions">
707
- <button className="shg-menu-del" onClick={onDelete}>Delete column</button>
708
- <button className="shg-menu-apply" onClick={apply}>Apply</button>
709
- </div>
710
845
  </>
711
846
  )}
847
+
848
+ <div className="shg-menu-actions">
849
+ <button className="shg-menu-del" onClick={onDelete}>Delete column</button>
850
+ <button className="shg-menu-apply" onClick={apply}>Apply</button>
851
+ </div>
712
852
  </div>
713
853
  </PopPortal>
714
854
  );
715
855
  }
716
856
 
717
- /**
718
- * The height each row would need to show its content in full, measured from what is on screen.
719
- *
720
- * A row is clamped to its height by design — a sheet you cannot scan is not a sheet. But after a
721
- * run, the thing a person wants is the answer, and an answer cut off at one line with no way to
722
- * see the rest is the grid hiding the work it just paid for. So the host measures and commits a
723
- * height, ONCE, rather than the grid guessing continuously.
724
- *
725
- * Measured, not estimated: `scrollHeight` is what the content actually occupies at this width,
726
- * including the file cards. A formula over character counts would be a number nobody derived.
727
- *
728
- * Returns { rowId: px } for the rows given (or every row), clamped to [min, max].
729
- */
730
- export function fitRowHeights(container, { rowIds, min = 34, max = 320, padding = 12 } = {}) {
731
- if (!container) return {};
732
- const out = {};
733
- const rows = container.querySelectorAll('tr[data-row-id]');
734
- for (const tr of rows) {
735
- const id = tr.getAttribute('data-row-id');
736
- if (rowIds && !rowIds.includes(id)) continue;
737
- let tallest = 0;
738
- for (const cell of tr.querySelectorAll('td[data-col-id] .shg-val')) {
739
- // The value box is clipped to the row; its scrollHeight is the content's real height.
740
- tallest = Math.max(tallest, cell.scrollHeight);
741
- }
742
- if (tallest) out[id] = Math.min(max, Math.max(min, Math.round(tallest + padding)));
743
- }
744
- return out;
745
- }
746
-
747
857
  // ── Export helpers (CSV / TSV / array-of-arrays) ─────────────────────────────
748
- // cellText(cell, column) lets a host say what one of its own column types is worth in a flat
749
- // file. Without it a cell whose value is an object exports as raw JSON, which is what a
750
- // spreadsheet export must never be.
751
- function defaultCellText(cell) {
752
- const v = cell?.value;
753
- if (v == null) return '';
754
- if (Array.isArray(v)) return v.join(', ');
755
- if (typeof v === 'object') return JSON.stringify(v);
756
- return String(v);
757
- }
758
-
759
- export function sheetToDelimited(sheet, sep = ',', { cellText = defaultCellText } = {}) {
858
+ export function sheetToDelimited(sheet, sep = ',') {
760
859
  const cols = sheet?.columns || [];
761
860
  const rows = sheet?.rows || [];
762
861
  const cells = sheet?.cells || {};
763
- const esc = (s) => {
862
+ const esc = (v) => {
863
+ const s = v == null ? '' : (Array.isArray(v) ? v.join(', ') : (typeof v === 'object' ? JSON.stringify(v) : String(v)));
764
864
  if (sep === ',' && /[",\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
765
865
  return s;
766
866
  };
767
867
  const header = cols.map((c) => esc(c.name)).join(sep);
768
- const body = rows.map((r) => cols.map((c) => (
769
- esc(String(cellText(cells[cellKey(r.id, c.id)], c) ?? ''))
770
- )).join(sep));
868
+ const body = rows.map((r) => cols.map((c) => {
869
+ const cell = cells[cellKey(r.id, c.id)];
870
+ return esc(cell ? cell.value : '');
871
+ }).join(sep));
771
872
  return [header, ...body].join('\n');
772
873
  }
773
874
 
774
- /** Rows as an array-of-arrays (header first) — feed to an xlsx writer.
775
- *
776
- * The default keeps numbers and booleans as themselves: a spreadsheet writer stores a JS number
777
- * as a numeric cell, and stringifying here would hand the person a column they cannot sum. */
778
- function defaultCellValue(cell) {
779
- const v = cell?.value;
780
- if (v == null) return '';
781
- if (Array.isArray(v)) return v.join(', ');
782
- if (typeof v === 'object') return JSON.stringify(v);
783
- return v;
784
- }
785
-
786
- export function sheetToAoA(sheet, { cellText = defaultCellValue } = {}) {
875
+ /** Rows as an array-of-arrays (header first) — feed to an xlsx writer. */
876
+ export function sheetToAoA(sheet) {
787
877
  const cols = sheet?.columns || [];
788
878
  const rows = sheet?.rows || [];
789
879
  const cells = sheet?.cells || {};
880
+ const val = (v) => (v == null ? '' : (Array.isArray(v) ? v.join(', ') : (typeof v === 'object' ? JSON.stringify(v) : v)));
790
881
  return [cols.map((c) => c.name),
791
- ...rows.map((r) => cols.map((c) => cellText(cells[cellKey(r.id, c.id)], c) ?? ''))];
882
+ ...rows.map((r) => cols.map((c) => val(cells[cellKey(r.id, c.id)]?.value)))];
792
883
  }