// GENERATED FILE - do not edit by hand. // Source: backend/embed-kit/{contract,banners,dataviz}.md // Regenerate with `npm run gen:embed-kit` in backend/. export const EMBED_CONTRACT_MD = "# Embed runtime and contract\n\nEvery embed is rendered in its own iframe, built from the embed HTML by\n`buildEmbedSrcdoc`: in the editor, in the Embed Studio preview, in the\npublished article and in the PDF. Before the embed, that document already\nprovides `window.Embed` (the shared runtime), D3 (loaded by the runtime),\nthe theme CSS variables for light and dark, and `window.ColorPalettes`.\nAn embed only describes its chart; the runtime owns the plumbing.\n\n## Shape of an embed\n\n```html\n
\n\n\n```\n\nRules for the fragment itself:\n\n- The root `
` is the first element of the fragment, with a unique,\n descriptive class (`d3-` prefix). No `id` on the root.\n- Every CSS rule is prefixed with the root class. Never style `body`,\n `html`, `svg` or `text` unprefixed.\n- The script is a classic inline script calling `Embed.mount` at top\n level. Do not wrap the call in `DOMContentLoaded`, `setTimeout` or an\n async function: the runtime finds the container from\n `document.currentScript`, which only exists while the script is parsed.\n- No globals. Keep state in the setup closure.\n- Query only inside `ctx.root` (`ctx.root.querySelector`, `d3.select(ctx.root)`).\n- Never hand-roll D3 loading, mount guards, `ResizeObserver` or theme\n observers: the runtime does all of it.\n\n## `Embed.mount(rootClass, setup, options)`\n\n| Option | Default | Meaning |\n|---|---|---|\n| `deps` | `['d3']` | Libraries to load before `setup`. Use `[]` for vanilla JS / canvas embeds. |\n| `resize` | `'width'` | Re-render on width changes only. `'size'` also re-renders on height changes (banners, fill-the-box layouts). |\n| `lazy` | `true` | Mount when the embed nears the viewport. Headless browsers and print always mount eagerly. |\n\n`setup(ctx)` may be async. It may return a render function, or nothing\nfor static or self-driven embeds (then the embed is ready when setup\nresolves).\n\nThe render function receives `{ width, height, theme, isDark }`, where\n`width` / `height` are the root's client size. The first render runs\nsynchronously after setup; later renders are coalesced to one per frame.\nMake render idempotent: use data joins (`selection.join()`), never append\nunconditionally inside it.\n\n## `ctx`\n\n| Member | Purpose |\n|---|---|\n| `root` | The embed's root element. |\n| `colors(kind, n)` | `kind`: `'categorical'`, `'sequential'` or `'diverging'`. Returns `n` colors from the article palette. |\n| `labelColor(color, t = 0.4)` | A palette color mixed toward the text color, so text in a series color stays readable on both themes. |\n| `textOn(background)` | `'#111111'` or `'#ffffff'`, whichever contrasts more with a filled mark (heatmap cell, bar, node). |\n| `describe(text)` | Accessible description: sets `role=\"img\"` and `aria-label` on the top-level svg/canvas and `data-description` on the root. |\n| `rerender()` | Ask for a render (after a control changes, for example). |\n| `animate(tick)` | `tick(time, dt)` on every frame. Paused off-screen and in background tabs; with reduced motion it runs exactly once. |\n| `reducedMotion` | `true` when the visitor prefers reduced motion. |\n| `theme()` | `'light'` or `'dark'`, read at call time. |\n| `signal` | `AbortSignal` aborted when the embed is removed. Pass it to `addEventListener(..., { signal })`. |\n| `onCleanup(fn)` | Run `fn` on removal (timers, workers, WebGL contexts). |\n| `fail(error)` | Show an error inside the embed and mark it failed. Thrown errors in setup or render do this automatically. |\n| `config` | Values of the tweakable settings declared in the fragment (see below), `{ key: value }`. Read them inside render. |\n\nLifecycle signals: the root gets `data-embed-status=\"ready\"` or `\"error\"`\nand dispatches a bubbling `embed:ready` / `embed:error` event after the\nfirst successful render (or failure). `Embed.whenReady()` resolves when\nevery mounted embed has settled.\n\n## Tweakable settings (`config`)\n\nDeclare the few settings an author is likely to adjust in a JSON block\nright after the root. The editor turns it into a Tweak panel (sliders,\ncolor pickers, selects, toggles, text fields) that updates the chart\ninstantly, without asking the model, and saves the new values back into\nthis block:\n\n```html\n
\n\n```\n\n- Types: `range` (`min`, `max`, `step`), `color`, `select` (`options`),\n `toggle`, `text`. Every field has a `label` and a `value`.\n- `ctx.config.barGap` is the current value. Read config inside render\n (not in setup), so a tweak re-renders with the new value.\n- 2 to 6 fields: the settings that change the reading (highlighted\n series, scale, sort, gap, label text), not every margin.\n- Visible text written by the chart (title, axis titles, annotations) comes\n from `text` fields, so authors can fix a label by clicking it.\n- `color` fields default to `\"\"`: use a palette color when empty, so the\n chart keeps following the theme until someone picks a color.\n- The block must be valid JSON (no comments, no trailing commas).\n\n## Data\n\nThe iframe cannot fetch files. Data lives in the script as a JS literal:\n\n- Attached files (CSV, JSON, ...) are read by the author or the agent and\n inlined as a parsed array of objects. Aggregate or downsample large\n files first: above about 5k marks prefer canvas, above about 50k\n pre-aggregate.\n- Never fabricate columns or values for real data. Synthetic data is fine\n for demos and banners; seed it (`d3.randomLcg(42)`) so it is identical\n on every load and in the PDF.\n- Validate what you rely on and fail with a useful message:\n `if (!rows.length) throw new Error('No rows to plot.');`\n\n## Theming\n\nTheme with CSS variables first. They switch instantly with the theme and\nneed no JavaScript:\n\n| Variable | Use |\n|---|---|\n| `--text-color` | Primary text, direct labels, emphasized values. |\n| `--muted-color` | Secondary text, axis titles, annotations. |\n| `--axis-color`, `--tick-color`, `--grid-color` | Axis lines, tick labels, gridlines. |\n| `--border-color` | Separators, swatch outlines, control borders. |\n| `--surface-bg` | Tooltips, popovers, controls. |\n| `--page-bg` | The page color, for knock-out strokes around marks. |\n| `--primary-color` | The one accent: highlight, selection, focus. |\n\nPalette colors come from `ctx.colors()` and must be read inside render,\nbecause they change with the theme and the primary color. Theme flips\nreach the iframe as a `palettes:updated` event and the runtime\nre-renders, so no `MutationObserver` on `data-theme` is needed.\n\nGotchas:\n\n- **Palette colors as text.** Palette colors are tuned for marks and are\n often too light for text. Use `ctx.labelColor(color)` for text in a\n series color, or `--text-color` next to a swatch.\n- **Text on filled marks.** For labels over heatmap cells, bars or nodes,\n color them with `ctx.textOn(fill)`, never with the theme text color and\n never with a hand-written lightness threshold.\n- **Coloring SVG text.** Prefer `.style('fill', ...)` or a scoped CSS rule\n over `.attr('fill', ...)`, so a later CSS rule cannot silently win.\n- **Background.** The root and its children are transparent unless the\n user asks for a surface; the article provides the page. Use\n `--surface-bg` if you need one, never a hardcoded color.\n- **Hardcoded colors** (`#000`, `white`, `steelblue`) break one of the two\n themes. Every color is a variable, a palette color, or `textOn()`.\n- **`--primary-color` is `oklch()`** in articles, and `d3.color` and the\n `d3.interpolate*` helpers cannot parse it (they return null or black).\n Use it as is in CSS, pass it to `ctx.labelColor()` / `ctx.textOn()`, or\n take a palette color from `ctx.colors()` when you need to compute with it.\n\n## Layout and responsiveness\n\n- Width comes from the render argument. Derive height from width with a\n floor and a ceiling (`Math.max(240, Math.min(420, width * 0.5))`), and\n set it on the svg with a matching `viewBox`. The iframe grows to the\n content height on its own.\n- Check at 360px. Below about 520px, drop what does not fit: fewer ticks\n (`Math.floor(innerW / 80)`), direct labels replaced by a legend,\n controls stacked.\n- Nothing may overflow the root horizontally.\n- Labels must not collide: shorten, rotate, thin out, or nudge them.\n\n## UI: controls, legends, tooltips\n\n- Controls, legends and tooltips are HTML inside the root, never SVG.\n- Controls are labeled `