import { useState, useEffect, useRef, useMemo, useCallback, type ClipboardEvent, type DragEvent, type KeyboardEvent, } from "react"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import { X, Send, Square, Code, Eye, Plus, Loader, BarChart3, Sun, Moon, Undo2, AlertTriangle, RotateCcw, Wrench, FolderOpen, Cpu, Database, Columns2, Check, Paperclip, SlidersHorizontal, Crosshair, ShieldCheck, ChevronDown, ChevronUp, } from "lucide-react"; import type { UIMessage } from "ai"; import type { HocuspocusProvider } from "@hocuspocus/provider"; import type { EmbedStore } from "../editor/embeds/embed-store"; import type { EmbedDataStore } from "../editor/embeds/embed-data-store"; import type { EmbedVersion, EmbedVersionStore } from "../editor/embeds/embed-versions"; import { draftWorkspace, isDraftDirty, type EmbedDraft, type EmbedDraftStore, } from "../editor/embeds/embed-drafts"; import type { EmbedChatStore } from "../editor/embeds/embed-history"; import { buildDoc } from "../editor/embeds/build-doc"; import { checkFixPrompt, createAutoFixGuard, fixPrompt, followUpPrompts, pickedContext, pickedLabel, starterPrompts, type PickedElement, } from "../editor/embeds/embed-suggestions"; import { applyConfigValues, configValues, parseEmbedConfig, textFieldFor, type ConfigValue, } from "../editor/embeds/embed-config"; import { detectPastedTable, pastedTableContent, uniqueDataName } from "../editor/embeds/data-insights"; import { progressLabel, streamingProgress } from "../editor/embeds/stream-progress"; import { useEmbedChat } from "../hooks/useEmbedChat"; import { useEmbedData } from "../hooks/useEmbedData"; import { useTheme } from "../hooks/useTheme"; import { useStudioPresence } from "../hooks/useStudioPresence"; import { useEmbedCheck } from "../hooks/useEmbedCheck"; import { isToolPart, normalizeToolPart } from "../utils/ai-tool-parts"; import { describeChatError } from "../utils/chat-errors"; import { FilesSidebar } from "./FilesSidebar"; import { EmbedCodeView } from "./embed-studio/EmbedCodeView"; import { CodeDiff } from "./embed-studio/CodeDiff"; import { DataDrawer } from "./embed-studio/DataDrawer"; import { TweakPanel } from "./embed-studio/TweakPanel"; interface EmbedStudioProps { src: string; embedStore: EmbedStore | null; dataStore?: EmbedDataStore | null; versions?: EmbedVersionStore | null; drafts: EmbedDraftStore | null; chats?: EmbedChatStore | null; /** The chart has no node in the article yet ("Insert into article"). */ isNew: boolean; /** Sent once on open (the launcher's description). */ initialPrompt?: string; provider?: HocuspocusProvider | null; modelRef: React.RefObject; /** Display name of the model the studio talks to (header pill). */ modelLabel?: string; userId: string; /** Display name stamped on versions and drafts. */ authorName?: string; onClose: () => void; /** Publish the draft into the article. Returns false when nothing was applied. */ onApply: (src: string) => boolean; /** Drop the draft; for a new chart, also its versions and conversation. */ onDiscard: (src: string) => void; /** * Invoked when the agent chooses a descriptive filename for a brand * new chart. Parent lifts the new src into its own state so subsequent * actions (apply, close, reopen) reference the renamed file. */ onRename?: (oldSrc: string, newSrc: string) => void; /** * Invoked when the user picks a different chart from the sidebar. * Parent is responsible for updating the studio's `src` and rotating * the React key on this component so the conversation reloads. */ onSelectChart?: (name: string) => void; } const EMBED_TOOL_LABELS: Record = { createEmbed: ["Creating chart...", "Created chart"], patchEmbed: ["Updating chart...", "Updated chart"], readEmbed: ["Reading chart...", "Read chart"], listDataFiles: ["Listing data files...", "Listed data files"], readDataFile: ["Reading data file...", "Read data file"], }; /** Preview widths: the article column, a Wide embed, a small phone. */ export const PREVIEW_WIDTHS = { article: { label: "Article", px: 680 }, wide: { label: "Wide", px: 1100 }, mobile: { label: "360", px: 360 }, } as const; type PreviewWidth = keyof typeof PREVIEW_WIDTHS; /** How long after a turn ends a preview error still triggers the automatic fix. */ const AUTO_FIX_WINDOW_MS = 6000; type CompareTarget = number | "article"; function embedToolLabel(name: string, state: string): string { const pair = EMBED_TOOL_LABELS[name]; if (!pair) return name; return state === "result" ? pair[1] : pair[0]; } function toolSubtitle( name: string, input: unknown, ): string | null { if (!input || typeof input !== "object") return null; const args = input as Record; switch (name) { case "createEmbed": return typeof args.title === "string" ? String(args.title) : null; case "readDataFile": return typeof args.name === "string" ? String(args.name) : null; case "patchEmbed": { const search = typeof args.search === "string" ? args.search : ""; const firstLine = search.split("\n")[0]?.trim() ?? ""; return firstLine ? firstLine.slice(0, 60) : null; } default: return null; } } function MessageBubble({ message, self }: { message: UIMessage; self?: string }) { const isUser = message.role === "user"; const author = (message.metadata as { author?: string } | undefined)?.author; return (
{isUser && author && author !== self && {author}} {message.parts.map((part, i) => { if (part.type === "text") { return (
{isUser ? part.text : ( {part.text} )}
); } if (isToolPart(part)) { const tool = normalizeToolPart(part); if (!tool) return null; const subtitle = toolSubtitle(tool.toolName, tool.input); const isDone = tool.state === "result"; return (
{!isDone && } {embedToolLabel(tool.toolName, tool.state)} {subtitle && ( {subtitle} )}
); } return null; })}
); } function EmbedAgentStatus({ messages }: { messages: UIMessage[] }) { const last = messages[messages.length - 1]; if (!last) return null; if (last.role === "assistant") { const progress = streamingProgress(last); if (progress) { return (
{progressLabel(progress)}
); } const parts = last.parts ?? []; const runningTools = parts .map((p) => normalizeToolPart(p)) .filter((t): t is NonNullable => t !== null && t.state !== "result") .map((t) => t.toolName); if (runningTools.length > 0) { const pair = EMBED_TOOL_LABELS[runningTools[runningTools.length - 1]]; const text = pair ? pair[0] : runningTools[runningTools.length - 1]; return (
{text}
); } const hasText = parts.some((p: any) => p.type === "text" && p.text?.trim()); if (hasText) return null; } return (
Thinking...
); } function VersionChip({ version, latest, previous, comparing, disabled, onCompare, onRestore, }: { version: EmbedVersion; latest: EmbedVersion | null; previous: EmbedVersion | null; comparing: CompareTarget | null; disabled: boolean; onCompare: (target: CompareTarget | null) => void; onRestore: (n: number) => void; }) { const isLatest = latest?.n === version.n; // Comparing the newest version means looking at what came before it. const target = isLatest ? previous?.n ?? null : version.n; const on = target !== null && comparing === target; return (
v{version.n} {isLatest && current} {!isLatest && ( )} {target !== null && ( )}
); } export function EmbedStudio({ src, embedStore, dataStore = null, versions = null, drafts, chats = null, isNew, initialPrompt, provider, modelRef, modelLabel, userId, authorName, onClose, onApply, onDiscard, onRename, onSelectChart, }: EmbedStudioProps) { const { isDark, primaryColor } = useTheme(); // The banner is a special embed: it renders edge-to-edge in a 5:2 box (the // hero) rather than as a height-reporting chart. The studio must preview it // the same way (fullBleed srcdoc + constrained 5:2 stage) so it's WYSIWYG. const isBanner = src === "banner.html"; const [appliedHtml, setAppliedHtml] = useState(""); const [draft, setDraft] = useState(undefined); const [viewMode, setViewMode] = useState<"preview" | "code">("preview"); const [previewWidth, setPreviewWidth] = useState("article"); const [previewDark, setPreviewDark] = useState(isDark); const [compare, setCompare] = useState(null); const [previewError, setPreviewError] = useState<{ message: string; at: number } | null>(null); const [versionList, setVersionList] = useState([]); const [mobilePane, setMobilePane] = useState<"chat" | "preview">("chat"); const [filesOpen, setFilesOpen] = useState(false); const [dataOpen, setDataOpen] = useState(false); const [dataSelected, setDataSelected] = useState(null); const [attached, setAttached] = useState([]); const [attachError, setAttachError] = useState(null); const [dropActive, setDropActive] = useState(false); const [closePrompt, setClosePrompt] = useState(false); const [notice, setNotice] = useState(null); const [tweakOpen, setTweakOpen] = useState(false); const [tweakValues, setTweakValues] = useState>({}); const [inspecting, setInspecting] = useState(false); const [picked, setPicked] = useState(null); const [labelDraft, setLabelDraft] = useState(""); const [checkOpen, setCheckOpen] = useState(false); const messagesEndRef = useRef(null); const textareaRef = useRef(null); // Iframe double-buffer (also the two sides of the before/after compare). const frameA = useRef(null); const frameB = useRef(null); const [activeFrame, setActiveFrame] = useState<"a" | "b">("a"); const activeRef = useRef<"a" | "b">("a"); activeRef.current = activeFrame; // Which srcdoc generation each frame holds: errors only count when they // come from the newest one. const genRef = useRef(0); const slotGenRef = useRef<{ a: number; b: number }>({ a: 0, b: 0 }); const skipReloadRef = useRef(null); const previewDarkRef = useRef(previewDark); previewDarkRef.current = previewDark; // The preview follows the editor theme until the user flips it locally. useEffect(() => { setPreviewDark(isDark); }, [isDark]); const authorRef = useRef(authorName); authorRef.current = authorName; const workspace = useMemo( () => (drafts && embedStore ? draftWorkspace(drafts, embedStore, () => authorRef.current) : null), [drafts, embedStore], ); const peers = useStudioPresence(provider, src); const data = useEmbedData({ dataStore, userId }); const chat = useEmbedChat({ embedStore, workspace, dataStore, versions, chats, allowRename: isNew, src, modelRef, userId, authorName, isDark: previewDark, onRename, onMeta: (target, meta) => drafts?.setMeta(target, meta), }); // Applied HTML (what the article shows) and the draft on top of it. useEffect(() => { if (!embedStore || !src) return; setAppliedHtml(embedStore.get(src)); return embedStore.observeKey(src, setAppliedHtml); }, [embedStore, src]); useEffect(() => { if (!drafts || !src) return; setDraft(drafts.get(src)); return drafts.observe(() => setDraft(drafts.get(src))); }, [drafts, src]); const html = draft?.html ?? appliedHtml; const dirty = isDraftDirty(draft); const configFields = useMemo(() => parseEmbedConfig(html), [html]); // The panel shows the chart's saved values; pending slider moves win // until they are written back. useEffect(() => { setTweakValues(configFields ? configValues(configFields) : {}); }, [configFields]); const check = useEmbedCheck(); useEffect(() => { if (!versions || !src) { setVersionList([]); return; } setVersionList(versions.list(src)); return versions.observe(src, () => setVersionList(versions.list(src))); }, [versions, src]); const latestVersion = versionList[versionList.length - 1] ?? null; const undoTarget = useMemo( () => (versions && src && versionList.length ? versions.undoTarget(src) : null), // versionList is the change signal for the store. // eslint-disable-next-line react-hooks/exhaustive-deps [versions, src, versionList], ); // --- Compare -------------------------------------------------------------- const beforeHtml = compare === null ? "" : compare === "article" ? appliedHtml : versionList.find((v) => v.n === compare)?.html ?? ""; const comparing = compare !== null && !!beforeHtml && !!html; const compareLabel = compare === "article" ? "Article" : compare !== null ? `v${compare}` : ""; const defaultCompareTarget: CompareTarget | null = dirty && appliedHtml ? "article" : undoTarget ? undoTarget.n : null; // Build srcdoc. Banner previews use fullBleed so the content fills the // iframe edge-to-edge, matching FrontmatterHero and the published output. // The theme is pushed with setTheme afterwards, so toggling it never // reloads the chart. const docFor = useCallback( (fragment: string) => fragment ? buildDoc(fragment, { isDark: previewDarkRef.current, primaryColor, fullBleed: isBanner, studio: true }) : "", [primaryColor, isBanner], ); const srcdoc = useMemo(() => docFor(html), [docFor, html]); const beforeDoc = useMemo(() => (comparing ? docFor(beforeHtml) : ""), [docFor, comparing, beforeHtml]); useEffect(() => { const a = frameA.current; const b = frameB.current; if (beforeDoc && srcdoc) { // Compare: A shows the "before", B the current version. Only B's // errors count. genRef.current += 1; slotGenRef.current = { a: -1, b: genRef.current }; setPreviewError(null); if (a) a.srcdoc = beforeDoc; if (b) b.srcdoc = srcdoc; setActiveFrame("b"); return; } if (!srcdoc) return; // A tweak is already live in the frame (embedConfig message): writing // it back into the HTML must not reload the chart. if (skipReloadRef.current !== null && skipReloadRef.current === htmlRef.current) { skipReloadRef.current = null; return; } const next = activeRef.current === "a" ? "b" : "a"; const frame = next === "a" ? a : b; genRef.current += 1; slotGenRef.current[next] = genRef.current; setPreviewError(null); if (frame) frame.srcdoc = srcdoc; }, [srcdoc, beforeDoc]); const postTheme = useCallback( (frame: HTMLIFrameElement | null) => { try { frame?.contentWindow?.postMessage( { type: "setTheme", theme: previewDarkRef.current ? "dark" : "light", primaryColor }, "*", ); } catch { // Frame not ready yet: onLoad sends it again. } }, [primaryColor], ); useEffect(() => { postTheme(frameA.current); postTheme(frameB.current); }, [previewDark, postTheme]); const inspectingRef = useRef(inspecting); inspectingRef.current = inspecting; const handleFrameLoad = useCallback( (slot: "a" | "b") => { const frame = slot === "a" ? frameA.current : frameB.current; postTheme(frame); if (inspectingRef.current) frame?.contentWindow?.postMessage({ type: "embedInspect", on: true }, "*"); if (slot !== activeRef.current && slotGenRef.current[slot] === genRef.current) { setActiveFrame(slot); } }, [postTheme], ); // Errors relayed by the studio reporter inside the preview iframe. useEffect(() => { const onMessage = (e: MessageEvent) => { const d = e.data as { type?: string; message?: unknown; pick?: PickedElement } | null; if (!d || (d.type !== "embedError" && d.type !== "embedPick" && d.type !== "embedInspectExit")) return; const slot = e.source === frameA.current?.contentWindow ? "a" : e.source === frameB.current?.contentWindow ? "b" : null; if (!slot || slotGenRef.current[slot] !== genRef.current) return; if (d.type === "embedPick") { if (d.pick && typeof d.pick.tag === "string") { setPicked(d.pick); setLabelDraft(d.pick.text ?? ""); setMobilePane("chat"); } setInspecting(false); return; } if (d.type === "embedInspectExit") { setInspecting(false); return; } const message = String(d.message ?? "Unknown error").slice(0, 500); setPreviewError((prev) => prev ?? { message, at: Date.now() }); }; window.addEventListener("message", onMessage); return () => window.removeEventListener("message", onMessage); }, []); // Auto-scroll messages useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [chat.messages]); useEffect(() => { if (!notice) return; const t = setTimeout(() => setNotice(null), 2500); return () => clearTimeout(t); }, [notice]); // Dev-only hook: let demo scripts inject a fake assistant reply into // the embed chat so the recording shows the agent "responding" // without waiting for a real LLM round-trip. useEffect(() => { if (!import.meta.env.DEV) return; const handler = (event: Event) => { const detail = (event as CustomEvent).detail as | { messages?: UIMessage[] } | undefined; if (Array.isArray(detail?.messages)) { chat.setMessages(detail.messages); } }; window.addEventListener("__demo-embed-chat", handler); return () => window.removeEventListener("__demo-embed-chat", handler); }, [chat]); // --- Sending, automatic fix ------------------------------------------- const guardRef = useRef(createAutoFixGuard(1)); const htmlRef = useRef(html); htmlRef.current = html; const htmlAtSendRef = useRef(html); const autoFixArmedRef = useRef(false); const attachedRef = useRef(attached); attachedRef.current = attached; const pickedRef = useRef(picked); pickedRef.current = picked; const tweakTurnRef = useRef(null); const send = useCallback( (text: string, manual = true) => { const trimmed = text.trim(); if (!trimmed || chat.isLoading) return; guardRef.current.onSend(manual); htmlAtSendRef.current = htmlRef.current; setCompare(null); setMobilePane("chat"); const files = manual ? attachedRef.current : []; const pick = manual ? pickedRef.current : null; let message = trimmed; if (pick) message += `\n\n${pickedContext(pick)}`; if (files.length) message += `\n\n(Attached data: ${files.join(", ")})`; tweakTurnRef.current = null; chat.sendMessage(message); if (files.length) setAttached([]); if (pick) setPicked(null); }, [chat], ); // A turn that changed the chart arms one automatic fix for a few seconds. const wasLoadingRef = useRef(false); useEffect(() => { if (wasLoadingRef.current && !chat.isLoading && htmlRef.current !== htmlAtSendRef.current) { void check.run(htmlRef.current, isBanner); autoFixArmedRef.current = true; const t = setTimeout(() => { autoFixArmedRef.current = false; }, AUTO_FIX_WINDOW_MS); wasLoadingRef.current = chat.isLoading; return () => clearTimeout(t); } wasLoadingRef.current = chat.isLoading; // check.run is stable; isBanner never changes for a studio instance. // eslint-disable-next-line react-hooks/exhaustive-deps }, [chat.isLoading]); useEffect(() => { if (!previewError || chat.isLoading || comparing) return; if (!autoFixArmedRef.current || chat.error) return; autoFixArmedRef.current = false; if (guardRef.current.take()) send(fixPrompt(previewError.message), false); }, [previewError, chat.isLoading, chat.error, comparing, send]); const handleSend = useCallback(() => { const text = chat.input; if (!text.trim() || chat.isLoading) return; send(text); chat.setInput(""); if (textareaRef.current) textareaRef.current.style.height = "auto"; }, [chat, send]); // The launcher's description is sent once the studio is open. const initialSentRef = useRef(false); useEffect(() => { if (!initialPrompt || initialSentRef.current || chat.messages.length > 0) return; initialSentRef.current = true; send(initialPrompt); }, [initialPrompt, chat.messages.length, send]); // --- Tweak panel: live values, written back as a "manual tweak" version --- const tweakTimerRef = useRef | null>(null); const tweakValuesRef = useRef(tweakValues); tweakValuesRef.current = tweakValues; const postToActiveFrame = useCallback((message: unknown) => { const frame = activeRef.current === "a" ? frameA.current : frameB.current; try { frame?.contentWindow?.postMessage(message, "*"); } catch { // Frame reloading: the next commit reloads it with the new values. } }, []); const commitTweaks = useCallback(() => { tweakTimerRef.current = null; if (!workspace) return; const target = chat.currentSrc(); const current = htmlRef.current; const next = applyConfigValues(current, tweakValuesRef.current); if (next === current) return; skipReloadRef.current = next; htmlRef.current = next; workspace.write(target, next); if (!tweakTurnRef.current) tweakTurnRef.current = `tweak-${Date.now().toString(36)}`; versions?.record(target, next, { kind: "tweak", author: authorName, turnId: tweakTurnRef.current, note: "Manual tweak", }); }, [workspace, chat, versions, authorName]); const handleTweak = useCallback( (key: string, value: ConfigValue) => { setTweakValues((prev) => ({ ...prev, [key]: value })); tweakValuesRef.current = { ...tweakValuesRef.current, [key]: value }; postToActiveFrame({ type: "embedConfig", values: { [key]: value } }); if (tweakTimerRef.current) clearTimeout(tweakTimerRef.current); tweakTimerRef.current = setTimeout(commitTweaks, 600); }, [postToActiveFrame, commitTweaks], ); useEffect( () => () => { if (tweakTimerRef.current) { clearTimeout(tweakTimerRef.current); commitTweaks(); } }, // Flush a pending tweak when the studio closes. // eslint-disable-next-line react-hooks/exhaustive-deps [], ); // --- Inspect mode ---------------------------------------------------------- const toggleInspect = useCallback(() => { const next = !inspectingRef.current; setInspecting(next); postToActiveFrame({ type: "embedInspect", on: next }); if (next) { setViewMode("preview"); setMobilePane("preview"); } }, [postToActiveFrame]); const pickedTextField = picked && picked.ownText ? textFieldFor(configFields, picked.text) : null; const handleKeyDown = useCallback( (e: KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); } }, [handleSend], ); const handleTextareaInput = useCallback(() => { const ta = textareaRef.current; if (ta) { ta.style.height = "auto"; ta.style.height = Math.min(ta.scrollHeight, 160) + "px"; } }, []); const handleNewConversation = useCallback(() => { if (chat.messages.length === 0) return; if (!window.confirm("Clear this chart's conversation for everyone? The chart and its versions stay.")) return; chat.clearMessages(); }, [chat]); // --- Data: drop on the chat, paste a table ------------------------------- const attach = useCallback((names: string[]) => { if (!names.length) return; setAttached((prev) => Array.from(new Set([...prev, ...names]))); }, []); const handleDropFiles = useCallback( async (files: FileList | File[]) => { setAttachError(null); const results = await data.uploadFiles(files); const failed = results.find((r) => !r.ok); if (failed?.error) setAttachError(failed.error); attach(results.filter((r) => r.ok && r.name).map((r) => r.name!)); }, [data, attach], ); const handlePaste = useCallback( async (e: ClipboardEvent) => { const text = e.clipboardData.getData("text/plain"); const table = detectPastedTable(text); if (!table) return; e.preventDefault(); const name = uniqueDataName("pasted-data", table.ext, (n) => !!data.getFile(n)); const content = pastedTableContent(text, table); const result = await data.uploadFile(new File([content], name, { type: "text/plain" })); if (!result.ok) { setAttachError(result.error ?? "Could not attach the pasted table"); return; } setAttachError(null); attach([name]); setNotice(`Pasted table saved as ${name} (${table.rows} rows, ${table.columns.length} columns)`); }, [data, attach], ); const chatDropProps = { onDragOver: (e: DragEvent) => { if (!Array.from(e.dataTransfer.types).includes("Files")) return; e.preventDefault(); setDropActive(true); }, onDragLeave: (e: DragEvent) => { if (e.currentTarget === e.target) setDropActive(false); }, onDrop: (e: DragEvent) => { if (!e.dataTransfer.files?.length) return; e.preventDefault(); setDropActive(false); void handleDropFiles(e.dataTransfer.files); }, }; // --- Versions, apply, close ------------------------------------------------ const writeHtml = useCallback( (next: string) => { workspace?.write(chat.currentSrc(), next); }, [workspace, chat], ); const handleRestore = useCallback( (n: number) => { if (!versions) return; const v = versions.restore(chat.currentSrc(), n, { author: authorName }); if (v) writeHtml(v.html); setCompare(null); }, [versions, chat, authorName, writeHtml], ); const handleUndo = useCallback(() => { if (!versions) return; const v = versions.undo(chat.currentSrc(), authorName); if (v) writeHtml(v.html); setCompare(null); }, [versions, chat, authorName, writeHtml]); const canApply = !chat.isLoading && !!html.trim() && (dirty || (isNew && !!draft)); const handleApply = useCallback(() => { if (!canApply) return false; const ok = onApply(chat.currentSrc()); if (ok) setNotice(isNew ? "Inserted into the article" : "Applied to the article"); return ok; }, [canApply, onApply, chat, isNew]); const requestClose = useCallback(() => { if (dirty || (isNew && draft && html.trim())) { setClosePrompt(true); return; } // Nothing unapplied: drop an empty or identical draft silently. if (draft) drafts?.discard(chat.currentSrc()); onClose(); }, [dirty, isNew, draft, html, drafts, chat, onClose]); const turnVersions = useMemo(() => { const map = new Map(); for (const v of versionList) if (v.turnId) map.set(v.turnId, v); return map; }, [versionList]); const previousOf = useCallback( (v: EmbedVersion): EmbedVersion | null => { const i = versionList.findIndex((x) => x.n === v.n); return i > 0 ? versionList[i - 1] : null; }, [versionList], ); // --- Render helpers --------------------------------------------------- const frameStyle = (slot: "a" | "b"): React.CSSProperties => comparing ? { border: "none", width: "100%", height: "100%", position: "relative" } : { position: "absolute", inset: 0, border: "none", width: "100%", height: "100%", transition: "opacity 120ms ease", opacity: activeFrame === slot ? 1 : 0, zIndex: activeFrame === slot ? 2 : 1, }; const hasChart = html.trim().length > 0; const errorInfo = chat.error ? describeChatError(chat.error.message) : null; const followUps = useMemo( () => (hasChart ? followUpPrompts(html, { isBanner }) : []), [html, hasChart, isBanner], ); const starters = useMemo( () => starterPrompts({ isBanner, dataFiles: data.files.map((f) => f.name) }), [isBanner, data.files], ); const lastMessage = chat.messages[chat.messages.length - 1]; const showFollowUps = !chat.isLoading && !chat.error && hasChart && lastMessage?.role === "assistant"; const kindLabel = isBanner ? "banner" : "chart"; const applyLabel = isNew ? "Insert into article" : "Apply to article"; const renderMessages = () => { let turnId: string | undefined; return chat.messages.map((msg, i) => { if (msg.role === "user") turnId = msg.id; const next = chat.messages[i + 1]; const endsTurn = msg.role === "assistant" && (next ? next.role === "user" : !chat.isLoading); const version = endsTurn && turnId ? turnVersions.get(turnId) : undefined; return (
{version && ( )}
); }); }; const widthPx = PREVIEW_WIDTHS[previewWidth].px; const stageMax = isBanner ? Math.min(widthPx, 980) : comparing ? widthPx * 2 + 16 : widthPx; const status = isNew ? hasChart ? "Not in the article yet" : null : dirty ? "Draft: changes not applied" : hasChart ? "Same as the article" : null; return (
{/* Header */}
{/* Body: split panel */}
{ setFilesOpen(false); onSelectChart(name); } : undefined } onSelectDataFile={(name) => { if (!name) { setDataOpen(false); return; } setDataSelected(name); setDataOpen(true); setFilesOpen(false); setMobilePane("preview"); }} onUploadFiles={data.uploadFiles} onRemoveDataFile={data.removeFile} />
{filesOpen && ( ))}
{!isBanner && (

Drop a CSV or JSON file here, or paste a table into the message box.

)}
)} {renderMessages()} {chat.isLoading && chat.messages.length > 0 && ( )} {showFollowUps && followUps.length > 0 && (
{followUps.map((s) => ( ))}
)}
{/* Input */}
{errorInfo && (
)} {picked && (
{pickedTextField && (
{ e.preventDefault(); if (!labelDraft.trim()) return; handleTweak(pickedTextField.key, labelDraft.trim()); setPicked(null); }} > setLabelDraft(e.target.value)} />
)}
)} {(attached.length > 0 || attachError) && (
{attached.map((name) => ( ))} {attachError && {attachError}}
)}