reifyui 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +31 -2
  2. package/dist/chart.js +2 -0
  3. package/dist/chart.js.map +1 -1
  4. package/dist/chunk-EL2DHWOH.js +1710 -0
  5. package/dist/chunk-EL2DHWOH.js.map +1 -0
  6. package/dist/chunk-J633KV57.js +41 -0
  7. package/dist/chunk-J633KV57.js.map +1 -0
  8. package/dist/chunk-J7SECRIG.js +295 -0
  9. package/dist/chunk-J7SECRIG.js.map +1 -0
  10. package/dist/chunk-PIRPLH2Z.js +231 -0
  11. package/dist/chunk-PIRPLH2Z.js.map +1 -0
  12. package/dist/chunk-PZ5AY32C.js +10 -0
  13. package/dist/chunk-PZ5AY32C.js.map +1 -0
  14. package/dist/chunk-UKG4Z6QK.js +130 -0
  15. package/dist/chunk-UKG4Z6QK.js.map +1 -0
  16. package/dist/chunk-ZYWE47EO.js +19 -0
  17. package/dist/chunk-ZYWE47EO.js.map +1 -0
  18. package/dist/collab.cjs +169 -0
  19. package/dist/collab.cjs.map +1 -0
  20. package/dist/collab.d.ts +30 -0
  21. package/dist/collab.js +18 -0
  22. package/dist/collab.js.map +1 -0
  23. package/dist/graph.cjs +2244 -0
  24. package/dist/graph.cjs.map +1 -0
  25. package/dist/graph.d.ts +41 -0
  26. package/dist/graph.js +1870 -0
  27. package/dist/graph.js.map +1 -0
  28. package/dist/harness.js +1 -0
  29. package/dist/harness.js.map +1 -1
  30. package/dist/index.cjs +2044 -867
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.ts +20 -2
  33. package/dist/index.js +892 -1686
  34. package/dist/index.js.map +1 -1
  35. package/dist/sheet-doc.cjs +235 -0
  36. package/dist/sheet-doc.cjs.map +1 -0
  37. package/dist/sheet-doc.d.ts +16 -0
  38. package/dist/sheet-doc.js +20 -0
  39. package/dist/sheet-doc.js.map +1 -0
  40. package/dist/sheet.cjs +2322 -0
  41. package/dist/sheet.cjs.map +1 -0
  42. package/dist/sheet.d.ts +23 -0
  43. package/dist/sheet.js +237 -0
  44. package/dist/sheet.js.map +1 -0
  45. package/dist/slides.js +2 -0
  46. package/dist/slides.js.map +1 -1
  47. package/package.json +35 -3
  48. package/src/auth/client.js +4 -2
  49. package/src/collab/colors.js +18 -0
  50. package/src/collab/index.d.ts +30 -0
  51. package/src/collab/index.js +8 -0
  52. package/src/collab/keepAlive.js +34 -0
  53. package/src/collab/useLiveDoc.js +76 -0
  54. package/src/components/CascadeMenu.jsx +216 -0
  55. package/src/components/ChatMessages.jsx +30 -9
  56. package/src/components/Chip.jsx +37 -10
  57. package/src/components/Composer.jsx +80 -2
  58. package/src/components/resizable.jsx +82 -12
  59. package/src/graph/ConnectPane.jsx +634 -0
  60. package/src/graph/ConnectToolDetail.jsx +565 -0
  61. package/src/graph/LogsPane.jsx +328 -0
  62. package/src/graph/Skeleton.jsx +13 -0
  63. package/src/graph/draft.js +108 -0
  64. package/src/graph/format.js +37 -0
  65. package/src/graph/index.d.ts +41 -0
  66. package/src/graph/index.js +14 -0
  67. package/src/graph/useGraphCollab.js +299 -0
  68. package/src/graph/vgraph.js +215 -0
  69. package/src/index.d.ts +20 -2
  70. package/src/index.js +6 -1
  71. package/src/mention/MentionInput.jsx +420 -0
  72. package/src/mention/mentionModel.js +177 -0
  73. package/src/sheet/RunStrip.jsx +57 -0
  74. package/src/sheet/SheetGrid.jsx +444 -353
  75. package/src/sheet/doc.d.ts +16 -0
  76. package/src/sheet/index.d.ts +23 -0
  77. package/src/sheet/index.js +10 -0
  78. package/src/sheet/sheetDoc.js +203 -0
  79. package/src/sheet/useSheetCollab.js +102 -0
  80. package/src/sheet/useSheetRun.js +80 -0
  81. package/styles/chat.css +47 -5
  82. package/styles/chip.css +36 -0
  83. package/styles/graph.css +395 -0
  84. package/styles/mention.css +79 -0
  85. package/styles/sheet.css +156 -112
@@ -0,0 +1,420 @@
1
+ // MentionInput — a text field that can hold people, columns, files: anything a host offers.
2
+ //
3
+ // Type the trigger ("@" by default) and a menu opens at the caret with the host's items, searched
4
+ // as you type (name, description, keywords). Pick one and it becomes a pill in the text: one
5
+ // unit to the caret and to Backspace, with its icon and name, tinted by kind. Underneath, the
6
+ // value is a plain string in the host's token format ({{Name}} for a sheet prompt, @Name for a
7
+ // chat message) and a `mentions` list rides beside it, so a host never parses text to learn who
8
+ // was mentioned. Loading a value turns the tokens it can resolve back into pills.
9
+ //
10
+ // items [{ id, name, kind?, section?, description?, keywords?, icon?, avatar?, color?,
11
+ // disabled? (true | 'reason'), tag? }] the menu, in the host's order
12
+ // format { open, close } token spelling; CURLY ({{Name}}) by default, AT for @Name
13
+ // trigger the character that opens the menu ('@')
14
+ // onChange(value, mentions)
15
+ // onSubmit() when given with submitOnEnter, Enter submits and Shift+Enter breaks the line
16
+ // ref { focus(), insertMention(item), clear(), el }
17
+ //
18
+ // The editor is a contentEditable whose DOM is read back into the model on every input; the
19
+ // menu is a Popover anchored to the caret. No dependency beyond react and react-dom.
20
+ import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
21
+ import { Popover } from '../components/Popover.jsx';
22
+ import { CURLY, makeResolver, parseValue, serializeSegments, mentionsOf, groupItems, activeTrigger } from './mentionModel.js';
23
+
24
+ const MENTION_ATTR = 'data-mention-id';
25
+
26
+ function monogram(name) {
27
+ const parts = String(name || '').trim().split(/\s+/).filter(Boolean);
28
+ return ((parts[0] || '')[0] || '') + ((parts[1] || '')[0] || '') || '?';
29
+ }
30
+
31
+ // The pill, as a DOM node (the editor is not React-managed inside).
32
+ export function buildPillNode(item) {
33
+ const el = document.createElement('span');
34
+ el.className = 'uic-mention';
35
+ el.setAttribute(MENTION_ATTR, item.id);
36
+ el.setAttribute('data-name', item.name);
37
+ if (item.kind) el.setAttribute('data-kind', item.kind);
38
+ el.setAttribute('contenteditable', 'false');
39
+ if (item.description) el.title = item.description;
40
+ if (item.color) el.style.setProperty('--uic-mention-color', item.color);
41
+ const ic = document.createElement('span');
42
+ ic.className = 'uic-mention-ic';
43
+ if (item.avatar) { const img = document.createElement('img'); img.src = item.avatar; img.alt = ''; ic.appendChild(img); }
44
+ else { ic.textContent = typeof item.icon === 'string' && item.icon ? item.icon : monogram(item.name); if (!(typeof item.icon === 'string' && item.icon)) ic.classList.add('is-mono'); }
45
+ const nm = document.createElement('span');
46
+ nm.className = 'uic-mention-name';
47
+ nm.textContent = item.name;
48
+ el.appendChild(ic);
49
+ el.appendChild(nm);
50
+ return el;
51
+ }
52
+
53
+ // DOM -> segments. Text nodes are text, <br> and block boundaries are line breaks, a pill is a
54
+ // mention; the browser's own trailing <br> (it keeps one so the last empty line can be reached)
55
+ // is not a newline of the user's.
56
+ function readSegments(root, resolver) {
57
+ const out = [];
58
+ let buf = '';
59
+ const flush = () => { if (buf) { out.push({ type: 'text', text: buf }); buf = ''; } };
60
+ const walk = (node, isLastAtRoot) => {
61
+ const kids = Array.from(node.childNodes);
62
+ kids.forEach((k, i) => {
63
+ const last = isLastAtRoot && i === kids.length - 1;
64
+ // a contentEditable writes a trailing space as a no-break space; the value keeps plain ones
65
+ if (k.nodeType === 3) { buf += k.data.replace(/\u00a0/g, ' '); return; }
66
+ if (k.nodeType !== 1) return;
67
+ const tag = k.tagName;
68
+ if (tag === 'BR') { if (!last) buf += '\n'; return; }
69
+ if (k.hasAttribute(MENTION_ATTR)) {
70
+ flush();
71
+ const id = k.getAttribute(MENTION_ATTR);
72
+ const name = k.getAttribute('data-name') || '';
73
+ const item = resolver.get(name) || { id, name, kind: k.getAttribute('data-kind') || null };
74
+ out.push({ type: 'mention', id: item.id, name: item.name, kind: item.kind || null, item });
75
+ return;
76
+ }
77
+ if (tag === 'DIV' || tag === 'P') {
78
+ // a block after other content starts a new line
79
+ if (out.length || buf) buf += '\n';
80
+ walk(k, last);
81
+ return;
82
+ }
83
+ walk(k, last);
84
+ });
85
+ };
86
+ walk(root, true);
87
+ flush();
88
+ return out;
89
+ }
90
+
91
+ // segments -> DOM
92
+ function writeSegments(root, segments) {
93
+ root.textContent = '';
94
+ for (const s of segments) {
95
+ if (s.type === 'mention') { root.appendChild(buildPillNode(s.item || s)); continue; }
96
+ const lines = String(s.text).split('\n');
97
+ lines.forEach((line, i) => {
98
+ if (i > 0) root.appendChild(document.createElement('br'));
99
+ if (line) root.appendChild(document.createTextNode(line));
100
+ });
101
+ }
102
+ // the reachable last line
103
+ root.appendChild(document.createElement('br'));
104
+ }
105
+
106
+ function placeCaretAfter(node) {
107
+ const sel = window.getSelection();
108
+ if (!sel) return;
109
+ const r = document.createRange();
110
+ r.setStartAfter(node);
111
+ r.collapse(true);
112
+ sel.removeAllRanges();
113
+ sel.addRange(r);
114
+ }
115
+
116
+ function selectionIn(root) {
117
+ const sel = typeof window !== 'undefined' ? window.getSelection() : null;
118
+ if (!sel || !sel.rangeCount) return null;
119
+ const r = sel.getRangeAt(0);
120
+ if (!root.contains(r.startContainer)) return null;
121
+ return { sel, range: r };
122
+ }
123
+
124
+ export const MentionInput = forwardRef(function MentionInput(props, ref) {
125
+ const {
126
+ value = '', onChange, items = [], format = CURLY, trigger = '@', placeholder, disabled = false,
127
+ onSubmit, submitOnEnter = false, autoFocus = false, className = '', label, menuWidth = 360,
128
+ menuTitle, emptyText = 'No match', renderIcon, onOpenChange, onFocus, onBlur, onKeyDown, id,
129
+ } = props;
130
+ const editorRef = useRef(null);
131
+ const resolver = useMemo(() => makeResolver(items), [items]);
132
+ const [menu, setMenu] = useState(null); // { node, start, query, rect }
133
+ const [active, setActive] = useState(0);
134
+ const [empty, setEmpty] = useState(!value);
135
+ const listId = useMemo(() => `uic-mention-${Math.random().toString(36).slice(2, 8)}`, []);
136
+
137
+ // ── model <-> DOM ──
138
+ const emit = useCallback(() => {
139
+ const root = editorRef.current;
140
+ if (!root) return;
141
+ const segs = readSegments(root, resolver);
142
+ const next = serializeSegments(segs, format);
143
+ setEmpty(!next);
144
+ if (onChange) onChange(next, mentionsOf(segs));
145
+ }, [resolver, format, onChange]);
146
+
147
+ // A value that arrives from outside (a reset after send, a loaded prompt) is drawn; the one
148
+ // the editor just emitted is already on screen, so the caret is left alone.
149
+ useLayoutEffect(() => {
150
+ const root = editorRef.current;
151
+ if (!root) return;
152
+ const current = serializeSegments(readSegments(root, resolver), format);
153
+ if (current === (value || '')) return;
154
+ writeSegments(root, parseValue(value || '', format, resolver));
155
+ setEmpty(!value);
156
+ }, [value, resolver, format]);
157
+
158
+ useEffect(() => { if (autoFocus && editorRef.current) editorRef.current.focus(); }, [autoFocus]);
159
+
160
+ // ── the menu at the caret ──
161
+ const closeMenu = useCallback(() => setMenu(null), []);
162
+ useEffect(() => { if (onOpenChange) onOpenChange(!!menu); }, [menu, onOpenChange]);
163
+ const groups = useMemo(() => (menu ? groupItems(items, menu.query) : []), [items, menu]);
164
+ const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);
165
+ useEffect(() => { setActive(0); }, [menu && menu.query, groups.length]);
166
+
167
+ const syncMenu = useCallback(() => {
168
+ const root = editorRef.current;
169
+ const s = root && selectionIn(root);
170
+ if (!s || !s.range.collapsed) { setMenu(null); return; }
171
+ const node = s.range.startContainer;
172
+ if (node.nodeType !== 3) { setMenu(null); return; }
173
+ const hit = activeTrigger(node.data.slice(0, s.range.startOffset), trigger);
174
+ if (!hit) { setMenu(null); return; }
175
+ const r = document.createRange();
176
+ r.setStart(node, hit.start);
177
+ r.setEnd(node, Math.min(node.data.length, hit.start + 1));
178
+ const rect = r.getBoundingClientRect();
179
+ setMenu({ node, start: hit.start, query: hit.query, rect: rect.width || rect.height ? rect : root.getBoundingClientRect() });
180
+ }, [trigger]);
181
+
182
+ const anchorRef = useMemo(() => ({
183
+ current: {
184
+ getBoundingClientRect: () => (menu ? menu.rect : new DOMRect()),
185
+ contains: () => false,
186
+ },
187
+ }), [menu]);
188
+
189
+ const insertPill = useCallback((item, replace) => {
190
+ const root = editorRef.current;
191
+ if (!root || !item || item.disabled) return;
192
+ const pill = buildPillNode(item);
193
+ const space = document.createTextNode(' ');
194
+ if (replace && replace.node && replace.node.parentNode === root) {
195
+ const { node, start, query } = replace;
196
+ node.deleteData(start, trigger.length + query.length);
197
+ const after = node.splitText(start);
198
+ root.insertBefore(pill, after);
199
+ root.insertBefore(space, after);
200
+ } else {
201
+ const s = selectionIn(root);
202
+ if (s) { s.range.deleteContents(); s.range.insertNode(space); s.range.insertNode(pill); }
203
+ else { root.appendChild(pill); root.appendChild(space); }
204
+ }
205
+ placeCaretAfter(space);
206
+ setMenu(null);
207
+ emit();
208
+ }, [emit, trigger]);
209
+
210
+ const pick = useCallback((item) => insertPill(item, menu), [insertPill, menu]);
211
+
212
+ const insertText = useCallback((text) => {
213
+ const root = editorRef.current;
214
+ if (!root) return;
215
+ root.focus();
216
+ let done = false;
217
+ try { done = document.execCommand('insertText', false, text); } catch { done = false; }
218
+ if (!done) {
219
+ const s = selectionIn(root);
220
+ const tn = document.createTextNode(text);
221
+ if (s) { s.range.deleteContents(); s.range.insertNode(tn); placeCaretAfter(tn); }
222
+ else root.appendChild(tn);
223
+ }
224
+ emit();
225
+ syncMenu();
226
+ }, [emit, syncMenu]);
227
+
228
+ // Markdown helpers for a host's formatting row: wrap what is selected (or leave the caret
229
+ // between the marks), or start the current line with a prefix.
230
+ const wrapSelection = useCallback((before, after = '') => {
231
+ const root = editorRef.current;
232
+ if (!root) return;
233
+ root.focus();
234
+ const s = selectionIn(root);
235
+ const selected = s ? s.range.toString() : '';
236
+ insertText(before + selected + after);
237
+ if (!selected && after) {
238
+ const sel = window.getSelection();
239
+ for (let i = 0; i < after.length; i++) sel && sel.modify && sel.modify('move', 'backward', 'character');
240
+ }
241
+ }, [insertText]);
242
+ const prefixLine = useCallback((prefix) => {
243
+ const root = editorRef.current;
244
+ if (!root) return;
245
+ root.focus();
246
+ const s = selectionIn(root);
247
+ const node = s && s.range.startContainer;
248
+ const before = node && node.nodeType === 3 ? node.data.slice(0, s.range.startOffset) : '';
249
+ const atLineStart = !before || /\n$/.test(before) || (node && node.nodeType !== 3);
250
+ insertText((atLineStart ? '' : '\n') + prefix);
251
+ }, [insertText]);
252
+
253
+ useImperativeHandle(ref, () => ({
254
+ focus: () => editorRef.current && editorRef.current.focus(),
255
+ clear: () => { const root = editorRef.current; if (root) { writeSegments(root, []); emit(); } },
256
+ insertMention: (item) => insertPill(item, null),
257
+ insertText,
258
+ wrapSelection,
259
+ prefixLine,
260
+ get el() { return editorRef.current; },
261
+ }), [emit, insertPill, insertText, wrapSelection, prefixLine]);
262
+
263
+ // ── events ──
264
+ const handleInput = () => { emit(); syncMenu(); };
265
+ const handleKeyDown = (e) => {
266
+ if (onKeyDown) onKeyDown(e);
267
+ if (e.defaultPrevented) return;
268
+ if (menu) {
269
+ if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => (flat.length ? (a + 1) % flat.length : 0)); return; }
270
+ if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => (flat.length ? (a - 1 + flat.length) % flat.length : 0)); return; }
271
+ if ((e.key === 'Enter' || e.key === 'Tab') && flat.length) { e.preventDefault(); pick(flat[active]); return; }
272
+ if (e.key === 'Escape') { e.preventDefault(); setMenu(null); return; }
273
+ }
274
+ if (e.key === 'Enter') {
275
+ if (submitOnEnter && !e.shiftKey) { e.preventDefault(); if (onSubmit) onSubmit(); return; }
276
+ e.preventDefault();
277
+ insertText('\n');
278
+ }
279
+ };
280
+ const handlePaste = (e) => {
281
+ e.preventDefault();
282
+ const text = (e.clipboardData && e.clipboardData.getData('text/plain')) || '';
283
+ if (!text) return;
284
+ // pasted tokens the host knows become pills, the rest stays text
285
+ const segs = parseValue(text, format, resolver);
286
+ if (segs.every((s) => s.type === 'text')) { insertText(text); return; }
287
+ const root = editorRef.current;
288
+ const s = selectionIn(root);
289
+ if (!s) { insertText(text); return; }
290
+ s.range.deleteContents();
291
+ const frag = document.createDocumentFragment();
292
+ let lastNode = null;
293
+ for (const seg of segs) {
294
+ if (seg.type === 'mention') { lastNode = buildPillNode(seg.item || seg); frag.appendChild(lastNode); continue; }
295
+ seg.text.split('\n').forEach((line, i) => {
296
+ if (i > 0) { lastNode = document.createElement('br'); frag.appendChild(lastNode); }
297
+ if (line) { lastNode = document.createTextNode(line); frag.appendChild(lastNode); }
298
+ });
299
+ }
300
+ s.range.insertNode(frag);
301
+ if (lastNode) placeCaretAfter(lastNode);
302
+ emit();
303
+ syncMenu();
304
+ };
305
+ const handleBlur = (e) => { if (onBlur) onBlur(e); };
306
+ const handleFocus = (e) => { if (onFocus) onFocus(e); };
307
+
308
+ // the caret moving away from the trigger (a click, an arrow) closes the menu
309
+ useEffect(() => {
310
+ if (!menu) return undefined;
311
+ const onSel = () => syncMenu();
312
+ document.addEventListener('selectionchange', onSel);
313
+ return () => document.removeEventListener('selectionchange', onSel);
314
+ }, [menu, syncMenu]);
315
+
316
+ // the active option stays in view: the list scrolls, never the page (scrollIntoView can
317
+ // move the document under a host that watches it)
318
+ useEffect(() => {
319
+ if (!menu) return;
320
+ const el = document.getElementById(`${listId}-${active}`);
321
+ const list = el && el.closest('.uic-mention-menu');
322
+ if (!el || !list) return;
323
+ const top = el.offsetTop - list.offsetTop;
324
+ const bottom = top + el.offsetHeight;
325
+ if (top < list.scrollTop) list.scrollTop = top;
326
+ else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;
327
+ }, [active, menu, listId]);
328
+
329
+ const iconOf = (item) => {
330
+ if (renderIcon) { const n = renderIcon(item); if (n) return n; }
331
+ if (item.avatar) return <img src={item.avatar} alt="" />;
332
+ if (typeof item.icon === 'string' && item.icon) return item.icon;
333
+ if (item.icon) return item.icon;
334
+ return <span className="is-mono">{monogram(item.name)}</span>;
335
+ };
336
+
337
+ let index = -1;
338
+ return (
339
+ <div className={['uic-mention-field', disabled ? 'is-disabled' : '', className].filter(Boolean).join(' ')}>
340
+ <div
341
+ ref={editorRef}
342
+ id={id}
343
+ className={'uic-mention-editor' + (empty ? ' is-empty' : '')}
344
+ contentEditable={!disabled}
345
+ suppressContentEditableWarning
346
+ role="textbox"
347
+ aria-multiline="true"
348
+ aria-label={label}
349
+ aria-autocomplete="list"
350
+ aria-expanded={!!menu}
351
+ aria-controls={menu ? listId : undefined}
352
+ aria-activedescendant={menu && flat.length ? `${listId}-${active}` : undefined}
353
+ data-placeholder={placeholder || ''}
354
+ spellCheck="true"
355
+ onInput={handleInput}
356
+ onKeyDown={handleKeyDown}
357
+ onPaste={handlePaste}
358
+ onFocus={handleFocus}
359
+ onBlur={handleBlur}
360
+ />
361
+ <Popover open={!!menu} anchorRef={anchorRef} onClose={closeMenu} width={menuWidth} minHeight={120} className="uic-mention-pop" label={menuTitle || 'Mentions'}>
362
+ <div className="uic-mention-menu" role="listbox" id={listId} onMouseDown={(e) => e.preventDefault()}>
363
+ {menuTitle ? <div className="uic-mention-head">{menuTitle}</div> : null}
364
+ {groups.map((g) => (
365
+ <div className="uic-mention-group" key={g.section || '_'}>
366
+ {g.section ? <div className="uic-mention-sec">{g.section}</div> : null}
367
+ {g.items.map((item) => {
368
+ index += 1;
369
+ const i = index;
370
+ const dis = !!item.disabled;
371
+ const reason = typeof item.disabled === 'string' ? item.disabled : null;
372
+ return (
373
+ <button
374
+ key={item.id} type="button" id={`${listId}-${i}`} role="option" aria-selected={i === active} aria-disabled={dis || undefined}
375
+ className={'uic-mention-item' + (i === active ? ' is-active' : '') + (dis ? ' is-disabled' : '')}
376
+ style={item.color ? { '--uic-mention-color': item.color } : undefined}
377
+ onMouseEnter={() => setActive(i)}
378
+ onClick={() => { if (!dis) pick(item); }}
379
+ >
380
+ <span className="uic-mention-ic">{iconOf(item)}</span>
381
+ <span className="uic-mention-text">
382
+ <span className="uic-mention-name">{item.name}</span>
383
+ {item.description ? <span className="uic-mention-desc">{item.description}</span> : null}
384
+ </span>
385
+ {reason || item.tag ? <span className="uic-mention-tag">{reason || item.tag}</span> : null}
386
+ </button>
387
+ );
388
+ })}
389
+ </div>
390
+ ))}
391
+ {!flat.length ? <div className="uic-mention-empty">{emptyText}</div> : null}
392
+ </div>
393
+ </Popover>
394
+ </div>
395
+ );
396
+ });
397
+
398
+ // Read-only: a stored value drawn with its pills, for a message or a preview.
399
+ export function MentionText({ value, items = [], format = CURLY, className = '', renderIcon }) {
400
+ const resolver = useMemo(() => makeResolver(items), [items]);
401
+ const segs = useMemo(() => parseValue(value || '', format, resolver), [value, format, resolver]);
402
+ return (
403
+ <span className={['uic-mention-text-view', className].filter(Boolean).join(' ')}>
404
+ {segs.map((s, i) => {
405
+ if (s.type === 'text') return <React.Fragment key={i}>{s.text}</React.Fragment>;
406
+ const item = s.item || s;
407
+ const icon = renderIcon ? renderIcon(item) : null;
408
+ return (
409
+ <span key={i} className="uic-mention" data-kind={s.kind || undefined} title={item.description || undefined}
410
+ style={item.color ? { '--uic-mention-color': item.color } : undefined}>
411
+ <span className={'uic-mention-ic' + (icon || (typeof item.icon === 'string' && item.icon) || item.avatar ? '' : ' is-mono')}>
412
+ {icon || (item.avatar ? <img src={item.avatar} alt="" /> : (typeof item.icon === 'string' && item.icon ? item.icon : monogram(item.name)))}
413
+ </span>
414
+ <span className="uic-mention-name">{s.name}</span>
415
+ </span>
416
+ );
417
+ })}
418
+ </span>
419
+ );
420
+ }
@@ -0,0 +1,177 @@
1
+ // The mention model: what a mention input holds, how it is written down, and how a menu is
2
+ // searched. Pure functions, no DOM, no React, so the same code serves the editor, the
3
+ // read-only renderer of a stored message, and a test.
4
+ //
5
+ // A value is a plain string with tokens in it. The token format belongs to the host:
6
+ // { open: '{{', close: '}}' } a sheet prompt: "Grade {{Answer}} against {{Gold}}"
7
+ // { open: '@', close: '' } a chat message: "@Project Manager can you take CT-281"
8
+ // A token names the item (its `name`), so the string stays readable wherever it travels, and
9
+ // the editor keeps a `mentions` list beside it ({id, name, kind}) so a host never parses text
10
+ // to learn who was mentioned.
11
+
12
+ export const CURLY = Object.freeze({ open: '{{', close: '}}' });
13
+ export const AT = Object.freeze({ open: '@', close: '' });
14
+ // A chat message carries the id too, as a markdown link a sanitizer lets through:
15
+ // [@Project Manager](#m-member.bot.project_manager)
16
+ export const CHAT_LINK = Object.freeze({
17
+ write: (item) => `[@${item.name}](#m-${item.id})`,
18
+ pattern: /\[@(?<name>[^\]\n]+)\]\(#m-(?<id>[^)\s]+)\)/g,
19
+ });
20
+
21
+ /** A resolver answers `name -> item | null`. Built from the items a host offers, longest names
22
+ * first, so "@Project Manager" is not read as "@Project" + " Manager". */
23
+ export function makeResolver(items) {
24
+ const byName = new Map();
25
+ const byId = new Map();
26
+ for (const it of items || []) {
27
+ if (!it) continue;
28
+ if (it.name) byName.set(it.name, it);
29
+ if (it.id != null) byId.set(String(it.id), it);
30
+ }
31
+ const names = [...byName.keys()].sort((a, b) => b.length - a.length);
32
+ return { get: (name) => byName.get(name) || null, byId: (id) => byId.get(String(id)) || null, names };
33
+ }
34
+
35
+ // A token spelled with its id parses even when the item is not offered any more (a member who
36
+ // left, a column since renamed): the name in the token is what is shown.
37
+ function parsePattern(text, format, resolver) {
38
+ const out = [];
39
+ const re = new RegExp(format.pattern.source, format.pattern.flags.includes('g') ? format.pattern.flags : format.pattern.flags + 'g');
40
+ let last = 0;
41
+ let m;
42
+ while ((m = re.exec(text))) {
43
+ if (m.index > last) out.push({ type: 'text', text: text.slice(last, m.index) });
44
+ const id = m.groups && m.groups.id != null ? m.groups.id : null;
45
+ const name = (m.groups && m.groups.name) || '';
46
+ const item = (id != null && resolver && resolver.byId(id)) || (resolver && resolver.get(name)) || { id: id ?? name, name, kind: null };
47
+ out.push({ type: 'mention', id: item.id, name: item.name || name, kind: item.kind || null, item });
48
+ last = m.index + m[0].length;
49
+ }
50
+ if (last < text.length) out.push({ type: 'text', text: text.slice(last) });
51
+ return out;
52
+ }
53
+
54
+ /** value -> segments: [{ type: 'text', text }] and [{ type: 'mention', id, name, kind, item }].
55
+ * Only names the resolver knows become mentions; anything else stays text, verbatim. */
56
+ export function parseValue(value, format, resolver) {
57
+ const text = value == null ? '' : String(value);
58
+ if (format && format.pattern) return parsePattern(text, format, resolver);
59
+ const { open, close } = format || CURLY;
60
+ const out = [];
61
+ let buf = '';
62
+ let i = 0;
63
+ const flush = () => { if (buf) { out.push({ type: 'text', text: buf }); buf = ''; } };
64
+ while (i < text.length) {
65
+ if (resolver && text.startsWith(open, i)) {
66
+ // At a word boundary for the bare "@" form: "email@host" is not a mention.
67
+ const boundary = close ? true : (i === 0 || /[\s([{"'>]/.test(text[i - 1]));
68
+ let hit = null;
69
+ if (boundary) {
70
+ for (const name of resolver.names) {
71
+ const start = i + open.length;
72
+ if (text.startsWith(name, start)) {
73
+ const end = start + name.length;
74
+ if (!close || text.startsWith(close, end)) {
75
+ // the bare form must end at a word boundary too
76
+ if (close || end === text.length || /[\s.,;:!?)\]}"']/.test(text[end])) { hit = { name, end: end + close.length }; break; }
77
+ }
78
+ }
79
+ }
80
+ }
81
+ if (hit) {
82
+ flush();
83
+ const item = resolver.get(hit.name);
84
+ out.push({ type: 'mention', id: item.id, name: item.name, kind: item.kind || null, item });
85
+ i = hit.end;
86
+ continue;
87
+ }
88
+ }
89
+ buf += text[i];
90
+ i += 1;
91
+ }
92
+ flush();
93
+ return out;
94
+ }
95
+
96
+ /** segments -> value string in the host's format. */
97
+ export function serializeSegments(segments, format) {
98
+ const f = format || CURLY;
99
+ if (f.write) return (segments || []).map((s) => (s.type === 'mention' ? f.write(s.item || s) : s.text)).join('');
100
+ const { open, close } = f;
101
+ return (segments || []).map((s) => (s.type === 'mention' ? `${open}${s.name}${close}` : s.text)).join('');
102
+ }
103
+
104
+ /** The distinct mentions in a segment list, in order of first appearance. */
105
+ export function mentionsOf(segments) {
106
+ const seen = new Set();
107
+ const out = [];
108
+ for (const s of segments || []) {
109
+ if (s.type !== 'mention' || seen.has(s.id)) continue;
110
+ seen.add(s.id);
111
+ out.push({ id: s.id, name: s.name, kind: s.kind || null });
112
+ }
113
+ return out;
114
+ }
115
+
116
+ // ── search ──────────────────────────────────────────────────────────────────
117
+ // Free text over name, description and keywords. A name that starts with the query ranks
118
+ // first, then a word of the name, then anything containing it, then a subsequence (typing
119
+ // "pm" finds "Project Manager"); a description or keyword match trails the name matches.
120
+ function norm(s) { return String(s || '').toLowerCase(); }
121
+
122
+ function subsequence(hay, needle) {
123
+ let j = 0;
124
+ for (let i = 0; i < hay.length && j < needle.length; i++) if (hay[i] === needle[j]) j++;
125
+ return j === needle.length;
126
+ }
127
+
128
+ export function scoreItem(item, query) {
129
+ const q = norm(query).trim();
130
+ if (!q) return 1;
131
+ const name = norm(item.name);
132
+ if (name === q) return 120;
133
+ if (name.startsWith(q)) return 100;
134
+ if (name.split(/[\s_-]+/).some((w) => w.startsWith(q))) return 80;
135
+ if (name.includes(q)) return 60;
136
+ const initials = name.split(/[\s_-]+/).map((w) => w[0]).join('');
137
+ if (initials.startsWith(q)) return 50;
138
+ if (subsequence(name, q)) return 30;
139
+ const desc = norm(item.description);
140
+ if (desc && desc.includes(q)) return 20;
141
+ const kws = (item.keywords || []).map(norm);
142
+ if (kws.some((k) => k.includes(q))) return 15;
143
+ return 0;
144
+ }
145
+
146
+ /** Items that match, best first, stable within a score (host order wins ties). */
147
+ export function searchItems(items, query) {
148
+ const scored = (items || []).map((it, i) => ({ it, i, s: scoreItem(it, query) })).filter((x) => x.s > 0);
149
+ scored.sort((a, b) => b.s - a.s || a.i - b.i);
150
+ return scored.map((x) => x.it);
151
+ }
152
+
153
+ /** Matching items grouped by section, sections in the order the host listed them
154
+ * (items without a section share the unnamed group, first). */
155
+ export function groupItems(items, query) {
156
+ const groups = new Map();
157
+ for (const it of searchItems(items, query)) {
158
+ const key = it.section || '';
159
+ if (!groups.has(key)) groups.set(key, []);
160
+ groups.get(key).push(it);
161
+ }
162
+ const order = [''];
163
+ for (const it of items || []) { const k = it.section || ''; if (!order.includes(k)) order.push(k); }
164
+ return order.filter((k) => groups.has(k)).map((k) => ({ section: k, items: groups.get(k) }));
165
+ }
166
+
167
+ /** Where a trigger is live in a piece of text ending at the caret: the query typed after it,
168
+ * or null. A trigger counts only at a word start and only while the query has no line break
169
+ * and is not too long to be a name someone is still typing. */
170
+ export function activeTrigger(textBeforeCaret, trigger = '@', maxLen = 48) {
171
+ const at = textBeforeCaret.lastIndexOf(trigger);
172
+ if (at < 0) return null;
173
+ if (at > 0 && !/[\s([{"'>]/.test(textBeforeCaret[at - 1])) return null;
174
+ const query = textBeforeCaret.slice(at + trigger.length);
175
+ if (query.length > maxLen || /\n/.test(query)) return null;
176
+ return { start: at, query };
177
+ }
@@ -0,0 +1,57 @@
1
+ // The run's one line in the tabs bar: what is filling, how far along, Stop;
2
+ // then the outcome until dismissed. Every number is the run's own.
3
+ import React from 'react';
4
+ import { isRunActive } from './useSheetRun.js';
5
+
6
+ // The outcome as counted from the document; a run closed while the document
7
+ // could not be read carries no counts, and says nothing rather than zeros.
8
+ function outcome(run) {
9
+ const c = run.counts;
10
+ if (!c) return '';
11
+ const parts = [`${c.done || 0} done`];
12
+ if (c.failed) parts.push(`${c.failed} failed`);
13
+ if (c.skipped) parts.push(`${c.skipped} skipped`);
14
+ return parts.join(', ');
15
+ }
16
+
17
+ export function RunStrip({ run, error, filled = 0, onCancel, onDismiss }) {
18
+ if (!run && !error) return null;
19
+ let text = error;
20
+ let tone = 'failed';
21
+ if (run) {
22
+ const names = (run.columns || []).map((c) => c.name).join(', ');
23
+ const total = run.cell_count || 0;
24
+ tone = run.status;
25
+ if (run.status === 'running') {
26
+ text = `Filling ${names}: ${filled} of ${total} cells, ${run.concurrency} rows at a time`;
27
+ } else if (run.status === 'cancelling') {
28
+ text = `Stopping after the cells in flight: ${filled} of ${total} cells`;
29
+ } else if (run.status === 'done') {
30
+ const o = outcome(run);
31
+ text = o ? `Filled ${names}: ${o}` : `Filled ${names}`;
32
+ } else if (run.status === 'cancelled') {
33
+ const c = run.counts;
34
+ const o = outcome(run);
35
+ const notRun = c ? Math.max(0, total - ((c.done || 0) + (c.failed || 0) + (c.skipped || 0))) : null;
36
+ text = o ? `Stopped: ${o}, ${notRun} not run` : 'Stopped';
37
+ } else {
38
+ const o = outcome(run);
39
+ text = run.error ? `The run stopped early: ${run.error}` : 'The run could not start';
40
+ if (o) text += ` (${o})`;
41
+ tone = 'failed';
42
+ }
43
+ }
44
+ const active = isRunActive(run);
45
+ return (
46
+ <div className={`shg-run shg-run-${tone}`} role="status" aria-live="polite">
47
+ <span className="shg-run-dot" aria-hidden="true" />
48
+ <span className="shg-run-text" title={text}>{text}</span>
49
+ {active ? (
50
+ <button type="button" className="shg-run-stop" onClick={onCancel}
51
+ disabled={run.status === 'cancelling'}>Stop</button>
52
+ ) : (
53
+ <button type="button" className="shg-run-x" onClick={onDismiss} aria-label="Dismiss">×</button>
54
+ )}
55
+ </div>
56
+ );
57
+ }