reifyui 0.15.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reifyui",
3
- "version": "0.15.1",
3
+ "version": "0.16.0",
4
4
  "description": "The open-source rendering & interaction layer for agentic applications. Stream and render any agent's output as polished, application-native UI — model-agnostic, framework-agnostic, design-system-native. The foundation for building generative-UI and agent products.",
5
5
  "keywords": [
6
6
  "react",
@@ -0,0 +1,55 @@
1
+ // The files a turn produced, opened beside the conversation instead of printed into it.
2
+ //
3
+ // In the conversation a file is a card (the package's FileCard: its kind, Copy, Download, and the
4
+ // whole card opens it). Opened, it shows here: the file rendered (Markdown as a document, code
5
+ // highlighted, images, PDFs, sheets), a switcher across every file the conversation made, Copy,
6
+ // Download and Close. Docked, it is a column the host places beside the chat; `overlay` makes it a
7
+ // drawer over the page from the right, which is what a narrow screen gets.
8
+ //
9
+ // Transport and rendering stay the host's, exactly as for FilePreview: `fetchFile` (with the
10
+ // host's auth), `renderMarkdown`, `officePdfUrl`, `parseWorkbook`, `onDownload`.
11
+ import React, { useEffect, useRef } from 'react';
12
+ import { FilePreview } from '../components/FilePreview.jsx';
13
+ import { FileTypeIcon } from '../components/FileTypeIcon.jsx';
14
+
15
+ /**
16
+ * files: [{ key, name, url }] (key: stable id, e.g. the file id); active: the key shown.
17
+ */
18
+ export function ArtifactPanel(props) {
19
+ const {
20
+ files = [], active, onSelect, onClose, overlay = false, label = 'Files in this conversation',
21
+ fetchFile, renderMarkdown, officePdfUrl, parseWorkbook, onDownload, className,
22
+ } = props;
23
+ const ref = useRef(null);
24
+ const cur = files.find((f) => f.key === active) || files[0] || null;
25
+ // a drawer takes the focus and gives it back with Escape, like any dialog
26
+ useEffect(() => {
27
+ if (!overlay || !cur) return undefined;
28
+ const back = document.activeElement;
29
+ const t = setTimeout(() => { const b = ref.current && ref.current.querySelector('button'); if (b) b.focus(); }, 0);
30
+ const key = (e) => { if (e.key === 'Escape') { e.stopPropagation(); onClose && onClose(); } };
31
+ document.addEventListener('keydown', key);
32
+ return () => { clearTimeout(t); document.removeEventListener('keydown', key); if (back && back.focus) back.focus(); };
33
+ }, [overlay, !!cur]); // eslint-disable-line react-hooks/exhaustive-deps
34
+ if (!cur) return null;
35
+ const switcher = files.length > 1 ? (
36
+ <nav className="uac-art-files" aria-label={label}>
37
+ {files.map((f) => (
38
+ <button key={f.key} type="button" className={'uac-art-file' + (f.key === cur.key ? ' is-on' : '')}
39
+ aria-current={f.key === cur.key ? 'true' : undefined} title={f.name} onClick={() => onSelect && onSelect(f.key)}>
40
+ <FileTypeIcon name={f.name} size={14} /><span>{f.name}</span>
41
+ </button>
42
+ ))}
43
+ </nav>
44
+ ) : null;
45
+ return (
46
+ <>
47
+ {overlay ? <div className="uac-art-scrim" aria-hidden="true" onClick={() => onClose && onClose()} /> : null}
48
+ <div ref={ref} className={'uac-art' + (overlay ? ' is-overlay' : '') + (className ? ` ${className}` : '')}
49
+ role={overlay ? 'dialog' : undefined} aria-modal={overlay ? 'true' : undefined} aria-label={overlay ? `Preview of ${cur.name}` : undefined}>
50
+ <FilePreview key={cur.key} file={{ url: cur.url, name: cur.name }} onClose={onClose} before={switcher}
51
+ fetchFile={fetchFile} renderMarkdown={renderMarkdown} officePdfUrl={officePdfUrl} parseWorkbook={parseWorkbook} onDownload={onDownload} />
52
+ </div>
53
+ </>
54
+ );
55
+ }
@@ -458,7 +458,12 @@ export function TurnOutcome(props) {
458
458
  if (!turn || turn.status === 'running') return null;
459
459
  const ms = turn.startedAt != null && turn.endedAt != null ? turn.endedAt - turn.startedAt : turn.elapsedMs;
460
460
  const time = ms != null && ms >= 0 ? formatElapsed(ms) : '';
461
- const tok = turn.usage && (turn.usage.total_tokens ?? ((turn.usage.input_tokens || 0) + (turn.usage.output_tokens || 0)));
461
+ // every token the turn's usage reports: fresh input, output, and the cache read and written. Some
462
+ // providers' total leaves the cache out (Anthropic's input counts fresh tokens only), so the
463
+ // same work would read 300 on one harness and 13k on another.
464
+ const u = turn.usage || null;
465
+ const parts = u ? ['input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens'].map((k) => Number(u[k]) || 0) : [];
466
+ const tok = u ? (parts.some(Boolean) ? parts.reduce((a, b) => a + b, 0) : (Number(u.total_tokens) || 0)) : 0;
462
467
  const tokens = tok ? labels.tokens(formatTokens(tok)) : '';
463
468
  if (turn.status === 'done') {
464
469
  if (!time && !tokens) return null;
@@ -188,3 +188,37 @@ export interface AgentConversationProps extends MarkProps {
188
188
  empty?: ReactNode;
189
189
  }
190
190
  export function AgentConversation(props: AgentConversationProps): ReactElement;
191
+
192
+ export interface ArtifactFile { key: string; name: string; url: string }
193
+ export interface ArtifactPanelProps {
194
+ files: ArtifactFile[];
195
+ /** the key of the file shown (default: the first) */
196
+ active?: string | null;
197
+ onSelect?: (key: string) => void;
198
+ onClose?: () => void;
199
+ /** a drawer over the page from the right (a narrow screen) instead of a docked column */
200
+ overlay?: boolean;
201
+ label?: string;
202
+ fetchFile?: (url: string) => Promise<Response>;
203
+ renderMarkdown?: (text: string) => ReactNode;
204
+ officePdfUrl?: (url: string) => string;
205
+ parseWorkbook?: (buf: ArrayBuffer) => Promise<{ name: string; filled: boolean; rows: unknown[][] }[]>;
206
+ onDownload?: (url: string, name: string) => void;
207
+ className?: string;
208
+ }
209
+ export function ArtifactPanel(props: ArtifactPanelProps): ReactElement | null;
210
+ export interface FileCardProps {
211
+ name: string; origin?: string; bytes?: number;
212
+ onPreview?: () => void; onDownload?: () => void;
213
+ /** copy the file's text; resolve when copied, reject when it could not be */
214
+ onCopy?: () => Promise<void> | void;
215
+ /** the file open in the preview */
216
+ active?: boolean;
217
+ className?: string;
218
+ }
219
+ export function FileCard(props: FileCardProps): ReactElement;
220
+ export function FilePreview(props: {
221
+ file: { url: string; name: string } | null; onClose?: () => void; fetchFile?: (url: string) => Promise<Response>;
222
+ officePdfUrl?: (url: string) => string; renderMarkdown?: (text: string) => ReactNode;
223
+ parseWorkbook?: ArtifactPanelProps['parseWorkbook']; onDownload?: (url: string, name: string) => void; title?: string; before?: ReactNode;
224
+ }): ReactElement;
@@ -10,6 +10,7 @@
10
10
  // WorkingIndicator, WorkingMark, StreamingText, TurnOutcome, UserBubble,
11
11
  // AgentComposer, CopyButton, DiffBadge, LinesBlock, useStickToBottom,
12
12
  // DEFAULT_AGENT_LABELS
13
+ // the files ArtifactPanel, FileCard, FilePreview (styles: also reifyui/styles/file.css)
13
14
  //
14
15
  // Styles: reifyui/styles/agent-chat.css. A separate entry so a host that renders a Button never
15
16
  // pulls in a conversation, and so nothing here changes what the root ChatMessages/ChatPanel do.
@@ -22,3 +23,7 @@ export { MARK_MOTIONS, MOTIONS, motionFor } from './marks.js';
22
23
  export { AgentConversation, AgentTurnView, WorkGroup, StepRow, ThinkingRow, TodoCard, WorkingIndicator, WorkingMark,
23
24
  StreamingText, TurnOutcome, UserBubble, AgentComposer, CopyButton, DiffBadge, LinesBlock, useStickToBottom,
24
25
  DEFAULT_AGENT_LABELS } from './components.jsx';
26
+ // the files a turn made: cards in the conversation (FileCard), opened beside it (ArtifactPanel)
27
+ export { ArtifactPanel } from './artifacts.jsx';
28
+ export { FileCard } from '../components/FileCard.jsx';
29
+ export { FilePreview } from '../components/FilePreview.jsx';
@@ -9,8 +9,12 @@
9
9
  // a variant of, which is what a variant usually is. A cell narrow enough to need a different card
10
10
  // is a cell too narrow to show the file at all — the name ellipsises and the card still works.
11
11
  import { FileTypeIcon, extOf } from './FileTypeIcon.jsx';
12
+ import { useEffect, useState } from 'react';
12
13
  import { IcDownload } from './icons.jsx';
13
14
 
15
+ const IcCopy = () => <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V6a2 2 0 0 1 2-2h9" /></svg>;
16
+ const IcCheckMark = () => <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12l5 5L20 7" /></svg>;
17
+
14
18
  /** "PPTX · output" — what it is, then where it came from. `origin` is the caller's word. */
15
19
  function subtitle(name, origin, bytes) {
16
20
  const parts = [(extOf(name) || 'file').toUpperCase()];
@@ -26,12 +30,16 @@ export function bytesLabel(n) {
26
30
  return `${(n / 1048576).toFixed(1)} MB`;
27
31
  }
28
32
 
29
- export function FileCard({ name, origin = 'output', bytes, onPreview, onDownload, className = '' }) {
33
+ export function FileCard({ name, origin = 'output', bytes, onPreview, onDownload, onCopy, active = false, className = '' }) {
34
+ // Copy: the host copies the file's text (it owns the read); the card says it did, briefly.
35
+ const [copied, setCopied] = useState('');
36
+ useEffect(() => { if (!copied) return undefined; const t = setTimeout(() => setCopied(''), 1600); return () => clearTimeout(t); }, [copied]);
30
37
  // The whole card opens the preview, and the eye repeats it as an explicit target — a card that
31
38
  // is clickable without saying so is a card people do not click.
32
39
  const open = onPreview ? (e) => { e.stopPropagation(); onPreview(); } : undefined;
33
40
  return (
34
- <div className={'uic-filecard' + (open ? ' is-clickable' : '') + (className ? ' ' + className : '')}
41
+ <div className={'uic-filecard' + (open ? ' is-clickable' : '') + (active ? ' is-active' : '') + (className ? ' ' + className : '')}
42
+ aria-current={active ? 'true' : undefined}
35
43
  onClick={open}
36
44
  role={open ? 'button' : undefined}
37
45
  tabIndex={open ? 0 : undefined}
@@ -42,6 +50,13 @@ export function FileCard({ name, origin = 'output', bytes, onPreview, onDownload
42
50
  <span className="uic-filecard-name">{name}</span>
43
51
  <span className="uic-filecard-sub">{subtitle(name, origin, bytes)}</span>
44
52
  </span>
53
+ {onCopy && (
54
+ <button type="button" className="uic-filecard-dl uic-filecard-copy" aria-label={copied === 'ok' ? 'Copied' : `Copy ${name}`}
55
+ title={copied === 'ok' ? 'Copied' : copied === 'no' ? 'Could not copy' : 'Copy'}
56
+ onClick={async (e) => { e.stopPropagation(); try { await onCopy(); setCopied('ok'); } catch { setCopied('no'); } }}>
57
+ {copied === 'ok' ? <IcCheckMark /> : <IcCopy />}
58
+ </button>
59
+ )}
45
60
  {onDownload && (
46
61
  <button type="button" className="uic-filecard-dl" aria-label={`Download ${name}`} title="Download"
47
62
  onClick={(e) => { e.stopPropagation(); onDownload(); }}>
@@ -95,7 +95,7 @@ const defaultDownload = (url, name) => {
95
95
  * all. Async, so the caller can load its spreadsheet library lazily.
96
96
  */
97
97
  export function FilePreview({
98
- file, onClose, fetchFile, officePdfUrl, renderMarkdown, parseWorkbook, onDownload, title,
98
+ file, onClose, fetchFile, officePdfUrl, renderMarkdown, parseWorkbook, onDownload, title, before,
99
99
  }) {
100
100
  const { url, name } = file || {};
101
101
  const [st, setSt] = useState({ kind: 'loading' });
@@ -164,9 +164,15 @@ export function FilePreview({
164
164
  }, [url, name, fetchFile, officePdfUrl, parseWorkbook]);
165
165
 
166
166
  const download = () => (onDownload ? onDownload(url, name) : defaultDownload(url, name));
167
+ // a file read as text can be copied from the header (what was read is what is copied)
168
+ const [copied, setCopied] = useState('');
169
+ useEffect(() => { if (!copied) return undefined; const t = setTimeout(() => setCopied(''), 1600); return () => clearTimeout(t); }, [copied]);
170
+ const copyText = typeof st.text === 'string' ? st.text : null;
171
+ const copy = async () => { try { await navigator.clipboard.writeText(copyText || ''); setCopied('ok'); } catch { setCopied('no'); } };
167
172
 
168
173
  return (
169
174
  <aside className="uic-fp" aria-label={title || `Preview of ${name}`}>
175
+ {before}
170
176
  <header className="uic-fp-head">
171
177
  <span className="uic-fp-ic"><FileTypeIcon name={name} size={20} /></span>
172
178
  <span className="uic-fp-name" title={name}>{name}</span>
@@ -178,6 +184,14 @@ export function FilePreview({
178
184
  ))}
179
185
  </div>
180
186
  )}
187
+ {copyText != null && (
188
+ <button type="button" className="uic-fp-btn uic-fp-copy" aria-label={copied === 'ok' ? 'Copied' : `Copy ${name}`}
189
+ title={copied === 'ok' ? 'Copied' : copied === 'no' ? 'Could not copy' : 'Copy'} onClick={copy}>
190
+ {copied === 'ok'
191
+ ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12l5 5L20 7" /></svg>
192
+ : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V6a2 2 0 0 1 2-2h9" /></svg>}
193
+ </button>
194
+ )}
181
195
  <button type="button" className="uic-fp-btn" aria-label={`Download ${name}`} title="Download"
182
196
  onClick={download}><IcDownload /></button>
183
197
  {onClose && (
@@ -279,6 +279,23 @@
279
279
  .uac-att button:hover { color: var(--_ink); background: var(--_hover); }
280
280
  .uac-att.is-error { border-color: var(--uic-fail-line, #fecaca); color: var(--_fail); }
281
281
 
282
+ /* ── the files a turn made, opened beside the conversation (ArtifactPanel; FilePreview's own
283
+ styles are reifyui/styles/file.css) ─────────────────────────────────────────────────── */
284
+ .uac-art { display: flex; flex-direction: column; min-width: 0; min-height: 0; height: 100%; background: var(--_surface); color: var(--_ink); }
285
+ .uac-art > .uic-fp { flex: 1; min-height: 0; height: 100%; display: flex; flex-direction: column; }
286
+ .uac-art-files { flex: none; display: flex; gap: 4px; padding: 8px 10px; overflow-x: auto; border-bottom: 1px solid var(--_line); scrollbar-width: thin; }
287
+ .uac-art-file { flex: none; display: inline-flex; align-items: center; gap: 6px; max-width: 220px; padding: 5px 10px; border: 1px solid transparent; border-radius: 8px;
288
+ background: none; font: inherit; font-size: 12.5px; color: var(--_mute); cursor: pointer; white-space: nowrap; }
289
+ .uac-art-file span { overflow: hidden; text-overflow: ellipsis; }
290
+ .uac-art-file:hover { color: var(--_ink); background: var(--_hover); }
291
+ .uac-art-file.is-on { color: var(--_ink); background: var(--_surface-2); border-color: var(--_line); }
292
+ .uac-art-file:focus-visible { outline: 2px solid var(--_brand); outline-offset: 1px; }
293
+ .uac-art.is-overlay { position: fixed; top: 0; right: 0; bottom: 0; width: min(680px, 100vw); height: auto; z-index: var(--uac-z-overlay, 60);
294
+ box-shadow: -16px 0 40px rgba(15, 23, 42, .22); padding-top: env(safe-area-inset-top, 0px); padding-bottom: env(safe-area-inset-bottom, 0px);
295
+ animation: uac-art-in .18s ease-out; }
296
+ .uac-art-scrim { position: fixed; inset: 0; z-index: calc(var(--uac-z-overlay, 60) - 1); background: var(--uic-scrim, rgba(17, 24, 39, .42)); }
297
+ @keyframes uac-art-in { from { transform: translateX(24px); opacity: .6; } to { transform: none; opacity: 1; } }
298
+
282
299
  /* ── narrow ──────────────────────────────────────────────────────────────────────────────────── */
283
300
  @media (max-width: 560px) {
284
301
  .uac-thread { gap: 24px; }
@@ -302,5 +319,6 @@
302
319
  .uac-shimmer { color: var(--_ink-2); background: none; }
303
320
  .uac-ring::before { border-color: var(--_brand); }
304
321
  .uac-composer, .uac-send { transition: none; }
322
+ .uac-art.is-overlay { animation: none; }
305
323
  }
306
324
  .uac-mark.is-still .uac-mark-in, .uac-mark.is-still .uac-mark-aura, .uac-mark.is-still i { animation: none; }
package/styles/file.css CHANGED
@@ -13,6 +13,8 @@
13
13
  .uic-filecard.is-clickable { cursor: pointer; }
14
14
  .uic-filecard.is-clickable:hover { border-color: var(--uic-brand-soft, #E1E9FF); }
15
15
  .uic-filecard:focus-visible { outline: 2px solid var(--uic-brand, #285AFF); outline-offset: 2px; }
16
+ /* the file open in a preview beside the conversation */
17
+ .uic-filecard.is-active { border-color: var(--uic-brand, #285AFF); box-shadow: 0 0 0 3px var(--uic-focus-ring, rgba(40, 90, 255, .14)); }
16
18
  .uic-filecard-ic { flex: 0 0 auto; display: flex; align-items: center; justify-content: center; }
17
19
  .uic-filecard-meta { flex: 1 1 auto; min-width: 0; }
18
20
  .uic-filecard-name {
@@ -1,177 +0,0 @@
1
- import {
2
- IcX
3
- } from "./chunk-WAND7AYD.js";
4
- import {
5
- useOverlayEscape
6
- } from "./chunk-J633KV57.js";
7
-
8
- // src/components/CodeBlock.jsx
9
- import React from "react";
10
- import { jsx, jsxs } from "react/jsx-runtime";
11
- var _hljsPromise = null;
12
- function loadHljs() {
13
- if (!_hljsPromise) {
14
- _hljsPromise = import("highlight.js/lib/core").then((m) => m.default || m);
15
- }
16
- return _hljsPromise;
17
- }
18
- var GRAMMARS = {
19
- javascript: () => import("highlight.js/lib/languages/javascript"),
20
- typescript: () => import("highlight.js/lib/languages/typescript"),
21
- python: () => import("highlight.js/lib/languages/python"),
22
- json: () => import("highlight.js/lib/languages/json"),
23
- bash: () => import("highlight.js/lib/languages/bash"),
24
- sql: () => import("highlight.js/lib/languages/sql"),
25
- java: () => import("highlight.js/lib/languages/java"),
26
- go: () => import("highlight.js/lib/languages/go"),
27
- rust: () => import("highlight.js/lib/languages/rust"),
28
- xml: () => import("highlight.js/lib/languages/xml"),
29
- css: () => import("highlight.js/lib/languages/css"),
30
- yaml: () => import("highlight.js/lib/languages/yaml"),
31
- groovy: () => import("highlight.js/lib/languages/groovy")
32
- };
33
- var ALIASES = {
34
- js: "javascript",
35
- jsx: "javascript",
36
- mjs: "javascript",
37
- cjs: "javascript",
38
- node: "javascript",
39
- ts: "typescript",
40
- tsx: "typescript",
41
- py: "python",
42
- python3: "python",
43
- sh: "bash",
44
- shell: "bash",
45
- zsh: "bash",
46
- console: "bash",
47
- html: "xml",
48
- xhtml: "xml",
49
- svg: "xml",
50
- yml: "yaml",
51
- golang: "go",
52
- rs: "rust",
53
- jsonc: "json",
54
- postgres: "sql",
55
- postgresql: "sql",
56
- mysql: "sql",
57
- plsql: "sql",
58
- gremlin: "groovy"
59
- };
60
- function canonicalLang(tag) {
61
- const t = String(tag || "").toLowerCase();
62
- if (!t) return null;
63
- const name = ALIASES[t] || t;
64
- return GRAMMARS[name] ? name : null;
65
- }
66
- var _ready = /* @__PURE__ */ new Map();
67
- function ensureLanguage(name) {
68
- if (!_ready.has(name)) {
69
- const p = Promise.all([loadHljs(), GRAMMARS[name]()]).then(([hljs, mod]) => {
70
- if (!hljs.getLanguage(name)) hljs.registerLanguage(name, mod.default || mod);
71
- return hljs;
72
- }).catch(() => null);
73
- _ready.set(name, p);
74
- }
75
- return _ready.get(name);
76
- }
77
- function CodeBlock(props) {
78
- const { code, language, className } = props;
79
- const src = String(code || "");
80
- const lang = canonicalLang(language);
81
- const [hl, setHl] = React.useState(null);
82
- React.useEffect(() => {
83
- if (!lang || !src) return void 0;
84
- let cancelled = false;
85
- const timer = setTimeout(() => {
86
- ensureLanguage(lang).then((hljs) => {
87
- if (!hljs || cancelled) return;
88
- try {
89
- const out = hljs.highlight(src, { language: lang, ignoreIllegals: true });
90
- if (!cancelled) setHl({ src, html: out.value });
91
- } catch {
92
- }
93
- });
94
- }, 200);
95
- return () => {
96
- cancelled = true;
97
- clearTimeout(timer);
98
- };
99
- }, [src, lang]);
100
- const html = hl && hl.src === src ? hl.html : null;
101
- const label = String(language || "").toLowerCase();
102
- return /* @__PURE__ */ jsxs("pre", { className: "wbx-code" + (className ? " " + className : ""), children: [
103
- label ? /* @__PURE__ */ jsx("span", { className: "wbx-code-lang", "aria-hidden": "true", children: label }) : null,
104
- html != null ? /* @__PURE__ */ jsx("code", { className: "hljs language-" + label, dangerouslySetInnerHTML: { __html: html } }) : /* @__PURE__ */ jsx("code", { className: label ? "language-" + label : void 0, children: src })
105
- ] });
106
- }
107
-
108
- // src/components/Modal.jsx
109
- import React2, { useCallback, useEffect, useId } from "react";
110
- import { createPortal } from "react-dom";
111
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
112
- function Modal(props) {
113
- const {
114
- open,
115
- onClose,
116
- title,
117
- description,
118
- actions,
119
- size = "md",
120
- width,
121
- labelledBy,
122
- children,
123
- classNames = {}
124
- } = props;
125
- const titleId = useId();
126
- const escape = useCallback(() => onClose?.(), [onClose]);
127
- useOverlayEscape(open, escape);
128
- useEffect(() => {
129
- if (!open || typeof document === "undefined") return void 0;
130
- const prev = document.body.style.overflow;
131
- document.body.style.overflow = "hidden";
132
- return () => {
133
- document.body.style.overflow = prev;
134
- };
135
- }, [open]);
136
- if (!open || typeof document === "undefined") return null;
137
- const onBackdrop = (e) => {
138
- if (e.target === e.currentTarget) onClose?.();
139
- };
140
- return createPortal(
141
- /* @__PURE__ */ jsx2(
142
- "div",
143
- {
144
- className: ["uic-modal-backdrop", classNames.backdrop || ""].filter(Boolean).join(" "),
145
- onMouseDown: onBackdrop,
146
- children: /* @__PURE__ */ jsxs2(
147
- "div",
148
- {
149
- className: ["uic-modal", `is-${size}`, classNames.root || ""].filter(Boolean).join(" "),
150
- style: width ? { width } : void 0,
151
- role: "dialog",
152
- "aria-modal": "true",
153
- "aria-labelledby": labelledBy || (title ? titleId : void 0),
154
- children: [
155
- title || actions ? /* @__PURE__ */ jsxs2("div", { className: "uic-modal-h", children: [
156
- /* @__PURE__ */ jsxs2("div", { className: "uic-modal-title", children: [
157
- title ? /* @__PURE__ */ jsx2("h3", { id: titleId, children: title }) : null,
158
- description ? /* @__PURE__ */ jsx2("p", { children: description }) : null
159
- ] }),
160
- actions,
161
- /* @__PURE__ */ jsx2("button", { type: "button", className: "uic-modal-x", "aria-label": "Close", onClick: onClose, children: /* @__PURE__ */ jsx2(IcX, { size: 18 }) })
162
- ] }) : null,
163
- /* @__PURE__ */ jsx2("div", { className: ["uic-modal-b", classNames.body || ""].filter(Boolean).join(" "), children })
164
- ]
165
- }
166
- )
167
- }
168
- ),
169
- document.body
170
- );
171
- }
172
-
173
- export {
174
- CodeBlock,
175
- Modal
176
- };
177
- //# sourceMappingURL=chunk-AGSX5YKH.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/CodeBlock.jsx","../src/components/Modal.jsx"],"sourcesContent":["// Fenced code block with language-aware syntax highlighting (highlight.js core).\n//\n// Consumers wire this into their markdown renderer's `pre` override (see the ChatPanel /\n// workbench MD_COMPONENTS): a ```mermaid fence keeps rendering as a diagram; every other fence\n// renders here. Design notes (same lazy pattern as the Mermaid block):\n// - highlight.js is LAZY-loaded (dynamic import) — the core plus exactly one small grammar\n// chunk per language actually used, never the full-language bundle. Until it loads the block\n// renders as plain <pre><code>, byte-identical geometry, so there is no layout shift.\n// - Highlighting is DEBOUNCED: while a fence is still streaming in token by token we render\n// plain text and re-arm the timer; the block highlights once it settles. hljs itself never\n// throws on partial input, the debounce just avoids re-lexing on every token.\n// - Unknown / missing language: NO auto-detect, render plain. Wrong-language colors are worse\n// than none.\n// - `gremlin` maps to the groovy grammar (Gremlin is a Groovy DSL — closest match).\n// - Colors are token-driven: .wbx-code maps hljs classes onto five --uic-code-* custom\n// properties (keyword/string/comment/number/function) with defaults tuned for the dark\n// code-block background. See styles/chat.css + README \"Theming\".\n// highlight.js must be a dependency of the CONSUMING app (the dynamic import resolves in its\n// bundler) — same rule as mermaid.\nimport React from 'react';\n\nlet _hljsPromise = null;\nfunction loadHljs() {\n if (!_hljsPromise) {\n _hljsPromise = import('highlight.js/lib/core').then((m) => m.default || m);\n }\n return _hljsPromise;\n}\n\n// One static dynamic-import per grammar so each becomes its own code-split chunk and only the\n// languages that actually appear in a conversation ever download.\nconst GRAMMARS = {\n javascript: () => import('highlight.js/lib/languages/javascript'),\n typescript: () => import('highlight.js/lib/languages/typescript'),\n python: () => import('highlight.js/lib/languages/python'),\n json: () => import('highlight.js/lib/languages/json'),\n bash: () => import('highlight.js/lib/languages/bash'),\n sql: () => import('highlight.js/lib/languages/sql'),\n java: () => import('highlight.js/lib/languages/java'),\n go: () => import('highlight.js/lib/languages/go'),\n rust: () => import('highlight.js/lib/languages/rust'),\n xml: () => import('highlight.js/lib/languages/xml'),\n css: () => import('highlight.js/lib/languages/css'),\n yaml: () => import('highlight.js/lib/languages/yaml'),\n groovy: () => import('highlight.js/lib/languages/groovy'),\n};\n\n// Fence-tag aliases → canonical grammar name.\nconst ALIASES = {\n js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript', node: 'javascript',\n ts: 'typescript', tsx: 'typescript',\n py: 'python', python3: 'python',\n sh: 'bash', shell: 'bash', zsh: 'bash', console: 'bash',\n html: 'xml', xhtml: 'xml', svg: 'xml',\n yml: 'yaml',\n golang: 'go',\n rs: 'rust',\n jsonc: 'json',\n postgres: 'sql', postgresql: 'sql', mysql: 'sql', plsql: 'sql',\n gremlin: 'groovy',\n};\n\nfunction canonicalLang(tag) {\n const t = String(tag || '').toLowerCase();\n if (!t) return null;\n const name = ALIASES[t] || t;\n return GRAMMARS[name] ? name : null;\n}\n\n// canonical name -> Promise<hljs | null> (null = load failed; stay plain forever, never retry-loop)\nconst _ready = new Map();\nfunction ensureLanguage(name) {\n if (!_ready.has(name)) {\n const p = Promise.all([loadHljs(), GRAMMARS[name]()])\n .then(([hljs, mod]) => {\n if (!hljs.getLanguage(name)) hljs.registerLanguage(name, mod.default || mod);\n return hljs;\n })\n .catch(() => null);\n _ready.set(name, p);\n }\n return _ready.get(name);\n}\n\nexport function CodeBlock(props) {\n const { code, language, className } = props;\n const src = String(code || '');\n const lang = canonicalLang(language);\n const [hl, setHl] = React.useState(null); // { src, html } — html valid only for exactly that src\n\n React.useEffect(() => {\n if (!lang || !src) return undefined;\n let cancelled = false;\n // Debounce: during streaming the fence grows every few ms — wait for a quiet gap, then\n // highlight the settled source. hljs output is fully HTML-escaped (safe to inject).\n const timer = setTimeout(() => {\n ensureLanguage(lang).then((hljs) => {\n if (!hljs || cancelled) return;\n try {\n const out = hljs.highlight(src, { language: lang, ignoreIllegals: true });\n if (!cancelled) setHl({ src, html: out.value });\n } catch {\n /* stay plain */\n }\n });\n }, 200);\n return () => { cancelled = true; clearTimeout(timer); };\n }, [src, lang]);\n\n const html = hl && hl.src === src ? hl.html : null;\n const label = String(language || '').toLowerCase();\n return (\n <pre className={'wbx-code' + (className ? ' ' + className : '')}>\n {label ? <span className=\"wbx-code-lang\" aria-hidden=\"true\">{label}</span> : null}\n {html != null\n ? <code className={'hljs language-' + label} dangerouslySetInnerHTML={{ __html: html }} />\n : <code className={label ? 'language-' + label : undefined}>{src}</code>}\n </pre>\n );\n}\n","// Modal — a dialog whose body is yours: a preview, a big form, a comparison.\n//\n// useDialog() answers a QUESTION and resolves to a value (confirm/prompt/alert). This is the\n// other half: a surface with arbitrary content that the caller opens and closes itself. Products\n// were re-implementing it per feature, each with its own backdrop mousedown handler and its own\n// document keydown listener.\n//\n// It shares the dialog host's Escape ordering through the package's overlay stack (components/\n// overlay.js), so a Modal opened on top of a confirm takes the key and the confirm does not, and\n// both sit at the same z-index layer (--uic-z-overlay). It does NOT render inside DialogHost's\n// portal: that root is created from the host's private state and only exists while a dialog is\n// open, so there is nothing to render into and no API to reach it with. One stack, two roots, is\n// the honest arrangement — and it means Modal works in an app that never mounted DialogHost.\nimport React, { useCallback, useEffect, useId } from 'react';\nimport { createPortal } from 'react-dom';\nimport { IcX } from './icons.jsx';\nimport { useOverlayEscape } from './overlay.js';\n\n/**\n * open render it\n * onClose Escape, the ✕, or a click on the backdrop itself\n * title the heading (string or node); also names the dialog for assistive tech\n * description one quiet line under the title\n * actions buttons in the header, before the ✕ (e.g. \"Use this template\")\n * size 'sm' | 'md' | 'lg' | 'full' — or pass `width` for an exact px/any CSS width\n * labelledBy id of your own heading, when `title` is not where the name lives\n */\nexport function Modal(props) {\n const { open, onClose, title, description, actions, size = 'md', width,\n labelledBy, children, classNames = {} } = props;\n const titleId = useId();\n\n const escape = useCallback(() => onClose?.(), [onClose]);\n useOverlayEscape(open, escape);\n\n // A modal that leaves the page scrolling behind it drifts under the reader's fingers on a\n // touch device and loses their place in the list they opened it from.\n useEffect(() => {\n if (!open || typeof document === 'undefined') return undefined;\n const prev = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n return () => { document.body.style.overflow = prev; };\n }, [open]);\n\n if (!open || typeof document === 'undefined') return null;\n // mousedown, not click: a press that STARTED inside the card and ended on the backdrop (a drag\n // that overshot, a text selection) would otherwise close it out from under the person.\n const onBackdrop = (e) => { if (e.target === e.currentTarget) onClose?.(); };\n return createPortal(\n <div className={['uic-modal-backdrop', classNames.backdrop || ''].filter(Boolean).join(' ')}\n onMouseDown={onBackdrop}>\n <div className={['uic-modal', `is-${size}`, classNames.root || ''].filter(Boolean).join(' ')}\n style={width ? { width } : undefined}\n role=\"dialog\" aria-modal=\"true\"\n aria-labelledby={labelledBy || (title ? titleId : undefined)}>\n {(title || actions) ? (\n <div className=\"uic-modal-h\">\n <div className=\"uic-modal-title\">\n {title ? <h3 id={titleId}>{title}</h3> : null}\n {description ? <p>{description}</p> : null}\n </div>\n {actions}\n <button type=\"button\" className=\"uic-modal-x\" aria-label=\"Close\" onClick={onClose}>\n <IcX size={18} />\n </button>\n </div>\n ) : null}\n <div className={['uic-modal-b', classNames.body || ''].filter(Boolean).join(' ')}>\n {children}\n </div>\n </div>\n </div>,\n document.body,\n );\n}\n"],"mappings":";;;;;;;;AAmBA,OAAO,WAAW;AA6Fd,SACW,KADX;AA3FJ,IAAI,eAAe;AACnB,SAAS,WAAW;AAClB,MAAI,CAAC,cAAc;AACjB,mBAAe,OAAO,uBAAuB,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,CAAC;AAAA,EAC3E;AACA,SAAO;AACT;AAIA,IAAM,WAAW;AAAA,EACf,YAAY,MAAM,OAAO,uCAAuC;AAAA,EAChE,YAAY,MAAM,OAAO,uCAAuC;AAAA,EAChE,QAAQ,MAAM,OAAO,mCAAmC;AAAA,EACxD,MAAM,MAAM,OAAO,iCAAiC;AAAA,EACpD,MAAM,MAAM,OAAO,iCAAiC;AAAA,EACpD,KAAK,MAAM,OAAO,gCAAgC;AAAA,EAClD,MAAM,MAAM,OAAO,iCAAiC;AAAA,EACpD,IAAI,MAAM,OAAO,+BAA+B;AAAA,EAChD,MAAM,MAAM,OAAO,iCAAiC;AAAA,EACpD,KAAK,MAAM,OAAO,gCAAgC;AAAA,EAClD,KAAK,MAAM,OAAO,gCAAgC;AAAA,EAClD,MAAM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