reifyui 0.2.0 → 0.4.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.
@@ -0,0 +1,194 @@
1
+ // Message list — extracted from HarnessRouter's workbench conversation render.
2
+ // Messages:
3
+ // { role: 'user', text, ... }
4
+ // { role: 'assistant', blocks, status: 'running'|'done'|'failed'|'cancelled'|'incomplete', ... }
5
+ // Assistant blocks render in stream order so tool activity interleaves with prose.
6
+ //
7
+ // Override slots (all optional):
8
+ // renderMarkdown(text) markdown renderer for prose blocks (inject your ReactMarkdown;
9
+ // default is a plain pre-wrap div — the package has no deps)
10
+ // renderMessage(m, i) full custom render for a message (return undefined to fall through)
11
+ // userExtras(m, i) extra content INSIDE the user bubble, before the text
12
+ // (HR renders its attachment cards here)
13
+ // workingExtra(m, i) extra content on the live Working row (HR's Stop button)
14
+ // assistantFooter(m, i) content below a finished assistant turn (file cards, action row)
15
+ // renderStep(step, j) per-step override inside the activity timeline
16
+ // statusLabels terminal badge copy per status
17
+ // workingLabel / toolLabels live-indicator + timeline copy
18
+ import React from 'react';
19
+ import { ToolGroup } from './ToolSteps.jsx';
20
+
21
+ export const DEFAULT_STATUS_LABELS = {
22
+ failed: '✕ Failed — see the output above for the reason',
23
+ cancelled: '◼ Stopped by you',
24
+ incomplete: '◔ Hit its step or time limit — Continue to resume',
25
+ };
26
+
27
+ const defaultMarkdown = (text) => <div style={{ whiteSpace: 'pre-wrap' }}>{text}</div>;
28
+
29
+ // Typewriter reveal for the actively-streaming text block. Deltas arrive in ~1.2s bursts, so raw
30
+ // rendering makes short answers pop in whole. This fills characters at a deliberate pace: reveal
31
+ // the currently-pending text over ~REVEAL_SEC seconds, but never slower than MIN_CPS (so the last
32
+ // characters don't drag) — and because the rate is (gap / REVEAL_SEC), a newly-arrived batch grows
33
+ // the gap and automatically speeds the reveal to catch up. Snaps to full when streaming stops.
34
+ //
35
+ // The typewriter is a DELTA smoother, not an entrance animation: text already present at mount is
36
+ // history (e.g. opening a running session loads the turn's progress-so-far as one snapshot) and
37
+ // paints instantly — only text appended after mount animates. A turn started live in this tab
38
+ // mounts with empty text, so its stream animates exactly as before.
39
+ const REVEAL_SEC = 3; // a pending burst fills over ~3s...
40
+ const MIN_CPS = 10; // ...unless the tail is small, then at least this many chars/sec
41
+ function TypewriterText(props) {
42
+ const { text, active, render } = props;
43
+ const [n, setN] = React.useState(() => (text ? text.length : 0));
44
+ const textRef = React.useRef(text);
45
+ textRef.current = text;
46
+ const accRef = React.useRef(text ? text.length : 0); // float char position (setN renders the floor)
47
+ React.useEffect(() => {
48
+ if (!active) { setN(textRef.current ? textRef.current.length : 0); return undefined; }
49
+ let raf; let prev = null;
50
+ const tick = (t) => {
51
+ if (prev == null) prev = t;
52
+ const dt = Math.min(0.1, (t - prev) / 1000); // clamp dt so a backgrounded tab doesn't jump
53
+ prev = t;
54
+ const len = textRef.current ? textRef.current.length : 0;
55
+ const gap = len - accRef.current;
56
+ if (gap > 0) {
57
+ const cps = Math.max(MIN_CPS, gap / REVEAL_SEC); // bigger backlog -> faster reveal
58
+ accRef.current = Math.min(len, accRef.current + cps * dt);
59
+ setN(Math.floor(accRef.current));
60
+ }
61
+ raf = requestAnimationFrame(tick);
62
+ };
63
+ raf = requestAnimationFrame(tick);
64
+ return () => cancelAnimationFrame(raf);
65
+ }, [active]);
66
+ const shown = active ? (text || '').slice(0, n) : (text || '');
67
+ return render(shown);
68
+ }
69
+
70
+ // NOTE: components take a single `props` object and destructure inside — TypeScript consumers
71
+ // (HR is TSX) infer inline-destructured JS props as REQUIRED, which would force every slot.
72
+ export function UserTurn(props) {
73
+ const { msg, children } = props;
74
+ return (
75
+ <div className="wbx-turn user">
76
+ <div className="wbx-bubble-user">
77
+ {children}
78
+ {msg.text && <div className="wbx-bubble-text">{msg.text}</div>}
79
+ </div>
80
+ </div>
81
+ );
82
+ }
83
+
84
+ export function AssistantTurn(props) {
85
+ const {
86
+ msg,
87
+ renderMarkdown = defaultMarkdown,
88
+ workingLabel = 'Working…',
89
+ workingExtra,
90
+ statusLabels = DEFAULT_STATUS_LABELS,
91
+ renderStep,
92
+ toolLabels,
93
+ footer,
94
+ } = props;
95
+ return (
96
+ <div className="wbx-turn asst">
97
+ {msg.blocks.map((b, bi) => (b.kind === 'tools'
98
+ ? <ToolGroup key={bi} reasoning={b.reasoning} steps={b.steps}
99
+ running={msg.status === 'running' && bi === msg.blocks.length - 1}
100
+ renderStep={renderStep} {...(toolLabels || {})} />
101
+ : <div key={bi} className="wbx-md"><TypewriterText text={b.text} render={renderMarkdown}
102
+ active={msg.status === 'running' && bi === msg.blocks.length - 1} /></div>
103
+ ))}
104
+ {/* Live "working" indicator BELOW the last row for the whole running turn (not just before
105
+ the first token) — long tool/think phases otherwise look frozen. */}
106
+ {msg.status === 'running' && (
107
+ <div className="wbx-working" aria-label="Working">
108
+ <span className="wbx-working-dots"><span /><span /><span /></span>
109
+ <span className="wbx-working-txt">{workingLabel}</span>
110
+ {workingExtra}
111
+ </div>
112
+ )}
113
+ {(msg.status === 'failed' || msg.status === 'cancelled' || msg.status === 'incomplete') && (
114
+ <div className={'wbx-turnbadge ' + msg.status} role="status">{statusLabels[msg.status]}</div>
115
+ )}
116
+ {footer}
117
+ </div>
118
+ );
119
+ }
120
+
121
+ // Loading placeholder for the conversation. Mirrors UserTurn/AssistantTurn geometry
122
+ // exactly (same .wbx-turn / .wbx-bubble-user / .wbx-md classes), so when real history
123
+ // streams in it lands with ZERO layout shift — assistant turns are full-width prose
124
+ // lines, user turns are right-aligned brand-tinted bubbles a fraction of the column.
125
+ // Themeable through the same --uic-* tokens as the live surface (light + dark), and
126
+ // the wrapper is display:contents so the turns inherit the consumer's own inter-turn
127
+ // spacing. Use on any conversational surface while history / the first tokens load:
128
+ // {loading ? <ChatMessagesSkeleton /> : <ChatMessages ... />}
129
+ // Pass `turns` to customize the mix (each {role:'user'|'assistant', lines:[widths],
130
+ // width?} — user `width` is the bubble's fraction of the column).
131
+ const DEFAULT_SKELETON_TURNS = [
132
+ { role: 'assistant', lines: ['94%', '82%', '58%'] },
133
+ { role: 'user', width: '46%', lines: ['88%', '62%'] },
134
+ { role: 'assistant', lines: ['90%', '97%', '71%'] },
135
+ { role: 'user', width: '38%', lines: ['80%'] },
136
+ ];
137
+
138
+ export function ChatMessagesSkeleton(props) {
139
+ const turns = (props && props.turns) || DEFAULT_SKELETON_TURNS;
140
+ return (
141
+ <div className="wbx-skel" aria-busy="true" aria-label="Loading conversation">
142
+ {turns.map((t, i) => (t.role === 'user' ? (
143
+ <div key={i} className="wbx-turn user wbx-skel-turn" aria-hidden="true">
144
+ <div className="wbx-bubble-user wbx-skel-lines" style={{ width: t.width }}>
145
+ {t.lines.map((w, j) => <span key={j} className="wbx-skel-bar" style={{ width: w }} />)}
146
+ </div>
147
+ </div>
148
+ ) : (
149
+ <div key={i} className="wbx-turn asst wbx-skel-turn" aria-hidden="true">
150
+ <div className="wbx-md wbx-skel-lines">
151
+ {t.lines.map((w, j) => <span key={j} className="wbx-skel-bar" style={{ width: w }} />)}
152
+ </div>
153
+ </div>
154
+ )))}
155
+ </div>
156
+ );
157
+ }
158
+
159
+ export function ChatMessages(props) {
160
+ const {
161
+ messages,
162
+ renderMarkdown,
163
+ renderMessage,
164
+ userExtras,
165
+ workingExtra,
166
+ assistantFooter,
167
+ statusLabels,
168
+ renderStep,
169
+ workingLabel,
170
+ toolLabels,
171
+ } = props;
172
+ return (
173
+ <>
174
+ {messages.map((m, i) => {
175
+ if (renderMessage) {
176
+ const el = renderMessage(m, i);
177
+ if (el !== undefined) return <React.Fragment key={i}>{el}</React.Fragment>;
178
+ }
179
+ return m.role === 'user' ? (
180
+ <UserTurn key={i} msg={m}>{userExtras?.(m, i)}</UserTurn>
181
+ ) : (
182
+ <AssistantTurn key={i} msg={m}
183
+ renderMarkdown={renderMarkdown}
184
+ workingLabel={workingLabel}
185
+ workingExtra={workingExtra?.(m, i)}
186
+ statusLabels={statusLabels}
187
+ renderStep={renderStep}
188
+ toolLabels={toolLabels}
189
+ footer={assistantFooter?.(m, i)} />
190
+ );
191
+ })}
192
+ </>
193
+ );
194
+ }
@@ -0,0 +1,120 @@
1
+ // Fenced code block with language-aware syntax highlighting (highlight.js core).
2
+ //
3
+ // Consumers wire this into their markdown renderer's `pre` override (see the ChatPanel /
4
+ // workbench MD_COMPONENTS): a ```mermaid fence keeps rendering as a diagram; every other fence
5
+ // renders here. Design notes (same lazy pattern as the Mermaid block):
6
+ // - highlight.js is LAZY-loaded (dynamic import) — the core plus exactly one small grammar
7
+ // chunk per language actually used, never the full-language bundle. Until it loads the block
8
+ // renders as plain <pre><code>, byte-identical geometry, so there is no layout shift.
9
+ // - Highlighting is DEBOUNCED: while a fence is still streaming in token by token we render
10
+ // plain text and re-arm the timer; the block highlights once it settles. hljs itself never
11
+ // throws on partial input, the debounce just avoids re-lexing on every token.
12
+ // - Unknown / missing language: NO auto-detect, render plain. Wrong-language colors are worse
13
+ // than none.
14
+ // - `gremlin` maps to the groovy grammar (Gremlin is a Groovy DSL — closest match).
15
+ // - Colors are token-driven: .wbx-code maps hljs classes onto five --uic-code-* custom
16
+ // properties (keyword/string/comment/number/function) with defaults tuned for the dark
17
+ // code-block background. See styles/chat.css + README "Theming".
18
+ // highlight.js must be a dependency of the CONSUMING app (the dynamic import resolves in its
19
+ // bundler) — same rule as mermaid.
20
+ import React from 'react';
21
+
22
+ let _hljsPromise = null;
23
+ function loadHljs() {
24
+ if (!_hljsPromise) {
25
+ _hljsPromise = import('highlight.js/lib/core').then((m) => m.default || m);
26
+ }
27
+ return _hljsPromise;
28
+ }
29
+
30
+ // One static dynamic-import per grammar so each becomes its own code-split chunk and only the
31
+ // languages that actually appear in a conversation ever download.
32
+ const GRAMMARS = {
33
+ javascript: () => import('highlight.js/lib/languages/javascript'),
34
+ typescript: () => import('highlight.js/lib/languages/typescript'),
35
+ python: () => import('highlight.js/lib/languages/python'),
36
+ json: () => import('highlight.js/lib/languages/json'),
37
+ bash: () => import('highlight.js/lib/languages/bash'),
38
+ sql: () => import('highlight.js/lib/languages/sql'),
39
+ java: () => import('highlight.js/lib/languages/java'),
40
+ go: () => import('highlight.js/lib/languages/go'),
41
+ rust: () => import('highlight.js/lib/languages/rust'),
42
+ xml: () => import('highlight.js/lib/languages/xml'),
43
+ css: () => import('highlight.js/lib/languages/css'),
44
+ yaml: () => import('highlight.js/lib/languages/yaml'),
45
+ groovy: () => import('highlight.js/lib/languages/groovy'),
46
+ };
47
+
48
+ // Fence-tag aliases → canonical grammar name.
49
+ const ALIASES = {
50
+ js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript', node: 'javascript',
51
+ ts: 'typescript', tsx: 'typescript',
52
+ py: 'python', python3: 'python',
53
+ sh: 'bash', shell: 'bash', zsh: 'bash', console: 'bash',
54
+ html: 'xml', xhtml: 'xml', svg: 'xml',
55
+ yml: 'yaml',
56
+ golang: 'go',
57
+ rs: 'rust',
58
+ jsonc: 'json',
59
+ postgres: 'sql', postgresql: 'sql', mysql: 'sql', plsql: 'sql',
60
+ gremlin: 'groovy',
61
+ };
62
+
63
+ function canonicalLang(tag) {
64
+ const t = String(tag || '').toLowerCase();
65
+ if (!t) return null;
66
+ const name = ALIASES[t] || t;
67
+ return GRAMMARS[name] ? name : null;
68
+ }
69
+
70
+ // canonical name -> Promise<hljs | null> (null = load failed; stay plain forever, never retry-loop)
71
+ const _ready = new Map();
72
+ function ensureLanguage(name) {
73
+ if (!_ready.has(name)) {
74
+ const p = Promise.all([loadHljs(), GRAMMARS[name]()])
75
+ .then(([hljs, mod]) => {
76
+ if (!hljs.getLanguage(name)) hljs.registerLanguage(name, mod.default || mod);
77
+ return hljs;
78
+ })
79
+ .catch(() => null);
80
+ _ready.set(name, p);
81
+ }
82
+ return _ready.get(name);
83
+ }
84
+
85
+ export function CodeBlock(props) {
86
+ const { code, language, className } = props;
87
+ const src = String(code || '');
88
+ const lang = canonicalLang(language);
89
+ const [hl, setHl] = React.useState(null); // { src, html } — html valid only for exactly that src
90
+
91
+ React.useEffect(() => {
92
+ if (!lang || !src) return undefined;
93
+ let cancelled = false;
94
+ // Debounce: during streaming the fence grows every few ms — wait for a quiet gap, then
95
+ // highlight the settled source. hljs output is fully HTML-escaped (safe to inject).
96
+ const timer = setTimeout(() => {
97
+ ensureLanguage(lang).then((hljs) => {
98
+ if (!hljs || cancelled) return;
99
+ try {
100
+ const out = hljs.highlight(src, { language: lang, ignoreIllegals: true });
101
+ if (!cancelled) setHl({ src, html: out.value });
102
+ } catch {
103
+ /* stay plain */
104
+ }
105
+ });
106
+ }, 200);
107
+ return () => { cancelled = true; clearTimeout(timer); };
108
+ }, [src, lang]);
109
+
110
+ const html = hl && hl.src === src ? hl.html : null;
111
+ const label = String(language || '').toLowerCase();
112
+ return (
113
+ <pre className={'wbx-code' + (className ? ' ' + className : '')}>
114
+ {label ? <span className="wbx-code-lang" aria-hidden="true">{label}</span> : null}
115
+ {html != null
116
+ ? <code className={'hljs language-' + label} dangerouslySetInnerHTML={{ __html: html }} />
117
+ : <code className={label ? 'language-' + label : undefined}>{src}</code>}
118
+ </pre>
119
+ );
120
+ }
@@ -0,0 +1,75 @@
1
+ // Composer — extracted from HarnessRouter's workbench composer (textarea + bottom action row).
2
+ // Enter sends (Shift+Enter for a newline). Auto-grows to fit content, capped at maxRows, then
3
+ // scrolls (HR behavior; pass autoGrow={false} for a fixed-height textarea).
4
+ //
5
+ // Slots:
6
+ // attachments node rendered ABOVE the textarea (attachment card row)
7
+ // accessoriesLeft nodes before the flexible spacer (attach button, model select, mic, …)
8
+ // accessoriesRight nodes after the spacer, before the send button
9
+ // renderSend() replaces the default send button entirely
10
+ // classNames { root, input, row } — each REPLACES the default class when provided,
11
+ // so a product can restyle wholesale without fighting the package CSS
12
+ import React, { useEffect, useRef } from 'react';
13
+ import { IcSend } from './icons.jsx';
14
+
15
+ // Takes a single `props` object (destructured inside) so TSX consumers don't infer every slot
16
+ // as required.
17
+ export function Composer(props) {
18
+ const {
19
+ value,
20
+ onChange,
21
+ onSend,
22
+ disabled = false,
23
+ sendDisabled,
24
+ placeholder,
25
+ rows = 1,
26
+ autoGrow = true,
27
+ maxRows = 15,
28
+ attachments,
29
+ accessoriesLeft,
30
+ accessoriesRight,
31
+ renderSend,
32
+ classNames = {},
33
+ inputRef,
34
+ } = props;
35
+ const ownRef = useRef(null);
36
+ const taRef = inputRef || ownRef;
37
+
38
+ // Auto-grow the composer to fit its content, capped at ~maxRows rows (then it scrolls).
39
+ useEffect(() => {
40
+ if (!autoGrow) return;
41
+ const el = taRef.current; if (!el) return;
42
+ el.style.height = 'auto';
43
+ const cs = getComputedStyle(el);
44
+ const lh = parseFloat(cs.lineHeight) || 21;
45
+ const max = lh * maxRows + parseFloat(cs.paddingTop || '0') + parseFloat(cs.paddingBottom || '0');
46
+ el.style.height = Math.min(el.scrollHeight, max) + 'px';
47
+ el.style.overflowY = el.scrollHeight > max ? 'auto' : 'hidden';
48
+ }, [value, autoGrow, maxRows, taRef]);
49
+
50
+ return (
51
+ <div className={classNames.root ?? 'wbx-composer'}>
52
+ {attachments}
53
+ <textarea
54
+ ref={taRef}
55
+ className={classNames.input ?? 'wbx-composer-input'}
56
+ placeholder={placeholder}
57
+ value={value}
58
+ disabled={disabled}
59
+ rows={rows}
60
+ onChange={(e) => onChange(e.target.value)}
61
+ onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSend(); } }}
62
+ />
63
+ <div className={classNames.row ?? 'wbx-composer-row'}>
64
+ {accessoriesLeft}
65
+ <span style={{ flex: 1 }} />
66
+ {accessoriesRight}
67
+ {renderSend ? renderSend() : (
68
+ <button type="button" className="uic-send" disabled={sendDisabled} onClick={() => onSend()} aria-label="Send message">
69
+ <IcSend />
70
+ </button>
71
+ )}
72
+ </div>
73
+ </div>
74
+ );
75
+ }