reifyui 0.3.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,125 @@
1
+ // Type declarations for `reifyui/slides`.
2
+ //
3
+ // Hand-authored, like the root index: the source is plain JSX, so there is nothing to infer from.
4
+ // The deck model below is the contract — an agent writing a deck and this renderer drawing one are
5
+ // agreeing on exactly these shapes, so it is worth stating them precisely rather than as `any`.
6
+ import type { ComponentType, CSSProperties } from 'react';
7
+
8
+ // ── deck model ────────────────────────────────────────────────────────────────────────────────
9
+ /** Absolute placement on the fixed 1920x1080 stage. Every element carries one. */
10
+ export interface Frame {
11
+ x: number;
12
+ y: number;
13
+ w: number;
14
+ h: number;
15
+ rotation?: number;
16
+ }
17
+
18
+ /** A span of text plus its marks. `link` is an object mark; the rest are plain strings. */
19
+ export interface Run {
20
+ text: string;
21
+ marks?: Array<'bold' | 'italic' | 'underline' | 'code' | { link: string }>;
22
+ }
23
+
24
+ export type ElementType = 'text' | 'image' | 'shape' | 'table' | 'chart' | 'diagram' | 'code';
25
+
26
+ export interface SlideElement {
27
+ id: string;
28
+ type: ElementType;
29
+ frame: Frame;
30
+ style?: CSSProperties & { fontSize?: number; align?: 'left' | 'center' | 'right'; fill?: string };
31
+ /** Shape depends on `type`: text/bullets carry `runs`, images carry `src`, charts carry `spec`. */
32
+ content?: Record<string, unknown> & { role?: string; runs?: Run[]; src?: string; alt?: string };
33
+ }
34
+
35
+ export interface Slide {
36
+ id: string;
37
+ layout?: string;
38
+ background?: { color?: string; image?: string };
39
+ notes?: string;
40
+ elements?: SlideElement[];
41
+ }
42
+
43
+ export interface Theme {
44
+ palette?: { bg?: string; ink?: string; mute?: string; brand?: string; accent?: string };
45
+ fonts?: { head?: string; body?: string };
46
+ }
47
+
48
+ export interface Deck {
49
+ meta?: { title?: string; [k: string]: unknown };
50
+ stage?: { width: number; height: number };
51
+ theme?: Theme;
52
+ slides?: Slide[];
53
+ }
54
+
55
+ /** Rewrites an element's `src` before it is fetched — point workspace-relative paths at your API. */
56
+ export type ResolveSrc = (src: string) => string;
57
+
58
+ // ── rendering ─────────────────────────────────────────────────────────────────────────────────
59
+ /** The theme as CSS custom properties (`--sl-bg`, `--sl-body`, ...), for spreading into a style. */
60
+ export function themeVars(theme?: Theme): CSSProperties;
61
+
62
+ export interface SlideStageProps {
63
+ slide?: Slide;
64
+ theme?: Theme;
65
+ resolveSrc?: ResolveSrc;
66
+ selectedId?: string | null;
67
+ onSelectElement?: (id: string) => void;
68
+ }
69
+
70
+ /** One slide at true 1920x1080. Scale it yourself — used by SlideView, EditorCanvas and print. */
71
+ export const SlideStage: ComponentType<SlideStageProps>;
72
+
73
+ export interface SlideViewProps extends SlideStageProps {
74
+ onDeselect?: () => void;
75
+ /** Drop the frame/shadow and render only the stage — for thumbnails and print pages. */
76
+ bare?: boolean;
77
+ }
78
+
79
+ /** A slide scaled to fit its container. The read-only renderer: thumbnails, previews, print. */
80
+ export const SlideView: ComponentType<SlideViewProps>;
81
+
82
+ /** A single element, unpositioned. Exported for hosts composing their own stage. */
83
+ export const ElementView: ComponentType<{ el: SlideElement; resolveSrc?: ResolveSrc }>;
84
+
85
+ // ── editing ───────────────────────────────────────────────────────────────────────────────────
86
+ /** A peer's cursor state, for multiplayer decorations. Omit `peers` for single-player. */
87
+ export interface Peer {
88
+ id: string;
89
+ name: string;
90
+ color: string;
91
+ sel?: { slideId: string; elId: string };
92
+ drag?: { elId: string; frame: Frame };
93
+ }
94
+
95
+ export interface EditorCanvasProps {
96
+ slide?: Slide;
97
+ theme?: Theme;
98
+ resolveSrc?: ResolveSrc;
99
+ selectedId?: string | null;
100
+ onSelect?: (id: string | null) => void;
101
+ /** A committed change to one element. The canvas never mutates the deck — the host owns state. */
102
+ onPatchElement?: (elementId: string, patch: Partial<SlideElement>) => void;
103
+ onDeleteElement?: (elementId: string) => void;
104
+ /** Fires continuously during a drag/resize, then with (null, null). For collab broadcast. */
105
+ onDragState?: (elementId: string | null, frame: Frame | null) => void;
106
+ peers?: Peer[];
107
+ /** Selection still works; nothing can be moved, resized, typed into or deleted. */
108
+ readOnly?: boolean;
109
+ }
110
+
111
+ /**
112
+ * Direct manipulation over the deck renderer: click-drag to move, corner handles to resize,
113
+ * double-click to edit text inline, Delete to remove, arrows to nudge (Shift for a coarse step).
114
+ * Every commit leaves as a typed patch, so undo, autosave and collaboration stay with the host.
115
+ */
116
+ export const EditorCanvas: ComponentType<EditorCanvasProps>;
117
+
118
+ // ── presenting ────────────────────────────────────────────────────────────────────────────────
119
+ /** Full-screen presentation with arrow/space navigation. Calls `onExit` on Escape. */
120
+ export const Presentation: ComponentType<{
121
+ deck?: Deck;
122
+ resolveSrc?: ResolveSrc;
123
+ startIndex?: number;
124
+ onExit?: () => void;
125
+ }>;
@@ -0,0 +1,10 @@
1
+ // Shared deck renderer + presentation (the Slides product's canvas — and,
2
+ // like SheetGrid, embeddable anywhere: studio Spaces can mount a deck later).
3
+ // IMPORT VIA SUBPATH ONLY ('@ui-core/src/slides/index.js'), NOT the ui-core
4
+ // root index: echarts/mermaid/highlight.js load lazily inside these
5
+ // components, and a root re-export would force every ui-core consumer (CG,
6
+ // Flowness) to resolve those deps at build time. See docs/slides-architecture.md.
7
+ export { SlideView, SlideStage, themeVars } from './SlideView.jsx';
8
+ export { ElementView } from './elements.jsx';
9
+ export { EditorCanvas } from './Editor.jsx';
10
+ export { Presentation } from './Presentation.jsx';
@@ -0,0 +1,37 @@
1
+ // Assistant-turn block state machine — extracted from HarnessRouter's workbench.
2
+ // An assistant turn is an ORDERED list of blocks appended as stream events arrive, so tool
3
+ // activity interleaves with prose in real time (never all tools hoisted to the top):
4
+ // { kind: 'text', text } — streamed prose
5
+ // { kind: 'tools', reasoning, steps: ToolStep[] } — a contiguous run of tool activity
6
+ // ToolStep: { name, args, result?, callId? }
7
+
8
+ export function withText(blocks, d) {
9
+ const out = blocks.slice(); const last = out[out.length - 1];
10
+ if (last && last.kind === 'text') out[out.length - 1] = { kind: 'text', text: last.text + d };
11
+ else out.push({ kind: 'text', text: d });
12
+ return out;
13
+ }
14
+
15
+ export function withReasoning(blocks, d) {
16
+ const out = blocks.slice(); const last = out[out.length - 1];
17
+ if (last && last.kind === 'tools') out[out.length - 1] = { ...last, reasoning: last.reasoning + d };
18
+ else out.push({ kind: 'tools', reasoning: d, steps: [] });
19
+ return out;
20
+ }
21
+
22
+ export function withStep(blocks, step) {
23
+ const out = blocks.slice(); const last = out[out.length - 1];
24
+ if (last && last.kind === 'tools') out[out.length - 1] = { ...last, steps: [...last.steps, step] };
25
+ else out.push({ kind: 'tools', reasoning: '', steps: [step] });
26
+ return out;
27
+ }
28
+
29
+ export function withResult(blocks, callId, output) {
30
+ return blocks.map((b) => (b.kind !== 'tools' ? b
31
+ : { ...b, steps: b.steps.map((t) => ((t.callId && t.callId === callId && t.result === undefined) ? { ...t, result: output } : t)) }));
32
+ }
33
+
34
+ /** All prose of an assistant message joined (for copy-to-clipboard etc.). */
35
+ export function asstText(a) {
36
+ return a.blocks.filter((b) => b.kind === 'text').map((b) => b.text).join('\n\n');
37
+ }
@@ -0,0 +1,55 @@
1
+ // Session-continuation store — extracted from HarnessRouter's workbench conv store.
2
+ // A module-level (per createConversationStore() instance) map of conversation state keyed by
3
+ // session id (or any stable key for a not-yet-allocated conversation), so:
4
+ // - switching conversations never destroys an optimistic user message or an in-flight stream
5
+ // - N concurrent turns all keep streaming into their own entries in the background
6
+ // - a broadcast/bus event source can write to the same entry the POST stream writes to
7
+ //
8
+ // State shape (extend via patches — unknown keys pass through):
9
+ // { msgs, busy, prevId, firstTurn, loaded }
10
+ // prevId is the last response id (previous_response_id chaining = session continuation).
11
+ import { useSyncExternalStore } from 'react';
12
+
13
+ export function createConversationStore(makeInitial) {
14
+ const initial = makeInitial || (() => ({ msgs: [], busy: false, prevId: null, firstTurn: true, loaded: false }));
15
+ const store = new Map();
16
+ const subs = new Map();
17
+
18
+ function get(key) {
19
+ let s = store.get(key);
20
+ if (!s) { s = initial(); store.set(key, s); }
21
+ return s;
22
+ }
23
+ function set(key, patch) {
24
+ const cur = get(key);
25
+ const p = typeof patch === 'function' ? patch(cur) : patch;
26
+ store.set(key, { ...cur, ...p });
27
+ subs.get(key)?.forEach((f) => f());
28
+ }
29
+ /** Rebind/seed a key directly (e.g. copy a new-conversation entry onto its real session id). */
30
+ function seed(key, state) { store.set(key, state); subs.get(key)?.forEach((f) => f()); }
31
+ /** Mutate the LAST assistant message of a conversation (streaming writes). */
32
+ function updateLastAssistant(key, fn) {
33
+ set(key, (s) => {
34
+ const out = s.msgs.slice();
35
+ for (let i = out.length - 1; i >= 0; i--) {
36
+ if (out[i].role === 'assistant') { const a = { ...out[i] }; fn(a); out[i] = a; break; }
37
+ }
38
+ return { msgs: out };
39
+ });
40
+ }
41
+ /** React hook: subscribe a component to one conversation's state. */
42
+ function use(key) {
43
+ return useSyncExternalStore(
44
+ (cb) => {
45
+ let set_ = subs.get(key);
46
+ if (!set_) { set_ = new Set(); subs.set(key, set_); }
47
+ set_.add(cb);
48
+ return () => { set_.delete(cb); };
49
+ },
50
+ () => get(key),
51
+ () => get(key),
52
+ );
53
+ }
54
+ return { get, set, seed, updateLastAssistant, use };
55
+ }
@@ -0,0 +1,122 @@
1
+ // OpenAI Responses SSE event parsing — extracted from HarnessRouter's chat client
2
+ // (harnessrouter/src/lib/chat.ts streamResponse). Transport-agnostic: the caller does the
3
+ // fetch/POST however it likes (BFF, broker, direct) and hands the response body (a
4
+ // ReadableStream) plus a handlers object here.
5
+ //
6
+ // Two layers:
7
+ // readSSEStream(body, onData) — raw SSE framing (blank-line separated, data: lines)
8
+ // createResponsesDispatcher(handlers) — native Responses event -> handler dispatch
9
+ // pumpResponsesStream(body, handlers) — both together; resolves to the response id
10
+ //
11
+ // Handlers (all optional):
12
+ // onCreated(responseId) response.created
13
+ // onSession(sessionId) response.created metadata.session_id (continuation)
14
+ // onReasoningDelta(text) response.reasoning_summary_text.delta
15
+ // onToolCall(name, args, callId) response.function_call_arguments.done (name + call_id
16
+ // captured from the matching output_item.added, keyed by
17
+ // output_index — the same pairing HR ships)
18
+ // onToolResult(callId, output) function_call_output items
19
+ // onTextDelta(text) response.output_text.delta
20
+ // onFile({container_id,file_id,filename}) container_file_citation annotations
21
+ // onDone(status, response) response.completed / .incomplete / .failed (a failed
22
+ // response's own status distinguishes user cancels)
23
+ // onError(message) error events
24
+
25
+ export function createResponsesDispatcher(h) {
26
+ // function_call name + call_id live on output_item.added; arguments finalize on .done — key by
27
+ // output_index. function_call_output (the tool result) carries the same call_id → pair them.
28
+ const fnByIdx = {};
29
+ const self = {
30
+ responseId: null,
31
+ dispatch(ev) {
32
+ const t = ev.type;
33
+ switch (t) {
34
+ case 'response.created': {
35
+ const resp = ev.response || {};
36
+ self.responseId = resp.id || self.responseId;
37
+ if (self.responseId) h.onCreated?.(self.responseId);
38
+ const sid = (resp.metadata && resp.metadata.session_id) || '';
39
+ if (sid) h.onSession?.(sid);
40
+ break;
41
+ }
42
+ case 'response.reasoning_summary_text.delta':
43
+ h.onReasoningDelta?.(ev.delta || '');
44
+ break;
45
+ case 'response.output_item.added': {
46
+ const item = ev.item || {};
47
+ if (item.type === 'function_call') {
48
+ fnByIdx[ev.output_index] = { name: item.name || 'tool', callId: item.call_id || '' };
49
+ } else if (item.type === 'function_call_output') {
50
+ h.onToolResult?.(item.call_id || '', String(item.output ?? ''));
51
+ }
52
+ break;
53
+ }
54
+ case 'response.function_call_arguments.done': {
55
+ const fn = fnByIdx[ev.output_index] || { name: 'tool', callId: '' };
56
+ h.onToolCall?.(fn.name, ev.arguments || '', fn.callId);
57
+ break;
58
+ }
59
+ case 'response.output_text.delta':
60
+ h.onTextDelta?.(ev.delta || '');
61
+ break;
62
+ case 'response.output_text.annotation.added': {
63
+ const a = ev.annotation || {};
64
+ if (a.type === 'container_file_citation') {
65
+ h.onFile?.({ container_id: a.container_id, file_id: a.file_id, filename: a.filename });
66
+ }
67
+ break;
68
+ }
69
+ case 'response.completed':
70
+ h.onDone?.('completed', ev.response);
71
+ break;
72
+ case 'response.incomplete':
73
+ h.onDone?.('incomplete', ev.response);
74
+ break;
75
+ case 'response.failed':
76
+ // the response object's own status distinguishes a user cancel ('cancelled')
77
+ // from a real failure — surface it so the UI can badge them differently
78
+ h.onDone?.((ev.response && ev.response.status) || 'failed', ev.response);
79
+ break;
80
+ case 'error':
81
+ h.onError?.(ev.message || 'stream error');
82
+ break;
83
+ default:
84
+ break;
85
+ }
86
+ },
87
+ };
88
+ return self;
89
+ }
90
+
91
+ /** Read an SSE body stream, calling onData(dataString) per frame (data: lines joined). */
92
+ export async function readSSEStream(body, onData) {
93
+ const reader = body.getReader();
94
+ const decoder = new TextDecoder();
95
+ let buf = '';
96
+ for (;;) {
97
+ const { value, done } = await reader.read();
98
+ if (done) break;
99
+ buf += decoder.decode(value, { stream: true });
100
+ let nl;
101
+ // SSE frames are separated by a blank line; each frame has one or more `data:` lines.
102
+ while ((nl = buf.indexOf('\n\n')) !== -1) {
103
+ const frame = buf.slice(0, nl);
104
+ buf = buf.slice(nl + 2);
105
+ const data = frame.split('\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join('');
106
+ if (!data) continue;
107
+ onData(data);
108
+ }
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Convenience: parse a Responses SSE body end-to-end, dispatching to handlers.
114
+ * Resolves to the response id (for previous_response_id chaining), or null.
115
+ */
116
+ export async function pumpResponsesStream(body, handlers) {
117
+ const d = createResponsesDispatcher(handlers);
118
+ await readSSEStream(body, (data) => {
119
+ try { d.dispatch(JSON.parse(data)); } catch { /* ignore malformed frame */ }
120
+ });
121
+ return d.responseId;
122
+ }
package/styles/slides.css CHANGED
@@ -23,3 +23,41 @@
23
23
  .sl-pp-btn:disabled { opacity: 0.35; cursor: default; }
24
24
  .sl-pp-count { font-size: 12.5px; color: #B9C0CF; padding: 0 6px; font-variant-numeric: tabular-nums; }
25
25
  .sl-pp-sep { width: 1px; height: 18px; background: rgba(255, 255, 255, 0.14); margin: 0 2px; }
26
+
27
+ /* ── EditorCanvas: selection, resize handles, inline text, peer decorations ──
28
+ These belong with the component, not with the app that mounts it: EditorCanvas
29
+ renders every one of these class names, so without them the editor has an
30
+ invisible selection and handles you cannot see to grab. Colors follow the same
31
+ `--sl-*`-with-fallback convention as the rest of this file, so the editor is
32
+ usable with no theme loaded and takes your brand the moment one is. */
33
+ .sl-editor-layer { cursor: default; }
34
+ .sl-sel-box {
35
+ position: absolute; pointer-events: none;
36
+ outline: 2px solid var(--sl-brand, #4F46E5); outline-offset: 0; border-radius: 2px;
37
+ }
38
+ .sl-sel-handle {
39
+ position: absolute; width: 11px; height: 11px; border-radius: 3px;
40
+ background: #fff; border: 2px solid var(--sl-brand, #4F46E5); pointer-events: auto;
41
+ box-shadow: 0 1px 4px rgba(15, 23, 42, .25);
42
+ }
43
+ /* Offset by half the handle so it straddles the corner it resizes. */
44
+ .sl-h-nw { left: -6px; top: -6px; cursor: nwse-resize; }
45
+ .sl-h-ne { right: -6px; top: -6px; cursor: nesw-resize; }
46
+ .sl-h-sw { left: -6px; bottom: -6px; cursor: nesw-resize; }
47
+ .sl-h-se { right: -6px; bottom: -6px; cursor: nwse-resize; }
48
+ .sl-text-edit {
49
+ position: absolute; z-index: 5; resize: none; overflow: hidden;
50
+ background: rgba(255, 255, 255, .96); color: #111827;
51
+ border: 2px solid var(--sl-brand, #4F46E5); border-radius: 4px; outline: none;
52
+ padding: 2px 4px; box-shadow: 0 8px 28px -6px rgba(15, 23, 42, .35);
53
+ }
54
+ /* Peers animate to their new frame; your own selection must not lag your pointer. */
55
+ .sl-peer-box {
56
+ position: absolute; pointer-events: none; border: 2px solid; border-radius: 3px;
57
+ transition: left 200ms ease, top 200ms ease, width 200ms ease, height 200ms ease;
58
+ }
59
+ .sl-peer-tag {
60
+ position: absolute; top: -22px; left: -2px; color: #fff;
61
+ font-size: 11px; font-weight: 600; padding: 2px 7px; border-radius: 6px 6px 6px 0;
62
+ white-space: nowrap;
63
+ }