tfrere's picture
tfrere HF Staff
Cursor
feat(embed-studio): tweak panel, inspect, automatic check, launcher, inline edit
4953bfd
|
Raw History Blame Contribute Delete
15.5 kB

Embed Studio - Architecture Document

Overview

The Embed Studio is a dedicated UI mode within the editor for creating, editing, and previewing HTML embed visualizations (D3.js charts). It isolates the dataviz workflow from the article editing flow, providing a focused chat + preview experience similar to the standalone dataviz-agent-space.

Context

Embeds are self-contained HTML fragments (root div + scoped style + script) that call the shared Embed.mount runtime. The runtime and the authoring guides live in backend/embed-kit/ (embed-runtime.js, contract.md, banners.md, dataviz.md); npm run gen:embed-kit in backend/ compiles them into the TypeScript modules used by buildEmbedSrcdoc and the Embed Studio prompt.

In the editor, users need to create and iterate on these charts without leaving the editor. The Embed Studio solves this by providing a dedicated panel with an AI assistant specialized in D3 chart generation.

Storage

Y.Map("embeds")

Embed HTML content is stored in a collaborative Yjs Map, keyed by filename:

Y.Map("embeds") = {
  "d3-scaling-chart.html": "<div class='d3-scaling-chart'>...</div>",
  "d3-performance.html": "<div class='d3-performance'>...</div>"
}

The ProseMirror node (htmlEmbed) only stores the src attribute as a reference key. The actual HTML lives in the shared Y.Map, enabling real-time collaboration on embed content.

Node attributes

The htmlEmbed TipTap node stores:

Attribute Type Description
src string Filename key into Y.Map("embeds")
title string Chart title (displayed above)
desc string Chart description
wide boolean Wide layout mode
downloadable boolean Show download button
height number Last known content height (pixels)

The height attribute eliminates layout jumps: once a chart reports its height, it is persisted and used as the iframe's initial height on subsequent loads.

UI: Two Modes

1. Inline Preview (article view)

When the user is editing the article, the htmlEmbed NodeView shows a read-only preview:

┌─────────────────────────────────────────┐
│ 📊 Chart Title              [Edit] [⋮] │
├─────────────────────────────────────────┤
│                                         │
│         <iframe preview>                │
│                                         │
└─────────────────────────────────────────┘
  • The iframe renders the chart using srcdoc with the full HTML document (buildDoc wrapper)
  • Height comes from the stored height attribute (default: 400px)
  • Clicking "Edit" opens the Embed Studio panel
  • No code editing in this mode

2. Embed Studio Panel (creation/editing)

A full-width panel (drawer or overlay) opens with a split layout:

┌────────────────────────────┬─────────────────────────────┐
│  Chat (D3 context)         │  Live Preview               │
│                            │                             │
│  System prompt includes:   │  ┌─────────────────────┐    │
│  - D3 embed directives     │  │                     │    │
│  - ColorPalettes API       │  │   [rendered chart]   │    │
│  - Current chart HTML      │  │                     │    │
│                            │  └─────────────────────┘    │
│  User: "make a bar chart   │                             │
│   showing model sizes"     │  Toggle: [Preview] [Code]   │
│                            │                             │
│  AI: Creating chart...     │                             │
│                            │       [Save & Close]        │
└────────────────────────────┴─────────────────────────────┘

Key design decisions:

  • The chat in this panel has a separate system prompt with D3 directives injected. This avoids bloating the main article chat with 500+ lines of D3 conventions.
  • The chat history is per-embed (scoped to the src key), so each chart has its own conversation thread.
  • The live preview uses double-buffered iframes (A/B swap with cross-fade) from the dataviz-agent pattern to avoid flashes on update.
  • An optional "Code" toggle shows the raw HTML for power users (future enhancement).

Iteration loop (current behaviour)

  • Preview errors reach the agent. The studio builds its preview with buildEmbedSrcdoc(..., { studio: true }), which installs an error reporter first in <head>. Uncaught errors, unhandled rejections, failed resource loads and the runtime's embed:error are posted to the parent as { type: "embedError" }. The studio shows "The chart threw ... [Fix it]"; when a turn that changed the chart ends with an error, one fix request is sent automatically (at most one per message the user typed, createAutoFixGuard).
  • Versions. Y.Map("embed-versions") keeps up to 20 versions per embed, shared with collaborators (embed-versions.ts). Each agent turn writes one version (all its createEmbed / patchEmbed calls update it). Under each reply: vN, Restore, Compare. Restoring and "Undo last change" append a copy, so history stays linear.
  • Chips. Starter prompts when the chat is empty, three follow-ups after each reply (embed-suggestions.ts, heuristics on the HTML).
  • Preview controls. Width presets (Article 680 px, Wide 1100 px, 360 px) and a light/dark toggle local to the preview, pushed with setTheme so the chart is not reloaded (the srcdoc carries data-theme-locked so the bootstrap keeps the preview's theme).
  • Code tab. Shiki-highlighted HTML with Copy and Download.
  • Errors. Provider failures keep their HTTP status (HTTP 402: ..., stream-errors.ts); the studio maps 401 / 402 / 429 to an actionable message with Retry (chat-errors.ts).
  • Mobile. Under 900 px the files sidebar becomes a drawer and Chat / Preview are tabs.

Drafts and "Apply to article"

  • The studio never writes to Y.Map("embeds") directly. Agent writes, restores and undos go to Y.Map("embed-drafts") (embed-drafts.ts, draftWorkspace), so the article and co-authors keep seeing the applied chart.
  • "Apply to article" (applyDraft + handleEmbedApply in App.tsx) copies the draft into embeds, mirrors the agent's title / source on the node, and drops the draft. A chart opened from the slash menu or the top bar has no node until then: the cursor position is kept as a Yjs relative position (insert-position.ts) and the node is inserted there on Apply. Closing never leaves an empty node behind.
  • Closing with unapplied changes asks: apply and close, keep the draft (the node shows "Unapplied draft by X"), or discard (a chart that never reached the article loses its versions and conversation too).
  • Charts already in the article are not renamed by the agent (allowRename).
  • Presence: the studio sets the awareness field embedStudio: { src, user }; the node shows "X is editing this chart" and the studio header lists who else is there (useStudioPresence.ts).

Compare, data, streaming, shared thread

  • Compare reuses the two preview iframes side by side: before (a version, or the applied chart) and after (current). The Code tab shows a line diff (line-diff.ts).
  • Data drawer under the preview: the file's table with an inferred type per column, and a "used by this chart" flag (data-insights.ts). Files dropped on the chat or tables pasted into the message box become data files and are attached to the next message.
  • Streaming: while createEmbed / patchEmbed input streams, the status shows "Writing chart... N lines" (stream-progress.ts).
  • Shared thread: the readable part of each chart's conversation (prompts and replies, no tool payloads) lives in Y.Map("embed-chats") (embed-history.ts); everyone who opens the chart sees it and the agent gets it as context. A thread only kept in this browser's localStorage is imported once.

Tweak, Inspect, automatic check, launcher, inline edit bar

  • Tweak panel. An embed declares 2 to 6 settings in a <script type="application/json" data-embed-config> block next to its root (contract: "Tweakable settings"). The runtime (1.2.0) exposes them as ctx.config and applies { type: "embedConfig", values } messages live. The studio parses the block (embed-config.ts) into sliders, color pickers, selects, toggles and text fields; a change is posted to the preview at once (no reload, no model call), then written back into the block in the draft after 600 ms and recorded as a "manual tweak" version (one per burst of tweaks).
  • Inspect. The studio preview ships a point-and-click inspector (STUDIO_INSPECTOR in embed-doc.ts, off until embedInspect). A click posts embedPick (tag, text, classes, selector, bound datum); the studio shows an @this chip and appends that pointer to the next message. When the clicked text is the value of a text setting, the chip offers "Edit label (no AI)".
  • Automatic check. After each turn that changed the chart, the studio posts the HTML to POST /api/embed-check. The server renders it in headless Chromium (light and dark, 360 and 680 px, network limited to script CDNs, one check at a time) with the same checker as npm run check:embeds (src/embed-check/check.ts), and returns a summary of 8 named checks: "7 checks passed, 1 warning [Details] [Fix]". Without Chromium the endpoint answers 503 and the line stays hidden.
  • Launcher. The top bar button and the slash menu "New Chart" open a launcher: describe the figure (the description is sent as the first message), drop a CSV or JSON, start from one of 4 gallery figures (GET /api/embed-starters, generated from embed-kit/gallery/ by npm run gen:embed-kit), or reopen a chart of the article.
  • Inline edit bar. "Ask AI" under a chart in the article runs the same assistant on a draft: the chart shows the result in place (dashed outline), Before / After, Accept (applies) or Undo (drops the draft). On screens under 900 px, "Edit" opens this bar instead of the full studio.

AI Tools

The Embed Studio provides three tools to the AI (following the dataviz-agent pattern):

createEmbed(src, html, title, source)

Create or fully replace the HTML for an embed. Writes to Y.Map("embeds").

patchEmbed(src, search, replace)

Exact string replacement in the current HTML. More efficient than full rewrite for small changes (color tweaks, label updates, data changes). Reads from and writes to Y.Map("embeds").

readEmbed(src)

Read the current HTML content. The AI should call this before patching to verify exact content.

Preview Infrastructure

buildDoc(html, isDark, primaryColor)

Wraps a chart HTML fragment into a complete HTML document with:

  • CSS variables for theming (--primary-color, --text-color, --surface-bg, etc.)
  • data-theme="dark" attribute when in dark mode
  • ColorPalettes polyfill (provides window.ColorPalettes.getColors(), .getPrimary(), etc.)
  • The Embed.mount runtime from backend/embed-kit/embed-runtime.js, inlined in <head>
  • Height reporting script (see below)
  • Base styles (box-sizing, font stack, padding)

Height reporting

A script injected by buildDoc() observes the chart container and reports its height to the parent:

// Injected into every chart iframe
new ResizeObserver(entries => {
  const height = Math.ceil(entries[0].contentRect.height);
  window.parent.postMessage({ type: 'embedResize', height }, '*');
}).observe(document.body);

The NodeView listens for this message and updates the node's height attribute:

window.addEventListener('message', (e) => {
  if (e.data?.type === 'embedResize') {
    updateAttributes({ height: e.data.height });
  }
});

On subsequent renders, the iframe starts at the stored height, eliminating layout jumps.

Preview strategy: srcdoc first

Initial implementation uses <iframe srcdoc="..."> directly. This avoids backend changes and keeps the architecture simple.

If we hit limitations (CSP restrictions, large HTML payloads, script execution issues), we migrate to a server-side preview route (POST /api/preview returning an ID, iframe loads /api/preview/:id), following the dataviz-agent pattern.

Export

Updated export API

The toMdx() function returns an object instead of a plain string:

interface ExportResult {
  mdx: string;                        // The MDX content with frontmatter
  embeds: Record<string, string>;     // filename -> HTML content
}

The caller is responsible for writing the embed files to app/src/content/embeds/.

MDX output

Each embed in the article exports as:

<HtmlEmbed src="d3-scaling-chart.html" title="Chart Title" desc="Description" />

The HTML files are exported separately from the Y.Map("embeds") contents.

System Prompt for D3 Generation

The Embed Studio injects the D3 directives into the AI's system prompt. The content comes from two sources:

  1. Tool descriptions (from dataviz-agent): create/patch/read tools with usage guidelines
  2. Embed contract and chart design guide (backend/embed-kit/contract.md, dataviz.md, plus banners.md in banner mode): the Embed.mount API, theming, data inlining, layout, UI, accessibility, motion and a review checklist

These are only injected when the Embed Studio is open, keeping the main article chat lightweight.

Implementation Plan

Phase 1: Core infrastructure

  1. Create Y.Map("embeds") in Editor.tsx and pass to the embed store
  2. Create EmbedStore (similar to FrontmatterStore) with get/set/observe/patch operations
  3. Replace the current atomic htmlEmbed NodeView with an iframe-based preview
  4. Implement buildDoc() with CSS variables and ColorPalettes polyfill
  5. Implement height reporting via postMessage

Phase 2: Embed Studio panel

  1. Create EmbedStudio.tsx - the split-panel UI (chat + preview)
  2. Create a dedicated chat hook (useEmbedChat) with D3 system prompt
  3. Implement createEmbed, patchEmbed, readEmbed AI tools (backend + frontend)
  4. Double-buffered iframe preview (A/B swap)
  5. Wire "Edit" button on inline NodeView to open the studio

Phase 3: Polish

  1. Per-embed chat history persistence
  2. Code view toggle
  3. Export API update (toMdx returns { mdx, embeds })
  4. Data file upload support (CSV/JSON stored in Y.Map)
  5. Screenshot-based validation (Playwright, optional)

References