scaling-swarms / frontend /src /components /EmbedStudio.tsx
tfrere's picture
tfrere HF Staff
Cursor
feat(embed-studio): tweak panel, inspect, automatic check, launcher, inline edit
4953bfd
Raw History Blame Contribute Delete
57.6 kB
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<string>; /** 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<string, [string, string]> = { 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<string, unknown>; 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 ( <div className={`es-message ${isUser ? "es-message--user" : "es-message--ai"}`}> {isUser && author && author !== self && <span className="es-message__author">{author}</span>} {message.parts.map((part, i) => { if (part.type === "text") { return ( <div key={i} className="es-message__text"> {isUser ? part.text : ( <ReactMarkdown remarkPlugins={[remarkGfm]}>{part.text}</ReactMarkdown> )} </div> ); } if (isToolPart(part)) { const tool = normalizeToolPart(part); if (!tool) return null; const subtitle = toolSubtitle(tool.toolName, tool.input); const isDone = tool.state === "result"; return ( <div key={i} className={`es-message__tool ${isDone ? "es-message__tool--done" : "es-message__tool--running"}`} > {!isDone && <Loader size={11} className="spin" />} <span className="es-message__tool-name"> {embedToolLabel(tool.toolName, tool.state)} </span> {subtitle && ( <span className="es-message__tool-subtitle">{subtitle}</span> )} </div> ); } return null; })} </div> ); } 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 ( <div className="chat-panel__thinking"> <Loader size={13} className="spin" /> <span className="shimmer-text">{progressLabel(progress)}</span> </div> ); } const parts = last.parts ?? []; const runningTools = parts .map((p) => normalizeToolPart(p)) .filter((t): t is NonNullable<typeof t> => 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 ( <div className="chat-panel__thinking"> <Loader size={13} className="spin" /> <span className="shimmer-text">{text}</span> </div> ); } const hasText = parts.some((p: any) => p.type === "text" && p.text?.trim()); if (hasText) return null; } return ( <div className="chat-panel__thinking"> <Loader size={13} className="spin" /> <span className="shimmer-text">Thinking...</span> </div> ); } 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 ( <div className="es-version" aria-label={`Version ${version.n}`}> <span className="es-version__n">v{version.n}</span> {isLatest && <span className="es-version__current">current</span>} {!isLatest && ( <button type="button" className="es-version__btn" onClick={() => onRestore(version.n)} disabled={disabled} > Restore </button> )} {target !== null && ( <button type="button" className={`es-version__btn ${on ? "es-version__btn--on" : ""}`} onClick={() => onCompare(on ? null : target)} title={isLatest ? `Compare with v${target}, before this change` : `Compare v${version.n} with the current version`} > Compare </button> )} </div> ); } 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<EmbedDraft | undefined>(undefined); const [viewMode, setViewMode] = useState<"preview" | "code">("preview"); const [previewWidth, setPreviewWidth] = useState<PreviewWidth>("article"); const [previewDark, setPreviewDark] = useState(isDark); const [compare, setCompare] = useState<CompareTarget | null>(null); const [previewError, setPreviewError] = useState<{ message: string; at: number } | null>(null); const [versionList, setVersionList] = useState<EmbedVersion[]>([]); const [mobilePane, setMobilePane] = useState<"chat" | "preview">("chat"); const [filesOpen, setFilesOpen] = useState(false); const [dataOpen, setDataOpen] = useState(false); const [dataSelected, setDataSelected] = useState<string | null>(null); const [attached, setAttached] = useState<string[]>([]); const [attachError, setAttachError] = useState<string | null>(null); const [dropActive, setDropActive] = useState(false); const [closePrompt, setClosePrompt] = useState(false); const [notice, setNotice] = useState<string | null>(null); const [tweakOpen, setTweakOpen] = useState(false); const [tweakValues, setTweakValues] = useState<Record<string, ConfigValue>>({}); const [inspecting, setInspecting] = useState(false); const [picked, setPicked] = useState<PickedElement | null>(null); const [labelDraft, setLabelDraft] = useState(""); const [checkOpen, setCheckOpen] = useState(false); const messagesEndRef = useRef<HTMLDivElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null); // Iframe double-buffer (also the two sides of the before/after compare). const frameA = useRef<HTMLIFrameElement>(null); const frameB = useRef<HTMLIFrameElement>(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<string | null>(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<string | null>(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<ReturnType<typeof setTimeout> | 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<HTMLTextAreaElement>) => { 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<HTMLTextAreaElement>) => { 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<string, EmbedVersion>(); 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 ( <div key={msg.id} className="es-message-group"> <MessageBubble message={msg} self={authorName} /> {version && ( <VersionChip version={version} latest={latestVersion} previous={previousOf(version)} comparing={compare} disabled={chat.isLoading} onCompare={setCompare} onRestore={handleRestore} /> )} </div> ); }); }; 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 ( <div className="embed-studio" data-pane={mobilePane} data-files-open={filesOpen ? "true" : undefined} > {/* Header */} <div className="es-header"> <div className="es-header__left"> <button type="button" className="embed-btn es-header__files-toggle" onClick={() => setFilesOpen((o) => !o)} aria-label="Charts and data files" aria-expanded={filesOpen} > <FolderOpen size={16} /> </button> <BarChart3 size={16} className="es-header__icon" aria-hidden="true" /> <span className="es-header__title">Embed Studio</span> <code className="es-header__src">{src}</code> {status && ( <span className={`es-header__status ${dirty || isNew ? "es-header__status--draft" : ""}`}>{status}</span> )} {peers.length > 0 && ( <span className="es-header__peers" title="Also editing this chart"> {peers.map((p) => ( <i key={p.name} style={{ background: p.color }} aria-hidden="true"> {p.name.slice(0, 1).toUpperCase()} </i> ))} {peers.length === 1 ? `${peers[0].name} is here too` : `${peers.length} people are here too`} </span> )} {modelLabel && ( <span className="es-header__model" title="Model used by the studio (change it in the chat panel)"> <Cpu size={12} aria-hidden="true" /> {modelLabel} </span> )} </div> <div className="es-header__actions"> <button className="embed-btn" onClick={handleNewConversation} aria-label="New conversation" title="New conversation" disabled={chat.messages.length === 0 || chat.isLoading} > <Plus size={16} /> </button> <button className="embed-btn embed-btn-primary es-header__apply" onClick={handleApply} disabled={!canApply} title={canApply ? undefined : "No changes to apply"} > <Check size={14} /> {applyLabel} </button> <button className="embed-btn" onClick={requestClose} aria-label="Close Embed Studio" > <X size={16} /> </button> </div> </div> <div className="es-mobile-tabs" role="tablist" aria-label="Studio panes"> <button type="button" role="tab" aria-selected={mobilePane === "chat"} className={`es-mobile-tabs__tab ${mobilePane === "chat" ? "es-mobile-tabs__tab--active" : ""}`} onClick={() => setMobilePane("chat")} > Chat </button> <button type="button" role="tab" aria-selected={mobilePane === "preview"} className={`es-mobile-tabs__tab ${mobilePane === "preview" ? "es-mobile-tabs__tab--active" : ""}`} onClick={() => setMobilePane("preview")} > Preview {previewError && <span className="es-mobile-tabs__dot" aria-label="The chart has an error" />} </button> </div> {/* Body: split panel */} <div className="es-body"> <div className="es-files-wrap"> <FilesSidebar embedStore={embedStore} drafts={drafts} currentSrc={src} dataFiles={data.files} selectedDataFile={dataOpen ? dataSelected : null} onSelectChart={ onSelectChart ? (name) => { 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} /> </div> {filesOpen && ( <button type="button" className="es-files-scrim" aria-label="Close files" onClick={() => setFilesOpen(false)} /> )} {/* Left: Chat */} <div className={`es-chat ${dropActive ? "es-chat--drop" : ""}`} {...chatDropProps}> {dropActive && ( <div className="es-chat__drop" aria-hidden="true"> <Database size={20} /> Drop to attach the data to this chat </div> )} <div className="es-chat__messages" aria-live="polite"> {chat.messages.length === 0 && ( <div className="es-chat__empty"> <p> {hasChart ? `Ask for changes to the ${kindLabel}.` : `Describe the ${kindLabel} you want to create.`} </p> <div className="es-chips" aria-label="Suggestions"> {(hasChart ? followUps : starters).map((s) => ( <button key={s} type="button" className="es-chip" onClick={() => send(s)} > {s} </button> ))} </div> {!isBanner && ( <p className="es-chat__hint">Drop a CSV or JSON file here, or paste a table into the message box.</p> )} </div> )} {renderMessages()} {chat.isLoading && chat.messages.length > 0 && ( <EmbedAgentStatus messages={chat.messages} /> )} {showFollowUps && followUps.length > 0 && ( <div className="es-chips es-chips--followups" aria-label="Follow-up suggestions"> {followUps.map((s) => ( <button key={s} type="button" className="es-chip" onClick={() => send(s)}> {s} </button> ))} </div> )} <div ref={messagesEndRef} /> </div> {/* Input */} <div className="es-chat__input-area"> {errorInfo && ( <div className="es-chat__error" role="alert"> <AlertTriangle size={14} aria-hidden="true" /> <div className="es-chat__error-body"> <strong>{errorInfo.title}</strong> <span>{errorInfo.detail}</span> <div className="es-chat__error-actions"> {errorInfo.retryable && ( <button type="button" className="embed-btn embed-btn-primary" onClick={chat.retry}> <RotateCcw size={13} /> Retry </button> )} {errorInfo.action && ( <a className="embed-btn" href={errorInfo.action.href} target="_blank" rel="noopener"> {errorInfo.action.label} </a> )} </div> </div> </div> )} {picked && ( <div className="es-picked"> <span className="es-picked__chip" title={picked.selector}> <Crosshair size={11} aria-hidden="true" /> @this <code>{pickedLabel(picked)}</code> <button type="button" aria-label="Forget the selected element" onClick={() => setPicked(null)}> <X size={11} /> </button> </span> {pickedTextField && ( <form className="es-picked__edit" onSubmit={(e) => { e.preventDefault(); if (!labelDraft.trim()) return; handleTweak(pickedTextField.key, labelDraft.trim()); setPicked(null); }} > <label htmlFor="es-label-edit">Edit label (no AI)</label> <input id="es-label-edit" value={labelDraft} onChange={(e) => setLabelDraft(e.target.value)} /> <button type="submit" className="embed-btn" disabled={!labelDraft.trim()}> Save </button> </form> )} </div> )} {(attached.length > 0 || attachError) && ( <div className="es-attached"> {attached.map((name) => ( <span key={name} className="es-attached__chip"> <Paperclip size={11} aria-hidden="true" /> {name} <button type="button" aria-label={`Do not attach ${name}`} onClick={() => setAttached((prev) => prev.filter((n) => n !== name))} > <X size={11} /> </button> </span> ))} {attachError && <span className="es-attached__error">{attachError}</span>} </div> )} <div className="es-chat__input-row"> <textarea ref={textareaRef} value={chat.input} onChange={(e) => chat.setInput(e.target.value)} onKeyDown={handleKeyDown} onInput={handleTextareaInput} onPaste={(e) => void handlePaste(e)} placeholder={hasChart ? `Tweak the ${kindLabel}...` : `Describe your ${kindLabel}...`} rows={1} className="es-chat__textarea" aria-label={`Message the ${kindLabel} assistant`} /> {chat.isLoading ? ( <button className="es-chat__send-btn" onClick={chat.stop} aria-label="Stop" > <Square size={16} /> </button> ) : ( <button className="es-chat__send-btn" onClick={handleSend} disabled={!chat.input.trim()} aria-label="Send" > <Send size={16} /> </button> )} </div> </div> </div> {/* Right: preview, code, data */} <div className="es-preview"> <div className="es-preview__toolbar"> <div className="es-segmented" role="group" aria-label="View"> <button className={`es-preview__tab ${viewMode === "preview" ? "es-preview__tab--active" : ""}`} onClick={() => setViewMode("preview")} aria-pressed={viewMode === "preview"} > <Eye size={14} /> Preview </button> <button className={`es-preview__tab ${viewMode === "code" ? "es-preview__tab--active" : ""}`} onClick={() => setViewMode("code")} aria-pressed={viewMode === "code"} > <Code size={14} /> Code </button> </div> {viewMode === "preview" && ( <> <div className="es-segmented es-segmented--widths" role="group" aria-label="Preview width"> {(Object.keys(PREVIEW_WIDTHS) as PreviewWidth[]).map((w) => ( <button key={w} type="button" className={`es-preview__tab ${previewWidth === w ? "es-preview__tab--active" : ""}`} onClick={() => setPreviewWidth(w)} aria-pressed={previewWidth === w} title={`${PREVIEW_WIDTHS[w].px} px wide`} > {PREVIEW_WIDTHS[w].label} </button> ))} </div> <button type="button" className="es-preview__tab" onClick={() => setPreviewDark((d) => !d)} aria-label={previewDark ? "Preview in light mode" : "Preview in dark mode"} title={previewDark ? "Preview in light mode" : "Preview in dark mode"} > {previewDark ? <Sun size={14} /> : <Moon size={14} />} </button> </> )} <button type="button" className={`es-preview__tab ${tweakOpen ? "es-preview__tab--active" : ""}`} onClick={() => setTweakOpen((o) => !o)} aria-pressed={tweakOpen} title="Tweak settings without asking the assistant" > <SlidersHorizontal size={14} /> <span className="es-hide-narrow">Tweak</span> {configFields && <span className="es-count">{configFields.length}</span>} </button> <button type="button" className={`es-preview__tab ${inspecting ? "es-preview__tab--active" : ""}`} onClick={toggleInspect} aria-pressed={inspecting} disabled={!hasChart || comparing} title="Click an element of the chart to talk about it (Esc to cancel)" > <Crosshair size={14} /> <span className="es-hide-narrow">Inspect</span> </button> <button type="button" className={`es-preview__tab ${compare !== null ? "es-preview__tab--active" : ""}`} onClick={() => setCompare((c) => (c !== null ? null : defaultCompareTarget))} disabled={compare === null && defaultCompareTarget === null} aria-pressed={compare !== null} title="Compare before and after" > <Columns2 size={14} /> <span className="es-hide-narrow">Compare</span> </button> <button type="button" className={`es-preview__tab ${dataOpen ? "es-preview__tab--active" : ""}`} onClick={() => setDataOpen((o) => !o)} aria-pressed={dataOpen} title="Data files" > <Database size={14} /> <span className="es-hide-narrow">Data</span> {data.files.length > 0 && <span className="es-count">{data.files.length}</span>} </button> <div style={{ flex: 1 }} /> <button type="button" className="embed-btn" onClick={handleUndo} disabled={!undoTarget || chat.isLoading} title={undoTarget ? `Go back to v${undoTarget.n}` : "Nothing to undo"} > <Undo2 size={14} /> <span className="es-hide-narrow">Undo last change</span> </button> <button className="embed-btn" onClick={requestClose}> Done </button> </div> {compare !== null && ( <div className="es-viewing" role="status"> <span> Before: <strong>{compareLabel}</strong>, after: <strong>current</strong> {latestVersion ? ` (v${latestVersion.n})` : ""} </span> {typeof compare === "number" && ( <button type="button" className="embed-btn embed-btn-primary" onClick={() => handleRestore(compare)} disabled={chat.isLoading} > Restore v{compare} </button> )} <button type="button" className="embed-btn" onClick={() => setCompare(null)}> Exit compare </button> </div> )} {check.state.status !== "idle" && check.state.html === html && compare === null && ( <div className={`es-check es-check--${check.state.status === "done" ? check.state.summary.status.toLowerCase() : check.state.status}`} role="status" > <ShieldCheck size={14} aria-hidden="true" /> {check.state.status === "running" && <span>Checking the {kindLabel} in light and dark, at 360 and 680 px...</span>} {check.state.status === "error" && <span>The automatic check could not run: {check.state.message}</span>} {check.state.status === "done" && ( <> <span>{check.state.summary.label}</span> {check.state.summary.status !== "PASS" && ( <> <button type="button" className="es-version__btn" onClick={() => setCheckOpen((o) => !o)} aria-expanded={checkOpen} > Details {checkOpen ? <ChevronUp size={12} /> : <ChevronDown size={12} />} </button> <button type="button" className="embed-btn embed-btn-primary" onClick={() => check.state.status === "done" && send(checkFixPrompt(check.state.summary))} disabled={chat.isLoading} > <Wrench size={13} /> Fix </button> </> )} </> )} <div style={{ flex: 1 }} /> {check.state.status !== "running" && ( <button type="button" className="es-version__btn" onClick={() => void check.run(html, isBanner)}> Re-run </button> )} </div> )} {checkOpen && check.state.status === "done" && check.state.html === html && compare === null && ( <ul className="es-check__details"> {check.state.summary.checks .filter((c) => c.level !== "pass") .map((c) => ( <li key={c.id} className={`es-check__item es-check__item--${c.level}`}> <strong>{c.label}</strong> {c.messages.slice(0, 3).map((m, i) => ( <span key={i}>{m}</span> ))} </li> ))} </ul> )} {/* Both panels always mounted - toggle with hidden class to preserve iframe state */} <div className={`es-preview__frame-container ${isBanner ? "es-preview__frame-container--banner" : ""} ${previewDark ? "es-preview__frame-container--dark" : "es-preview__frame-container--light"} ${viewMode !== "preview" ? "es-hidden" : ""}`} > {html ? ( <div className={`es-preview__stage ${isBanner ? "es-preview__stage--banner" : ""} ${comparing ? "es-preview__stage--compare" : ""}`} style={{ maxWidth: stageMax }} > {comparing && <span className="es-compare__label">Before: {compareLabel}</span>} {comparing && <span className="es-compare__label">After: current</span>} <iframe ref={frameA} title={comparing ? "Before" : "Chart preview A"} sandbox="allow-scripts allow-same-origin" onLoad={() => handleFrameLoad("a")} style={frameStyle("a")} /> <iframe ref={frameB} title={comparing ? "After" : "Chart preview B"} sandbox="allow-scripts allow-same-origin" onLoad={() => handleFrameLoad("b")} style={frameStyle("b")} /> </div> ) : ( <div className="es-preview__empty"> <BarChart3 size={32} aria-hidden="true" style={{ opacity: 0.4 }} /> <p>The {kindLabel} preview will appear here</p> </div> )} {previewError && html && ( <div className="es-preview__error" role="alert"> <AlertTriangle size={14} aria-hidden="true" /> <span className="es-preview__error-text"> The {kindLabel} threw: <code>{previewError.message}</code> </span> <button type="button" className="embed-btn embed-btn-primary" onClick={() => send(fixPrompt(previewError.message))} disabled={chat.isLoading} > <Wrench size={13} /> Fix it </button> <button type="button" className="embed-btn" onClick={() => setPreviewError(null)} aria-label="Dismiss the error" > <X size={13} /> </button> </div> )} </div> <div className={`es-preview__code ${viewMode !== "code" ? "es-hidden" : ""}`}> <EmbedCodeView html={html} filename={chat.currentSrc()}> {comparing ? ( <CodeDiff before={beforeHtml} after={html} beforeLabel={compareLabel} afterLabel="current" /> ) : undefined} </EmbedCodeView> </div> {tweakOpen && ( <TweakPanel fields={configFields} values={tweakValues} onChange={handleTweak} onClose={() => setTweakOpen(false)} latest={latestVersion} disabled={chat.isLoading || !hasChart || comparing} onAskForSettings={() => send("Declare 2 to 6 tweakable settings for this chart in a data-embed-config block and read them from ctx.config.") } /> )} {dataOpen && ( <DataDrawer files={data.files} getFile={data.getFile} selected={dataSelected} onSelect={setDataSelected} onClose={() => setDataOpen(false)} chartHtml={html} /> )} {notice && ( <div className="es-notice" role="status"> <Check size={13} aria-hidden="true" /> {notice} </div> )} </div> </div> {closePrompt && ( <div className="es-dialog-scrim" role="presentation" onClick={() => setClosePrompt(false)}> <div className="es-dialog" role="dialog" aria-modal="true" aria-labelledby="es-close-title" onClick={(e) => e.stopPropagation()} > <h2 id="es-close-title"> {isNew ? `This ${kindLabel} is not in the article yet` : "Your changes are not in the article yet"} </h2> <p> {isNew ? `Insert it where you opened the studio, keep it as a draft for later, or throw it away.` : `Co-authors still see the applied version. Apply your changes, keep them as a draft, or discard them.`} </p> <div className="es-dialog__actions"> <button type="button" className="embed-btn embed-btn-primary" onClick={() => { if (onApply(chat.currentSrc())) { setClosePrompt(false); onClose(); } }} disabled={chat.isLoading} > {applyLabel} and close </button> <button type="button" className="embed-btn" onClick={() => { setClosePrompt(false); onClose(); }} > Keep draft </button> <button type="button" className="embed-btn es-dialog__danger" onClick={() => { setClosePrompt(false); onDiscard(chat.currentSrc()); onClose(); }} > {isNew ? `Discard ${kindLabel}` : "Discard changes"} </button> <button type="button" className="embed-btn" onClick={() => setClosePrompt(false)}> Cancel </button> </div> </div> </div> )} </div> ); }
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<string>;
/** Display name of the model the studio talks to (header pill). */
modelLabel?: string;
userId: string;