reifyui 0.12.0 → 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 (82) hide show
  1. package/README.md +29 -0
  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 +1699 -817
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.ts +3 -0
  33. package/dist/index.js +680 -1769
  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 +34 -2
  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 +9 -3
  55. package/src/components/Composer.jsx +37 -3
  56. package/src/components/resizable.jsx +82 -12
  57. package/src/graph/ConnectPane.jsx +634 -0
  58. package/src/graph/ConnectToolDetail.jsx +565 -0
  59. package/src/graph/LogsPane.jsx +328 -0
  60. package/src/graph/Skeleton.jsx +13 -0
  61. package/src/graph/draft.js +108 -0
  62. package/src/graph/format.js +37 -0
  63. package/src/graph/index.d.ts +41 -0
  64. package/src/graph/index.js +14 -0
  65. package/src/graph/useGraphCollab.js +299 -0
  66. package/src/graph/vgraph.js +215 -0
  67. package/src/index.d.ts +3 -0
  68. package/src/index.js +4 -1
  69. package/src/mention/MentionInput.jsx +420 -0
  70. package/src/mention/mentionModel.js +177 -0
  71. package/src/sheet/RunStrip.jsx +57 -0
  72. package/src/sheet/SheetGrid.jsx +448 -423
  73. package/src/sheet/doc.d.ts +16 -0
  74. package/src/sheet/index.d.ts +23 -0
  75. package/src/sheet/index.js +10 -0
  76. package/src/sheet/sheetDoc.js +203 -0
  77. package/src/sheet/useSheetCollab.js +102 -0
  78. package/src/sheet/useSheetRun.js +80 -0
  79. package/styles/chat.css +2 -0
  80. package/styles/graph.css +395 -0
  81. package/styles/mention.css +79 -0
  82. package/styles/sheet.css +156 -112
@@ -1,74 +1,47 @@
1
- // SheetGrid — the reusable AI-spreadsheet grid.
1
+ // SheetGrid — the reusable AI-spreadsheet grid (UI Core).
2
2
  //
3
- // CLAMP_LINE / CLAMP_PAD are the line height and the vertical padding a cell is laid out with;
4
- // they turn a measured row height into a number of lines for `--shg-clamp`, which host CSS uses
5
- // for line-clamp.
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.
6
7
  //
7
- // Product-agnostic: it renders a sheet JSON and calls back for edits/runs. All I/O is injected —
8
- // this file has no product API.
9
- //
10
- // Sheet shape:
11
- // { meta{title}, columns[{id,name,type,options?,width?}],
12
- // 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} } }
13
11
  //
14
12
  // Props:
15
13
  // sheet — the sheet JSON (required)
16
- // onChange(next) — persist an edited sheet (add/edit/delete col/row/cell)
17
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
18
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
19
22
  // readOnly — no editing/running (template previews / embedded read views)
20
- // fetchBlobUrl(path) — async product-authed fetch -> object URL, for inline images
21
- // 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
22
25
  // onOpenResource(ref) — open a referenced artifact (sheet/slides/…)
23
- // columnTypes — the column vocabulary (see SheetColumnType below). Defaults to
24
- // this file's own set, so existing hosts need not pass it.
25
- // renderCell(ctx) — replace a cell's body. Return undefined to fall through.
26
- // renderColumnConfig(ctx) — replace the column popover's body. Return undefined to fall through.
27
26
  //
28
- // Editing is optimistic: local edits call onChange with the next sheet; the host persists and
29
- // hands truth back through `sheet`.
30
- import { useEffect, useLayoutEffect, useRef, useState } from 'react';
31
-
32
- const CLAMP_LINE = 18;
33
- const CLAMP_PAD = 10;
34
- // A cell says which of its children is the clamped text by marking it. Without a mark the cell IS
35
- // its text (the built-in value cell), which is the right default.
36
- const CLAMP_TEXT_SEL = '[data-shg-clamp-text]';
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';
37
31
  import { createPortal } from 'react-dom';
32
+ import { withAlpha } from '../collab/colors.js';
38
33
 
39
34
  const cellKey = (rowId, colId) => `${rowId}:${colId}`;
40
35
  const uid = (p) => `${p}_${Math.random().toString(36).slice(2, 10)}`;
41
36
 
42
- // A column type is a descriptor, not a hardcoded literal. This grid used to test
43
- // `col.type === 'compute'` in twelve places, which meant a host could not add a column kind
44
- // without forking the file — and a fork is how two copies of one component start.
45
- //
46
- // type the value stored in column.type
47
- // label what the type menu and the header sub-label show
48
- // computed the app fills these cells, not the person: status dot, tint, run affordances
49
- // editable defaults to !computed
50
- // configKey the column's config object for this type; dropped when the type changes
51
- // badge(col) an extra header sub-label, e.g. which kind of compute this is
52
- // configWidth / configHeight how much room this type's config popover needs. A type whose
53
- // config is a prompt editor does not fit in the width a Type select needs.
54
- const DEFAULT_COLUMN_TYPES = [
55
- { type: 'text', label: 'Text' },
56
- { type: 'number', label: 'Number' },
57
- { type: 'select', label: 'Select' },
58
- { type: 'tags', label: 'Tags' },
59
- { type: 'checkbox', label: 'Checkbox' },
60
- { type: 'date', label: 'Date' },
61
- { type: 'url', label: 'Link' },
62
- { type: 'resource', label: 'Resource' },
63
- {
64
- type: 'compute',
65
- label: 'Computed',
66
- computed: true,
67
- configKey: 'compute',
68
- badge: (col) => col.compute?.kind,
69
- },
70
- ];
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: '✦' };
71
43
 
44
+ const MANUAL_TYPES = ['text', 'number', 'select', 'tags', 'checkbox', 'date', 'url', 'resource'];
72
45
  const COMPUTE_KINDS = [
73
46
  { kind: 'prompt', label: 'AI prompt' },
74
47
  { kind: 'harness', label: 'Agent (harness)' },
@@ -78,34 +51,24 @@ const COMPUTE_KINDS = [
78
51
  const RESOURCE_KINDS = ['image', 'sheet', 'slides', 'workflow', 'graph'];
79
52
  const RESOURCE_ICON = { image: '🖼', sheet: '▦', slides: '▤', workflow: '⚙', graph: '◉' };
80
53
 
81
- // Popovers render through a body portal with FIXED positioning — inside the grid they'd be
82
- // clipped by the scroll container and out-stacked by the sticky header/row-number cells. anchor
83
- // is a DOMRect captured at open time; the box clamps to the viewport and flips above the anchor
84
- // 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.
85
60
  function PopPortal({ anchor, width = 250, estHeight = 300, className, children, onClose }) {
86
61
  const boxRef = useRef(null);
87
62
  useEffect(() => {
88
63
  if (!onClose) return undefined;
89
- const close = () => onClose();
90
- // mousedown, not click: React 18 flushes a listener attached in this effect synchronously
91
- // during the very discrete event that opened the popover, so a `click` listener closes the
92
- // box before it paints. A press inside the anchor is also ignored — that is the trigger's
93
- // own toggle, and closing here would race it into staying open.
94
- const onDown = (e) => {
95
- if (boxRef.current && boxRef.current.contains(e.target)) return;
96
- if (anchor && e.clientX >= anchor.left && e.clientX <= anchor.right
97
- && 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;
98
66
  onClose();
99
67
  };
100
- window.addEventListener('mousedown', onDown);
101
68
  window.addEventListener('scroll', close, true);
102
69
  window.addEventListener('resize', close);
103
- return () => {
104
- window.removeEventListener('mousedown', onDown);
105
- window.removeEventListener('scroll', close, true);
106
- window.removeEventListener('resize', close);
107
- };
108
- }, [onClose, anchor]);
70
+ return () => { window.removeEventListener('scroll', close, true); window.removeEventListener('resize', close); };
71
+ }, [onClose]);
109
72
  if (!anchor) return null;
110
73
  const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8));
111
74
  let top = anchor.bottom + 6;
@@ -118,19 +81,37 @@ function PopPortal({ anchor, width = 250, estHeight = 300, className, children,
118
81
  );
119
82
  }
120
83
 
121
- // 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
+ ];
122
96
  const PILL_FALLBACKS = ['#E0E7FF', '#FCE7F3', '#D1FAE5', '#FEF3C7', '#E0F2FE', '#F3E8FF', '#FFE4E6'];
123
97
 
124
- function normOptions(options) {
98
+ export function normOptions(options) {
125
99
  return (options || []).map((o, i) => {
126
100
  if (typeof o === 'string') return { label: o, color: PILL_FALLBACKS[i % PILL_FALLBACKS.length] };
127
101
  return { label: o.label ?? String(o.value ?? ''), color: o.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] };
128
102
  });
129
103
  }
130
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
+
131
113
  function pillColor(label, options) {
132
- const opts = normOptions(options);
133
- const hit = opts.find((o) => o.label === label);
114
+ const hit = optionFor(label, options);
134
115
  if (hit) return hit.color;
135
116
  // stable fallback by hash so ad-hoc tags keep their color
136
117
  let h = 0;
@@ -163,21 +144,24 @@ function ResourceChip({ refVal, onOpen }) {
163
144
  );
164
145
  }
165
146
 
166
- // 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.
167
149
  function StatusDot({ status }) {
168
- if (!status || status === 'empty') return null;
150
+ if (!status || status === 'empty' || status === 'done') return null;
169
151
  return <span className={`shg-dot shg-dot-${status}`} title={status} />;
170
152
  }
171
153
 
172
154
  function CellValue({ cell, col, fetchBlobUrl, onOpenResource }) {
173
155
  const v = cell?.value;
174
156
  if (v === undefined || v === null || v === '') return <span className="shg-val-txt" />;
175
- // A typed artifact ref renders the same whether hand-set (resource column) or produced by a
176
- // 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).
177
159
  if (v && typeof v === 'object' && !Array.isArray(v) && v.kind) {
178
160
  if (v.kind === 'image') return <RefImage refVal={v} fetchBlobUrl={fetchBlobUrl} />;
179
161
  return <ResourceChip refVal={v} onOpen={onOpenResource} />;
180
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>;
181
165
  switch (col.type) {
182
166
  case 'select':
183
167
  return <span className="shg-pill" style={{ background: pillColor(String(v), col.options) }}>{String(v)}</span>;
@@ -204,13 +188,12 @@ function CellValue({ cell, col, fetchBlobUrl, onOpenResource }) {
204
188
  }
205
189
  }
206
190
 
207
- export function SheetGrid({
208
- sheet, onChange, onRunCell, onRunColumn, readOnly = false, fetchBlobUrl, onOpenResource,
209
- peerMarks, onActiveCell, columnTypes = DEFAULT_COLUMN_TYPES, renderCell, renderColumnConfig,
210
- }) {
191
+ export function SheetGrid({ sheet, ops, onRunCell, onRunColumn, readOnly = false, fetchBlobUrl, onOpenResource, peers, onPresence }) {
211
192
  const columns = sheet?.columns || [];
212
193
  const rows = sheet?.rows || [];
213
194
  const cells = sheet?.cells || {};
195
+ const tabId = sheet?.id;
196
+ const canEdit = !readOnly && !!ops && !!tabId;
214
197
  const [editing, setEditing] = useState(null); // {rowId, colId, type}
215
198
  const [draft, setDraft] = useState('');
216
199
  const [menuCol, setMenuCol] = useState(null); // {id, rect} of the open column menu
@@ -219,16 +202,60 @@ export function SheetGrid({
219
202
  const [dropAt, setDropAt] = useState(null); // {kind, id, after} current drop slot
220
203
  const inputRef = useRef(null);
221
204
  const dragRef = useRef(null);
222
- const gridRef = useRef(null);
223
-
224
- // An unknown type still renders — as plain text, editable. Refusing to draw a column because
225
- // its type is unfamiliar would hide the person's data from them.
226
- const descOf = (type) => columnTypes.find((t) => t.type === type) || { type, label: type };
227
- const isComputed = (col) => !!descOf(col?.type).computed;
228
- const isEditable = (col) => {
229
- const d = descOf(col?.type);
230
- return d.editable ?? !d.computed;
231
- };
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]);
232
259
 
233
260
  // Drag-to-resize: live via sizeDraft, persisted into the sheet on release.
234
261
  const startResize = (e, kind, id, start) => {
@@ -250,10 +277,9 @@ export function SheetGrid({
250
277
  document.body.style.cursor = '';
251
278
  if (!d) return;
252
279
  setSizeDraft({});
253
- mutate((n) => {
254
- if (d.kind === 'col') { const c = n.columns.find((x) => x.id === d.id); if (c) c.width = Math.round(d.last); }
255
- else { const r = n.rows.find((x) => x.id === d.id); if (r) r.height = Math.round(d.last); }
256
- });
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) }); }
257
283
  };
258
284
  window.addEventListener('mousemove', onMove);
259
285
  window.addEventListener('mouseup', onUp);
@@ -262,16 +288,17 @@ export function SheetGrid({
262
288
  const colWidth = (col) => (sizeDraft.col && sizeDraft.col[col.id]) || col.width || undefined;
263
289
 
264
290
  // Drag-to-reorder (columns by their header, rows by their number cell).
265
- const reorder = (kind, fromId, toId, after) => mutate((n) => {
266
- const arr = kind === 'col' ? n.columns : n.rows;
267
- const i = arr.findIndex((x) => x.id === fromId);
268
- if (i < 0 || fromId === toId) return;
269
- const [item] = arr.splice(i, 1);
270
- let j = arr.findIndex((x) => x.id === toId);
271
- 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;
272
299
  if (after) j += 1;
273
- arr.splice(j, 0, item);
274
- });
300
+ if (kind === 'col') ops.moveColumn(tabId, fromId, j); else ops.moveRow(tabId, fromId, j);
301
+ };
275
302
  const dndProps = (kind, id) => (readOnly ? {} : {
276
303
  draggable: true,
277
304
  onDragStart: (e) => {
@@ -307,112 +334,36 @@ export function SheetGrid({
307
334
  }
308
335
  return cls;
309
336
  };
310
- // The number gutter is FIXED: sized by the digit count of the row total so it never stretches
311
- // (an empty grid otherwise splits the table width). Wide enough for the number AND the delete
312
- // button beside it, both at a size worth aiming at.
313
- 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);
314
340
  const numStyle = { width: numW, minWidth: numW, maxWidth: numW };
315
341
  const rowHeight = (row) => (sizeDraft.row && sizeDraft.row[row.id]) || row.height || undefined;
316
342
 
317
343
  useEffect(() => { if (editing && inputRef.current) inputRef.current.focus(); }, [editing]);
318
344
 
319
- // How many lines of text a row has room for.
320
- //
321
- // This used to be derived from the row's STORED height, falling back to 34px — one line — for
322
- // any row that had never been sized. But a row is very often tall because of a NEIGHBOURING
323
- // column: an agent cell with files under its answer, or simply a taller one. Every other cell
324
- // in that row then showed a single ellipsised line with the rest of the row empty beneath it,
325
- // which is what the space was there for.
326
- //
327
- // Measured with every clamp forced back to one line first. That is the whole trick: the basis
328
- // has to be the height the row's OTHER content needs, never the height the clamp itself just
329
- // produced. Deriving it from the rendered height directly feeds back — more lines makes the
330
- // row taller, which allows more lines — and the rows grow without bound (92 → 137 → 182 → …).
331
- useLayoutEffect(() => {
332
- const rowsEl = gridRef.current?.querySelectorAll('tbody tr[data-row-id]');
333
- if (!rowsEl || !rowsEl.length) return;
334
- const trs = Array.from(rowsEl);
335
-
336
- // 1. Put every clamp back to one line, so what we measure next is the height the row's other
337
- // content NEEDS rather than the height the last clamp happened to produce.
338
- for (const tr of trs) {
339
- tr.style.removeProperty('--shg-clamp');
340
- for (const td of tr.children) td.style.setProperty('--shg-clamp', '1');
341
- }
342
-
343
- // 2. Measure, in one pass: the row, and per cell whatever sits ALONGSIDE its text (an agent
344
- // cell keeps its files under its answer). Measured on the text's own box, which sizes to
345
- // its content — the <td> is stretched to the row and would report the row height for every
346
- // cell, making them all look equally full.
347
- const plan = trs.map((tr) => ({
348
- base: tr.offsetHeight,
349
- cells: Array.from(tr.children).map((td) => {
350
- const txt = td.querySelector(CLAMP_TEXT_SEL);
351
- const box = txt && txt.parentElement;
352
- return { td, extra: box ? Math.max(0, box.scrollHeight - txt.offsetHeight) : 0 };
353
- }),
354
- }));
355
-
356
- // 3. Give every cell in a row the same amount of room for text.
357
- //
358
- // `floor` is the line count the row's own height already allows. `need` is how tall the row
359
- // must be for the cell carrying the most alongside its text — the one with files under it —
360
- // to still get that many lines. Every other cell then fills THAT height, which is the whole
361
- // point: a cell with nothing under its text was showing one ellipsised line beside a
362
- // neighbour whose files made the row four times taller.
363
- //
364
- // extra + lines*LINE <= need by construction, so no cell outgrows the height this was
365
- // measured against, and `base` is always re-measured at one line — so a second pass
366
- // computes the same answer instead of ratcheting the rows upward.
367
- for (const { base, cells } of plan) {
368
- const floorLines = Math.max(1, Math.floor((base - CLAMP_PAD) / CLAMP_LINE));
369
- const need = Math.max(...cells.map((c) => c.extra)) + floorLines * CLAMP_LINE + CLAMP_PAD;
370
- for (const { td, extra } of cells) {
371
- const lines = Math.max(floorLines, Math.floor((need - extra - CLAMP_PAD) / CLAMP_LINE));
372
- td.style.setProperty('--shg-clamp', String(lines));
373
- }
374
- }
375
- });
376
-
377
- const mutate = (fn) => {
378
- if (readOnly || !onChange) return;
379
- const next = JSON.parse(JSON.stringify(sheet));
380
- fn(next);
381
- 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) });
382
348
  };
383
349
 
384
- // A manual edit writes the value and nothing else. It used to stamp `status:'done'`, which
385
- // made every hand-typed cell claim to be the output of a run that never happened — and forced
386
- // status rendering to be gated on the column type rather than on the cell. On a computed
387
- // column the surrounding run record is kept, because there an override sits on top of a real
388
- // run and the link to that run is still true.
389
- const setCell = (rowId, colId, value) => mutate((n) => {
390
- n.cells = n.cells || {};
391
- const k = cellKey(rowId, colId);
392
- const col = (n.columns || []).find((c) => c.id === colId);
393
- const prev = n.cells[k];
394
- n.cells[k] = isComputed(col) && prev ? { ...prev, value } : { value };
395
- });
396
-
397
- const openEdit = (rowId, col, anchorEl) => {
398
- if (readOnly) return;
399
- if (!isEditable(col)) return;
400
- 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
401
354
  const cur = cells[cellKey(rowId, col.id)];
402
355
  setCell(rowId, col.id, !(cur && cur.value));
403
356
  return;
404
357
  }
405
358
  const c = cells[cellKey(rowId, col.id)];
406
359
  const v = c?.value;
407
- if (col.type === 'tags') setDraft(Array.isArray(v) ? v.join(', ') : (v || ''));
360
+ if (col.type === 'tags') setDraft(initial ?? (Array.isArray(v) ? v.join(', ') : (v || '')));
408
361
  else if (col.type === 'resource') setDraft(v && typeof v === 'object' ? v : { kind: 'sheet', name: '', id: '', url: '' });
409
- else setDraft(v == null ? '' : String(v));
362
+ else setDraft(initial ?? (v == null ? '' : String(v)));
410
363
  setEditing({ rowId, colId: col.id, type: col.type, rect: anchorEl?.getBoundingClientRect?.() || null });
411
- onActiveCell && onActiveCell(cellKey(rowId, col.id));
412
364
  };
413
365
 
414
366
  const commitEdit = () => {
415
- onActiveCell && onActiveCell(null);
416
367
  if (!editing) return;
417
368
  const { rowId, colId, type } = editing;
418
369
  let value = draft;
@@ -422,30 +373,104 @@ export function SheetGrid({
422
373
  setEditing(null);
423
374
  };
424
375
 
425
- const addColumn = () => mutate((n) => {
426
- n.columns.push({ id: uid('col'), name: `Column ${n.columns.length + 1}`, type: 'text' });
427
- });
428
- const addRow = () => mutate((n) => { n.rows.push({ id: uid('row') }); });
429
- const deleteColumn = (colId) => mutate((n) => {
430
- n.columns = n.columns.filter((c) => c.id !== colId);
431
- for (const k of Object.keys(n.cells || {})) if (k.endsWith(`:${colId}`)) delete n.cells[k];
432
- });
433
- const deleteRow = (rowId) => mutate((n) => {
434
- n.rows = n.rows.filter((r) => r.id !== rowId);
435
- for (const k of Object.keys(n.cells || {})) if (k.startsWith(`${rowId}:`)) delete n.cells[k];
436
- });
437
- const renameColumn = (colId, name) => mutate((n) => {
438
- const c = n.columns.find((x) => x.id === colId); if (c) c.name = name;
439
- });
440
- const configureColumn = (colId, patch) => mutate((n) => {
441
- const c = n.columns.find((x) => x.id === colId); if (!c) return;
442
- Object.assign(c, patch);
443
- // A column carries the config of its own type and no other. Changing the type takes the old
444
- // config with it, so a harness column that becomes a text column stops carrying a prompt.
445
- if (patch.type) {
446
- 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'));
447
407
  }
448
- });
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
+ };
449
474
 
450
475
  // The inline editor for the editing cell, by type.
451
476
  const renderEditor = (col) => {
@@ -495,12 +520,16 @@ export function SheetGrid({
495
520
  placeholder={col.type === 'tags' ? 'tag, tag, …' : ''}
496
521
  onChange={(e) => setDraft(e.target.value)}
497
522
  onBlur={commitEdit}
498
- 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
+ }} />
499
528
  );
500
529
  };
501
530
 
502
531
  return (
503
- <div className="shg" ref={gridRef}>
532
+ <div className="shg" ref={rootRef} tabIndex={0} onKeyDown={onKeyDown} onCopy={copySelection} onPaste={pasteAt}>
504
533
  <div className="shg-scroll">
505
534
  <table className="shg-table">
506
535
  <thead>
@@ -508,7 +537,7 @@ export function SheetGrid({
508
537
  <th className="shg-corner" style={numStyle} />
509
538
  {columns.map((col) => (
510
539
  <th key={col.id}
511
- 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)}
512
541
  style={colWidth(col) ? { width: colWidth(col), minWidth: colWidth(col), maxWidth: colWidth(col) } : undefined}
513
542
  {...dndProps('col', col.id)}>
514
543
  {!readOnly && (
@@ -517,8 +546,6 @@ export function SheetGrid({
517
546
  <div className="shg-col-h">
518
547
  <ColumnHeader
519
548
  col={col} columns={columns} readOnly={readOnly}
520
- desc={descOf(col.type)} columnTypes={columnTypes}
521
- renderColumnConfig={renderColumnConfig}
522
549
  menuOpen={menuCol?.id === col.id}
523
550
  menuAnchor={menuCol?.id === col.id ? menuCol.rect : null}
524
551
  onMenu={(e) => setMenuCol(menuCol?.id === col.id ? null
@@ -527,7 +554,8 @@ export function SheetGrid({
527
554
  onRename={renameColumn}
528
555
  onConfigure={configureColumn}
529
556
  onDelete={() => { setMenuCol(null); deleteColumn(col.id); }}
530
- onRun={isComputed(col) && onRunColumn ? () => onRunColumn(col.id) : null} />
557
+ onRun={col.type === 'compute' && onRunColumn ? () => onRunColumn(col.id) : null}
558
+ width={colWidth(col)} />
531
559
  </div>
532
560
  </th>
533
561
  ))}
@@ -538,8 +566,11 @@ export function SheetGrid({
538
566
  </thead>
539
567
  <tbody>
540
568
  {rows.map((row, ri) => (
541
- <tr key={row.id} data-row-id={row.id}
542
- style={rowHeight(row) ? { height: rowHeight(row) } : undefined}>
569
+ <tr key={row.id}
570
+ style={{
571
+ ...(rowHeight(row) ? { height: rowHeight(row) } : null),
572
+ '--shg-clamp': Math.max(1, Math.floor(((rowHeight(row) || 34) - 10) / 18)),
573
+ }}>
543
574
  <td className={'shg-rownum' + dndClass('row', row.id)} style={numStyle}
544
575
  title="Drag to reorder" {...dndProps('row', row.id)}>
545
576
  <span>{ri + 1}</span>
@@ -548,56 +579,51 @@ export function SheetGrid({
548
579
  <span className="shg-resize-row" onMouseDown={(e) => startResize(e, 'row', row.id, rowHeight(row) || e.currentTarget.closest('tr').offsetHeight)} />
549
580
  )}
550
581
  </td>
551
- {columns.map((col) => {
552
- const c = cells[cellKey(row.id, col.id)] || {};
553
- const computed = isComputed(col);
582
+ {columns.map((col, ci) => {
583
+ const key = cellKey(row.id, col.id);
584
+ const c = cells[key] || {};
554
585
  const isEditing = editing && editing.rowId === row.id && editing.colId === col.id;
555
- const peer = peerMarks && peerMarks[cellKey(row.id, col.id)];
556
- // A host owns the whole cell body when it wants to: a running cell's live text
557
- // lives in the host's run store, not in the sheet JSON, so only a closure can
558
- // reach it. Returning undefined falls through to the built-in rendering.
559
- const custom = renderCell && renderCell({
560
- cell: c, column: col, row, rowIndex: ri, sheet, computed,
561
- width: colWidth(col), height: rowHeight(row), editing: !!isEditing, readOnly,
562
- setCell: (v) => setCell(row.id, col.id, v),
563
- runCell: onRunCell && !readOnly ? () => onRunCell(row.id, col.id) : null,
564
- });
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];
565
593
  return (
566
- <td key={col.id} data-col-id={col.id}
567
- className={'shg-cell' + (computed ? ' shg-cell-compute' : '')
568
- + (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' : '')
569
598
  + (peer ? ' shg-cell-peer' : '')}
570
- style={peer ? { boxShadow: `inset 0 0 0 2px ${peer.color}` } : undefined}
571
- 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); }}
572
613
  title={c.error || ''}>
573
- {/* The boundaries a spreadsheet lets you grab are the ones you can see, and
574
- from row 20 the header is scrolled away. Both edges of every cell resize
575
- the same column and row the header and the gutter do — same handler,
576
- same drag, just reachable where the person already is. */}
577
- {!readOnly && (
578
- <>
579
- <span className="shg-resize-col shg-resize-in-cell"
580
- onClick={(e) => e.stopPropagation()}
581
- onMouseDown={(e) => startResize(e, 'col', col.id,
582
- colWidth(col) || e.currentTarget.closest('td').offsetWidth)} />
583
- <span className="shg-resize-row shg-resize-in-cell"
584
- onClick={(e) => e.stopPropagation()}
585
- onMouseDown={(e) => startResize(e, 'row', row.id,
586
- rowHeight(row) || e.currentTarget.closest('tr').offsetHeight)} />
587
- </>
588
- )}
589
614
  {peer && <span className="shg-peer-flag" style={{ background: peer.color }}>{peer.name}</span>}
590
615
  {isEditing ? renderEditor(col) : (
591
- <div className="shg-val">
592
- {custom !== undefined ? custom : (
593
- <>
594
- {computed && <StatusDot status={c.status} />}
595
- <CellValue cell={c} col={col} fetchBlobUrl={fetchBlobUrl} onOpenResource={onOpenResource} />
596
- {computed && !readOnly && onRunCell && (
597
- <button className="shg-runcell" title="Run this cell"
598
- onClick={(e) => { e.stopPropagation(); onRunCell(row.id, col.id); }}>▶</button>
599
- )}
600
- </>
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>
601
627
  )}
602
628
  </div>
603
629
  )}
@@ -620,16 +646,15 @@ export function SheetGrid({
620
646
  );
621
647
  }
622
648
 
623
- function ColumnHeader({
624
- col, columns, readOnly, desc, columnTypes, renderColumnConfig,
625
- menuOpen, menuAnchor, onMenu, onCloseMenu, onRename, onConfigure, onDelete, onRun,
626
- }) {
649
+ function ColumnHeader({ col, columns, readOnly, menuOpen, menuAnchor, onMenu, onCloseMenu, onRename, onConfigure, onDelete, onRun, width }) {
627
650
  const [editing, setEditing] = useState(false);
628
651
  const [name, setName] = useState(col.name);
629
652
  useEffect(() => setName(col.name), [col.name]);
630
- 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' : '';
631
656
  return (
632
- <div className="shg-colhdr">
657
+ <div className={'shg-colhdr' + fit}>
633
658
  <div className="shg-colhdr-main">
634
659
  {editing && !readOnly ? (
635
660
  <input className="shg-colname-input" value={name} autoFocus
@@ -639,20 +664,19 @@ function ColumnHeader({
639
664
  ) : (
640
665
  <span className="shg-colname" onDoubleClick={() => !readOnly && setEditing(true)} title={col.name}>{col.name}</span>
641
666
  )}
642
- <span className={'shg-coltype' + (desc.computed ? ' compute' : '')}>
643
- {desc.label || col.type}
644
- {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}` : ''}
645
670
  </span>
646
671
  </div>
647
672
  {!readOnly && (
648
673
  <div className="shg-colhdr-tools">
649
- {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>}
650
675
  <button className="shg-colmenu-btn" onClick={(e) => onMenu(e)} title="Column settings">⋯</button>
651
676
  </div>
652
677
  )}
653
678
  {menuOpen && !readOnly && (
654
679
  <ColumnMenu col={col} columns={columns} anchor={menuAnchor}
655
- columnTypes={columnTypes} renderColumnConfig={renderColumnConfig}
656
680
  onApply={(patch) => { onConfigure(col.id, patch); onCloseMenu(); }}
657
681
  onDelete={onDelete} onClose={onCloseMenu} />
658
682
  )}
@@ -660,13 +684,64 @@ function ColumnHeader({
660
684
  );
661
685
  }
662
686
 
663
- // The column configuration popover: type, options (select/tags), and the type's own config body.
664
- // Product-agnostic — plain controlled inputs, applied as one patch. A host that adds a column
665
- // type supplies renderColumnConfig and owns the body below the Type select.
666
- 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 }) {
667
741
  const [type, setType] = useState(col.type || 'text');
668
- const [optText, setOptText] = useState(
669
- 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 } : {}) })));
670
745
  const comp = col.compute || {};
671
746
  const [kind, setKind] = useState(comp.kind || 'prompt');
672
747
  const [prompt, setPrompt] = useState(comp.prompt || '');
@@ -674,20 +749,37 @@ function ColumnMenu({ col, columns, anchor, columnTypes, renderColumnConfig, onA
674
749
  const [wfSlug, setWfSlug] = useState(comp.workflow_slug || '');
675
750
  const [outKey, setOutKey] = useState(comp.output_key || '');
676
751
  const [deps, setDeps] = useState(new Set(comp.deps || []));
752
+ const ref = useRef(null);
677
753
 
678
- const others = columns.filter((c) => c.id !== col.id);
679
- const toggleDep = (id) => setDeps((s) => {
680
- const n = new Set(s);
681
- if (n.has(id)) n.delete(id); else n.add(id);
682
- return n;
683
- });
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]);
684
778
 
685
779
  const apply = () => {
686
780
  const patch = { type };
687
- if (type === 'select' || type === 'tags') {
688
- patch.options = optText.split('\n').map((s) => s.trim()).filter(Boolean);
689
- }
690
- // 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));
691
783
  if (type === 'compute') {
692
784
  const compute = { kind, deps: [...deps] };
693
785
  if (kind === 'prompt') compute.prompt = prompt;
@@ -698,161 +790,94 @@ function ColumnMenu({ col, columns, anchor, columnTypes, renderColumnConfig, onA
698
790
  onApply(patch);
699
791
  };
700
792
 
701
- // A custom body owns its own primary action, because only it knows when its config is
702
- // complete. It gets applyPatch to commit and close in one call.
703
- const custom = renderColumnConfig && renderColumnConfig({
704
- column: col, columns, type,
705
- applyPatch: (patch) => onApply({ type, ...patch }),
706
- deleteColumn: onDelete,
707
- close: onClose,
708
- });
709
-
710
- const desc = columnTypes.find((t) => t.type === type) || {};
711
793
  return (
712
- <PopPortal anchor={anchor} width={desc.configWidth || 250} estHeight={desc.configHeight || 340}
713
- className="shg-menu" onClose={onClose}>
714
- <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()}>
715
796
  <label className="shg-menu-lbl">Type
716
797
  <select className="shg-menu-input" value={type} onChange={(e) => setType(e.target.value)}>
717
- {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>
718
800
  </select>
719
801
  </label>
720
802
 
721
- {(type === 'select' || type === 'tags') && (
722
- <label className="shg-menu-lbl">Options (one per line)
723
- <textarea className="shg-menu-input" rows={3} value={optText}
724
- onChange={(e) => setOptText(e.target.value)} placeholder={'Todo\nDoing\nDone'} />
725
- </label>
726
- )}
803
+ <div className="shg-menu-lbl">{type === 'select' || type === 'tags' ? 'Options' : 'Values'}
804
+ <ValuePills values={values} onChange={setValues} />
805
+ </div>
727
806
 
728
- {custom !== undefined ? custom : (
807
+ {type === 'compute' && (
729
808
  <>
730
- {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' && (
731
836
  <>
732
- <label className="shg-menu-lbl">Runs
733
- <select className="shg-menu-input" value={kind} onChange={(e) => setKind(e.target.value)}>
734
- {COMPUTE_KINDS.map((k) => <option key={k.kind} value={k.kind}>{k.label}</option>)}
735
- </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" />
736
842
  </label>
737
- {(kind === 'prompt' || kind === 'harness') && (
738
- <label className="shg-menu-lbl">Prompt — reference columns as {'{{Name}}'}
739
- <textarea className="shg-menu-input" rows={3} value={prompt}
740
- onChange={(e) => setPrompt(e.target.value)}
741
- placeholder="Summarize {{Company}} in one line" />
742
- </label>
743
- )}
744
- {kind === 'harness' && (
745
- <label className="shg-menu-lbl">Agent id
746
- <input className="shg-menu-input" value={harnessId} onChange={(e) => setHarnessId(e.target.value)} placeholder="chrn_…" />
747
- </label>
748
- )}
749
- {kind === 'workflow' && (
750
- <>
751
- <label className="shg-menu-lbl">Workflow id
752
- <input className="shg-menu-input" value={wfSlug} onChange={(e) => setWfSlug(e.target.value)} placeholder="my-workflow" />
753
- </label>
754
- <label className="shg-menu-lbl">Output key (optional)
755
- <input className="shg-menu-input" value={outKey} onChange={(e) => setOutKey(e.target.value)} placeholder="summary" />
756
- </label>
757
- </>
758
- )}
759
- {others.length > 0 && (
760
- <div className="shg-menu-lbl">Reads columns
761
- <div className="shg-menu-deps">
762
- {others.map((c) => (
763
- <label key={c.id} className="shg-menu-dep">
764
- <input type="checkbox" checked={deps.has(c.id)} onChange={() => toggleDep(c.id)} /> {c.name}
765
- </label>
766
- ))}
767
- </div>
768
- </div>
769
- )}
770
843
  </>
771
844
  )}
772
- <div className="shg-menu-actions">
773
- <button className="shg-menu-del" onClick={onDelete}>Delete column</button>
774
- <button className="shg-menu-apply" onClick={apply}>Apply</button>
775
- </div>
776
845
  </>
777
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>
778
852
  </div>
779
853
  </PopPortal>
780
854
  );
781
855
  }
782
856
 
783
- /**
784
- * The height each row would need to show its content in full, measured from what is on screen.
785
- *
786
- * A row is clamped to its height by design — a sheet you cannot scan is not a sheet. But after a
787
- * run, the thing a person wants is the answer, and an answer cut off at one line with no way to
788
- * see the rest is the grid hiding the work it just paid for. So the host measures and commits a
789
- * height, ONCE, rather than the grid guessing continuously.
790
- *
791
- * Measured, not estimated: `scrollHeight` is what the content actually occupies at this width,
792
- * including the file cards. A formula over character counts would be a number nobody derived.
793
- *
794
- * Returns { rowId: px } for the rows given (or every row), clamped to [min, max].
795
- */
796
- export function fitRowHeights(container, { rowIds, min = 34, max = 320, padding = 12 } = {}) {
797
- if (!container) return {};
798
- const out = {};
799
- const rows = container.querySelectorAll('tr[data-row-id]');
800
- for (const tr of rows) {
801
- const id = tr.getAttribute('data-row-id');
802
- if (rowIds && !rowIds.includes(id)) continue;
803
- let tallest = 0;
804
- for (const cell of tr.querySelectorAll('td[data-col-id] .shg-val')) {
805
- // The value box is clipped to the row; its scrollHeight is the content's real height.
806
- tallest = Math.max(tallest, cell.scrollHeight);
807
- }
808
- if (tallest) out[id] = Math.min(max, Math.max(min, Math.round(tallest + padding)));
809
- }
810
- return out;
811
- }
812
-
813
857
  // ── Export helpers (CSV / TSV / array-of-arrays) ─────────────────────────────
814
- // cellText(cell, column) lets a host say what one of its own column types is worth in a flat
815
- // file. Without it a cell whose value is an object exports as raw JSON, which is what a
816
- // spreadsheet export must never be.
817
- function defaultCellText(cell) {
818
- const v = cell?.value;
819
- if (v == null) return '';
820
- if (Array.isArray(v)) return v.join(', ');
821
- if (typeof v === 'object') return JSON.stringify(v);
822
- return String(v);
823
- }
824
-
825
- export function sheetToDelimited(sheet, sep = ',', { cellText = defaultCellText } = {}) {
858
+ export function sheetToDelimited(sheet, sep = ',') {
826
859
  const cols = sheet?.columns || [];
827
860
  const rows = sheet?.rows || [];
828
861
  const cells = sheet?.cells || {};
829
- 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)));
830
864
  if (sep === ',' && /[",\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
831
865
  return s;
832
866
  };
833
867
  const header = cols.map((c) => esc(c.name)).join(sep);
834
- const body = rows.map((r) => cols.map((c) => (
835
- esc(String(cellText(cells[cellKey(r.id, c.id)], c) ?? ''))
836
- )).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));
837
872
  return [header, ...body].join('\n');
838
873
  }
839
874
 
840
- /** Rows as an array-of-arrays (header first) — feed to an xlsx writer.
841
- *
842
- * The default keeps numbers and booleans as themselves: a spreadsheet writer stores a JS number
843
- * as a numeric cell, and stringifying here would hand the person a column they cannot sum. */
844
- function defaultCellValue(cell) {
845
- const v = cell?.value;
846
- if (v == null) return '';
847
- if (Array.isArray(v)) return v.join(', ');
848
- if (typeof v === 'object') return JSON.stringify(v);
849
- return v;
850
- }
851
-
852
- 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) {
853
877
  const cols = sheet?.columns || [];
854
878
  const rows = sheet?.rows || [];
855
879
  const cells = sheet?.cells || {};
880
+ const val = (v) => (v == null ? '' : (Array.isArray(v) ? v.join(', ') : (typeof v === 'object' ? JSON.stringify(v) : v)));
856
881
  return [cols.map((c) => c.name),
857
- ...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)))];
858
883
  }