Skip to content

DeepTeam is a framework to red team LLMs and AI agents.

Remove diagram frame components

penguine95238d2552bb
diff --git a/docs/components/frames/BoardFrame/BoardFrame.tsx b/docs/components/frames/BoardFrame/BoardFrame.tsx
deleted file mode 100644
index 5ccf01d3..00000000
--- a/docs/components/frames/BoardFrame/BoardFrame.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import type * as React from "react";
-import FrameShell from "@/components/frames/FrameShell/FrameShell";
-import type { LegendEntry } from "@/components/frames/FrameShell/FrameShell";
-import type { BoardData, BoardType } from "@/lib/frames/board";
-import { BOARD_KIND } from "@/lib/frames/kinds";
-import BoardPlot from "./_BoardPlot";
-import { layoutBoard } from "./_layout";
-
-interface BoardFrameProps {
- id: string;
- board?: BoardData;
- type: string;
- title: string;
- description: string;
- kicker?: string;
- subtitle?: string;
- note?: string;
- caption?: string;
-}
-
-const BoardFrame: React.FC<BoardFrameProps> = ({ id, board, type, title, description, kicker, subtitle, note, caption }) => {
- const problems = !board
- ? ["unknown or invalid data"]
- : !BOARD_KIND.types.includes(type)
- ? [`unknown type "${type}"`]
- : BOARD_KIND.typeProblems(type, board);
- if (!board || problems.length) {
- console.warn(`[BoardFrame] Can't draw "${id}" as "${type}": ${problems.join("; ")}. Run yarn check:content for details.`);
- return null;
- }
- // A venn's members name their category; each named color gets a legend entry.
- const legend: LegendEntry[] = [];
- for (const m of board.main.members)
- if (m.label && m.color && !legend.some(e => e.label === m.label)) legend.push({ id: m.label, label: m.label, color: m.color });
- return (
- <FrameShell
- data={{ "data-board": id, "data-board-type": type }}
- legend={legend}
- title={title}
- description={description}
- kicker={kicker}
- subtitle={subtitle}
- caption={caption}
- note={note}
- >
- <BoardPlot scene={layoutBoard(board, type as BoardType)} id={id} />
- </FrameShell>
- );
-};
-
-export const createBoardFrame = (data: Record<string, BoardData>) =>
- function ArticleBoardFrame(props: Omit<BoardFrameProps, "board">) {
- return <BoardFrame {...props} board={Object.hasOwn(data, props.id) ? data[props.id] : undefined} />;
- };
-
-export default BoardFrame;
diff --git a/docs/components/frames/BoardFrame/_BoardIcon.tsx b/docs/components/frames/BoardFrame/_BoardIcon.tsx
deleted file mode 100644
index 222074c2..00000000
--- a/docs/components/frames/BoardFrame/_BoardIcon.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import type * as React from "react";
-import { markColor } from "@/components/frames/FrameShell/FrameShell";
-import { iconTint, resolveIcon } from "@/lib/frames/board-icons";
-import type { SceneIcon } from "./_scene";
-import styles from "./styles.module.scss";
-
-export const BoardIcon = ({ icon }: { icon: SceneIcon }): React.ReactElement | null => {
- const resolved = resolveIcon(icon.ref);
- if (!resolved) return null;
- const { x, y, w, h } = icon;
- const tint = iconTint(icon.ref);
- const tinted = tint ? { className: styles.tinted, style: markColor(tint) } : {};
- if (resolved.source === "brand") {
- return (
- <svg
- className={[styles.brand, tinted.className].filter(Boolean).join(" ")}
- x={x}
- y={y}
- width={w}
- height={h}
- viewBox="0 0 24 24"
- style={tinted.style ?? (resolved.color ? { fill: resolved.color } : undefined)}
- >
- <path d={resolved.path} />
- </svg>
- );
- }
- if (resolved.source === "icon") {
- const { Component } = resolved;
- return (
- <Component
- className={[styles.lineIcon, tinted.className].filter(Boolean).join(" ")}
- style={tinted.style}
- x={x}
- y={y}
- width={w}
- height={h}
- strokeWidth={1.75}
- aria-hidden="true"
- />
- );
- }
- return <image href={resolved.src} x={x} y={y} width={w} height={h} preserveAspectRatio="xMidYMid meet" />;
-};
diff --git a/docs/components/frames/BoardFrame/_BoardPlot.tsx b/docs/components/frames/BoardFrame/_BoardPlot.tsx
deleted file mode 100644
index f0139365..00000000
--- a/docs/components/frames/BoardFrame/_BoardPlot.tsx
+++ /dev/null
@@ -1,256 +0,0 @@
-import type * as React from "react";
-import { type Box, textWidth } from "@/components/frames/FlowPlot/_scene";
-import { markColor } from "@/components/frames/FrameShell/FrameShell";
-import type { ChartColor } from "@/lib/charts/schema";
-import {
- ARROW_LENGTH,
- type BoardScene,
- END_CIRCLE,
- END_DOT,
- MAGNIFIER,
- MIN_SCALE,
- type SceneEnd,
- type ScenePulloutLine,
- type SceneMark,
- type SceneText,
-} from "./_scene";
-import { BoardIcon } from "./_BoardIcon";
-import { ELLIPSIS, TIER, sizeVars } from "./_tokens";
-import styles from "./styles.module.scss";
-
-interface BoardPlotProps {
- scene: BoardScene;
- id: string;
-}
-
-const rectOf = (b: Box, rx: number) => ({ x: b.x, y: b.y, width: b.w, height: b.h, rx });
-
-interface TextProps {
- text: SceneText;
- tone?: "muted";
- halo?: boolean;
-}
-
-const CODE_SPAN = /(`[^`]+`)/;
-const isCode = (part: string) => part.length > 2 && part.startsWith("`") && part.endsWith("`");
-const CHIP_PAD = 4;
-
-// `backticks` draw as inline code; a line that is only code also gets a chip behind it.
-const Text = ({ text, tone, halo }: TextProps): React.ReactElement => {
- const parts = text.text.split(CODE_SPAN).filter(Boolean);
- const size = TIER[text.tier].text;
- const chip = parts.length === 1 && isCode(parts[0]) ? textWidth(parts[0].slice(1, -1), size) + 2 * CHIP_PAD : 0;
- const chipX = text.anchor === "middle" ? text.x - chip / 2 : text.anchor === "end" ? text.x - chip + CHIP_PAD : text.x - CHIP_PAD;
- return (
- <>
- {chip ? <rect className={styles.codeChip} x={chipX} y={text.y - size / 2 - 3} width={chip} height={size + 6} rx={3} /> : null}
- <text
- className={styles.text}
- data-tier={text.tier}
- data-tone={tone}
- data-halo={halo || undefined}
- data-weight={text.weight}
- x={text.x}
- y={text.y}
- textAnchor={text.anchor}
- dominantBaseline="central"
- >
- {parts.map((part, i) =>
- isCode(part) ? (
- <tspan key={i} className={styles.code}>
- {part.slice(1, -1)}
- </tspan>
- ) : (
- part
- )
- )}
- </text>
- </>
- );
-};
-
-/** A group drawn in a chart color, or in the board's own colors without one. */
-const tint = (color: ChartColor | undefined, className?: string) => ({
- className: [className, color ? styles.tinted : undefined].filter(Boolean).join(" ") || undefined,
- style: color ? markColor(color) : undefined,
-});
-
-const Mark = ({ mark, rx, hatch }: { mark: SceneMark; rx: number; hatch?: string }): React.ReactElement => (
- <g {...tint(mark.color)}>
- <rect className={mark.color ? styles.mark : styles.note} {...rectOf(mark, rx)} />
- {hatch ? <rect className={styles.hatchFill} {...rectOf(mark, rx)} fill={hatch} /> : null}
- <Text text={mark.text} />
- </g>
-);
-
-const End = ({ end }: { end: SceneEnd }): React.ReactElement | null => {
- const { at, dir } = end;
- if (end.shape === "magnifier") {
- return (
- <>
- <circle className={styles.endHollow} cx={at.x} cy={at.y} r={MAGNIFIER} />
- <path className={styles.endHollow} d={`M${at.x - MAGNIFIER},${at.y}h${2 * MAGNIFIER}M${at.x},${at.y - MAGNIFIER}v${2 * MAGNIFIER}`} />
- </>
- );
- }
- if (end.shape === "circle") return <circle className={styles.endHollow} cx={at.x} cy={at.y} r={END_CIRCLE} />;
- if (end.shape === "dot") return <circle className={styles.endSolid} cx={at.x} cy={at.y} r={END_DOT} />;
- if (end.shape === "arrow") {
- const base = { x: at.x - dir.x * ARROW_LENGTH, y: at.y - dir.y * ARROW_LENGTH };
- const half = { x: -dir.y * (ARROW_LENGTH / 2), y: dir.x * (ARROW_LENGTH / 2) };
- return <polygon className={styles.endSolid} points={`${at.x},${at.y} ${base.x + half.x},${base.y + half.y} ${base.x - half.x},${base.y - half.y}`} />;
- }
- return null;
-};
-
-const PulloutLine = ({ line, children }: { line: ScenePulloutLine; children: React.ReactNode }): React.ReactElement => (
- <g {...tint(line.color, styles.pulloutLine)} data-colored={line.color ? "" : undefined}>
- {children}
- </g>
-);
-
-const BoardPlot: React.FC<BoardPlotProps> = ({ scene, id }) => {
- const arrow = `board-arrow-${id}`;
- const tip = `board-tip-${id}`;
- const hatchId = (color: ChartColor) => `board-hatch-${id}-${color}`;
- const hatched = new Set(scene.hatch);
- const { view, radius } = scene;
-
- const hatchOf = (mark: { color?: ChartColor }) => (mark.color && hatched.has(mark.color) ? `url(#${hatchId(mark.color)})` : undefined);
-
- return (
- <svg
- className={styles.plot}
- viewBox={`${view.x} ${view.y} ${view.w} ${view.h}`}
- style={{ ...sizeVars, maxWidth: view.w, minWidth: Math.round(view.w * MIN_SCALE) }}
- aria-hidden="true"
- >
- <defs>
- <marker id={arrow} viewBox="0 0 8 8" refX="8" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
- <path className={styles.arrowHead} d="M0,0L8,4L0,8Z" />
- </marker>
- <marker id={tip} viewBox="0 0 8 8" refX="8" refY="4" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto">
- <path className={styles.arrowHead} d="M0,0L8,4L0,8Z" />
- </marker>
- {scene.hatch.map(color => (
- <pattern
- key={color}
- id={hatchId(color)}
- width="6"
- height="6"
- patternUnits="userSpaceOnUse"
- patternTransform="rotate(45)"
- {...tint(color)}
- >
- <line className={styles.hatch} x1="0" y1="0" x2="0" y2="6" />
- </pattern>
- ))}
- </defs>
- <rect className={styles.panel} data-border={scene.panel.border} {...rectOf(scene.panel, radius.panel)} />
- {scene.heading ? <Text text={scene.heading} /> : null}
- {scene.mainBox ? <rect className={styles.tree} data-border={scene.mainBox.border} {...rectOf(scene.mainBox, radius.box)} /> : null}
- {scene.pullouts.flatMap((pullout, i) =>
- pullout.lines.map((line, j) => (
- <PulloutLine key={`${i}-${j}`} line={line}>
- <polyline className={styles.leader} data-style={line.style} points={line.points.map(p => `${p.x},${p.y}`).join(" ")} />
- </PulloutLine>
- ))
- )}
- {scene.main.boxes.map(box => (
- <g key={box.id} {...tint(box.color, styles.box)}>
- {box.shape === "ellipse" ? (
- <>
- <ellipse className={styles.boxShape} cx={box.x + box.w / 2} cy={box.y + box.h / 2} rx={box.w / 2} ry={box.h / 2} />
- {box.color && hatchOf(box) ? <ellipse className={styles.hatchFill} cx={box.x + box.w / 2} cy={box.y + box.h / 2} rx={box.w / 2} ry={box.h / 2} fill={hatchOf(box)} /> : null}
- </>
- ) : box.shape === "circle" ? (
- <>
- <circle className={box.wash ? styles.setShape : styles.boxShape} data-border={box.border} cx={box.x + box.w / 2} cy={box.y + box.h / 2} r={box.w / 2} />
- {box.color && !box.wash && hatchOf(box) ? <circle className={styles.hatchFill} cx={box.x + box.w / 2} cy={box.y + box.h / 2} r={box.w / 2} fill={hatchOf(box)} /> : null}
- </>
- ) : (
- <>
- <rect className={styles.boxShape} data-border={box.border} {...rectOf(box, box.holds ? radius.box : radius.card)} />
- {box.color && hatchOf(box) ? <rect className={styles.hatchFill} {...rectOf(box, box.holds ? radius.box : radius.card)} fill={hatchOf(box)} /> : null}
- </>
- )}
- </g>
- ))}
- {scene.main.rules.map((rule, i) => (
- <g key={i} {...tint(rule.color, styles.box)}>
- <path className={styles.rule} data-border={rule.border} d={rule.d} />
- </g>
- ))}
- {scene.main.labels.map((label, i) => (
- <Text key={i} text={label} />
- ))}
- {scene.main.dots.map((dots, i) =>
- [-1, 0, 1].map(k => (
- <circle
- key={`${i}-${k}`}
- className={styles.ellipsis}
- cx={dots.x + (dots.vertical ? 0 : k * ELLIPSIS.pitch)}
- cy={dots.y + (dots.vertical ? k * ELLIPSIS.pitch : 0)}
- r={ELLIPSIS.r}
- />
- ))
- )}
- {scene.main.elbows.map((d, i) => (
- <path key={i} className={styles.line} d={d} markerEnd={`url(#${tip})`} />
- ))}
- {scene.main.links.map((link, i) => (
- <path key={i} className={styles.line} data-dashed={link.dashed || undefined} d={link.d} markerStart={link.start ? `url(#${arrow})` : undefined} markerEnd={link.end ? `url(#${arrow})` : undefined} />
- ))}
- {scene.arrows.map((a, i) => (
- <path key={i} className={styles.line} d={a.d} markerStart={a.start ? `url(#${arrow})` : undefined} markerEnd={a.end ? `url(#${arrow})` : undefined} />
- ))}
- {scene.main.bars.map(bar => (
- <Mark key={bar.id} mark={bar} rx={radius.mark} hatch={hatchOf(bar)} />
- ))}
- {scene.main.icons.map((icon, i) => (
- <BoardIcon key={i} icon={icon} />
- ))}
- {scene.columnHeadings.map((text, i) => (
- <Text key={i} text={text} halo />
- ))}
- {scene.notes.map((note, i) =>
- note.bare ? (
- <Text key={i} text={note.text} />
- ) : (
- <Mark key={i} mark={note} rx={radius.mark} hatch={hatchOf(note)} />
- )
- )}
- {[...scene.arrowLabels, ...scene.main.linkLabels].map((text, i) => (
- <Text key={i} text={text} tone="muted" halo />
- ))}
- {scene.pullouts.map((pullout, i) => (
- <g key={i}>
- {pullout.shape === "circle" ? (
- <>
- <circle className={styles.lens} cx={pullout.circle.x} cy={pullout.circle.y} r={pullout.circle.r} />
- <rect className={styles.card} {...rectOf(pullout.card, radius.card)} />
- </>
- ) : null}
- {pullout.heading ? <Text text={pullout.heading} /> : null}
- {pullout.pills.map((pill, j) => (
- <Mark key={j} mark={pill} rx={radius.mark} hatch={hatchOf(pill)} />
- ))}
- </g>
- ))}
- {scene.icons.map((icon, i) => (
- <BoardIcon key={i} icon={icon} />
- ))}
- {scene.pullouts.flatMap((pullout, i) =>
- pullout.lines.map((line, j) => (
- <PulloutLine key={`${i}-${j}`} line={line}>
- <End end={line.start} />
- <End end={line.end} />
- {line.label ? <Text text={line.label} tone="muted" halo /> : null}
- </PulloutLine>
- ))
- )}
- </svg>
- );
-};
-
-export default BoardPlot;
diff --git a/docs/components/frames/BoardFrame/_arrange.ts b/docs/components/frames/BoardFrame/_arrange.ts
deleted file mode 100644
index 26f4c5ef..00000000
--- a/docs/components/frames/BoardFrame/_arrange.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { Point } from "@/components/frames/FlowPlot/_scene";
-import type { IconArrangement } from "@/lib/frames/board";
-import { TIER } from "./_tokens";
-
-/** The icon size the spacing below is tuned for; other sizes scale it. */
-const BASE = TIER.sm.icon;
-const PITCH = 40;
-const ROW_PITCH = 36;
-const ZIGZAG = 14;
-const SCATTER_PITCH = 46;
-const SCATTER_JITTER = 16;
-
-export interface Arranged {
- w: number;
- h: number;
- points: Point[];
-}
-
-const seeded = (seed: string) => {
- let h = 2166136261;
- for (const ch of seed) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
- return () => {
- h = (h + 0x6d2b79f5) | 0;
- let t = Math.imul(h ^ (h >>> 15), 1 | h);
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-};
-
-const fit = (points: Point[], size: number): Arranged => {
- const xs = points.map(p => p.x);
- const ys = points.map(p => p.y);
- const [minX, minY] = [Math.min(...xs), Math.min(...ys)];
- return {
- w: Math.max(...xs) - minX + size,
- h: Math.max(...ys) - minY + size,
- points: points.map(p => ({ x: p.x - minX + size / 2, y: p.y - minY + size / 2 })),
- };
-};
-
-const grid = (n: number, cols: number, pitch: number, rowPitch: number): Point[] =>
- Array.from({ length: n }, (_, i) => {
- const row = Math.floor(i / cols);
- const inRow = Math.min(cols, n - row * cols);
- return { x: ((cols - inRow) * pitch) / 2 + (i % cols) * pitch, y: row * rowPitch };
- });
-
-export const arrangeIcons = (n: number, arrange: IconArrangement, seed: string, size: number): Arranged => {
- const placed = (points: Point[]) => fit(points.map(p => ({ x: (p.x * size) / BASE, y: (p.y * size) / BASE })), size);
- if (n === 1) return placed([{ x: 0, y: 0 }]);
- if (arrange === "line") return placed(Array.from({ length: n }, (_, i) => ({ x: i * PITCH, y: 0 })));
- if (arrange === "zigzag-h") return placed(Array.from({ length: n }, (_, i) => ({ x: i * PITCH * 0.8, y: i % 2 ? 0 : ZIGZAG })));
- if (arrange === "zigzag-v") return placed(Array.from({ length: n }, (_, i) => ({ x: i % 2 ? ZIGZAG * 1.4 : 0, y: i * ROW_PITCH * 0.8 })));
- if (arrange === "circle") {
- const r = Math.max(PITCH * 0.75, (PITCH * n) / (2 * Math.PI));
- return placed(Array.from({ length: n }, (_, i) => {
- const a = -Math.PI / 2 + (i * 2 * Math.PI) / n;
- return { x: r * Math.cos(a), y: r * Math.sin(a) };
- }));
- }
- if (arrange === "scatter") {
- const random = seeded(seed);
- const cols = Math.ceil(Math.sqrt(n));
- return placed(
- grid(n, cols, SCATTER_PITCH, SCATTER_PITCH).map(p => ({
- x: p.x + (random() - 0.5) * SCATTER_JITTER,
- y: p.y + (random() - 0.5) * SCATTER_JITTER,
- }))
- );
- }
- return placed(grid(n, n <= 3 ? n : Math.ceil(Math.sqrt(n)), PITCH, ROW_PITCH));
-};
diff --git a/docs/components/frames/BoardFrame/_groups.ts b/docs/components/frames/BoardFrame/_groups.ts
deleted file mode 100644
index f238598b..00000000
--- a/docs/components/frames/BoardFrame/_groups.ts
+++ /dev/null
@@ -1,405 +0,0 @@
-import { type Box, textWidth, wrapWords } from "@/components/frames/FlowPlot/_scene";
-import type { BoardData, BoardItem, BoardLink, BoardSize, Direction, LabelPlace } from "@/lib/frames/board";
-import { type Arranged, arrangeIcons } from "./_arrange";
-import { type Anchor, ellipsisOf, emptyMain, inlineIcons, inlineWidth, MAIN_PAD, type MainLayout, type SceneRule } from "./_scene";
-import { ROLE, TIER, weightOf } from "./_tokens";
-
-/** Room around a title, on top of its line: a box's head, or a cell's and circle's label. */
-const HEAD_ROOM = 12;
-const CELL_ROOM = 8;
-const PAD = 14;
-const BOX_GAP = 18;
-const LINKED_GAP = 40;
-const LANE_START = 14;
-const LANE = 12;
-const MIN_BOX = 140;
-const MIN_CELL = 96;
-const MIN_CIRCLE = 56;
-const LABEL_ROOM = 16;
-const PAIR_SPREAD = 18;
-const TEXT_WRAP = 240;
-const CONTENT_GAP = 8;
-const BODY = TIER[ROLE.body];
-
-interface Row {
- text: string;
- icons: string[];
- indent: number;
- centered: boolean;
-}
-
-interface TextBlock {
- w: number;
- h: number;
- rows: Row[];
-}
-
-/** Items laid out in rows of `cols`, every column as wide as the widest item, every row as tall as its tallest. */
-interface Grid {
- cols: number;
- cellW: number;
- rows: number[];
- w: number;
- h: number;
-}
-
-const gridOf = (items: { w: number; h: number }[], columns: number, gap: number): Grid => {
- const cols = Math.min(columns, items.length);
- const cellW = Math.max(...items.map(i => i.w));
- const rows = Array.from({ length: Math.ceil(items.length / cols) }, (_, r) => Math.max(...items.slice(r * cols, r * cols + cols).map(i => i.h)));
- return { cols, cellW, rows, w: cols * cellW + (cols - 1) * gap, h: rows.reduce((a, b) => a + b, 0) + (rows.length - 1) * gap };
-};
-
-/** Places items into a grid stretched to w × h; `rule` draws the lines between cells (none between boxes). */
-const placeGrid = <T,>(items: T[], grid: Grid, x: number, y: number, w: number, h: number, gap: number, put: (item: T, x: number, y: number, w: number, h: number) => void, rule?: (d: string) => void) => {
- const cellW = (w - gap * (grid.cols - 1)) / grid.cols;
- const extra = (h - grid.h) / grid.rows.length;
- let top = y;
- grid.rows.forEach((rowH, r) => {
- const height = rowH + extra;
- if (r && rule) rule(`M${x},${top}H${x + w}`);
- items.slice(r * grid.cols, r * grid.cols + grid.cols).forEach((item, c) => {
- const left = x + c * (cellW + gap);
- if (c && rule) rule(`M${left},${top}V${top + height}`);
- put(item, left, top, cellW, height);
- });
- top += height + gap;
- });
-};
-
-interface Sized {
- item: BoardItem;
- depth: number;
- dir: Direction;
- boxed: boolean;
- at: LabelPlace;
- band: number;
- titleTier: BoardSize;
- titleRole: "title" | "label";
- titleIcons: string[];
- /** The title, wrapped like body text when it's long. */
- titleLines: string[];
- gap: number;
- iconPx: number;
- icons: Arranged | null;
- text: TextBlock | null;
- content: { w: number; h: number };
- kids: Sized[];
- grid: Grid | null;
- diameter: number;
- w: number;
- h: number;
-}
-
-type Frame = Omit<SceneRule, "d">;
-
-const across = (dir: Direction): Direction => (dir === "vertical" ? "horizontal" : "vertical");
-const sum = (values: number[]) => values.reduce((a, b) => a + b, 0);
-
-const textBlock = (lines: BoardItem["lines"]): TextBlock | null => {
- if (!lines.length) return null;
- const rows = lines.flatMap(line => {
- const indent = inlineWidth(line.icons.length, ROLE.body);
- return wrapWords(line.text, TEXT_WRAP - indent, BODY.text).map((text, i) => ({ text, icons: i ? [] : line.icons, indent, centered: !line.icons.length }));
- });
- return { w: Math.max(...rows.map(r => r.indent + textWidth(r.text, BODY.text))), h: rows.length * BODY.line, rows };
-};
-
-const labelW = (link: BoardLink) => (link.label ? textWidth(link.label, TIER[ROLE.annotation].text) : 0);
-
-const pad = (links: BoardLink[], route: BoardLink["route"]) => {
- const on = links.filter(l => l.route === route);
- const label = Math.max(0, ...on.map(labelW));
- const room = !label ? 0 : route === "left" || route === "right" ? label + 8 : 14;
- return Math.max(MAIN_PAD, LANE_START + Math.max(0, on.length - 1) * LANE + 12 + room);
-};
-
-export const layoutGroups = (main: BoardData["main"], x0: number, y0: number): MainLayout => {
- const dir = main.direction ?? "vertical";
- const parentOf = new Map<string, BoardItem>();
- const walk = (items: BoardItem[]) =>
- items.forEach(item => {
- item.children.forEach(child => parentOf.set(child.id, item));
- walk(item.children);
- });
- walk(main.items);
- const siblings = (link: BoardLink) => {
- const parent = parentOf.get(link.from);
- return parent !== undefined && parent === parentOf.get(link.to) && parent.split === "boxes";
- };
- const direct = main.links.filter(l => l.route === "direct");
- const gapFor = (links: BoardLink[], along: Direction) =>
- links.length ? Math.max(LINKED_GAP, along === "horizontal" ? Math.max(0, ...links.map(labelW)) + 2 * LABEL_ROOM : 0) : BOX_GAP;
-
- const measure = (item: BoardItem, depth: number, parentDir: Direction, boxed: boolean): Sized => {
- const itemDir = item.direction ?? across(parentDir);
- const split = item.split === "boxes";
- const circle = item.shape === "circle";
- const headed = boxed && !circle;
- const titleRole = headed ? "title" : "label";
- const titleTier = item.size ?? ROLE[titleRole];
- const iconPx = TIER[item.size ?? ROLE.icon].icon;
- const titleIcons = item.iconsAt === "label" ? item.icons : [];
- const icons = item.icons.length && !titleIcons.length ? arrangeIcons(item.icons.length, item.arrange ?? "grid", item.id, iconPx) : null;
- const text = textBlock(item.lines);
- const content = {
- w: Math.max(icons?.w ?? 0, text?.w ?? 0),
- h: (icons?.h ?? 0) + (icons && text ? CONTENT_GAP : 0) + (text?.h ?? 0),
- };
- const kids = item.children.map(child => measure(child, depth + 1, itemDir, split));
- const ids = new Set(item.children.map(c => c.id));
- const gap = split ? gapFor(direct.filter(l => siblings(l) && ids.has(l.from)), itemDir) : 0;
- const at = item.labelAt ?? (circle ? "below" : "head");
- const grid = item.columns && kids.length ? gridOf(kids, item.columns, split ? BOX_GAP : 0) : null;
- const spread = (values: number[]) => sum(values) + gap * (values.length - 1);
- const inset = split && item.border !== "none" ? 2 * PAD : 0;
- const kidsW = !kids.length ? 0 : (grid ? grid.w : itemDir === "horizontal" ? spread(kids.map(k => k.w)) : Math.max(...kids.map(k => k.w))) + inset;
- const kidsH = !kids.length ? 0 : (grid ? grid.h : itemDir === "horizontal" ? Math.max(...kids.map(k => k.h)) : spread(kids.map(k => k.h))) + inset;
- const title = TIER[titleTier];
- // A title wraps only when it's wider than both the body-text width and what its box already holds.
- const titleIconsW = inlineWidth(titleIcons.length, titleTier);
- const titleLines = wrapWords(item.label, Math.max(TEXT_WRAP, content.w, kidsW - 2 * PAD) - titleIconsW, title.text);
- const label = Math.max(...titleLines.map(line => textWidth(line, title.text))) + titleIconsW + 2 * PAD;
- const band = Math.max(titleLines.length * title.line, titleIcons.length ? title.inline : 0) + (headed ? HEAD_ROOM : CELL_ROOM);
- const base = { item, depth, dir: itemDir, boxed, at, band, titleTier, titleRole, titleIcons, titleLines, gap, iconPx, icons, text, content, kids, grid, diameter: 0 } as const;
- if (circle) {
- const diameter = Math.max(MIN_CIRCLE, Math.hypot(content.w, content.h) + PAD);
- return { ...base, diameter, w: Math.max(label, diameter), h: band + diameter };
- }
- if (at === "below") return { ...base, w: Math.max(label, content.w + 2 * PAD), h: PAD + content.h + band };
- const contentH = content.h ? content.h + (boxed ? 2 * PAD : PAD) : 0;
- return {
- ...base,
- w: Math.max(boxed ? MIN_BOX : MIN_CELL, label, content.w + 2 * PAD, kidsW),
- h: band + contentH + kidsH,
- };
- };
-
- const sized = main.items.map(item => measure(item, 0, dir, true));
- const gap = gapFor(direct.filter(l => !siblings(l)), dir);
- const along = (s: Sized) => (dir === "vertical" ? s.h : s.w);
- const cross = Math.max(...sized.map(s => (dir === "vertical" ? s.w : s.h)));
- const length = sum(sized.map(along)) + (sized.length - 1) * gap;
- const [padL, padR, padT, padB] = (["left", "right", "top", "bottom"] as const).map(side => pad(main.links, side));
- const mainGrid = main.columns ? gridOf(sized, main.columns, BOX_GAP) : null;
- const layout = emptyMain(
- (mainGrid ? mainGrid.w : dir === "vertical" ? cross : length) + padL + padR,
- (mainGrid ? mainGrid.h : dir === "vertical" ? length : cross) + padT + padB
- );
- const childDir = new Map<string, Direction>();
-
- const placeContent = (s: Sized, cx: number, top: number) => {
- if (s.icons) {
- const { w, points } = s.icons;
- s.item.icons.forEach((ref, i) => {
- const p = points[i];
- layout.icons.push({ ref, x: cx - w / 2 + p.x - s.iconPx / 2, y: top + p.y - s.iconPx / 2, w: s.iconPx, h: s.iconPx });
- });
- }
- if (!s.text) return;
- const textTop = top + (s.icons ? s.icons.h + CONTENT_GAP : 0);
- const left = cx - s.text.w / 2;
- s.text.rows.forEach((row, i) => {
- const y = textTop + i * BODY.line + BODY.line / 2;
- const text = { y, text: row.text, tier: ROLE.body, role: "body" } as const;
- const dots = row.centered && ellipsisOf(row.text);
- if (dots) {
- layout.dots.push({ x: cx, y, ...dots });
- return;
- }
- if (row.centered) {
- layout.labels.push({ ...text, x: cx, anchor: "middle" });
- return;
- }
- layout.icons.push(...inlineIcons(row.icons, left, y, ROLE.body));
- layout.labels.push({ ...text, x: left + row.indent, anchor: "start" });
- });
- };
-
- /** The title's lines centered on (cx, cy), its icons in front; with `left`, starting at that x instead (a section heading). */
- const placeTitle = (s: Sized, cx: number, cy: number, left?: number, width?: number) => {
- const dots = ellipsisOf(s.item.label);
- if (dots) {
- layout.dots.push({ x: cx, y: cy, ...dots });
- return;
- }
- const { text: size, line } = TIER[s.titleTier];
- const iconsW = inlineWidth(s.titleIcons.length, s.titleTier);
- // A box stretched wider than it measured can take its title on fewer lines.
- const lines = width && s.titleLines.length > 1 ? wrapWords(s.item.label, width - iconsW, size) : s.titleLines;
- const start = left ?? (iconsW ? cx - (iconsW + Math.max(...lines.map(l => textWidth(l, size)))) / 2 : undefined);
- const firstY = cy - ((lines.length - 1) / 2) * line;
- if (iconsW) layout.icons.push(...inlineIcons(s.titleIcons, start!, firstY, s.titleTier));
- lines.forEach((text, i) => {
- const y = cy + (i - (lines.length - 1) / 2) * line;
- const label = { y, text, tier: s.titleTier, role: s.titleRole, weight: weightOf(s.titleRole) };
- layout.labels.push(start === undefined ? { ...label, x: cx, anchor: "middle" } : { ...label, x: start + iconsW, anchor: "start" });
- });
- };
-
- /** A box that's only a title keeps its own height in a row instead of stretching to its neighbours'. */
- const compact = (s: Sized) => s.at === "head" && !s.kids.length && !s.content.h && !s.diameter;
-
- const place = (s: Sized, x: number, y: number, w: number, h: number, anchor: Omit<Anchor, "x" | "y" | "box">, frame: Frame = {}) => {
- const { id, color, border } = s.item;
- if (s.diameter) {
- const cx = x + w / 2;
- const centered = y + Math.max(0, (h - s.diameter) / 2);
- const top = s.at === "above" ? Math.max(centered, y + s.band) : Math.min(centered, y + h - s.h);
- const body = { x: cx - s.diameter / 2, y: top, w: s.diameter, h: s.diameter };
- layout.anchors.set(id, { ...anchor, x: cx, y: body.y + s.diameter / 2, box: body });
- placeTitle(s, cx, s.at === "above" ? body.y - s.band / 2 : body.y + s.diameter + s.band / 2 + 1);
- layout.boxes.push({ id, ...body, color, border, shape: "circle", depth: s.depth });
- placeContent(s, cx, body.y + (s.diameter - s.content.h) / 2);
- return;
- }
- const below = s.at === "below" ? y + (h - s.content.h - s.band) / 2 + (s.content.h ? PAD / 2 : 0) : 0;
- // A borderless item that's only a title is anchored on its title, so arrows meet it head-on.
- const bareTitle = s.at === "below" && !s.content.h && border === "none";
- const box = s.at === "above" ? { x, y: y + s.band, w, h: h - s.band } : bareTitle ? { x, y: below, w, h: s.band } : { x, y, w, h };
- layout.anchors.set(id, { ...anchor, x: x + w / 2, y: box.y + box.h / 2, box });
- const framed = s.boxed && border !== "none";
- if (framed) layout.boxes.push({ id, ...box, color, border, depth: s.depth, holds: s.item.split === "boxes" && s.kids.length > 0 });
- const inner = framed ? { color, border } : frame;
- const rule = (d: string) => layout.rules.push({ d, ...inner });
- if (s.at === "below") {
- placeContent(s, x + w / 2, below);
- placeTitle(s, x + w / 2, below + s.content.h + s.band / 2, undefined, w - 2 * PAD);
- return;
- }
- const titleOnly = !s.content.h && !s.kids.length;
- // A borderless row's title above it reads as a section heading: flush left. A column of cards keeps it centered.
- const heading = s.at === "above" && border === "none" && s.kids.length > 0 && s.dir === "horizontal";
- placeTitle(s, x + w / 2, s.at === "head" && titleOnly ? y + h / 2 : y + s.band / 2 + (s.boxed ? 0 : 3), heading ? x : undefined, w - 2 * PAD);
- if (s.at === "head" && framed && (s.content.h || s.kids.length)) rule(`M${x},${y + s.band}H${x + w}`);
- let top = y + s.band;
- const split = s.item.split === "boxes";
- if (s.content.h) {
- const area = s.kids.length ? s.content.h + (s.boxed ? 2 * PAD : PAD) : y + h - top;
- const blockTop = s.kids.length ? top + (s.boxed ? PAD : 0) : top + (area - s.content.h) / 2 - (s.boxed ? 0 : PAD / 4);
- placeContent(s, x + w / 2, blockTop);
- top += area;
- if (s.kids.length && !split) rule(`M${x},${top}H${x + w}`);
- }
- if (!s.kids.length) return;
- childDir.set(id, s.dir);
- const bottom = y + h;
- if (s.grid) {
- const inset = split && border !== "none" ? PAD : 0;
- const put = (kid: Sized, kx: number, ky: number, kw: number, kh: number) => place(kid, kx, ky, kw, kh, anchor, inner);
- placeGrid(s.kids, s.grid, x + inset, top + inset, w - 2 * inset, bottom - top - 2 * inset, split ? BOX_GAP : 0, put, split ? undefined : rule);
- return;
- }
- if (split) {
- const inset = border === "none" ? 0 : PAD;
- const [ix, iy, iw, ih] = [x + inset, top + inset, w - 2 * inset, bottom - top - 2 * inset];
- if (s.dir === "horizontal") {
- const extra = (iw - sum(s.kids.map(k => k.w)) - s.gap * (s.kids.length - 1)) / s.kids.length;
- let cx = ix;
- for (const kid of s.kids) {
- if (compact(kid)) place(kid, cx, iy + (ih - kid.h) / 2, kid.w + extra, kid.h, anchor, inner);
- else place(kid, cx, iy, kid.w + extra, ih, anchor, inner);
- cx += kid.w + extra + s.gap;
- }
- } else {
- let cy = iy;
- for (const kid of s.kids) {
- place(kid, ix, cy, iw, kid.h, anchor, inner);
- cy += kid.h + s.gap;
- }
- }
- return;
- }
- if (s.dir === "horizontal") {
- const extra = (w - sum(s.kids.map(k => k.w))) / s.kids.length;
- let cx = x;
- s.kids.forEach((kid, i) => {
- if (i) rule(`M${cx},${top}V${bottom}`);
- place(kid, cx, top, kid.w + extra, bottom - top, anchor, inner);
- cx += kid.w + extra;
- });
- } else {
- const extra = (bottom - top - sum(s.kids.map(k => k.h))) / s.kids.length;
- let cy = top;
- s.kids.forEach((kid, i) => {
- if (i) rule(`M${x},${cy}H${x + w}`);
- place(kid, x, cy, w, kid.h + extra, anchor, inner);
- cy += kid.h + extra;
- });
- }
- };
-
- const roots: Box[] = [];
- if (mainGrid) {
- placeGrid(sized, mainGrid, x0 + padL, y0 + padT, mainGrid.w, mainGrid.h, BOX_GAP, (s, x, y, w, h) => {
- place(s, x, y, w, h, { left: x - 2, right: x + w + 2, gutter: y + h + BOX_GAP / 2, root: roots.length });
- roots.push({ x, y, w, h });
- });
- return layout;
- }
- // Plain boxes beside a bordered group line up with the boxes inside it.
- const groupInset = sized.some(s => s.item.split === "boxes" && s.kids.length && s.item.border !== "none") ? PAD : 0;
- let cursor = dir === "vertical" ? y0 + padT : x0 + padL;
- sized.forEach((s, i) => {
- const [x, y] = dir === "vertical" ? [x0 + padL, cursor] : [cursor, y0 + padT];
- const [w, h] = dir === "vertical" ? [cross, s.h] : [s.w, cross];
- const last = i === sized.length - 1;
- const gutter = dir === "vertical" && !last ? y + h + gap / 2 : y + h + padB / 2;
- const inset = !s.kids.length && !s.diameter ? groupInset : 0;
- const [px, py, pw, ph] =
- dir === "vertical" ? [x + inset, y, w - 2 * inset, h] : compact(s) ? [x, y + (h - s.h) / 2, w, s.h] : [x, y + inset, w, h - 2 * inset];
- place(s, px, py, pw, ph, { left: px - 2, right: px + pw + 2, gutter, root: i });
- roots.push(s.at === "above" ? layout.anchors.get(s.item.id)!.box : { x, y, w, h });
- cursor += along(s) + gap;
- });
-
- const used = { left: 0, right: 0, top: 0, bottom: 0 };
- const pairs = new Map<string, BoardLink[]>();
- for (const link of direct) {
- const key = [link.from, link.to].sort().join(" ");
- pairs.set(key, [...(pairs.get(key) ?? []), link]);
- }
- for (const link of main.links) {
- const a = layout.anchors.get(link.from)!;
- const b = layout.anchors.get(link.to)!;
- const [ra, rb] = [roots[a.root], roots[b.root]];
- const push = (d: string, label?: { x: number; y: number; anchor: "start" | "middle" | "end" }) => {
- layout.links.push({ d, start: link.both, end: true, dashed: link.dashed });
- if (link.label && label) layout.linkLabels.push({ ...label, text: link.label, tier: ROLE.annotation });
- };
- if (link.route === "direct") {
- const inside = siblings(link);
- const parent = parentOf.get(link.from);
- const axis = inside ? childDir.get(parent!.id)! : dir;
- // A nested box's arrow starts and ends at that box, crossing its parent's edge, so field-to-field arrows read as such.
- const top = (id: string) => main.items.some(i => i.id === id);
- const [ea, eb] = inside ? [a.box, b.box] : [top(link.from) ? ra : a.box, top(link.to) ? rb : b.box];
- const order = (id: string) => parent!.children.findIndex(c => c.id === id);
- const forward = inside ? order(link.from) < order(link.to) : a.root < b.root;
- const twins = pairs.get([link.from, link.to].sort().join(" "))!;
- const spread = (twins.indexOf(link) - (twins.length - 1) / 2) * PAIR_SPREAD;
- // Of two arrows side by side, the first is labelled on its outer side, so neither label crosses the other arrow.
- const outside = twins.length > 1 && twins.indexOf(link) === 0;
- if (axis === "vertical") {
- const [lo, hi] = [Math.max(a.box.x, b.box.x), Math.min(a.box.x + a.box.w, b.box.x + b.box.w)];
- const x = (lo < hi ? (lo + hi) / 2 : ea.x + ea.w / 2) + spread;
- const [y1, y2] = forward ? [ea.y + ea.h, eb.y - 1] : [ea.y, eb.y + eb.h + 1];
- push(`M${x},${y1}V${y2}`, outside ? { x: x - 8, y: (y1 + y2) / 2, anchor: "end" } : { x: x + 8, y: (y1 + y2) / 2, anchor: "start" });
- } else {
- const [lo, hi] = [Math.max(a.box.y, b.box.y), Math.min(a.box.y + a.box.h, b.box.y + b.box.h)];
- const y = (lo < hi ? (lo + hi) / 2 : ea.y + ea.h / 2) + spread;
- const [x1, x2] = forward ? [ea.x + ea.w, eb.x - 1] : [ea.x, eb.x + eb.w + 1];
- push(`M${x1},${y}H${x2}`, { x: (x1 + x2) / 2, y: twins.length > 1 && !outside ? y + 11 : y - 9, anchor: "middle" });
- }
- continue;
- }
- const lane = LANE_START + used[link.route]++ * LANE;
- const outer = LANE_START + (main.links.filter(l => l.route === link.route).length - 1) * LANE;
- const midX = (a.x + b.x) / 2;
- if (link.route === "left") push(`M${ra.x},${a.y}H${ra.x - lane}V${b.y}H${rb.x - 1}`, { x: ra.x - outer - 6, y: b.y, anchor: "end" });
- if (link.route === "right") push(`M${ra.x + ra.w},${a.y}H${ra.x + ra.w + lane}V${b.y}H${rb.x + rb.w + 1}`, { x: ra.x + ra.w + outer + 6, y: b.y, anchor: "start" });
- if (link.route === "top") push(`M${a.x},${ra.y}V${ra.y - lane}H${b.x}V${rb.y - 1}`, { x: midX, y: ra.y - outer - 8, anchor: "middle" });
- if (link.route === "bottom") push(`M${a.x},${ra.y + ra.h}V${ra.y + ra.h + lane}H${b.x}V${rb.y + rb.h + 1}`, { x: midX, y: ra.y + ra.h + outer + 11, anchor: "middle" });
- }
- return layout;
-};
diff --git a/docs/components/frames/BoardFrame/_layout.ts b/docs/components/frames/BoardFrame/_layout.ts
deleted file mode 100644
index 9d40baad..00000000
--- a/docs/components/frames/BoardFrame/_layout.ts
+++ /dev/null
@@ -1,391 +0,0 @@
-import { type Box, type Point, textWidth } from "@/components/frames/FlowPlot/_scene";
-import {
- BOARD_SIDES,
- type BoardNote,
- type BoardNoteColumn,
- type BoardPullout,
- type BoardPulloutLine,
- type BoardData,
- type BoardRadius,
- type BoardSide,
- type BoardSize,
- type BoardType,
- pulloutLines,
- type LineEnd,
-} from "@/lib/frames/board";
-import { type Arranged, arrangeIcons } from "./_arrange";
-import { layoutGroups } from "./_groups";
-import {
- type Anchor,
- ARROW_LENGTH,
- type BoardScene,
- END_CIRCLE,
- inlineIcons,
- inlineWidth,
- MAGNIFIER,
- type SceneIcon,
- type ScenePullout,
- type SceneMark,
- type SceneText,
- TEXT_INSET,
-} from "./_scene";
-import { ROLE, TIER, weightOf } from "./_tokens";
-import { layoutTree } from "./_tree";
-import { layoutVenn } from "./_venn";
-
-const PANEL_PAD = 32;
-const HEADING_ROOM = 40;
-const NOTE_GAP = 64;
-const PULLOUT_GAP = 56;
-const PULLOUT_STACK = 20;
-const CARD_PAD = 16;
-const PILL_GAP = 10;
-const PILL_MIN = 120;
-const BEND = 14;
-const PLACE_GAP = 8;
-const BOTTOM_GAP = 48;
-const NOTE_SPREAD = 16;
-const ARROW_LABEL_ROOM = 16;
-const BLOCK_GAP = 6;
-const PARALLEL = 20;
-const LEVEL_RAISE = 0.45;
-/** Room above and below the text of a note box, a pill and a card's heading. */
-const NOTE_ROOM = 4;
-const PILL_ROOM = 6;
-const CARD_ROOM = 6;
-const ANNOTATION = TIER[ROLE.annotation];
-const PILL_H = ANNOTATION.line + PILL_ROOM;
-
-const RADII: Record<BoardRadius, BoardScene["radius"]> = {
- none: { panel: 0, box: 0, mark: 0, card: 0 },
- small: { panel: 6, box: 8, mark: 2, card: 4 },
- medium: { panel: 14, box: 16, mark: 4, card: 10 },
- large: { panel: 22, box: 24, mark: 10, card: 16 },
-};
-
-const END_ROOM: Record<LineEnd, number> = { magnifier: MAGNIFIER, circle: END_CIRCLE, dot: 0, arrow: ARROW_LENGTH - 1, none: 0 };
-
-interface Content {
- w: number;
- h: number;
- icons: Arranged | null;
- tier: BoardSize;
-}
-
-const blockOf = (refs: string[], arrange: BoardNote["arrange"], fallback: "line" | "grid", seed: string, tier: BoardSize) =>
- refs.length ? arrangeIcons(refs.length, arrange ?? fallback, seed, TIER[tier].icon) : null;
-
-const placeBlock = (refs: string[], block: Arranged | null, cx: number, top: number, tier: BoardSize): SceneIcon[] => {
- const size = TIER[tier].icon;
- return block ? refs.map((ref, i) => ({ ref, x: cx - block.w / 2 + block.points[i].x - size / 2, y: top + block.points[i].y - size / 2, w: size, h: size })) : [];
-};
-
-const inlineMark = (box: Omit<SceneMark, "text">, label: string, refs: string[], tier: BoardSize) => {
- const inline = inlineWidth(refs.length, tier);
- const cy = box.y + box.h / 2;
- const start = box.x + (box.w - inline - textWidth(label, TIER[tier].text)) / 2;
- return {
- mark: { ...box, text: refs.length ? { x: start + inline, y: cy, text: label, anchor: "start" as const, tier } : { x: box.x + box.w / 2, y: cy, text: label, anchor: "middle" as const, tier } },
- icons: inlineIcons(refs, start, cy, tier),
- };
-};
-
-const noteContent = (note: BoardNote): Content => {
- const tier = note.size ?? ROLE.label;
- const { text, line } = TIER[tier];
- if (note.shape === "box") return { w: inlineWidth(note.icons.length, tier) + textWidth(note.label, text) + 2 * TEXT_INSET, h: line + NOTE_ROOM, icons: null, tier };
- const icons = blockOf(note.icons, note.arrange, "line", note.label, tier);
- return { w: Math.max(textWidth(note.label, text), icons?.w ?? 0), h: (icons ? icons.h + BLOCK_GAP : 0) + line, icons, tier };
-};
-
-const placeNote = (note: BoardNote, size: Content, cx: number, cy: number) => {
- const box = { x: cx - size.w / 2, y: cy - size.h / 2, w: size.w, h: size.h, color: note.color };
- if (note.shape === "box") {
- const { mark, icons } = inlineMark(box, note.label, note.icons, size.tier);
- return { note: { ...mark, bare: false }, icons };
- }
- const textY = box.y + (size.icons ? size.icons.h + BLOCK_GAP : 0) + TIER[size.tier].line / 2;
- return {
- note: { ...box, bare: true, text: { x: cx, y: textY, text: note.label, anchor: "middle" as const, tier: size.tier } },
- icons: placeBlock(note.icons, size.icons, cx, box.y, size.tier),
- };
-};
-
-const ends = (arrow: BoardNote["arrow"]) => ({ start: arrow === "in" || arrow === "both", end: arrow === "out" || arrow === "both" });
-
-const columnSize = (column?: BoardNoteColumn) => {
- if (!column) return { w: 0, gap: 0, sizes: [] as Content[] };
- const sizes = column.items.map(noteContent);
- const labels = column.items.map(n => (n.arrowLabel ? textWidth(n.arrowLabel, ANNOTATION.text) + 2 * ARROW_LABEL_ROOM : 0));
- return {
- w: Math.max(...sizes.map(s => s.w), column.heading ? textWidth(column.heading, TIER[ROLE.title].text) : 0),
- gap: Math.max(NOTE_GAP, ...labels),
- sizes,
- };
-};
-
-const pulloutSize = (pullout: BoardPullout) => {
- const bare = pullout.shape === "none";
- const tier = pullout.size ?? (bare ? ROLE.actor : ROLE.label);
- const { text, line } = TIER[tier];
- const cardHead = line + CARD_ROOM;
- const icons = blockOf(pullout.icons, pullout.arrange, "grid", pullout.for ?? pullout.heading ?? "pullout", tier);
- const pills = pullout.items.map(i => inlineWidth(i.icons.length, ROLE.annotation) + textWidth(i.label, ANNOTATION.text) + 2 * TEXT_INSET);
- const heading = pullout.heading ? textWidth(pullout.heading, text) : 0;
- const inner = Math.max(pullout.items.length ? PILL_MIN : 0, ...pills, icons?.w ?? 0, heading);
- const pillsH = pullout.items.length ? pullout.items.length * PILL_H + (pullout.items.length - 1) * PILL_GAP : 0;
- if (bare) {
- const above = (icons ? icons.h + BLOCK_GAP : 0) + (pullout.heading ? line : 0);
- const h = above + (pillsH ? (above ? PILL_GAP : 0) + pillsH : 0);
- return { bare, tier, cardHead, inner, icons, w: inner, h, half: { w: inner / 2, h: h / 2 }, r: 0 };
- }
- const w = inner + 2 * CARD_PAD;
- const h = 2 * CARD_PAD + (pullout.heading ? cardHead : 0) + (icons?.h ?? 0) + (icons && pillsH ? PILL_GAP : 0) + pillsH;
- const r = Math.hypot(w / 2, h / 2) + 10;
- return { bare, tier, cardHead, inner, icons, w, h, half: { w: r, h: r }, r };
-};
-
-const rectRim = (center: Point, half: { w: number; h: number }, from: Point): Point => {
- const [dx, dy] = [from.x - center.x, from.y - center.y];
- const t = Math.min(dx ? half.w / Math.abs(dx) : Infinity, dy ? half.h / Math.abs(dy) : Infinity);
- return { x: center.x + dx * t, y: center.y + dy * t };
-};
-
-const lineLabel = (points: Point[], text: string): SceneText => {
- const segments = points.slice(1).map((p, i) => [points[i], p] as const);
- const [a, b] = segments.reduce((best, seg) => (Math.hypot(seg[1].x - seg[0].x, seg[1].y - seg[0].y) > Math.hypot(best[1].x - best[0].x, best[1].y - best[0].y) ? seg : best));
- const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
- return Math.abs(b.x - a.x) >= Math.abs(b.y - a.y)
- ? { x: mid.x, y: mid.y - 9, text, anchor: "middle", tier: ROLE.annotation }
- : { x: mid.x + 8, y: mid.y, text, anchor: "start", tier: ROLE.annotation };
-};
-
-const unit = (from: Point, to: Point): Point => {
- const d = Math.hypot(to.x - from.x, to.y - from.y) || 1;
- return { x: (to.x - from.x) / d, y: (to.y - from.y) / d };
-};
-
-const toward = (from: Point, to: Point, by: number): Point => {
- const u = unit(from, to);
- return { x: from.x + u.x * by, y: from.y + u.y * by };
-};
-
-const labelled = (text: string, refs: string[], x: number, y: number, anchor: "start" | "middle") => {
- const tier = ROLE.annotation;
- if (!refs.length) return { text: { x, y, text, anchor, tier } as SceneText, icons: [] as SceneIcon[] };
- const inline = inlineWidth(refs.length, tier);
- const left = anchor === "middle" ? x - (inline + textWidth(text, ANNOTATION.text)) / 2 : x;
- return { text: { x: left + inline, y, text, anchor: "start", tier } as SceneText, icons: inlineIcons(refs, left, y, tier) };
-};
-
-const labelWidth = (line: BoardPulloutLine) =>
- line.label ? inlineWidth(line.icons.length, ROLE.annotation) + textWidth(line.label, ANNOTATION.text) + 2 * ARROW_LABEL_ROOM : 0;
-
-const sceneLines = (pullout: BoardPullout, path: Point[], edge: number) => {
- const lines = pulloutLines(pullout);
- const icons: SceneIcon[] = [];
- const u = unit(path[0], path[1]);
- const normal = Math.abs(u.x) >= Math.abs(u.y) ? { x: 0, y: 1 } : { x: 1, y: 0 };
- const scene = lines.map((line, k) => {
- const offset = (k - (lines.length - 1) / 2) * PARALLEL;
- const shifted = path.map(p => ({ x: p.x + normal.x * offset, y: p.y + normal.y * offset }));
- const [first, second] = shifted;
- const [beforeLast, last] = shifted.slice(-2);
- let label: SceneText | undefined;
- if (line.label) {
- const level = Math.abs(last.y - beforeLast.y) < Math.abs(last.x - beforeLast.x);
- const below = lines.length > 1 && k === lines.length - 1;
- const spot = level ? { x: (edge + last.x) / 2, y: last.y + (below ? 11 : -9), anchor: "middle" as const } : lineLabel(shifted, line.label);
- const placed = labelled(line.label, line.icons, spot.x, spot.y, spot.anchor === "start" ? "start" : "middle");
- label = placed.text;
- icons.push(...placed.icons);
- }
- const points = [...shifted];
- points[0] = toward(first, second, END_ROOM[line.start]);
- points[points.length - 1] = toward(last, beforeLast, END_ROOM[line.end]);
- return {
- points,
- style: line.style,
- color: line.color,
- start: { shape: line.start, at: first, dir: unit(second, first) },
- end: { shape: line.end, at: last, dir: unit(beforeLast, last) },
- label,
- };
- });
- return { lines: scene, icons };
-};
-
-export const layoutBoard = (data: BoardData, type: BoardType): BoardScene => {
- const pulloutSizes = { left: (data.pullouts.left ?? []).map(pulloutSize), right: (data.pullouts.right ?? []).map(pulloutSize) };
- const pulloutGap = (side: BoardSide) =>
- Math.max(PULLOUT_GAP, ...(data.pullouts[side] ?? []).flatMap(c => pulloutLines(c).map(labelWidth)));
- const gaps = { left: pulloutGap("left"), right: pulloutGap("right") };
- const reach = (side: BoardSide) => (pulloutSizes[side].length ? Math.max(...pulloutSizes[side].map(s => 2 * s.half.w)) + gaps[side] : 0);
- const columns = { left: columnSize(data.notes.left), right: columnSize(data.notes.right) };
-
- const layoutMain = (x: number, y: number) =>
- type === "groups" ? layoutGroups(data.main, x, y) : type === "venn" ? layoutVenn(data.main, x, y) : layoutTree(data.main.items, x, y);
- const columnSpan = (column: (typeof columns)["left"]) => (column.w ? column.w + column.gap : 0);
- const content = columnSpan(columns.left) + layoutMain(0, 0).w + columnSpan(columns.right);
- const widen = data.heading ? Math.max(0, textWidth(data.heading.text, TIER[ROLE.heading].text) - content) / 2 : 0;
-
- const panelX = reach("left");
- const leftX = panelX + PANEL_PAD + widen;
- const treeX = leftX + columnSpan(columns.left);
- const treeY = PANEL_PAD + (data.heading ? HEADING_ROOM : 0);
- const main = layoutMain(treeX, treeY);
- const treeRight = treeX + main.w;
- const treeBottom = treeY + main.h;
- const rightX = treeRight + columns.right.gap;
- const drawn = [...main.boxes, ...main.bars];
- const edges =
- data.main.border !== "none" || !drawn.length
- ? { left: treeX, right: treeRight, top: treeY, bottom: treeBottom }
- : {
- left: Math.min(...drawn.map(b => b.x)),
- right: Math.max(...drawn.map(b => b.x + b.w)),
- top: Math.min(...drawn.map(b => b.y)),
- bottom: Math.max(...drawn.map(b => b.y + b.h)),
- };
- const whole: Anchor = {
- x: (edges.left + edges.right) / 2,
- y: (edges.top + edges.bottom) / 2,
- left: edges.left,
- right: edges.right,
- gutter: treeBottom + PANEL_PAD / 2,
- root: -1,
- box: { x: edges.left, y: edges.top, w: edges.right - edges.left, h: edges.bottom - edges.top },
- };
- const anchor = (id?: string) => (id ? main.anchors.get(id)! : whole);
-
- const notes: BoardScene["notes"] = [];
- const icons: SceneIcon[] = [];
- const arrows: BoardScene["arrows"] = [];
- const arrowLabels: SceneText[] = [];
- const columnHeadings: SceneText[] = [];
- for (const side of BOARD_SIDES) {
- const column = data.notes[side];
- if (!column) continue;
- const x = side === "left" ? leftX : rightX;
- const { w, sizes } = columns[side];
- if (column.heading) columnHeadings.push({ x: x + w / 2, y: treeY, text: column.heading, anchor: "middle", tier: ROLE.title, weight: weightOf("title") });
- column.items.forEach((item, i) => {
- const a = anchor(item.for);
- const placed = placeNote(item, sizes[i], x + w / 2, a.y);
- notes.push(placed.note);
- icons.push(...placed.icons);
- const [from, to] = side === "right" ? [a.right, placed.note.x - 1] : [a.left, placed.note.x + placed.note.w + 1];
- arrows.push({ d: `M${from},${a.y}H${to}`, ...ends(item.arrow) });
- if (item.arrowLabel) arrowLabels.push({ x: (from + to) / 2, y: a.y - 9, text: item.arrowLabel, anchor: "middle", tier: ROLE.annotation });
- });
- }
-
- let panelRight = (columns.right.w ? rightX + columns.right.w : treeRight) + PANEL_PAD + widen;
- let panelBottom = treeBottom + PANEL_PAD;
- const bottom = data.notes.bottom?.items ?? [];
- if (bottom.length) {
- const top = treeBottom + BOTTOM_GAP;
- const placed = bottom
- .map(item => ({ item, size: noteContent(item), cx: anchor(item.for).x }))
- .sort((p, q) => p.cx - q.cx);
- let edge = leftX - NOTE_SPREAD;
- for (const p of placed) {
- p.cx = Math.max(p.cx, edge + NOTE_SPREAD + p.size.w / 2);
- edge = p.cx + p.size.w / 2;
- const { note, icons: noteIcons } = placeNote(p.item, p.size, p.cx, top + p.size.h / 2);
- notes.push(note);
- icons.push(...noteIcons);
- const from = p.item.for && data.main.border === "none" ? anchor(p.item.for).box.y + anchor(p.item.for).box.h : edges.bottom;
- arrows.push({ d: `M${p.cx},${from}V${top - 1}`, ...ends(p.item.arrow) });
- if (p.item.arrowLabel) arrowLabels.push({ x: p.cx + 8, y: (from + top) / 2, text: p.item.arrowLabel, anchor: "start", tier: ROLE.annotation });
- }
- panelRight = Math.max(panelRight, edge + PANEL_PAD);
- panelBottom = Math.max(...placed.map(p => top + p.size.h)) + PANEL_PAD;
- }
- const panel = { x: panelX, y: 0, w: panelRight - panelX, h: panelBottom, border: data.panel };
-
- const pullouts: ScenePullout[] = [];
- for (const side of BOARD_SIDES) {
- const dir = side === "right" ? 1 : -1;
- let floor = -Infinity;
- (data.pullouts[side] ?? []).forEach((pullout, i) => {
- const size = pulloutSizes[side][i];
- const target = anchor(pullout.for);
- const start = { x: side === "right" ? edges.right : edges.left, y: target.y };
- const gap = gaps[side];
- const circle = { x: side === "right" ? panelRight + gap + size.half.w : panelX - gap - size.half.w, y: 0, r: size.r };
- const level = size.bare ? start.y : start.y - size.r * LEVEL_RAISE;
- const wanted = { above: start.y - size.half.h - PLACE_GAP, level, below: start.y + size.half.h + PLACE_GAP }[pullout.place];
- circle.y = Math.max(wanted, floor + PULLOUT_STACK + size.half.h);
- floor = circle.y + size.half.h;
- const bend = { x: start.x + dir * BEND, y: target.gutter };
- const exit = { x: side === "right" ? panelRight + gap / 2 : panelX - gap / 2, y: bend.y };
- const via = pullout.route === "gap" ? [bend, exit] : [];
- const from = via.at(-1) ?? start;
- const rim = size.bare ? rectRim(circle, { w: size.half.w + BLOCK_GAP, h: size.half.h + BLOCK_GAP }, from) : toward(circle, from, size.r);
- const card = { x: circle.x - size.w / 2, y: circle.y - size.h / 2, w: size.w, h: size.h };
- let top = size.bare ? card.y : card.y + CARD_PAD + (pullout.heading ? size.cardHead : 0);
- icons.push(...placeBlock(pullout.icons, size.icons, circle.x, top, size.tier));
- if (size.icons) top += size.icons.h + (size.bare ? BLOCK_GAP : PILL_GAP);
- let heading: SceneText | undefined;
- if (pullout.heading) {
- const line = TIER[size.tier].line;
- heading = size.bare
- ? { x: circle.x, y: top + line / 2, text: pullout.heading, anchor: "middle", tier: size.tier, weight: weightOf("actor") }
- : { x: circle.x, y: card.y + CARD_PAD + size.cardHead / 2 - 4, text: pullout.heading, anchor: "middle", tier: size.tier };
- if (size.bare) top += line + PILL_GAP;
- }
- const pills = pullout.items.map((item, j) => {
- const placed = inlineMark({ x: circle.x - size.inner / 2, y: top + j * (PILL_H + PILL_GAP), w: size.inner, h: PILL_H, color: item.color }, item.label, item.icons, ROLE.annotation);
- icons.push(...placed.icons);
- return placed.mark;
- });
- const drawn = sceneLines(pullout, [start, ...via, rim], side === "right" ? panelRight : panelX);
- icons.push(...drawn.icons);
- pullouts.push({
- shape: pullout.shape,
- lines: drawn.lines,
- circle,
- extent: size.half,
- card,
- heading,
- pills,
- });
- });
- }
-
- const heading = data.heading
- ? {
- x: data.heading.align === "left" ? leftX : data.heading.align === "right" ? panelRight - PANEL_PAD : panelX + panel.w / 2,
- y: PANEL_PAD + 8,
- text: data.heading.text,
- tier: ROLE.heading,
- weight: weightOf("heading"),
- anchor: data.heading.align === "left" ? ("start" as const) : data.heading.align === "right" ? ("end" as const) : ("middle" as const),
- }
- : undefined;
-
- const viewTop = Math.min(0, ...pullouts.map(l => l.circle.y - l.extent.h - MAGNIFIER)) - 2;
- const viewBottom = Math.max(panel.h, ...pullouts.map(l => l.circle.y + l.extent.h + MAGNIFIER)) + 2;
- const viewRight = Math.max(panelRight, ...pullouts.map(l => l.circle.x + l.extent.w + MAGNIFIER)) + 2;
- const viewLeft = Math.min(0, ...pullouts.map(l => l.circle.x - l.extent.w - MAGNIFIER)) - 2;
-
- const colors = [...main.bars, ...main.boxes, ...notes, ...pullouts.flatMap(l => l.pills)].flatMap(m => (m.color ? [m.color] : []));
- const hatch = data.fill === "hatch" ? [...new Set(colors)] : [];
-
- return {
- view: { x: viewLeft, y: viewTop, w: viewRight - viewLeft, h: viewBottom - viewTop },
- radius: RADII[data.radius],
- hatch,
- panel,
- heading,
- mainBox: data.main.border === "none" ? undefined : { x: treeX, y: treeY, w: main.w, h: main.h, border: data.main.border },
- main,
- arrows,
- arrowLabels,
- columnHeadings,
- notes,
- pullouts,
- icons,
- };
-};
diff --git a/docs/components/frames/BoardFrame/_scene.ts b/docs/components/frames/BoardFrame/_scene.ts
deleted file mode 100644
index e6844def..00000000
--- a/docs/components/frames/BoardFrame/_scene.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-import type { Box, Point } from "@/components/frames/FlowPlot/_scene";
-import type { ChartColor } from "@/lib/charts/schema";
-import type { BoardPullout, BoardPulloutLine, BoardItem, BoardSize, LineEnd } from "@/lib/frames/board";
-import { INLINE_GAP, TIER } from "./_tokens";
-
-export const TEXT_INSET = 12;
-export const MAIN_PAD = 24;
-export const MAGNIFIER = 9;
-export const END_CIRCLE = 5;
-export const END_DOT = 3.5;
-export const ARROW_LENGTH = 8;
-export const MIN_SCALE = 0.6;
-
-export interface SceneText {
- x: number;
- y: number;
- text: string;
- anchor: "start" | "middle" | "end";
- tier: BoardSize;
- weight?: "medium";
-}
-
-export interface SceneMark extends Box {
- color?: ChartColor;
- text: SceneText;
-}
-
-export interface SceneIcon extends Box {
- ref: string;
-}
-
-export interface SceneBox extends Box {
- id: string;
- color?: ChartColor;
- border?: BoardItem["border"];
- shape?: "circle" | "ellipse";
- depth: number;
- /** An overlapping venn set: a see-through wash, so the overlap shows. */
- wash?: boolean;
- /** Holds boxes of its own (`split: "boxes"`): drawn with the larger corner radius. */
- holds?: boolean;
-}
-
-export interface SceneEnd {
- shape: LineEnd;
- at: Point;
- dir: Point;
-}
-
-export interface ScenePulloutLine {
- points: Point[];
- style: BoardPulloutLine["style"];
- color?: ChartColor;
- start: SceneEnd;
- end: SceneEnd;
- label?: SceneText;
-}
-
-export interface ScenePullout {
- shape: BoardPullout["shape"];
- lines: ScenePulloutLine[];
- circle: Point & { r: number };
- extent: { w: number; h: number };
- card: Box;
- heading?: SceneText;
- pills: SceneMark[];
-}
-
-export interface Anchor {
- x: number;
- y: number;
- left: number;
- right: number;
- gutter: number;
- root: number;
- box: Box;
-}
-
-export interface SceneRule {
- d: string;
- color?: ChartColor;
- border?: BoardItem["border"];
-}
-
-/** Text that's only an ellipsis: "⋮" (vertical), "…", "⋯" or "..." (horizontal). */
-const ELLIPSIS_TEXT = /^\s*(⋮|…|⋯|\.{3})\s*$/;
-
-export const ellipsisOf = (text: string): { vertical: boolean } | null => (ELLIPSIS_TEXT.test(text) ? { vertical: text.trim() === "⋮" } : null);
-
-export interface SceneDots extends Point {
- vertical: boolean;
-}
-
-export interface MainLayout {
- w: number;
- h: number;
- anchors: Map<string, Anchor>;
- bars: (SceneMark & { id: string })[];
- elbows: string[];
- boxes: SceneBox[];
- rules: SceneRule[];
- labels: (SceneText & { role: "title" | "label" | "body" })[];
- icons: SceneIcon[];
- links: { d: string; start: boolean; end: boolean; dashed: boolean }[];
- linkLabels: SceneText[];
- dots: SceneDots[];
-}
-
-export const emptyMain = (w: number, h: number): MainLayout => ({
- w,
- h,
- anchors: new Map(),
- bars: [],
- elbows: [],
- boxes: [],
- rules: [],
- labels: [],
- icons: [],
- links: [],
- linkLabels: [],
- dots: [],
-});
-
-/** The room inline icons take in front of text of a tier, gap included. */
-export const inlineWidth = (count: number, tier: BoardSize) => (count ? count * TIER[tier].inline + (count - 1) * INLINE_GAP + TIER[tier].gap : 0);
-
-export const inlineIcons = (refs: string[], x: number, cy: number, tier: BoardSize): SceneIcon[] => {
- const size = TIER[tier].inline;
- return refs.map((ref, i) => ({ ref, x: x + i * (size + INLINE_GAP), y: cy - size / 2, w: size, h: size }));
-};
-
-export interface BoardScene {
- view: Box;
- radius: { panel: number; box: number; mark: number; card: number };
- hatch: ChartColor[];
- panel: Box & { border: "solid" | "none" };
- heading?: SceneText;
- mainBox?: Box & { border: "solid" | "dashed" };
- main: MainLayout;
- arrows: { d: string; start: boolean; end: boolean }[];
- arrowLabels: SceneText[];
- columnHeadings: SceneText[];
- notes: (SceneMark & { bare: boolean })[];
- pullouts: ScenePullout[];
- icons: SceneIcon[];
-}
diff --git a/docs/components/frames/BoardFrame/_tokens.ts b/docs/components/frames/BoardFrame/_tokens.ts
deleted file mode 100644
index 5ecb7fa6..00000000
--- a/docs/components/frames/BoardFrame/_tokens.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type * as React from "react";
-import { BOARD_SIZES, type BoardSize } from "@/lib/frames/board";
-
-/**
- * Every size a board draws comes from one of four tiers. `text` and `line` are the font size and the
- * height of one line; `inline` is an icon in front of text of this tier, `icon` an icon standing on its
- * own (in a box, above a label); `gap` separates an inline icon from its text.
- */
-export interface TierTokens {
- text: number;
- line: number;
- inline: number;
- icon: number;
- gap: number;
-}
-
-export const TIER: Record<BoardSize, TierTokens> = {
- xs: { text: 11, line: 16, inline: 14, icon: 20, gap: 4 },
- sm: { text: 12, line: 18, inline: 16, icon: 24, gap: 6 },
- md: { text: 14, line: 20, inline: 18, icon: 40, gap: 6 },
- lg: { text: 18, line: 26, inline: 22, icon: 64, gap: 8 },
-};
-
-/** What each part of a board is, and the tier it's drawn at unless the board sets a `size`. */
-export const ROLE = {
- /** The board's heading. */
- heading: "lg",
- /** Box titles, tree rows, column headings, a bare pullout's heading. */
- title: "md",
- /** Cell and circle titles, notes, a circle pullout's card. */
- label: "sm",
- /** Lines of text inside a box. */
- body: "sm",
- /** Link and line labels, pills. */
- annotation: "xs",
- /** A bare pullout: the user, an input, an output. */
- actor: "md",
- /** Icons standing in a box. */
- icon: "sm",
-} as const satisfies Record<string, BoardSize>;
-
-export type Role = keyof typeof ROLE;
-
-/** Roles drawn at medium weight; every other role is regular. */
-const MEDIUM: ReadonlySet<Role> = new Set<Role>(["heading", "title", "actor"]);
-
-export const weightOf = (role: Role): "medium" | undefined => (MEDIUM.has(role) ? "medium" : undefined);
-
-/** An ellipsis ("⋮", "…") is drawn as three dots this size, readable whatever tier its text would be. */
-export const ELLIPSIS = { r: 2.25, pitch: 8 };
-
-/** Space between two inline icons. */
-export const INLINE_GAP = 4;
-
-/** The font sizes the stylesheet reads, so drawn text is always the size layout measured. */
-export const sizeVars = Object.fromEntries(BOARD_SIZES.map(size => [`--board-text-${size}`, `${TIER[size].text}px`])) as React.CSSProperties;
diff --git a/docs/components/frames/BoardFrame/_tree.ts b/docs/components/frames/BoardFrame/_tree.ts
deleted file mode 100644
index e0b7820c..00000000
--- a/docs/components/frames/BoardFrame/_tree.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { type Point, textWidth } from "@/components/frames/FlowPlot/_scene";
-import { type BoardItem, type BoardRow, flattenItems } from "@/lib/frames/board";
-import { emptyMain, inlineIcons, inlineWidth, MAIN_PAD, type MainLayout, TEXT_INSET } from "./_scene";
-import { ROLE, TIER, weightOf } from "./_tokens";
-
-const ROW = 38;
-const BAR = 26;
-const INDENT = 40;
-const ELBOW = 14;
-const TREE_MIN = 220;
-
-export const layoutTree = (items: BoardItem[], x0: number, y0: number): MainLayout => {
- const rows = flattenItems(items);
- const inner = Math.max(TREE_MIN, ...rows.map(r => r.depth * INDENT + inlineWidth(r.item.icons.length, ROLE.title) + textWidth(r.item.label, TIER[ROLE.title].text) + 2 * TEXT_INSET + 24));
- const barLeft = x0 + MAIN_PAD;
- const barRight = barLeft + inner;
- const main = emptyMain(inner + 2 * MAIN_PAD, rows.length * ROW - (ROW - BAR) + 2 * MAIN_PAD);
- const at = new Map<BoardRow, Point>(rows.map((r, i) => [r, { x: barLeft + r.depth * INDENT, y: y0 + MAIN_PAD + i * ROW }]));
-
- for (const r of rows) {
- const { x, y } = at.get(r)!;
- const mid = y + BAR / 2;
- const bar = { x, y, w: barRight - x, h: BAR };
- main.anchors.set(r.item.id, { x: x + bar.w / 2, y: mid, left: x0, right: barRight + 2, gutter: mid + ROW / 2, root: 0, box: bar });
- main.icons.push(...inlineIcons(r.item.icons, x + TEXT_INSET, mid, ROLE.title));
- main.bars.push({
- id: r.item.id,
- x,
- y,
- w: barRight - x,
- h: BAR,
- color: r.item.color ?? "muted",
- text: { x: barRight - TEXT_INSET, y: mid, text: r.item.label, anchor: "end", tier: ROLE.title, weight: weightOf("title") },
- });
- if (r.parent) {
- const parent = at.get(r.parent)!;
- main.elbows.push(`M${parent.x + ELBOW},${parent.y + BAR}V${mid}H${x - 1}`);
- }
- }
- return main;
-};
diff --git a/docs/components/frames/BoardFrame/_venn.ts b/docs/components/frames/BoardFrame/_venn.ts
deleted file mode 100644
index 6b892fe6..00000000
--- a/docs/components/frames/BoardFrame/_venn.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-import { textWidth, wrapWords } from "@/components/frames/FlowPlot/_scene";
-import type { BoardData, BoardItem, BoardMember, BoardSize } from "@/lib/frames/board";
-import { emptyMain, MAIN_PAD, type MainLayout } from "./_scene";
-import { ROLE, TIER, weightOf } from "./_tokens";
-
-/** Room between a circle's edge and what's inside it. */
-const MARGIN = 18;
-/** Between circles side by side, and between members stacked in a region. */
-const GAP = 16;
-const MIN_SET = 72;
-const MIN_LENS = 64;
-const TITLE_ROOM = 10;
-/** Set titles wrap at this width, so a long name doesn't inflate its circle: nested sets narrower than top-level ones. */
-const TITLE_WRAP = { nested: 96, top: 200 };
-/** A member is an ellipse around its text: padding, then how much wider and taller the ellipse is than that box. */
-const MEMBER_PAD = { x: 18, y: 10 };
-const MEMBER_ROUND = { x: 1.3, y: 1.45 };
-
-const BODY = TIER[ROLE.body];
-
-interface Member {
- member: BoardMember;
- w: number;
- h: number;
-}
-
-interface Stack {
- members: Member[];
- w: number;
- h: number;
-}
-
-interface SetSize {
- item: BoardItem;
- depth: number;
- tier: BoardSize;
- titleLines: string[];
- band: number;
- kids: SetSize[];
- own: Stack;
- row: { w: number; h: number };
- /** Child sets without members of their own sit evenly on a ring this far from the middle. */
- ring: number;
- d: number;
-}
-
-const memberOf = (member: BoardMember): Member => {
- const w = Math.max(...member.lines.map(l => textWidth(l.text, BODY.text))) + 2 * MEMBER_PAD.x;
- const h = member.lines.length * BODY.line + 2 * MEMBER_PAD.y;
- return { member, w: w * MEMBER_ROUND.x, h: h * MEMBER_ROUND.y };
-};
-
-const stackOf = (members: BoardMember[]): Stack => {
- const sized = members.map(memberOf);
- return {
- members: sized,
- w: Math.max(0, ...sized.map(m => m.w)),
- h: sized.reduce((sum, m) => sum + m.h, 0) + Math.max(0, sized.length - 1) * GAP,
- };
-};
-
-/** Sets, members and how they relate: a venn's sets are the board's items; nested items are sets inside their parent. */
-export const layoutVenn = (main: BoardData["main"], x0: number, y0: number): MainLayout => {
- const members = main.members;
- const only = (id: string) => members.filter(m => m.in.length === 1 && m.in[0] === id);
-
- const measure = (item: BoardItem, depth: number): SetSize => {
- const tier = item.size ?? (depth ? ROLE.label : ROLE.title);
- // Wrap between words only: never narrower than the longest word, so no word is split.
- const longestWord = Math.max(...item.label.split(/\s+/).map(word => textWidth(word, TIER[tier].text)));
- const titleLines = wrapWords(item.label, Math.max(depth ? TITLE_WRAP.nested : TITLE_WRAP.top, longestWord), TIER[tier].text);
- const band = titleLines.length * TIER[tier].line + TITLE_ROOM;
- const kids = item.children.map(child => measure(child, depth + 1));
- const own = stackOf(only(item.id));
- const row = { w: kids.reduce((sum, k) => sum + k.d, 0) + Math.max(0, kids.length - 1) * GAP, h: Math.max(0, ...kids.map(k => k.d)) };
- const label = Math.max(...titleLines.map(line => textWidth(line, TIER[tier].text)));
- const base = { item, depth, tier, titleLines, band, kids, own, row, ring: 0 };
- if (!kids.length && !own.members.length) return { ...base, d: Math.max(MIN_SET, Math.hypot(label, band) + MARGIN) };
- if (!own.members.length) {
- // Child sets on a ring (one in the middle, two side by side, three in a triangle…), the title above them.
- const kd = row.h;
- // Sibling sets on a ring are drawn the same size, so the ring reads as a set of equals.
- for (const kid of kids) kid.d = kd;
- const ring = kids.length === 1 ? 0 : (kd + GAP) / (2 * Math.sin(Math.PI / kids.length));
- let r = ring + kd / 2 + MARGIN + band / 2;
- // The title sits near the top, where the circle is narrowest: grow it until the title fits that chord.
- while (2 * Math.sqrt(Math.max(0, r * r - (r - MARGIN - band / 2) ** 2)) < label + MARGIN && r < 2000) r += 2;
- return { ...base, ring, d: 2 * r };
- }
- const w = Math.max(label, row.w, own.w);
- const h = band + row.h + (row.h && own.h ? GAP : 0) + own.h;
- return { ...base, d: Math.hypot(w, h) + 2 * MARGIN };
- };
-
- const placeStack = (layout: MainLayout, stack: Stack, cx: number, top: number) => {
- let y = top;
- for (const { member, w, h } of stack.members) {
- layout.boxes.push({ id: `member-${layout.boxes.length}`, x: cx - w / 2, y, w, h, color: member.color, shape: "ellipse", depth: 1 });
- const textTop = y + (h - member.lines.length * BODY.line) / 2;
- member.lines.forEach((line, i) =>
- layout.labels.push({ x: cx, y: textTop + i * BODY.line + BODY.line / 2, text: line.text, anchor: "middle", tier: ROLE.body, role: "body" })
- );
- y += h + GAP;
- }
- };
-
- /** A set's title lines, centered on (x, y). */
- const title = (layout: MainLayout, s: SetSize, x: number, y: number) => {
- const { line } = TIER[s.tier];
- const role = s.depth ? "label" : "title";
- s.titleLines.forEach((text, i) =>
- layout.labels.push({ x, y: y + (i - (s.titleLines.length - 1) / 2) * line, text, anchor: "middle", tier: s.tier, role, weight: weightOf(role) })
- );
- };
-
- const anchorSet = (layout: MainLayout, s: SetSize, cx: number, cy: number, r: number) =>
- layout.anchors.set(s.item.id, { x: cx, y: cy, left: cx - r - 2, right: cx + r + 2, gutter: cy + r + MAIN_PAD / 2, root: 0, box: { x: cx - r, y: cy - r, w: 2 * r, h: 2 * r } });
-
- /** A set and everything inside it, centered on (cx, cy). */
- const placeSet = (layout: MainLayout, s: SetSize, cx: number, cy: number) => {
- const { color, border } = s.item;
- layout.boxes.push({ id: s.item.id, x: cx - s.d / 2, y: cy - s.d / 2, w: s.d, h: s.d, color, border, shape: "circle", depth: s.depth });
- anchorSet(layout, s, cx, cy, s.d / 2);
- if (!s.kids.length && !s.own.members.length) {
- title(layout, s, cx, cy);
- return;
- }
- if (!s.own.members.length) {
- const r = s.d / 2;
- title(layout, s, cx, cy - r + MARGIN + s.band / 2);
- const middle = cy + s.band / 2;
- s.kids.forEach((kid, i) => {
- const angle = -Math.PI / 2 + Math.PI / s.kids.length + (i * 2 * Math.PI) / s.kids.length;
- placeSet(layout, kid, cx + s.ring * Math.cos(angle), middle + s.ring * Math.sin(angle));
- });
- return;
- }
- const h = s.band + s.row.h + (s.row.h && s.own.h ? GAP : 0) + s.own.h;
- const top = cy - h / 2;
- title(layout, s, cx, top + s.band / 2);
- let x = cx - s.row.w / 2;
- for (const kid of s.kids) {
- placeSet(layout, kid, x + kid.d / 2, top + s.band + s.row.h / 2);
- x += kid.d + GAP;
- }
- placeStack(layout, s.own, cx, top + s.band + s.row.h + (s.row.h && s.own.h ? GAP : 0));
- };
-
- const [a, b] = main.items.map(item => measure(item, 0));
- if (!b) {
- const layout = emptyMain(a.d + 2 * MAIN_PAD, a.d + 2 * MAIN_PAD);
- placeSet(layout, a, x0 + MAIN_PAD + a.d / 2, y0 + MAIN_PAD + a.d / 2);
- return layout;
- }
-
- // Two overlapping sets: each one's own members in its crescent, shared members in the lens.
- const both = stackOf(members.filter(m => m.in.length === 2));
- const [onlyA, onlyB] = [a.own, b.own];
- let apart = Math.max(onlyA.w, onlyB.w, MIN_SET) + 2 * MARGIN;
- const lens = Math.max(both.w + 2 * MARGIN, MIN_LENS);
- // Grow the circles until every member's left, right, top and bottom sit inside the circles it belongs to.
- const offsets = (stack: Stack) => {
- let y = -stack.h / 2;
- return stack.members.map(m => {
- const dy = y + m.h / 2;
- y += m.h + GAP;
- return { m, dy };
- });
- };
- const RIM = Array.from({ length: 24 }, (_, i) => (i * Math.PI) / 12);
- const inside = (r: number, dx: number, dy: number, m: Member) =>
- RIM.every(a => Math.hypot(dx + (Math.cos(a) * m.w) / 2, dy + (Math.sin(a) * m.h) / 2) <= r - MARGIN);
- const crescentsFit = (r: number) =>
- offsets(onlyA).every(({ m, dy }) => inside(r, -r + apart / 2, dy, m)) && offsets(onlyB).every(({ m, dy }) => inside(r, r - apart / 2, dy, m));
- const lensFits = (r: number) => offsets(both).every(({ m, dy }) => inside(r, apart / 2, dy, m) && inside(r, -apart / 2, dy, m));
- // A crescent that's too tight needs the circles further apart; a lens that's too tight needs bigger circles.
- let r = (apart + lens) / 2;
- for (let step = 0; step < 1000 && !(crescentsFit(r) && lensFits(r)); step++) {
- if (!crescentsFit(r)) {
- apart += 2;
- r = Math.max(r, (apart + lens) / 2);
- } else r += 2;
- }
- const band = Math.max(a.band, b.band);
- const layout = emptyMain(2 * r + apart + 2 * MAIN_PAD, band + 2 * r + 2 * MAIN_PAD);
- const cy = y0 + MAIN_PAD + band + r;
- const [ax, bx] = [x0 + MAIN_PAD + r, x0 + MAIN_PAD + r + apart];
- for (const [s, cx] of [[a, ax], [b, bx]] as const) {
- layout.boxes.push({ id: s.item.id, x: cx - r, y: cy - r, w: 2 * r, h: 2 * r, color: s.item.color, border: s.item.border, shape: "circle", depth: 0, wash: true });
- anchorSet(layout, s, cx, cy, r);
- title(layout, s, cx, cy - r - band / 2);
- }
- placeStack(layout, onlyA, ax - r + apart / 2, cy - onlyA.h / 2);
- placeStack(layout, onlyB, bx + r - apart / 2, cy - onlyB.h / 2);
- placeStack(layout, both, (ax + bx) / 2, cy - both.h / 2);
- return layout;
-};
diff --git a/docs/components/frames/BoardFrame/styles.module.scss b/docs/components/frames/BoardFrame/styles.module.scss
deleted file mode 100644
index 511e7b45..00000000
--- a/docs/components/frames/BoardFrame/styles.module.scss
+++ /dev/null
@@ -1,231 +0,0 @@
-@import "../vars";
-@import "../FrameShell/frame";
-
-.plot {
- // tokens:start
- $relative-color: "(color: oklch(from red l c h))";
-
- // Every color a board draws. Sizes (--board-text-xs … --board-text-lg) are set on the <svg> from
- // _tokens.ts, the same numbers layout measures text with. Nothing below the tokens mixes a color or
- // names a pixel size.
- --board-surface: var(--bg-card);
- --board-ink: var(--text-primary);
- --board-text: var(--text-primary);
- --board-text-muted: var(--text-secondary);
- --board-frame: var(--border-strong);
- --board-card-fill: color-mix(in srgb, var(--text-secondary) 6%, var(--bg-card));
-
- @supports #{$relative-color} {
- --board-surface: oklch(from var(--bg-card) max(l, 0.24) c h);
- --board-ink: oklch(from var(--text-primary) min(l, 0.82) c h);
- --board-card-fill: color-mix(in srgb, var(--text-secondary) 6%, oklch(from var(--bg-card) max(l, 0.24) c h));
- }
-
- // Anything drawn in a chart color: its fill, stroke and hatch, from the --mark-color it's given.
- .tinted {
- --mark-fill: color-mix(in srgb, var(--mark-color) 12%, var(--board-surface));
- --mark-stroke: color-mix(in srgb, var(--mark-color) 60%, var(--board-surface));
- --mark-hatch: color-mix(in srgb, var(--mark-color) 20%, transparent);
- --mark-icon: color-mix(in srgb, var(--mark-color) 88%, var(--board-ink));
- --mark-wash: color-mix(in srgb, var(--mark-color) 8%, transparent);
-
- @supports #{$relative-color} {
- --mark-fill: oklch(from color-mix(in srgb, var(--mark-color) 12%, var(--board-surface)) max(l, 0.3) calc(c * (2.2 - 1.2 * l)) h);
- --mark-hatch: oklch(from color-mix(in srgb, var(--mark-color) 26%, var(--board-surface)) l c h / clamp(0.2, calc(l * 1.4 - 0.4), 1));
- }
- }
-
- // A box and the rules dividing it share one stroke, so they can't disagree.
- .box {
- --box-fill: var(--board-surface);
- --box-wash: none;
- --box-stroke: var(--board-ink);
-
- &.tinted {
- --box-fill: var(--mark-fill);
- --box-wash: var(--mark-wash);
- --box-stroke: var(--mark-stroke);
- }
- }
- // tokens:end
-
- display: block;
- width: 100%;
- height: auto;
- // No board taller than most of the screen: a taller one scales down to fit, so readers never lose their place in it.
- max-height: 60vh;
- margin: 4px auto 0;
- overflow: visible;
-
- .code {
- font-family: $DM_MONO;
- }
-
- .codeChip {
- fill: color-mix(in srgb, var(--board-text) 9%, transparent);
- }
-
- .text {
- fill: var(--board-text);
-
- &[data-tier="xs"] {
- font-size: var(--board-text-xs);
- }
-
- &[data-tier="sm"] {
- font-size: var(--board-text-sm);
- }
-
- &[data-tier="md"] {
- font-size: var(--board-text-md);
- }
-
- &[data-tier="lg"] {
- font-size: var(--board-text-lg);
- }
-
- &[data-tone="muted"] {
- fill: var(--board-text-muted);
- }
-
- &[data-weight="medium"] {
- font-weight: $FONT_MEDIUM;
- }
-
- &[data-halo] {
- @include halo;
- stroke: var(--board-surface);
- }
- }
-
- .panel {
- fill: var(--board-surface);
- stroke: var(--board-frame);
- stroke-width: 1.25;
-
- &[data-border="none"] {
- stroke: none;
- }
- }
-
- .tree {
- fill: none;
- stroke: var(--board-ink);
-
- &[data-border="dashed"] {
- stroke-dasharray: 6 5;
- }
- }
-
- .boxShape {
- fill: var(--box-fill);
- stroke: var(--box-stroke);
- }
-
- .setShape {
- fill: var(--box-wash);
- stroke: var(--box-stroke);
- }
-
- .rule {
- fill: none;
- stroke: var(--box-stroke);
- }
-
- .boxShape,
- .setShape,
- .rule {
- &[data-border="dashed"] {
- stroke-dasharray: 6 5;
- }
- }
-
- .mark {
- fill: var(--mark-fill);
- stroke: var(--mark-stroke);
- }
-
- .note {
- fill: var(--board-surface);
- stroke: var(--board-frame);
- }
-
- .hatchFill {
- stroke: none;
- }
-
- .hatch {
- stroke: var(--mark-hatch);
- stroke-width: 1.2;
- }
-
- .brand {
- fill: var(--board-ink);
-
- &.tinted {
- fill: var(--mark-icon);
- }
- }
-
- .lineIcon {
- color: var(--board-ink);
-
- &.tinted {
- color: var(--mark-icon);
- }
- }
-
- .line {
- fill: none;
- stroke: var(--board-ink);
-
- &[data-dashed] {
- stroke-dasharray: 4 4;
- }
- }
-
- .arrowHead,
- .ellipsis {
- fill: var(--board-ink);
- }
-
- .pulloutLine {
- --line-color: var(--board-text-muted);
- --end-color: var(--board-ink);
-
- &[data-colored] {
- --line-color: var(--mark-color);
- --end-color: var(--mark-color);
- }
- }
-
- .leader {
- fill: none;
- stroke: var(--line-color);
- stroke-linecap: round;
-
- &[data-style="dashed"] {
- stroke-dasharray: 5 4;
- }
- }
-
- .endHollow {
- fill: var(--board-surface);
- stroke: var(--end-color);
- }
-
- .endSolid {
- fill: var(--end-color);
- }
-
- .lens {
- fill: var(--board-surface);
- stroke: var(--board-ink);
- stroke-width: 1.25;
- }
-
- .card {
- fill: var(--board-card-fill);
- stroke: var(--board-text-muted);
- }
-}
diff --git a/docs/components/frames/ChartFrame/ChartFrame.tsx b/docs/components/frames/ChartFrame/ChartFrame.tsx
deleted file mode 100644
index b143a349..00000000
--- a/docs/components/frames/ChartFrame/ChartFrame.tsx
+++ /dev/null
@@ -1,142 +0,0 @@
-import type * as React from "react";
-import type { ChartDataMap } from "@/lib/charts/store";
-import { type ChartData, isChartType, typeProblems } from "@/lib/charts/schema";
-import FrameShell, { type LegendEntry } from "@/components/frames/FrameShell/FrameShell";
-import { type CategoryType, layoutCategories, categoryCanvas } from "./_categories";
-import type { Canvas } from "./_scene";
-import { ScenePlot } from "./_ScenePlot";
-import { layoutXY, type XYType } from "./_xy";
-import { type DistributionType, layoutDistribution } from "./_distribution";
-import { layoutParts, type PartsType } from "./_parts";
-import { ganttHeight, layoutTime, type TimeType } from "./_time";
-import { layoutMatrix, matrixCanvas, type MatrixType } from "./_matrix";
-import { ChartReveal } from "./_ChartReveal";
-import { FunctionPlot } from "./_FunctionPlot";
-import styles from "./styles.module.scss";
-
-interface ChartFrameProps {
- id: string;
- chart?: ChartData;
-
- type: string;
- title: string;
-
- description: string;
- kicker?: string;
- subtitle?: string;
- note?: string;
- caption?: string;
-}
-
-const canvases = (type: string, chart: ChartData): [Canvas, Canvas] => {
- if (type === "gantt" && chart.shape === "time") {
- return [
- { width: 640, height: ganttHeight(chart.data, 640) },
- { width: 360, height: ganttHeight(chart.data, 360) },
- ];
- }
- if (chart.shape === "matrix") {
- return [matrixCanvas(type as MatrixType, chart.data, 640), matrixCanvas(type as MatrixType, chart.data, 360)];
- }
- if (type === "radar") return [{ width: 640, height: 380 }, { width: 360, height: 340 }];
- if (chart.shape === "categories") {
- return [categoryCanvas(type as CategoryType, chart.data, 640), categoryCanvas(type as CategoryType, chart.data, 360)];
- }
- return [{ width: 640, height: 320 }, { width: 360, height: 320 }];
-};
-
-const LINE_TYPES = new Set(["slope", "function", "line", "area", "stacked-area", "step", "error-bars", "band", "cdf"]);
-
-const legendEntries = (type: string, chart: ChartData): LegendEntry[] => {
- const line = LINE_TYPES.has(type);
- if (chart.shape === "matrix") {
- // Heatmaps print their numbers; confusion matrices say what their two colors mean.
- return type === "confusion-matrix"
- ? [
- { id: "_agree", label: "agree", color: "teal" },
- { id: "_disagree", label: "disagree", color: "pink" },
- ]
- : [];
- }
- const entries: LegendEntry[] = [];
-
- for (const s of type === "funnel" || type === "gantt" ? [] : chart.data.series) {
- if (s.label) entries.push({ id: s.id, label: s.label, color: s.color, line, dashed: "dashed" in s && s.dashed });
- }
-
- if (chart.shape === "parts" && type !== "funnel") {
- const total = chart.data.series.reduce((sum, s) => sum + s.value, 0);
- for (const [k, s] of chart.data.series.entries()) {
- const share = total ? s.value / total : 0;
- entries[k].label = `${s.label} ${share > 0 && share < 0.01 ? "<1%" : `${Math.round(share * 100)}%`}`;
- }
- }
- if (type === "waterfall") {
- entries.push({ id: "_up", label: "increase", color: "teal", line }, { id: "_down", label: "decrease", color: "ember", line });
- }
- return entries;
-};
-
-const Drawing = ({ id, type, chart }: { id: string; type: string; chart: ChartData }): React.ReactElement => {
- const [wide, narrow] = canvases(type, chart);
- if (chart.shape === "function") {
- return (
- <>
- <FunctionPlot spec={chart.data} canvas={wide} clipId={`chart-${id}-wide`} className={styles.wide} />
- <FunctionPlot spec={chart.data} canvas={narrow} clipId={`chart-${id}-narrow`} className={styles.narrow} />
- </>
- );
- }
- const layout = (canvas: Canvas) =>
- chart.shape === "xy"
- ? layoutXY(type as XYType, chart.data, canvas)
- : chart.shape === "distribution"
- ? layoutDistribution(type as DistributionType, chart.data, canvas)
- : chart.shape === "parts"
- ? layoutParts(type as PartsType, chart.data, canvas)
- : chart.shape === "time"
- ? layoutTime(type as TimeType, chart.data, canvas)
- : chart.shape === "matrix"
- ? layoutMatrix(type as MatrixType, chart.data, canvas)
- : layoutCategories(type as CategoryType, chart.data, canvas);
- return (
- <>
- <ScenePlot scene={layout(wide)} canvas={wide} className={styles.wide} />
- <ScenePlot scene={layout(narrow)} canvas={narrow} className={styles.narrow} />
- </>
- );
-};
-
-const ChartFrame: React.FC<ChartFrameProps> = ({ id, chart, type, title, description, kicker, subtitle, note, caption }) => {
- const problems = !chart ? ["unknown or invalid data file"] : !isChartType(type) ? [`unknown type "${type}"`] : typeProblems(type, chart);
- if (!chart || problems.length) {
- console.warn(`[ChartFrame] Can't draw "${id}" as "${type}": ${problems.join("; ")}. Run yarn check:content for details.`);
- return null;
- }
-
- return (
- <FrameShell
- className={styles.frame}
- data={{ "data-chart": id, "data-chart-type": type }}
- title={title}
- description={description}
- kicker={kicker}
- subtitle={subtitle}
- caption={caption}
- legend={legendEntries(type, chart)}
- note={note}
- >
- <ChartReveal>
- <Drawing id={id} type={type} chart={chart} />
- </ChartReveal>
- </FrameShell>
- );
-};
-
-/** Bind MDX to this article's data; authors only supply the local ID. */
-export const createChartFrame = (data: ChartDataMap) =>
- function ArticleChartFrame(props: Omit<ChartFrameProps, "chart">) {
- return <ChartFrame {...props} chart={Object.hasOwn(data, props.id) ? data[props.id] : undefined} />;
- };
-
-export default ChartFrame;
diff --git a/docs/components/frames/ChartFrame/_ChartReveal.tsx b/docs/components/frames/ChartFrame/_ChartReveal.tsx
deleted file mode 100644
index eda8e3bb..00000000
--- a/docs/components/frames/ChartFrame/_ChartReveal.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-"use client";
-
-import type * as React from "react";
-import { useInView } from "react-intersection-observer";
-import styles from "./styles.module.scss";
-
-export const ChartReveal = ({ children }: { children: React.ReactNode }): React.ReactElement => {
- const { ref, inView } = useInView({ triggerOnce: true, threshold: 0.3 });
- return (
- <div ref={ref} className={styles.reveal} data-revealed={inView}>
- {children}
- </div>
- );
-};
diff --git a/docs/components/frames/ChartFrame/_FunctionPlot.tsx b/docs/components/frames/ChartFrame/_FunctionPlot.tsx
deleted file mode 100644
index 86317f67..00000000
--- a/docs/components/frames/ChartFrame/_FunctionPlot.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import type * as React from "react";
-import type { FunctionData } from "@/lib/charts/schema";
-import type { Canvas } from "./_scene";
-import { layoutFunction } from "./_function";
-import styles from "./styles.module.scss";
-
-const n1 = (v: number) => Math.round(v * 10) / 10;
-const color = (name: string) => ({ "--mark-color": `var(--chart-${name})` }) as React.CSSProperties;
-
-export const FunctionPlot = ({
- spec,
- canvas,
- clipId,
- className,
-}: {
- spec: FunctionData;
- canvas: Canvas;
- clipId: string;
- className?: string;
-}): React.ReactElement => {
- const l = layoutFunction(spec, canvas);
- const { plot } = l;
- return (
- <svg
- className={[styles.plot, className].filter(Boolean).join(" ")}
- viewBox={`0 0 ${canvas.width} ${canvas.height}`}
- aria-hidden="true"
- focusable="false"
- >
- <defs>
- <clipPath id={clipId}>
- <rect x={plot.left} y={plot.top} width={plot.right - plot.left} height={plot.bottom - plot.top} />
- </clipPath>
- </defs>
-
- {l.xTicks.map(t => (
- <g key={`x${t.label}`}>
- <line className={t.zero ? styles.gridZero : styles.gridSolid} x1={n1(t.x)} x2={n1(t.x)} y1={plot.top} y2={plot.bottom} />
- <text className={styles.tick} x={n1(t.x)} y={plot.bottom + 16} textAnchor="middle">
- {t.label}
- </text>
- </g>
- ))}
- {l.yTicks.map(t => (
- <g key={`y${t.label}`}>
- <line className={t.zero ? styles.gridZero : styles.gridSolid} x1={plot.left} x2={plot.right} y1={n1(t.y)} y2={n1(t.y)} />
- <text className={styles.tick} x={plot.left - 8} y={n1(t.y + 3.5)} textAnchor="end">
- {t.label}
- </text>
- </g>
- ))}
-
- <g clipPath={`url(#${clipId})`}>
- {l.regions.map((r, i) => (
- <polygon key={i} className={styles.region} points={r.points} style={{ ...color(r.color), fillOpacity: r.opacity }} />
- ))}
- {l.hlines.map(h => (
- <line key={h.y} className={styles.threshold} x1={plot.left} x2={plot.right} y1={n1(h.y)} y2={n1(h.y)} />
- ))}
- {l.vlines.map(v => (
- <line key={v.x} className={styles.vline} style={color(v.color)} x1={n1(v.x)} x2={n1(v.x)} y1={plot.top} y2={plot.bottom} />
- ))}
- {l.drops.map((d, i) => (
- <line key={i} className={styles.drop} style={color(d.color)} x1={n1(d.x)} x2={n1(d.x)} y1={n1(d.y1)} y2={n1(d.y2)} />
- ))}
- {l.curves.map((c, i) => (
- <path
- key={i}
- className={c.dashed ? styles.curveDashed : styles.curve}
- style={{ ...color(c.color), "--i": i } as React.CSSProperties}
- d={c.d}
- pathLength={c.dashed ? undefined : 1}
- />
- ))}
- </g>
-
- {l.axes === "arrows" ? (
- <g className={styles.arrowAxes}>
- <path d={`M${plot.left} ${plot.bottom + 10}H${plot.right}M${plot.right - 6} ${plot.bottom + 6}L${plot.right} ${plot.bottom + 10}L${plot.right - 6} ${plot.bottom + 14}`} />
- <path d={`M${plot.left - 10} ${plot.bottom}V${plot.top}M${plot.left - 14} ${plot.top + 6}L${plot.left - 10} ${plot.top}L${plot.left - 6} ${plot.top + 6}`} />
- </g>
- ) : null}
-
- {l.vlines.map(v =>
- v.label ? (
- <text
- key={`vl${v.x}`}
- className={`${styles.halo} ${styles.annotationLabel}`}
- style={color(v.color)}
- x={n1(v.labelEnd ? v.x - 6 : v.x + 6)}
- y={plot.top + 12}
- textAnchor={v.labelEnd ? "end" : "start"}
- >
- {v.label}
- </text>
- ) : null
- )}
- {l.hlines.map(h =>
- h.label ? (
- <text key={`hl${h.y}`} className={`${styles.halo} ${styles.thresholdLabel}`} x={plot.right - 4} y={n1(h.y - 6)} textAnchor="end">
- {h.label}
- </text>
- ) : null
- )}
- {l.regions.map((r, i) =>
- r.label ? (
- <text key={`rl${i}`} className={`${styles.halo} ${styles.regionLabel}`} x={n1(r.label.x)} y={n1(r.label.y)} textAnchor="middle">
- {r.label.text}
- </text>
- ) : null
- )}
- {l.points.map((p, i) => (
- <g key={`p${i}`} className={styles.point} style={color(p.color)}>
- <circle className={p.hollow ? styles.dotHollow : styles.dot} cx={n1(p.x)} cy={n1(p.y)} r={4.5} />
- {p.label ? (
- <text className={`${styles.halo} ${styles.pointLabel}`} x={n1(p.x)} y={n1(p.y - 11)} textAnchor="middle">
- {p.label}
- </text>
- ) : null}
- </g>
- ))}
-
- {l.xLabel ? (
- <text className={styles.axisLabel} x={n1(l.xLabel.x)} y={n1(l.xLabel.y)} textAnchor="middle">
- {l.xLabel.text}
- </text>
- ) : null}
- {l.yLabel ? (
- <text
- className={styles.axisLabel}
- transform={`translate(${n1(l.yLabel.x)} ${n1(l.yLabel.y)}) rotate(-90)`}
- textAnchor="middle"
- >
- {l.yLabel.text}
- </text>
- ) : null}
- </svg>
- );
-};
diff --git a/docs/components/frames/ChartFrame/_ScenePlot.tsx b/docs/components/frames/ChartFrame/_ScenePlot.tsx
deleted file mode 100644
index b2a36136..00000000
--- a/docs/components/frames/ChartFrame/_ScenePlot.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { fitTicks, fitLabel } from "./_labels";
-import type * as React from "react";
-import type { Canvas, Scene } from "./_scene";
-import styles from "./styles.module.scss";
-
-const n1 = (v: number) => Math.round(v * 10) / 10;
-const color = (name: string) => `var(--chart-${name})`;
-const mark = (name: string, i: number) => ({ "--mark-color": color(name), "--i": i }) as React.CSSProperties;
-
-export const ScenePlot = ({
- scene: s,
- canvas,
- className,
-}: {
- scene: Scene;
- canvas: Canvas;
- className?: string;
-}): React.ReactElement => (
- <svg
- className={[styles.plot, className].filter(Boolean).join(" ")}
- viewBox={`0 0 ${canvas.width} ${canvas.height}`}
- style={canvas.minWidth ? { minWidth: canvas.minWidth } : undefined}
- aria-hidden="true"
- focusable="false"
- >
- {s.rings.map((points, i) => (
- <polygon key={`r${i}`} className={styles.ring} points={points} />
- ))}
- {s.grid.map((g, i) => (
- <line key={`g${i}`} className={styles.grid} x1={n1(g.x1)} y1={n1(g.y1)} x2={n1(g.x2)} y2={n1(g.y2)} />
- ))}
- {fitTicks(s.ticks, canvas, s.axisLabels.some(a => a.rotate) ? 28 : 4).map(t => (
- <text key={`t${t.text}${t.x}${t.y}`} className={styles.tick} x={n1(t.x)} y={n1(t.y)} textAnchor={t.anchor}>
- <title>{t.fullText ?? t.text}</title>
- {t.text}
- </text>
- ))}
- {s.axisLabels.map(a => (
- <text
- key={`a${a.text}`}
- className={styles.axisLabel}
- x={a.rotate ? undefined : n1(a.x)}
- y={a.rotate ? undefined : n1(a.y)}
- transform={a.rotate ? `translate(${n1(a.x)} ${n1(a.y)}) rotate(-90)` : undefined}
- textAnchor="middle"
- >
- <title>{a.text}</title>
- {fitLabel(a.text, a.rotate ? canvas.height - 60 : canvas.width - 80, 12)}
- </text>
- ))}
-
- {s.barGroups.map(g => (
- <g
- key={`b${g.i}`}
- className={g.from === "left" ? styles.barBodyX : styles.barBody}
- style={{ "--i": g.i } as React.CSSProperties}
- >
- {g.bars.map((b, j) => (
- <rect
- key={j}
- className={b.solid ? styles.barSolid : styles.bar}
- style={{ "--mark-color": color(b.color) } as React.CSSProperties}
- x={n1(b.x)}
- y={n1(b.y)}
- width={n1(Math.max(0, b.w))}
- height={n1(Math.max(0, b.h))}
- />
- ))}
- </g>
- ))}
- {s.cells.map(c => (
- <rect
- key={`m${c.i}`}
- className={styles.cell}
- style={{ ...mark(c.color, c.i), fillOpacity: c.opacity }}
- x={n1(c.x)}
- y={n1(c.y)}
- width={n1(c.w)}
- height={n1(c.h)}
- />
- ))}
- {s.polygons.map((p, j) => (
- <polygon
- key={`p${j}`}
- className={p.slice ? styles.slice : p.outline ? styles.area : styles.areaFill}
- style={{ ...mark(p.color, p.i), ...(p.opacity !== undefined ? { fillOpacity: p.opacity } : {}) }}
- points={p.points}
- />
- ))}
- {s.lines.map((l, j) => (
- <path key={`l${j}`} className={styles.curve} style={{ ...mark(l.color, l.i), strokeWidth: l.width }} d={l.d} pathLength={1} />
- ))}
- {s.axis ? <path className={styles.axis} d={s.axis} /> : null}
- {s.thresholds.map((t, j) => (
- <g key={`th${j}`}>
- <path className={styles.threshold} d={t.d} fill="none" />
- {t.label ? (
- <text className={`${styles.halo} ${styles.thresholdLabel}`} x={n1(t.label.x)} y={n1(t.label.y)} textAnchor={t.label.anchor}>
- {t.label.text}
- </text>
- ) : null}
- </g>
- ))}
- {s.dots.map((d, j) => (
- <circle
- key={`d${j}`}
- className={`${styles.point} ${d.bubble ? styles.bubble : styles.dot}`}
- style={mark(d.color, d.i)}
- cx={n1(d.x)}
- cy={n1(d.y)}
- r={n1(d.r ?? 4.5)}
- />
- ))}
- {s.labels.map((l, j) => (
- <text
- key={`v${j}`}
- className={[l.plain ? "" : styles.halo, styles.value, l.large ? styles.valueLarge : "", l.small ? styles.valueSmall : ""].filter(Boolean).join(" ")}
- style={mark(l.color, l.i)}
- x={n1(l.x)}
- y={n1(l.y)}
- textAnchor={l.anchor}
- >
- {l.text}
- </text>
- ))}
- {s.categoryLabels.map((c, j) => (
- <text key={`c${j}`} className={styles.category} x={n1(c.x)} y={n1(c.y)} textAnchor={c.anchor} transform={c.rotate ? `rotate(${c.rotate} ${n1(c.x)} ${n1(c.y)})` : undefined}>
- <title>{c.fullText ?? c.lines.join(" ")}</title>
- {c.lines.map((line, k) => (
- <tspan key={k} x={n1(c.x)} dy={k ? 15 : 0}>
- {line}
- </tspan>
- ))}
- </text>
- ))}
- </svg>
-);
diff --git a/docs/components/frames/ChartFrame/_categories.ts b/docs/components/frames/ChartFrame/_categories.ts
deleted file mode 100644
index 597c33c7..00000000
--- a/docs/components/frames/ChartFrame/_categories.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-import { wrapLabel as wrap, wrapFullLabel, labelWidth } from "./_labels";
-import { runningTotals, valueDomain } from "@/lib/charts/domain";
-import type { CategoryData, ChartColor, ChartType } from "@/lib/charts/schema";
-import { niceTicks } from "./_scale";
-import { type Canvas, emptyScene, type Scene } from "./_scene";
-
-export type CategoryType = Extract<
- ChartType,
- "grouped-bars" | "stacked-bars" | "horizontal-bars" | "lollipop" | "dumbbell" | "slope" | "radar" | "waterfall"
->;
-
-export const layoutCategories = (type: CategoryType, data: CategoryData, canvas: Canvas): Scene => {
- switch (type) {
- case "horizontal-bars":
- case "dumbbell":
- return layoutRows(type, data, canvas);
- case "radar":
- return layoutRadar(data, canvas);
- default:
- return layoutColumns(type, data, canvas);
- }
-};
-
-const format = (data: CategoryData) => (v: number) => `${v.toFixed(data.y.decimals)}${data.y.unit}`;
-const tickText = (data: CategoryData) => (v: number) => `${+v.toFixed(6)}${data.y.unit}`;
-
-const columnPlan = (type: CategoryType, data: CategoryData, requestedWidth: number) => {
- const categories = type === "waterfall" ? [...data.x.categories, "Total"] : data.x.categories;
- const { min, max, step } = valueDomain(type, data);
- const tickWidth = Math.max(...niceTicks(min, max, step).map(v => labelWidth(tickText(data)(v), 11)));
- const baseLeft = type === "slope" ? 16 : Math.min(requestedWidth * 0.3, Math.max(52, tickWidth + 12));
- const right = type === "slope" ? 16 : 10;
- const slot = (requestedWidth - baseLeft - right) / categories.length;
- const wrapped = categories.map(c => wrapFullLabel(c, Math.max(16, slot - 6)));
- // A long unbroken word must also rotate, rather than being split in two.
- const rotate = wrapped.some(lines => lines.length > 2) || categories.some(c => c.split(/\s+/).some(w => labelWidth(w) > slot - 6));
- const projection = Math.max(...categories.map(c => labelWidth(c))) / Math.SQRT2;
- const left = rotate ? Math.max(baseLeft, projection + 12) : baseLeft;
- const width = Math.max(requestedWidth, left + right + categories.length * (rotate ? 32 : 40));
- const lines = rotate ? categories.map(c => [c]) : wrapped;
- const bottom = rotate ? Math.ceil(projection + 32) : 14 + 15 * Math.max(...lines.map(l => l.length));
- return { categories, min, max, step, left, right, width, lines, bottom, rotate };
-};
-
-const rowPlan = (type: CategoryType, data: CategoryData, width: number) => {
- const labelArea = Math.min(width * 0.36, Math.max(...data.x.categories.map(c => labelWidth(c))) + 4);
- const lines = data.x.categories.map(c => wrapFullLabel(c, labelArea));
- const marks = type === "horizontal-bars" ? 20 + 18 * data.series.length : 44;
- const rowHeight = Math.max(marks, 15 * Math.max(...lines.map(l => l.length)) + 16);
- return { labelArea, lines, height: Math.max(180, 50 + data.x.categories.length * rowHeight) };
-};
-
-/** Reserve label space without taking height away from the data plot. */
-export const categoryCanvas = (type: CategoryType, data: CategoryData, width: number): Canvas => {
- if (type === "horizontal-bars" || type === "dumbbell") return { width, height: rowPlan(type, data, width).height };
- const plan = columnPlan(type, data, width);
- return { width: plan.width, height: 276 + plan.bottom, layoutWidth: width, ...(plan.width > width ? { minWidth: plan.width } : {}) };
-};
-
-const layoutColumns = (type: CategoryType, data: CategoryData, canvas: Canvas): Scene => {
- const s = emptyScene();
- const fmt = format(data);
- const slope = type === "slope";
- const { categories, min, max, step, left, right, width, lines: labelLines, bottom: bottomPad, rotate } = columnPlan(type, data, canvas.layoutWidth ?? canvas.width);
- const height = Math.max(canvas.height, 276 + bottomPad);
- const colWidth = (width - left - right) / categories.length;
- const plot = { left, right: width - right, top: 30, bottom: height - bottomPad };
- const sy = (v: number) => plot.bottom - ((v - min) / (max - min)) * (plot.bottom - plot.top);
- const centers = slope
- ? [plot.left + (plot.right - plot.left) * 0.3, plot.left + (plot.right - plot.left) * 0.7]
- : categories.map((_, c) => plot.left + colWidth * (c + 0.5));
-
- if (!slope) {
- for (const v of niceTicks(min, max, step)) {
- s.grid.push({ x1: plot.left, y1: sy(v), x2: plot.right, y2: sy(v) });
- s.ticks.push({ x: plot.left - 8, y: sy(v) + 3.5, text: tickText(data)(v), anchor: "end" });
- }
- const zeroY = sy(Math.max(min, Math.min(max, 0)));
- s.axis = `M${plot.left} ${plot.top}V${plot.bottom}M${plot.left} ${zeroY}H${plot.right}`;
- } else {
- for (const x of centers) s.grid.push({ x1: x, y1: plot.top - 10, x2: x, y2: plot.bottom });
- }
- centers.forEach((x, c) => s.categoryLabels.push({ x, y: plot.bottom + 20, lines: labelLines[c], fullText: categories[c], rotate: rotate ? -45 : undefined, anchor: rotate ? "end" : "middle" }));
-
- for (const t of data.annotations) {
- const y = sy(t.y);
- s.thresholds.push({
- d: `M${plot.left} ${y}H${plot.right}`,
- label: t.label ? { x: plot.right - 4, y: y - 6, text: t.label, anchor: "end" } : undefined,
- });
- }
-
- const n = data.series.length;
- const base = sy(Math.max(min, Math.min(max, 0)));
-
- if (type === "grouped-bars" || type === "lollipop") {
- const lollipop = type === "lollipop";
- const barW = lollipop ? 2 : Math.min(72, (colWidth * 0.74) / (n + 0.2 * (n - 1)));
- const gap = lollipop ? 0 : barW * 0.2;
- const slot = lollipop ? Math.min(26, (colWidth * 0.7) / n) : barW + gap;
- const span = lollipop ? slot * (n - 1) : n * barW + (n - 1) * gap;
- data.x.categories.forEach((_, c) => {
- data.series.forEach((ser, si) => {
- const i = c * n + si;
- const v = ser.y[c];
- const x = centers[c] - span / 2 + si * slot;
- const y = sy(v);
- const top = Math.min(y, base);
- s.barGroups.push({ i, from: "bottom", bars: [{ x: lollipop ? x - barW / 2 : x, y: top, w: barW, h: Math.abs(base - y), color: ser.color }] });
- const cx = lollipop ? x : x + barW / 2;
- if (lollipop) s.dots.push({ x: cx, y, color: ser.color, i });
- s.labels.push({ x: cx, y: (v >= 0 ? y : y + 14) - (lollipop ? 10 : 8), text: fmt(v), color: ser.color, anchor: "middle", i });
- });
- });
- } else if (type === "stacked-bars") {
- const barW = Math.min(80, colWidth * 0.56);
- data.x.categories.forEach((_, c) => {
- let pos = 0;
- let neg = 0;
- const bars = data.series.map(ser => {
- const v = ser.y[c];
- const from = v >= 0 ? pos : neg;
- const to = from + v;
- if (v >= 0) pos = to;
- else neg = to;
- return { x: centers[c] - barW / 2, y: sy(Math.max(from, to)), w: barW, h: Math.abs(sy(from) - sy(to)), color: ser.color };
- });
- s.barGroups.push({ i: c, from: "bottom", bars });
- s.labels.push({ x: centers[c], y: sy(pos) - 8, text: fmt(pos), color: "ink", anchor: "middle", i: c });
- });
- } else if (type === "waterfall") {
- const ser = data.series[0];
- const totals = runningTotals(ser.y);
- const barW = Math.min(64, colWidth * 0.6);
- const total = totals[totals.length - 1];
- categories.forEach((_, c) => {
- const isEnd = c === 0 || c === categories.length - 1;
- const from = isEnd ? 0 : totals[c - 1];
- const to = c === categories.length - 1 ? total : totals[c];
- const delta = to - from;
- const color: ChartColor = isEnd ? ser.color : delta >= 0 ? "teal" : "ember";
- s.barGroups.push({ i: c, from: "bottom", bars: [{ x: centers[c] - barW / 2, y: sy(Math.max(from, to)), w: barW, h: Math.abs(sy(from) - sy(to)), color }] });
- if (c > 0 && c < categories.length - 1) {
- s.grid.push({ x1: centers[c] + barW / 2, y1: sy(to), x2: centers[c + 1] - barW / 2, y2: sy(to) });
- }
- const text = isEnd ? fmt(to) : `${delta >= 0 ? "+" : "−"}${fmt(Math.abs(delta))}`;
- s.labels.push({ x: centers[c], y: sy(Math.max(from, to)) - 8, text, color: isEnd ? "ink" : color, anchor: "middle", i: c });
- });
- } else if (type === "slope") {
- data.series.forEach((ser, i) => {
- const [y0, y1] = [sy(ser.y[0]), sy(ser.y[1])];
- s.lines.push({ d: `M${centers[0]} ${y0}L${centers[1]} ${y1}`, color: ser.color, i, width: 2 });
- s.dots.push({ x: centers[0], y: y0, color: ser.color, i }, { x: centers[1], y: y1, color: ser.color, i });
- s.labels.push(
- { x: centers[0] - 10, y: y0 + 4, text: fmt(ser.y[0]), color: ser.color, anchor: "end", i },
- { x: centers[1] + 10, y: y1 + 4, text: fmt(ser.y[1]), color: ser.color, anchor: "start", i }
- );
- });
- }
- return s;
-};
-
-const layoutRows = (type: CategoryType, data: CategoryData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const fmt = format(data);
- const { min, max, step } = valueDomain(type, data);
- const { labelArea: labelWidth, lines: rowLines, height: requiredHeight } = rowPlan(type, data, width);
- height = Math.max(height, requiredHeight);
- const plot = { left: labelWidth + 16, right: width - 44, top: data.annotations.some(a => a.label) ? 22 : 8, bottom: height - 26 };
- const rowH = (plot.bottom - plot.top) / data.x.categories.length;
- const sx = (v: number) => plot.left + ((v - min) / (max - min)) * (plot.right - plot.left);
-
- for (const v of niceTicks(min, max, step)) {
- s.grid.push({ x1: sx(v), y1: plot.top, x2: sx(v), y2: plot.bottom });
- s.ticks.push({ x: sx(v), y: plot.bottom + 16, text: tickText(data)(v), anchor: "middle" });
- }
- data.x.categories.forEach((_, r) => {
- const lines = rowLines[r];
- s.categoryLabels.push({ x: plot.left - 10, y: plot.top + rowH * (r + 0.5) + 4 - (lines.length - 1) * 7, lines, fullText: data.x.categories[r], anchor: "end" });
- });
- for (const t of data.annotations) {
- const x = sx(t.y);
- s.thresholds.push({
- d: `M${x} ${plot.top}V${plot.bottom}`,
- label: t.label ? { x, y: plot.top - 7, text: t.label, anchor: "middle" } : undefined,
- });
- }
-
- const n = data.series.length;
- const base = sx(Math.max(min, Math.min(max, 0)));
- if (type === "horizontal-bars") {
- s.axis = `M${base} ${plot.top}V${plot.bottom}`;
- const barH = Math.min(22, (rowH * 0.72) / (n + 0.25 * (n - 1)));
- const gap = barH * 0.25;
- data.x.categories.forEach((_, r) => {
- data.series.forEach((ser, si) => {
- const i = r * n + si;
- const v = ser.y[r];
- const y = plot.top + rowH * (r + 0.5) - (n * barH + (n - 1) * gap) / 2 + si * (barH + gap);
- const x = sx(v);
- s.barGroups.push({ i, from: "left", bars: [{ x: Math.min(x, base), y, w: Math.abs(x - base), h: barH, color: ser.color }] });
- s.labels.push({ x: Math.max(x, base) + 5, y: y + barH / 2 + 3.5, text: fmt(v), color: ser.color, anchor: "start", i });
- });
- });
- } else {
- const [a, b] = data.series;
- data.x.categories.forEach((_, r) => {
- const y = plot.top + rowH * (r + 0.5);
- const [xa, xb] = [sx(a.y[r]), sx(b.y[r])];
- s.lines.push({ d: `M${Math.min(xa, xb)} ${y}H${Math.max(xa, xb)}`, color: "muted", i: r, width: 3 });
- s.dots.push({ x: xa, y, color: a.color, i: r }, { x: xb, y, color: b.color, i: r });
- const [lo, hi] = a.y[r] <= b.y[r] ? [[xa, a], [xb, b]] as const : [[xb, b], [xa, a]] as const;
- s.labels.push(
- { x: lo[0] - 8, y: y + 3.5, text: fmt(lo[1].y[r]), color: lo[1].color, anchor: "end", i: r },
- { x: hi[0] + 8, y: y + 3.5, text: fmt(hi[1].y[r]), color: hi[1].color, anchor: "start", i: r }
- );
- });
- }
- return s;
-};
-
-const layoutRadar = (data: CategoryData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const { min, max, step } = valueDomain("radar", data);
- const k = data.x.categories.length;
- const cx = width / 2;
- const cy = height / 2 + 4;
- const radius = Math.min(width / 2 - Math.min(110, Math.max(...data.x.categories.map(c => c.length)) * 3.2 + 30), height / 2 - 28);
- const at = (c: number, v: number) => {
- const r = ((v - min) / (max - min)) * radius;
- const a = (2 * Math.PI * c) / k;
- return [cx + r * Math.sin(a), cy - r * Math.cos(a)] as const;
- };
- const ring = (v: number) => data.x.categories.map((_, c) => at(c, v).map(n => n.toFixed(1)).join(",")).join(" ");
-
- for (const v of niceTicks(min, max, step)) if (v > min) s.rings.push(ring(v));
- data.x.categories.forEach((label, c) => {
- const [x, y] = at(c, max);
- s.grid.push({ x1: cx, y1: cy, x2: x, y2: y });
- const a = (2 * Math.PI * c) / k;
- const sin = Math.sin(a);
- const [lx, ly] = [cx + (radius + 14) * sin, cy - (radius + 14) * Math.cos(a)];
- const lines = wrap(label, 110);
- s.categoryLabels.push({
- x: lx,
- y: ly + 4 - (Math.cos(a) > 0.3 ? (lines.length - 1) * 14 : Math.cos(a) < -0.3 ? -6 : (lines.length - 1) * 7),
- lines,
- fullText: label,
- anchor: Math.abs(sin) < 0.2 ? "middle" : sin > 0 ? "start" : "end",
- });
- });
- for (const t of data.annotations) {
- const pts = ring(t.y);
- s.thresholds.push({
- d: `M${pts.replace(/ /g, "L")}Z`,
- label: t.label ? { x: at(0, t.y)[0] + 5, y: at(0, t.y)[1] - 5, text: t.label, anchor: "start" } : undefined,
- });
- }
- data.series.forEach((ser, i) => {
- const pts = ser.y.map((v, c) => at(c, v));
- s.polygons.push({ points: pts.map(p => p.map(n => n.toFixed(1)).join(",")).join(" "), color: ser.color, i, outline: true });
- pts.forEach(([x, y]) => s.dots.push({ x, y, color: ser.color, i }));
- });
- return s;
-};
diff --git a/docs/components/frames/ChartFrame/_distribution.ts b/docs/components/frames/ChartFrame/_distribution.ts
deleted file mode 100644
index 46c87905..00000000
--- a/docs/components/frames/ChartFrame/_distribution.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { distributionDomain, niceRange, niceStep } from "@/lib/charts/domain";
-import type { ChartType, DistributionData } from "@/lib/charts/schema";
-import { boxStats, density, histogram, quantile } from "@/lib/charts/stats";
-import { niceTicks } from "./_scale";
-import { type Canvas, emptyScene, linePath, pointList, type Scene } from "./_scene";
-
-export type DistributionType = Extract<ChartType, "histogram" | "box" | "strip" | "cdf" | "violin">;
-
-const CHAR = 7.4;
-
-export const layoutDistribution = (type: DistributionType, data: DistributionData, canvas: Canvas): Scene =>
- type === "histogram" || type === "cdf" ? layoutAcross(type, data, canvas) : layoutColumns(type, data, canvas);
-
-const fmt = (data: DistributionData) => (v: number) => `${+v.toFixed(6)}${data.value.unit}`;
-
-const layoutAcross = (type: DistributionType, data: DistributionData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const vd = distributionDomain(data);
- const plot = { left: 58, right: width - 14, top: 16, bottom: height - 28 - (data.value.label ? 22 : 0) };
- const sx = (v: number) => plot.left + ((v - vd.min) / (vd.max - vd.min)) * (plot.right - plot.left);
-
- const most = Math.max(...data.series.map(ser => ser.values.length));
- const binWidth = niceStep(vd.max - vd.min, Math.min(20, Math.max(10, Math.round(Math.sqrt(most) * 1.5))));
- const binStart = Math.floor(vd.min / binWidth + 1e-9) * binWidth;
- const bins = Math.max(1, Math.ceil((vd.max - binStart) / binWidth - 1e-9));
- const counts = data.series.map(ser => histogram(ser.values, binStart, binWidth, bins));
-
- const yd =
- type === "histogram"
- ? niceRange({ lo: 0, hi: Math.max(...counts.flat()), zero: true }, {})
- : { min: 0, max: 1, step: 0.25 };
- const sy = (v: number) => plot.bottom - ((v - yd.min) / (yd.max - yd.min)) * (plot.bottom - plot.top);
-
- for (const v of niceTicks(yd.min, yd.max, yd.step)) {
- s.grid.push({ x1: plot.left, y1: sy(v), x2: plot.right, y2: sy(v) });
- s.ticks.push({ x: plot.left - 8, y: sy(v) + 3.5, text: type === "cdf" ? `${Math.round(v * 100)}%` : String(v), anchor: "end" });
- }
- for (const v of niceTicks(vd.min, vd.max, vd.step)) s.ticks.push({ x: sx(v), y: plot.bottom + 17, text: fmt(data)(v), anchor: "middle" });
- s.axis = `M${plot.left} ${plot.top}V${plot.bottom}H${plot.right}`;
- if (data.value.label) s.axisLabels.push({ x: (plot.left + plot.right) / 2, y: height - 6, text: data.value.label });
- s.axisLabels.push({ x: 13, y: (plot.top + plot.bottom) / 2, text: type === "cdf" ? "share at or below" : "count", rotate: true });
-
- for (const t of data.annotations) {
- const x = sx(t.value);
- s.thresholds.push({ d: `M${x} ${plot.top}V${plot.bottom}`, label: t.label ? { x: x + 5, y: plot.top + 10, text: t.label, anchor: "start" } : undefined });
- }
-
- data.series.forEach((ser, i) => {
- if (type === "histogram") {
- counts[i].forEach((count, b) => {
- if (!count) return;
- const x0 = sx(binStart + b * binWidth);
- const x1 = sx(binStart + (b + 1) * binWidth);
- s.barGroups.push({ i: i * bins + b, from: "bottom", bars: [{ x: x0 + 0.5, y: sy(count), w: x1 - x0 - 1, h: plot.bottom - sy(count), color: ser.color }] });
- });
- } else {
- const v = [...ser.values].sort((a, b) => a - b);
- const pts: [number, number][] = [[sx(vd.min), sy(0)]];
- v.forEach((value, j) => pts.push([sx(value), sy((j + 1) / v.length)]));
- pts.push([sx(vd.max), sy(1)]);
- s.lines.push({ d: linePath(pts, true), color: ser.color, i, width: 2 });
- }
- });
- return s;
-};
-
-const wrap = (text: string, width: number): string[] => {
- const max = Math.max(4, Math.floor(width / CHAR));
- if (text.length <= max) return [text];
- const lines: string[] = [""];
- for (const word of text.split(" ")) {
- const line = lines[lines.length - 1];
- if (!line || `${line} ${word}`.length <= max || lines.length === 2) lines[lines.length - 1] = line ? `${line} ${word}` : word;
- else lines.push(word);
- }
- return lines;
-};
-
-const jitter = (j: number) => ((j * 0.618034) % 1) - 0.5;
-
-const layoutColumns = (type: DistributionType, data: DistributionData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const vd = distributionDomain(data);
- const left = 52 + (data.value.label ? 18 : 0);
- const colWidth = (width - left - 10) / data.series.length;
- const labelLines = data.series.map(ser => wrap(ser.label, colWidth - 6));
- const plot = { left, right: width - 10, top: 16, bottom: height - 14 - 15 * Math.max(...labelLines.map(l => l.length)) };
- const sy = (v: number) => plot.bottom - ((v - vd.min) / (vd.max - vd.min)) * (plot.bottom - plot.top);
- const half = Math.min(42, colWidth * 0.32);
-
- for (const v of niceTicks(vd.min, vd.max, vd.step)) {
- s.grid.push({ x1: plot.left, y1: sy(v), x2: plot.right, y2: sy(v) });
- s.ticks.push({ x: plot.left - 8, y: sy(v) + 3.5, text: fmt(data)(v), anchor: "end" });
- }
- s.axis = `M${plot.left} ${plot.top}V${plot.bottom}H${plot.right}`;
- if (data.value.label) s.axisLabels.push({ x: 13, y: (plot.top + plot.bottom) / 2, text: data.value.label, rotate: true });
- for (const t of data.annotations) {
- const y = sy(t.value);
- s.thresholds.push({ d: `M${plot.left} ${y}H${plot.right}`, label: t.label ? { x: plot.right - 4, y: y - 6, text: t.label, anchor: "end" } : undefined });
- }
-
- data.series.forEach((ser, i) => {
- const cx = plot.left + colWidth * (i + 0.5);
- s.categoryLabels.push({ x: cx, y: plot.bottom + 20, lines: labelLines[i], anchor: "middle" });
- const st = boxStats(ser.values);
-
- if (type === "box") {
- s.lines.push({ d: `M${cx} ${sy(st.high)}V${sy(st.q3)}M${cx} ${sy(st.q1)}V${sy(st.low)}M${cx - half / 2} ${sy(st.high)}H${cx + half / 2}M${cx - half / 2} ${sy(st.low)}H${cx + half / 2}`, color: ser.color, i, width: 1.25 });
- s.barGroups.push({ i, from: "bottom", bars: [{ x: cx - half, y: sy(st.q3), w: half * 2, h: sy(st.q1) - sy(st.q3), color: ser.color }] });
- s.lines.push({ d: `M${cx - half} ${sy(st.median)}H${cx + half}`, color: ser.color, i, width: 2.5 });
- st.outliers.forEach(v => s.dots.push({ x: cx, y: sy(v), color: ser.color, i, r: 2.5 }));
- s.labels.push({ x: cx + half + 6, y: sy(st.median) + 4, text: fmt(data)(+st.median.toFixed(data.value.decimals)), color: ser.color, anchor: "start", i });
- } else if (type === "strip") {
- [...ser.values].sort((a, b) => a - b).forEach((v, j) => s.dots.push({ x: cx + jitter(j) * half * 1.6, y: sy(v), color: ser.color, i, r: 2.5 }));
- s.lines.push({ d: `M${cx - half} ${sy(st.median)}H${cx + half}`, color: ser.color, i, width: 2 });
- } else {
- const steps = 64;
- const at = Array.from({ length: steps + 1 }, (_, k) => st.min + ((st.max - st.min) * k) / steps);
- const d = density(ser.values, at);
- const peak = Math.max(...d) || 1;
- const right = at.map((v, k) => [cx + (d[k] / peak) * half, sy(v)] as const);
- const leftSide = at.map((v, k) => [cx - (d[k] / peak) * half, sy(v)] as const).reverse();
- s.polygons.push({ points: pointList([...right, ...leftSide]), color: ser.color, i, outline: true });
- s.lines.push({ d: `M${cx} ${sy(quantile(ser.values, 0.75))}V${sy(quantile(ser.values, 0.25))}`, color: ser.color, i, width: 3 });
- s.dots.push({ x: cx, y: sy(st.median), color: ser.color, i, r: 3.5 });
- }
- });
- return s;
-};
diff --git a/docs/components/frames/ChartFrame/_function.ts b/docs/components/frames/ChartFrame/_function.ts
deleted file mode 100644
index 93b731f5..00000000
--- a/docs/components/frames/ChartFrame/_function.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { asymptotes, crossings, maxima, minima, roots, safe } from "@/lib/charts/analysis";
-import { compileExpression, type Fn } from "@/lib/charts/expression";
-import type { ChartColor, FunctionData } from "@/lib/charts/schema";
-import type { Canvas } from "./_scene";
-import { niceTicks } from "./_scale";
-
-export interface FunctionLayout {
- plot: { left: number; right: number; top: number; bottom: number };
- axes: FunctionData["axes"];
- xTicks: { x: number; label: string; zero: boolean }[];
- yTicks: { y: number; label: string; zero: boolean }[];
- xLabel?: { x: number; y: number; text: string };
- yLabel?: { x: number; y: number; text: string };
- regions: { points: string; color: ChartColor; opacity: number; label?: { x: number; y: number; text: string } }[];
- curves: { d: string; color: ChartColor; dashed: boolean }[];
- hlines: { y: number; label?: string }[];
- vlines: { x: number; color: ChartColor; label?: string; labelEnd: boolean }[];
- drops: { x: number; y1: number; y2: number; color: ChartColor }[];
- points: { x: number; y: number; color: ChartColor; hollow: boolean; label?: string }[];
-}
-
-const n1 = (v: number) => Math.round(v * 10) / 10;
-const tickLabel = (v: number) => (Math.abs(v) < 1e-10 ? "0" : String(+v.toPrecision(4)).replace("-", "−"));
-
-export const layoutFunction = (spec: FunctionData, { width, height }: Canvas): FunctionLayout => {
- const grid = spec.axes === "grid";
- const left = (grid ? 40 : 28) + (spec.y.label ? 20 : 0);
- const bottom = (grid ? 26 : 22) + (spec.x.label ? 22 : 0);
- const plot = { left, right: width - 12, top: 14, bottom: height - bottom };
- const { min: x0, max: x1 } = spec.x;
- const { min: y0, max: y1 } = spec.y;
- const span = y1 - y0;
- const sx = (x: number) => plot.left + ((x - x0) / (x1 - x0)) * (plot.right - plot.left);
- const sy = (y: number) => plot.bottom - ((y - y0) / span) * (plot.bottom - plot.top);
- const inX = (x: number) => x >= x0 - 1e-9 && x <= x1 + 1e-9;
- const inY = (y: number) => y >= y0 - 1e-9 && y <= y1 + 1e-9;
- const clampY = (y: number) => Math.min(y1, Math.max(y0, y));
-
- const fns = new Map<string, Fn>(
- spec.series.map(s => [s.id, typeof s.y === "number" ? () => s.y as number : compileExpression(s.y)])
- );
-
- const fnOf = (ref: string | number): Fn =>
- typeof ref === "number" ? () => ref : (fns.get(ref) ?? compileExpression(ref));
- const colorOf = new Map(spec.series.map(s => [s.id, s.color]));
-
- const xTicks = grid
- ? niceTicks(x0, x1, spec.x.step).map(v => ({ x: sx(v), label: tickLabel(v), zero: v === 0 }))
- : [];
- const yTicks = grid
- ? niceTicks(y0, y1, spec.y.step).map(v => ({ y: sy(v), label: tickLabel(v), zero: v === 0 }))
- : [];
- const xLabel = spec.x.label
- ? { x: (plot.left + plot.right) / 2, y: height - 6, text: spec.x.label }
- : undefined;
- const yLabel = spec.y.label
- ? { x: 12, y: (plot.top + plot.bottom) / 2, text: spec.y.label }
- : undefined;
-
- const curvePath = (f: Fn, a: number, b: number) => {
- const n = 900;
- const outside = (y: number) => y > y1 || y < y0;
- let d = "";
- let pen = false;
- let prev: number | null = null;
- for (let i = 0; i <= n; i++) {
- const x = a + ((b - a) * i) / n;
- const y = safe(f, x);
- if (!Number.isFinite(y)) {
- pen = false;
- prev = null;
- continue;
- }
- if (prev !== null && Math.abs(y - prev) > 2 * span && (outside(y) || outside(prev))) pen = false;
- const yc = Math.min(y1 + 10 * span, Math.max(y0 - 10 * span, y));
- d += `${pen ? "L" : "M"}${n1(sx(x))} ${n1(sy(yc))}`;
- pen = true;
- prev = y;
- }
- return d;
- };
-
- const regions = spec.annotations.flatMap(a => {
- if (a.type !== "region") return [];
- const f = fnOf(a.upper);
- const g = fnOf(a.lower);
- const from = Math.max(a.from ?? x0, x0);
- const to = Math.min(a.to ?? x1, x1);
- const n = 300;
- const top: string[] = [];
- const bot: string[] = [];
- for (let i = 0; i <= n; i++) {
- const x = from + ((to - from) * i) / n;
- const ya = safe(f, x);
- const yb = safe(g, x);
- if (!Number.isFinite(ya) || !Number.isFinite(yb)) continue;
- top.push(`${n1(sx(x))},${n1(sy(clampY(ya)))}`);
- bot.push(`${n1(sx(x))},${n1(sy(clampY(yb)))}`);
- }
- let label: { x: number; y: number; text: string } | undefined;
- if (a.label) {
- let at = a.labelAt;
- if (at === undefined) {
- let best = -1;
- const pad = (to - from) * 0.1;
- for (let i = 0; i <= 200; i++) {
- const x = from + pad + ((to - from - 2 * pad) * i) / 200;
- const h = Math.abs(clampY(safe(f, x)) - clampY(safe(g, x)));
- const score = h * (1 - (0.25 * Math.abs(i - 100)) / 100);
- if (Number.isFinite(score) && score > best) {
- best = score;
- at = x;
- }
- }
- }
- const ym = at === undefined ? NaN : (clampY(safe(f, at)) + clampY(safe(g, at))) / 2;
- if (at !== undefined && Number.isFinite(ym)) label = { x: sx(at), y: sy(ym) + 4, text: a.label };
- }
- return [{ points: top.concat(bot.reverse()).join(" "), color: a.color, opacity: a.opacity, label }];
- });
-
- const curves = spec.series.map(s => ({
- d: curvePath(fns.get(s.id)!, Math.max(s.from ?? x0, x0), Math.min(s.to ?? x1, x1)),
- color: s.color,
- dashed: s.dashed,
- }));
-
- const hlines = spec.annotations.flatMap(a =>
- a.type === "threshold" && inY(a.y) ? [{ y: sy(a.y), label: a.label }] : []
- );
-
- const vlines = spec.annotations.flatMap(a => {
- if (a.type === "vline")
- return inX(a.x) ? [{ x: sx(a.x), color: a.color, label: a.label, labelEnd: sx(a.x) > plot.right - 90 }] : [];
- if (a.type !== "asymptotes") return [];
- const label = a.label ?? "x = {x}";
- return asymptotes(fns.get(a.series)!, x0, x1, span).map(x => ({
- x: sx(x),
- color: "muted" as const,
- label: label.replace("{x}", x.toFixed(spec.x.decimals)),
- labelEnd: sx(x) > plot.right - 90,
- }));
- });
-
- const drops: FunctionLayout["drops"] = [];
- const points: FunctionLayout["points"] = [];
- for (const a of spec.annotations) {
- if (a.type !== "points") continue;
- const f = fns.get(a.series)!;
- const xs =
- a.at === "minima"
- ? minima(f, x0, x1, span)
- : a.at === "maxima"
- ? maxima(f, x0, x1, span)
- : a.at === "roots"
- ? roots(f, x0, x1, span)
- : Array.isArray(a.at)
- ? a.at
- : crossings(f, fnOf(a.at.crosses), x0, x1, span);
- const color = a.color ?? colorOf.get(a.series) ?? "muted";
- for (const x of xs) {
- const y = safe(f, x);
- if (!inX(x) || !Number.isFinite(y) || !inY(y)) continue;
- if (a.drop !== undefined) {
- const to = a.drop === "axis" ? y0 : safe(fnOf(a.drop), x);
- if (Number.isFinite(to)) drops.push({ x: sx(x), y1: sy(y), y2: sy(clampY(to)), color });
- }
- const label = a.label
- ?.replace("{x}", x.toFixed(spec.x.decimals))
- .replace("{y}", y.toFixed(spec.y.decimals));
- points.push({ x: sx(x), y: sy(y), color, hollow: a.hollow, label });
- }
- }
-
- return { plot, axes: spec.axes, xTicks, yTicks, xLabel, yLabel, regions, curves, hlines, vlines, drops, points };
-};
diff --git a/docs/components/frames/ChartFrame/_labels.ts b/docs/components/frames/ChartFrame/_labels.ts
deleted file mode 100644
index f990d0fc..00000000
--- a/docs/components/frames/ChartFrame/_labels.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import type { Canvas, Scene } from "./_scene";
-
-// Conservative estimate for the inherited proportional font. Leave breathing
-// room instead of shrinking type to fit an arbitrary number of labels.
-export const labelWidth = (text: string, size = 13) => Array.from(text).length * size * 0.72;
-
-export const fitLabel = (text: string, width: number, size = 13): string => {
- if (labelWidth(text, size) <= width) return text;
- const count = Math.max(0, Math.floor(width / (size * 0.72)) - 1);
- return `${Array.from(text).slice(0, count).join("")}…`;
-};
-
-export const wrapLabel = (text: string, width: number): string[] => {
- const words = text.trim().split(/\s+/);
- const lines: string[] = [];
- let line = "";
- for (let i = 0; i < words.length; i++) {
- const next = line ? `${line} ${words[i]}` : words[i];
- if (labelWidth(next) <= width) {
- line = next;
- } else if (line && lines.length === 0) {
- lines.push(line);
- line = words[i];
- } else {
- const rest = [next, ...words.slice(i + 1)].join(" ");
- lines.push(fitLabel(rest, width));
- return lines;
- }
- }
- if (line) lines.push(fitLabel(line, width));
- return lines;
-};
-
-/** Keep labels inside the canvas and omit ticks whose text would collide. */
-export const fitTicks = (ticks: Scene["ticks"], canvas: Canvas, inset = 4): Scene["ticks"] => {
- const kept: Scene["ticks"] = [];
- const boxes: { left: number; right: number; top: number; bottom: number }[] = [];
- for (const tick of ticks) {
- const available = tick.anchor === "end" ? tick.x - inset : tick.anchor === "start" ? canvas.width - tick.x - 4 : canvas.width - 8;
- let compact = tick.text;
- if (labelWidth(compact, 11) > available) {
- const match = compact.match(/^(-?\d+(?:\.\d+)?)(.*)$/);
- if (match) {
- const value = Number(match[1]);
- const number = Math.abs(value) >= 10000
- ? new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 }).format(value)
- : value !== 0 && Math.abs(value) < 0.001 ? value.toExponential(1) : match[1];
- compact = number + match[2];
- }
- }
- const text = fitLabel(compact, Math.max(8, available), 11);
- const width = labelWidth(text, 11);
- const offset = tick.anchor === "end" ? width : tick.anchor === "middle" ? width / 2 : 0;
- const left = Math.max(inset, Math.min(canvas.width - width - 4, tick.x - offset));
- const box = { left, right: left + width, top: tick.y - 11, bottom: tick.y + 3 };
- if (boxes.some(b => box.left < b.right + 8 && box.right + 8 > b.left && box.top < b.bottom + 4 && box.bottom + 4 > b.top)) continue;
- boxes.push(box);
- kept.push({ ...tick, x: left + offset, text, fullText: tick.text });
- }
- return kept;
-};
-
-/** Wrap without losing text; break long unspaced names as a last resort. */
-export const wrapFullLabel = (text: string, width: number): string[] => {
- const max = Math.max(1, Math.floor(width / (13 * 0.72)));
- const lines: string[] = [];
- let line = "";
- for (const word of text.trim().split(/\s+/)) {
- if (line && Array.from(`${line} ${word}`).length <= max) {
- line += ` ${word}`;
- continue;
- }
- if (line) lines.push(line);
- const chars = Array.from(word);
- while (chars.length > max) lines.push(chars.splice(0, max).join(""));
- line = chars.join("");
- }
- if (line) lines.push(line);
- return lines;
-};
diff --git a/docs/components/frames/ChartFrame/_matrix.ts b/docs/components/frames/ChartFrame/_matrix.ts
deleted file mode 100644
index 22c43d06..00000000
--- a/docs/components/frames/ChartFrame/_matrix.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import type { MatrixData } from "@/lib/charts/schema";
-import { labelWidth, wrapFullLabel } from "./_labels";
-import { type Canvas, emptyScene, type Scene } from "./_scene";
-
-export type MatrixType = "heatmap" | "confusion-matrix";
-
-// Rows are y categories, columns x categories. In a confusion matrix rows are
-// the truth and columns the prediction, and the first category is "positive".
-
-const AXIS_TITLE = 24;
-const LINE = 15;
-// Below this a column can't hold its number legibly, so the canvas widens and scrolls.
-const MIN_CELL = 52;
-
-const formatter = (data: MatrixData) => (v: number) =>
- `${v.toLocaleString("en-US", { minimumFractionDigits: data.value.decimals, maximumFractionDigits: data.value.decimals })}${data.value.unit}`;
-
-const percent = (share: number) => `${share > 0 && share < 0.01 ? "<1" : Math.round(share * 100)}%`;
-
-/** Names of a 2×2 confusion matrix's cells, by [actual][predicted]. */
-const CELL_NAMES = [
- ["true positive", "false negative"],
- ["false positive", "true negative"],
-];
-
-export const confusionStats = (values: number[][]) => {
- const total = values.flat().reduce((sum, v) => sum + v, 0);
- const agree = values.reduce((sum, row, i) => sum + (row[i] ?? 0), 0);
- const stats: { label: string; value: string }[] = [{ label: "accuracy", value: percent(total ? agree / total : 0) }];
- if (values.length === 2) {
- const [[tp, fn], [fp]] = values;
- const precision = tp + fp ? tp / (tp + fp) : 0;
- const recall = tp + fn ? tp / (tp + fn) : 0;
- const f1 = precision + recall ? (2 * precision * recall) / (precision + recall) : 0;
- stats.push(
- { label: "precision", value: precision.toFixed(2) },
- { label: "recall", value: recall.toFixed(2) },
- { label: "F1", value: f1.toFixed(2) }
- );
- }
- return stats;
-};
-
-/** Everything the canvas size and the layout share. */
-const plan = (type: MatrixType, data: MatrixData, width: number) => {
- const cols = data.x.categories.length;
- const rows = data.y.categories.length;
- const titleLeft = data.y.label ? AXIS_TITLE : 0;
- // Row labels get at least their longest word, so they wrap between words, never inside one.
- const longestRowWord = Math.max(...data.y.categories.flatMap(c => c.split(/\s+/).map(w => labelWidth(w))));
- const rowLabelWidth = Math.min(
- Math.max(width * 0.28, longestRowWord + 14),
- width * 0.4,
- Math.max(...data.y.categories.map(c => labelWidth(c))) + 12
- );
- const rowLines = data.y.categories.map(c => wrapFullLabel(c, rowLabelWidth - 10));
- const left = titleLeft + rowLabelWidth;
- // Column labels wrap at spaces; when a single word can't fit its column, they angle instead.
- const roughCell = Math.max(MIN_CELL, (width - left - 4) / cols);
- const longestWord = Math.max(...data.x.categories.flatMap(c => c.split(/\s+/).map(w => labelWidth(w))));
- const rotate = longestWord > roughCell - 8;
- // Angled labels rise to the right, so the last one needs room past the grid.
- const lastLabel = labelWidth(data.x.categories[cols - 1]) * Math.SQRT1_2 + 8;
- const right = rotate ? Math.max(4, lastLabel - roughCell / 2) : 4;
- const layoutWidth = Math.max(width, left + cols * MIN_CELL + right);
- const cellW = (layoutWidth - left - right) / cols;
- const colLines = data.x.categories.map(c => (rotate ? [c] : wrapFullLabel(c, cellW - 8)));
- const labelsHeight = rotate
- ? Math.max(...data.x.categories.map(c => labelWidth(c))) * Math.SQRT1_2 + 6
- : Math.max(...colLines.map(l => l.length)) * LINE;
- const top = (data.x.label ? AXIS_TITLE : 0) + labelsHeight + 8;
- const confusion = type === "confusion-matrix";
- const big = confusion && rows <= 3;
- const labelsTall = Math.max(...rowLines.map(l => l.length)) * LINE + 8;
- const cellH = Math.max(labelsTall, big ? Math.min(Math.max(cellW * 0.55, 72), 104) : Math.min(Math.max(cellW * 0.45, 36), 56));
- const bottom = confusion ? 34 : 6;
- return { cols, rows, titleLeft, rowLabelWidth, rowLines, left, layoutWidth, cellW, cellH, colLines, rotate, top, bottom, big };
-};
-
-export const matrixCanvas = (type: MatrixType, data: MatrixData, width: number): Canvas => {
- const p = plan(type, data, width);
- return {
- width: p.layoutWidth,
- height: p.top + p.rows * p.cellH + p.bottom,
- layoutWidth: width,
- ...(p.layoutWidth > width ? { minWidth: p.layoutWidth } : {}),
- };
-};
-
-export const layoutMatrix = (type: MatrixType, data: MatrixData, canvas: Canvas): Scene => {
- const s = emptyScene();
- const p = plan(type, data, canvas.layoutWidth ?? canvas.width);
- const fmt = formatter(data);
- const gridBottom = p.top + p.rows * p.cellH;
- const gridRight = p.left + p.cols * p.cellW;
-
- if (data.x.label) s.axisLabels.push({ x: p.left + (gridRight - p.left) / 2, y: 14, text: data.x.label });
- if (data.y.label) s.axisLabels.push({ x: 12, y: p.top + (gridBottom - p.top) / 2, text: data.y.label, rotate: true });
-
- data.x.categories.forEach((_, c) => {
- const lines = p.colLines[c];
- s.categoryLabels.push(
- p.rotate
- ? { x: p.left + p.cellW * (c + 0.5) + 4, y: p.top - 8, lines, fullText: data.x.categories[c], anchor: "start", rotate: -45 }
- : { x: p.left + p.cellW * (c + 0.5), y: p.top - 8 - (lines.length - 1) * LINE, lines, fullText: data.x.categories[c], anchor: "middle" }
- );
- });
- data.y.categories.forEach((category, r) => {
- const lines = p.rowLines[r];
- s.categoryLabels.push({
- x: p.left - 10,
- y: p.top + p.cellH * (r + 0.5) + 4.5 - ((lines.length - 1) * LINE) / 2,
- lines,
- fullText: category,
- anchor: "end",
- });
- });
-
- const flat = data.values.flat();
- const lo = Math.min(...flat);
- const hi = Math.max(...flat);
- const total = flat.reduce((sum, v) => sum + v, 0);
- // Tints stay light enough for the numbers on them to read in both themes.
- const tint = (v: number, max: number, min = 0) => (max > min ? 0.1 + 0.5 * ((v - min) / (max - min)) : 0.35);
-
- data.values.forEach((row, r) =>
- row.forEach((v, c) => {
- const x = p.left + c * p.cellW;
- const y = p.top + r * p.cellH;
- const i = r * p.cols + c;
- // Cells fade in one by one; their numbers follow row by row.
- const li = r;
- const cx = x + p.cellW / 2;
- const cy = y + p.cellH / 2;
- if (type === "heatmap") {
- s.cells.push({ x, y, w: p.cellW, h: p.cellH, color: data.color, opacity: tint(v, hi, lo), i });
- s.labels.push({ x: cx, y: cy + 4.5, text: fmt(v), color: "ink", anchor: "middle", i: li, plain: true });
- return;
- }
- const agree = r === c;
- s.cells.push({ x, y, w: p.cellW, h: p.cellH, color: agree ? "teal" : "pink", opacity: tint(v, hi), i });
- const name = p.rows === 2 && p.big ? CELL_NAMES[r][c] : null;
- const share = percent(total ? v / total : 0);
- if (p.big) {
- if (name) s.labels.push({ x: cx, y: cy - 16, text: name, color: "ink", anchor: "middle", i: li, plain: true, small: true });
- s.labels.push({ x: cx, y: cy + (name ? 9 : 4), text: fmt(v), color: "ink", anchor: "middle", i: li, plain: true, large: true });
- s.labels.push({ x: cx, y: cy + (name ? 27 : 22), text: share, color: "ink", anchor: "middle", i: li, plain: true, small: true });
- } else {
- s.labels.push({ x: cx, y: cy + 4.5, text: `${fmt(v)} · ${share}`, color: "ink", anchor: "middle", i: li, plain: true });
- }
- })
- );
-
- if (type === "confusion-matrix") {
- const text = confusionStats(data.values)
- .map(st => `${st.label} ${st.value}`)
- .join(" · ");
- s.labels.push({ x: p.left + (gridRight - p.left) / 2, y: gridBottom + 24, text, color: "ink", anchor: "middle", i: p.rows, plain: true, small: true });
- }
- return s;
-};
diff --git a/docs/components/frames/ChartFrame/_parts.ts b/docs/components/frames/ChartFrame/_parts.ts
deleted file mode 100644
index 56ca3097..00000000
--- a/docs/components/frames/ChartFrame/_parts.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-import type { ChartType, PartsData } from "@/lib/charts/schema";
-import { type Canvas, emptyScene, pointList, type Scene } from "./_scene";
-
-export type PartsType = Extract<ChartType, "pie" | "donut" | "stacked-100" | "waffle" | "treemap" | "funnel">;
-
-const CHAR = 7.4;
-
-const MIN_INSIDE = 0.06;
-
-const formatter = (data: PartsData) => (v: number) =>
- `${v.toLocaleString("en-US", { minimumFractionDigits: data.value.decimals, maximumFractionDigits: data.value.decimals })}${data.value.unit}`;
-const percent = (share: number) => (share > 0 && share < 0.01 ? "<1%" : `${Math.round(share * 100)}%`);
-
-export const layoutParts = (type: PartsType, data: PartsData, canvas: Canvas): Scene => {
- switch (type) {
- case "pie":
- case "donut":
- return layoutRing(type, data, canvas);
- case "stacked-100":
- return layoutBar(data, canvas);
- case "waffle":
- return layoutWaffle(data, canvas);
- case "treemap":
- return layoutTreemap(data, canvas);
- case "funnel":
- return layoutFunnel(data, canvas);
- }
-};
-
-const shares = (data: PartsData) => {
- const total = data.series.reduce((sum, s) => sum + s.value, 0);
- return { total, share: data.series.map(s => s.value / total) };
-};
-
-const layoutRing = (type: PartsType, data: PartsData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const { total, share } = shares(data);
- const cx = width / 2;
- const cy = height / 2;
-
- const anyOutside = share.some(v => v > 0 && v < MIN_INSIDE);
- const r = anyOutside ? Math.min(height / 2 - 28, width / 2 - 56) : Math.min(height / 2 - 14, width / 2 - 14);
- const inner = type === "donut" ? r * 0.58 : 0;
- const at = (radius: number, a: number) => [cx + radius * Math.sin(a), cy - radius * Math.cos(a)] as const;
- const outside: { mid: number; text: string; i: number }[] = [];
-
- let start = 0;
- data.series.forEach((ser, i) => {
- const sweep = share[i] * 2 * Math.PI;
- if (sweep <= 0) return;
-
- const steps = Math.max(2, Math.ceil(sweep / 0.04));
- const outer = Array.from({ length: steps + 1 }, (_, k) => at(r, start + (sweep * k) / steps));
- const back = inner
- ? Array.from({ length: steps + 1 }, (_, k) => at(inner, start + sweep - (sweep * k) / steps))
- : [[cx, cy] as const];
- s.polygons.push({ points: pointList([...outer, ...back]), color: ser.color, i, outline: false, slice: true });
- const mid = start + sweep / 2;
- if (share[i] >= MIN_INSIDE) {
- const [lx, ly] = at(inner ? (r + inner) / 2 : r * 0.64, mid);
- s.labels.push({ x: lx, y: ly + 4.5, text: percent(share[i]), color: "ink", anchor: "middle", i, plain: true });
- } else {
- outside.push({ mid, text: percent(share[i]), i });
- }
- start += sweep;
- });
-
- const placed = outside.map(o => {
- const [x0, y0] = at(r + 2, o.mid);
- const [x1, y1] = at(r + 11, o.mid);
- const sin = Math.sin(o.mid);
- const side: "top" | "bottom" | "left" | "right" =
- Math.abs(sin) < 0.4 ? (Math.cos(o.mid) > 0 ? "top" : "bottom") : sin > 0 ? "right" : "left";
- return { ...o, x0, y0, x1, y1, side, lx: x1, ly: y1 };
- });
- for (const side of ["left", "right"] as const) {
- const group = placed.filter(p => p.side === side).sort((a, b) => a.ly - b.ly);
- for (let k = 1; k < group.length; k++) group[k].ly = Math.max(group[k].ly, group[k - 1].ly + 15);
- }
- for (const side of ["top", "bottom"] as const) {
- const group = placed.filter(p => p.side === side).sort((a, b) => a.lx - b.lx);
- for (let k = 1; k < group.length; k++) group[k].lx = Math.max(group[k].lx, group[k - 1].lx + 36);
- }
- for (const p of placed) {
- s.lines.push({ d: `M${p.x0} ${p.y0}L${p.x1} ${p.y1}`, color: "muted", i: p.i, width: 1 });
- const label =
- p.side === "top"
- ? { x: p.lx, y: p.ly - 5, anchor: "middle" as const }
- : p.side === "bottom"
- ? { x: p.lx, y: p.ly + 14, anchor: "middle" as const }
- : p.side === "right"
- ? { x: p.lx + 4, y: p.ly + 4.5, anchor: "start" as const }
- : { x: p.lx - 4, y: p.ly + 4.5, anchor: "end" as const };
- s.labels.push({ ...label, text: p.text, color: "ink", i: p.i });
- }
- if (type === "donut") {
- s.labels.push({ x: cx, y: cy + 4, text: formatter(data)(total), color: "ink", anchor: "middle", i: data.series.length, plain: true, large: true });
- s.labels.push({ x: cx, y: cy + 24, text: "total", color: "muted", anchor: "middle", i: data.series.length, plain: true });
- }
- return s;
-};
-
-const layoutBar = (data: PartsData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const { share } = shares(data);
- const left = 16;
- const span = width - 32;
- const h = Math.min(64, height * 0.3);
- const y = (height - h) / 2;
- let x = left;
-
- let lastBelow = { x: -Infinity, row: 0 };
- data.series.forEach((ser, i) => {
- const w = span * share[i];
- s.barGroups.push({ i, from: "left", bars: [{ x, y, w, h, color: ser.color, solid: true }] });
- const cx = x + w / 2;
- const text = percent(share[i]);
- if (w >= text.length * 8 + 12) {
- s.labels.push({ x: cx, y: y + h / 2 + 4.5, text, color: "ink", anchor: "middle", i, plain: true });
- } else if (w > 0) {
- const row = cx - lastBelow.x < 36 ? lastBelow.row + 1 : 0;
- const ly = y + h + 18 + row * 15;
- s.lines.push({ d: `M${cx} ${y + h + 2}V${ly - 11}`, color: "muted", i, width: 1 });
- s.labels.push({ x: cx, y: ly, text, color: "ink", anchor: "middle", i });
- lastBelow = { x: cx, row };
- }
- x += w;
- });
- return s;
-};
-
-const squares = (share: number[]) => {
- const raw = share.map(v => v * 100);
- const counts = raw.map(Math.floor);
- const order = raw.map((v, i) => [v - Math.floor(v), i] as const).sort((a, b) => b[0] - a[0]);
- for (let k = 0; counts.reduce((a, b) => a + b, 0) < 100; k++) counts[order[k % order.length][1]]++;
- return counts;
-};
-
-const layoutWaffle = (data: PartsData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const counts = squares(shares(data).share);
- const cols = width >= 500 ? 20 : 10;
- const rows = 100 / cols;
- const gap = 3;
- const cell = Math.min((width - 32 - gap * (cols - 1)) / cols, (height - 32 - gap * (rows - 1)) / rows);
- const x0 = (width - (cell * cols + gap * (cols - 1))) / 2;
- const y0 = (height - (cell * rows + gap * (rows - 1))) / 2;
- let k = 0;
- data.series.forEach((ser, i) => {
- for (let j = 0; j < counts[i]; j++, k++) {
- const row = Math.floor(k / cols);
- const col = k % cols;
- s.barGroups.push({
- i: row,
- from: "bottom",
- bars: [{ x: x0 + col * (cell + gap), y: y0 + row * (cell + gap), w: cell, h: cell, color: ser.color, solid: true }],
- });
- }
- });
- return s;
-};
-
-interface Rect {
- x: number;
- y: number;
- w: number;
- h: number;
-}
-
-const partition = (items: { value: number; index: number }[], r: Rect): { index: number; rect: Rect }[] => {
- if (items.length === 1) return [{ index: items[0].index, rect: r }];
- const total = items.reduce((sum, it) => sum + it.value, 0);
- let acc = 0;
- let cut = 1;
- for (; cut < items.length - 1; cut++) {
- if (acc + items[cut - 1].value >= total / 2) break;
- acc += items[cut - 1].value;
- }
- acc = items.slice(0, cut).reduce((sum, it) => sum + it.value, 0);
- const f = total ? acc / total : 0.5;
- const [a, b] =
- r.w >= r.h
- ? [{ ...r, w: r.w * f }, { ...r, x: r.x + r.w * f, w: r.w * (1 - f) }]
- : [{ ...r, h: r.h * f }, { ...r, y: r.y + r.h * f, h: r.h * (1 - f) }];
- return [...partition(items.slice(0, cut), a), ...partition(items.slice(cut), b)];
-};
-
-const layoutTreemap = (data: PartsData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const { share } = shares(data);
- const items = data.series
- .map((ser, index) => ({ value: ser.value, index }))
- .filter(it => it.value > 0)
- .sort((a, b) => b.value - a.value);
- const fmt = formatter(data);
- for (const { index: i, rect } of partition(items, { x: 8, y: 8, w: width - 16, h: height - 16 })) {
- const ser = data.series[i];
- s.barGroups.push({ i, from: "bottom", bars: [{ ...rect, color: ser.color, solid: true }] });
- if (rect.w >= Math.max(64, ser.label.length * CHAR + 16) && rect.h >= 44) {
- s.labels.push({ x: rect.x + 10, y: rect.y + 22, text: ser.label, color: "ink", anchor: "start", i, plain: true });
- s.labels.push({ x: rect.x + 10, y: rect.y + 40, text: `${fmt(ser.value)} · ${percent(share[i])}`, color: "ink", anchor: "start", i, plain: true });
- } else if (rect.w >= 40 && rect.h >= 24) {
- s.labels.push({ x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 + 4.5, text: percent(share[i]), color: "ink", anchor: "middle", i, plain: true });
- }
- }
- return s;
-};
-
-const layoutFunnel = (data: PartsData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const fmt = formatter(data);
- const first = data.series[0].value || 1;
- const labelW = Math.min(width * 0.32, Math.max(...data.series.map(ser => ser.label.length)) * CHAR);
- const left = labelW + 18;
- const right = width - 112;
- const rowH = (height - 16) / data.series.length;
- const center = (left + right) / 2;
- data.series.forEach((ser, i) => {
- const w = Math.max(2, ((right - left) * ser.value) / first);
- const y = 8 + rowH * i;
- s.barGroups.push({ i, from: "bottom", bars: [{ x: center - w / 2, y: y + 3, w, h: rowH - 6, color: ser.color, solid: true }] });
- s.categoryLabels.push({ x: labelW + 6, y: y + rowH / 2 + 4.5, lines: [ser.label], anchor: "end" });
- s.labels.push({ x: right + 10, y: y + rowH / 2 + 4.5, text: `${fmt(ser.value)} · ${percent(ser.value / first)}`, color: ser.color, anchor: "start", i });
- });
- return s;
-};
diff --git a/docs/components/frames/ChartFrame/_scale.ts b/docs/components/frames/ChartFrame/_scale.ts
deleted file mode 100644
index fcabbfce..00000000
--- a/docs/components/frames/ChartFrame/_scale.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export const niceTicks = (min: number, max: number, step?: number): number[] => {
- if (!step) {
- const raw = (max - min) / 4;
- const magnitude = 10 ** Math.floor(Math.log10(raw));
- const norm = raw / magnitude;
- step = (norm < 1.5 ? 1 : norm < 3 ? 2 : norm < 7 ? 5 : 10) * magnitude;
- }
- const ticks: number[] = [];
- for (let v = Math.ceil(min / step - 1e-9) * step; v <= max + step * 1e-9; v += step) {
- ticks.push(+v.toFixed(10));
- }
- return ticks;
-};
diff --git a/docs/components/frames/ChartFrame/_scene.ts b/docs/components/frames/ChartFrame/_scene.ts
deleted file mode 100644
index 07d47c00..00000000
--- a/docs/components/frames/ChartFrame/_scene.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import type { ChartColor } from "@/lib/charts/schema";
-
-export interface Canvas {
- width: number;
- height: number;
- minWidth?: number;
- layoutWidth?: number;
-}
-
-export type Anchor = "start" | "middle" | "end";
-
-export interface Scene {
- grid: { x1: number; y1: number; x2: number; y2: number }[];
- rings: string[];
- axis?: string;
- ticks: { x: number; y: number; text: string; fullText?: string; anchor: Anchor }[];
-
- axisLabels: { x: number; y: number; text: string; rotate?: boolean }[];
- categoryLabels: { x: number; y: number; lines: string[]; fullText?: string; rotate?: number; anchor: Anchor }[];
- thresholds: { d: string; label?: { x: number; y: number; text: string; anchor: Anchor } }[];
-
- barGroups: {
- i: number;
- from: "bottom" | "left";
-
- bars: { x: number; y: number; w: number; h: number; color: ChartColor; solid?: boolean }[];
- }[];
-
- polygons: { points: string; color: ChartColor; i: number; outline: boolean; opacity?: number; slice?: boolean }[];
- lines: { d: string; color: ChartColor; i: number; width: number }[];
-
- dots: { x: number; y: number; color: ChartColor; i: number; r?: number; bubble?: boolean }[];
-
- /** Matrix cells, each tinted with its own opacity. */
- cells: { x: number; y: number; w: number; h: number; color: ChartColor; opacity: number; i: number }[];
-
- labels: {
- x: number;
- y: number;
- text: string;
- color: ChartColor | "ink";
- anchor: Anchor;
- i: number;
- plain?: boolean;
- large?: boolean;
- /** 11px secondary text, e.g. a cell's share or name. */
- small?: boolean;
- }[];
-}
-
-export const emptyScene = (): Scene => ({
- grid: [], rings: [], ticks: [], axisLabels: [], categoryLabels: [], thresholds: [],
- barGroups: [], polygons: [], lines: [], dots: [], cells: [], labels: [],
-});
-
-export const linePath = (pts: (readonly [number, number])[], step = false) =>
- pts
- .map(([x, y], i) => {
- if (i === 0) return `M${x.toFixed(1)} ${y.toFixed(1)}`;
- return step ? `H${x.toFixed(1)}V${y.toFixed(1)}` : `L${x.toFixed(1)} ${y.toFixed(1)}`;
- })
- .join("");
-
-export const pointList = (pts: (readonly [number, number])[]) =>
- pts.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(" ");
-
-export const textWidth = (text: string, size = 13) => text.length * size * 0.6;
-
-export const assignLanes = (
- items: { x: number; width: number }[],
- left: number,
- right: number,
- gap = 12
-): { lane: number; anchor: Anchor }[] => {
- const ends: number[] = [];
- const out: { lane: number; anchor: Anchor }[] = new Array(items.length);
- const order = items.map((item, i) => ({ ...item, i })).sort((a, b) => a.x - b.x);
- for (const item of order) {
- const anchor: Anchor = item.x - item.width / 2 < left ? "start" : item.x + item.width / 2 > right ? "end" : "middle";
- const from = anchor === "start" ? item.x : anchor === "end" ? item.x - item.width : item.x - item.width / 2;
- let lane = ends.findIndex(end => end + gap <= from);
- if (lane < 0) lane = ends.push(0) - 1;
- ends[lane] = from + item.width;
- out[item.i] = { lane, anchor };
- }
- return out;
-};
-
diff --git a/docs/components/frames/ChartFrame/_time.ts b/docs/components/frames/ChartFrame/_time.ts
deleted file mode 100644
index 9896619b..00000000
--- a/docs/components/frames/ChartFrame/_time.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { niceStep } from "@/lib/charts/domain";
-import { type ChartType, type Moment, momentValue, type TimeData } from "@/lib/charts/schema";
-import { niceTicks } from "./_scale";
-import { assignLanes, type Canvas, emptyScene, type Scene, textWidth } from "./_scene";
-
-export type TimeType = Extract<ChartType, "gantt" | "timeline">;
-
-const CHAR = 7.4;
-const DAY = 86_400_000;
-const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
-
-const usesDates = (data: TimeData) =>
- data.series.some(s => [...(s.spans ?? []).flat(), ...(s.events ?? []).map(e => e[0])].some(m => typeof m === "string"));
-
-const momentText = (days: number, dates: boolean) => {
- if (!dates) return String(+days.toFixed(2));
- const d = new Date(days * DAY);
- return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;
-};
-
-const timeTicks = (lo: number, hi: number, dates: boolean): { at: number; text: string }[] => {
- if (!dates) return niceTicks(lo, hi, niceStep(hi - lo, 5)).map(v => ({ at: v, text: momentText(v, false) }));
- const span = hi - lo;
- if (span > 100) {
- const every = span > 400 ? 3 : span > 200 ? 2 : 1;
- const out: { at: number; text: string }[] = [];
- const d = new Date(lo * DAY);
- let m = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
- while (m.getTime() / DAY <= hi) {
- if (m.getUTCMonth() % every === 0) out.push({ at: m.getTime() / DAY, text: MONTHS[m.getUTCMonth()] });
- m = new Date(Date.UTC(m.getUTCFullYear(), m.getUTCMonth() + 1, 1));
- }
- return out;
- }
- const step = span > 50 ? 14 : span > 12 ? 7 : span > 6 ? 2 : 1;
-
- const first = step >= 7 ? Math.ceil((lo - 4) / 7) * 7 + 4 : Math.ceil(lo);
- const out: { at: number; text: string }[] = [];
- for (let t = first; t <= hi; t += step) out.push({ at: t, text: momentText(t, true) });
- return out;
-};
-
-export const layoutTime = (type: TimeType, data: TimeData, canvas: Canvas): Scene =>
- type === "gantt" ? layoutGantt(data, canvas) : layoutTimeline(data, canvas);
-
-const domain = (data: TimeData) => {
- const all = data.series.flatMap(s => [...(s.spans ?? []).flat(), ...(s.events ?? []).map(e => e[0])]).map(momentValue);
- const lo = data.x.min !== undefined ? momentValue(data.x.min) : Math.min(...all);
- const hi = data.x.max !== undefined ? momentValue(data.x.max) : Math.max(...all);
- const pad = data.x.min === undefined && data.x.max === undefined ? (hi - lo || 1) * 0.04 : 0;
- return { lo: lo - pad, hi: hi + pad };
-};
-
-const GANTT_ROW = 52;
-const LANE = 16;
-
-const ganttRows = (data: TimeData, width: number) => {
- const { lo, hi } = domain(data);
- const labelW = Math.min(width * 0.34, Math.max(...data.series.map(ser => ser.label.length)) * CHAR);
- const left = labelW + 16;
- const right = width - 16;
- const sx = (m: Moment | number) => left + (((typeof m === "number" ? m : momentValue(m)) - lo) / (hi - lo)) * (right - left);
- const rows = data.series.map(ser => {
- const events = (ser.events ?? []).map(([at, label]) => ({ x: sx(at), label }));
- const lanes = assignLanes(events.map(e => ({ x: e.x, width: textWidth(e.label) })), left, right);
- const count = Math.max(1, ...lanes.map(l => l.lane + 1));
- return { events, lanes, height: GANTT_ROW + (count - 1) * LANE };
- });
- return { lo, hi, labelW, left, right, sx, rows };
-};
-
-export const ganttHeight = (data: TimeData, width: number) =>
- 8 + ganttRows(data, width).rows.reduce((sum, r) => sum + r.height, 0) + 26 + (data.x.label ? 20 : 0);
-
-const layoutGantt = (data: TimeData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const dates = usesDates(data);
- const { lo, hi, labelW, left, right, sx, rows } = ganttRows(data, width);
- const plot = { left, right, top: 8, bottom: height - 26 - (data.x.label ? 20 : 0) };
-
- for (const t of timeTicks(lo, hi, dates)) {
- s.grid.push({ x1: sx(t.at), y1: plot.top, x2: sx(t.at), y2: plot.bottom });
- s.ticks.push({ x: sx(t.at), y: plot.bottom + 16, text: t.text, anchor: "middle" });
- }
- s.axis = `M${plot.left} ${plot.bottom}H${plot.right}`;
- if (data.x.label) s.axisLabels.push({ x: (plot.left + plot.right) / 2, y: height - 6, text: data.x.label });
-
- let y = plot.top;
- data.series.forEach((ser, i) => {
- const row = rows[i];
- const barH = 22;
- const barY = y + row.height - barH - 6;
- s.categoryLabels.push({ x: labelW + 6, y: barY + barH / 2 + 4.5, lines: [ser.label], anchor: "end" });
- s.barGroups.push({
- i,
- from: "left",
- bars: (ser.spans ?? []).map(([from, to]) => ({ x: sx(from), y: barY, w: Math.max(2, sx(to) - sx(from)), h: barH, color: ser.color })),
- });
- row.events.forEach((e, k) => {
- const { lane, anchor } = row.lanes[k];
- s.dots.push({ x: e.x, y: barY + barH / 2, color: ser.color, i, r: 4 });
- s.labels.push({ x: e.x, y: barY - 6 - lane * LANE, text: e.label, color: ser.color, anchor, i });
- });
- y += row.height;
- });
- return s;
-};
-
-const layoutTimeline = (data: TimeData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const dates = usesDates(data);
- const { lo, hi } = domain(data);
- const plot = { left: 24, right: width - 24, top: 12, bottom: height - 24 - (data.x.label ? 20 : 0) };
- const axisY = (plot.top + plot.bottom) / 2;
- const sx = (m: Moment) => plot.left + ((momentValue(m) - lo) / (hi - lo)) * (plot.right - plot.left);
-
- for (const t of timeTicks(lo, hi, dates)) {
- const x = plot.left + ((t.at - lo) / (hi - lo)) * (plot.right - plot.left);
- s.grid.push({ x1: x, y1: plot.top, x2: x, y2: plot.bottom });
- s.ticks.push({ x, y: plot.bottom + 16, text: t.text, anchor: "middle" });
- }
- s.axis = `M${plot.left} ${axisY}H${plot.right}`;
- if (data.x.label) s.axisLabels.push({ x: (plot.left + plot.right) / 2, y: height - 6, text: data.x.label });
-
- data.series.forEach((ser, i) => {
- s.barGroups.push({
- i,
- from: "left",
- bars: (ser.spans ?? []).map(([from, to]) => ({ x: sx(from), y: axisY - 4, w: Math.max(2, sx(to) - sx(from)), h: 8, color: ser.color })),
- });
- });
-
- const events = data.series.flatMap((ser, i) =>
- (ser.events ?? []).map(([at, label]) => ({ x: sx(at), label, date: momentText(momentValue(at), dates), color: ser.color, i }))
- );
- const lanes = assignLanes(
- events.map(e => ({ x: e.x, width: Math.max(textWidth(e.label), textWidth(e.date)) })),
- plot.left,
- plot.right
- );
- const room = axisY - plot.top - 30;
- events.forEach((e, k) => {
- const { lane, anchor } = lanes[k];
- const up = lane % 2 === 0;
- const stem = Math.min(room, 24 + Math.floor(lane / 2) * 34);
- const end = up ? axisY - stem : axisY + stem;
- s.lines.push({ d: `M${e.x} ${axisY}V${end}`, color: "muted", i: e.i, width: 1 });
- s.dots.push({ x: e.x, y: axisY, color: e.color, i: e.i, r: 5 });
- s.labels.push({ x: e.x, y: up ? end - 18 : end + 14, text: e.label, color: "ink", anchor, i: e.i });
- s.labels.push({ x: e.x, y: up ? end - 5 : end + 27, text: e.date, color: "muted", anchor, i: e.i });
- });
- return s;
-};
diff --git a/docs/components/frames/ChartFrame/_xy.ts b/docs/components/frames/ChartFrame/_xy.ts
deleted file mode 100644
index 08bd6fe6..00000000
--- a/docs/components/frames/ChartFrame/_xy.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { labelWidth } from "./_labels";
-import { xyDomain } from "@/lib/charts/domain";
-import type { ChartType, XYData } from "@/lib/charts/schema";
-import { niceTicks } from "./_scale";
-import { type Canvas, emptyScene, linePath, pointList, type Scene } from "./_scene";
-
-export type XYType = Extract<ChartType, "line" | "area" | "stacked-area" | "step" | "scatter" | "bubble" | "error-bars" | "band">;
-
-const MAX_BUBBLE = 22;
-
-export const layoutXY = (type: XYType, data: XYData, { width, height }: Canvas): Scene => {
- const s = emptyScene();
- const { x: xd, y: yd } = xyDomain(type, data);
- const tickWidth = Math.max(...niceTicks(yd.min, yd.max, yd.step).map(v => labelWidth(`${+v.toFixed(6)}${data.y.unit}`, 11)));
- const left = Math.min(width * 0.35, Math.max(52, tickWidth + 12)) + (data.y.label ? 18 : 0);
- const bottom = 28 + (data.x.label ? 22 : 0);
- const plot = { left, right: width - 14, top: 16, bottom: height - bottom };
- const sx = (v: number) => plot.left + ((v - xd.min) / (xd.max - xd.min)) * (plot.right - plot.left);
- const sy = (v: number) => plot.bottom - ((v - yd.min) / (yd.max - yd.min)) * (plot.bottom - plot.top);
- const at = ([x, y]: readonly [number, number]) => [sx(x), sy(y)] as const;
- const tick = (axis: XYData["x"]) => (v: number) => `${+v.toFixed(6)}${axis.unit}`;
-
- for (const v of niceTicks(yd.min, yd.max, yd.step)) {
- s.grid.push({ x1: plot.left, y1: sy(v), x2: plot.right, y2: sy(v) });
- s.ticks.push({ x: plot.left - 8, y: sy(v) + 3.5, text: tick(data.y)(v), anchor: "end" });
- }
- for (const v of niceTicks(xd.min, xd.max, xd.step)) {
- s.ticks.push({ x: sx(v), y: plot.bottom + 17, text: tick(data.x)(v), anchor: "middle" });
- }
- s.axis = `M${plot.left} ${plot.top}V${plot.bottom}H${plot.right}`;
- if (data.x.label) s.axisLabels.push({ x: (plot.left + plot.right) / 2, y: height - 6, text: data.x.label });
- if (data.y.label) s.axisLabels.push({ x: 13, y: (plot.top + plot.bottom) / 2, text: data.y.label, rotate: true });
-
- for (const t of data.annotations) {
- const y = sy(t.y);
- s.thresholds.push({
- d: `M${plot.left} ${y}H${plot.right}`,
- label: t.label ? { x: plot.right - 4, y: y - 6, text: t.label, anchor: "end" } : undefined,
- });
- }
-
- const base = sy(Math.max(yd.min, Math.min(yd.max, 0)));
-
- if (type === "stacked-area") {
- let below: (readonly [number, number])[] = data.series[0].points.map(([x]) => [x, 0] as const);
- data.series.forEach((ser, i) => {
- const top = ser.points.map(([x, y], j) => [x, below[j][1] + y] as const);
- s.polygons.push({ points: pointList([...top.map(at), ...below.map(at).reverse()]), color: ser.color, i, outline: false, opacity: 0.45 });
- s.lines.push({ d: linePath(top.map(at)), color: ser.color, i, width: 1.5 });
- below = top;
- });
- return s;
- }
-
- const sizes = data.series.flatMap(ser => ser.size ?? []);
- const radius = (v: number) => Math.max(4, MAX_BUBBLE * Math.sqrt(v / Math.max(...sizes)));
-
- data.series.forEach((ser, i) => {
- const pts = ser.points.map(at);
- const err = (j: number) => ser.error?.[j] ?? 0;
- switch (type) {
- case "line":
- case "step":
- s.lines.push({ d: linePath(pts, type === "step"), color: ser.color, i, width: 2 });
- s.dots.push({ x: pts[pts.length - 1][0], y: pts[pts.length - 1][1], color: ser.color, i, r: 3.5 });
- break;
- case "area": {
- const first = pts[0][0];
- const last = pts[pts.length - 1][0];
- s.polygons.push({ points: pointList([...pts, [last, base], [first, base]]), color: ser.color, i, outline: false, opacity: 0.16 });
- s.lines.push({ d: linePath(pts), color: ser.color, i, width: 2 });
- break;
- }
- case "band": {
- const upper = ser.points.map(([x, y], j) => at([x, y + err(j)]));
- const lower = ser.points.map(([x, y], j) => at([x, y - err(j)]));
- s.polygons.push({ points: pointList([...upper, ...lower.reverse()]), color: ser.color, i, outline: false, opacity: 0.18 });
- s.lines.push({ d: linePath(pts), color: ser.color, i, width: 2 });
- break;
- }
- case "error-bars":
- s.lines.push({ d: linePath(pts), color: ser.color, i, width: 1.25 });
- ser.points.forEach(([x, y], j) => {
- const [px, top] = at([x, y + err(j)]);
- const bot = sy(y - err(j));
- s.lines.push({ d: `M${px - 4} ${top}H${px + 4}M${px} ${top}V${bot}M${px - 4} ${bot}H${px + 4}`, color: ser.color, i, width: 1.25 });
- s.dots.push({ x: px, y: sy(y), color: ser.color, i, r: 3.5 });
- });
- break;
- case "scatter":
- pts.forEach(([x, y]) => s.dots.push({ x, y, color: ser.color, i, r: 3.5 }));
- break;
- case "bubble":
- pts.forEach(([x, y], j) => s.dots.push({ x, y, color: ser.color, i, r: radius(ser.size?.[j] ?? 1), bubble: true }));
- break;
- }
- });
- return s;
-};
diff --git a/docs/components/frames/ChartFrame/styles.module.scss b/docs/components/frames/ChartFrame/styles.module.scss
deleted file mode 100644
index d5c81f80..00000000
--- a/docs/components/frames/ChartFrame/styles.module.scss
+++ /dev/null
@@ -1,355 +0,0 @@
-@import "../vars";
-
-.frame.frame {
- // The frame box, head, legend and caption are FrameShell's; this styles the drawing.
-
- .plot {
- display: block;
- width: 100%;
- height: auto;
- margin: 0;
- overflow: visible;
- }
-
- .wide {
- max-height: 60vh;
-
- @container (max-width: 520px) {
- display: none;
- }
- }
-
- .narrow {
- display: none;
-
- @container (max-width: 520px) {
- display: block;
- }
- }
-
- .grid {
- stroke: var(--border-subtle);
- stroke-dasharray: 2 4;
- }
-
- .axis {
- fill: none;
- stroke: var(--border-strong);
- }
-
- .tick {
- font-size: 11px;
- fill: var(--text-secondary);
- }
-
- .category {
- font-size: 13px;
- fill: var(--text-primary);
- }
-
- .threshold {
- stroke: var(--text-secondary);
- stroke-dasharray: 6 4;
- }
-
- .thresholdLabel {
- font-size: 11px;
- fill: var(--text-secondary);
- stroke: var(--bg-secondary);
- stroke-width: 3.5;
- stroke-linejoin: round;
- paint-order: stroke;
- }
-
- .bar {
- fill: var(--mark-color);
- fill-opacity: 0.2;
- stroke: var(--mark-color);
- stroke-width: 1;
- }
-
- .ring {
- fill: none;
- stroke: var(--border-subtle);
- }
-
- .area {
- fill: var(--mark-color);
- fill-opacity: 0.16;
- stroke: var(--mark-color);
- stroke-width: 1.5;
- stroke-linejoin: round;
- }
-
- .areaFill {
- fill: var(--mark-color);
- fill-opacity: 0.16;
- }
-
- .barSolid,
- .slice {
- fill: var(--mark-color);
- fill-opacity: 0.6;
- stroke: var(--bg-secondary);
- stroke-width: 2;
- stroke-linejoin: round;
- }
-
-
- // Matrix cells: a 2px gap in the frame's background between neighbours.
- .cell {
- fill: var(--mark-color);
- stroke: var(--bg-secondary);
- stroke-width: 2;
- }
-
- .bubble {
- fill: var(--mark-color);
- fill-opacity: 0.3;
- stroke: var(--mark-color);
- stroke-width: 1.25;
- }
-
- .value {
- font-size: 13px;
- font-weight: $FONT_MEDIUM;
- fill: var(--mark-color);
- }
-
- // Sizes for value labels; after .value so they override it.
- .valueLarge {
- font-size: 22px;
- }
-
- .valueSmall {
- font-size: 11px;
- font-weight: $FONT_REGULAR;
- fill: var(--text-secondary);
- }
-
- .gridSolid {
- stroke: var(--border-subtle);
- }
-
- .gridZero {
- stroke: var(--border-strong);
- }
-
- .region {
- fill: var(--mark-color);
- }
-
- .curve,
- .curveDashed {
- fill: none;
- stroke: var(--mark-color);
- stroke-width: 2;
- stroke-linecap: round;
- stroke-linejoin: round;
- }
-
- .curveDashed {
- stroke-width: 1.5;
- stroke-dasharray: 5 4;
- }
-
- .vline {
- stroke: var(--mark-color);
- stroke-dasharray: 2 4;
- }
-
- .drop {
- stroke: var(--mark-color);
- stroke-width: 1.25;
- stroke-dasharray: 3 4;
- }
-
- .dot {
- fill: var(--mark-color);
- stroke: var(--bg-secondary);
- stroke-width: 1.5;
- }
-
- .dotHollow {
- fill: var(--bg-secondary);
- stroke: var(--mark-color);
- stroke-width: 1.75;
- }
-
- .arrowAxes path {
- fill: none;
- stroke: var(--text-primary);
- stroke-width: 1.4;
- stroke-linecap: round;
- stroke-linejoin: round;
- }
-
- .halo {
- stroke: var(--bg-secondary);
- stroke-width: 3.5;
- stroke-linejoin: round;
- paint-order: stroke;
- }
-
- .regionLabel {
- font-size: 13px;
- font-weight: $FONT_MEDIUM;
- fill: var(--text-primary);
- }
-
- .annotationLabel,
- .pointLabel {
- font-size: 11px;
- fill: var(--mark-color);
- }
-
- .axisLabel {
- font-size: 12px;
- fill: var(--text-secondary);
- }
-
- .barBody,
- .barBodyX {
- transform-box: fill-box;
- transform-origin: bottom;
- transition: transform 700ms cubic-bezier(0.22, 1, 0.36, 1);
- transition-delay: calc(var(--i) * 120ms);
- }
-
- .barBodyX {
- transform-origin: left;
- }
-
- .curve {
- stroke-dasharray: 1;
- transition: stroke-dashoffset 1100ms cubic-bezier(0.45, 0, 0.25, 1);
- transition-delay: calc(var(--i) * 150ms);
- }
-
- .value,
- .cell,
- .area,
- .areaFill,
- .slice,
- .curveDashed,
- .region,
- .threshold,
- .thresholdLabel,
- .vline,
- .drop,
- .point,
- .regionLabel,
- .annotationLabel {
- transition: opacity 400ms ease-out;
- }
-
- .value {
- transition-delay: calc(var(--i) * 120ms + 500ms);
- }
-
- .area,
- .areaFill,
- .slice {
- transition-delay: calc(var(--i) * 150ms + 200ms);
- }
-
- .cell {
- transition-delay: calc(var(--i) * 40ms);
- }
-
- .curveDashed,
- .region,
- .threshold,
- .thresholdLabel,
- .vline,
- .annotationLabel,
- .regionLabel {
- transition-delay: 600ms;
- }
-
- .drop,
- .point {
- transition-delay: 1000ms;
- }
-
- .reveal[data-revealed="false"] {
- .barBody {
- transform: scaleY(0);
- }
-
- .barBodyX {
- transform: scaleX(0);
- }
-
- .curve {
- stroke-dashoffset: 1;
- }
-
- .value,
- .cell,
- .area,
- .areaFill,
- .slice,
- .curveDashed,
- .region,
- .threshold,
- .thresholdLabel,
- .vline,
- .drop,
- .point,
- .regionLabel,
- .annotationLabel {
- opacity: 0;
- }
- }
-
- @media (prefers-reduced-motion: reduce) {
- .barBody,
- .barBodyX,
- .curve,
- .value,
- .cell,
- .area,
- .areaFill,
- .slice,
- .curveDashed,
- .region,
- .threshold,
- .thresholdLabel,
- .vline,
- .drop,
- .point,
- .regionLabel,
- .annotationLabel {
- transition: none;
- }
-
- .reveal[data-revealed="false"] {
- .barBody,
- .barBodyX {
- transform: none;
- }
-
- .curve {
- stroke-dashoffset: 0;
- }
-
- .value,
- .cell,
- .area,
- .areaFill,
- .slice,
- .curveDashed,
- .region,
- .threshold,
- .thresholdLabel,
- .vline,
- .drop,
- .point,
- .regionLabel,
- .annotationLabel {
- opacity: 1;
- }
- }
- }
-}
diff --git a/docs/components/frames/ChatFrame/ChatFrame.tsx b/docs/components/frames/ChatFrame/ChatFrame.tsx
deleted file mode 100644
index 3046085f..00000000
--- a/docs/components/frames/ChatFrame/ChatFrame.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-import type * as React from "react";
-import { ArrowUp, Bot, Check, X } from "lucide-react";
-import FrameShell from "@/components/frames/FrameShell/FrameShell";
-import { renderHighlights } from "@/components/frames/TranscriptFrame/_text";
-import type { ChatData, ChatMessage } from "@/lib/frames/chat";
-import { CHAT_KIND } from "@/lib/frames/kinds";
-import styles from "./styles.module.scss";
-
-interface ChatFrameProps {
- id: string;
- chat?: ChatData;
- type: string;
- title: string;
- description: string;
- kicker?: string;
- subtitle?: string;
- note?: string;
- caption?: string;
-}
-
-const Verdict = ({ verdict }: { verdict?: ChatMessage["verdict"] }): React.ReactElement | null =>
- verdict ? (
- <span className={styles.verdict} data-verdict={verdict} aria-label={verdict === "pass" ? "acceptable reply" : "unsafe reply"}>
- {verdict === "pass" ? <Check size={11} strokeWidth={3} /> : <X size={11} strokeWidth={3} />}
- </span>
- ) : null;
-
-const Text = ({ text }: { text: string }): React.ReactElement => <>{renderHighlights(text, styles.highlight)}</>;
-
-/** Bubbles in a chat window: the user's on the right, the bot's on the left beside its avatar. */
-const Chat = ({ data }: { data: ChatData }): React.ReactElement => (
- <div className={styles.window}>
- <div className={styles.windowHead}>
- <span className={styles.avatar} aria-hidden="true">
- <Bot size={14} />
- </span>
- {data.bot}
- </div>
- <div className={styles.messages}>
- {data.messages.map((m, i) =>
- m.from === "user" ? (
- <div key={i} className={styles.userBubble}>
- <Text text={m.text} />
- </div>
- ) : (
- <div key={i} className={styles.botRow}>
- <span className={styles.avatar} aria-hidden="true">
- <Bot size={14} />
- </span>
- <div className={styles.botBubble}>
- <Text text={m.text} />
- </div>
- <Verdict verdict={m.verdict} />
- </div>
- )
- )}
- </div>
- <div className={styles.composer} aria-hidden="true">
- <span>Message {data.bot}…</span>
- <span className={styles.send}>
- <ArrowUp size={12} strokeWidth={2.5} />
- </span>
- </div>
- </div>
-);
-
-/** A playground: each prompt in a field with a Generate button, each reply in a terminal-style output panel. */
-const Playground = ({ data }: { data: ChatData }): React.ReactElement => (
- <div className={styles.playground}>
- {data.messages.map((m, i) =>
- m.from === "user" ? (
- <div key={i} className={styles.promptBlock}>
- <span className={styles.fieldLabel}>Prompt</span>
- <div className={styles.field}>
- <Text text={m.text} />
- </div>
- <span className={styles.generate} aria-hidden="true">
- Generate
- </span>
- </div>
- ) : (
- <div key={i} className={styles.outputBlock}>
- <div className={styles.outputHead}>
- <span className={styles.botName}>{data.bot}</span>
- <Verdict verdict={m.verdict} />
- </div>
- <div className={styles.output}>
- <Text text={m.text} />
- </div>
- </div>
- )
- )}
- </div>
-);
-
-const ChatFrame: React.FC<ChatFrameProps> = ({ id, chat, type, title, description, kicker, subtitle, note, caption }) => {
- const problems = !chat
- ? ["unknown or invalid data"]
- : !CHAT_KIND.types.includes(type)
- ? [`unknown type "${type}"`]
- : CHAT_KIND.typeProblems(type, chat);
- if (!chat || problems.length) {
- console.warn(`[ChatFrame] Can't draw "${id}" as "${type}": ${problems.join("; ")}. Run yarn check:content for details.`);
- return null;
- }
- return (
- <FrameShell
- className={styles.frame}
- data={{ "data-chat": id, "data-chat-type": type }}
- title={title}
- description={description}
- kicker={kicker}
- subtitle={subtitle}
- caption={caption}
- note={note}
- content="text"
- >
- {type === "playground" ? <Playground data={chat} /> : <Chat data={chat} />}
- </FrameShell>
- );
-};
-
-export const createChatFrame = (data: Record<string, ChatData>) =>
- function ArticleChatFrame(props: Omit<ChatFrameProps, "chat">) {
- return <ChatFrame {...props} chat={Object.hasOwn(data, props.id) ? data[props.id] : undefined} />;
- };
-
-export default ChatFrame;
diff --git a/docs/components/frames/ChatFrame/styles.module.scss b/docs/components/frames/ChatFrame/styles.module.scss
deleted file mode 100644
index 20b1442b..00000000
--- a/docs/components/frames/ChatFrame/styles.module.scss
+++ /dev/null
@@ -1,211 +0,0 @@
-@import "../vars";
-@import "../FrameShell/frame";
-
-.frame.frame {
- // tokens:start
- // Every color and size a chat draws. Unbranded on purpose: a generic chat app, not any real product's look.
- --chat-surface: var(--bg-card);
- --chat-sunken: var(--bg-secondary);
- --chat-border: var(--border-subtle);
- --chat-text: var(--text-primary);
- --chat-muted: var(--text-secondary);
- --chat-user: color-mix(in srgb, var(--chart-violet) 14%, var(--bg-card));
- --chat-terminal: color-mix(in srgb, var(--text-primary) 88%, #000);
- --chat-terminal-text: color-mix(in srgb, var(--chart-teal) 55%, #fff);
- --chat-pass: var(--chart-teal);
- --chat-fail: var(--chart-pink);
- --chat-radius: 14px;
- --chat-text-size: 14px;
- --chat-small: 12px;
- // tokens:end
-
- .highlight {
- background: none;
- font-weight: $FONT_MEDIUM;
- color: var(--chat-fail);
- }
-
- .verdict {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 18px;
- height: 18px;
- flex-shrink: 0;
- border-radius: 50%;
- color: var(--chat-surface);
-
- &[data-verdict="pass"] {
- background: var(--chat-pass);
- }
-
- &[data-verdict="fail"] {
- background: var(--chat-fail);
- }
- }
-
- // chat: bubbles in a window.
- .window {
- display: flex;
- flex-direction: column;
- max-width: 620px;
- margin: 4px auto 0;
- border: 1px solid var(--chat-border);
- border-radius: var(--chat-radius);
- background: var(--chat-surface);
- overflow: hidden;
- }
-
- .windowHead {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 10px 14px;
- border-bottom: 1px solid var(--chat-border);
- font-size: var(--chat-small);
- font-weight: $FONT_MEDIUM;
- color: var(--chat-text);
- }
-
- .avatar {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 24px;
- height: 24px;
- flex-shrink: 0;
- border-radius: 50%;
- background: var(--chat-sunken);
- color: var(--chat-muted);
- }
-
- .messages {
- display: flex;
- flex-direction: column;
- gap: 14px;
- padding: 18px 14px;
- font-size: var(--chat-text-size);
- line-height: 1.5;
- color: var(--chat-text);
- }
-
- .userBubble {
- align-self: flex-end;
- max-width: 80%;
- padding: 8px 14px;
- border-radius: var(--chat-radius);
- background: var(--chat-user);
- white-space: pre-line;
- overflow-wrap: anywhere;
- }
-
- .botRow {
- display: flex;
- align-items: flex-start;
- gap: 10px;
- max-width: 92%;
- }
-
- .botBubble {
- min-width: 0;
- padding-top: 2px;
- white-space: pre-line;
- overflow-wrap: anywhere;
- }
-
- .botRow .verdict {
- margin-top: 3px;
- }
-
- .composer {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin: 0 12px 12px;
- padding: 8px 8px 8px 14px;
- border: 1px solid var(--chat-border);
- border-radius: var(--chat-radius);
- font-size: var(--chat-small);
- color: var(--chat-muted);
- }
-
- .send {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 22px;
- height: 22px;
- border-radius: 50%;
- background: var(--chat-text);
- color: var(--chat-surface);
- }
-
- // playground: a prompt field, a Generate button, an output panel.
- .playground {
- display: flex;
- flex-direction: column;
- gap: 18px;
- margin-top: 4px;
- padding: 16px;
- border: 1px solid var(--chat-border);
- border-radius: var(--chat-radius);
- background: var(--chat-surface);
- font-size: var(--chat-text-size);
- line-height: 1.5;
- color: var(--chat-text);
- }
-
- .promptBlock,
- .outputBlock {
- display: flex;
- flex-direction: column;
- gap: 8px;
- }
-
- .fieldLabel {
- font-size: var(--chat-small);
- color: var(--chat-muted);
- }
-
- .field {
- padding: 12px 14px;
- background: var(--chat-sunken);
- white-space: pre-line;
- overflow-wrap: anywhere;
- }
-
- .generate {
- align-self: flex-start;
- padding: 6px 14px;
- border: 1px solid var(--chat-border);
- border-radius: 8px;
- font-size: var(--chat-small);
- }
-
- .outputHead {
- display: flex;
- align-items: center;
- gap: 8px;
- }
-
- .botName {
- font-weight: $FONT_MEDIUM;
- }
-
- .output {
- min-height: 72px;
- padding: 12px 14px;
- background: var(--chat-terminal);
- font-family: $DM_MONO;
- font-size: var(--chat-small);
- line-height: 1.7;
- color: var(--chat-terminal-text);
- white-space: pre-line;
- overflow-wrap: anywhere;
-
- .highlight {
- color: inherit;
- text-decoration: underline;
- }
- }
-}
diff --git a/docs/components/frames/FlowFrame/FlowFrame.tsx b/docs/components/frames/FlowFrame/FlowFrame.tsx
deleted file mode 100644
index b40641b3..00000000
--- a/docs/components/frames/FlowFrame/FlowFrame.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import type * as React from "react";
-import FlowPlot from "@/components/frames/FlowPlot/FlowPlot";
-import { type FlowScene, MIN_SCALE } from "@/components/frames/FlowPlot/_scene";
-import FrameShell from "@/components/frames/FrameShell/FrameShell";
-import type { FlowData } from "@/lib/frames/flow";
-import { FLOW_KIND } from "@/lib/frames/kinds";
-import { layoutGraph, layoutSequence } from "./_layout";
-
-interface FlowFrameProps {
- id: string;
- flow?: FlowData;
-
- type: string;
- title: string;
-
- description: string;
- kicker?: string;
- subtitle?: string;
- note?: string;
- caption?: string;
-}
-
-// Label wrap widths for the wide (desktop) and narrow (phone) drawings.
-const WIDE_WRAP = 150;
-const NARROW_WRAP = 110;
-// The wide drawing's budget: the chart canvas width. A left-to-right flow wider
-// than this is laid out top to bottom instead.
-const WIDE_MAX = 640;
-
-const scenes = (type: string, flow: FlowData): [FlowScene, FlowScene] => {
- if (flow.shape === "sequence") return [layoutSequence(flow.data, WIDE_WRAP + 40), layoutSequence(flow.data, NARROW_WRAP)];
- const authored = layoutGraph(flow.data, flow.data.direction, WIDE_WRAP);
- const tall = flow.data.direction === "LR" && authored.width > WIDE_MAX ? layoutGraph(flow.data, "TB", WIDE_WRAP) : null;
- const wide = tall && tall.width < authored.width ? tall : authored;
- return [wide, layoutGraph(flow.data, "TB", NARROW_WRAP)];
-};
-
-const FlowFrame: React.FC<FlowFrameProps> = ({ id, flow, type, title, description, kicker, subtitle, note, caption }) => {
- const problems = !flow
- ? ["unknown or invalid data"]
- : !FLOW_KIND.types.includes(type)
- ? [`unknown type "${type}"`]
- : FLOW_KIND.typeProblems(type, flow);
- if (!flow || problems.length) {
- console.warn(`[FlowFrame] Can't draw "${id}" as "${type}": ${problems.join("; ")}. Run yarn check:content for details.`);
- return null;
- }
- const [wide, narrow] = scenes(type, flow);
- return (
- <FrameShell
- data={{ "data-flow": id, "data-flow-type": type }}
- title={title}
- description={description}
- kicker={kicker}
- subtitle={subtitle}
- caption={caption}
- note={note}
- >
- <FlowPlot scene={wide} id={id} variant="wide" minScale={MIN_SCALE.wide} />
- <FlowPlot scene={narrow} id={id} variant="narrow" minScale={MIN_SCALE.narrow} />
- </FrameShell>
- );
-};
-
-/** Bind MDX to this article's flows.json; authors only supply the local ID. */
-export const createFlowFrame = (data: Record<string, FlowData>) =>
- function ArticleFlowFrame(props: Omit<FlowFrameProps, "flow">) {
- return <FlowFrame {...props} flow={Object.hasOwn(data, props.id) ? data[props.id] : undefined} />;
- };
-
-export default FlowFrame;
diff --git a/docs/components/frames/FlowFrame/_layout.ts b/docs/components/frames/FlowFrame/_layout.ts
deleted file mode 100644
index cd948dd9..00000000
--- a/docs/components/frames/FlowFrame/_layout.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import dagre from "@dagrejs/dagre";
-import { type GraphData, type GraphNode, nodeColor, nodeIcon, type SequenceData } from "@/lib/frames/flow";
-import {
- type Box,
- boundary,
- type FlowScene,
- GROUP_HEAD,
- GROUP_PAD,
- groupHeaderWidth,
- iconRoom,
- LINE,
- normalize,
- PAD_X,
- PAD_Y,
- type Point,
- type SceneEdge,
- type SceneGroup,
- type SceneNode,
- SMALL,
- SMALL_LINE,
- smoothPath,
- textWidth,
- wrapWords,
-} from "@/components/frames/FlowPlot/_scene";
-
-// FlowFrame's layouts: dagre for flows and trees, columns and rows for sequences.
-
-const nodeSize = (node: GraphNode, wrap: number) => {
- const lines = wrapWords(node.label, wrap);
- const text = Math.max(...lines.map(l => textWidth(l))) + iconRoom(nodeIcon(node));
- const tall = lines.length * LINE;
- if (node.shape === "circle") {
- const d = Math.max(40, text + 20, tall + 16);
- return { lines, w: d, h: d };
- }
- if (node.shape === "diamond") return { lines, w: text * 1.5 + 32, h: tall * 1.6 + 28 };
- if (node.shape === "store") return { lines, w: text + PAD_X * 2, h: tall + PAD_Y * 2 + 10 };
- if (node.shape === "pill") return { lines, w: text + PAD_X * 2 + 10, h: tall + PAD_Y * 2 };
- return { lines, w: Math.max(56, text + PAD_X * 2), h: tall + PAD_Y * 2 };
-};
-
-export const layoutGraph = (data: GraphData, direction: "TB" | "LR", wrap: number): FlowScene => {
- const g = new dagre.graphlib.Graph({ compound: true, multigraph: true });
- // Groups need room for their header row: above them in TB, beside them in LR.
- const grouped = data.groups.length > 0;
- g.setGraph({
- rankdir: direction,
- nodesep: direction === "LR" ? (grouped ? GROUP_HEAD + 24 : 24) : 32,
- ranksep: direction === "TB" && grouped ? GROUP_HEAD + 44 : 44,
- edgesep: 14,
- marginx: 0,
- marginy: 0,
- });
- g.setDefaultEdgeLabel(() => ({}));
-
- const sizes = new Map(data.nodes.map(n => [n.id, nodeSize(n, wrap)]));
- for (const n of data.nodes) {
- const { w, h } = sizes.get(n.id)!;
- g.setNode(n.id, { width: w, height: h });
- }
- for (const group of data.groups) g.setNode(group.id, {});
- for (const group of data.groups) if (group.parent) g.setParent(group.id, group.parent);
- for (const n of data.nodes) if (n.group) g.setParent(n.id, n.group);
-
- const edgeLabels = data.edges.map(e => (e.label ? wrapWords(e.label, 120, SMALL) : undefined));
- data.edges.forEach((e, i) => {
- const lines = edgeLabels[i];
- const label = lines ? { width: Math.max(...lines.map(l => textWidth(l, SMALL))) + 8, height: lines.length * SMALL_LINE + 4, labelpos: "c" } : {};
- g.setEdge(e.from, e.to, label, `e${i}`);
- });
-
- dagre.layout(g);
-
- const nodes: SceneNode[] = data.nodes.map(n => {
- const laid = g.node(n.id);
- const { w, h, lines } = sizes.get(n.id)!;
- return { id: n.id, x: laid.x - w / 2, y: laid.y - h / 2, w, h, lines, color: nodeColor(n), shape: n.shape, icon: nodeIcon(n) };
- });
- const byId = new Map(nodes.map(n => [n.id, n]));
-
- // Group boxes are measured from their members rather than taken from dagre,
- // so each gets a header row for its label and badge. Inner groups first.
- const depth = (id: string): number => {
- const parent = data.groups.find(x => x.id === id)?.parent;
- return parent ? 1 + depth(parent) : 0;
- };
- const boxes = new Map<string, Box>();
- for (const group of [...data.groups].sort((a, b) => depth(b.id) - depth(a.id))) {
- const members: Box[] = [
- ...nodes.filter(n => data.nodes.find(x => x.id === n.id)?.group === group.id),
- ...data.groups.filter(x => x.parent === group.id).map(x => boxes.get(x.id)!),
- ];
- const left = Math.min(...members.map(b => b.x)) - GROUP_PAD;
- const right = Math.max(...members.map(b => b.x + b.w)) + GROUP_PAD;
- const top = Math.min(...members.map(b => b.y)) - GROUP_HEAD - 6;
- const bottom = Math.max(...members.map(b => b.y + b.h)) + GROUP_PAD;
- const minW = groupHeaderWidth(group.label, group.badge ? textWidth(group.badge, SMALL) + 14 : 0);
- const grow = Math.max(0, minW - (right - left)) / 2;
- boxes.set(group.id, { x: left - grow, y: top, w: right - left + grow * 2, h: bottom - top });
- }
- const groups: SceneGroup[] = data.groups.map(group => ({
- id: group.id,
- label: group.label,
- badge: group.badge ? { text: group.badge, w: textWidth(group.badge, SMALL) + 14 } : undefined,
- ...boxes.get(group.id)!,
- }));
-
- const edges: SceneEdge[] = data.edges.map((e, i) => {
- const laid = g.edge({ v: e.from, w: e.to, name: `e${i}` });
- const pts: Point[] = laid.points.map((p: Point) => ({ x: p.x, y: p.y }));
- const from = byId.get(e.from)!;
- const to = byId.get(e.to)!;
- pts[0] = boundary(from, pts[1] ?? { x: to.x + to.w / 2, y: to.y + to.h / 2 });
- pts[pts.length - 1] = boundary(to, pts[pts.length - 2] ?? { x: from.x + from.w / 2, y: from.y + from.h / 2 });
- const lines = edgeLabels[i];
- return {
- d: smoothPath(pts),
- dashed: e.dashed,
- both: e.both,
- label: lines && laid.x !== undefined ? { x: laid.x, y: laid.y, lines } : undefined,
- };
- });
-
- return normalize({ width: 0, height: 0, nodes, groups, edges, lifelines: [] });
-};
-
-const SEQ_GAP = 32;
-
-/** Participants as columns, messages as numbered arrows down the page. */
-export const layoutSequence = (data: SequenceData, wrap: number): FlowScene => {
- const index = new Map(data.participants.map((p, i) => [p.id, i]));
- const heads = data.participants.map(p => {
- const lines = wrapWords(p.label, Math.max(wrap, 96));
- const icon = nodeIcon(p);
- return { lines, icon, w: Math.max(88, Math.max(...lines.map(l => textWidth(l))) + iconRoom(icon) + PAD_X * 2) };
- });
- const headH = Math.max(...heads.map(h => h.lines.length)) * LINE + PAD_Y * 2;
-
- const messages = data.messages.map((m, i) => ({
- ...m,
- a: index.get(m.from)!,
- b: index.get(m.to)!,
- lines: wrapWords(`${i + 1}. ${m.label}`, wrap, SMALL),
- }));
- const labelW = (lines: string[]) => Math.max(...lines.map(l => textWidth(l, SMALL)));
-
- // Column gaps: room for both heads, then widened until each label fits over its span.
- const gaps = heads.slice(1).map((h, i) => (heads[i].w + h.w) / 2 + SEQ_GAP);
- const sorted = [...messages].filter(m => m.a !== m.b).sort((p, q) => Math.abs(p.b - p.a) - Math.abs(q.b - q.a));
- for (const m of sorted) {
- const lo = Math.min(m.a, m.b);
- const hi = Math.max(m.a, m.b);
- const span = gaps.slice(lo, hi).reduce((s, g) => s + g, 0);
- const need = labelW(m.lines) + 24;
- if (span < need) for (let k = lo; k < hi; k++) gaps[k] += (need - span) / (hi - lo);
- }
- const xs = [heads[0].w / 2];
- for (const g of gaps) xs.push(xs.at(-1)! + g);
-
- const nodes: SceneNode[] = data.participants.map((p, i) => ({
- id: p.id,
- x: xs[i] - heads[i].w / 2,
- y: 0,
- w: heads[i].w,
- h: headH,
- lines: heads[i].lines,
- color: nodeColor(p),
- shape: "box",
- icon: heads[i].icon,
- }));
-
- const edges: SceneEdge[] = [];
- let y = headH + 18;
- for (const m of messages) {
- const textH = m.lines.length * SMALL_LINE;
- const x1 = xs[m.a];
- const x2 = xs[m.b];
- if (m.a === m.b) {
- const top = y + textH + 2;
- edges.push({
- d: `M${x1},${top}L${x1 + 28},${top}L${x1 + 28},${top + 16}L${x1 + 2},${top + 16}`,
- dashed: m.dashed,
- both: false,
- label: { x: x1 + 8 + labelW(m.lines) / 2, y: y + textH / 2, lines: m.lines },
- });
- y = top + 16 + 20;
- } else {
- const arrowY = y + textH + 6;
- const dir = Math.sign(x2 - x1);
- edges.push({
- d: `M${x1 + dir * 2},${arrowY}L${x2 - dir * 2},${arrowY}`,
- dashed: m.dashed,
- both: false,
- label: { x: (x1 + x2) / 2, y: y + textH / 2, lines: m.lines },
- });
- y = arrowY + 18;
- }
- }
- const lifelines = xs.map(x => ({ x, y1: headH, y2: y - 4 }));
- return normalize({ width: 0, height: 0, nodes, groups: [], edges, lifelines });
-};
-
diff --git a/docs/components/frames/FlowPlot/FlowPlot.tsx b/docs/components/frames/FlowPlot/FlowPlot.tsx
deleted file mode 100644
index d62d27f7..00000000
--- a/docs/components/frames/FlowPlot/FlowPlot.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import type * as React from "react";
-import { markColor } from "@/components/frames/FrameShell/FrameShell";
-import { FLOW_ICON_COMPONENTS } from "./_icons";
-import { blockHeight, type FlowScene, GROUP_HEAD, ICON, iconRoom, LINE, type SceneNode, SMALL_LINE } from "./_scene";
-import styles from "./styles.module.scss";
-
-interface FlowPlotProps {
- scene: FlowScene;
- /** Unique within the page; names the arrowhead marker. */
- id: string;
- /** Wide shows above a 520px frame, narrow below it. */
- variant: "wide" | "narrow";
- /** How far the drawing may shrink to fit before it scrolls instead. */
- minScale: number;
-}
-
-const Lines = ({ x, y, lines, className, lineHeight, anchor }: { x: number; y: number; lines: string[]; className: string; lineHeight: number; anchor?: "start" | "middle" }): React.ReactElement => (
- <text className={className} x={x} y={y} textAnchor={anchor ?? "middle"} dominantBaseline="central">
- {lines.map((line, i) => (
- <tspan key={i} x={x} dy={i ? lineHeight : 0}>
- {line}
- </tspan>
- ))}
- </text>
-);
-
-// Average glyph width used to center an icon and its label as one unit; nearer
-// the real font than the layout's deliberately roomy estimate.
-const CENTERING_CHAR = 0.56;
-
-/** A node's label (and smaller lines under it), with its icon to the left; centered in the node. */
-const NodeContent = ({ node }: { node: SceneNode }): React.ReactElement | null => {
- if (node.ghost) return null;
- const sub = node.sub ?? [];
- const cx = node.x + node.w / 2;
- const cy = node.y + node.h / 2 + (node.shape === "store" ? 3 : 0);
- // First line's center, so the label and sub-lines together sit in the middle.
- const top = cy - blockHeight(node.lines.length, sub.length) / 2 + LINE / 2;
- const subTop = top + (node.lines.length - 1) * LINE + LINE / 2 + 2 + SMALL_LINE / 2;
- const Icon = node.icon ? FLOW_ICON_COMPONENTS[node.icon] : null;
- const textW = Math.max(...node.lines.map(l => Array.from(l).length * 13 * CENTERING_CHAR));
- const x0 = cx - (iconRoom(node.icon) + textW) / 2;
- const tx = Icon ? x0 + iconRoom(node.icon) : cx;
- return (
- <>
- {Icon ? (
- <Icon className={styles.icon} x={x0} y={top - ICON / 2} width={ICON} height={ICON} strokeWidth={1.75} aria-hidden="true" />
- ) : null}
- <Lines x={tx} y={top} lines={node.lines} className={styles.nodeLabel} lineHeight={LINE} anchor={Icon ? "start" : "middle"} />
- {sub.length ? <Lines x={cx} y={subTop} lines={sub} className={styles.sub} lineHeight={SMALL_LINE} /> : null}
- </>
- );
-};
-
-const Shape = ({ node }: { node: SceneNode }): React.ReactElement => {
- const { x, y, w, h } = node;
- const className = node.ghost ? styles.ghost : node.dashed ? `${styles.node} ${styles.dashed}` : styles.node;
- if (node.shape === "circle") return <circle className={className} cx={x + w / 2} cy={y + h / 2} r={w / 2} />;
- if (node.shape === "diamond") {
- return <polygon className={className} points={`${x + w / 2},${y} ${x + w},${y + h / 2} ${x + w / 2},${y + h} ${x},${y + h / 2}`} />;
- }
- if (node.shape === "store") {
- const ry = 5;
- return (
- <>
- <path className={className} d={`M${x},${y + ry}A${w / 2},${ry} 0 0 1 ${x + w},${y + ry}V${y + h - ry}A${w / 2},${ry} 0 0 1 ${x},${y + h - ry}Z`} />
- <path className={styles.storeRim} d={`M${x},${y + ry}A${w / 2},${ry} 0 0 0 ${x + w},${y + ry}`} />
- </>
- );
- }
- return <rect className={className} x={x} y={y} width={w} height={h} rx={node.shape === "pill" ? h / 2 : 0} />;
-};
-
-/** Where a path ends: the last two numbers of its last command. */
-const endOf = (d: string) => {
- const n = d.match(/-?\d+(\.\d+)?/g)!.map(Number);
- return { x: n[n.length - 2], y: n[n.length - 1] };
-};
-
-/** Boxes, containers and lines from a frame's layout, as one static SVG. */
-const FlowPlot: React.FC<FlowPlotProps> = ({ scene, id, variant, minScale }) => {
- const marker = `flow-arrow-${id}-${variant}`;
- return (
- <svg
- className={`${styles.plot} ${styles[variant]}`}
- viewBox={`0 0 ${scene.width} ${scene.height}`}
- style={{ maxWidth: scene.width, minWidth: Math.round(scene.width * minScale) }}
- aria-hidden="true"
- >
- <defs>
- <marker id={marker} viewBox="0 0 8 8" refX="8" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
- <path className={styles.arrowHead} d="M0,0L8,4L0,8Z" />
- </marker>
- </defs>
- {scene.groups.map(g => (
- <rect key={g.id} className={styles.group} x={g.x} y={g.y} width={g.w} height={g.h} />
- ))}
- {scene.lifelines.map((l, i) => (
- <line key={i} className={styles.lifeline} x1={l.x} y1={l.y1} x2={l.x} y2={l.y2} />
- ))}
- {scene.edges.map((e, i) =>
- e.color ? (
- <g key={i} style={markColor(e.color)}>
- <path className={e.dashed ? `${styles.connector} ${styles.dashedLine}` : styles.connector} d={e.d} />
- <circle className={styles.connectorEnd} cx={endOf(e.d).x} cy={endOf(e.d).y} r={3} />
- </g>
- ) : (
- <path
- key={i}
- className={e.dashed ? `${styles.edge} ${styles.dashedLine}` : styles.edge}
- d={e.d}
- markerEnd={`url(#${marker})`}
- markerStart={e.both ? `url(#${marker})` : undefined}
- />
- )
- )}
- {scene.nodes.map(n => (
- <g key={n.id} style={markColor(n.color)}>
- <Shape node={n} />
- <NodeContent node={n} />
- </g>
- ))}
- {scene.groups.map(g => (
- <g key={g.id}>
- <text className={styles.groupLabel} x={g.x + 10} y={g.y + GROUP_HEAD / 2 + 3} dominantBaseline="central">
- {g.label}
- </text>
- {g.badge ? (
- <g style={markColor(g.badge.color ?? "teal")}>
- <rect className={styles.badge} x={g.x + g.w - g.badge.w - 6} y={g.y + 6} width={g.badge.w} height={GROUP_HEAD - 6} />
- <text className={styles.badgeLabel} x={g.x + g.w - g.badge.w / 2 - 6} y={g.y + 6 + (GROUP_HEAD - 6) / 2} textAnchor="middle" dominantBaseline="central">
- {g.badge.text}
- </text>
- </g>
- ) : null}
- </g>
- ))}
- {scene.edges.map((e, i) =>
- e.label ? (
- <Lines
- key={i}
- x={e.label.x}
- y={e.label.y - ((e.label.lines.length - 1) * SMALL_LINE) / 2}
- lines={e.label.lines}
- className={styles.edgeLabel}
- lineHeight={SMALL_LINE}
- />
- ) : null
- )}
- </svg>
- );
-};
-
-export default FlowPlot;
diff --git a/docs/components/frames/FlowPlot/_icons.ts b/docs/components/frames/FlowPlot/_icons.ts
deleted file mode 100644
index 73724ee5..00000000
--- a/docs/components/frames/FlowPlot/_icons.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import {
- Activity,
- AppWindow,
- Bell,
- Binary,
- BookOpen,
- Bot,
- Boxes,
- Brain,
- Bug,
- Calendar,
- ClipboardCheck,
- Code,
- Cpu,
- Database,
- FileSearch,
- FileText,
- Filter,
- Gauge,
- Gavel,
- Globe,
- HardDrive,
- Image,
- Inbox,
- Key,
- Layers,
- LayoutTemplate,
- Library,
- ListChecks,
- Lock,
- type LucideIcon,
- Mail,
- MessageSquare,
- MessageSquareReply,
- Network,
- Plug,
- Scale,
- Search,
- Send,
- Server,
- ShieldAlert,
- ShieldCheck,
- Sparkles,
- Table,
- Target,
- Terminal,
- TextCursorInput,
- User,
- Users,
- Workflow,
- Wrench,
- Zap,
-} from "lucide-react";
-import type { FlowIcon } from "@/lib/frames/flow";
-
-/** The lucide component for each name in FLOW_ICONS; TypeScript keeps the two lists in step. */
-export const FLOW_ICON_COMPONENTS: Record<FlowIcon, LucideIcon> = {
- activity: Activity,
- "app-window": AppWindow,
- bell: Bell,
- binary: Binary,
- "book-open": BookOpen,
- bot: Bot,
- boxes: Boxes,
- brain: Brain,
- bug: Bug,
- calendar: Calendar,
- "clipboard-check": ClipboardCheck,
- code: Code,
- cpu: Cpu,
- database: Database,
- "file-search": FileSearch,
- "file-text": FileText,
- filter: Filter,
- gauge: Gauge,
- gavel: Gavel,
- globe: Globe,
- "hard-drive": HardDrive,
- image: Image,
- inbox: Inbox,
- key: Key,
- layers: Layers,
- "layout-template": LayoutTemplate,
- library: Library,
- "list-checks": ListChecks,
- lock: Lock,
- mail: Mail,
- "message-square": MessageSquare,
- "message-square-reply": MessageSquareReply,
- network: Network,
- plug: Plug,
- scale: Scale,
- search: Search,
- send: Send,
- server: Server,
- "shield-alert": ShieldAlert,
- "shield-check": ShieldCheck,
- sparkles: Sparkles,
- table: Table,
- target: Target,
- terminal: Terminal,
- "text-cursor-input": TextCursorInput,
- user: User,
- users: Users,
- workflow: Workflow,
- wrench: Wrench,
- zap: Zap,
-};
diff --git a/docs/components/frames/FlowPlot/_scene.ts b/docs/components/frames/FlowPlot/_scene.ts
deleted file mode 100644
index fc3c60ff..00000000
--- a/docs/components/frames/FlowPlot/_scene.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import type { ChartColor } from "@/lib/charts/schema";
-import type { FlowIcon, NodeShape } from "@/lib/frames/flow";
-
-// The geometry FlowPlot draws: boxes, containers and lines, positioned by a
-// frame's own layout (FlowFrame's dagre layout, SchemaFrame's rows). Text sizes
-// match the charts: 13px labels, 11px small print.
-
-export const LABEL = 13;
-export const SMALL = 11;
-export const LINE = 17;
-export const SMALL_LINE = 14;
-// Average glyph width of the inherited proportional font, as the charts estimate it.
-const CHAR = 0.6;
-
-export const textWidth = (text: string, size = LABEL) => Array.from(text).length * size * CHAR;
-
-/**
- * Wrap at word boundaries without dropping text. A word too long for a line
- * breaks after its hyphens ("Reference-" / "less"), and only then mid-word.
- */
-export const wrapWords = (text: string, width: number, size = LABEL): string[] => {
- const max = Math.max(4, Math.floor(width / (size * CHAR)));
- // Pieces, each with whether it follows the previous one after a space.
- const pieces = text
- .trim()
- .split(/\s+/)
- .flatMap(word =>
- Array.from(word).length > max ? word.split(/(?<=-)/).map((part, i) => ({ part, spaced: i === 0 })) : [{ part: word, spaced: true }]
- );
- const lines: string[] = [];
- let line = "";
- for (const { part, spaced } of pieces) {
- const joined = line ? `${line}${spaced ? " " : ""}${part}` : part;
- if (Array.from(joined).length <= max) {
- line = joined;
- continue;
- }
- if (line) lines.push(line);
- const chars = Array.from(part);
- while (chars.length > max) lines.push(chars.splice(0, max).join(""));
- line = chars.join("");
- }
- if (line) lines.push(line);
- return lines;
-};
-
-export interface Point {
- x: number;
- y: number;
-}
-
-export interface Box {
- x: number;
- y: number;
- w: number;
- h: number;
-}
-
-export interface SceneNode extends Box {
- id: string;
- lines: string[];
- color: ChartColor;
- shape: NodeShape;
- /** Drawn left of the label, which is centered in the space after it. */
- icon?: FlowIcon;
- /** Smaller secondary lines under the label, e.g. an example value. */
- sub?: string[];
- /** A dashed outline, e.g. for an optional field. */
- dashed?: boolean;
- /** An empty dashed slot marking something absent. */
- ghost?: boolean;
-}
-
-export interface SceneGroup extends Box {
- id: string;
- label: string;
- badge?: { text: string; w: number; color?: ChartColor };
-}
-
-export interface SceneEdge {
- d: string;
- dashed: boolean;
- both: boolean;
- label?: { x: number; y: number; lines: string[] };
- /** A colored connector that ends in a dot instead of an arrowhead. */
- color?: ChartColor;
-}
-
-export interface FlowScene {
- width: number;
- height: number;
- nodes: SceneNode[];
- groups: SceneGroup[];
- edges: SceneEdge[];
- /** Sequence diagrams only. */
- lifelines: { x: number; y1: number; y2: number }[];
-}
-
-export const PAD_X = 14;
-export const PAD_Y = 9;
-// Icons sit left of the label at the label's cap height.
-export const ICON = 15;
-const ICON_GAP = 7;
-/** Horizontal room an icon takes in a node, or 0. */
-export const iconRoom = (icon?: FlowIcon) => (icon ? ICON + ICON_GAP : 0);
-
-// How far a drawing may shrink to fit before it scrolls instead, so labels stay
-// legible (13px at 0.75 is about the size of a phone chart's tick labels).
-export const MIN_SCALE = { wide: 0.8, narrow: 0.75 };
-
-export const GROUP_HEAD = 22;
-export const GROUP_PAD = 12;
-
-/** Width a container needs for its header: the uppercase, letter-spaced label and its badge. */
-export const groupHeaderWidth = (label: string, badgeW = 0) =>
- // 0.08em tracking and uppercase glyphs run about 30% wider than the estimate.
- textWidth(label.toUpperCase(), SMALL) * 1.3 + 20 + (badgeW ? badgeW + 10 : 0);
-
-/** Height of a label block: label lines plus any smaller lines under them. */
-export const blockHeight = (lines: number, sub = 0) => lines * LINE + (sub ? 2 + sub * SMALL_LINE : 0);
-
-/** Where the line from a node's center towards `p` leaves the node's outline. */
-export const boundary = (n: SceneNode, p: Point): Point => {
- const cx = n.x + n.w / 2;
- const cy = n.y + n.h / 2;
- const dx = p.x - cx;
- const dy = p.y - cy;
- const len = Math.hypot(dx, dy);
- if (!len) return p;
- const ux = dx / len;
- const uy = dy / len;
- let t: number;
- if (n.shape === "circle") t = n.w / 2;
- else if (n.shape === "diamond") t = 1 / (Math.abs(ux) / (n.w / 2) + Math.abs(uy) / (n.h / 2));
- else t = Math.min(ux ? n.w / 2 / Math.abs(ux) : Infinity, uy ? n.h / 2 / Math.abs(uy) : Infinity);
- return { x: cx + ux * t, y: cy + uy * t };
-};
-
-const f = (n: number) => Math.round(n * 10) / 10;
-
-/** A smooth path through layout points: straight ends, rounded bends. */
-export const smoothPath = (pts: Point[]): string => {
- if (pts.length < 3) return `M${f(pts[0].x)},${f(pts[0].y)}L${f(pts.at(-1)!.x)},${f(pts.at(-1)!.y)}`;
- const mid = (a: Point, b: Point) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
- let d = `M${f(pts[0].x)},${f(pts[0].y)}`;
- const first = mid(pts[0], pts[1]);
- d += `L${f(first.x)},${f(first.y)}`;
- for (let i = 1; i < pts.length - 1; i++) {
- const m = mid(pts[i], pts[i + 1]);
- d += `Q${f(pts[i].x)},${f(pts[i].y)} ${f(m.x)},${f(m.y)}`;
- }
- const last = pts.at(-1)!;
- return `${d}L${f(last.x)},${f(last.y)}`;
-};
-
-/** A horizontal S-curve from `a` to `b`, leaving and entering level. */
-export const sCurve = (a: Point, b: Point): string => {
- const dx = (b.x - a.x) / 2;
- return `M${f(a.x)},${f(a.y)}C${f(a.x + dx)},${f(a.y)} ${f(b.x - dx)},${f(b.y)} ${f(b.x)},${f(b.y)}`;
-};
-
-/** Shift everything so the drawing starts at a small margin, and measure it. */
-export const normalize = (scene: FlowScene): FlowScene => {
- const boxes: Box[] = [...scene.nodes, ...scene.groups];
- for (const e of scene.edges) {
- if (e.label) {
- const w = Math.max(...e.label.lines.map(l => textWidth(l, SMALL)));
- const h = e.label.lines.length * SMALL_LINE;
- boxes.push({ x: e.label.x - w / 2, y: e.label.y - h / 2, w, h });
- }
- }
- const nums = (d: string) => (d.match(/-?\d+(\.\d+)?/g) ?? []).map(Number);
- for (const e of scene.edges) {
- const n = nums(e.d);
- for (let i = 0; i + 1 < n.length; i += 2) boxes.push({ x: n[i], y: n[i + 1], w: 0, h: 0 });
- }
- const M = 4;
- const minX = Math.min(...boxes.map(b => b.x)) - M;
- const minY = Math.min(...boxes.map(b => b.y)) - M;
- const maxX = Math.max(...boxes.map(b => b.x + b.w)) + M;
- const maxY = Math.max(...boxes.map(b => b.y + b.h)) + M;
- const shift = <T extends Box>(b: T): T => ({ ...b, x: b.x - minX, y: b.y - minY });
- const shiftPath = (d: string) => {
- let i = 0;
- return d.replace(/-?\d+(\.\d+)?/g, m => String(Math.round((Number(m) - (i++ % 2 === 0 ? minX : minY)) * 10) / 10));
- };
- return {
- width: Math.ceil(maxX - minX),
- height: Math.ceil(maxY - minY),
- nodes: scene.nodes.map(shift),
- groups: scene.groups.map(shift),
- edges: scene.edges.map(e => ({
- ...e,
- d: shiftPath(e.d),
- label: e.label ? { ...e.label, x: e.label.x - minX, y: e.label.y - minY } : undefined,
- })),
- lifelines: scene.lifelines.map(l => ({ x: l.x - minX, y1: l.y1 - minY, y2: l.y2 - minY })),
- };
-};
diff --git a/docs/components/frames/FlowPlot/styles.module.scss b/docs/components/frames/FlowPlot/styles.module.scss
deleted file mode 100644
index c8315fca..00000000
--- a/docs/components/frames/FlowPlot/styles.module.scss
+++ /dev/null
@@ -1,123 +0,0 @@
-@import "../vars";
-@import "../FrameShell/frame";
-
-// Sized against the FrameShell figure, which is the container for the queries.
-.plot {
- display: block;
- width: 100%;
- height: auto;
- margin: 4px auto 0;
- overflow: visible;
-
- &.wide {
- max-height: 60vh;
- }
-
- &.narrow {
- display: none;
- }
-
- @container (max-width: 520px) {
- &.wide {
- display: none;
- }
-
- &.narrow {
- display: block;
- }
- }
-
- .node {
- @include mark-fill-svg;
- }
-
- .dashed {
- stroke-dasharray: 4 3;
- }
-
- .ghost {
- fill: none;
- stroke: var(--border-strong);
- stroke-dasharray: 4 3;
- }
-
- .storeRim {
- fill: none;
- stroke: var(--mark-color);
- stroke-width: 1;
- }
-
- .icon {
- color: var(--mark-color);
- fill: none;
- }
-
- .nodeLabel {
- font-size: 13px;
- fill: var(--text-primary);
- }
-
- .sub {
- font-size: 11px;
- fill: var(--text-secondary);
- }
-
- .group {
- fill: none;
- stroke: var(--border-strong);
- stroke-dasharray: 4 4;
- }
-
- .groupLabel {
- @include halo;
- font-size: 11px;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- fill: var(--text-secondary);
- }
-
- .badge {
- @include mark-fill-svg;
- }
-
- .badgeLabel {
- font-size: 11px;
- fill: var(--text-primary);
- }
-
- .edge {
- fill: none;
- stroke: var(--text-secondary);
- stroke-width: 1.25;
- stroke-linejoin: round;
- }
-
- .connector {
- fill: none;
- stroke: var(--mark-color);
- stroke-width: 1.5;
- }
-
- .connectorEnd {
- fill: var(--mark-color);
- }
-
- .dashedLine {
- stroke-dasharray: 5 4;
- }
-
- .arrowHead {
- fill: var(--text-secondary);
- }
-
- .edgeLabel {
- @include halo;
- font-size: 11px;
- fill: var(--text-secondary);
- }
-
- .lifeline {
- stroke: var(--border-strong);
- stroke-dasharray: 2 4;
- }
-}
diff --git a/docs/components/frames/FrameShell/FrameShell.tsx b/docs/components/frames/FrameShell/FrameShell.tsx
deleted file mode 100644
index 258b9c0d..00000000
--- a/docs/components/frames/FrameShell/FrameShell.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import type * as React from "react";
-import type { ChartColor } from "@/lib/charts/schema";
-import styles from "./styles.module.scss";
-
-export interface LegendEntry {
- id: string;
- label: string;
- color: ChartColor;
- /** Draw a line swatch instead of a square. */
- line?: boolean;
- dashed?: boolean;
-}
-
-interface FrameShellProps {
- /** Frame-specific class for the figure; its nested rules style the drawing. */
- className?: string;
- /** data-* attributes for the figure, e.g. { "data-chart": id }. */
- data?: Record<`data-${string}`, string>;
- title: string;
- description: string;
- kicker?: string;
- subtitle?: string;
- caption?: string;
- legend?: LegendEntry[];
- note?: string;
- /**
- * "image" for drawings (SVG): screen readers get the description instead.
- * "text" for frames made of real text: they read it, after the description.
- */
- content?: "image" | "text";
- children: React.ReactNode;
-}
-
-const Title = ({ text }: { text: string }): React.ReactElement => (
- <div className={styles.title}>
- {text.split(/(\*[^*]+\*)/).map((part, i) =>
- part.startsWith("*") && part.endsWith("*") ? <em key={i}>{part.slice(1, -1)}</em> : part
- )}
- </div>
-);
-
-// A caption may credit its source with a markdown link: [DeepTeam](https://trydeepteam.com).
-const Caption = ({ text }: { text: string }): React.ReactElement => (
- <figcaption className={styles.caption}>
- {text.split(/(\[[^\]]+\]\([^)\s]+\))/).map((part, i) => {
- const link = part.match(/^\[([^\]]+)\]\(([^)\s]+)\)$/);
- if (!link) return part;
- const external = /^https?:\/\//.test(link[2]) && !/^https?:\/\/(www\.)?trydeepteam\.com(\/|$)/.test(link[2]);
- return (
- <a key={i} href={link[2]} {...(external ? { target: "_blank", rel: "noopener" } : {})}>
- {link[1]}
- </a>
- );
- })}
- </figcaption>
-);
-
-export const markColor = (name: ChartColor) => ({ "--mark-color": `var(--chart-${name})` }) as React.CSSProperties;
-
-const Legend = ({ entries, note }: { entries: LegendEntry[]; note?: string }): React.ReactElement | null => {
- if (!entries.length && !note) return null;
- return (
- <div className={styles.legend}>
- {entries.map(e => (
- <span key={e.id} className={styles.legendItem}>
- <span
- className={e.line ? styles.lineSwatch : styles.swatch}
- data-dashed={e.dashed || undefined}
- style={markColor(e.color)}
- />
- {e.label}
- </span>
- ))}
- {note ? <span className={styles.note}>{note}</span> : null}
- </div>
- );
-};
-
-/** The figure every frame shares: head, drawing, legend and caption. */
-const FrameShell: React.FC<FrameShellProps> = ({
- className,
- data,
- title,
- description,
- kicker,
- subtitle,
- caption,
- legend = [],
- note,
- content = "image",
- children,
-}) => (
- <figure className={className ? `${styles.frame} ${className}` : styles.frame} {...data}>
- <div className={styles.head}>
- {kicker ? <div className={styles.kicker}>{kicker}</div> : null}
- <Title text={title} />
- {subtitle ? <div className={styles.subtitle}>{subtitle}</div> : null}
- </div>
- {content === "image" ? (
- <div className={styles.drawing} role="img" aria-label={description} tabIndex={0}>
- {children}
- </div>
- ) : (
- <div className={styles.drawing}>
- <p className={styles.srOnly}>{description}</p>
- {children}
- </div>
- )}
- <Legend entries={legend} note={note} />
- {caption ? <Caption text={caption} /> : null}
- </figure>
-);
-
-export default FrameShell;
diff --git a/docs/components/frames/FrameShell/_frame.scss b/docs/components/frames/FrameShell/_frame.scss
deleted file mode 100644
index a352c9d0..00000000
--- a/docs/components/frames/FrameShell/_frame.scss
+++ /dev/null
@@ -1,72 +0,0 @@
-// Shared by ChartFrame, TranscriptFrame, SchemaFrame and FlowFrame so every
-// frame draws with the same palette, type scale and marks. FrameShell defines
-// the --chart-* colors on the figure; frames only pick one with --mark-color.
-
-@mixin frame-colors {
- --chart-violet: color-mix(in srgb, var(--accent-label-violet) 72%, var(--text-primary));
- --chart-ember: color-mix(in srgb, var(--accent-label-ember) 80%, var(--text-primary));
- --chart-blue: color-mix(in srgb, var(--accent-label-blue) 80%, var(--text-primary));
- --chart-teal: color-mix(in srgb, var(--accent-label-teal) 70%, var(--text-primary));
- --chart-pink: color-mix(in srgb, var(--accent-label-pink) 80%, var(--text-primary));
- --chart-yellow: color-mix(in srgb, var(--accent-label-yellow) 65%, var(--text-primary));
- --chart-muted: var(--text-secondary);
- --chart-ink: var(--text-primary);
-}
-
-// A tinted box in the mark's color, as a chart bar draws it: 20% fill over the
-// frame background (solid, so lines behind it stay hidden) and a 1px outline.
-@mixin mark-fill {
- background-color: color-mix(in srgb, var(--mark-color) 20%, var(--bg-secondary));
- border: 1px solid var(--mark-color);
-}
-
-@mixin mark-fill-svg {
- fill: color-mix(in srgb, var(--mark-color) 20%, var(--bg-secondary));
- stroke: var(--mark-color);
- stroke-width: 1;
-}
-
-// Label sizes: 13px for content, 11px for small print, 12px uppercase for kickers.
-@mixin label {
- font-size: 13px;
- line-height: 1.45;
- color: var(--text-primary);
-}
-
-@mixin small {
- font-size: 11px;
- line-height: 1.4;
- color: var(--text-secondary);
-}
-
-@mixin kicker {
- font-size: 11px;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-secondary);
-}
-
-// Text over lines in an SVG, as chart threshold labels draw it.
-@mixin halo {
- stroke: var(--bg-secondary);
- stroke-width: 3.5;
- stroke-linejoin: round;
- paint-order: stroke;
-}
-
-// Frames that draw a wide and a narrow SVG show one per container width.
-@mixin wide-narrow {
- .wide {
- @container (max-width: 520px) {
- display: none;
- }
- }
-
- .narrow {
- display: none;
-
- @container (max-width: 520px) {
- display: block;
- }
- }
-}
diff --git a/docs/components/frames/FrameShell/_markdown.ts b/docs/components/frames/FrameShell/_markdown.ts
deleted file mode 100644
index 4dcf27fe..00000000
--- a/docs/components/frames/FrameShell/_markdown.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/** The markdown every frame exports: its head, the description, its data, then note and caption. */
-export const frameMarkdown = (attrs: Record<string, string>, body: string): string => {
- const title = attrs.title.replace(/\*([^*]+)\*/g, "$1");
- return [
- `**${attrs.kicker ? `${attrs.kicker}: ` : ""}${title}**`,
- attrs.description ?? "",
- body,
- attrs.note ? `*${attrs.note}*` : "",
- attrs.caption ? `*${attrs.caption}*` : "",
- ]
- .filter(Boolean)
- .join("\n\n");
-};
diff --git a/docs/components/frames/FrameShell/styles.module.scss b/docs/components/frames/FrameShell/styles.module.scss
deleted file mode 100644
index 122585b7..00000000
--- a/docs/components/frames/FrameShell/styles.module.scss
+++ /dev/null
@@ -1,127 +0,0 @@
-@import "../vars";
-@import "./frame";
-
-.frame.frame {
- @include site-tokens;
- @include frame-colors;
-
- container-type: inline-size;
- width: 100%;
- margin: var(--media-frame-margin, 0 0 20px);
- padding: 16px 24px;
- border: 1px solid var(--border-subtle);
- background-color: var(--bg-secondary);
-
- @include responsive(xs) {
- padding: 14px 16px;
- }
-
- .head {
- display: flex;
- flex-direction: column;
- gap: 4px;
- margin-bottom: 8px;
- }
-
- .kicker {
- font-size: 12px;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-secondary);
- }
-
- .title {
- font-size: 20px;
- font-weight: $FONT_MEDIUM;
- line-height: 1.2;
- color: var(--text-primary);
-
- em {
- font-style: normal;
- color: var(--chart-violet);
- }
- }
-
- .subtitle {
- font-size: 15px;
- line-height: 1.5;
- color: var(--text-secondary);
- }
-
- .drawing {
- margin: 0;
- overflow-x: auto;
-
- &:focus-visible {
- outline: 2px solid var(--chart-violet);
- outline-offset: 2px;
- }
- }
-
- .srOnly {
- position: absolute;
- width: 1px;
- height: 1px;
- overflow: hidden;
- clip-path: inset(50%);
- white-space: nowrap;
- }
-
- .legend {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 6px 16px;
- margin-top: 8px;
- padding-top: 10px;
- border-top: 1px solid var(--border-subtle);
- font-size: 12px;
- color: var(--text-primary);
- }
-
- .legendItem {
- max-width: 100%;
- min-width: 0;
- overflow-wrap: anywhere;
- display: inline-flex;
- align-items: center;
- gap: 8px;
- }
-
- .swatch,
- .lineSwatch {
- flex-shrink: 0;
- }
-
- .swatch {
- width: 9px;
- height: 9px;
- background-color: var(--mark-color);
- }
-
- .lineSwatch {
- width: 14px;
- border-top: 2px solid var(--mark-color);
-
- &[data-dashed] {
- border-top-style: dashed;
- }
- }
-
- .note {
- flex-basis: 100%;
- min-width: 0;
- overflow-wrap: anywhere;
- line-height: 1.4;
- font-size: 11px;
- color: var(--text-secondary);
- }
-
- .caption.caption {
- margin: 10px 0 0;
- font-size: 14px;
- line-height: 1.5;
- text-align: center;
- color: var(--text-secondary);
- }
-}
diff --git a/docs/components/frames/SchemaFrame/SchemaFrame.tsx b/docs/components/frames/SchemaFrame/SchemaFrame.tsx
deleted file mode 100644
index 03da7f37..00000000
--- a/docs/components/frames/SchemaFrame/SchemaFrame.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import type * as React from "react";
-import FlowPlot from "@/components/frames/FlowPlot/FlowPlot";
-import { MIN_SCALE } from "@/components/frames/FlowPlot/_scene";
-import FrameShell from "@/components/frames/FrameShell/FrameShell";
-import { SCHEMA_KIND } from "@/lib/frames/kinds";
-import type { SchemaCardData, SchemaType } from "@/lib/frames/schema-card";
-import { layoutSchema } from "./_layout";
-
-interface SchemaFrameProps {
- id: string;
- schema?: SchemaCardData;
-
- type: string;
- title: string;
-
- description: string;
- kicker?: string;
- subtitle?: string;
- note?: string;
- caption?: string;
-}
-
-const SchemaFrame: React.FC<SchemaFrameProps> = ({ id, schema, type, title, description, kicker, subtitle, note, caption }) => {
- const problems = !schema
- ? ["unknown or invalid data"]
- : !SCHEMA_KIND.types.includes(type)
- ? [`unknown type "${type}"`]
- : SCHEMA_KIND.typeProblems(type, schema);
- if (!schema || problems.length) {
- console.warn(`[SchemaFrame] Can't draw "${id}" as "${type}": ${problems.join("; ")}. Run yarn check:content for details.`);
- return null;
- }
- return (
- <FrameShell
- data={{ "data-schema": id, "data-schema-type": type }}
- title={title}
- description={description}
- kicker={kicker}
- subtitle={subtitle}
- caption={caption}
- note={note}
- >
- <FlowPlot scene={layoutSchema(type as SchemaType, schema, "wide")} id={`schema-${id}`} variant="wide" minScale={MIN_SCALE.wide} />
- <FlowPlot scene={layoutSchema(type as SchemaType, schema, "narrow")} id={`schema-${id}`} variant="narrow" minScale={MIN_SCALE.narrow} />
- </FrameShell>
- );
-};
-
-/** Bind MDX to this article's schemas.json; authors only supply the local ID. */
-export const createSchemaFrame = (data: Record<string, SchemaCardData>) =>
- function ArticleSchemaFrame(props: Omit<SchemaFrameProps, "schema">) {
- return <SchemaFrame {...props} schema={Object.hasOwn(data, props.id) ? data[props.id] : undefined} />;
- };
-
-export default SchemaFrame;
diff --git a/docs/components/frames/SchemaFrame/_layout.ts b/docs/components/frames/SchemaFrame/_layout.ts
deleted file mode 100644
index 0a5a778c..00000000
--- a/docs/components/frames/SchemaFrame/_layout.ts
+++ /dev/null
@@ -1,204 +0,0 @@
-import {
- blockHeight,
- type FlowScene,
- GROUP_HEAD,
- GROUP_PAD,
- groupHeaderWidth,
- iconRoom,
- LINE,
- normalize,
- PAD_X,
- PAD_Y,
- type SceneEdge,
- type SceneGroup,
- type SceneNode,
- sCurve,
- SMALL,
- smoothPath,
- textWidth,
- wrapWords,
-} from "@/components/frames/FlowPlot/_scene";
-import { fieldRefOf, type SchemaCardData, type SchemaField, type SchemaObject, type SchemaType } from "@/lib/frames/schema-card";
-
-// SchemaFrame draws objects as containers of field chips, in FlowFrame's
-// visual language: chips are nodes, objects are groups, links are edges.
-
-export type Variant = "wide" | "narrow";
-
-const CHIP_GAP = 8;
-const SPACING = {
- wide: { wrap: 190, highlight: 64, columns: 40, link: 96 },
- narrow: { wrap: 150, highlight: 36, columns: 24, link: 44 },
-};
-
-interface Chip {
- field: SchemaField;
- lines: string[];
- sub: string[];
- textW: number;
- h: number;
-}
-
-/** A field as a chip: its name (with `?` when optional) and its example or note under it. */
-const chipFor = (field: SchemaField, wrap: number): Chip => {
- const lines = wrapWords(field.optional ? `${field.name}?` : field.name, wrap);
- const sub = [
- ...(field.example ? wrapWords(`“${field.example}”`, wrap, SMALL) : []),
- ...(field.note ? wrapWords(field.note, wrap, SMALL) : []),
- ];
- const textW = Math.max(...lines.map(l => textWidth(l)), ...sub.map(l => textWidth(l, SMALL)));
- return { field, lines, sub, textW, h: blockHeight(lines.length, sub.length) + PAD_Y * 2 };
-};
-
-const badgeOf = (object: SchemaObject) =>
- object.subtitle ? { text: object.subtitle, w: textWidth(object.subtitle, SMALL) + 14, color: object.color } : undefined;
-
-/** Narrowest container that fits its chips and its header. */
-const columnWidth = (objects: SchemaObject[], chips: Chip[]) => {
- const header = Math.max(...objects.map(o => groupHeaderWidth(o.title, badgeOf(o)?.w)));
- return Math.max(150, ...chips.map(c => c.textW + PAD_X * 2 + GROUP_PAD * 2), header);
-};
-
-/**
- * One object's container at (x, y), with a chip (or an empty slot, for null) per
- * row. Rows share heights across columns so fields line up side by side.
- */
-const column = (object: SchemaObject, rows: (Chip | null)[], heights: number[], x: number, y: number, w: number) => {
- const nodes: SceneNode[] = [];
- let top = y + GROUP_HEAD + 6;
- rows.forEach((chip, i) => {
- const box = { x: x + GROUP_PAD, y: top, w: w - GROUP_PAD * 2, h: heights[i] };
- nodes.push(
- chip
- ? { ...box, id: fieldRefOf(object, chip.field), lines: chip.lines, sub: chip.sub, color: object.color, shape: "box", dashed: chip.field.optional }
- : { ...box, id: `${object.id}.empty-${i}`, lines: [], color: "muted", shape: "box", ghost: true }
- );
- top += heights[i] + CHIP_GAP;
- });
- const group: SceneGroup = { id: object.id, label: object.title, badge: badgeOf(object), x, y, w, h: top - CHIP_GAP + GROUP_PAD - y };
- return { nodes, group };
-};
-
-/** One object, with each highlight as a box joined to the fields it reads. */
-const card = (data: SchemaCardData, variant: Variant): FlowScene => {
- const s = SPACING[variant];
- const object = data.objects[0];
- const chips = object.fields.map(f => chipFor(f, s.wrap));
- const w = columnWidth([object], chips);
- const { nodes, group } = column(object, chips, chips.map(c => c.h), 0, 0, w);
- const byRef = new Map(nodes.map(n => [n.id, n]));
-
- // Wide drawings alternate highlights left and right; narrow ones keep them on the left.
- const boxes = data.highlights.map((h, i) => {
- const side = variant === "wide" && i % 2 === 1 ? "right" : "left";
- const lines = wrapWords(h.label, variant === "wide" ? 140 : 110);
- const width = Math.max(...lines.map(l => textWidth(l))) + iconRoom("gauge") + PAD_X * 2;
- const height = lines.length * LINE + PAD_Y * 2;
- const targets = h.fields.map(ref => byRef.get(ref)!);
- const center = targets.reduce((sum, t) => sum + t.y + t.h / 2, 0) / targets.length;
- return { h, side, lines, width, height, targets, center, y: 0 };
- });
- for (const side of ["left", "right"]) {
- let floor = -Infinity;
- for (const b of boxes.filter(x => x.side === side).sort((p, q) => p.center - q.center)) {
- b.y = Math.max(b.center - b.height / 2, floor);
- floor = b.y + b.height + 12;
- }
- }
-
- const highlightNodes: SceneNode[] = boxes.map((b, i) => ({
- id: `highlight-${i}`,
- x: b.side === "left" ? group.x - s.highlight - b.width : group.x + group.w + s.highlight,
- y: b.y,
- w: b.width,
- h: b.height,
- lines: b.lines,
- color: b.h.color,
- shape: "box",
- icon: "gauge",
- }));
-
- // Lines from each highlight to its fields; where two arrive at one chip side, they spread apart.
- const arrivals = new Map<string, number>();
- const counts = new Map<string, number>();
- for (const b of boxes) for (const t of b.targets) counts.set(`${t.id}:${b.side}`, (counts.get(`${t.id}:${b.side}`) ?? 0) + 1);
- const edges: SceneEdge[] = boxes.flatMap((b, i) => {
- const box = highlightNodes[i];
- const start = { x: b.side === "left" ? box.x + box.w : box.x, y: box.y + box.h / 2 };
- return b.targets.map(t => {
- const key = `${t.id}:${b.side}`;
- const k = arrivals.get(key) ?? 0;
- arrivals.set(key, k + 1);
- const spread = (k - ((counts.get(key) ?? 1) - 1) / 2) * 8;
- const end = { x: b.side === "left" ? t.x : t.x + t.w, y: t.y + t.h / 2 + spread };
- return { d: sCurve(start, end), dashed: false, both: false, color: b.h.color };
- });
- });
-
- return normalize({ width: 0, height: 0, nodes: [...nodes, ...highlightNodes], groups: [group], edges, lifelines: [] });
-};
-
-/** Objects side by side with one row per field name, so a field one lacks shows as an empty slot. */
-const compare = (data: SchemaCardData, variant: Variant): FlowScene => {
- const s = SPACING[variant];
- const wrap = variant === "narrow" ? s.wrap : data.objects.length > 2 ? 140 : s.wrap;
- const chipsOf = data.objects.map(o => o.fields.map(f => chipFor(f, wrap)));
- const w = columnWidth(data.objects, chipsOf.flat());
- const nodes: SceneNode[] = [];
- const groups: SceneGroup[] = [];
-
- if (variant === "narrow") {
- // Stacked, so each object lists only its own fields.
- let y = 0;
- data.objects.forEach((o, i) => {
- const col = column(o, chipsOf[i], chipsOf[i].map(c => c.h), 0, y, w);
- nodes.push(...col.nodes);
- groups.push(col.group);
- y += col.group.h + 16;
- });
- } else {
- const names = [...new Set(data.objects.flatMap(o => o.fields.map(f => f.name)))];
- const rows = chipsOf.map(chips => names.map(name => chips.find(c => c.field.name === name) ?? null));
- const heights = names.map((_, r) => Math.max(...rows.map(row => row[r]?.h ?? 0)));
- data.objects.forEach((o, i) => {
- const col = column(o, rows[i], heights, i * (w + s.columns), 0, w);
- nodes.push(...col.nodes);
- groups.push(col.group);
- });
- }
- return normalize({ width: 0, height: 0, nodes, groups, edges: [], lifelines: [] });
-};
-
-/** Two objects, rows aligned by link, with an arrow per link. */
-const match = (data: SchemaCardData, variant: Variant): FlowScene => {
- const s = SPACING[variant];
- const wrap = variant === "wide" ? 170 : 100;
- const [left, right] = data.objects;
- const chip = (object: SchemaObject, ref: string) => {
- const field = object.fields.find(f => fieldRefOf(object, f) === ref);
- return field ? chipFor(field, wrap) : null;
- };
- const linkedLeft = new Set(data.links.map(l => l.from));
- const linkedRight = new Set(data.links.map(l => l.to));
- const rows: [Chip | null, Chip | null][] = [
- ...data.links.map(l => [chip(left, l.from), chip(right, l.to)] as [Chip | null, Chip | null]),
- ...left.fields.filter(f => !linkedLeft.has(fieldRefOf(left, f))).map(f => [chipFor(f, wrap), null] as [Chip, null]),
- ...right.fields.filter(f => !linkedRight.has(fieldRefOf(right, f))).map(f => [null, chipFor(f, wrap)] as [null, Chip]),
- ];
- const heights = rows.map(([a, b]) => Math.max(a?.h ?? 0, b?.h ?? 0));
- const w = columnWidth([left, right], rows.flat().filter((c): c is Chip => c !== null));
- const l = column(left, rows.map(r => r[0]), heights, 0, 0, w);
- const r = column(right, rows.map(row => row[1]), heights, w + s.link, 0, w);
- const edges: SceneEdge[] = rows.flatMap(([a, b], i) => {
- if (!a || !b) return [];
- const from = l.nodes[i];
- const to = r.nodes[i];
- const y = from.y + from.h / 2;
- return [{ d: smoothPath([{ x: from.x + from.w, y }, { x: to.x, y }]), dashed: false, both: false }];
- });
- return normalize({ width: 0, height: 0, nodes: [...l.nodes, ...r.nodes], groups: [l.group, r.group], edges, lifelines: [] });
-};
-
-const LAYOUTS: Record<SchemaType, (data: SchemaCardData, variant: Variant) => FlowScene> = { card, compare, match };
-
-export const layoutSchema = (type: SchemaType, data: SchemaCardData, variant: Variant): FlowScene => LAYOUTS[type](data, variant);
diff --git a/docs/components/frames/TranscriptFrame/TranscriptFrame.tsx b/docs/components/frames/TranscriptFrame/TranscriptFrame.tsx
deleted file mode 100644
index 86d94dae..00000000
--- a/docs/components/frames/TranscriptFrame/TranscriptFrame.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import type * as React from "react";
-import { Check, X } from "lucide-react";
-import FrameShell, { markColor } from "@/components/frames/FrameShell/FrameShell";
-import type { ChartColor } from "@/lib/charts/schema";
-import { TRANSCRIPT_KIND } from "@/lib/frames/kinds";
-import { roleLabel, type TranscriptData, type TranscriptTurn } from "@/lib/frames/transcript";
-import { renderHighlights } from "./_text";
-import styles from "./styles.module.scss";
-
-interface TranscriptFrameProps {
- id: string;
- transcript?: TranscriptData;
-
- type: string;
- title: string;
-
- description: string;
- kicker?: string;
- subtitle?: string;
- note?: string;
- caption?: string;
-}
-
-const ROLE_COLORS: Record<TranscriptTurn["role"], ChartColor> = {
- user: "teal",
- assistant: "violet",
- system: "muted",
- tool: "ember",
-};
-
-const Verdict = ({ verdict }: { verdict?: "pass" | "fail" }): React.ReactElement | null =>
- verdict ? (
- <span
- className={styles.verdict}
- style={markColor(verdict === "pass" ? "teal" : "pink")}
- aria-label={verdict === "pass" ? "kept" : "rejected"}
- >
- {verdict === "pass" ? <Check size={11} strokeWidth={3} /> : <X size={11} strokeWidth={3} />}
- </span>
- ) : null;
-
-const Turn = ({ turn, speaker, tag }: { turn: TranscriptTurn; speaker?: string; tag?: string }): React.ReactElement => (
- <div className={styles.turn} style={markColor(ROLE_COLORS[turn.role])} data-role={turn.role}>
- <div className={styles.turnHead}>
- <span className={styles.role}>{roleLabel(turn, speaker)}</span>
- {tag ? <span className={styles.inlineTag}>{tag}</span> : null}
- <Verdict verdict={turn.verdict} />
- </div>
- <div className={styles.text}>{renderHighlights(turn.text, styles.highlight)}</div>
- </div>
-);
-
-/** A mock playground: each prompt in a field, each reply in an output panel. */
-const Chat = ({ data }: { data: TranscriptData }): React.ReactElement => (
- <div className={styles.chat}>
- {data.turns.map((turn, i) => (
- <div key={i} className={turn.role === "user" ? styles.prompt : styles.reply} data-role={turn.role}>
- <div className={styles.turnHead}>
- <span className={styles.role}>{turn.role === "user" ? (turn.name ?? "Prompt") : roleLabel(turn, data.speaker)}</span>
- <Verdict verdict={turn.verdict} />
- </div>
- <div className={styles.text}>{renderHighlights(turn.text, styles.highlight)}</div>
- </div>
- ))}
- </div>
-);
-
-/** Turns stacked in order, with brackets over ranges and pointers at single turns. */
-const Turns = ({ data }: { data: TranscriptData }): React.ReactElement => {
- const pointerAt = new Map(data.pointers.map(p => [p.turn, p.label]));
- return (
- <div className={styles.turns} style={{ gridTemplateRows: `repeat(${data.turns.length}, auto)` }}>
- {data.ranges.map((r, i) => (
- <div key={`r${i}`} className={styles.range} style={{ gridRow: `${r.from + 1} / ${r.to + 2}` }}>
- <span className={styles.rangeLabel}>{r.label}</span>
- <span className={styles.bracket} aria-hidden="true" />
- </div>
- ))}
- {data.turns.map((turn, i) => (
- <div key={`t${i}`} className={styles.turnCell} style={{ gridRow: i + 1 }}>
- <Turn turn={turn} speaker={data.speaker} tag={pointerAt.get(i)} />
- </div>
- ))}
- {data.pointers.map((p, i) => (
- <div key={`p${i}`} className={styles.pointer} style={{ gridRow: p.turn + 1 }}>
- <span className={styles.pointerArrow} aria-hidden="true" />
- {p.label}
- </div>
- ))}
- </div>
- );
-};
-
-const Conversation = ({ turns, speaker, title }: { turns: TranscriptTurn[]; speaker?: string; title?: string }): React.ReactElement => (
- <div className={styles.conversation}>
- {title ? <div className={styles.panelTitle}>{title}</div> : null}
- {turns.map((turn, i) => (
- <div key={i} className={styles.line}>
- <span className={styles.lineRole} style={markColor(ROLE_COLORS[turn.role])}>
- {roleLabel(turn, speaker)}
- </span>
- <span className={styles.text}>{renderHighlights(turn.text, styles.highlight)}</span>
- </div>
- ))}
- </div>
-);
-
-/** Conversation (or candidate panels) → judge prompt → verdict. */
-const Judge = ({ data }: { data: TranscriptData }): React.ReactElement => {
- const judge = data.judge!;
- return (
- <div className={styles.judge}>
- <div className={styles.judgeInput}>
- {data.turns.length ? <Conversation turns={data.turns} speaker={data.speaker} /> : null}
- {data.panels.map((panel, i) => (
- <Conversation key={i} turns={panel.turns} speaker={data.speaker} title={panel.title} />
- ))}
- </div>
- <span className={styles.flowArrow} aria-hidden="true" />
- <div className={styles.judgeBox} style={markColor("yellow")}>
- <div className={styles.role}>{judge.label}</div>
- <div className={styles.text}>“{judge.prompt}”</div>
- </div>
- <span className={styles.flowArrow} aria-hidden="true" />
- <div className={styles.verdictBox}>
- <div className={styles.role}>{judge.verdictLabel}</div>
- <div className={styles.score} style={markColor("teal")}>
- {judge.verdict}
- </div>
- </div>
- </div>
- );
-};
-
-/** Panels side by side, each a titled column of turns. */
-const Compare = ({ data }: { data: TranscriptData }): React.ReactElement => (
- <div className={styles.compare}>
- {data.panels.map((panel, i) => (
- <div key={i} className={styles.panel}>
- <div className={styles.panelTitle}>{panel.title}</div>
- {panel.turns.map((turn, j) => (
- <Turn key={j} turn={turn} speaker={data.speaker} />
- ))}
- </div>
- ))}
- </div>
-);
-
-const BODIES: Record<string, React.FC<{ data: TranscriptData }>> = { chat: Chat, turns: Turns, judge: Judge, compare: Compare };
-
-const TranscriptFrame: React.FC<TranscriptFrameProps> = ({ id, transcript, type, title, description, kicker, subtitle, note, caption }) => {
- const problems = !transcript
- ? ["unknown or invalid data"]
- : !TRANSCRIPT_KIND.types.includes(type)
- ? [`unknown type "${type}"`]
- : TRANSCRIPT_KIND.typeProblems(type, transcript);
- if (!transcript || problems.length) {
- console.warn(`[TranscriptFrame] Can't draw "${id}" as "${type}": ${problems.join("; ")}. Run yarn check:content for details.`);
- return null;
- }
- const Body = BODIES[type];
- return (
- <FrameShell
- className={styles.frame}
- data={{ "data-transcript": id, "data-transcript-type": type }}
- title={title}
- description={description}
- kicker={kicker}
- subtitle={subtitle}
- caption={caption}
- note={note}
- content="text"
- >
- <Body data={transcript} />
- </FrameShell>
- );
-};
-
-/** Bind MDX to this article's transcripts.json; authors only supply the local ID. */
-export const createTranscriptFrame = (data: Record<string, TranscriptData>) =>
- function ArticleTranscriptFrame(props: Omit<TranscriptFrameProps, "transcript">) {
- return <TranscriptFrame {...props} transcript={Object.hasOwn(data, props.id) ? data[props.id] : undefined} />;
- };
-
-export default TranscriptFrame;
diff --git a/docs/components/frames/TranscriptFrame/_text.tsx b/docs/components/frames/TranscriptFrame/_text.tsx
deleted file mode 100644
index d85f968b..00000000
--- a/docs/components/frames/TranscriptFrame/_text.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import type * as React from "react";
-
-/**
- * Turn text with ==highlighted== spans (markdown's highlight syntax, so
- * asterisks in quoted prompts such as "*****" stay literal).
- */
-export const highlightParts = (text: string): { text: string; highlight: boolean }[] =>
- text
- .split(/(==[^=]+==)/)
- .filter(Boolean)
- .map(part =>
- part.startsWith("==") && part.endsWith("==") && part.length > 4
- ? { text: part.slice(2, -2), highlight: true }
- : { text: part, highlight: false }
- );
-
-export const plainText = (text: string) => highlightParts(text).map(p => p.text).join("");
-
-export const renderHighlights = (text: string, className: string): React.ReactNode =>
- highlightParts(text).map((part, i) =>
- part.highlight ? (
- <mark key={i} className={className}>
- {part.text}
- </mark>
- ) : (
- part.text
- )
- );
diff --git a/docs/components/frames/TranscriptFrame/styles.module.scss b/docs/components/frames/TranscriptFrame/styles.module.scss
deleted file mode 100644
index d7512552..00000000
--- a/docs/components/frames/TranscriptFrame/styles.module.scss
+++ /dev/null
@@ -1,293 +0,0 @@
-@import "../vars";
-@import "../FrameShell/frame";
-
-.frame.frame {
- .text {
- @include label;
- min-width: 0;
- overflow-wrap: anywhere;
- white-space: pre-line;
- }
-
- .highlight {
- background: none;
- font-weight: $FONT_MEDIUM;
- color: var(--chart-pink);
- }
-
- .role {
- @include kicker;
- }
-
- .turnHead {
- display: flex;
- align-items: center;
- gap: 8px;
- min-width: 0;
- }
-
- .verdict {
- @include mark-fill;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 18px;
- height: 18px;
- margin-left: auto;
- flex-shrink: 0;
- color: var(--mark-color);
- }
-
- .turn {
- @include mark-fill;
- display: flex;
- flex-direction: column;
- gap: 2px;
- padding: 8px 12px;
- min-width: 0;
- }
-
- .inlineTag {
- display: none;
- @include small;
- color: var(--mark-color);
- }
-
- .panelTitle {
- font-size: 13px;
- font-weight: $FONT_MEDIUM;
- color: var(--text-primary);
- }
-
- // chat: a mock playground.
- .chat {
- display: flex;
- flex-direction: column;
- gap: 10px;
- padding: 4px 0;
- }
-
- .prompt,
- .reply {
- display: flex;
- flex-direction: column;
- gap: 6px;
- padding: 10px 12px;
- border: 1px solid var(--border-subtle);
- }
-
- .prompt {
- background-color: var(--bg-primary);
- }
-
- .reply {
- --mark-color: var(--chart-violet);
- @include mark-fill;
- border-left-width: 3px;
- }
-
- .reply[data-role="tool"] {
- --mark-color: var(--chart-ember);
- }
-
- .reply[data-role="system"] {
- --mark-color: var(--chart-muted);
- }
-
- // turns: a stack with ranges on the left and pointers on the right.
- .turns {
- display: grid;
- grid-template-columns: minmax(80px, 0.7fr) minmax(0, 2fr) minmax(80px, 0.8fr);
- column-gap: 12px;
- row-gap: 6px;
- padding: 4px 0;
- }
-
- .range {
- grid-column: 1;
- display: flex;
- align-items: center;
- justify-content: flex-end;
- gap: 8px;
- min-width: 0;
- }
-
- .rangeLabel {
- @include small;
- min-width: 0;
- text-align: right;
- overflow-wrap: anywhere;
- }
-
- .bracket {
- align-self: stretch;
- width: 8px;
- flex-shrink: 0;
- border: 1px solid var(--text-secondary);
- border-right: 0;
- }
-
- .turnCell {
- grid-column: 2;
- min-width: 0;
- }
-
- .pointer {
- grid-column: 3;
- display: flex;
- align-items: center;
- gap: 8px;
- @include small;
- }
-
- .pointerArrow {
- flex-shrink: 0;
- width: 18px;
- height: 1px;
- background: var(--text-secondary);
- position: relative;
-
- &::before {
- content: "";
- position: absolute;
- left: 0;
- top: -3px;
- border: 3.5px solid transparent;
- border-right: 6px solid var(--text-secondary);
- border-left: 0;
- }
- }
-
- @container (max-width: 520px) {
- .turns {
- grid-template-columns: 76px minmax(0, 1fr);
- column-gap: 8px;
- }
-
- .pointer {
- display: none;
- }
-
- .inlineTag {
- display: inline;
- }
- }
-
- // judge: input → judge prompt → verdict.
- .judge {
- display: grid;
- grid-template-columns: minmax(0, 1.3fr) 24px minmax(0, 1.2fr) 24px auto;
- align-items: center;
- gap: 8px;
- padding: 4px 0;
- }
-
- .judgeInput {
- display: flex;
- flex-direction: column;
- gap: 10px;
- min-width: 0;
- }
-
- .conversation {
- display: flex;
- flex-direction: column;
- gap: 6px;
- padding: 10px 12px;
- border: 1px dashed var(--border-strong);
- }
-
- .line {
- display: grid;
- grid-template-columns: auto minmax(0, 1fr);
- gap: 8px;
- align-items: baseline;
- }
-
- .lineRole {
- @include kicker;
- color: var(--mark-color);
- }
-
- .judgeBox {
- @include mark-fill;
- display: flex;
- flex-direction: column;
- gap: 4px;
- padding: 10px 12px;
- }
-
- .verdictBox {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- }
-
- .score {
- @include mark-fill;
- display: flex;
- align-items: center;
- justify-content: center;
- min-width: 48px;
- height: 48px;
- padding: 0 10px;
- border-radius: 999px;
- font-size: 15px;
- font-weight: $FONT_MEDIUM;
- color: var(--text-primary);
- }
-
- .flowArrow {
- position: relative;
- height: 1px;
- background: var(--text-secondary);
-
- &::after {
- content: "";
- position: absolute;
- right: 0;
- top: -3px;
- border: 3.5px solid transparent;
- border-left: 6px solid var(--text-secondary);
- border-right: 0;
- }
- }
-
- @container (max-width: 520px) {
- .judge {
- grid-template-columns: minmax(0, 1fr);
- justify-items: stretch;
- }
-
- .flowArrow {
- justify-self: center;
- width: 1px;
- height: 18px;
-
- &::after {
- right: -3px;
- top: auto;
- bottom: 0;
- border: 3.5px solid transparent;
- border-top: 6px solid var(--text-secondary);
- border-bottom: 0;
- }
- }
- }
-
- // compare: panels side by side.
- .compare {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
- gap: 16px;
- padding: 4px 0;
- }
-
- .panel {
- display: flex;
- flex-direction: column;
- gap: 8px;
- min-width: 0;
- }
-}
diff --git a/docs/components/frames/_vars.scss b/docs/components/frames/_vars.scss
deleted file mode 100644
index edd40b7b..00000000
--- a/docs/components/frames/_vars.scss
+++ /dev/null
@@ -1,35 +0,0 @@
-$FONT_REGULAR: 400;
-$FONT_MEDIUM: 500;
-$FONT_SEMIBOLD: 600;
-$DM_MONO: ui-monospace, SFMono-Regular, Menlo, monospace;
-
-$custom-breakpoints: (
- xs: (minSize: 0px, maxSize: 479px),
- sm: (minSize: 480px, maxSize: 767px),
- md: (minSize: 768px, maxSize: 991px),
- lg: (minSize: 992px, maxSize: 1439px),
-);
-
-@mixin responsive($breakpoint) {
- @media (max-width: #{map-get(map-get($custom-breakpoints, $breakpoint), maxSize)}) {
- @content;
- }
-}
-
-// The colors frames draw with, taken from the docs theme.
-@mixin site-tokens {
- --text-primary: var(--color-fd-foreground);
- --text-secondary: var(--color-fd-muted-foreground);
- --bg-primary: var(--color-fd-background);
- --bg-secondary: var(--color-fd-card);
- --bg-card: var(--color-fd-background);
- --border-subtle: var(--color-fd-border);
- --border-strong: color-mix(in srgb, var(--color-fd-foreground) 25%, var(--color-fd-border));
- --accent-label-yellow: rgb(232, 255, 1);
- --accent-label-blue: rgb(0, 157, 255);
- --accent-label-teal: rgb(0, 255, 200);
- --accent-label-ember: rgb(255, 65, 1);
- --accent-label-violet: #6200ff;
- --accent-label-pink: rgb(231, 0, 116);
- --accent-label-muted: var(--text-secondary);
-}
diff --git a/docs/components/frames/index.tsx b/docs/components/frames/index.tsx
deleted file mode 100644
index 83fa4f58..00000000
--- a/docs/components/frames/index.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { createBoardFrame } from "@/components/frames/BoardFrame/BoardFrame";
-import { createChartFrame } from "@/components/frames/ChartFrame/ChartFrame";
-import { createChatFrame } from "@/components/frames/ChatFrame/ChatFrame";
-import { createFlowFrame } from "@/components/frames/FlowFrame/FlowFrame";
-import { createSchemaFrame } from "@/components/frames/SchemaFrame/SchemaFrame";
-import { createTranscriptFrame } from "@/components/frames/TranscriptFrame/TranscriptFrame";
-import { EMPTY_FRAME_DATA, type FrameData } from "@/lib/frames/store";
-
-/** Every frame component, bound to one content file's frame data (loadFrameData). */
-export const createFrameComponents = (data: FrameData = EMPTY_FRAME_DATA) => ({
- ChartFrame: createChartFrame(data.charts),
- TranscriptFrame: createTranscriptFrame(data.transcripts),
- SchemaFrame: createSchemaFrame(data.schemas),
- FlowFrame: createFlowFrame(data.flows),
- BoardFrame: createBoardFrame(data.boards),
- ChatFrame: createChatFrame(data.chats),
-});
diff --git a/docs/lib/charts/analysis.ts b/docs/lib/charts/analysis.ts
deleted file mode 100644
index c374afe9..00000000
--- a/docs/lib/charts/analysis.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import type { Fn } from "./expression";
-
-export const safe = (f: Fn, x: number): number => {
- try {
- const v = f(x);
- return typeof v === "number" ? v : NaN;
- } catch {
- return NaN;
- }
-};
-
-const sample = (f: Fn, a: number, b: number, n: number) => {
- const xs: number[] = [];
- const ys: number[] = [];
- for (let i = 0; i <= n; i++) {
- const x = a + ((b - a) * i) / n;
- xs.push(x);
- ys.push(safe(f, x));
- }
- return { xs, ys };
-};
-
-const dedupe = (values: number[], tolerance: number) => {
- const out: number[] = [];
- for (const v of values.filter(Number.isFinite).sort((p, q) => p - q)) {
- if (!out.length || v - out[out.length - 1] > tolerance) out.push(v);
- }
- return out;
-};
-
-const golden = (g: Fn, a: number, b: number) => {
- const r = (Math.sqrt(5) - 1) / 2;
- let c = b - r * (b - a);
- let d = a + r * (b - a);
- let fc = g(c);
- let fd = g(d);
- for (let i = 0; i < 90; i++) {
- if (fc < fd) {
- b = d;
- d = c;
- fd = fc;
- c = b - r * (b - a);
- fc = g(c);
- } else {
- a = c;
- c = d;
- fc = fd;
- d = a + r * (b - a);
- fd = g(d);
- }
- }
- return (a + b) / 2;
-};
-
-const extrema = (f: Fn, sign: 1 | -1, a: number, b: number, span: number) => {
- const n = 600;
- const { xs, ys } = sample(f, a, b, n);
- const out: number[] = [];
- for (let i = 1; i < n; i++) {
- const [y0, y1, y2] = [ys[i - 1] * sign, ys[i] * sign, ys[i + 1] * sign];
- if (![y0, y1, y2].every(Number.isFinite)) continue;
- if (y1 < y0 && y1 <= y2) {
- const x = golden(t => {
- const v = safe(f, t) * sign;
- return Number.isFinite(v) ? v : Infinity;
- }, xs[i - 1], xs[i + 1]);
- const v = safe(f, x);
- if (Number.isFinite(v) && Math.abs(v) < 50 * span) out.push(x);
- }
- }
- return dedupe(out, (b - a) * 1e-4);
-};
-
-export const minima = (f: Fn, a: number, b: number, span: number) => extrema(f, 1, a, b, span);
-export const maxima = (f: Fn, a: number, b: number, span: number) => extrema(f, -1, a, b, span);
-
-export const roots = (f: Fn, a: number, b: number, span: number) => {
- const n = 1000;
- const { xs, ys } = sample(f, a, b, n);
- const out: number[] = [];
- for (let i = 0; i <= n; i++) if (ys[i] === 0) out.push(xs[i]);
- for (let i = 0; i < n; i++) {
- const y0 = ys[i];
- const y1 = ys[i + 1];
- if (!Number.isFinite(y0) || !Number.isFinite(y1) || y0 === 0 || y1 === 0) continue;
- if (Math.sign(y0) === Math.sign(y1) || Math.abs(y1 - y0) > 2 * span) continue;
- let lo = xs[i];
- let hi = xs[i + 1];
- let flo = y0;
- for (let k = 0; k < 64; k++) {
- const m = (lo + hi) / 2;
- const fm = safe(f, m);
- if (!Number.isFinite(fm)) break;
- if (Math.sign(fm) === Math.sign(flo)) {
- lo = m;
- flo = fm;
- } else hi = m;
- }
- out.push((lo + hi) / 2);
- }
- return dedupe(out, (b - a) * 1e-4);
-};
-
-export const crossings = (f: Fn, g: Fn, a: number, b: number, span: number) =>
- roots(x => f(x) - g(x), a, b, span);
-
-export const asymptotes = (f: Fn, a: number, b: number, span: number) => {
- const big = 20 * span;
- const n = 2000;
- const { xs, ys } = sample(f, a, b, n);
- const out: number[] = [];
- for (let i = 0; i <= n; i++) if (ys[i] === Infinity || ys[i] === -Infinity) out.push(xs[i]);
- for (let i = 0; i < n; i++) {
- const y0 = ys[i];
- const y1 = ys[i + 1];
- if (!Number.isFinite(y0) || !Number.isFinite(y1)) continue;
- if (Math.sign(y0) === Math.sign(y1) || Math.abs(y1 - y0) <= 2 * span) continue;
- let lo = xs[i];
- let hi = xs[i + 1];
- let flo = y0;
- for (let k = 0; k < 80; k++) {
- const m = (lo + hi) / 2;
- const fm = safe(f, m);
- if (!Number.isFinite(fm)) {
- lo = hi = m;
- break;
- }
- if (Math.sign(fm) === Math.sign(flo)) {
- lo = m;
- flo = fm;
- } else hi = m;
- }
- const x = (lo + hi) / 2;
- const eps = 1e-9 * (1 + Math.abs(x));
- if (Math.abs(safe(f, x - eps)) > big || !Number.isFinite(safe(f, x))) out.push(x);
- }
- for (let i = 1; i < n; i++) {
- const [y0, y1, y2] = [Math.abs(ys[i - 1]), Math.abs(ys[i]), Math.abs(ys[i + 1])];
- if (![y0, y1, y2].every(Number.isFinite)) continue;
- if (y1 > big && y1 >= y0 && y1 >= y2) {
- const x = golden(t => {
- const v = Math.abs(safe(f, t));
- return Number.isFinite(v) ? -v : -Infinity;
- }, xs[i - 1], xs[i + 1]);
- const v = safe(f, x);
- if (!Number.isFinite(v) || Math.abs(v) > big * 10) out.push(x);
- }
- }
- return dedupe(out, (b - a) * 1e-3);
-};
diff --git a/docs/lib/charts/domain.ts b/docs/lib/charts/domain.ts
deleted file mode 100644
index 1797a78a..00000000
--- a/docs/lib/charts/domain.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import type { CategoryData, ChartType, DistributionData, XYData } from "./schema";
-
-export interface Extent {
- lo: number;
- hi: number;
-
- zero: boolean;
-}
-
-export const runningTotals = (values: number[]): number[] => {
- const out: number[] = [];
- values.forEach((v, i) => out.push(i === 0 ? v : out[i - 1] + v));
- return out;
-};
-
-const withZero = ({ lo, hi, zero }: Extent): Extent =>
- zero ? { lo: Math.min(0, lo), hi: Math.max(0, hi), zero } : { lo, hi, zero };
-
-export const valueExtent = (type: ChartType, data: CategoryData): Extent => {
- const all = data.series.flatMap(s => s.y);
- let lo = Math.min(...all);
- let hi = Math.max(...all);
- let zero = true;
- if (type === "stacked-bars") {
- const sums = data.x.categories.map((_, c) => data.series.map(s => s.y[c]));
- lo = Math.min(0, ...sums.map(v => v.filter(n => n < 0).reduce((a, b) => a + b, 0)));
- hi = Math.max(...sums.map(v => v.filter(n => n > 0).reduce((a, b) => a + b, 0)));
- } else if (type === "waterfall") {
- const totals = runningTotals(data.series[0]?.y ?? []);
- lo = Math.min(...totals);
- hi = Math.max(...totals);
- } else if (type === "dumbbell" || type === "slope") {
- zero = false;
- }
- const thresholds = data.annotations.map(a => a.y);
- return withZero({ lo: Math.min(lo, ...thresholds), hi: Math.max(hi, ...thresholds), zero });
-};
-
-export const xyExtent = (type: ChartType, data: XYData): { x: Extent; y: Extent } => {
- const points = data.series.flatMap(s => s.points);
- const xs = points.map(p => p[0]);
- let ys = points.map(p => p[1]);
- if (type === "stacked-area") {
- ys = data.series[0].points.map((_, i) => data.series.reduce((sum, s) => sum + s.points[i][1], 0));
- } else if (type === "error-bars" || type === "band") {
- ys = data.series.flatMap(s => s.points.flatMap((p, i) => [p[1] - (s.error?.[i] ?? 0), p[1] + (s.error?.[i] ?? 0)]));
- }
- const thresholds = data.annotations.map(a => a.y);
- return {
- x: { lo: Math.min(...xs), hi: Math.max(...xs), zero: false },
- y: withZero({
- lo: Math.min(...ys, ...thresholds),
- hi: Math.max(...ys, ...thresholds),
- zero: type === "area" || type === "stacked-area",
- }),
- };
-};
-
-export const distributionExtent = (data: DistributionData): Extent => {
- const values = [...data.series.flatMap(s => s.values), ...data.annotations.map(a => a.value)];
- return { lo: Math.min(...values), hi: Math.max(...values), zero: false };
-};
-
-export const niceStep = (span: number, target = 4) => {
- const raw = span / target || 1;
- const magnitude = 10 ** Math.floor(Math.log10(raw));
- const norm = raw / magnitude;
- return (norm < 1.5 ? 1 : norm < 3 ? 2 : norm < 7 ? 5 : 10) * magnitude;
-};
-
-export const niceRange = (
- extent: Extent,
- axis: { min?: number; max?: number; step?: number },
- tight = false
-) => {
- const lo = axis.min ?? extent.lo;
- const hi = axis.max ?? extent.hi;
- const pad = tight || (extent.zero && axis.min === undefined) ? 0 : (hi - lo || 1) * 0.06;
- const step = axis.step ?? niceStep(hi - lo + 2 * pad);
-
- const padded = Math.floor((lo - pad) / step + 1e-9) * step;
- const min = axis.min ?? (tight ? lo : lo >= 0 && padded < 0 ? 0 : padded);
- const max = axis.max ?? (tight ? hi : Math.ceil((hi + pad) / step - 1e-9) * step);
- return { min, max: max > min ? max : min + step, step };
-};
-
-export const valueDomain = (type: ChartType, data: CategoryData) => niceRange(valueExtent(type, data), data.y);
-
-export const xyDomain = (type: ChartType, data: XYData) => {
- const extent = xyExtent(type, data);
-
- const tightX = type !== "scatter" && type !== "bubble";
- return { x: niceRange(extent.x, data.x, tightX), y: niceRange(extent.y, data.y) };
-};
-
-export const distributionDomain = (data: DistributionData) => niceRange(distributionExtent(data), data.value);
diff --git a/docs/lib/charts/expression.ts b/docs/lib/charts/expression.ts
deleted file mode 100644
index a13a1c3a..00000000
--- a/docs/lib/charts/expression.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-export type Fn = (x: number) => number;
-
-const FUNCTIONS: Record<string, { arity: number; fn: (...args: number[]) => number }> = {
- sin: { arity: 1, fn: Math.sin },
- cos: { arity: 1, fn: Math.cos },
- tan: { arity: 1, fn: Math.tan },
- asin: { arity: 1, fn: Math.asin },
- acos: { arity: 1, fn: Math.acos },
- atan: { arity: 1, fn: Math.atan },
- exp: { arity: 1, fn: Math.exp },
- ln: { arity: 1, fn: Math.log },
- log: { arity: 1, fn: Math.log10 },
- sqrt: { arity: 1, fn: Math.sqrt },
- abs: { arity: 1, fn: Math.abs },
- floor: { arity: 1, fn: Math.floor },
- ceil: { arity: 1, fn: Math.ceil },
- sign: { arity: 1, fn: Math.sign },
- min: { arity: 2, fn: Math.min },
- max: { arity: 2, fn: Math.max },
- pow: { arity: 2, fn: Math.pow },
-};
-
-const CONSTANTS: Record<string, number> = { pi: Math.PI, e: Math.E };
-
-type Token = { kind: "num"; value: number } | { kind: "name"; value: string } | { kind: "op"; value: string };
-
-const tokenize = (src: string): Token[] => {
- const tokens: Token[] = [];
- let i = 0;
- while (i < src.length) {
- const ch = src[i];
- if (/\s/.test(ch)) {
- i++;
- } else if (/[0-9.]/.test(ch)) {
- const m = /^(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/i.exec(src.slice(i));
- if (!m) throw new Error(`unexpected "${ch}" at position ${i + 1}`);
- tokens.push({ kind: "num", value: Number(m[0]) });
- i += m[0].length;
- } else if (/[a-z_]/i.test(ch)) {
- const m = /^[a-z_][a-z0-9_]*/i.exec(src.slice(i))!;
- tokens.push({ kind: "name", value: m[0].toLowerCase() });
- i += m[0].length;
- } else if ((ch === "<" || ch === ">") && src[i + 1] === "=") {
- tokens.push({ kind: "op", value: `${ch}=` });
- i += 2;
- } else if ("+-*/^(),<>?:".includes(ch)) {
- tokens.push({ kind: "op", value: ch });
- i++;
- } else {
- throw new Error(`unexpected "${ch}" at position ${i + 1}`);
- }
- }
- return tokens;
-};
-
-export const compileExpression = (src: string): Fn => {
- const tokens = tokenize(src);
- let pos = 0;
- const peek = () => tokens[pos];
- const isOp = (value: string) => peek()?.kind === "op" && peek()!.value === value;
- const expect = (value: string) => {
- if (!isOp(value)) throw new Error(`expected "${value}"${peek() ? ` before "${peek()!.value}"` : " at the end"}`);
- pos++;
- };
-
- const conditional = (): Fn => {
- const test = comparison();
- if (!isOp("?")) return test;
- pos++;
- const yes = conditional();
- expect(":");
- const no = conditional();
- return x => (test(x) ? yes(x) : no(x));
- };
-
- const comparison = (): Fn => {
- const left = sum();
- const next = peek();
- const op = next?.kind === "op" ? next.value : "";
- if (!["<", ">", "<=", ">="].includes(op)) return left;
- pos++;
- const right = sum();
- if (op === "<") return x => (left(x) < right(x) ? 1 : 0);
- if (op === ">") return x => (left(x) > right(x) ? 1 : 0);
- if (op === "<=") return x => (left(x) <= right(x) ? 1 : 0);
- return x => (left(x) >= right(x) ? 1 : 0);
- };
-
- const sum = (): Fn => {
- let left = product();
- while (isOp("+") || isOp("-")) {
- const op = tokens[pos++].value;
- const a = left;
- const b = product();
- left = op === "+" ? x => a(x) + b(x) : x => a(x) - b(x);
- }
- return left;
- };
-
- const product = (): Fn => {
- let left = unary();
- while (isOp("*") || isOp("/")) {
- const op = tokens[pos++].value;
- const a = left;
- const b = unary();
- left = op === "*" ? x => a(x) * b(x) : x => a(x) / b(x);
- }
- return left;
- };
-
- const unary = (): Fn => {
- if (isOp("-")) {
- pos++;
- const a = unary();
- return x => -a(x);
- }
- if (isOp("+")) {
- pos++;
- return unary();
- }
- return power();
- };
-
- const power = (): Fn => {
- const base = atom();
- if (!isOp("^")) return base;
- pos++;
- const exponent = unary();
- return x => base(x) ** exponent(x);
- };
-
- const atom = (): Fn => {
- const token = tokens[pos++];
- if (!token) throw new Error("ends too early");
- if (token.kind === "num") {
- const v = token.value;
- if (peek()?.kind === "name" || isOp("(")) throw new Error(`write multiplication out: "${v} * …"`);
- return () => v;
- }
- if (token.kind === "op") {
- if (token.value !== "(") throw new Error(`unexpected "${token.value}"`);
- const inner = conditional();
- expect(")");
- return inner;
- }
- const name = token.value;
- if (name === "x") return x => x;
- if (Object.hasOwn(CONSTANTS, name)) {
- const v = CONSTANTS[name];
- return () => v;
- }
- const f = Object.hasOwn(FUNCTIONS, name) ? FUNCTIONS[name] : undefined;
- if (!f) throw new Error(`unknown name "${name}" (use x, pi, e, or ${Object.keys(FUNCTIONS).join(", ")})`);
- expect("(");
- const args: Fn[] = [conditional()];
- while (isOp(",")) {
- pos++;
- args.push(conditional());
- }
- expect(")");
- if (args.length !== f.arity) throw new Error(`${name}() takes ${f.arity} argument${f.arity > 1 ? "s" : ""}`);
- return args.length === 1
- ? x => f.fn(args[0](x))
- : x => f.fn(args[0](x), args[1](x));
- };
-
- const fn = conditional();
- if (pos < tokens.length) throw new Error(`unexpected "${tokens[pos].value}"`);
- return fn;
-};
-
-export const expressionError = (src: string): string | null => {
- try {
- compileExpression(src);
- return null;
- } catch (err) {
- return (err as Error).message;
- }
-};
diff --git a/docs/lib/charts/schema.ts b/docs/lib/charts/schema.ts
deleted file mode 100644
index 6b4ab511..00000000
--- a/docs/lib/charts/schema.ts
+++ /dev/null
@@ -1,535 +0,0 @@
-import { z } from "zod";
-import { expressionError } from "@/lib/charts/expression";
-import { distributionExtent, valueExtent, xyExtent } from "./domain";
-
-export const CHART_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
-
-export const CHART_COLORS = ["violet", "ember", "blue", "teal", "pink", "yellow", "muted", "ink"] as const;
-export const chartColor = z.enum(CHART_COLORS);
-export type ChartColor = z.infer<typeof chartColor>;
-
-const nonEmpty = z.string().trim().min(1);
-
-const seriesBase = {
- id: nonEmpty,
- label: nonEmpty,
- color: chartColor,
-};
-
-const thresholdAnnotation = z.strictObject({
- type: z.literal("threshold"),
- y: z.number(),
- label: nonEmpty.optional(),
-});
-
-const valueAxis = z.strictObject({
- min: z.number().optional(),
- max: z.number().optional(),
- step: z.number().positive().optional(),
- unit: z.string().default(""),
- decimals: z.number().int().min(0).max(4).default(1),
-});
-
-export const categoryData = z.strictObject({
- x: z.strictObject({ categories: z.array(nonEmpty).min(1) }),
- y: valueAxis.default({ unit: "", decimals: 1 }),
- series: z
- .array(
- z.strictObject({
- ...seriesBase,
-
- y: z.array(z.number()).min(1),
- })
- )
- .min(1),
- annotations: z.array(z.discriminatedUnion("type", [thresholdAnnotation])).default([]),
-});
-
-export type CategoryData = z.infer<typeof categoryData>;
-
-const rangeAxis = z.strictObject({
- min: z.number(),
- max: z.number(),
- step: z.number().positive().optional(),
- label: nonEmpty.optional(),
- decimals: z.number().int().min(0).max(4).default(1),
-});
-
-const curveRef = z.union([nonEmpty, z.number()]);
-
-const vlineAnnotation = z.strictObject({
- type: z.literal("vline"),
- x: z.number(),
- label: nonEmpty.optional(),
- color: chartColor.default("muted"),
-});
-
-const regionAnnotation = z.strictObject({
- type: z.literal("region"),
- upper: curveRef,
- lower: curveRef,
- color: chartColor,
- opacity: z.number().min(0).max(1).default(0.14),
- label: nonEmpty.optional(),
- labelAt: z.number().optional(),
- from: z.number().optional(),
- to: z.number().optional(),
-});
-
-const pointsAnnotation = z.strictObject({
- type: z.literal("points"),
- series: nonEmpty,
- at: z.union([
- z.enum(["minima", "maxima", "roots"]),
- z.strictObject({ crosses: curveRef }),
- z.array(z.number()).min(1),
- ]),
- color: chartColor.optional(),
- hollow: z.boolean().default(false),
- label: nonEmpty.optional(),
- drop: z.union([curveRef, z.literal("axis")]).optional(),
-});
-
-const asymptotesAnnotation = z.strictObject({
- type: z.literal("asymptotes"),
- series: nonEmpty,
- label: nonEmpty.optional(),
-});
-
-export const functionData = z.strictObject({
- axes: z.enum(["grid", "arrows"]).default("grid"),
- x: rangeAxis,
- y: rangeAxis,
- series: z
- .array(
- z.strictObject({
- ...seriesBase,
-
- label: nonEmpty.optional(),
- y: z.union([nonEmpty, z.number()]),
- dashed: z.boolean().default(false),
- from: z.number().optional(),
- to: z.number().optional(),
- })
- )
- .min(1),
- annotations: z
- .array(
- z.discriminatedUnion("type", [thresholdAnnotation, vlineAnnotation, regionAnnotation, pointsAnnotation, asymptotesAnnotation])
- )
- .default([]),
-});
-
-export type FunctionData = z.infer<typeof functionData>;
-
-const numberAxis = z.strictObject({
- min: z.number().optional(),
- max: z.number().optional(),
- step: z.number().positive().optional(),
- label: nonEmpty.optional(),
- unit: z.string().default(""),
- decimals: z.number().int().min(0).max(4).default(1),
-});
-
-const defaultAxis = { unit: "", decimals: 1 };
-
-export const xyData = z.strictObject({
- x: numberAxis.default(defaultAxis),
- y: numberAxis.default(defaultAxis),
- series: z
- .array(
- z.strictObject({
- ...seriesBase,
- points: z.array(z.tuple([z.number(), z.number()])).min(1),
-
- error: z.array(z.number().min(0)).optional(),
- size: z.array(z.number().positive()).optional(),
- })
- )
- .min(1),
- annotations: z.array(z.discriminatedUnion("type", [thresholdAnnotation])).default([]),
-});
-
-export type XYData = z.infer<typeof xyData>;
-
-export const distributionData = z.strictObject({
- value: numberAxis.default(defaultAxis),
- series: z
- .array(
- z.strictObject({
- ...seriesBase,
- values: z.array(z.number()).min(1),
- })
- )
- .min(1),
- annotations: z
- .array(
- z.discriminatedUnion("type", [
- z.strictObject({ type: z.literal("threshold"), value: z.number(), label: nonEmpty.optional() }),
- ])
- )
- .default([]),
-});
-
-export type DistributionData = z.infer<typeof distributionData>;
-
-export const partsData = z.strictObject({
- value: z
- .strictObject({
- unit: z.string().default(""),
- decimals: z.number().int().min(0).max(4).default(0),
- })
- .default({ unit: "", decimals: 0 }),
- series: z
- .array(
- z.strictObject({
- ...seriesBase,
- value: z.number().min(0),
- })
- )
- .min(1),
-});
-
-export type PartsData = z.infer<typeof partsData>;
-
-const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
-const moment = z.union([
- z.number(),
- z
- .string()
- .regex(ISO_DATE, "use an ISO date like 2026-09-14")
-
- .refine(v => !Number.isNaN(Date.parse(v)) && new Date(`${v}T00:00:00Z`).toISOString().startsWith(v), "isn't a real date"),
-]);
-export type Moment = z.infer<typeof moment>;
-
-export const timeData = z.strictObject({
- x: z
- .strictObject({
- label: nonEmpty.optional(),
- min: moment.optional(),
- max: moment.optional(),
- })
- .default({}),
- series: z
- .array(
- z.strictObject({
- ...seriesBase,
-
- spans: z.array(z.tuple([moment, moment])).optional(),
-
- events: z.array(z.tuple([moment, nonEmpty])).optional(),
- })
- )
- .min(1),
-});
-
-export type TimeData = z.infer<typeof timeData>;
-
-/**
- * A grid of values: one row per y category, one column per x category. For a
- * confusion matrix, rows are the truth (y) and columns the prediction (x).
- */
-export const matrixData = z.strictObject({
- x: z.strictObject({ label: nonEmpty.optional(), categories: z.array(nonEmpty).min(1) }),
- y: z.strictObject({ label: nonEmpty.optional(), categories: z.array(nonEmpty).min(1) }),
- values: z.array(z.array(z.number())).min(1),
- value: z
- .strictObject({
- unit: z.string().default(""),
- decimals: z.number().int().min(0).max(4).default(0),
- })
- .default({ unit: "", decimals: 0 }),
- color: chartColor.default("violet"),
-});
-
-export type MatrixData = z.infer<typeof matrixData>;
-
-export const momentValue = (m: Moment): number => (typeof m === "number" ? m : Date.parse(`${m}T00:00:00Z`) / 86_400_000);
-
-export type ChartData =
- | { shape: "categories"; data: CategoryData }
- | { shape: "xy"; data: XYData }
- | { shape: "distribution"; data: DistributionData }
- | { shape: "parts"; data: PartsData }
- | { shape: "time"; data: TimeData }
- | { shape: "function"; data: FunctionData }
- | { shape: "matrix"; data: MatrixData };
-export type DataShape = ChartData["shape"];
-
-const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
-
-export const shapeOf = (raw: unknown): DataShape => {
- if (isObject(raw) && Array.isArray(raw.values)) return "matrix";
- if (isObject(raw) && isObject(raw.x) && "categories" in raw.x) return "categories";
- const seriesHave = (field: string) =>
- isObject(raw) && Array.isArray(raw.series) && raw.series.some(s => isObject(s) && field in s);
- if (seriesHave("points")) return "xy";
- if (seriesHave("values")) return "distribution";
- if (seriesHave("value")) return "parts";
- if (seriesHave("spans") || seriesHave("events")) return "time";
- return "function";
-};
-
-export const parseChartData = (raw: unknown) => {
- const shape = shapeOf(raw);
- if (shape === "categories") return { shape, result: categoryData.safeParse(raw) } as const;
- if (shape === "xy") return { shape, result: xyData.safeParse(raw) } as const;
- if (shape === "distribution") return { shape, result: distributionData.safeParse(raw) } as const;
- if (shape === "parts") return { shape, result: partsData.safeParse(raw) } as const;
- if (shape === "time") return { shape, result: timeData.safeParse(raw) } as const;
- if (shape === "matrix") return { shape, result: matrixData.safeParse(raw) } as const;
- return { shape, result: functionData.safeParse(raw) } as const;
-};
-
-type TypeRule =
- | { shape: "categories"; check?: (d: CategoryData) => string[] }
- | { shape: "xy"; check?: (d: XYData) => string[] }
- | { shape: "distribution"; check?: (d: DistributionData) => string[] }
- | { shape: "parts"; check?: (d: PartsData) => string[] }
- | { shape: "time"; check?: (d: TimeData) => string[] }
- | { shape: "function" }
- | { shape: "matrix"; check?: (d: MatrixData) => string[] };
-
-const sliceCount = (type: string, max: number) => (d: PartsData) =>
- d.series.length <= max ? [] : [`${type} gets hard to read past ${max} slices, this data has ${d.series.length}`];
-
-const valueCount = (type: string, min: number, max = Infinity) => (d: DistributionData) =>
- d.series.flatMap(s =>
- s.values.length < min
- ? [`${type} needs at least ${min} values per series, "${s.id}" has ${s.values.length}`]
- : s.values.length > max
- ? [`${type} gets unreadable past ${max} values per series, "${s.id}" has ${s.values.length}`]
- : []
- );
-
-const seriesCount = (n: number, type: string) => (d: CategoryData) =>
- d.series.length === n ? [] : [`${type} needs exactly ${n} series, this data has ${d.series.length}`];
-
-const increasingX = (type: string) => (d: XYData) =>
- d.series.flatMap(s =>
- s.points.every((p, i) => i === 0 || p[0] > s.points[i - 1][0])
- ? []
- : [`${type} joins points left to right, so "${s.id}" needs increasing x values`]
- );
-
-const needsExtra = (field: "error" | "size", type: string) => (d: XYData) =>
- d.series.flatMap(s => (s[field] ? [] : [`${type} needs "${field}" on every series, "${s.id}" has none`]));
-
-const all = (...checks: ((d: XYData) => string[])[]) => (d: XYData) => checks.flatMap(c => c(d));
-
-export const CHART_TYPES = {
- "grouped-bars": { shape: "categories" },
- "stacked-bars": { shape: "categories" },
- "horizontal-bars": { shape: "categories" },
- lollipop: { shape: "categories" },
- dumbbell: { shape: "categories", check: seriesCount(2, "dumbbell") },
- slope: {
- shape: "categories",
- check: d => (d.x.categories.length === 2 ? [] : [`slope needs exactly 2 categories (before and after), this data has ${d.x.categories.length}`]),
- },
- radar: {
- shape: "categories",
- check: d => (d.x.categories.length >= 3 ? [] : [`radar needs at least 3 categories, this data has ${d.x.categories.length}`]),
- },
-
- waterfall: { shape: "categories", check: seriesCount(1, "waterfall") },
-
- line: { shape: "xy", check: increasingX("line") },
- area: { shape: "xy", check: increasingX("area") },
- "stacked-area": {
- shape: "xy",
- check: all(increasingX("stacked-area"), d => {
- const xs = (s: XYData["series"][number]) => s.points.map(p => p[0]).join(",");
- return d.series.every(s => xs(s) === xs(d.series[0])) ? [] : ["stacked-area needs every series to have the same x values"];
- }),
- },
- step: { shape: "xy", check: increasingX("step") },
- scatter: { shape: "xy" },
- bubble: { shape: "xy", check: needsExtra("size", "bubble") },
- "error-bars": { shape: "xy", check: all(increasingX("error-bars"), needsExtra("error", "error-bars")) },
- band: { shape: "xy", check: all(increasingX("band"), needsExtra("error", "band")) },
-
- histogram: { shape: "distribution", check: valueCount("histogram", 10) },
-
- box: { shape: "distribution", check: valueCount("box", 5) },
- strip: { shape: "distribution", check: valueCount("strip", 1, 300) },
- cdf: { shape: "distribution", check: valueCount("cdf", 5) },
-
- violin: { shape: "distribution", check: valueCount("violin", 20) },
-
- pie: { shape: "parts", check: sliceCount("pie", 6) },
- donut: { shape: "parts", check: sliceCount("donut", 6) },
- "stacked-100": { shape: "parts", check: sliceCount("stacked-100", 8) },
- waffle: { shape: "parts", check: sliceCount("waffle", 6) },
- treemap: { shape: "parts" },
-
- funnel: {
- shape: "parts",
- check: d =>
- d.series.flatMap((s, i) =>
- i > 0 && s.value > d.series[i - 1].value
- ? [`funnel stages narrow, so "${s.id}" (${s.value}) can't be larger than "${d.series[i - 1].id}" (${d.series[i - 1].value})`]
- : []
- ),
- },
-
- gantt: {
- shape: "time",
- check: d => d.series.flatMap(s => (s.spans?.length ? [] : [`gantt draws a row of spans per series, "${s.id}" has none`])),
- },
- timeline: {
- shape: "time",
- check: d => (d.series.some(s => s.events?.length) ? [] : ["timeline needs at least one event"]),
- },
-
- function: { shape: "function" },
-
- heatmap: { shape: "matrix" },
- "confusion-matrix": {
- shape: "matrix",
- check: d => {
- const same = d.x.categories.length === d.y.categories.length && d.x.categories.every((c, i) => c === d.y.categories[i]);
- const problems = same ? [] : ["confusion-matrix needs the same categories, in the same order, on x (predicted) and y (actual)"];
- if (d.values.flat().some(v => v < 0 || !Number.isInteger(v))) problems.push("confusion-matrix counts must be whole numbers, 0 or more");
- return problems;
- },
- },
-} satisfies Record<string, TypeRule>;
-
-export type ChartType = keyof typeof CHART_TYPES;
-export const CHART_TYPE_NAMES = Object.keys(CHART_TYPES) as ChartType[];
-export const isChartType = (type: string): type is ChartType => Object.hasOwn(CHART_TYPES, type);
-
-export const dataProblems = (chart: ChartData): string[] => {
- const problems: string[] = [];
- if (chart.shape === "matrix") {
- const { data } = chart;
- if (data.values.length !== data.y.categories.length)
- problems.push(`"values" has ${data.values.length} rows but "y.categories" has ${data.y.categories.length}`);
- data.values.forEach((row, i) => {
- if (row.length !== data.x.categories.length)
- problems.push(`"values.${i}" has ${row.length} values but "x.categories" has ${data.x.categories.length}`);
- });
- return problems;
- }
- const ids = chart.data.series.map(s => s.id);
- if (new Set(ids).size !== ids.length) problems.push("series ids must be unique");
- const range = (axis: { min?: number; max?: number }, name: string) => {
- if (axis.min !== undefined && axis.max !== undefined && axis.max <= axis.min)
- problems.push(`"${name}.max" must be greater than "${name}.min"`);
- };
-
- if (chart.shape === "categories") {
- const { data } = chart;
- const count = data.x.categories.length;
- data.series.forEach((s, i) => {
- if (s.y.length !== count) problems.push(`"series.${i}.y" has ${s.y.length} values but "x.categories" has ${count}`);
- });
- range(data.y, "y");
- } else if (chart.shape === "xy") {
- const { data } = chart;
- range(data.x, "x");
- range(data.y, "y");
- data.series.forEach((s, i) => {
- for (const field of ["error", "size"] as const) {
- const extra = s[field];
- if (extra && extra.length !== s.points.length)
- problems.push(`"series.${i}.${field}" has ${extra.length} values but "series.${i}.points" has ${s.points.length}`);
- }
- });
- } else if (chart.shape === "distribution") {
- range(chart.data.value, "value");
- } else if (chart.shape === "time") {
- const { data } = chart;
- const moments = [
- ...data.series.flatMap(s => [...(s.spans ?? []).flat(), ...(s.events ?? []).map(e => e[0])]),
- ...[data.x.min, data.x.max].filter(m => m !== undefined),
- ];
- if (!moments.length) problems.push("needs at least one span or event");
- if (new Set(moments.map(m => typeof m)).size > 1) problems.push("use numbers or ISO dates throughout, not both");
- data.series.forEach((s, i) =>
- (s.spans ?? []).forEach(([from, to], j) => {
- if (momentValue(to) < momentValue(from)) problems.push(`"series.${i}.spans.${j}" ends (${to}) before it starts (${from})`);
- })
- );
- if (data.x.min !== undefined && data.x.max !== undefined && momentValue(data.x.max) <= momentValue(data.x.min))
- problems.push(`"x.max" must be after "x.min"`);
- } else if (chart.shape === "parts") {
- if (!chart.data.series.some(s => s.value > 0)) problems.push("at least one series needs a value above 0");
- } else {
- const { data } = chart;
- range(data.x, "x");
- range(data.y, "y");
- const known = new Set(ids);
-
- const checkRef = (ref: string | number, at: string) => {
- if (typeof ref !== "string" || known.has(ref)) return;
- const error = expressionError(ref);
- if (error) problems.push(`${at} is neither a series id nor an equation: "${ref}" (${error})`);
- };
- data.series.forEach((s, i) => {
- if (typeof s.y === "string") {
- const error = expressionError(s.y);
- if (error) problems.push(`"series.${i}.y" can't be read: ${error}`);
- }
- });
- data.annotations.forEach((a, i) => {
- const at = (field: string) => `"annotations.${i}.${field}"`;
- if (a.type === "region") {
- checkRef(a.upper, at("upper"));
- checkRef(a.lower, at("lower"));
- } else if (a.type === "asymptotes") {
- if (!known.has(a.series)) problems.push(`${at("series")} names unknown series "${a.series}"`);
- } else if (a.type === "points") {
- if (!known.has(a.series)) problems.push(`${at("series")} names unknown series "${a.series}"`);
- if (typeof a.at === "object" && !Array.isArray(a.at)) checkRef(a.at.crosses, at("at.crosses"));
- if (a.drop !== undefined && a.drop !== "axis") checkRef(a.drop, at("drop"));
- }
- });
- }
- return problems;
-};
-
-export const typeProblems = (type: ChartType, chart: ChartData): string[] => {
- const rule: TypeRule = CHART_TYPES[type];
- if (rule.shape !== chart.shape)
- return [`${type} draws ${rule.shape} data, but this file holds ${chart.shape} data`];
- if (rule.shape === "categories" && chart.shape === "categories") {
- const problems = rule.check ? rule.check(chart.data) : [];
-
- const { y } = chart.data;
- if (!problems.length && (y.min !== undefined || y.max !== undefined)) {
- const { lo, hi } = valueExtent(type, chart.data);
- if (y.min !== undefined && lo < y.min) problems.push(`${type} needs y down to ${lo}, but "y.min" is ${y.min}`);
- if (y.max !== undefined && hi > y.max) problems.push(`${type} needs y up to ${hi}, but "y.max" is ${y.max}`);
- }
- return problems;
- }
- if (rule.shape === "xy" && chart.shape === "xy") {
- const problems = rule.check ? rule.check(chart.data) : [];
- const { x, y } = chart.data;
- if (!problems.length) {
- const e = xyExtent(type, chart.data);
- if (x.min !== undefined && e.x.lo < x.min) problems.push(`${type} needs x down to ${e.x.lo}, but "x.min" is ${x.min}`);
- if (x.max !== undefined && e.x.hi > x.max) problems.push(`${type} needs x up to ${e.x.hi}, but "x.max" is ${x.max}`);
- if (y.min !== undefined && e.y.lo < y.min) problems.push(`${type} needs y down to ${e.y.lo}, but "y.min" is ${y.min}`);
- if (y.max !== undefined && e.y.hi > y.max) problems.push(`${type} needs y up to ${e.y.hi}, but "y.max" is ${y.max}`);
- }
- return problems;
- }
- if (rule.shape === "distribution" && chart.shape === "distribution") {
- const problems = rule.check ? rule.check(chart.data) : [];
- const { value } = chart.data;
- if (!problems.length) {
- const e = distributionExtent(chart.data);
- if (value.min !== undefined && e.lo < value.min) problems.push(`${type} needs values down to ${e.lo}, but "value.min" is ${value.min}`);
- if (value.max !== undefined && e.hi > value.max) problems.push(`${type} needs values up to ${e.hi}, but "value.max" is ${value.max}`);
- }
- return problems;
- }
- if (rule.shape === "parts" && chart.shape === "parts") return rule.check ? rule.check(chart.data) : [];
- if (rule.shape === "time" && chart.shape === "time") return rule.check ? rule.check(chart.data) : [];
- if (rule.shape === "matrix" && chart.shape === "matrix") return rule.check ? rule.check(chart.data) : [];
- return [];
-};
diff --git a/docs/lib/charts/stats.ts b/docs/lib/charts/stats.ts
deleted file mode 100644
index 6fc1d37a..00000000
--- a/docs/lib/charts/stats.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-const sorted = (values: number[]) => [...values].sort((a, b) => a - b);
-
-export const quantile = (values: number[], p: number): number => {
- const s = sorted(values);
- const at = (s.length - 1) * p;
- const lo = Math.floor(at);
- return s[lo] + (s[Math.min(lo + 1, s.length - 1)] - s[lo]) * (at - lo);
-};
-
-export interface BoxStats {
- n: number;
- min: number;
- q1: number;
- median: number;
- q3: number;
- max: number;
-
- low: number;
- high: number;
- outliers: number[];
-}
-
-export const boxStats = (values: number[]): BoxStats => {
- const s = sorted(values);
- const q1 = quantile(s, 0.25);
- const q3 = quantile(s, 0.75);
- const reach = 1.5 * (q3 - q1);
- const inside = s.filter(v => v >= q1 - reach && v <= q3 + reach);
- return {
- n: s.length,
- min: s[0],
- q1,
- median: quantile(s, 0.5),
- q3,
- max: s[s.length - 1],
- low: inside[0] ?? q1,
- high: inside[inside.length - 1] ?? q3,
- outliers: s.filter(v => v < q1 - reach || v > q3 + reach),
- };
-};
-
-export const histogram = (values: number[], start: number, width: number, bins: number): number[] => {
- const counts = new Array(bins).fill(0);
- for (const v of values) counts[Math.min(bins - 1, Math.max(0, Math.floor((v - start) / width)))]++;
- return counts;
-};
-
-export const density = (values: number[], at: number[]): number[] => {
- const n = values.length;
- const mean = values.reduce((a, b) => a + b, 0) / n;
- const sd = Math.sqrt(values.reduce((a, v) => a + (v - mean) ** 2, 0) / Math.max(1, n - 1));
- const iqr = quantile(values, 0.75) - quantile(values, 0.25);
- const spread = Math.min(sd, iqr / 1.34) || sd || 1;
- const h = 0.9 * spread * n ** -0.2;
- return at.map(x => values.reduce((sum, v) => sum + Math.exp(-0.5 * ((x - v) / h) ** 2), 0) / (n * h * Math.sqrt(2 * Math.PI)));
-};
diff --git a/docs/lib/charts/store.ts b/docs/lib/charts/store.ts
deleted file mode 100644
index cd1e0433..00000000
--- a/docs/lib/charts/store.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { ChartData } from "./schema";
-import { CHART_KIND } from "@/lib/frames/kinds";
-import { loadFrameFile } from "@/lib/frames/store";
-
-export type ChartDataMap = Record<string, ChartData>;
-
-/** Chart IDs are local to the charts.json beside the content file. */
-export const loadChartData = (sourceFile: string): ChartDataMap => loadFrameFile(CHART_KIND, sourceFile);
diff --git a/docs/lib/frames/board-brands.ts b/docs/lib/frames/board-brands.ts
deleted file mode 100644
index 5f7a308e..00000000
--- a/docs/lib/frames/board-brands.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-export interface ExtraBrand {
- title: string;
- hex: string;
- path: string;
- source: string;
-}
-
-export const EXTRA_BRANDS: Record<string, ExtraBrand> = {
- openai: {
- title: "OpenAI",
- hex: "000000",
- path: "M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z",
- source: "https://github.com/simple-icons/simple-icons/blob/13.0.0/icons/openai.svg",
- },
- slack: {
- title: "Slack",
- hex: "4A154B",
- path: "M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zM18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zM15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z",
- source: "https://github.com/simple-icons/simple-icons/blob/13.0.0/icons/slack.svg",
- },
- xai: {
- title: "xAI",
- hex: "000000",
- path: "M6.469 8.776L16.512 23h-4.464L2.005 8.776H6.47zm-.004 7.9l2.233 3.164L6.467 23H2l4.465-6.324zM22 2.582V23h-3.659V7.764L22 2.582zM22 1l-9.952 14.095-2.233-3.163L17.533 1H22z",
- source: "https://github.com/lobehub/lobe-icons/blob/master/packages/static-svg/icons/xai.svg",
- },
-};
diff --git a/docs/lib/frames/board-icons.ts b/docs/lib/frames/board-icons.ts
deleted file mode 100644
index 944dfe90..00000000
--- a/docs/lib/frames/board-icons.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { icons as lucideIcons, type LucideIcon } from "lucide-react";
-import * as simpleIcons from "simple-icons";
-import type { SimpleIcon } from "simple-icons";
-import { CHART_COLORS, type ChartColor } from "@/lib/charts/schema";
-import { loadLibrary, resolveMedia } from "@/lib/media/library.mjs";
-import { EXTRA_BRANDS } from "./board-brands";
-
-export const ICON_SOURCES = ["brand", "icon", "media"] as const;
-/** `<source>:<name>`, optionally `@<chart color>` to draw it in that color, e.g. `icon:bot@violet`. */
-export const ICON_REF = /^(brand|icon|media):([^\s@]+)(?:@(\S+))?$/;
-
-/** The chart color an icon is drawn in, when its reference names one. */
-export const iconTint = (ref: string): ChartColor | undefined => {
- const color = ICON_REF.exec(ref)?.[3];
- return CHART_COLORS.find(c => c === color);
-};
-
-export type ResolvedIcon =
- | { source: "brand"; title: string; path: string; color: string | null }
- | { source: "icon"; title: string; Component: LucideIcon }
- | { source: "media"; title: string; src: string; width: number; height: number };
-
-const BRANDS = new Map<string, { title: string; hex: string; path: string }>([
- ...Object.values(simpleIcons as Record<string, SimpleIcon>)
- .filter(icon => typeof icon === "object" && "slug" in icon)
- .map(icon => [icon.slug, icon] as const),
- ...Object.entries(EXTRA_BRANDS),
-]);
-
-const pascal = (name: string) =>
- name
- .split("-")
- .map(part => part.charAt(0).toUpperCase() + part.slice(1))
- .join("");
-
-const lucide = (name: string): LucideIcon | undefined =>
- /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) && Object.hasOwn(lucideIcons, pascal(name))
- ? lucideIcons[pascal(name) as keyof typeof lucideIcons]
- : undefined;
-
-const luminance = (hex: string) => {
- const [r, g, b] = [0, 2, 4].map(i => {
- const c = parseInt(hex.slice(i, i + 2), 16) / 255;
- return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
- });
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
-};
-
-const brandColor = (hex: string) => {
- const l = luminance(hex);
- return l < 0.04 || l > 0.85 ? null : `#${hex}`;
-};
-
-export const resolveIcon = (ref: string): ResolvedIcon | null => {
- const match = ICON_REF.exec(ref);
- if (!match) return null;
- const [, source, name] = match;
- if (source === "brand") {
- const icon = BRANDS.get(name);
- return icon ? { source, title: icon.title, path: icon.path, color: brandColor(icon.hex) } : null;
- }
- if (source === "icon") {
- const Component = lucide(name);
- return Component ? { source, title: name.replace(/-/g, " "), Component } : null;
- }
- const entry = loadLibrary().get(name);
- return entry ? { source: "media", title: entry.title, ...resolveMedia(name) } : null;
-};
-
-export const iconProblem = (ref: string): string | null => {
- const match = ICON_REF.exec(ref);
- if (!match) return `icon "${ref}" needs a source: "brand:<slug>" (Simple Icons), "icon:<name>" (Lucide) or "media:<id>" (media library)`;
- const [, source, name, color] = match;
- if (color && !iconTint(ref)) return `unknown color "${color}" in icon "${ref}": use ${CHART_COLORS.map(c => `"@${c}"`).join(", ")}`;
- if (color && source === "media") return `media images keep their own colors; drop "@${color}" from "${ref}"`;
- if (resolveIcon(ref)) return null;
- if (source === "brand") {
- return `unknown brand "${name}": use a slug from simpleicons.org (or ${Object.keys(EXTRA_BRANDS).join(", ")}), or add the logo to docs/media/ and use "media:<id>"`;
- }
- if (source === "icon") return `unknown Lucide icon "${name}": use a kebab-case name from lucide.dev/icons`;
- return `unknown media id "${name}": add the image to docs/media/ first`;
-};
diff --git a/docs/lib/frames/board.ts b/docs/lib/frames/board.ts
deleted file mode 100644
index d1c33788..00000000
--- a/docs/lib/frames/board.ts
+++ /dev/null
@@ -1,325 +0,0 @@
-import { z } from "zod";
-import { type ChartColor, chartColor } from "@/lib/charts/schema";
-import { ICON_REF, iconProblem } from "./board-icons";
-
-const nonEmpty = z.string().trim().min(1);
-const itemId = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "use lowercase-kebab-case item ids");
-
-export const ICON_ARRANGEMENTS = ["grid", "line", "zigzag-h", "zigzag-v", "circle", "scatter"] as const;
-export type IconArrangement = (typeof ICON_ARRANGEMENTS)[number];
-export const DIRECTIONS = ["vertical", "horizontal"] as const;
-export type Direction = (typeof DIRECTIONS)[number];
-export const ITEM_SPLITS = ["cells", "boxes"] as const;
-export const ITEM_SHAPES = ["box", "circle"] as const;
-export const ITEM_BORDERS = ["solid", "dashed", "none"] as const;
-export const BOARD_SIZES = ["xs", "sm", "md", "lg"] as const;
-export type BoardSize = (typeof BOARD_SIZES)[number];
-export const LABEL_PLACES = ["head", "above", "below"] as const;
-export type LabelPlace = (typeof LABEL_PLACES)[number];
-export const ICON_PLACES = ["body", "label"] as const;
-
-const iconRef = z.string().regex(ICON_REF, 'write icons as "brand:<slug>", "icon:<name>" or "media:<id>", optionally with "@<color>"');
-
-const iconFields = {
- icons: z.array(iconRef).default([]),
- arrange: z.enum(ICON_ARRANGEMENTS).optional(),
-};
-
-export interface BoardLine {
- text: string;
- icons: string[];
-}
-
-export interface BoardItem {
- id: string;
- label: string;
- color?: ChartColor;
- icons: string[];
- arrange?: IconArrangement;
- size?: BoardSize;
- labelAt?: LabelPlace;
- iconsAt?: (typeof ICON_PLACES)[number];
- lines: BoardLine[];
- shape?: (typeof ITEM_SHAPES)[number];
- border?: (typeof ITEM_BORDERS)[number];
- direction?: Direction;
- split?: (typeof ITEM_SPLITS)[number];
- columns?: number;
- children: BoardItem[];
-}
-
-const textLine = z.strictObject({ text: nonEmpty, icons: z.array(iconRef).default([]) });
-
-const boardItem: z.ZodType<BoardItem, unknown> = z.lazy(() =>
- z.strictObject({
- id: itemId,
- label: nonEmpty,
- color: chartColor.optional(),
- ...iconFields,
- size: z.enum(BOARD_SIZES).optional(),
- labelAt: z.enum(LABEL_PLACES).optional(),
- iconsAt: z.enum(ICON_PLACES).optional(),
- lines: z.array(textLine).default([]),
- shape: z.enum(ITEM_SHAPES).optional(),
- border: z.enum(ITEM_BORDERS).optional(),
- direction: z.enum(DIRECTIONS).optional(),
- split: z.enum(ITEM_SPLITS).optional(),
- columns: z.number().int().min(2).optional(),
- children: z.array(boardItem).default([]),
- })
-);
-
-export const NOTE_ARROWS = ["out", "in", "both", "none"] as const;
-export const NOTE_SHAPES = ["box", "text"] as const;
-
-const noteFields = {
- for: itemId.optional(),
- label: nonEmpty,
- color: chartColor.optional(),
- shape: z.enum(NOTE_SHAPES).default("box"),
- arrow: z.enum(NOTE_ARROWS).default("out"),
- arrowLabel: nonEmpty.optional(),
- size: z.enum(BOARD_SIZES).optional(),
- ...iconFields,
-};
-
-const noteColumn = z.strictObject({
- heading: nonEmpty.optional(),
- items: z.array(z.strictObject(noteFields)).min(1),
-});
-
-const bottomNotes = z.strictObject({
- items: z.array(z.strictObject(noteFields)).min(1),
-});
-
-export const LINK_ROUTES = ["direct", "left", "right", "top", "bottom"] as const;
-export type LinkRoute = (typeof LINK_ROUTES)[number];
-
-const link = z.strictObject({
- from: itemId,
- to: itemId,
- route: z.enum(LINK_ROUTES).default("direct"),
- label: nonEmpty.optional(),
- both: z.boolean().default(false),
- dashed: z.boolean().default(false),
-});
-
-export const LINE_ENDS = ["magnifier", "circle", "dot", "arrow", "none"] as const;
-export type LineEnd = (typeof LINE_ENDS)[number];
-export const LINE_STYLES = ["solid", "dashed"] as const;
-export const PULLOUT_ROUTES = ["gap", "straight"] as const;
-export const PULLOUT_PLACES = ["above", "level", "below"] as const;
-export const PULLOUT_SHAPES = ["circle", "none"] as const;
-
-const pulloutLine = z.strictObject({
- style: z.enum(LINE_STYLES).default("solid"),
- color: chartColor.optional(),
- start: z.enum(LINE_ENDS).default("magnifier"),
- end: z.enum(LINE_ENDS).default("none"),
- label: nonEmpty.optional(),
- icons: z.array(iconRef).default([]),
-});
-
-const pullout = z.strictObject({
- for: itemId.optional(),
- shape: z.enum(PULLOUT_SHAPES).default("circle"),
- heading: nonEmpty.optional(),
- route: z.enum(PULLOUT_ROUTES).default("gap"),
- place: z.enum(PULLOUT_PLACES).default("level"),
- size: z.enum(BOARD_SIZES).optional(),
- line: z.union([pulloutLine, z.array(pulloutLine).min(1).max(2)]).prefault({}),
- ...iconFields,
- items: z.array(z.strictObject({ label: nonEmpty, color: chartColor.default("muted"), icons: z.array(iconRef).default([]) })).default([]),
-});
-
-/** A venn member: text drawn in the region of the sets it's `in` (one set, or both of two overlapping sets). */
-const member = z.strictObject({
- in: z.array(itemId).min(1).max(2),
- label: nonEmpty.optional(),
- color: chartColor.optional(),
- lines: z.array(textLine).min(1),
-});
-
-export const BOARD_SIDES = ["left", "right"] as const;
-export type BoardSide = (typeof BOARD_SIDES)[number];
-
-export const BOARD_RADII = ["none", "small", "medium", "large"] as const;
-export type BoardRadius = (typeof BOARD_RADII)[number];
-
-export const BOARD_FILLS = ["hatch", "tint"] as const;
-
-export const boardData = z.strictObject({
- radius: z.enum(BOARD_RADII).default("medium"),
- /** The border around the whole board; with "none" its space and fill stay. */
- panel: z.enum(["solid", "none"]).default("solid"),
- fill: z.enum(BOARD_FILLS).default("hatch"),
- heading: z
- .strictObject({
- text: nonEmpty,
- align: z.enum(["left", "center", "right"]).default("left"),
- })
- .optional(),
- main: z.strictObject({
- border: z.enum(["solid", "dashed", "none"]).default("dashed"),
- direction: z.enum(DIRECTIONS).optional(),
- columns: z.number().int().min(2).optional(),
- items: z.array(boardItem).min(1),
- links: z.array(link).default([]),
- members: z.array(member).default([]),
- }),
- notes: z
- .strictObject({ left: noteColumn.optional(), right: noteColumn.optional(), bottom: bottomNotes.optional() })
- .default({}),
- pullouts: z
- .strictObject({ left: z.array(pullout).min(1).optional(), right: z.array(pullout).min(1).optional() })
- .default({}),
-});
-
-export type BoardData = z.infer<typeof boardData>;
-export type BoardNoteColumn = z.infer<typeof noteColumn>;
-export type BoardNote = BoardNoteColumn["items"][number];
-export type BoardLink = z.infer<typeof link>;
-export type BoardMember = z.infer<typeof member>;
-export const NOTE_SIDES = ["left", "right", "bottom"] as const;
-export type BoardPullout = z.infer<typeof pullout>;
-export type BoardPulloutLine = z.infer<typeof pulloutLine>;
-
-export const pulloutLines = (pullout: BoardPullout): BoardPulloutLine[] => (Array.isArray(pullout.line) ? pullout.line : [pullout.line]);
-
-export const BOARD_TYPES = ["tree", "groups", "venn"] as const;
-export type BoardType = (typeof BOARD_TYPES)[number];
-
-export interface BoardRow {
- item: BoardItem;
- depth: number;
- parent?: BoardRow;
-}
-
-export const flattenItems = (items: BoardItem[], depth = 0, parent?: BoardRow, rows: BoardRow[] = []): BoardRow[] => {
- for (const item of items) {
- const row: BoardRow = { item, depth, parent };
- rows.push(row);
- flattenItems(item.children, depth + 1, row, rows);
- }
- return rows;
-};
-
-const repeated = (values: string[]) => [...new Set(values.filter((v, i) => values.indexOf(v) !== i))];
-
-export const boardProblems = (data: BoardData): string[] => {
- const problems: string[] = [];
- const rows = flattenItems(data.main.items);
- const ids = rows.map(r => r.item.id);
- const known = new Set(ids);
- for (const id of repeated(ids)) problems.push(`item id "${id}" is used more than once`);
- const checkIcons = (icons: string[], at: string) =>
- icons.forEach((ref, i) => {
- const problem = iconProblem(ref);
- if (problem) problems.push(`${at}.icons.${i}": ${problem}`);
- });
- const parentOf = new Map(rows.flatMap(r => r.item.children.map((child, index) => [child.id, { parent: r.item, index }] as const)));
- for (const { item } of rows) {
- checkIcons(item.icons, `item "${item.id}" "`);
- item.lines.forEach((line, i) => checkIcons(line.icons, `item "${item.id}" "lines.${i}`));
- if (item.shape === "circle" && item.children.length) problems.push(`item "${item.id}": a circle can't hold children`);
- if (item.split && !item.children.length) problems.push(`item "${item.id}": "split" needs children`);
- if (item.columns && !item.children.length) problems.push(`item "${item.id}": "columns" needs children`);
- if (item.columns && data.main.links.some(l => item.children.some(c => c.id === l.from) && item.children.some(c => c.id === l.to)))
- problems.push(`item "${item.id}": links can't join boxes in a grid; drop "columns" or the links between its children`);
- if (item.labelAt === "below" && item.children.length) problems.push(`item "${item.id}": a label below can't sit under children; use "head" or "above"`);
- if (item.labelAt === "head" && item.shape === "circle") problems.push(`item "${item.id}": a circle has no head; use labelAt "above" or "below"`);
- if (item.iconsAt === "label" && !item.icons.length) problems.push(`item "${item.id}": "iconsAt" needs "icons"`);
- if (item.iconsAt === "label" && item.arrange) problems.push(`item "${item.id}": "arrange" places icons in the body; drop it with "iconsAt": "label"`);
- }
- for (const side of NOTE_SIDES) {
- const notes = data.notes[side]?.items ?? [];
- notes.forEach((note, i) => {
- const at = `"notes.${side}.items.${i}`;
- if (note.for && !known.has(note.for)) problems.push(`${at}.for" names unknown item "${note.for}"`);
- if (note.arrange && note.shape === "box") problems.push(`${at}": a box shows its icons inline; "arrange" needs shape "text"`);
- checkIcons(note.icons, at);
- });
- for (const id of repeated(notes.map(n => n.for ?? "the whole board"))) problems.push(`"notes.${side}" annotates ${id === "the whole board" ? id : `"${id}"`} more than once`);
- }
- for (const side of BOARD_SIDES) {
- const pullouts = data.pullouts[side] ?? [];
- pullouts.forEach((c, i) => {
- const at = `"pullouts.${side}.${i}`;
- if (c.for && !known.has(c.for)) problems.push(`${at}.for" names unknown item "${c.for}"`);
- if (!c.items.length && !c.icons.length && !c.heading) problems.push(`${at}" needs a "heading", "items" or "icons"`);
- checkIcons(c.icons, at);
- c.items.forEach((item, j) => checkIcons(item.icons, `${at}.items.${j}`));
- const lines = pulloutLines(c);
- lines.forEach((line, j) => checkIcons(line.icons, `${at}.line${lines.length > 1 ? `.${j}` : ""}`));
- if (lines.length > 1 && c.route !== "straight") problems.push(`${at}": side-by-side lines need route "straight"`);
- });
- for (const id of repeated(pullouts.map(c => c.for ?? "the whole board"))) problems.push(`"pullouts.${side}" points at ${id === "the whole board" ? id : `"${id}"`} more than once`);
- }
- const root = new Map<string, number>();
- data.main.items.forEach((item, i) => flattenItems([item]).forEach(r => root.set(r.item.id, i)));
- const sides = data.main.direction === "horizontal" ? ["top", "bottom"] : ["left", "right"];
- if (data.main.columns && data.main.links.length) problems.push('"main.columns" lays the boxes out in a grid, which links can\'t join; drop the columns or "main.links"');
- data.main.links.forEach((l, i) => {
- const at = `"main.links.${i}"`;
- for (const end of [l.from, l.to]) if (!known.has(end)) problems.push(`${at} names unknown item "${end}"`);
- if (l.from === l.to) problems.push(`${at} links "${l.from}" to itself`);
- if (!known.has(l.from) || !known.has(l.to)) return;
- const [pa, pb] = [parentOf.get(l.from), parentOf.get(l.to)];
- const siblings = pa && pb && pa.parent === pb.parent && pa.parent.split === "boxes" && Math.abs(pa.index - pb.index) === 1;
- if (l.route === "direct" && !siblings && Math.abs(root.get(l.from)! - root.get(l.to)!) !== 1) {
- problems.push(`${at}: "direct" links neighbouring boxes (top-level, or children of a "split": "boxes" item); go around with route ${sides.map(s => `"${s}"`).join(" or ")}`);
- }
- if (l.route !== "direct" && !sides.includes(l.route)) {
- problems.push(`${at}: route "${l.route}" doesn't fit ${data.main.direction ?? "vertical"} boxes; use "direct", ${sides.map(s => `"${s}"`).join(" or ")}`);
- }
- });
- return problems;
-};
-
-const VENN_UNUSED = ["arrange", "labelAt", "iconsAt", "direction", "shape", "split", "columns"] as const;
-
-const vennProblems = (data: BoardData): string[] => {
- const problems: string[] = [];
- const { items, members } = data.main;
- if (data.main.direction || data.main.columns) problems.push('venn doesn\'t use "main.direction" or "main.columns"; it places the sets itself');
- if (data.main.links.length) problems.push('venn has no links; "main.links" are for groups');
- if (items.length > 2) problems.push(`venn draws one set, or two overlapping; it has ${items.length} top-level items (nest sets inside one instead)`);
- if (items.length === 2 && items.some(i => i.children.length)) problems.push("two overlapping sets hold members, not sets; to nest sets, use one top-level set");
- const ids = new Set(flattenItems(items).map(r => r.item.id));
- for (const { item } of flattenItems(items)) {
- const unused: string[] = VENN_UNUSED.filter(key => item[key]);
- if (item.icons.length) unused.push("icons");
- if (item.lines.length) unused.push("lines");
- if (unused.length) problems.push(`venn sets don't use ${unused.map(k => `"${k}"`).join(" or ")} (item "${item.id}"); put text in "main.members"`);
- }
- members.forEach((m, i) => {
- for (const id of m.in) if (!ids.has(id)) problems.push(`"main.members.${i}.in" names unknown set "${id}"`);
- if (m.in.length === 2 && !(items.length === 2 && m.in.every(id => items.some(i => i.id === id))))
- problems.push(`"main.members.${i}" is in two sets; that needs the two top-level, overlapping sets`);
- });
- return problems;
-};
-
-export const boardTypeProblems = (type: BoardType, data: BoardData): string[] => {
- if (type !== "venn" && data.main.members.length) return [`"main.members" are for venn boards, not ${type}`];
- if (type === "venn") return vennProblems(data);
- if (type === "groups") {
- const rows = flattenItems(data.main.items);
- return rows.flatMap(({ item, parent }) =>
- parent && parent.item.split !== "boxes" && (item.shape || item.border || item.color)
- ? [`item "${item.id}" is a cell, so it has no box to shape, border or tint; set "split": "boxes" on its parent`]
- : []
- );
- }
- if (type !== "tree") return [`unknown type "${type}"`];
- const problems: string[] = [];
- if (data.main.direction) problems.push('tree doesn\'t use "main.direction"; it\'s for groups');
- if (data.main.columns) problems.push('tree doesn\'t use "main.columns"; it\'s for groups');
- if (data.main.links.length) problems.push('tree draws its own arrows; "main.links" are for groups');
- for (const { item } of flattenItems(data.main.items)) {
- const unused: string[] = (["arrange", "size", "labelAt", "iconsAt", "direction", "shape", "border", "split", "columns"] as const).filter(key => item[key]);
- if (item.lines.length) unused.push("lines");
- if (unused.length) problems.push(`tree rows don't use ${unused.map(k => `"${k}"`).join(" or ")} (item "${item.id}"); those are for groups`);
- }
- return problems;
-};
diff --git a/docs/lib/frames/chat.ts b/docs/lib/frames/chat.ts
deleted file mode 100644
index 6286f3a1..00000000
--- a/docs/lib/frames/chat.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { z } from "zod";
-
-const nonEmpty = z.string().trim().min(1);
-
-/** One message: what the user sent or what the bot replied. `==text==` highlights part of it. */
-const message = z.strictObject({
- from: z.enum(["user", "bot"]),
- text: nonEmpty,
- /** Marks a reply as one the bot should (pass) or shouldn't (fail) have given. */
- verdict: z.enum(["pass", "fail"]).optional(),
-});
-
-/**
- * A mock chat with an unbranded bot: never a real product's name, logo or look,
- * since these often show a bot failing (a jailbreak, a leak) that no real product did.
- */
-export const chatData = z.strictObject({
- /** The bot's name, e.g. "Chatbot" or "Command Bot". */
- bot: nonEmpty.default("Chatbot"),
- messages: z.array(message).min(2),
-});
-
-export type ChatData = z.infer<typeof chatData>;
-export type ChatMessage = ChatData["messages"][number];
-
-/** `chat`: bubbles in a chat window. `playground`: a prompt field, a Generate button and an output panel. */
-export const CHAT_TYPES = ["chat", "playground"] as const;
-export type ChatType = (typeof CHAT_TYPES)[number];
-
-export const chatProblems = (data: ChatData): string[] => {
- const problems: string[] = [];
- if (!data.messages.some(m => m.from === "user") || !data.messages.some(m => m.from === "bot")) {
- problems.push("needs at least one user message and one bot reply");
- }
- data.messages.forEach((m, i) => {
- if (m.verdict && m.from === "user") problems.push(`"messages.${i}": only bot replies take a "verdict"`);
- });
- return problems;
-};
-
-export const chatTypeProblems = (type: ChatType, data: ChatData): string[] =>
- type === "playground" && data.messages[0].from !== "user" ? ["a playground starts with the user's prompt"] : [];
diff --git a/docs/lib/frames/flow.ts b/docs/lib/frames/flow.ts
deleted file mode 100644
index a2e16af5..00000000
--- a/docs/lib/frames/flow.ts
+++ /dev/null
@@ -1,225 +0,0 @@
-import { z } from "zod";
-import { type ChartColor, chartColor } from "@/lib/charts/schema";
-
-const nonEmpty = z.string().trim().min(1);
-const localId = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "use lowercase-kebab-case ids");
-
-export const NODE_KINDS = ["input", "llm", "tool", "store", "eval", "output", "decision", "actor"] as const;
-export type NodeKind = (typeof NODE_KINDS)[number];
-
-/** A node's kind picks its color unless the node names one. */
-export const KIND_COLORS: Record<NodeKind, ChartColor> = {
- input: "blue",
- llm: "violet",
- tool: "ember",
- store: "teal",
- eval: "pink",
- output: "blue",
- decision: "yellow",
- actor: "muted",
-};
-
-/**
- * Lucide icons a node may show, by name (lucide.dev/icons). A short, deliberate
- * list keeps diagrams in one visual language; add a name here (and its import
- * in components/frames/FlowPlot/_icons.ts) when a diagram needs one.
- */
-export const FLOW_ICONS = [
- "activity",
- "app-window",
- "bell",
- "binary",
- "book-open",
- "bot",
- "boxes",
- "brain",
- "bug",
- "calendar",
- "clipboard-check",
- "code",
- "cpu",
- "database",
- "file-search",
- "file-text",
- "filter",
- "gauge",
- "gavel",
- "globe",
- "hard-drive",
- "image",
- "inbox",
- "key",
- "layers",
- "layout-template",
- "library",
- "list-checks",
- "lock",
- "mail",
- "message-square",
- "message-square-reply",
- "network",
- "plug",
- "scale",
- "search",
- "send",
- "server",
- "shield-alert",
- "shield-check",
- "sparkles",
- "table",
- "target",
- "terminal",
- "text-cursor-input",
- "user",
- "users",
- "workflow",
- "wrench",
- "zap",
-] as const;
-export type FlowIcon = (typeof FLOW_ICONS)[number];
-
-/** A node's kind picks its icon unless the node names one, or "none". */
-export const KIND_ICONS: Partial<Record<NodeKind, FlowIcon>> = {
- input: "message-square",
- llm: "brain",
- tool: "wrench",
- store: "database",
- eval: "gauge",
- output: "message-square-reply",
- actor: "user",
-};
-
-const icon = z.union([z.enum(FLOW_ICONS), z.literal("none")]);
-
-export const NODE_SHAPES = ["box", "pill", "diamond", "circle", "store"] as const;
-export type NodeShape = (typeof NODE_SHAPES)[number];
-/** Shapes that hold a question or a score, not a component: drawn without icons. */
-const TEXT_SHAPES: readonly NodeShape[] = ["diamond", "circle"];
-
-export const graphData = z.strictObject({
- direction: z.enum(["TB", "LR"]).default("TB"),
- nodes: z
- .array(
- z.strictObject({
- id: localId,
- label: nonEmpty,
- kind: z.enum(NODE_KINDS).optional(),
- color: chartColor.optional(),
- icon: icon.optional(),
- shape: z.enum(NODE_SHAPES).default("box"),
- group: localId.optional(),
- })
- )
- .min(1),
- groups: z
- .array(z.strictObject({ id: localId, label: nonEmpty, badge: nonEmpty.optional(), parent: localId.optional() }))
- .default([]),
- edges: z
- .array(
- z.strictObject({
- from: localId,
- to: localId,
- label: nonEmpty.optional(),
- dashed: z.boolean().default(false),
- both: z.boolean().default(false),
- })
- )
- .default([]),
-});
-
-export const sequenceData = z.strictObject({
- participants: z
- .array(
- z.strictObject({
- id: localId,
- label: nonEmpty,
- kind: z.enum(NODE_KINDS).optional(),
- color: chartColor.optional(),
- icon: icon.optional(),
- })
- )
- .min(2),
- messages: z
- .array(z.strictObject({ from: localId, to: localId, label: nonEmpty, dashed: z.boolean().default(false) }))
- .min(1),
-});
-
-export type GraphData = z.infer<typeof graphData>;
-export type GraphNode = GraphData["nodes"][number];
-export type SequenceData = z.infer<typeof sequenceData>;
-export type FlowData = { shape: "graph"; data: GraphData } | { shape: "sequence"; data: SequenceData };
-
-export const nodeColor = (n: { kind?: NodeKind; color?: ChartColor }): ChartColor =>
- n.color ?? (n.kind ? KIND_COLORS[n.kind] : "muted");
-
-/** The icon a node or participant shows, if any. */
-export const nodeIcon = (n: { kind?: NodeKind; icon?: FlowIcon | "none"; shape?: NodeShape }): FlowIcon | undefined => {
- if (n.icon === "none" || (n.shape && TEXT_SHAPES.includes(n.shape))) return undefined;
- return n.icon ?? (n.kind ? KIND_ICONS[n.kind] : undefined);
-};
-
-export const parseFlowData = (raw: unknown) =>
- typeof raw === "object" && raw !== null && "participants" in raw
- ? ({ shape: "sequence", result: sequenceData.safeParse(raw) } as const)
- : ({ shape: "graph", result: graphData.safeParse(raw) } as const);
-
-export const FLOW_TYPES = ["flow", "tree", "sequence"] as const;
-export type FlowType = (typeof FLOW_TYPES)[number];
-
-const duplicates = (ids: string[]) => ids.filter((id, i) => ids.indexOf(id) !== i);
-
-export const flowProblems = (flow: FlowData): string[] => {
- const problems: string[] = [];
- if (flow.shape === "sequence") {
- const ids = flow.data.participants.map(p => p.id);
- for (const id of new Set(duplicates(ids))) problems.push(`participant id "${id}" is used twice`);
- flow.data.messages.forEach((m, i) => {
- for (const end of ["from", "to"] as const) {
- if (!ids.includes(m[end])) problems.push(`"messages.${i}.${end}" names unknown participant "${m[end]}"`);
- }
- });
- return problems;
- }
- const { nodes, groups, edges } = flow.data;
- const nodeIds = nodes.map(n => n.id);
- const groupIds = groups.map(g => g.id);
- for (const id of new Set(duplicates([...nodeIds, ...groupIds]))) problems.push(`id "${id}" is used twice`);
- nodes.forEach((n, i) => {
- if (n.group && !groupIds.includes(n.group)) problems.push(`"nodes.${i}.group" names unknown group "${n.group}"`);
- if (n.icon && n.icon !== "none" && TEXT_SHAPES.includes(n.shape)) {
- problems.push(`"nodes.${i}" is a ${n.shape}, which holds text and draws no icon; remove "icon"`);
- }
- });
- groups.forEach((g, i) => {
- if (g.parent && !groupIds.includes(g.parent)) problems.push(`"groups.${i}.parent" names unknown group "${g.parent}"`);
- const seen = new Set([g.id]);
- for (let p = g.parent; p; p = groups.find(x => x.id === p)?.parent) {
- if (seen.has(p)) {
- problems.push(`group "${g.id}" is nested inside itself`);
- break;
- }
- seen.add(p);
- }
- if (!nodes.some(n => n.group === g.id) && !groups.some(x => x.parent === g.id)) problems.push(`group "${g.id}" is empty`);
- });
- edges.forEach((e, i) => {
- for (const end of ["from", "to"] as const) {
- if (!nodeIds.includes(e[end])) problems.push(`"edges.${i}.${end}" names unknown node "${e[end]}"`);
- }
- if (e.from === e.to) problems.push(`"edges.${i}" connects "${e.from}" to itself`);
- });
- return problems;
-};
-
-export const flowTypeProblems = (type: FlowType, flow: FlowData): string[] => {
- if (type === "sequence") return flow.shape === "sequence" ? [] : ['sequence needs "participants" and "messages"'];
- if (flow.shape !== "graph") return [`${type} needs "nodes" and "edges", this data has "participants"`];
- if (type === "flow") return [];
- const { nodes, edges } = flow.data;
- const incoming = new Map(nodes.map(n => [n.id, edges.filter(e => e.to === n.id).length]));
- const roots = nodes.filter(n => incoming.get(n.id) === 0);
- const problems = roots.length === 1 ? [] : [`tree needs exactly one root (a node with no incoming edge), this data has ${roots.length}`];
- for (const [id, count] of incoming) if (count > 1) problems.push(`tree nodes have one parent, "${id}" has ${count}`);
- if (edges.some(e => e.both)) problems.push("tree edges point one way; remove \"both\"");
- return problems;
-};
diff --git a/docs/lib/frames/kinds.ts b/docs/lib/frames/kinds.ts
deleted file mode 100644
index 733442cc..00000000
--- a/docs/lib/frames/kinds.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import type { z } from "zod";
-import { CHART_TYPE_NAMES, type ChartData, dataProblems, isChartType, parseChartData, typeProblems } from "@/lib/charts/schema";
-import { BOARD_TYPES, type BoardData, type BoardType, boardData, boardProblems, boardTypeProblems } from "./board";
-import { CHAT_TYPES, type ChatData, type ChatType, chatData, chatProblems, chatTypeProblems } from "./chat";
-import { FLOW_TYPES, type FlowData, type FlowType, flowProblems, flowTypeProblems, parseFlowData } from "./flow";
-import { SCHEMA_TYPES, type SchemaCardData, type SchemaType, schemaCardData, schemaProblems, schemaTypeProblems } from "./schema-card";
-import {
- TRANSCRIPT_TYPES,
- type TranscriptData,
- type TranscriptType,
- transcriptData,
- transcriptProblems,
- transcriptTypeProblems,
-} from "./transcript";
-
-const formatIssues = (error: z.ZodError): string[] =>
- error.issues.map(issue => {
- const field = issue.path.join(".");
- const message =
- issue.code === "unrecognized_keys"
- ? `unknown field${issue.keys.length > 1 ? "s" : ""} ${issue.keys.map(k => `"${k}"`).join(", ")}`
- : issue.code === "invalid_type" && issue.message.endsWith("received undefined")
- ? "is required"
- : issue.message;
- return field ? `"${field}" ${message}` : message;
- });
-
-/**
- * One entry per frame component. Each frame reads its data from its own JSON
- * file beside the content file, keyed by IDs local to that folder; the loader,
- * the validator and /dev/frames all work from this list.
- */
-export interface FrameKind<D> {
- key: "charts" | "transcripts" | "schemas" | "flows" | "boards" | "chats";
- component: string;
- file: string;
- /** Singular, for messages: `chart "scores" …`. */
- noun: string;
- parse: (raw: unknown) => { data: D; problems: [] } | { data: null; problems: string[] };
- types: readonly string[];
- typeProblems: (type: string, data: D) => string[];
-}
-
-const issues = (error: z.ZodError, suffix = "") => formatIssues(error).map(issue => issue + suffix);
-
-const zodKind = <D>(schema: z.ZodType<D>, check: (data: D) => string[]) => (raw: unknown) => {
- const result = schema.safeParse(raw);
- if (!result.success) return { data: null, problems: issues(result.error) };
- const problems = check(result.data);
- return problems.length ? { data: null, problems } : { data: result.data, problems: [] as [] };
-};
-
-export const CHART_KIND: FrameKind<ChartData> = {
- key: "charts",
- component: "ChartFrame",
- file: "charts.json",
- noun: "chart",
- parse: raw => {
- const { shape, result } = parseChartData(raw);
- if (!result.success) return { data: null, problems: issues(result.error, ` (read as ${shape} data)`) };
- const chart = { shape, data: result.data } as ChartData;
- const problems = dataProblems(chart);
- return problems.length ? { data: null, problems } : { data: chart, problems: [] };
- },
- types: CHART_TYPE_NAMES,
- typeProblems: (type, chart) => (isChartType(type) ? typeProblems(type, chart) : []),
-};
-
-export const TRANSCRIPT_KIND: FrameKind<TranscriptData> = {
- key: "transcripts",
- component: "TranscriptFrame",
- file: "transcripts.json",
- noun: "transcript",
- parse: zodKind(transcriptData, transcriptProblems),
- types: TRANSCRIPT_TYPES,
- typeProblems: (type, data) => transcriptTypeProblems(type as TranscriptType, data),
-};
-
-export const SCHEMA_KIND: FrameKind<SchemaCardData> = {
- key: "schemas",
- component: "SchemaFrame",
- file: "schemas.json",
- noun: "schema",
- parse: zodKind(schemaCardData, schemaProblems),
- types: SCHEMA_TYPES,
- typeProblems: (type, data) => schemaTypeProblems(type as SchemaType, data),
-};
-
-export const FLOW_KIND: FrameKind<FlowData> = {
- key: "flows",
- component: "FlowFrame",
- file: "flows.json",
- noun: "flow",
- parse: raw => {
- const { shape, result } = parseFlowData(raw);
- if (!result.success) return { data: null, problems: issues(result.error, ` (read as ${shape} data)`) };
- const flow = { shape, data: result.data } as FlowData;
- const problems = flowProblems(flow);
- return problems.length ? { data: null, problems } : { data: flow, problems: [] };
- },
- types: FLOW_TYPES,
- typeProblems: (type, data) => flowTypeProblems(type as FlowType, data),
-};
-
-export const BOARD_KIND: FrameKind<BoardData> = {
- key: "boards",
- component: "BoardFrame",
- file: "boards.json",
- noun: "board",
- parse: zodKind(boardData, boardProblems),
- types: BOARD_TYPES,
- typeProblems: (type, data) => boardTypeProblems(type as BoardType, data),
-};
-
-export const CHAT_KIND: FrameKind<ChatData> = {
- key: "chats",
- component: "ChatFrame",
- file: "chats.json",
- noun: "chat",
- parse: zodKind(chatData, chatProblems),
- types: CHAT_TYPES,
- typeProblems: (type, data) => chatTypeProblems(type as ChatType, data),
-};
-
-export const FRAME_KINDS = [CHART_KIND, TRANSCRIPT_KIND, SCHEMA_KIND, FLOW_KIND, BOARD_KIND, CHAT_KIND] as const;
-export const FRAME_FILES: readonly string[] = FRAME_KINDS.map(k => k.file);
-
-export const FRAME_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
diff --git a/docs/lib/frames/schema-card.ts b/docs/lib/frames/schema-card.ts
deleted file mode 100644
index 63895404..00000000
--- a/docs/lib/frames/schema-card.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { z } from "zod";
-import { chartColor } from "@/lib/charts/schema";
-
-// Data for SchemaFrame: objects with named fields, such as an LLM test case.
-// Named schema-card.ts so it isn't mistaken for a zod schema module.
-
-const nonEmpty = z.string().trim().min(1);
-const objectId = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "use lowercase-kebab-case object ids");
-/** `"<object id>.<field name>"`. */
-const fieldRef = z.string().regex(/^[a-z0-9-]+\.[^.\s]+$/, 'refer to a field as "<object id>.<field name>"');
-
-const field = z.strictObject({
- name: nonEmpty,
- optional: z.boolean().default(false),
- example: nonEmpty.optional(),
- note: nonEmpty.optional(),
-});
-
-export const schemaCardData = z.strictObject({
- objects: z
- .array(
- z.strictObject({
- id: objectId,
- title: nonEmpty,
- subtitle: nonEmpty.optional(),
- color: chartColor.default("blue"),
- fields: z.array(field).min(1),
- })
- )
- .min(1),
- highlights: z
- .array(z.strictObject({ label: nonEmpty, color: chartColor, fields: z.array(fieldRef).min(1) }))
- .default([]),
- links: z.array(z.strictObject({ from: fieldRef, to: fieldRef })).default([]),
-});
-
-export type SchemaCardData = z.infer<typeof schemaCardData>;
-export type SchemaObject = SchemaCardData["objects"][number];
-export type SchemaField = SchemaObject["fields"][number];
-
-export const SCHEMA_TYPES = ["card", "compare", "match"] as const;
-export type SchemaType = (typeof SCHEMA_TYPES)[number];
-
-export const fieldRefOf = (object: SchemaObject, field: SchemaField) => `${object.id}.${field.name}`;
-
-export const schemaProblems = (data: SchemaCardData): string[] => {
- const problems: string[] = [];
- const ids = data.objects.map(o => o.id);
- if (new Set(ids).size !== ids.length) problems.push("object ids must be unique");
- const refs = new Set<string>();
- data.objects.forEach((o, i) => {
- const names = o.fields.map(f => f.name);
- if (new Set(names).size !== names.length) problems.push(`"objects.${i}" has duplicate field names`);
- for (const f of o.fields) refs.add(fieldRefOf(o, f));
- });
- const check = (ref: string, at: string) => {
- if (!refs.has(ref)) problems.push(`${at} names unknown field "${ref}"`);
- };
- data.highlights.forEach((h, i) => h.fields.forEach((ref, j) => check(ref, `"highlights.${i}.fields.${j}"`)));
- data.links.forEach((l, i) => {
- check(l.from, `"links.${i}.from"`);
- check(l.to, `"links.${i}.to"`);
- });
- return problems;
-};
-
-export const schemaTypeProblems = (type: SchemaType, data: SchemaCardData): string[] => {
- const n = data.objects.length;
- if (type === "card") return n === 1 ? [] : [`card shows exactly 1 object, this data has ${n}`];
- // Highlights are drawn as boxes with lines to the fields they read, around a single object.
- const highlights = data.highlights.length ? [`${type} doesn't draw highlights; use a card, or remove "highlights"`] : [];
- if (type === "compare") return [...(n >= 2 && n <= 4 ? [] : [`compare needs 2 to 4 objects, this data has ${n}`]), ...highlights];
- const problems = n === 2 ? [...highlights] : [`match needs exactly 2 objects, this data has ${n}`, ...highlights];
- if (!data.links.length) problems.push('match needs at least one entry in "links"');
- const [left, right] = data.objects;
- data.links.forEach((l, i) => {
- if (left && right && !(l.from.startsWith(`${left.id}.`) && l.to.startsWith(`${right.id}.`))) {
- problems.push(`"links.${i}" must go from "${left.id}" to "${right.id}"`);
- }
- });
- return problems;
-};
diff --git a/docs/lib/frames/store.ts b/docs/lib/frames/store.ts
deleted file mode 100644
index 2d239bf9..00000000
--- a/docs/lib/frames/store.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-import type { ChartData } from "@/lib/charts/schema";
-import type { BoardData } from "./board";
-import type { ChatData } from "./chat";
-import type { FlowData } from "./flow";
-import { BOARD_KIND, CHART_KIND, CHAT_KIND, FLOW_KIND, type FrameKind, SCHEMA_KIND, TRANSCRIPT_KIND } from "./kinds";
-import type { SchemaCardData } from "./schema-card";
-import type { TranscriptData } from "./transcript";
-
-export interface FrameData {
- charts: Record<string, ChartData>;
- transcripts: Record<string, TranscriptData>;
- schemas: Record<string, SchemaCardData>;
- flows: Record<string, FlowData>;
- boards: Record<string, BoardData>;
- chats: Record<string, ChatData>;
-}
-
-export const EMPTY_FRAME_DATA: FrameData = { charts: {}, transcripts: {}, schemas: {}, flows: {}, boards: {}, chats: {} };
-
-/** Frame IDs are local to the JSON file beside the content file. */
-export const loadFrameFile = <D>(kind: FrameKind<D>, sourceFile: string): Record<string, D> => {
- const file = path.join(path.dirname(sourceFile), kind.file);
- if (!fs.existsSync(file)) return {};
- const raw: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
- throw new Error(`${file}: expected an object keyed by ${kind.noun} IDs`);
- }
- return Object.fromEntries(
- Object.entries(raw).map(([id, value]) => {
- const { data, problems } = kind.parse(value);
- if (!data) throw new Error(`${file}: invalid ${kind.noun} "${id}": ${problems.join("; ")}`);
- return [id, data];
- })
- );
-};
-
-export const loadFrameData = (sourceFile: string): FrameData => ({
- charts: loadFrameFile(CHART_KIND, sourceFile),
- transcripts: loadFrameFile(TRANSCRIPT_KIND, sourceFile),
- schemas: loadFrameFile(SCHEMA_KIND, sourceFile),
- flows: loadFrameFile(FLOW_KIND, sourceFile),
- boards: loadFrameFile(BOARD_KIND, sourceFile),
- chats: loadFrameFile(CHAT_KIND, sourceFile),
-});
diff --git a/docs/lib/frames/transcript.ts b/docs/lib/frames/transcript.ts
deleted file mode 100644
index 2775e83e..00000000
--- a/docs/lib/frames/transcript.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { z } from "zod";
-
-const nonEmpty = z.string().trim().min(1);
-const index = z.number().int().min(0);
-
-export const TRANSCRIPT_ROLES = ["user", "assistant", "system", "tool"] as const;
-
-const turn = z.strictObject({
- role: z.enum(TRANSCRIPT_ROLES),
- text: nonEmpty,
- /** Overrides the role's label, e.g. "Command Bot". */
- name: nonEmpty.optional(),
- verdict: z.enum(["pass", "fail"]).optional(),
-});
-
-export const transcriptData = z.strictObject({
- /** Label for every assistant turn that has no name of its own. */
- speaker: nonEmpty.optional(),
- turns: z.array(turn).default([]),
- panels: z.array(z.strictObject({ title: nonEmpty, turns: z.array(turn).min(1) })).default([]),
- ranges: z.array(z.strictObject({ from: index, to: index, label: nonEmpty })).default([]),
- pointers: z.array(z.strictObject({ turn: index, label: nonEmpty })).default([]),
- judge: z
- .strictObject({
- label: nonEmpty.default("LLM-as-a-Judge"),
- prompt: nonEmpty,
- verdict: nonEmpty,
- verdictLabel: nonEmpty.default("Verdict"),
- })
- .optional(),
-});
-
-export type TranscriptData = z.infer<typeof transcriptData>;
-export type TranscriptTurn = TranscriptData["turns"][number];
-
-export const TRANSCRIPT_TYPES = ["chat", "turns", "judge", "compare"] as const;
-export type TranscriptType = (typeof TRANSCRIPT_TYPES)[number];
-
-export const roleLabel = (turn: TranscriptTurn, speaker?: string): string =>
- turn.name ??
- (turn.role === "assistant" ? (speaker ?? "Assistant") : turn.role === "user" ? "User" : turn.role === "tool" ? "Tool" : "System");
-
-export const transcriptProblems = (data: TranscriptData): string[] => {
- const problems: string[] = [];
- if (!data.turns.length && !data.panels.length) problems.push('needs "turns" or "panels"');
- const last = data.turns.length - 1;
- data.ranges.forEach((r, i) => {
- if (r.from > r.to) problems.push(`"ranges.${i}" starts after it ends`);
- if (r.to > last) problems.push(`"ranges.${i}.to" is turn ${r.to}, but the last turn is ${last}`);
- });
- data.pointers.forEach((p, i) => {
- if (p.turn > last) problems.push(`"pointers.${i}.turn" is turn ${p.turn}, but the last turn is ${last}`);
- });
- return problems;
-};
-
-export const transcriptTypeProblems = (type: TranscriptType, data: TranscriptData): string[] => {
- if (type === "chat") {
- return data.turns.some(t => t.role === "user") && data.turns.some(t => t.role === "assistant")
- ? []
- : ["chat needs at least one user turn and one assistant turn"];
- }
- if (type === "turns") return data.turns.length >= 2 ? [] : [`turns needs at least 2 turns, this data has ${data.turns.length}`];
- if (type === "judge") return data.judge ? [] : ['judge needs a "judge" with a prompt and a verdict'];
- return data.panels.length >= 2 ? [] : [`compare needs at least 2 panels, this data has ${data.panels.length}`];
-};
diff --git a/docs/lib/post-folders.mjs b/docs/lib/post-folders.mjs
index f5ad2324..61616a75 100644
--- a/docs/lib/post-folders.mjs
+++ b/docs/lib/post-folders.mjs
@@ -12,7 +12,6 @@ export const MONTH_FOLDER = new RegExp(`^\\d{4}_(${MONTHS.join("|")})$`);
export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export const POST_FILE = /^(\d{4}_[a-z]{3})\/([^/]+)\/article\.mdx$/;
export const COVER_FILE = /^cover\.(webp|png|jpe?g|gif)$/;
-export const FRAME_FILES = ["boards.json", "flows.json", "charts.json", "schemas.json", "chats.json", "transcripts.json"];
/** Slugs for a blog file path relative to `content/blog`; `undefined` keeps fumadocs' default. */
export function postSlugs(file) {
diff --git a/docs/lib/section.tsx b/docs/lib/section.tsx
index 53f974d7..88ae404f 100644
--- a/docs/lib/section.tsx
+++ b/docs/lib/section.tsx
@@ -1,4 +1,3 @@
-import path from "node:path";
import type { ReactNode } from "react";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
@@ -15,8 +14,6 @@ import {
import { createRelativeLink } from "fumadocs-ui/mdx";
import { baseOptions } from "@/lib/layout.shared";
import { getMDXComponents } from "@/components/mdx";
-import { createFrameComponents } from "@/components/frames";
-import { loadFrameData } from "@/lib/frames/store";
import { gitConfig } from "@/lib/shared";
import { getPageContributors } from "@/lib/contributors";
import { getPageDescription } from "@/lib/source";
@@ -213,9 +210,6 @@ export function createSection(config: SectionConfig) {
<MDX
components={getMDXComponents({
a: createRelativeLink(source, page),
- ...createFrameComponents(
- loadFrameData(path.join(process.cwd(), contentDir, page.path)),
- ),
})}
/>
</DocsBody>
diff --git a/docs/package.json b/docs/package.json
index 696d544d..be1a498a 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -16,7 +16,6 @@
"postinstall": "fumadocs-mdx"
},
"dependencies": {
- "@dagrejs/dagre": "^3.1.1",
"@radix-ui/react-popover": "1.1.15",
"fumadocs-core": "16.8.1",
"fumadocs-mdx": "14.3.1",
@@ -33,7 +32,6 @@
"rehype-katex": "^7.0.1",
"remark-directive": "^4.0.0",
"remark-math": "^6.0.0",
- "simple-icons": "16.35.0",
"tailwind-merge": "^3.5.0"
},
"devDependencies": {
diff --git a/docs/scripts/validate-content.mjs b/docs/scripts/validate-content.mjs
index 85480c36..917e3da6 100644
--- a/docs/scripts/validate-content.mjs
+++ b/docs/scripts/validate-content.mjs
@@ -5,7 +5,7 @@
*/
import fs from "node:fs";
import path from "node:path";
-import { BLOG_DIR, COVER_FILE, FRAME_FILES, MONTH_FOLDER, SLUG, monthFolder } from "../lib/post-folders.mjs";
+import { BLOG_DIR, COVER_FILE, MONTH_FOLDER, SLUG, monthFolder } from "../lib/post-folders.mjs";
import { IMAGE_FILE, IMAGE_FOLDERS, INDEX_FILE, MEDIA_DIR, NAME, indexFolders, loadLibrary } from "../lib/media/library.mjs";
const ROOT = process.cwd();
@@ -42,8 +42,8 @@ for (const entry of fs.readdirSync(BLOG_DIR, { withFileTypes: true })) {
if (!files.some((f) => f.name === "article.mdx")) fail(dir, "missing article.mdx");
if (files.filter((f) => COVER_FILE.test(f.name)).length > 1) fail(dir, "a post has at most one cover");
for (const f of files) {
- const ok = f.isFile() && (f.name === "article.mdx" || COVER_FILE.test(f.name) || FRAME_FILES.includes(f.name));
- if (!ok) fail(path.join(dir, f.name), `a post folder holds only article.mdx, one cover.* and ${FRAME_FILES.join(", ")}`);
+ const ok = f.isFile() && (f.name === "article.mdx" || COVER_FILE.test(f.name));
+ if (!ok) fail(path.join(dir, f.name), "a post folder holds only article.mdx and one cover.*");
}
posts.push({ month: entry.name, slug: post.name, file: path.join(dir, "article.mdx") });
}
diff --git a/docs/yarn.lock b/docs/yarn.lock
index 6f810afe..7498d74c 100644
--- a/docs/yarn.lock
+++ b/docs/yarn.lock
@@ -50,18 +50,6 @@
resolved "https://registry.npmjs.org/@chevrotain/utils/-/utils-12.0.0.tgz"
integrity sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==
-"@dagrejs/dagre@^3.1.1":
- version "3.1.1"
- resolved "https://registry.yarnpkg.com/@dagrejs/dagre/-/dagre-3.1.1.tgz#06de3070d584886b8820aaceeefc45a553cf2b97"
- integrity sha512-zroZB1dFOFiGgv4Xcrn1DckB1o4aOikPqD2NDQPV0WM//CXGcS6xiD0rNkqHmw6FEg4tabt4nxPLwgCWT+Vb2A==
- dependencies:
- "@dagrejs/graphlib" "4.0.5"
-
-"@dagrejs/[email protected]":
- version "4.0.5"
- resolved "https://registry.yarnpkg.com/@dagrejs/graphlib/-/graphlib-4.0.5.tgz#1ae7a93a4640a9e50117439d23327e27d6b698d3"
- integrity sha512-7xrBTqIts3o+PMUZX97wSc+7TUbW+/rULzGNCTP6yooNVDXbzw4Wutg/H/xOutTB/c/k0YqOAavgPh4/Zk9PFA==
-
"@emnapi/core@^1.8.1":
version "1.10.0"
resolved "https://registry.yarnpkg.com/@emnapi/core/-/core-1.10.0.tgz#380ccc8f2412ea22d1d972df7f8ee23a3b9c7467"
@@ -3765,11 +3753,6 @@ shiki@^4.0.2:
"@shikijs/vscode-textmate" "^10.0.2"
"@types/hast" "^3.0.4"
- version "16.35.0"
- resolved "https://registry.yarnpkg.com/simple-icons/-/simple-icons-16.35.0.tgz#78db83dd7f5ae0212b68d05c2ae7797e5d864921"
- integrity sha512-TCfl/2+GTrx0nCo4pEWGvxhOb8c6NsqOU1OpwjtF4lwJAthB8IYVD0fuIMjLMg6JFuG1YBO0t1iETQqJLqkoJA==
-
"source-map-js@>=0.6.2 <2.0.0", source-map-js@^1.0.2, source-map-js@^1.2.1:
version "1.2.1"
resolved "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz"