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
@@ -0,0 +1,1710 @@
1
+ import {
2
+ useOverlayEscape
3
+ } from "./chunk-J633KV57.js";
4
+ import {
5
+ withAlpha
6
+ } from "./chunk-ZYWE47EO.js";
7
+
8
+ // src/components/Popover.jsx
9
+ import React, { useCallback, useEffect, useRef, useState } from "react";
10
+ import { createPortal } from "react-dom";
11
+ import { jsx } from "react/jsx-runtime";
12
+ var GAP = 6;
13
+ var MARGIN = 8;
14
+ function Popover(props) {
15
+ const {
16
+ open,
17
+ anchorRef,
18
+ onClose,
19
+ width = 280,
20
+ minHeight = 140,
21
+ placement = "auto",
22
+ children,
23
+ className,
24
+ label
25
+ } = props;
26
+ const popRef = useRef(null);
27
+ const [pos, setPos] = useState(null);
28
+ useEffect(() => {
29
+ if (!open) {
30
+ setPos(null);
31
+ return void 0;
32
+ }
33
+ const place = () => {
34
+ const el = anchorRef?.current;
35
+ if (!el) return;
36
+ const r = el.getBoundingClientRect();
37
+ const vw = window.innerWidth;
38
+ const vh = window.innerHeight;
39
+ const w = Math.min(width, vw - MARGIN * 2);
40
+ const below = vh - r.bottom - GAP - MARGIN;
41
+ const above = r.top - GAP - MARGIN;
42
+ const up = placement === "above" || placement === "auto" && below < minHeight && above > below;
43
+ const maxHeight = Math.max(minHeight, Math.floor(up ? above : below));
44
+ const left = Math.max(MARGIN, Math.min(r.left, vw - w - MARGIN));
45
+ setPos(up ? { left, bottom: Math.round(vh - r.top + GAP), width: w, maxHeight } : { left, top: Math.round(r.bottom + GAP), width: w, maxHeight });
46
+ };
47
+ place();
48
+ window.addEventListener("resize", place);
49
+ window.addEventListener("scroll", place, true);
50
+ return () => {
51
+ window.removeEventListener("resize", place);
52
+ window.removeEventListener("scroll", place, true);
53
+ };
54
+ }, [open, anchorRef, width, minHeight, placement]);
55
+ useEffect(() => {
56
+ if (!open) return void 0;
57
+ const onDown = (e) => {
58
+ if (popRef.current?.contains(e.target)) return;
59
+ if (anchorRef?.current?.contains(e.target)) return;
60
+ onClose?.();
61
+ };
62
+ document.addEventListener("pointerdown", onDown);
63
+ return () => document.removeEventListener("pointerdown", onDown);
64
+ }, [open, anchorRef, onClose]);
65
+ const escape = useCallback(() => onClose?.(), [onClose]);
66
+ useOverlayEscape(open, escape);
67
+ if (!open || !pos || typeof document === "undefined") return null;
68
+ return createPortal(
69
+ /* @__PURE__ */ jsx(
70
+ "div",
71
+ {
72
+ ref: popRef,
73
+ className: ["uic-pop", className || ""].filter(Boolean).join(" "),
74
+ style: pos,
75
+ role: "dialog",
76
+ "aria-label": label,
77
+ children
78
+ }
79
+ ),
80
+ document.body
81
+ );
82
+ }
83
+
84
+ // src/mention/MentionInput.jsx
85
+ import React2, { forwardRef, useCallback as useCallback2, useEffect as useEffect2, useImperativeHandle, useLayoutEffect, useMemo, useRef as useRef2, useState as useState2 } from "react";
86
+
87
+ // src/mention/mentionModel.js
88
+ var CURLY = Object.freeze({ open: "{{", close: "}}" });
89
+ var AT = Object.freeze({ open: "@", close: "" });
90
+ var CHAT_LINK = Object.freeze({
91
+ write: (item) => `[@${item.name}](#m-${item.id})`,
92
+ pattern: /\[@(?<name>[^\]\n]+)\]\(#m-(?<id>[^)\s]+)\)/g
93
+ });
94
+ function makeResolver(items) {
95
+ const byName = /* @__PURE__ */ new Map();
96
+ const byId = /* @__PURE__ */ new Map();
97
+ for (const it of items || []) {
98
+ if (!it) continue;
99
+ if (it.name) byName.set(it.name, it);
100
+ if (it.id != null) byId.set(String(it.id), it);
101
+ }
102
+ const names = [...byName.keys()].sort((a, b) => b.length - a.length);
103
+ return { get: (name) => byName.get(name) || null, byId: (id) => byId.get(String(id)) || null, names };
104
+ }
105
+ function parsePattern(text, format, resolver) {
106
+ const out = [];
107
+ const re = new RegExp(format.pattern.source, format.pattern.flags.includes("g") ? format.pattern.flags : format.pattern.flags + "g");
108
+ let last = 0;
109
+ let m;
110
+ while (m = re.exec(text)) {
111
+ if (m.index > last) out.push({ type: "text", text: text.slice(last, m.index) });
112
+ const id = m.groups && m.groups.id != null ? m.groups.id : null;
113
+ const name = m.groups && m.groups.name || "";
114
+ const item = id != null && resolver && resolver.byId(id) || resolver && resolver.get(name) || { id: id ?? name, name, kind: null };
115
+ out.push({ type: "mention", id: item.id, name: item.name || name, kind: item.kind || null, item });
116
+ last = m.index + m[0].length;
117
+ }
118
+ if (last < text.length) out.push({ type: "text", text: text.slice(last) });
119
+ return out;
120
+ }
121
+ function parseValue(value, format, resolver) {
122
+ const text = value == null ? "" : String(value);
123
+ if (format && format.pattern) return parsePattern(text, format, resolver);
124
+ const { open, close } = format || CURLY;
125
+ const out = [];
126
+ let buf = "";
127
+ let i = 0;
128
+ const flush = () => {
129
+ if (buf) {
130
+ out.push({ type: "text", text: buf });
131
+ buf = "";
132
+ }
133
+ };
134
+ while (i < text.length) {
135
+ if (resolver && text.startsWith(open, i)) {
136
+ const boundary = close ? true : i === 0 || /[\s([{"'>]/.test(text[i - 1]);
137
+ let hit = null;
138
+ if (boundary) {
139
+ for (const name of resolver.names) {
140
+ const start = i + open.length;
141
+ if (text.startsWith(name, start)) {
142
+ const end = start + name.length;
143
+ if (!close || text.startsWith(close, end)) {
144
+ if (close || end === text.length || /[\s.,;:!?)\]}"']/.test(text[end])) {
145
+ hit = { name, end: end + close.length };
146
+ break;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+ if (hit) {
153
+ flush();
154
+ const item = resolver.get(hit.name);
155
+ out.push({ type: "mention", id: item.id, name: item.name, kind: item.kind || null, item });
156
+ i = hit.end;
157
+ continue;
158
+ }
159
+ }
160
+ buf += text[i];
161
+ i += 1;
162
+ }
163
+ flush();
164
+ return out;
165
+ }
166
+ function serializeSegments(segments, format) {
167
+ const f = format || CURLY;
168
+ if (f.write) return (segments || []).map((s) => s.type === "mention" ? f.write(s.item || s) : s.text).join("");
169
+ const { open, close } = f;
170
+ return (segments || []).map((s) => s.type === "mention" ? `${open}${s.name}${close}` : s.text).join("");
171
+ }
172
+ function mentionsOf(segments) {
173
+ const seen = /* @__PURE__ */ new Set();
174
+ const out = [];
175
+ for (const s of segments || []) {
176
+ if (s.type !== "mention" || seen.has(s.id)) continue;
177
+ seen.add(s.id);
178
+ out.push({ id: s.id, name: s.name, kind: s.kind || null });
179
+ }
180
+ return out;
181
+ }
182
+ function norm(s) {
183
+ return String(s || "").toLowerCase();
184
+ }
185
+ function subsequence(hay, needle) {
186
+ let j = 0;
187
+ for (let i = 0; i < hay.length && j < needle.length; i++) if (hay[i] === needle[j]) j++;
188
+ return j === needle.length;
189
+ }
190
+ function scoreItem(item, query) {
191
+ const q = norm(query).trim();
192
+ if (!q) return 1;
193
+ const name = norm(item.name);
194
+ if (name === q) return 120;
195
+ if (name.startsWith(q)) return 100;
196
+ if (name.split(/[\s_-]+/).some((w) => w.startsWith(q))) return 80;
197
+ if (name.includes(q)) return 60;
198
+ const initials = name.split(/[\s_-]+/).map((w) => w[0]).join("");
199
+ if (initials.startsWith(q)) return 50;
200
+ if (subsequence(name, q)) return 30;
201
+ const desc = norm(item.description);
202
+ if (desc && desc.includes(q)) return 20;
203
+ const kws = (item.keywords || []).map(norm);
204
+ if (kws.some((k) => k.includes(q))) return 15;
205
+ return 0;
206
+ }
207
+ function searchItems(items, query) {
208
+ const scored = (items || []).map((it, i) => ({ it, i, s: scoreItem(it, query) })).filter((x) => x.s > 0);
209
+ scored.sort((a, b) => b.s - a.s || a.i - b.i);
210
+ return scored.map((x) => x.it);
211
+ }
212
+ function groupItems(items, query) {
213
+ const groups = /* @__PURE__ */ new Map();
214
+ for (const it of searchItems(items, query)) {
215
+ const key = it.section || "";
216
+ if (!groups.has(key)) groups.set(key, []);
217
+ groups.get(key).push(it);
218
+ }
219
+ const order = [""];
220
+ for (const it of items || []) {
221
+ const k = it.section || "";
222
+ if (!order.includes(k)) order.push(k);
223
+ }
224
+ return order.filter((k) => groups.has(k)).map((k) => ({ section: k, items: groups.get(k) }));
225
+ }
226
+ function activeTrigger(textBeforeCaret, trigger = "@", maxLen = 48) {
227
+ const at = textBeforeCaret.lastIndexOf(trigger);
228
+ if (at < 0) return null;
229
+ if (at > 0 && !/[\s([{"'>]/.test(textBeforeCaret[at - 1])) return null;
230
+ const query = textBeforeCaret.slice(at + trigger.length);
231
+ if (query.length > maxLen || /\n/.test(query)) return null;
232
+ return { start: at, query };
233
+ }
234
+
235
+ // src/mention/MentionInput.jsx
236
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
237
+ var MENTION_ATTR = "data-mention-id";
238
+ function monogram(name) {
239
+ const parts = String(name || "").trim().split(/\s+/).filter(Boolean);
240
+ return ((parts[0] || "")[0] || "") + ((parts[1] || "")[0] || "") || "?";
241
+ }
242
+ function buildPillNode(item) {
243
+ const el = document.createElement("span");
244
+ el.className = "uic-mention";
245
+ el.setAttribute(MENTION_ATTR, item.id);
246
+ el.setAttribute("data-name", item.name);
247
+ if (item.kind) el.setAttribute("data-kind", item.kind);
248
+ el.setAttribute("contenteditable", "false");
249
+ if (item.description) el.title = item.description;
250
+ if (item.color) el.style.setProperty("--uic-mention-color", item.color);
251
+ const ic = document.createElement("span");
252
+ ic.className = "uic-mention-ic";
253
+ if (item.avatar) {
254
+ const img = document.createElement("img");
255
+ img.src = item.avatar;
256
+ img.alt = "";
257
+ ic.appendChild(img);
258
+ } else {
259
+ ic.textContent = typeof item.icon === "string" && item.icon ? item.icon : monogram(item.name);
260
+ if (!(typeof item.icon === "string" && item.icon)) ic.classList.add("is-mono");
261
+ }
262
+ const nm = document.createElement("span");
263
+ nm.className = "uic-mention-name";
264
+ nm.textContent = item.name;
265
+ el.appendChild(ic);
266
+ el.appendChild(nm);
267
+ return el;
268
+ }
269
+ function readSegments(root, resolver) {
270
+ const out = [];
271
+ let buf = "";
272
+ const flush = () => {
273
+ if (buf) {
274
+ out.push({ type: "text", text: buf });
275
+ buf = "";
276
+ }
277
+ };
278
+ const walk = (node, isLastAtRoot) => {
279
+ const kids = Array.from(node.childNodes);
280
+ kids.forEach((k, i) => {
281
+ const last = isLastAtRoot && i === kids.length - 1;
282
+ if (k.nodeType === 3) {
283
+ buf += k.data.replace(/\u00a0/g, " ");
284
+ return;
285
+ }
286
+ if (k.nodeType !== 1) return;
287
+ const tag = k.tagName;
288
+ if (tag === "BR") {
289
+ if (!last) buf += "\n";
290
+ return;
291
+ }
292
+ if (k.hasAttribute(MENTION_ATTR)) {
293
+ flush();
294
+ const id = k.getAttribute(MENTION_ATTR);
295
+ const name = k.getAttribute("data-name") || "";
296
+ const item = resolver.get(name) || { id, name, kind: k.getAttribute("data-kind") || null };
297
+ out.push({ type: "mention", id: item.id, name: item.name, kind: item.kind || null, item });
298
+ return;
299
+ }
300
+ if (tag === "DIV" || tag === "P") {
301
+ if (out.length || buf) buf += "\n";
302
+ walk(k, last);
303
+ return;
304
+ }
305
+ walk(k, last);
306
+ });
307
+ };
308
+ walk(root, true);
309
+ flush();
310
+ return out;
311
+ }
312
+ function writeSegments(root, segments) {
313
+ root.textContent = "";
314
+ for (const s of segments) {
315
+ if (s.type === "mention") {
316
+ root.appendChild(buildPillNode(s.item || s));
317
+ continue;
318
+ }
319
+ const lines = String(s.text).split("\n");
320
+ lines.forEach((line, i) => {
321
+ if (i > 0) root.appendChild(document.createElement("br"));
322
+ if (line) root.appendChild(document.createTextNode(line));
323
+ });
324
+ }
325
+ root.appendChild(document.createElement("br"));
326
+ }
327
+ function placeCaretAfter(node) {
328
+ const sel = window.getSelection();
329
+ if (!sel) return;
330
+ const r = document.createRange();
331
+ r.setStartAfter(node);
332
+ r.collapse(true);
333
+ sel.removeAllRanges();
334
+ sel.addRange(r);
335
+ }
336
+ function selectionIn(root) {
337
+ const sel = typeof window !== "undefined" ? window.getSelection() : null;
338
+ if (!sel || !sel.rangeCount) return null;
339
+ const r = sel.getRangeAt(0);
340
+ if (!root.contains(r.startContainer)) return null;
341
+ return { sel, range: r };
342
+ }
343
+ var MentionInput = forwardRef(function MentionInput2(props, ref) {
344
+ const {
345
+ value = "",
346
+ onChange,
347
+ items = [],
348
+ format = CURLY,
349
+ trigger = "@",
350
+ placeholder,
351
+ disabled = false,
352
+ onSubmit,
353
+ submitOnEnter = false,
354
+ autoFocus = false,
355
+ className = "",
356
+ label,
357
+ menuWidth = 360,
358
+ menuTitle,
359
+ emptyText = "No match",
360
+ renderIcon,
361
+ onOpenChange,
362
+ onFocus,
363
+ onBlur,
364
+ onKeyDown,
365
+ id
366
+ } = props;
367
+ const editorRef = useRef2(null);
368
+ const resolver = useMemo(() => makeResolver(items), [items]);
369
+ const [menu, setMenu] = useState2(null);
370
+ const [active, setActive] = useState2(0);
371
+ const [empty, setEmpty] = useState2(!value);
372
+ const listId = useMemo(() => `uic-mention-${Math.random().toString(36).slice(2, 8)}`, []);
373
+ const emit = useCallback2(() => {
374
+ const root = editorRef.current;
375
+ if (!root) return;
376
+ const segs = readSegments(root, resolver);
377
+ const next = serializeSegments(segs, format);
378
+ setEmpty(!next);
379
+ if (onChange) onChange(next, mentionsOf(segs));
380
+ }, [resolver, format, onChange]);
381
+ useLayoutEffect(() => {
382
+ const root = editorRef.current;
383
+ if (!root) return;
384
+ const current = serializeSegments(readSegments(root, resolver), format);
385
+ if (current === (value || "")) return;
386
+ writeSegments(root, parseValue(value || "", format, resolver));
387
+ setEmpty(!value);
388
+ }, [value, resolver, format]);
389
+ useEffect2(() => {
390
+ if (autoFocus && editorRef.current) editorRef.current.focus();
391
+ }, [autoFocus]);
392
+ const closeMenu = useCallback2(() => setMenu(null), []);
393
+ useEffect2(() => {
394
+ if (onOpenChange) onOpenChange(!!menu);
395
+ }, [menu, onOpenChange]);
396
+ const groups = useMemo(() => menu ? groupItems(items, menu.query) : [], [items, menu]);
397
+ const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);
398
+ useEffect2(() => {
399
+ setActive(0);
400
+ }, [menu && menu.query, groups.length]);
401
+ const syncMenu = useCallback2(() => {
402
+ const root = editorRef.current;
403
+ const s = root && selectionIn(root);
404
+ if (!s || !s.range.collapsed) {
405
+ setMenu(null);
406
+ return;
407
+ }
408
+ const node = s.range.startContainer;
409
+ if (node.nodeType !== 3) {
410
+ setMenu(null);
411
+ return;
412
+ }
413
+ const hit = activeTrigger(node.data.slice(0, s.range.startOffset), trigger);
414
+ if (!hit) {
415
+ setMenu(null);
416
+ return;
417
+ }
418
+ const r = document.createRange();
419
+ r.setStart(node, hit.start);
420
+ r.setEnd(node, Math.min(node.data.length, hit.start + 1));
421
+ const rect = r.getBoundingClientRect();
422
+ setMenu({ node, start: hit.start, query: hit.query, rect: rect.width || rect.height ? rect : root.getBoundingClientRect() });
423
+ }, [trigger]);
424
+ const anchorRef = useMemo(() => ({
425
+ current: {
426
+ getBoundingClientRect: () => menu ? menu.rect : new DOMRect(),
427
+ contains: () => false
428
+ }
429
+ }), [menu]);
430
+ const insertPill = useCallback2((item, replace) => {
431
+ const root = editorRef.current;
432
+ if (!root || !item || item.disabled) return;
433
+ const pill = buildPillNode(item);
434
+ const space = document.createTextNode("\xA0");
435
+ if (replace && replace.node && replace.node.parentNode === root) {
436
+ const { node, start, query } = replace;
437
+ node.deleteData(start, trigger.length + query.length);
438
+ const after = node.splitText(start);
439
+ root.insertBefore(pill, after);
440
+ root.insertBefore(space, after);
441
+ } else {
442
+ const s = selectionIn(root);
443
+ if (s) {
444
+ s.range.deleteContents();
445
+ s.range.insertNode(space);
446
+ s.range.insertNode(pill);
447
+ } else {
448
+ root.appendChild(pill);
449
+ root.appendChild(space);
450
+ }
451
+ }
452
+ placeCaretAfter(space);
453
+ setMenu(null);
454
+ emit();
455
+ }, [emit, trigger]);
456
+ const pick = useCallback2((item) => insertPill(item, menu), [insertPill, menu]);
457
+ const insertText = useCallback2((text) => {
458
+ const root = editorRef.current;
459
+ if (!root) return;
460
+ root.focus();
461
+ let done = false;
462
+ try {
463
+ done = document.execCommand("insertText", false, text);
464
+ } catch {
465
+ done = false;
466
+ }
467
+ if (!done) {
468
+ const s = selectionIn(root);
469
+ const tn = document.createTextNode(text);
470
+ if (s) {
471
+ s.range.deleteContents();
472
+ s.range.insertNode(tn);
473
+ placeCaretAfter(tn);
474
+ } else root.appendChild(tn);
475
+ }
476
+ emit();
477
+ syncMenu();
478
+ }, [emit, syncMenu]);
479
+ const wrapSelection = useCallback2((before, after = "") => {
480
+ const root = editorRef.current;
481
+ if (!root) return;
482
+ root.focus();
483
+ const s = selectionIn(root);
484
+ const selected = s ? s.range.toString() : "";
485
+ insertText(before + selected + after);
486
+ if (!selected && after) {
487
+ const sel = window.getSelection();
488
+ for (let i = 0; i < after.length; i++) sel && sel.modify && sel.modify("move", "backward", "character");
489
+ }
490
+ }, [insertText]);
491
+ const prefixLine = useCallback2((prefix) => {
492
+ const root = editorRef.current;
493
+ if (!root) return;
494
+ root.focus();
495
+ const s = selectionIn(root);
496
+ const node = s && s.range.startContainer;
497
+ const before = node && node.nodeType === 3 ? node.data.slice(0, s.range.startOffset) : "";
498
+ const atLineStart = !before || /\n$/.test(before) || node && node.nodeType !== 3;
499
+ insertText((atLineStart ? "" : "\n") + prefix);
500
+ }, [insertText]);
501
+ useImperativeHandle(ref, () => ({
502
+ focus: () => editorRef.current && editorRef.current.focus(),
503
+ clear: () => {
504
+ const root = editorRef.current;
505
+ if (root) {
506
+ writeSegments(root, []);
507
+ emit();
508
+ }
509
+ },
510
+ insertMention: (item) => insertPill(item, null),
511
+ insertText,
512
+ wrapSelection,
513
+ prefixLine,
514
+ get el() {
515
+ return editorRef.current;
516
+ }
517
+ }), [emit, insertPill, insertText, wrapSelection, prefixLine]);
518
+ const handleInput = () => {
519
+ emit();
520
+ syncMenu();
521
+ };
522
+ const handleKeyDown = (e) => {
523
+ if (onKeyDown) onKeyDown(e);
524
+ if (e.defaultPrevented) return;
525
+ if (menu) {
526
+ if (e.key === "ArrowDown") {
527
+ e.preventDefault();
528
+ setActive((a) => flat.length ? (a + 1) % flat.length : 0);
529
+ return;
530
+ }
531
+ if (e.key === "ArrowUp") {
532
+ e.preventDefault();
533
+ setActive((a) => flat.length ? (a - 1 + flat.length) % flat.length : 0);
534
+ return;
535
+ }
536
+ if ((e.key === "Enter" || e.key === "Tab") && flat.length) {
537
+ e.preventDefault();
538
+ pick(flat[active]);
539
+ return;
540
+ }
541
+ if (e.key === "Escape") {
542
+ e.preventDefault();
543
+ setMenu(null);
544
+ return;
545
+ }
546
+ }
547
+ if (e.key === "Enter") {
548
+ if (submitOnEnter && !e.shiftKey) {
549
+ e.preventDefault();
550
+ if (onSubmit) onSubmit();
551
+ return;
552
+ }
553
+ e.preventDefault();
554
+ insertText("\n");
555
+ }
556
+ };
557
+ const handlePaste = (e) => {
558
+ e.preventDefault();
559
+ const text = e.clipboardData && e.clipboardData.getData("text/plain") || "";
560
+ if (!text) return;
561
+ const segs = parseValue(text, format, resolver);
562
+ if (segs.every((s2) => s2.type === "text")) {
563
+ insertText(text);
564
+ return;
565
+ }
566
+ const root = editorRef.current;
567
+ const s = selectionIn(root);
568
+ if (!s) {
569
+ insertText(text);
570
+ return;
571
+ }
572
+ s.range.deleteContents();
573
+ const frag = document.createDocumentFragment();
574
+ let lastNode = null;
575
+ for (const seg of segs) {
576
+ if (seg.type === "mention") {
577
+ lastNode = buildPillNode(seg.item || seg);
578
+ frag.appendChild(lastNode);
579
+ continue;
580
+ }
581
+ seg.text.split("\n").forEach((line, i) => {
582
+ if (i > 0) {
583
+ lastNode = document.createElement("br");
584
+ frag.appendChild(lastNode);
585
+ }
586
+ if (line) {
587
+ lastNode = document.createTextNode(line);
588
+ frag.appendChild(lastNode);
589
+ }
590
+ });
591
+ }
592
+ s.range.insertNode(frag);
593
+ if (lastNode) placeCaretAfter(lastNode);
594
+ emit();
595
+ syncMenu();
596
+ };
597
+ const handleBlur = (e) => {
598
+ if (onBlur) onBlur(e);
599
+ };
600
+ const handleFocus = (e) => {
601
+ if (onFocus) onFocus(e);
602
+ };
603
+ useEffect2(() => {
604
+ if (!menu) return void 0;
605
+ const onSel = () => syncMenu();
606
+ document.addEventListener("selectionchange", onSel);
607
+ return () => document.removeEventListener("selectionchange", onSel);
608
+ }, [menu, syncMenu]);
609
+ useEffect2(() => {
610
+ if (!menu) return;
611
+ const el = document.getElementById(`${listId}-${active}`);
612
+ const list = el && el.closest(".uic-mention-menu");
613
+ if (!el || !list) return;
614
+ const top = el.offsetTop - list.offsetTop;
615
+ const bottom = top + el.offsetHeight;
616
+ if (top < list.scrollTop) list.scrollTop = top;
617
+ else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;
618
+ }, [active, menu, listId]);
619
+ const iconOf = (item) => {
620
+ if (renderIcon) {
621
+ const n = renderIcon(item);
622
+ if (n) return n;
623
+ }
624
+ if (item.avatar) return /* @__PURE__ */ jsx2("img", { src: item.avatar, alt: "" });
625
+ if (typeof item.icon === "string" && item.icon) return item.icon;
626
+ if (item.icon) return item.icon;
627
+ return /* @__PURE__ */ jsx2("span", { className: "is-mono", children: monogram(item.name) });
628
+ };
629
+ let index = -1;
630
+ return /* @__PURE__ */ jsxs("div", { className: ["uic-mention-field", disabled ? "is-disabled" : "", className].filter(Boolean).join(" "), children: [
631
+ /* @__PURE__ */ jsx2(
632
+ "div",
633
+ {
634
+ ref: editorRef,
635
+ id,
636
+ className: "uic-mention-editor" + (empty ? " is-empty" : ""),
637
+ contentEditable: !disabled,
638
+ suppressContentEditableWarning: true,
639
+ role: "textbox",
640
+ "aria-multiline": "true",
641
+ "aria-label": label,
642
+ "aria-autocomplete": "list",
643
+ "aria-expanded": !!menu,
644
+ "aria-controls": menu ? listId : void 0,
645
+ "aria-activedescendant": menu && flat.length ? `${listId}-${active}` : void 0,
646
+ "data-placeholder": placeholder || "",
647
+ spellCheck: "true",
648
+ onInput: handleInput,
649
+ onKeyDown: handleKeyDown,
650
+ onPaste: handlePaste,
651
+ onFocus: handleFocus,
652
+ onBlur: handleBlur
653
+ }
654
+ ),
655
+ /* @__PURE__ */ jsx2(Popover, { open: !!menu, anchorRef, onClose: closeMenu, width: menuWidth, minHeight: 120, className: "uic-mention-pop", label: menuTitle || "Mentions", children: /* @__PURE__ */ jsxs("div", { className: "uic-mention-menu", role: "listbox", id: listId, onMouseDown: (e) => e.preventDefault(), children: [
656
+ menuTitle ? /* @__PURE__ */ jsx2("div", { className: "uic-mention-head", children: menuTitle }) : null,
657
+ groups.map((g) => /* @__PURE__ */ jsxs("div", { className: "uic-mention-group", children: [
658
+ g.section ? /* @__PURE__ */ jsx2("div", { className: "uic-mention-sec", children: g.section }) : null,
659
+ g.items.map((item) => {
660
+ index += 1;
661
+ const i = index;
662
+ const dis = !!item.disabled;
663
+ const reason = typeof item.disabled === "string" ? item.disabled : null;
664
+ return /* @__PURE__ */ jsxs(
665
+ "button",
666
+ {
667
+ type: "button",
668
+ id: `${listId}-${i}`,
669
+ role: "option",
670
+ "aria-selected": i === active,
671
+ "aria-disabled": dis || void 0,
672
+ className: "uic-mention-item" + (i === active ? " is-active" : "") + (dis ? " is-disabled" : ""),
673
+ style: item.color ? { "--uic-mention-color": item.color } : void 0,
674
+ onMouseEnter: () => setActive(i),
675
+ onClick: () => {
676
+ if (!dis) pick(item);
677
+ },
678
+ children: [
679
+ /* @__PURE__ */ jsx2("span", { className: "uic-mention-ic", children: iconOf(item) }),
680
+ /* @__PURE__ */ jsxs("span", { className: "uic-mention-text", children: [
681
+ /* @__PURE__ */ jsx2("span", { className: "uic-mention-name", children: item.name }),
682
+ item.description ? /* @__PURE__ */ jsx2("span", { className: "uic-mention-desc", children: item.description }) : null
683
+ ] }),
684
+ reason || item.tag ? /* @__PURE__ */ jsx2("span", { className: "uic-mention-tag", children: reason || item.tag }) : null
685
+ ]
686
+ },
687
+ item.id
688
+ );
689
+ })
690
+ ] }, g.section || "_")),
691
+ !flat.length ? /* @__PURE__ */ jsx2("div", { className: "uic-mention-empty", children: emptyText }) : null
692
+ ] }) })
693
+ ] });
694
+ });
695
+ function MentionText({ value, items = [], format = CURLY, className = "", renderIcon }) {
696
+ const resolver = useMemo(() => makeResolver(items), [items]);
697
+ const segs = useMemo(() => parseValue(value || "", format, resolver), [value, format, resolver]);
698
+ return /* @__PURE__ */ jsx2("span", { className: ["uic-mention-text-view", className].filter(Boolean).join(" "), children: segs.map((s, i) => {
699
+ if (s.type === "text") return /* @__PURE__ */ jsx2(React2.Fragment, { children: s.text }, i);
700
+ const item = s.item || s;
701
+ const icon = renderIcon ? renderIcon(item) : null;
702
+ return /* @__PURE__ */ jsxs(
703
+ "span",
704
+ {
705
+ className: "uic-mention",
706
+ "data-kind": s.kind || void 0,
707
+ title: item.description || void 0,
708
+ style: item.color ? { "--uic-mention-color": item.color } : void 0,
709
+ children: [
710
+ /* @__PURE__ */ jsx2("span", { className: "uic-mention-ic" + (icon || typeof item.icon === "string" && item.icon || item.avatar ? "" : " is-mono"), children: icon || (item.avatar ? /* @__PURE__ */ jsx2("img", { src: item.avatar, alt: "" }) : typeof item.icon === "string" && item.icon ? item.icon : monogram(item.name)) }),
711
+ /* @__PURE__ */ jsx2("span", { className: "uic-mention-name", children: s.name })
712
+ ]
713
+ },
714
+ i
715
+ );
716
+ }) });
717
+ }
718
+
719
+ // src/sheet/SheetGrid.jsx
720
+ import { useEffect as useEffect3, useMemo as useMemo2, useRef as useRef3, useState as useState3 } from "react";
721
+ import { createPortal as createPortal2 } from "react-dom";
722
+ import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
723
+ var cellKey = (rowId, colId) => `${rowId}:${colId}`;
724
+ var uid = (p) => `${p}_${Math.random().toString(36).slice(2, 10)}`;
725
+ var TYPE_LABEL = {
726
+ text: "Text",
727
+ number: "Number",
728
+ select: "Select",
729
+ tags: "Tags",
730
+ checkbox: "Checkbox",
731
+ date: "Date",
732
+ url: "Link",
733
+ resource: "Resource",
734
+ compute: "Computed"
735
+ };
736
+ var TYPE_GLYPH = { text: "Aa", number: "#", select: "\u25BE", tags: "#", checkbox: "\u2713", date: "\u25A6", url: "\u2197", resource: "\u25EB", compute: "\u2726" };
737
+ var MANUAL_TYPES = ["text", "number", "select", "tags", "checkbox", "date", "url", "resource"];
738
+ var COMPUTE_KINDS = [
739
+ { kind: "prompt", label: "AI prompt" },
740
+ { kind: "harness", label: "Agent (harness)" },
741
+ { kind: "workflow", label: "Workflow" },
742
+ { kind: "image", label: "Generate image" }
743
+ ];
744
+ var RESOURCE_KINDS = ["image", "sheet", "slides", "workflow", "graph"];
745
+ var RESOURCE_ICON = { image: "\u{1F5BC}", sheet: "\u25A6", slides: "\u25A4", workflow: "\u2699", graph: "\u25C9" };
746
+ function PopPortal({ anchor, width = 250, estHeight = 300, className, children, onClose }) {
747
+ const boxRef = useRef3(null);
748
+ useEffect3(() => {
749
+ if (!onClose) return void 0;
750
+ const close = (e) => {
751
+ if (e?.type === "scroll" && boxRef.current && e.target instanceof Node && boxRef.current.contains(e.target)) return;
752
+ onClose();
753
+ };
754
+ window.addEventListener("scroll", close, true);
755
+ window.addEventListener("resize", close);
756
+ return () => {
757
+ window.removeEventListener("scroll", close, true);
758
+ window.removeEventListener("resize", close);
759
+ };
760
+ }, [onClose]);
761
+ if (!anchor) return null;
762
+ const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8));
763
+ let top = anchor.bottom + 6;
764
+ if (top + estHeight > window.innerHeight - 8) top = Math.max(8, anchor.top - estHeight - 6);
765
+ return createPortal2(
766
+ /* @__PURE__ */ jsx3("div", { ref: boxRef, className, style: { position: "fixed", top, left, width, zIndex: 1e3 }, children }),
767
+ document.body
768
+ );
769
+ }
770
+ var PILL_PALETTE = [
771
+ { name: "green", color: "#D1FAE5" },
772
+ { name: "red", color: "#FEE2E2" },
773
+ { name: "amber", color: "#FEF3C7" },
774
+ { name: "blue", color: "#DBEAFE" },
775
+ { name: "purple", color: "#EDE9FE" },
776
+ { name: "pink", color: "#FCE7F3" },
777
+ { name: "teal", color: "#CCFBF1" },
778
+ { name: "gray", color: "#E5E7EB" }
779
+ ];
780
+ var PILL_FALLBACKS = ["#E0E7FF", "#FCE7F3", "#D1FAE5", "#FEF3C7", "#E0F2FE", "#F3E8FF", "#FFE4E6"];
781
+ function normOptions(options) {
782
+ return (options || []).map((o, i) => {
783
+ if (typeof o === "string") return { label: o, color: PILL_FALLBACKS[i % PILL_FALLBACKS.length] };
784
+ return { label: o.label ?? String(o.value ?? ""), color: o.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] };
785
+ });
786
+ }
787
+ var sameValue = (a, b) => String(a).trim().toLowerCase() === String(b).trim().toLowerCase();
788
+ function optionFor(value, options) {
789
+ if (value === void 0 || value === null || value === "") return null;
790
+ return normOptions(options).find((o) => sameValue(o.label, value)) || null;
791
+ }
792
+ function pillColor(label, options) {
793
+ const hit = optionFor(label, options);
794
+ if (hit) return hit.color;
795
+ let h = 0;
796
+ for (const ch of String(label)) h = h * 31 + ch.charCodeAt(0) >>> 0;
797
+ return PILL_FALLBACKS[h % PILL_FALLBACKS.length];
798
+ }
799
+ function RefImage({ refVal, fetchBlobUrl }) {
800
+ const [src, setSrc] = useState3(/^https?:\/\//i.test(refVal.url || "") ? refVal.url : null);
801
+ useEffect3(() => {
802
+ let dead = false;
803
+ let obj = null;
804
+ if (!src && refVal.url && fetchBlobUrl) {
805
+ fetchBlobUrl(refVal.url).then((u) => {
806
+ if (!dead) {
807
+ obj = u;
808
+ setSrc(u);
809
+ }
810
+ });
811
+ }
812
+ return () => {
813
+ dead = true;
814
+ if (obj) URL.revokeObjectURL(obj);
815
+ };
816
+ }, [refVal.url]);
817
+ if (!src) return /* @__PURE__ */ jsxs2("span", { className: "shg-refchip", children: [
818
+ RESOURCE_ICON.image,
819
+ " ",
820
+ refVal.name || "image"
821
+ ] });
822
+ return /* @__PURE__ */ jsx3("img", { className: "shg-refimg", src, alt: refVal.name || "", title: refVal.name || "" });
823
+ }
824
+ function ResourceChip({ refVal, onOpen }) {
825
+ const icon = RESOURCE_ICON[refVal.kind] || "\u25C7";
826
+ return /* @__PURE__ */ jsxs2(
827
+ "button",
828
+ {
829
+ className: "shg-refchip shg-refchip-btn",
830
+ title: `Open ${refVal.kind}`,
831
+ onClick: (e) => {
832
+ e.stopPropagation();
833
+ onOpen && onOpen(refVal);
834
+ },
835
+ children: [
836
+ /* @__PURE__ */ jsx3("span", { className: "shg-refchip-ic", children: icon }),
837
+ /* @__PURE__ */ jsx3("span", { className: "shg-refchip-name", children: refVal.name || refVal.id || refVal.kind })
838
+ ]
839
+ }
840
+ );
841
+ }
842
+ function StatusDot({ status }) {
843
+ if (!status || status === "empty" || status === "done") return null;
844
+ return /* @__PURE__ */ jsx3("span", { className: `shg-dot shg-dot-${status}`, title: status });
845
+ }
846
+ function CellValue({ cell, col, fetchBlobUrl, onOpenResource }) {
847
+ const v = cell?.value;
848
+ if (v === void 0 || v === null || v === "") return /* @__PURE__ */ jsx3("span", { className: "shg-val-txt" });
849
+ if (v && typeof v === "object" && !Array.isArray(v) && v.kind) {
850
+ if (v.kind === "image") return /* @__PURE__ */ jsx3(RefImage, { refVal: v, fetchBlobUrl });
851
+ return /* @__PURE__ */ jsx3(ResourceChip, { refVal: v, onOpen: onOpenResource });
852
+ }
853
+ const styled = col.type !== "tags" && optionFor(v, col.options);
854
+ if (styled) return /* @__PURE__ */ jsx3("span", { className: "shg-pill", style: { background: styled.color }, children: styled.label });
855
+ switch (col.type) {
856
+ case "select":
857
+ return /* @__PURE__ */ jsx3("span", { className: "shg-pill", style: { background: pillColor(String(v), col.options) }, children: String(v) });
858
+ case "tags": {
859
+ const tags = Array.isArray(v) ? v : String(v).split(",").map((s) => s.trim()).filter(Boolean);
860
+ return /* @__PURE__ */ jsx3("span", { className: "shg-pills", children: tags.map((t) => /* @__PURE__ */ jsx3("span", { className: "shg-pill", style: { background: pillColor(t, col.options) }, children: t }, t)) });
861
+ }
862
+ case "checkbox":
863
+ return /* @__PURE__ */ jsx3("span", { className: "shg-check" + (v ? " on" : ""), children: v ? "\u2713" : "" });
864
+ case "url": {
865
+ const href = /^https?:\/\//i.test(String(v)) ? String(v) : `https://${v}`;
866
+ return /* @__PURE__ */ jsx3("a", { className: "shg-link", href, target: "_blank", rel: "noreferrer", onClick: (e) => e.stopPropagation(), children: String(v) });
867
+ }
868
+ case "number":
869
+ return /* @__PURE__ */ jsx3("span", { className: "shg-val-txt shg-num", children: String(v) });
870
+ default:
871
+ return /* @__PURE__ */ jsx3("span", { className: "shg-val-txt", children: typeof v === "object" ? JSON.stringify(v) : String(v) });
872
+ }
873
+ }
874
+ function SheetGrid({ sheet, ops, onRunCell, onRunColumn, readOnly = false, fetchBlobUrl, onOpenResource, peers, onPresence }) {
875
+ const columns = sheet?.columns || [];
876
+ const rows = sheet?.rows || [];
877
+ const cells = sheet?.cells || {};
878
+ const tabId = sheet?.id;
879
+ const canEdit = !readOnly && !!ops && !!tabId;
880
+ const [editing, setEditing] = useState3(null);
881
+ const [draft, setDraft] = useState3("");
882
+ const [menuCol, setMenuCol] = useState3(null);
883
+ const [sizeDraft, setSizeDraft] = useState3({});
884
+ const [dnd, setDnd] = useState3(null);
885
+ const [dropAt, setDropAt] = useState3(null);
886
+ const inputRef = useRef3(null);
887
+ const dragRef = useRef3(null);
888
+ const [sel, setSel] = useState3(null);
889
+ const dragSel = useRef3(false);
890
+ const rootRef = useRef3(null);
891
+ const presenceRef = useRef3(onPresence);
892
+ presenceRef.current = onPresence;
893
+ const range = sel ? {
894
+ r0: Math.min(sel.a.r, sel.f.r),
895
+ r1: Math.max(sel.a.r, sel.f.r),
896
+ c0: Math.min(sel.a.c, sel.f.c),
897
+ c1: Math.max(sel.a.c, sel.f.c)
898
+ } : null;
899
+ const inSel = (ri, ci) => !!range && ri >= range.r0 && ri <= range.r1 && ci >= range.c0 && ci <= range.c1;
900
+ const isFocus = (ri, ci) => !!sel && sel.f.r === ri && sel.f.c === ci;
901
+ 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)) });
902
+ const moveFocus = (dr, dc, extend) => setSel((cur) => {
903
+ if (!cur || !rows.length || !columns.length) return cur;
904
+ const f = clampSel({ r: cur.f.r + dr, c: cur.f.c + dc });
905
+ return { a: extend ? cur.a : f, f };
906
+ });
907
+ useEffect3(() => {
908
+ const up = () => {
909
+ dragSel.current = false;
910
+ };
911
+ window.addEventListener("mouseup", up);
912
+ return () => window.removeEventListener("mouseup", up);
913
+ }, []);
914
+ useEffect3(() => {
915
+ const fn = presenceRef.current;
916
+ if (!fn) return;
917
+ const ids = (p) => [rows[p.r]?.id, columns[p.c]?.id];
918
+ fn({
919
+ sel: sel && rows[sel.f.r] && columns[sel.f.c] ? { a: ids(sel.a), f: ids(sel.f) } : null,
920
+ typing: editing && typeof draft === "string" ? { key: cellKey(editing.rowId, editing.colId), text: draft } : null
921
+ });
922
+ }, [sel, editing, draft, rows, columns]);
923
+ const peerLayer = useMemo2(() => {
924
+ const focus = {}, tint = {}, typing = {};
925
+ const rIdx = new Map(rows.map((r, i) => [r.id, i]));
926
+ const cIdx = new Map(columns.map((c, i) => [c.id, i]));
927
+ for (const p of peers || []) {
928
+ if (p.typing && p.typing.key) typing[p.typing.key] = { text: p.typing.text, color: p.color, name: p.name };
929
+ if (!p.sel || !p.sel.a || !p.sel.f) continue;
930
+ 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]) };
931
+ if ([a.r, a.c, f.r, f.c].some((v) => v === void 0)) continue;
932
+ focus[cellKey(p.sel.f[0], p.sel.f[1])] = p;
933
+ for (let r = Math.min(a.r, f.r); r <= Math.max(a.r, f.r); r++) {
934
+ for (let c = Math.min(a.c, f.c); c <= Math.max(a.c, f.c); c++) {
935
+ const k = cellKey(rows[r].id, columns[c].id);
936
+ if (!tint[k]) tint[k] = p.color;
937
+ }
938
+ }
939
+ }
940
+ return { focus, tint, typing };
941
+ }, [peers, rows, columns]);
942
+ const startResize = (e, kind, id, start) => {
943
+ if (readOnly) return;
944
+ e.preventDefault();
945
+ e.stopPropagation();
946
+ const origin = kind === "col" ? e.clientX : e.clientY;
947
+ dragRef.current = { kind, id, start, origin, last: start };
948
+ const onMove = (ev) => {
949
+ const d = dragRef.current;
950
+ if (!d) return;
951
+ const delta = (d.kind === "col" ? ev.clientX : ev.clientY) - d.origin;
952
+ const next = Math.max(d.kind === "col" ? 90 : 26, d.start + delta);
953
+ d.last = next;
954
+ setSizeDraft((sd) => ({ ...sd, [d.kind]: { ...sd[d.kind] || {}, [d.id]: next } }));
955
+ };
956
+ const onUp = () => {
957
+ const d = dragRef.current;
958
+ dragRef.current = null;
959
+ window.removeEventListener("mousemove", onMove);
960
+ window.removeEventListener("mouseup", onUp);
961
+ document.body.style.cursor = "";
962
+ if (!d) return;
963
+ setSizeDraft({});
964
+ if (!canEdit) return;
965
+ if (d.kind === "col") {
966
+ const c = columns.find((x) => x.id === d.id);
967
+ if (c) ops.setColumn(tabId, { ...c, width: Math.round(d.last) });
968
+ } else {
969
+ const r = rows.find((x) => x.id === d.id);
970
+ if (r) ops.setRow(tabId, { ...r, height: Math.round(d.last) });
971
+ }
972
+ };
973
+ window.addEventListener("mousemove", onMove);
974
+ window.addEventListener("mouseup", onUp);
975
+ document.body.style.cursor = kind === "col" ? "col-resize" : "row-resize";
976
+ };
977
+ const colWidth = (col) => sizeDraft.col && sizeDraft.col[col.id] || col.width || void 0;
978
+ const reorder = (kind, fromId, toId, after) => {
979
+ if (!canEdit || fromId === toId) return;
980
+ const arr = (kind === "col" ? columns : rows).map((x) => x.id);
981
+ const i = arr.indexOf(fromId);
982
+ if (i < 0) return;
983
+ arr.splice(i, 1);
984
+ let j = arr.indexOf(toId);
985
+ if (j < 0) return;
986
+ if (after) j += 1;
987
+ if (kind === "col") ops.moveColumn(tabId, fromId, j);
988
+ else ops.moveRow(tabId, fromId, j);
989
+ };
990
+ const dndProps = (kind, id) => readOnly ? {} : {
991
+ draggable: true,
992
+ onDragStart: (e) => {
993
+ if (e.target.closest && e.target.closest(".shg-resize-col, .shg-resize-row, input, button")) {
994
+ e.preventDefault();
995
+ return;
996
+ }
997
+ e.dataTransfer.effectAllowed = "move";
998
+ e.dataTransfer.setData("text/plain", `${kind}:${id}`);
999
+ setDnd({ kind, id });
1000
+ },
1001
+ onDragOver: (e) => {
1002
+ if (!dnd || dnd.kind !== kind || dnd.id === id) return;
1003
+ e.preventDefault();
1004
+ const r = e.currentTarget.getBoundingClientRect();
1005
+ const after = kind === "col" ? e.clientX > r.x + r.width / 2 : e.clientY > r.y + r.height / 2;
1006
+ setDropAt((d) => d && d.id === id && d.after === after ? d : { kind, id, after });
1007
+ },
1008
+ onDrop: (e) => {
1009
+ e.preventDefault();
1010
+ if (dnd && dnd.kind === kind && dnd.id !== id) {
1011
+ const r = e.currentTarget.getBoundingClientRect();
1012
+ const after = kind === "col" ? e.clientX > r.x + r.width / 2 : e.clientY > r.y + r.height / 2;
1013
+ reorder(kind, dnd.id, id, after);
1014
+ }
1015
+ setDnd(null);
1016
+ setDropAt(null);
1017
+ },
1018
+ onDragEnd: () => {
1019
+ setDnd(null);
1020
+ setDropAt(null);
1021
+ }
1022
+ };
1023
+ const dndClass = (kind, id) => {
1024
+ let cls = "";
1025
+ if (dnd && dnd.kind === kind && dnd.id === id) cls += " shg-dragging";
1026
+ if (dropAt && dropAt.kind === kind && dropAt.id === id) {
1027
+ cls += dropAt.after ? kind === "col" ? " shg-drop-after" : " shg-drop-below" : kind === "col" ? " shg-drop-before" : " shg-drop-above";
1028
+ }
1029
+ return cls;
1030
+ };
1031
+ const numW = Math.max(40, 24 + String(rows.length || 1).length * 9);
1032
+ const numStyle = { width: numW, minWidth: numW, maxWidth: numW };
1033
+ const rowHeight = (row) => sizeDraft.row && sizeDraft.row[row.id] || row.height || void 0;
1034
+ useEffect3(() => {
1035
+ if (editing && inputRef.current) inputRef.current.focus();
1036
+ }, [editing]);
1037
+ const setCell = (rowId, colId, value) => {
1038
+ if (!canEdit) return;
1039
+ ops.setCell(tabId, cellKey(rowId, colId), { value, status: "done", updated_at: Math.floor(Date.now() / 1e3) });
1040
+ };
1041
+ const openEdit = (rowId, col, anchorEl, initial) => {
1042
+ if (!canEdit) return;
1043
+ if (col.type === "compute") return;
1044
+ if (col.type === "checkbox") {
1045
+ const cur = cells[cellKey(rowId, col.id)];
1046
+ setCell(rowId, col.id, !(cur && cur.value));
1047
+ return;
1048
+ }
1049
+ const c = cells[cellKey(rowId, col.id)];
1050
+ const v = c?.value;
1051
+ if (col.type === "tags") setDraft(initial ?? (Array.isArray(v) ? v.join(", ") : v || ""));
1052
+ else if (col.type === "resource") setDraft(v && typeof v === "object" ? v : { kind: "sheet", name: "", id: "", url: "" });
1053
+ else setDraft(initial ?? (v == null ? "" : String(v)));
1054
+ setEditing({ rowId, colId: col.id, type: col.type, rect: anchorEl?.getBoundingClientRect?.() || null });
1055
+ };
1056
+ const commitEdit = () => {
1057
+ if (!editing) return;
1058
+ const { rowId, colId, type } = editing;
1059
+ let value = draft;
1060
+ if (type === "number") value = draft === "" ? null : Number(draft);
1061
+ else if (type === "tags") value = draft ? draft.split(",").map((s) => s.trim()).filter(Boolean) : [];
1062
+ setCell(rowId, colId, value);
1063
+ setEditing(null);
1064
+ };
1065
+ const addColumn = () => canEdit && ops.setColumn(tabId, { id: uid("col"), name: `Column ${columns.length + 1}`, type: "text" });
1066
+ const addRow = () => canEdit && ops.setRow(tabId, { id: uid("row") });
1067
+ const deleteColumn = (colId) => canEdit && ops.deleteColumn(tabId, colId);
1068
+ const deleteRow = (rowId) => canEdit && ops.deleteRow(tabId, rowId);
1069
+ const renameColumn = (colId, name) => {
1070
+ const c = columns.find((x) => x.id === colId);
1071
+ if (canEdit && c) ops.setColumn(tabId, { ...c, name });
1072
+ };
1073
+ const configureColumn = (colId, patch) => {
1074
+ const c = columns.find((x) => x.id === colId);
1075
+ if (!canEdit || !c) return;
1076
+ const next = { ...c, ...patch };
1077
+ if (patch.type && patch.type !== "compute") delete next.compute;
1078
+ ops.setColumn(tabId, next);
1079
+ };
1080
+ const cellText = (c) => {
1081
+ const v = c?.value;
1082
+ if (v === void 0 || v === null) return "";
1083
+ if (Array.isArray(v)) return v.join(", ");
1084
+ if (typeof v === "object") return v.name || v.url || v.id || "";
1085
+ return String(v);
1086
+ };
1087
+ const copySelection = (e) => {
1088
+ if (!range || editing) return;
1089
+ const lines = [];
1090
+ for (let r = range.r0; r <= range.r1; r++) {
1091
+ const parts = [];
1092
+ for (let c = range.c0; c <= range.c1; c++) parts.push(cellText(cells[cellKey(rows[r].id, columns[c].id)]));
1093
+ lines.push(parts.join(" "));
1094
+ }
1095
+ e.clipboardData.setData("text/plain", lines.join("\n"));
1096
+ e.preventDefault();
1097
+ };
1098
+ const pasteAt = (e) => {
1099
+ if (!sel || editing || !canEdit) return;
1100
+ const text = e.clipboardData.getData("text/plain");
1101
+ if (!text) return;
1102
+ e.preventDefault();
1103
+ const now = Math.floor(Date.now() / 1e3);
1104
+ const patch = {};
1105
+ const lines = text.replace(/\r/g, "").split("\n");
1106
+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
1107
+ lines.forEach((line, dr) => line.split(" ").forEach((raw, dc) => {
1108
+ const row = rows[sel.f.r + dr], col = columns[sel.f.c + dc];
1109
+ if (!row || !col || col.type === "compute") return;
1110
+ let value = raw;
1111
+ if (col.type === "number") value = raw === "" ? null : Number(raw);
1112
+ else if (col.type === "checkbox") value = /^(true|yes|1|✓)$/i.test(raw.trim());
1113
+ else if (col.type === "tags") value = raw ? raw.split(",").map((x) => x.trim()).filter(Boolean) : [];
1114
+ patch[cellKey(row.id, col.id)] = value === null || value === "" ? null : { value, status: "done", updated_at: now };
1115
+ }));
1116
+ if (Object.keys(patch).length) ops.setCells(tabId, patch);
1117
+ setSel({ a: sel.f, f: clampSel({ r: sel.f.r + lines.length - 1, c: sel.f.c + Math.max(...lines.map((l) => l.split(" ").length)) - 1 }) });
1118
+ };
1119
+ const clearSelection = () => {
1120
+ if (!range || !canEdit) return;
1121
+ const patch = {};
1122
+ for (let r = range.r0; r <= range.r1; r++) {
1123
+ for (let c = range.c0; c <= range.c1; c++) {
1124
+ if (columns[c].type === "compute") continue;
1125
+ const k = cellKey(rows[r].id, columns[c].id);
1126
+ if (cells[k]) patch[k] = null;
1127
+ }
1128
+ }
1129
+ if (Object.keys(patch).length) ops.setCells(tabId, patch);
1130
+ };
1131
+ const onKeyDown = (e) => {
1132
+ if (editing || menuCol) return;
1133
+ if (!sel) return;
1134
+ const meta = e.metaKey || e.ctrlKey;
1135
+ if (meta && (e.key === "c" || e.key === "v" || e.key === "x")) return;
1136
+ const focusCell = () => ({ row: rows[sel.f.r], col: columns[sel.f.c] });
1137
+ switch (e.key) {
1138
+ case "ArrowUp":
1139
+ e.preventDefault();
1140
+ moveFocus(-1, 0, e.shiftKey);
1141
+ return;
1142
+ case "ArrowDown":
1143
+ e.preventDefault();
1144
+ moveFocus(1, 0, e.shiftKey);
1145
+ return;
1146
+ case "ArrowLeft":
1147
+ e.preventDefault();
1148
+ moveFocus(0, -1, e.shiftKey);
1149
+ return;
1150
+ case "ArrowRight":
1151
+ e.preventDefault();
1152
+ moveFocus(0, 1, e.shiftKey);
1153
+ return;
1154
+ case "Tab":
1155
+ e.preventDefault();
1156
+ moveFocus(0, e.shiftKey ? -1 : 1, false);
1157
+ return;
1158
+ case "Escape":
1159
+ setSel(null);
1160
+ return;
1161
+ case "Enter":
1162
+ case "F2": {
1163
+ e.preventDefault();
1164
+ const { row, col } = focusCell();
1165
+ if (row && col) openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell="${cellKey(row.id, col.id)}"]`));
1166
+ return;
1167
+ }
1168
+ case "Delete":
1169
+ case "Backspace":
1170
+ e.preventDefault();
1171
+ clearSelection();
1172
+ return;
1173
+ default:
1174
+ }
1175
+ if (!meta && !e.altKey && e.key.length === 1) {
1176
+ const { row, col } = focusCell();
1177
+ if (row && col && col.type !== "compute" && col.type !== "checkbox") {
1178
+ e.preventDefault();
1179
+ openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell="${cellKey(row.id, col.id)}"]`), e.key);
1180
+ }
1181
+ }
1182
+ };
1183
+ const renderEditor = (col) => {
1184
+ if (col.type === "resource") {
1185
+ const d = typeof draft === "object" && draft ? draft : { kind: "sheet" };
1186
+ const set = (k, v) => setDraft({ ...d, [k]: v });
1187
+ return /* @__PURE__ */ jsx3(
1188
+ PopPortal,
1189
+ {
1190
+ anchor: editing.rect,
1191
+ width: 240,
1192
+ estHeight: 230,
1193
+ className: "shg-select-pop shg-ref-pop",
1194
+ onClose: () => setEditing(null),
1195
+ children: /* @__PURE__ */ jsxs2("div", { onClick: (e) => e.stopPropagation(), children: [
1196
+ /* @__PURE__ */ jsx3("select", { className: "shg-menu-input", value: d.kind || "sheet", onChange: (e) => set("kind", e.target.value), children: RESOURCE_KINDS.map((k) => /* @__PURE__ */ jsx3("option", { value: k, children: k }, k)) }),
1197
+ /* @__PURE__ */ jsx3("input", { className: "shg-menu-input", placeholder: "Name", value: d.name || "", onChange: (e) => set("name", e.target.value) }),
1198
+ /* @__PURE__ */ jsx3("input", { className: "shg-menu-input", placeholder: "Resource id (e.g. sheet.\u2026)", value: d.id || "", onChange: (e) => set("id", e.target.value) }),
1199
+ /* @__PURE__ */ jsx3("input", { className: "shg-menu-input", placeholder: "or URL", value: d.url || "", onChange: (e) => set("url", e.target.value) }),
1200
+ /* @__PURE__ */ jsxs2("div", { className: "shg-menu-actions", children: [
1201
+ /* @__PURE__ */ jsx3("button", { className: "shg-pop-clear", onClick: () => {
1202
+ setCell(editing.rowId, editing.colId, null);
1203
+ setEditing(null);
1204
+ }, children: "Clear" }),
1205
+ /* @__PURE__ */ jsx3("button", { className: "shg-menu-apply", onClick: () => {
1206
+ setCell(editing.rowId, editing.colId, d);
1207
+ setEditing(null);
1208
+ }, children: "Set" })
1209
+ ] })
1210
+ ] })
1211
+ }
1212
+ );
1213
+ }
1214
+ if (col.type === "select") {
1215
+ const opts = normOptions(col.options);
1216
+ return /* @__PURE__ */ jsxs2(
1217
+ PopPortal,
1218
+ {
1219
+ anchor: editing.rect,
1220
+ width: 190,
1221
+ estHeight: 40 + opts.length * 30,
1222
+ className: "shg-select-pop",
1223
+ onClose: () => setEditing(null),
1224
+ children: [
1225
+ opts.length === 0 && /* @__PURE__ */ jsx3("div", { className: "shg-pop-note", children: "No options yet \u2014 add them in the column menu." }),
1226
+ opts.map((o) => /* @__PURE__ */ jsx3(
1227
+ "button",
1228
+ {
1229
+ className: "shg-pill shg-pill-btn",
1230
+ style: { background: o.color },
1231
+ onClick: (e) => {
1232
+ e.stopPropagation();
1233
+ setCell(editing.rowId, editing.colId, o.label);
1234
+ setEditing(null);
1235
+ },
1236
+ children: o.label
1237
+ },
1238
+ o.label
1239
+ )),
1240
+ /* @__PURE__ */ jsx3(
1241
+ "button",
1242
+ {
1243
+ className: "shg-pop-clear",
1244
+ onClick: (e) => {
1245
+ e.stopPropagation();
1246
+ setCell(editing.rowId, editing.colId, null);
1247
+ setEditing(null);
1248
+ },
1249
+ children: "Clear"
1250
+ }
1251
+ )
1252
+ ]
1253
+ }
1254
+ );
1255
+ }
1256
+ const inputType = col.type === "date" ? "date" : col.type === "number" ? "number" : "text";
1257
+ return /* @__PURE__ */ jsx3(
1258
+ "input",
1259
+ {
1260
+ ref: inputRef,
1261
+ className: "shg-input",
1262
+ type: inputType,
1263
+ value: draft,
1264
+ placeholder: col.type === "tags" ? "tag, tag, \u2026" : "",
1265
+ onChange: (e) => setDraft(e.target.value),
1266
+ onBlur: commitEdit,
1267
+ onKeyDown: (e) => {
1268
+ if (e.key === "Enter") {
1269
+ e.preventDefault();
1270
+ commitEdit();
1271
+ moveFocus(1, 0, false);
1272
+ rootRef.current?.focus();
1273
+ } else if (e.key === "Tab") {
1274
+ e.preventDefault();
1275
+ commitEdit();
1276
+ moveFocus(0, e.shiftKey ? -1 : 1, false);
1277
+ rootRef.current?.focus();
1278
+ } else if (e.key === "Escape") {
1279
+ setEditing(null);
1280
+ rootRef.current?.focus();
1281
+ }
1282
+ }
1283
+ }
1284
+ );
1285
+ };
1286
+ return /* @__PURE__ */ jsx3("div", { className: "shg", ref: rootRef, tabIndex: 0, onKeyDown, onCopy: copySelection, onPaste: pasteAt, children: /* @__PURE__ */ jsx3("div", { className: "shg-scroll", children: /* @__PURE__ */ jsxs2("table", { className: "shg-table", children: [
1287
+ /* @__PURE__ */ jsx3("thead", { children: /* @__PURE__ */ jsxs2("tr", { children: [
1288
+ /* @__PURE__ */ jsx3("th", { className: "shg-corner", style: numStyle }),
1289
+ columns.map((col) => /* @__PURE__ */ jsxs2(
1290
+ "th",
1291
+ {
1292
+ className: "shg-col" + (col.type === "compute" ? " shg-col-compute" : "") + dndClass("col", col.id),
1293
+ style: colWidth(col) ? { width: colWidth(col), minWidth: colWidth(col), maxWidth: colWidth(col) } : void 0,
1294
+ ...dndProps("col", col.id),
1295
+ children: [
1296
+ !readOnly && /* @__PURE__ */ jsx3("span", { className: "shg-resize-col", onMouseDown: (e) => startResize(e, "col", col.id, colWidth(col) || e.currentTarget.closest("th").offsetWidth) }),
1297
+ /* @__PURE__ */ jsx3("div", { className: "shg-col-h", children: /* @__PURE__ */ jsx3(
1298
+ ColumnHeader,
1299
+ {
1300
+ col,
1301
+ columns,
1302
+ readOnly,
1303
+ menuOpen: menuCol?.id === col.id,
1304
+ menuAnchor: menuCol?.id === col.id ? menuCol.rect : null,
1305
+ onMenu: (e) => setMenuCol(menuCol?.id === col.id ? null : { id: col.id, rect: e.currentTarget.getBoundingClientRect() }),
1306
+ onCloseMenu: () => setMenuCol(null),
1307
+ onRename: renameColumn,
1308
+ onConfigure: configureColumn,
1309
+ onDelete: () => {
1310
+ setMenuCol(null);
1311
+ deleteColumn(col.id);
1312
+ },
1313
+ onRun: col.type === "compute" && onRunColumn ? () => onRunColumn(col.id) : null,
1314
+ width: colWidth(col)
1315
+ }
1316
+ ) })
1317
+ ]
1318
+ },
1319
+ col.id
1320
+ )),
1321
+ !readOnly && /* @__PURE__ */ jsx3("th", { className: "shg-add-col", children: /* @__PURE__ */ jsx3("button", { className: "shg-add", onClick: addColumn, title: "Add column", children: "+" }) })
1322
+ ] }) }),
1323
+ /* @__PURE__ */ jsxs2("tbody", { children: [
1324
+ rows.map((row, ri) => /* @__PURE__ */ jsxs2(
1325
+ "tr",
1326
+ {
1327
+ style: {
1328
+ ...rowHeight(row) ? { height: rowHeight(row) } : null,
1329
+ "--shg-clamp": Math.max(1, Math.floor(((rowHeight(row) || 34) - 10) / 18))
1330
+ },
1331
+ children: [
1332
+ /* @__PURE__ */ jsxs2(
1333
+ "td",
1334
+ {
1335
+ className: "shg-rownum" + dndClass("row", row.id),
1336
+ style: numStyle,
1337
+ title: "Drag to reorder",
1338
+ ...dndProps("row", row.id),
1339
+ children: [
1340
+ /* @__PURE__ */ jsx3("span", { children: ri + 1 }),
1341
+ !readOnly && /* @__PURE__ */ jsx3("button", { className: "shg-rowdel", onClick: () => deleteRow(row.id), title: "Delete row", children: "\xD7" }),
1342
+ !readOnly && /* @__PURE__ */ jsx3("span", { className: "shg-resize-row", onMouseDown: (e) => startResize(e, "row", row.id, rowHeight(row) || e.currentTarget.closest("tr").offsetHeight) })
1343
+ ]
1344
+ }
1345
+ ),
1346
+ columns.map((col, ci) => {
1347
+ const key = cellKey(row.id, col.id);
1348
+ const c = cells[key] || {};
1349
+ const isEditing = editing && editing.rowId === row.id && editing.colId === col.id;
1350
+ const peer = peerLayer.focus[key];
1351
+ const ghost = !isEditing && peerLayer.typing[key];
1352
+ const selected = inSel(ri, ci), focused = isFocus(ri, ci);
1353
+ const shadows = [];
1354
+ if (focused) shadows.push("inset 0 0 0 2px var(--brand, #0E7490)");
1355
+ if (peer) shadows.push(`inset 0 0 0 2px ${peer.color}`);
1356
+ const tint = !selected && peerLayer.tint[key];
1357
+ return /* @__PURE__ */ jsxs2(
1358
+ "td",
1359
+ {
1360
+ "data-cell": key,
1361
+ className: "shg-cell" + (col.type === "compute" ? " shg-cell-compute" : "") + (c.status && col.type === "compute" ? ` shg-cell-${c.status}` : "") + (selected ? " shg-sel" : "") + (focused ? " shg-focus" : "") + (peer ? " shg-cell-peer" : ""),
1362
+ style: {
1363
+ ...shadows.length ? { boxShadow: shadows.join(", ") } : null,
1364
+ ...tint ? { background: withAlpha(tint, 0.1) } : null
1365
+ },
1366
+ onMouseDown: (e) => {
1367
+ if (e.button !== 0 || isEditing) return;
1368
+ if (editing) commitEdit();
1369
+ const p = { r: ri, c: ci };
1370
+ setSel((cur) => e.shiftKey && cur ? { a: cur.a, f: p } : { a: p, f: p });
1371
+ dragSel.current = true;
1372
+ e.preventDefault();
1373
+ rootRef.current?.focus();
1374
+ },
1375
+ onMouseEnter: () => {
1376
+ if (dragSel.current) setSel((cur) => cur ? { a: cur.a, f: { r: ri, c: ci } } : cur);
1377
+ },
1378
+ onClick: (e) => {
1379
+ if (col.type === "checkbox" && !isEditing) openEdit(row.id, col, e.currentTarget);
1380
+ },
1381
+ onDoubleClick: (e) => {
1382
+ if (!isEditing) openEdit(row.id, col, e.currentTarget);
1383
+ },
1384
+ title: c.error || "",
1385
+ children: [
1386
+ peer && /* @__PURE__ */ jsx3("span", { className: "shg-peer-flag", style: { background: peer.color }, children: peer.name }),
1387
+ isEditing ? renderEditor(col) : /* @__PURE__ */ jsxs2(
1388
+ "div",
1389
+ {
1390
+ className: "shg-val",
1391
+ style: { maxWidth: colWidth(col) ? colWidth(col) - 20 : 400 },
1392
+ children: [
1393
+ col.type === "compute" && /* @__PURE__ */ jsx3(StatusDot, { status: c.status }),
1394
+ ghost ? /* @__PURE__ */ jsx3("span", { className: "shg-ghost", style: { color: ghost.color }, title: `${ghost.name} is typing`, children: ghost.text }) : /* @__PURE__ */ jsx3(CellValue, { cell: c, col, fetchBlobUrl, onOpenResource }),
1395
+ col.type === "compute" && !readOnly && onRunCell && /* @__PURE__ */ jsx3(
1396
+ "button",
1397
+ {
1398
+ className: "shg-runcell",
1399
+ title: "Run this cell",
1400
+ onClick: (e) => {
1401
+ e.stopPropagation();
1402
+ onRunCell(row.id, col.id);
1403
+ },
1404
+ children: "\u25B6"
1405
+ }
1406
+ )
1407
+ ]
1408
+ }
1409
+ )
1410
+ ]
1411
+ },
1412
+ col.id
1413
+ );
1414
+ }),
1415
+ !readOnly && /* @__PURE__ */ jsx3("td", { className: "shg-pad" })
1416
+ ]
1417
+ },
1418
+ row.id
1419
+ )),
1420
+ !readOnly && /* @__PURE__ */ jsxs2("tr", { className: "shg-ghost-row", onClick: addRow, children: [
1421
+ /* @__PURE__ */ jsx3("td", { className: "shg-rownum shg-ghost-num", style: numStyle, children: "+" }),
1422
+ /* @__PURE__ */ jsx3("td", { className: "shg-ghost-cell", colSpan: columns.length + 1, children: "New row" })
1423
+ ] })
1424
+ ] })
1425
+ ] }) }) });
1426
+ }
1427
+ function ColumnHeader({ col, columns, readOnly, menuOpen, menuAnchor, onMenu, onCloseMenu, onRename, onConfigure, onDelete, onRun, width }) {
1428
+ const [editing, setEditing] = useState3(false);
1429
+ const [name, setName] = useState3(col.name);
1430
+ useEffect3(() => setName(col.name), [col.name]);
1431
+ const w = Number(width) || 0;
1432
+ const fit = w && w < 160 ? " tight" : w && w < 200 ? " narrow" : "";
1433
+ return /* @__PURE__ */ jsxs2("div", { className: "shg-colhdr" + fit, children: [
1434
+ /* @__PURE__ */ jsxs2("div", { className: "shg-colhdr-main", children: [
1435
+ editing && !readOnly ? /* @__PURE__ */ jsx3(
1436
+ "input",
1437
+ {
1438
+ className: "shg-colname-input",
1439
+ value: name,
1440
+ autoFocus: true,
1441
+ onChange: (e) => setName(e.target.value),
1442
+ onBlur: () => {
1443
+ setEditing(false);
1444
+ if (name.trim() && name !== col.name) onRename(col.id, name.trim());
1445
+ },
1446
+ onKeyDown: (e) => {
1447
+ if (e.key === "Enter") e.target.blur();
1448
+ }
1449
+ }
1450
+ ) : /* @__PURE__ */ jsx3("span", { className: "shg-colname", onDoubleClick: () => !readOnly && setEditing(true), title: col.name, children: col.name }),
1451
+ /* @__PURE__ */ jsxs2("span", { className: "shg-coltype" + (col.type === "compute" ? " compute" : ""), children: [
1452
+ TYPE_LABEL[col.type] || col.type,
1453
+ col.type === "compute" && col.compute?.kind ? ` \xB7 ${col.compute.kind}` : ""
1454
+ ] })
1455
+ ] }),
1456
+ !readOnly && /* @__PURE__ */ jsxs2("div", { className: "shg-colhdr-tools", children: [
1457
+ onRun && /* @__PURE__ */ jsxs2("button", { className: "shg-colrun", onClick: onRun, title: "Run this column", "aria-label": "Run this column", children: [
1458
+ "\u25B6",
1459
+ /* @__PURE__ */ jsx3("span", { className: "shg-colrun-label", children: " Run" })
1460
+ ] }),
1461
+ /* @__PURE__ */ jsx3("button", { className: "shg-colmenu-btn", onClick: (e) => onMenu(e), title: "Column settings", children: "\u22EF" })
1462
+ ] }),
1463
+ menuOpen && !readOnly && /* @__PURE__ */ jsx3(
1464
+ ColumnMenu,
1465
+ {
1466
+ col,
1467
+ columns,
1468
+ anchor: menuAnchor,
1469
+ onApply: (patch) => {
1470
+ onConfigure(col.id, patch);
1471
+ onCloseMenu();
1472
+ },
1473
+ onDelete,
1474
+ onClose: onCloseMenu
1475
+ }
1476
+ )
1477
+ ] });
1478
+ }
1479
+ function ValuePills({ values, onChange }) {
1480
+ const [text, setText] = useState3("");
1481
+ const [picking, setPicking] = useState3(null);
1482
+ const add = () => {
1483
+ const label = text.trim();
1484
+ if (!label) return;
1485
+ if (!values.some((v) => sameValue(v.label, label))) onChange([...values, { label }]);
1486
+ setText("");
1487
+ };
1488
+ const remove = (i) => {
1489
+ onChange(values.filter((_, j) => j !== i));
1490
+ setPicking(null);
1491
+ };
1492
+ const paint = (i, color) => {
1493
+ onChange(values.map((v, j) => j === i ? { ...v, color } : v));
1494
+ setPicking(null);
1495
+ };
1496
+ return /* @__PURE__ */ jsxs2("div", { className: "shg-values", onClick: (e) => {
1497
+ if (e.target === e.currentTarget) e.currentTarget.querySelector("input")?.focus();
1498
+ }, children: [
1499
+ values.map((v, i) => /* @__PURE__ */ jsxs2("span", { className: "shg-value", children: [
1500
+ /* @__PURE__ */ jsxs2(
1501
+ "button",
1502
+ {
1503
+ type: "button",
1504
+ className: "shg-pill shg-pill-btn",
1505
+ style: { background: v.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] },
1506
+ title: "Pick a color",
1507
+ "aria-expanded": picking === i,
1508
+ onClick: (e) => {
1509
+ e.stopPropagation();
1510
+ setPicking(picking === i ? null : i);
1511
+ },
1512
+ children: [
1513
+ v.label,
1514
+ /* @__PURE__ */ jsx3(
1515
+ "span",
1516
+ {
1517
+ className: "shg-value-x",
1518
+ role: "button",
1519
+ "aria-label": `Remove ${v.label}`,
1520
+ onClick: (e) => {
1521
+ e.stopPropagation();
1522
+ remove(i);
1523
+ },
1524
+ children: "\xD7"
1525
+ }
1526
+ )
1527
+ ]
1528
+ }
1529
+ ),
1530
+ picking === i && /* @__PURE__ */ jsx3("span", { className: "shg-swatches", role: "listbox", "aria-label": `Color for ${v.label}`, children: PILL_PALETTE.map((p) => /* @__PURE__ */ jsx3(
1531
+ "button",
1532
+ {
1533
+ type: "button",
1534
+ role: "option",
1535
+ "aria-selected": v.color === p.color,
1536
+ className: "shg-swatch" + (v.color === p.color ? " on" : ""),
1537
+ style: { background: p.color },
1538
+ title: p.name,
1539
+ onClick: (e) => {
1540
+ e.stopPropagation();
1541
+ paint(i, p.color);
1542
+ }
1543
+ },
1544
+ p.name
1545
+ )) })
1546
+ ] }, v.label)),
1547
+ /* @__PURE__ */ jsx3(
1548
+ "input",
1549
+ {
1550
+ className: "shg-values-input",
1551
+ value: text,
1552
+ placeholder: values.length ? "" : "Type a value, press Enter",
1553
+ onChange: (e) => setText(e.target.value),
1554
+ onKeyDown: (e) => {
1555
+ if (e.key === "Enter" || e.key === ",") {
1556
+ e.preventDefault();
1557
+ add();
1558
+ } else if (e.key === "Backspace" && !text && values.length) remove(values.length - 1);
1559
+ },
1560
+ onBlur: add
1561
+ }
1562
+ )
1563
+ ] });
1564
+ }
1565
+ function ColumnMenu({ col, columns, anchor, onApply, onDelete, onClose }) {
1566
+ const [type, setType] = useState3(col.type || "text");
1567
+ const [values, setValues] = useState3(() => (col.options || []).map((o) => typeof o === "string" ? { label: o } : { label: o.label ?? String(o.value ?? ""), ...o.color ? { color: o.color } : {} }));
1568
+ const comp = col.compute || {};
1569
+ const [kind, setKind] = useState3(comp.kind || "prompt");
1570
+ const [prompt, setPrompt] = useState3(comp.prompt || "");
1571
+ const [harnessId, setHarnessId] = useState3(comp.harness_id || "");
1572
+ const [wfSlug, setWfSlug] = useState3(comp.workflow_slug || "");
1573
+ const [outKey, setOutKey] = useState3(comp.output_key || "");
1574
+ const [deps, setDeps] = useState3(new Set(comp.deps || []));
1575
+ const ref = useRef3(null);
1576
+ useEffect3(() => {
1577
+ const onDown = (e) => {
1578
+ if (ref.current && !ref.current.contains(e.target) && !(e.target.closest && e.target.closest(".uic-pop"))) onClose();
1579
+ };
1580
+ window.addEventListener("mousedown", onDown);
1581
+ return () => window.removeEventListener("mousedown", onDown);
1582
+ }, [onClose]);
1583
+ const promptItems = useMemo2(() => {
1584
+ const at = columns.findIndex((c) => c.id === col.id);
1585
+ return columns.filter((c) => c.id !== col.id).map((c) => {
1586
+ const idx = columns.findIndex((x) => x.id === c.id);
1587
+ const right = at >= 0 && idx > at;
1588
+ return {
1589
+ id: c.id,
1590
+ name: c.name,
1591
+ kind: c.type,
1592
+ section: right ? "Fills after this column" : "Columns",
1593
+ icon: TYPE_GLYPH[c.type] || "Aa",
1594
+ description: TYPE_LABEL[c.type] || c.type,
1595
+ color: c.type === "compute" ? "#7C3AED" : void 0,
1596
+ disabled: right ? "to the right" : false
1597
+ };
1598
+ });
1599
+ }, [columns, col.id]);
1600
+ const apply = () => {
1601
+ const patch = { type };
1602
+ patch.options = values.map((v) => v.color ? { label: v.label, color: v.color } : v.label);
1603
+ if (type === "compute") {
1604
+ const compute = { kind, deps: [...deps] };
1605
+ if (kind === "prompt") compute.prompt = prompt;
1606
+ if (kind === "harness") {
1607
+ compute.harness_id = harnessId;
1608
+ compute.prompt = prompt;
1609
+ }
1610
+ if (kind === "workflow") {
1611
+ compute.workflow_slug = wfSlug;
1612
+ compute.output_key = outKey;
1613
+ }
1614
+ patch.compute = compute;
1615
+ }
1616
+ onApply(patch);
1617
+ };
1618
+ return /* @__PURE__ */ jsx3(PopPortal, { anchor, width: 250, estHeight: 340, className: "shg-menu", onClose, children: /* @__PURE__ */ jsxs2("div", { ref, onClick: (e) => e.stopPropagation(), children: [
1619
+ /* @__PURE__ */ jsxs2("label", { className: "shg-menu-lbl", children: [
1620
+ "Type",
1621
+ /* @__PURE__ */ jsxs2("select", { className: "shg-menu-input", value: type, onChange: (e) => setType(e.target.value), children: [
1622
+ MANUAL_TYPES.map((t) => /* @__PURE__ */ jsx3("option", { value: t, children: TYPE_LABEL[t] }, t)),
1623
+ /* @__PURE__ */ jsx3("option", { value: "compute", children: "Computed" })
1624
+ ] })
1625
+ ] }),
1626
+ /* @__PURE__ */ jsxs2("div", { className: "shg-menu-lbl", children: [
1627
+ type === "select" || type === "tags" ? "Options" : "Values",
1628
+ /* @__PURE__ */ jsx3(ValuePills, { values, onChange: setValues })
1629
+ ] }),
1630
+ type === "compute" && /* @__PURE__ */ jsxs2(Fragment, { children: [
1631
+ /* @__PURE__ */ jsxs2("label", { className: "shg-menu-lbl", children: [
1632
+ "Runs",
1633
+ /* @__PURE__ */ jsx3("select", { className: "shg-menu-input", value: kind, onChange: (e) => setKind(e.target.value), children: COMPUTE_KINDS.map((k) => /* @__PURE__ */ jsx3("option", { value: k.kind, children: k.label }, k.kind)) })
1634
+ ] }),
1635
+ (kind === "prompt" || kind === "harness") && /* @__PURE__ */ jsxs2("div", { className: "shg-menu-lbl", children: [
1636
+ "Prompt",
1637
+ /* @__PURE__ */ jsx3("div", { className: "shg-menu-input shg-menu-prompt", children: /* @__PURE__ */ jsx3(
1638
+ MentionInput,
1639
+ {
1640
+ value: prompt,
1641
+ onChange: (v, ms) => {
1642
+ setPrompt(v);
1643
+ setDeps(new Set(ms.map((m) => m.id)));
1644
+ },
1645
+ items: promptItems,
1646
+ placeholder: "Summarize @Company in one line",
1647
+ menuTitle: "Columns this cell can read",
1648
+ emptyText: "No column by that name",
1649
+ label: "Prompt"
1650
+ }
1651
+ ) }),
1652
+ /* @__PURE__ */ jsx3("div", { className: "shg-menu-hint", children: "Type @ to add a column from this row. Columns to the left fill first." })
1653
+ ] }),
1654
+ kind === "harness" && /* @__PURE__ */ jsxs2("label", { className: "shg-menu-lbl", children: [
1655
+ "Agent id",
1656
+ /* @__PURE__ */ jsx3("input", { className: "shg-menu-input", value: harnessId, onChange: (e) => setHarnessId(e.target.value), placeholder: "chrn_\u2026" })
1657
+ ] }),
1658
+ kind === "workflow" && /* @__PURE__ */ jsxs2(Fragment, { children: [
1659
+ /* @__PURE__ */ jsxs2("label", { className: "shg-menu-lbl", children: [
1660
+ "Workflow id",
1661
+ /* @__PURE__ */ jsx3("input", { className: "shg-menu-input", value: wfSlug, onChange: (e) => setWfSlug(e.target.value), placeholder: "my-workflow" })
1662
+ ] }),
1663
+ /* @__PURE__ */ jsxs2("label", { className: "shg-menu-lbl", children: [
1664
+ "Output key (optional)",
1665
+ /* @__PURE__ */ jsx3("input", { className: "shg-menu-input", value: outKey, onChange: (e) => setOutKey(e.target.value), placeholder: "summary" })
1666
+ ] })
1667
+ ] })
1668
+ ] }),
1669
+ /* @__PURE__ */ jsxs2("div", { className: "shg-menu-actions", children: [
1670
+ /* @__PURE__ */ jsx3("button", { className: "shg-menu-del", onClick: onDelete, children: "Delete column" }),
1671
+ /* @__PURE__ */ jsx3("button", { className: "shg-menu-apply", onClick: apply, children: "Apply" })
1672
+ ] })
1673
+ ] }) });
1674
+ }
1675
+ function sheetToDelimited(sheet, sep = ",") {
1676
+ const cols = sheet?.columns || [];
1677
+ const rows = sheet?.rows || [];
1678
+ const cells = sheet?.cells || {};
1679
+ const esc = (v) => {
1680
+ const s = v == null ? "" : Array.isArray(v) ? v.join(", ") : typeof v === "object" ? JSON.stringify(v) : String(v);
1681
+ if (sep === "," && /[",\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
1682
+ return s;
1683
+ };
1684
+ const header = cols.map((c) => esc(c.name)).join(sep);
1685
+ const body = rows.map((r) => cols.map((c) => {
1686
+ const cell = cells[cellKey(r.id, c.id)];
1687
+ return esc(cell ? cell.value : "");
1688
+ }).join(sep));
1689
+ return [header, ...body].join("\n");
1690
+ }
1691
+ function sheetToAoA(sheet) {
1692
+ const cols = sheet?.columns || [];
1693
+ const rows = sheet?.rows || [];
1694
+ const cells = sheet?.cells || {};
1695
+ const val = (v) => v == null ? "" : Array.isArray(v) ? v.join(", ") : typeof v === "object" ? JSON.stringify(v) : v;
1696
+ return [
1697
+ cols.map((c) => c.name),
1698
+ ...rows.map((r) => cols.map((c) => val(cells[cellKey(r.id, c.id)]?.value)))
1699
+ ];
1700
+ }
1701
+
1702
+ export {
1703
+ Popover,
1704
+ MentionInput,
1705
+ MentionText,
1706
+ SheetGrid,
1707
+ sheetToDelimited,
1708
+ sheetToAoA
1709
+ };
1710
+ //# sourceMappingURL=chunk-EL2DHWOH.js.map