visuals
HTML pages (html_preview, html_render) and native inline charts, positioned diagrams and sortable tables in agent replies.
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/visuals@0.2.2
Visuals — official plugin
divergence/visuals provides publish_visual for interactive, native visual replies. It ships enabled on a fresh install; an existing install keeps the choice it has, and users can turn it off or on in Settings → Plugins. It starts only when a reply first contains one of its fences and loads Pele only on the first Mermaid fence, so a chat without fences pays nothing. Its only requested permission is tools.provide.
HTML pages (T3 Code's html_preview and html_render)
html.ts holds T3's contract (pingdotgg/t3code b24f0fbb): the tool names, descriptions, limits (HTML 1–512000 UTF-16 units, title 1–200, preview width 240–1600 with 728 by default, frame height 80–2000), the result shapes and messages, and the theme bootstrap with Divergence's colours. Both tools are direct, so in code mode they stay tools of their own and the preview's PNG reaches the agent as an MCP image part.
html_previewsends the themed page tohost/web.preview. With a web view it answers T3's metadata as text and structured content plus the PNG. Without one it is an error,HtmlBackendUnavailable: <raw reason>, with no image, and no screenshot is made up.html_rendersaves the agent's page unchanged as ahtmlv1 transcript artifact (the host stamps the owner) and answers T3'shtmlRenderreference and message. Measuredheightsare not supplied: the frame follows the live page's own height, and the agent's height shows only until the page has measured itself.- Inline (
html-view.ts) the page is live (ui.webDocument): borderless in the reply, as wide as the column and as tall as the page, with one small glass Open in panel control. The panel is a detail-pane tab (thedivergence/tabsservice): the page live again, its Source, Copy and Save (kernel/copy_text,kernel/save_text, both after a click).
The renderer is the system's web view (crates/host/src/web): WKWebView on macOS, so a page behaves as it would in Safari, WebView2 on Windows, as in Edge, and WebKitGTK on Linux, which the app draws itself. The difference from T3 is that pages are offline: remote URLs and local image paths never load (missingImages lists the paths a page names). Where the web view cannot start, the page says why and its source, copy and save still work.
Version 2 supports responsive multi-panel compositions: bar (grouped/stacked/ percent; horizontal/vertical), line, area, scatter/bubble, pie/donut, heatmap, histogram, range/timeline, waterfall and boxplot, plus metrics, text, typed tables and positioned diagrams. document.ts defines the strict, bounded JSON schema; rules.md is the agent-facing reference. Version 1 documents still replay.
Rendering and interaction
Rust/GPUI draws every shape, label, control and floating tooltip. A pinned, DOM-free D3 math subset computes scales, numeric/UTC ticks and paths inside QuickJS; there is no browser, JavaScript UI execution, graph auto-layout, network, file, process or plugin-storage access. math.LICENSES.txt includes provenance and licenses; scripts/bundle-visuals-math.mjs reproduces the readable bundle.
Charts use the native canvas's onResize({width,height}) logical-pixel measurement, not a scaled viewBox. Text remains readable as panels grow or wrap. Compact legends keep original domains, colors and percentage denominators when hidden. Null breaks paths and stays explicitly missing in shared bar inspection.
Hover opens a clamped floating tooltip; click pins/unpins. Arrow keys, Home/End traverse observations, Enter/Space pin, Escape clears inspection. In the expanded overlay Escape unpins first, then closes. Tables retain stable raw row identity, sort nulls last in either direction, paginate and expose full selected values. Diagram node details remain accessible through a native picker.
State and cached geometry belong to each artifact's ctx.state, with separate panels and inline/expanded inspection. Hover does not recompute paths. Native resize reports are change-only and coalesced off-paint. No JavaScript frame loop or render-time notification runs.
Persistence and compatibility
The host owns immutable transcript artifacts. ctx.artifacts.publish persists the complete document independently of the surrounding tool result, including discarded acknowledgements and later code-mode errors. The plugin registers removable visual renderers for versions 1 and 2; Source retains original input and Data retains all raw values, including hidden series and nulls.
This plugin requires the updated native host and canvas resize API. Older hosts without artifact support fail with an explicit update message. Invalid persisted documents keep their readable summary and expose a validation error.
Verification
node --import ./plugins/testing/register.mjs --test plugins/visuals/*.test.ts
pnpm -C plugins typecheck
pnpm -C plugins exec prettier --check 'visuals/**/*.{ts,json,md}'
Geometry tests use asymmetric data and independent numeric expectations; view tests exercise real native element factories and handlers. Native desktop checks and app-owned Metal captures supplement these tests; they do not use a browser.
Permissions in 0.2.2
Files
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import type { CanvasCommand } from "divergence";
import {
DOCUMENT_LIMITS,
legacyVisualDocumentSchema,
panelCost,
richChartSchema,
richVisualDocumentSchema,
} from "./document.ts";
import type { RichChart } from "./document.ts";
import { chartDataTable, chartScene, formatValue, inspectAt, inspectionCommands, PALETTE } from "./plot.ts";
import type { ChartScene, Hit } from "./plot.ts";
import { dataTable } from "./table.ts";
import { artifact, context, fire, node } from "./testing.ts";
import { renderArtifact } from "./views.ts";
const chart = (input: unknown): RichChart => richChartSchema.parse({ kind: "chart", ...(input as object) });
const scene = (input: unknown, hidden: number[] = []) => chartScene(chart(input), 640, 320, hidden);
const near = (a: number, b: number, epsilon = 1e-8) => assert.ok(Math.abs(a - b) <= epsilon, `${a} ≠ ${b}`);
const find = (s: ChartScene, id: string) => {
const i = s.items.find((i) => i.id === id);
assert.ok(i, id);
return i;
};
const hitRect = (s: ChartScene, id: string) => {
const hit = find(s, id).hit;
assert.equal(hit.kind, "rect");
return hit as Extract<Hit, { kind: "rect" }>;
};
const paths = (s: ChartScene) => s.commands.filter((c): c is Extract<CanvasCommand, { op: "path" }> => c.op === "path");
const bars = {
chart: "bar",
x: { type: "category", values: ["Alpha", "Beta", "Gamma"] },
series: [
{ name: "Same", values: [2, -3, null] },
{ name: "Same", values: [6, 1, -1] },
],
};
const percent = {
chart: "bar",
stack: "percent",
x: { type: "category", values: ["One", "Zero", "Null"] },
series: [
{ name: "Small", values: [1, 0, null] },
{ name: "Large", values: [3, 0, null] },
],
};
const linear = {
chart: "line",
x: { type: "number", values: [1, 2, 8] },
series: [{ name: "Growth", values: [0, 2, 8] }],
};
const DAY = 86_400_000,
T = Date.UTC(2024, 2, 9);
test("formatting is deterministic, bounded, unit-aware and has no Intl dependency", () => {
assert.equal(formatValue(1234.567), "1234.57");
assert.equal(formatValue(5), "5");
assert.equal(formatValue(-0), "0");
assert.equal(formatValue(0.125, { style: "percent" }), "12.5%");
assert.equal(formatValue(-1_234_567, { style: "compact", precision: 1, unit: "requests" }), "-1.2M requests");
assert.equal(formatValue(1e12, { style: "compact" }), "1T");
assert.equal(formatValue(12, { style: "currency", currency: "EUR" }), "EUR 12.00");
assert.equal(formatValue(4 / 3, { style: "number", precision: 6 }), "1.333333");
assert.equal(formatValue(1e-9), "1e-9");
assert.equal(formatValue(-1e-5, { style: "number", precision: 3 }), "-1.000e-5");
assert.equal(formatValue(0, { style: "number", precision: 6 }), "0.000000");
});
test("continuous axes keep regular intervals instead of skipping middle ticks", () => {
const bar = chartScene(
chart({
chart: "bar",
x: { type: "category", values: ["Low", "High"] },
series: [{ name: "Value", values: [-7, 21] }],
}),
640,
250,
);
assert.deepEqual(
bar.commands
.filter((c) => c.op === "text" && c.align === "right")
.map((c) => (c as Extract<CanvasCommand, { op: "text" }>).text),
["-10", "0", "10", "20", "30"],
);
for (const time of [false, true]) {
const line = chartScene(
chart({
chart: "line",
x: { type: time ? "time" : "number", values: time ? [T, T + 4 * DAY] : [0, 8] },
series: [{ name: "Value", values: [1, 3] }],
}),
time ? 640 : 470,
250,
);
const ticks = line.commands.filter((c) => c.op === "text" && c.y === line.plot.top + line.plot.height + 13);
assert.deepEqual(
ticks.map((c) => (c as Extract<CanvasCommand, { op: "text" }>).text),
time ? ["03-09", "03-10", "03-11", "03-12", "03-13"] : ["0", "2", "4", "6", "8"],
);
}
});
test("short category labels fit a narrow panel without silently omitting middle categories", () => {
const categories = ["Loss", "Gain", "Missing", "Recovery"];
const s = chartScene(
chart({
chart: "bar",
x: { type: "category", values: categories },
series: [{ name: "Value", values: [-7, 21, null, 12] }],
}),
316,
250,
);
assert.deepEqual(
s.commands
.filter((c) => c.op === "text" && c.y === s.plot.top + s.plot.height + 13)
.map((c) => (c as Extract<CanvasCommand, { op: "text" }>).text),
categories,
);
});
test("grouped bars use original slots, exact nulls and real rectangle hits", () => {
const s = scene(bars),
p = s.plot,
unit = p.height / 10; // nice domain [-4, 6]
const a = hitRect(s, "series:0:value:0"),
b = hitRect(s, "series:1:value:0");
near(a.x, p.left + p.width / 30);
near(a.width, (p.width / 3) * 0.4);
near(b.x - a.x, a.width);
near(a.height, 2 * unit);
near(a.y, p.top + 4 * unit);
const negative = hitRect(s, "series:0:value:1");
near(negative.y, p.top + 6 * unit);
near(negative.height, 3 * unit);
assert.ok(!s.items.some((i) => i.id === "series:0:value:2"));
assert.equal(inspectAt(s, p.left, p.top), null); // not a guessed category
assert.equal(inspectAt(s, a.x + a.width / 2, a.y + a.height / 2)?.id, "series:0:value:0");
const hidden = scene(bars, [0]);
assert.deepEqual(hitRect(hidden, "series:1:value:0"), b);
assert.deepEqual(hidden.legend, s.legend);
assert.deepEqual(chartDataTable(chart(bars)).rows, [
["Alpha", 2, 6],
["Beta", -3, 1],
["Gamma", null, -1],
]);
assert.deepEqual(
chartDataTable(chart(bars)).columns.map((c) => c.key),
["x", "series_0", "series_1"],
);
});
test("horizontal bars swap quantitative/category directions and keep sign baselines", () => {
const s = scene({ ...bars, orientation: "horizontal" }),
p = s.plot;
const a = hitRect(s, "series:0:value:0"),
neg = hitRect(s, "series:0:value:1");
near(a.x, p.left + p.width * 0.4);
near(a.width, p.width * 0.2);
near(neg.x + neg.width, a.x);
near(neg.width, p.width * 0.3);
near(a.height, (p.height / 3) * 0.4);
near(a.y, p.top + p.height / 30);
});
test("diverging stacked bars keep independent positive and negative accumulators", () => {
const input = {
chart: "bar",
stack: "stacked",
x: { type: "category", values: ["Mixed", "Other"] },
series: [
{ name: "First", values: [2, -1] },
{ name: "Second", values: [-3, 4] },
{ name: "Third", values: [5, -2] },
{ name: "Fourth", values: [-1, null] },
],
};
const s = scene(input),
p = s.plot,
u = p.height / 12; // nice [-4,8]
near(hitRect(s, "series:0:value:0").y, p.top + 6 * u);
near(hitRect(s, "series:2:value:0").y, p.top + u);
near(hitRect(s, "series:2:value:0").height, 5 * u);
near(hitRect(s, "series:1:value:0").y, p.top + 8 * u);
near(hitRect(s, "series:3:value:0").y, p.top + 11 * u);
const hidden = scene(input, [0, 1]);
assert.deepEqual(hitRect(hidden, "series:2:value:0"), hitRect(s, "series:2:value:0"));
});
test("percent bars retain original denominators on hiding and make zero totals explicit", () => {
const s = scene(percent),
h = scene(percent, [1]);
near(hitRect(h, "series:0:value:0").height, s.plot.height / 4);
assert.deepEqual(hitRect(h, "series:0:value:0"), hitRect(s, "series:0:value:0"));
assert.equal(find(h, "series:0:value:0").rows[1].value, "25%");
assert.equal(s.commands.filter((c) => c.op === "text" && c.text === "No total").length, 1);
assert.equal(s.commands.filter((c) => c.op === "text" && c.text === "Missing").length, 1);
assert.ok(
scene({
...percent,
x: { type: "category", values: ["Zero"] },
series: [{ name: "None", values: [0] }],
}).empty?.includes("undefined"),
);
assert.deepEqual(chartDataTable(chart(percent)).rows, [
["One", 1, 3],
["Zero", 0, 0],
["Null", null, null],
]);
});
test("numeric line spacing, nearest-x slabs and step-after geometry are not ordinal", () => {
const s = scene(linear),
p = s.plot;
near(find(s, "x:0").x, p.left);
near(find(s, "x:1").x, p.left + p.width / 7);
near(find(s, "x:2").x, p.left + p.width);
const d = paths(s)[0].d;
assert.deepEqual(
d.map((v) => v[0]),
["moveTo", "lineTo", "lineTo"],
);
assert.equal(inspectAt(s, p.left + p.width * 0.45, p.top + 1)?.id, "x:1");
assert.equal(inspectAt(s, p.left + p.width * 0.6, p.top + 1)?.id, "x:2");
const step = paths(scene({ ...linear, interpolation: "step" }))[0].d;
assert.deepEqual(
step.map((v) => v[0]),
["moveTo", "lineTo", "lineTo", "lineTo", "lineTo"],
);
near(step[1][1] as number, find(s, "x:1").x);
near(step[1][2] as number, find(s, "x:0").y);
near(step[2][2] as number, find(s, "x:1").y);
});
test("UTC lines span irregular dates across DST independently of local time", () => {
const input = { ...linear, x: { type: "time", values: [T, T + DAY, T + 8 * DAY] } };
const s = scene(input),
p = s.plot;
near(find(s, "x:1").x, p.left + p.width / 8);
assert.equal(find(s, "x:1").label, "2024-03-10T00:00:00.000Z");
assert.deepEqual(chartDataTable(chart(input)).rows, [
[T, 0],
[T + DAY, 2],
[T + 8 * DAY, 8],
]);
assert.equal(chartDataTable(chart(input)).columns[0].type, "number");
});
test("nullable category lines and areas break both edges, never bridging a gap to zero", () => {
const input = {
chart: "line",
x: { type: "category", values: ["A", "B", "C", "D", "E"] },
series: [{ name: "Observed", values: [2, 6, null, 4, 8] }],
};
const s = scene(input),
d = paths(s)[0].d;
assert.deepEqual(
d.map((v) => v[0]),
["moveTo", "lineTo", "moveTo", "lineTo"],
);
assert.equal(inspectAt(s, s.plot.left + s.plot.width / 2, s.plot.top + 2), null);
for (const interpolation of ["linear", "step"]) {
const a = scene({ ...input, chart: "area", interpolation });
const path = paths(a)[0].d;
assert.equal(path.filter((v) => v[0] === "moveTo").length, 2);
assert.equal(path.filter((v) => v[0] === "close").length, 2);
assert.ok(!path.some((v) => v[0] !== "close" && v[1] === a.plot.left + a.plot.width / 2));
assert.deepEqual(chartDataTable(chart({ ...input, chart: "area" })).rows[2], ["C", null]);
}
});
test("linear and stepped areas use real numeric/time x and stable signed stacks", () => {
for (const type of ["number", "time"])
for (const interpolation of ["linear", "step"]) {
const input = {
chart: "area",
stack: "stacked",
interpolation,
x: { type, values: type === "time" ? [T, T + DAY, T + 7 * DAY] : [1, 2, 8] },
series: [
{ name: "Base", values: [2, -2, 4] },
{ name: "Upper", values: [3, -3, 1] },
],
};
const s = scene(input),
h = scene(input, [0]);
assert.deepEqual(paths(h)[0].d, paths(s)[1].d);
const d = paths(s)[1].d,
u = s.plot.height / 12; // nice [-6,6]
near(d[0][2] as number, s.plot.top + u); // 2+3 = 5
const bottomOfNegative = interpolation === "linear" ? d[1] : d[2];
near(bottomOfNegative[2] as number, s.plot.top + 11 * u); // -2 + -3 = -5
near(find(s, "x:1").x, s.plot.left + s.plot.width / 7);
}
});
test("percent area keeps missing gaps and original totals/upper offsets after hiding", () => {
const input = { ...percent, chart: "area", interpolation: "step" };
const s = scene(input),
h = scene(input, [0]);
assert.deepEqual(paths(h)[0].d, paths(s)[1].d);
const d = paths(h)[0].d;
near(d[0][2] as number, h.plot.top);
near(d[1][2] as number, h.plot.top + h.plot.height * 0.75);
assert.equal(find(h, "x:1").rows.at(-1)?.value, "No total (empty)");
assert.ok(scene({ ...input, series: [{ name: "No total", values: [0, 0, null] }] }).empty?.includes("undefined"));
});
test("scatter/bubble sizes encode area, spacing is numerical and hidden domains/sizes stay fixed", () => {
const input = {
chart: "scatter",
series: [
{
name: "Small",
points: [
{ x: 1, y: 2, size: 1, label: "Point A" },
{ x: 2, y: 3, size: 4 },
],
},
{
name: "Large",
points: [
{ x: 8, y: 10, size: 16 },
{ x: 4, y: 8, size: 0 },
],
},
],
};
const s = scene(input),
h = scene(input, [1]);
const circles = s.commands.filter((c): c is Extract<CanvasCommand, { op: "roundRect" }> => c.op === "roundRect");
near(circles[1].radius! ** 2 / circles[0].radius! ** 2, 4);
near(circles[2].radius! ** 2 / circles[0].radius! ** 2, 16);
assert.equal(circles[3].radius, 0);
near(find(s, "series:0:point:1").x - find(s, "series:0:point:0").x, (s.plot.width - 40) / 7);
assert.deepEqual(find(h, "series:0:point:0"), find(s, "series:0:point:0"));
const a = find(s, "series:0:point:0");
assert.equal(inspectAt(s, a.x, a.y)?.id, a.id);
assert.equal(inspectAt(s, a.x + 30, a.y), null);
assert.deepEqual(chartDataTable(chart(input)).rows[0], [0, "Small", 0, "Point A", 1, 2, 1]);
assert.deepEqual(
chartDataTable(chart({ chart: "scatter", series: [{ name: "Plain", points: [{ x: 2, y: -1 }] }] })).rows,
[[0, "Plain", 0, null, 2, -1, null]],
);
});
test("nearest actual point wins over larger overlapping bubbles; equal distances use topmost order", () => {
const s = scene({
chart: "scatter",
series: [
{
name: "Points",
points: [
{ x: 0, y: 0, size: 16 },
{ x: 0.01, y: 0, size: 1 },
{ x: 1, y: 1, size: 1 },
{ x: 0.01, y: 0, size: 1 },
],
},
],
});
const first = find(s, "series:0:point:0"),
second = find(s, "series:0:point:1");
assert.equal(inspectAt(s, first.x, first.y)?.id, first.id);
assert.equal(inspectAt(s, second.x, second.y)?.id, "series:0:point:3");
assert.equal(inspectAt(s, first.x + 20.01, first.y + 20.01), null); // not a square bubble hit
});
test("pie order/percentages stay original; wedge edges and empty zero-total state are explicit", () => {
const input = {
chart: "pie",
parts: [
{ label: "Quarter", value: 1 },
{ label: "Remainder", value: 3 },
{ label: "Zero", value: 0 },
],
};
const s = scene(input),
h = scene(input, [1]),
hit = find(s, "part:0").hit;
assert.equal(hit.kind, "sector");
if (hit.kind !== "sector") return;
near(hit.startAngle, 0);
near(hit.endAngle, Math.PI / 2);
assert.deepEqual(find(h, "part:0"), find(s, "part:0"));
assert.equal(find(h, "part:0").rows[1].value, "25%");
assert.equal(inspectAt(s, hit.cx, hit.cy - hit.outerRadius * 0.8)?.id, "part:0");
assert.equal(inspectAt(s, hit.cx + hit.outerRadius * 0.8, hit.cy)?.id, "part:1");
assert.equal(inspectAt(h, hit.cx + hit.outerRadius * 0.8, hit.cy), null);
assert.equal(inspectAt(s, hit.cx, hit.cy - hit.outerRadius - 1), null);
assert.ok(scene({ chart: "pie", parts: [{ label: "Nothing", value: 0 }] }).empty?.includes("undefined"));
assert.deepEqual(chartDataTable(chart(input)).rows, [
["Quarter", 1],
["Remainder", 3],
["Zero", 0],
]);
const center = scene({
chart: "pie",
parts: [
{ label: "First", value: 1 },
{ label: "Second", value: 2 },
{ label: "Topmost", value: 1 },
],
});
assert.equal(
inspectAt(center, center.plot.left + center.plot.width / 2, center.plot.top + center.plot.height / 2)?.id,
"part:2",
);
});
test("donut holes remain transparent, reverse inner winding and cubic arc endpoints are exact", () => {
const s = scene({
chart: "donut",
centerLabel: "Original total",
parts: [
{ label: "Quarter", value: 2 },
{ label: "Rest", value: 6 },
],
});
const h = find(s, "part:0").hit;
assert.equal(h.kind, "sector");
if (h.kind !== "sector") return;
assert.equal(inspectAt(s, h.cx, h.cy), null);
assert.equal(inspectAt(s, h.cx, h.cy - h.innerRadius), null);
assert.equal(inspectAt(s, h.cx, h.cy - h.innerRadius - 0.01)?.id, "part:0");
const d = paths(s)[0].d;
assert.deepEqual(
d.map((v) => v[0]),
["moveTo", "cubicTo", "lineTo", "cubicTo", "close"],
);
const outer = d[1],
inner = d[3];
near(outer[5] as number, h.cx + h.outerRadius);
near(outer[6] as number, h.cy);
near(inner[5] as number, h.cx);
near(inner[6] as number, h.cy - h.innerRadius);
assert.ok((outer[1] as number) > h.cx);
assert.ok((inner[2] as number) < h.cy);
assert.ok(!s.commands.some((c) => c.op === "rect" && "fill" in c && c.fill === "background"));
const full = scene({ chart: "donut", parts: [{ label: "Whole", value: 5 }] });
const ring = full.commands.find((c) => c.op === "roundRect");
assert.ok(ring && ring.op === "roundRect");
const fh = full.items[0].hit;
assert.ok(fh.kind === "sector");
near(ring.width / 2, fh.outerRadius);
near(ring.lineWidth!, fh.outerRadius - fh.innerRadius);
assert.equal(inspectAt(full, fh.cx, fh.cy), null);
});
test("heatmaps keep null cells distinct from zero, use native hex and sequential/diverging numerical colors", () => {
const input = {
chart: "heatmap",
x: ["A", "B", "C"],
y: ["Top", "Bottom"],
cells: [
{ x: 2, y: 1, value: 10 },
{ x: 0, y: 0, value: null },
{ x: 1, y: 0, value: 0 },
{ x: 0, y: 1, value: -10 },
],
};
const seq = scene(input),
div = scene({ ...input, scale: "diverging" });
assert.equal(find(seq, "cell:1").rows[2].value, "Missing");
assert.equal(find(seq, "cell:2").rows[2].value, "0");
assert.equal(find(seq, "cell:0").rows[2].color, PALETTE[0].toLowerCase());
assert.equal(find(div, "cell:0").rows[2].color, PALETTE[2].toLowerCase());
assert.equal(find(div, "cell:3").rows[2].color, PALETTE[1].toLowerCase());
assert.equal(find(div, "cell:2").rows[2].color, "#b4c5da");
const r = hitRect(seq, "cell:0");
near(r.x, seq.plot.left + (seq.plot.width * 2) / 3);
near(r.y, seq.plot.top + seq.plot.height / 2);
assert.equal(inspectAt(seq, r.x + r.width / 2, r.y + r.height / 2)?.id, "cell:0");
assert.equal(inspectAt(seq, seq.plot.left + (seq.plot.width * 5) / 6, seq.plot.top + seq.plot.height / 4), null); // absent ≠ null ≠ zero
assert.deepEqual(chartDataTable(chart(input)).rows, [
[2, 1, "C", "Bottom", 10],
[0, 0, "A", "Top", null],
[1, 0, "B", "Top", 0],
[0, 1, "A", "Bottom", -10],
]);
assert.ok(scene({ ...input, cells: [{ x: 0, y: 0, value: null }] }).empty?.includes("missing"));
});
test("histogram explicit unequal bins occupy numerical widths, leave real gaps and preserve counts", () => {
const input = {
chart: "histogram",
bins: [
{ from: 0, to: 1, count: 4 },
{ from: 2, to: 5, count: 2 },
],
};
const s = scene(input),
a = hitRect(s, "bin:0"),
b = hitRect(s, "bin:1");
near(a.width, s.plot.width / 5);
near(b.width, a.width * 3);
near(a.height, s.plot.height);
near(b.height, s.plot.height / 2);
assert.equal(inspectAt(s, s.plot.left + (s.plot.width * 1.5) / 5, s.plot.top + s.plot.height * 0.9), null);
assert.deepEqual(chartDataTable(chart(input)).rows, [
[0, 1, 4],
[2, 5, 2],
]);
});
test("numeric/time intervals share stable explicit lanes, and overlaps resolve to last painted interval", () => {
for (const axis of ["number", "time"]) {
const offset = axis === "time" ? T : 0,
unit = axis === "time" ? DAY : 1;
const input = {
chart: "range",
axis,
items: [
{ label: "First", lane: "Build", start: offset, end: offset + 2 * unit },
{ label: "Second", lane: "Test", start: offset + unit, end: offset + 8 * unit },
{ label: "Overlap", lane: "Build", start: offset + unit, end: offset + 3 * unit },
],
};
const s = scene(input),
h = scene(input, [1]),
a = hitRect(s, "interval:0"),
b = hitRect(s, "interval:1");
near(a.width, s.plot.width / 4);
near(b.width, (s.plot.width * 7) / 8);
near(b.y - a.y, s.plot.height / 2);
near(a.height, s.plot.height * 0.3);
assert.equal(inspectAt(s, s.plot.left + (s.plot.width * 1.5) / 8, a.y + a.height / 2)?.id, "interval:2");
assert.equal(inspectAt(s, s.plot.left + (s.plot.width * 6) / 8, a.y + a.height / 2), null);
assert.deepEqual(hitRect(h, "interval:0"), a);
assert.deepEqual(h.legend, s.legend);
assert.deepEqual(chartDataTable(chart(input)).rows[0], ["First", "Build", offset, offset + 2 * unit]);
}
});
test("waterfall totals are absolute resets, negative deltas start at the accumulated total", () => {
const input = {
chart: "waterfall",
entries: [
{ label: "Start", value: 10, role: "total" },
{ label: "Loss", value: -4, role: "delta" },
{ label: "Reset", value: 3, role: "total" },
{ label: "Growth", value: 2, role: "delta" },
{ label: "Negative total", value: -2, role: "total" },
],
};
const s = scene(input),
p = s.plot,
u = p.height / 12; // nice [-2,10], 2-unit ticks
near(hitRect(s, "entry:0").height, 10 * u);
near(hitRect(s, "entry:1").y, p.top);
near(hitRect(s, "entry:1").height, 4 * u);
near(hitRect(s, "entry:2").height, 3 * u);
near(hitRect(s, "entry:3").y, p.top + 5 * u);
near(hitRect(s, "entry:3").height, 2 * u);
assert.equal(find(s, "entry:3").rows[1].value, "5");
assert.equal(find(s, "entry:4").rows[1].value, "-2");
assert.deepEqual(chartDataTable(chart(input)).rows, [
["Start", "total", 10],
["Loss", "delta", -4],
["Reset", "total", 3],
["Growth", "delta", 2],
["Negative total", "total", -2],
]);
});
test("box summaries retain exact five numbers, domain includes outliers, and inspection uses actual marks", () => {
const input = {
chart: "box",
items: [
{ label: "Sample A", min: -2, q1: 1, median: 2, q3: 5, max: 7, outliers: [-5, 10] },
{ label: "Sample B", min: 0, q1: 0, median: 1, q3: 3, max: 4 },
],
};
const s = scene(input),
h = scene(input, [1]),
p = s.plot,
u = p.height / 15;
const a = hitRect(s, "box:0");
near(a.y, p.top + 5 * u);
near(a.height, 4 * u);
near(find(s, "box:0:outlier:0").y, p.top + p.height);
near(find(s, "box:0:outlier:1").y, p.top);
assert.deepEqual(find(h, "box:0"), find(s, "box:0"));
assert.deepEqual(
find(s, "box:0").rows.map((r) => r.value),
["-2", "1", "2", "5", "7"],
);
const o = find(s, "box:0:outlier:1");
assert.equal(inspectAt(s, o.x, o.y)?.id, o.id);
assert.equal(inspectAt(s, a.x, p.top + 2 * u), null); // neither box nor whisker at this x/y
assert.equal(inspectAt(s, a.x + a.width * 0.95, a.y + a.height / 2)?.id, "box:0");
assert.deepEqual(chartDataTable(chart(input)).rows, [
[0, "Sample A", -2, 1, 2, 5, 7, null, null],
[0, "Sample A", -2, 1, 2, 5, 7, 0, -5],
[0, "Sample A", -2, 1, 2, 5, 7, 1, 10],
[1, "Sample B", 0, 0, 1, 3, 4, null, null],
]);
});
test("reference lines/bands are typed original-coordinate overlays beneath observations", () => {
for (const orientation of ["vertical", "horizontal"]) {
const input = {
...bars,
orientation,
references: [{ value: 10, label: "Target" }],
bands: [{ from: -10, to: -5, label: "Low range" }],
};
const s = scene(input),
p = s.plot;
const b = hitRect(s, "band:0"),
r = hitRect(s, "reference:0");
if (orientation === "vertical") {
near(b.y, p.top + p.height * 0.75);
near(b.height, p.height / 4);
near(r.y, p.top);
} else {
near(b.x, p.left);
near(b.width, p.width / 4);
near(r.x, p.left + p.width - 1);
}
assert.deepEqual(
find(s, "band:0").rows.map((v) => v.value),
["-10", "-5"],
);
assert.ok(s.items.findIndex((i) => i.id === "band:0") < s.items.findIndex((i) => i.id === "series:0:value:0"));
assert.deepEqual(find(scene(input, [1]), "band:0"), find(s, "band:0"));
assert.deepEqual(chartDataTable(chart(input)).rows.slice(-2), [
[null, null, null, "Target", 10, null, null, null],
[null, null, null, null, null, "Low range", -10, -5],
]);
}
});
test("null-only normalized categories stay missing, not fabricated zero totals", () => {
const input = { ...percent, chart: "area" };
const s = scene(input);
assert.equal(find(s, "x:2").rows.at(-1)?.value, "Missing (no observations)");
assert.equal(scene({ ...input, series: [{ name: "Missing", values: [null, null, null] }] }).empty, "No observations");
});
test("equal labels without explicit interval lanes keep separate source rows", () => {
const input = {
chart: "range",
items: [
{ label: "Same", start: 0, end: 2 },
{ label: "Same", start: 1, end: 3 },
],
};
const s = scene(input);
assert.equal(s.legend.length, 2);
near(hitRect(s, "interval:1").y - hitRect(s, "interval:0").y, s.plot.height / 2);
assert.deepEqual(chartDataTable(chart(input)).rows, [
["Same", null, 0, 2],
["Same", null, 1, 3],
]);
});
test("constant box summaries inspect the actual visible median and remain finite", () => {
const input = chart({ chart: "box", items: [{ label: "Constant", min: 5, q1: 5, median: 5, q3: 5, max: 5 }] });
const s = chartScene(input, 640, 320),
b = find(s, "box:0");
assert.equal(inspectAt(s, b.x, b.y + 1)?.id, b.id);
verifyScene(input, s);
});
function pathCost(commands: readonly CanvasCommand[]) {
return commands.reduce(
(sum, command) =>
sum +
(command.op === "path" ? command.d.reduce((n, s) => n + (s[0] === "close" ? 1 : (s.length - 1) / 2), 0) : 0),
0,
);
}
function verifyScene(input: RichChart, s: ChartScene, expanded = s) {
const cost = panelCost({ id: "test", span: 1, body: input });
const overlays = s.items.map((i) => inspectionCommands(s, i));
const expandedOverlays = expanded.items.map((i) => inspectionCommands(expanded, i));
const maxCommands =
Math.max(0, ...overlays.map((o) => o.length)) + Math.max(0, ...expandedOverlays.map((o) => o.length));
const maxPoints = Math.max(0, ...overlays.map(pathCost)) + Math.max(0, ...expandedOverlays.map(pathCost));
assert.ok(
s.commands.length + expanded.commands.length + maxCommands <= cost.commands,
`${input.chart} commands: ${s.commands.length + expanded.commands.length + maxCommands}/${cost.commands}`,
);
assert.ok(
pathCost(s.commands) + pathCost(expanded.commands) + maxPoints <= cost.pathPoints,
`${input.chart} paths: ${pathCost(s.commands) + pathCost(expanded.commands) + maxPoints}/${cost.pathPoints}`,
);
for (const c of [...s.commands, ...overlays.flat()]) {
assert.ok(["rect", "roundRect", "path", "text"].includes(c.op));
for (const value of Object.values(c))
if (typeof value === "number") assert.ok(Number.isFinite(value) && Math.abs(value) <= 1e6, `${c.op} ${value}`);
if (c.op === "rect" || c.op === "roundRect") {
assert.ok(c.width >= 0 && c.height >= 0);
assert.ok(
c.x >= -1e-8 && c.y >= -1e-8 && c.x + c.width <= s.width + 1e-8 && c.y + c.height <= s.height + 1e-8,
`${input.chart}: ${JSON.stringify(c)}`,
);
}
if (c.op === "path")
for (const step of c.d) {
for (const value of step.slice(1))
assert.ok(typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= 1e6);
for (let i = 1; i < step.length; i += 2) {
const x = step[i] as number,
y = step[i + 1] as number;
assert.ok(
x >= -1e-8 && x <= s.width + 1e-8 && y >= -1e-8 && y <= s.height + 1e-8,
`${input.chart}: ${JSON.stringify(step)}`,
);
}
}
if (c.op === "text") {
assert.ok(c.size !== undefined);
if (input.chart === "donut" && c.color === "foreground") assert.ok(c.size >= 11 && c.size <= 26);
else assert.equal(c.size, 11);
}
for (const key of ["fill", "stroke", "color"] as const)
if (key in c) {
const color = (c as Record<string, unknown>)[key] as string;
assert.match(color, /^(#[\da-fA-F]{6}([\da-fA-F]{2})?|(?:mutedForeground|foreground)(?:\/\d+)?)$/);
}
}
const ids = s.items.map((i) => i.id);
assert.equal(new Set(ids).size, ids.length);
}
test("all families: finite native geometry, actual dimensions, raw preservation, independent duplicate scene budgets", () => {
const fixtures = [
bars,
{ ...bars, orientation: "horizontal", stack: "stacked" },
percent,
linear,
{ ...linear, chart: "area", stack: "percent" },
{ ...linear, chart: "area", interpolation: "step" },
{
chart: "scatter",
series: [
{
name: "Bubbles",
points: [
{ x: -10, y: 1, size: 2 },
{ x: 3, y: 9, size: 7 },
],
},
],
},
{ chart: "pie", parts: [{ label: "A", value: 5 }] },
{ chart: "donut", parts: [{ label: "A", value: 5 }] },
{
chart: "donut",
parts: [
{ label: "A", value: 999 },
{ label: "B", value: 1 },
],
},
{
chart: "heatmap",
x: ["A", "B"],
y: ["C"],
cells: [
{ x: 0, y: 0, value: null },
{ x: 1, y: 0, value: 0 },
],
},
{
chart: "histogram",
bins: [
{ from: -10, to: -5, count: 9 },
{ from: 1, to: 7, count: 3 },
],
},
{ chart: "range", items: [{ label: "Task", start: 1, end: 8 }] },
{
chart: "waterfall",
entries: [
{ label: "A", value: -3, role: "delta" },
{ label: "B", value: 6, role: "total" },
],
},
{ chart: "box", items: [{ label: "Five", min: 1, q1: 2, median: 3, q3: 4, max: 5, outliers: [-2, 9] }] },
];
for (const fixture of fixtures) {
const input = chart(fixture),
before = structuredClone(input),
data = chartDataTable(input);
for (const [width, height] of [
[320, 180],
[640, 320],
[1400, 900],
]) {
const s = chartScene(input, width, height),
big = chartScene(input, 1400, 900);
assert.equal(s.width, width);
assert.equal(s.height, height);
near(s.plot.left + s.plot.width, width - 18);
near(
s.plot.top + s.plot.height,
height -
Math.min(
input.chart === "heatmap" ? 85 : input.chart === "pie" || input.chart === "donut" ? 14 : 42,
height * (input.chart === "heatmap" ? 0.35 : 0.2),
),
);
verifyScene(input, s, big);
const commands = structuredClone(s.commands);
if (s.items[0]) inspectionCommands(s, s.items[0]);
assert.deepEqual(s.commands, commands);
assert.deepEqual(chartDataTable(input), data);
assert.deepEqual(input, before);
}
}
});
test("dense scenes retain observations/vertices while fitting aggregate publication estimates", () => {
const xs = Array.from({ length: 1000 }, (_, i) => i * i + 1),
names = xs.map(String);
const fixtures = [
{ chart: "bar", x: { type: "category", values: names }, series: [{ name: "All", values: xs }] },
...["linear", "step"].map((interpolation) => ({
chart: "area",
interpolation,
stack: "none",
x: { type: "number", values: xs },
series: [{ name: "All", values: xs }],
})),
{ chart: "scatter", series: [{ name: "All", points: xs.map((x, i) => ({ x, y: i, size: i + 1 })) }] },
{ chart: "pie", parts: Array.from({ length: 24 }, (_, i) => ({ label: String(i), value: i + 1 })) },
{
chart: "heatmap",
x: names.slice(0, 40),
y: names.slice(0, 40),
cells: Array.from({ length: 1600 }, (_, i) => ({
x: i % 40,
y: Math.floor(i / 40),
value: i % 7 === 0 ? null : i,
})),
},
{ chart: "histogram", bins: xs.slice(0, 200).map((x) => ({ from: x, to: x + 1, count: x })) },
{
chart: "range",
items: xs.slice(0, 200).map((x, i) => ({ label: String(i), lane: String(i % 8), start: x, end: x + 1 })),
},
{ chart: "waterfall", entries: xs.slice(0, 200).map((x, i) => ({ label: String(i), value: x, role: "delta" })) },
{
chart: "box",
items: xs
.slice(0, 100)
.map((_, i) => ({ label: String(i), min: -2, q1: 1, median: 2, q3: 3, max: 7, outliers: [-3, 10] })),
},
];
for (const fixture of fixtures) {
const input = chart(fixture),
s = chartScene(input, 640, 320),
expanded = chartScene(input, 1400, 900);
verifyScene(input, s, expanded);
if (input.chart === "area") {
assert.equal(s.items.length, 1000);
assert.equal(paths(s)[0].d.filter((v) => v[0] === "moveTo").length, 1);
assert.equal(s.commands.filter((c) => c.op === "roundRect").length, 0);
}
if (input.chart === "scatter" || input.chart === "bar") assert.equal(s.items.length, 1000);
if (input.chart === "waterfall") assert.equal(s.items.length, 200);
}
const document = richVisualDocumentSchema.parse({
version: 2,
title: "Budget",
summary: "Three charts together",
panels: fixtures.slice(0, 3).map((f, i) => ({ id: `p${i}`, body: { kind: "chart", ...f } })),
});
const scenes = document.panels.map((p) => chartScene(p.body as RichChart, 640, 320));
assert.ok(scenes.reduce((n, s) => n + s.commands.length * 2 + 4, 0) <= DOCUMENT_LIMITS.commands);
assert.ok(scenes.reduce((n, s) => n + pathCost(s.commands) * 2, 0) <= DOCUMENT_LIMITS.pathPoints);
});
test("dense null gaps, maximum typed overlays and extreme valid domains stay finite and bounded", () => {
const values = Array.from({ length: 1000 }, (_, i) => (i % 2 ? null : i % 3 ? -1e12 : 1e12));
for (const family of ["line", "area"]) {
const input = chart({
chart: family,
interpolation: "step",
...(family === "area" ? { stack: "stacked" } : {}),
x: { type: "category", values: values.map((_, i) => String(i)) },
series: [{ name: "Extreme", values }],
});
verifyScene(input, chartScene(input, 640, 320));
}
const input = chart({
...linear,
references: Array.from({ length: 8 }, (_, i) => ({ value: i + 10, label: `Ref ${i}` })),
bands: Array.from({ length: 8 }, (_, i) => ({ from: -20 + i, to: -10 + i, label: `Band ${i}` })),
xLabel: "Horizontal",
yLabel: "Vertical",
});
verifyScene(input, chartScene(input, 1400, 900));
for (const timestamp of [-8_640_000_000_000_000, 8_640_000_000_000_000]) {
const input = chart({
chart: "line",
x: { type: "time", values: [timestamp] },
series: [{ name: "Limit", values: [1] }],
});
verifyScene(input, chartScene(input, 640, 320));
}
});
test("valid subnormal numbers retain finite geometry, spacing and nonzero percentages", () => {
const tiny = Number.MIN_VALUE;
const fixtures = [
{
chart: "line",
x: { type: "number", values: [0, tiny, 4 * tiny] },
series: [{ name: "Tiny", values: [0, tiny, 4 * tiny] }],
},
{
chart: "bar",
x: { type: "category", values: ["Below", "Above"] },
series: [{ name: "Tiny", values: [-tiny, tiny] }],
},
{
chart: "pie",
parts: [
{ label: "Tiny", value: tiny },
{ label: "Triple", value: 3 * tiny },
],
},
{
chart: "scatter",
series: [
{
name: "Tiny",
points: [
{ x: 0, y: -tiny },
{ x: tiny, y: tiny },
],
},
],
},
];
for (const fixture of fixtures) {
const input = chart(fixture),
s = chartScene(input, 640, 320);
verifyScene(input, s);
assert.deepEqual(chartDataTable(input), chartDataTable(chart(fixture)));
}
const s = scene(fixtures[0]);
near(find(s, "x:1").x, s.plot.left + s.plot.width / 4);
assert.equal(find(scene(fixtures[2]), "part:0").rows[1].value, "25%");
});
test("adjacent tiny normal values render value-axis ticks in raw units without collapsing observations", () => {
const document = richVisualDocumentSchema.parse({
version: 2,
title: "Tiny measurements",
summary: "Two distinct finite measurements.",
panels: [
{
id: "tiny",
body: {
kind: "chart",
chart: "line",
x: { type: "category", values: ["A", "B"] },
series: [{ name: "Signal", values: [1e-299, 1.0000000000000001e-299] }],
},
},
],
});
const input = document.panels[0].body;
assert.equal(input.kind, "chart");
if (input.kind !== "chart") return;
const before = structuredClone(input);
for (const width of [380, 640]) {
const s = chartScene(input, width, 250);
verifyScene(input, s);
assert.ok(find(s, "x:0").y - find(s, "x:1").y > s.plot.height / 4);
const ticks = s.commands.filter((c) => c.op === "text" && c.align === "right");
assert.ok(ticks.length >= 2);
for (const tick of ticks) assert.equal((tick as Extract<CanvasCommand, { op: "text" }>).text, "1e-299");
}
assert.deepEqual(chartDataTable(input).rows, [
["A", 1e-299],
["B", 1.0000000000000001e-299],
]);
assert.deepEqual(input, before);
});
test("adjacent tiny normal numeric coordinates retain full-width spacing, raw ticks and table values", () => {
const low = 1e-299,
high = 1.0000000000000001e-299;
const fixtures = [
{
input: {
chart: "line",
x: { type: "number", values: [low, high] },
series: [{ name: "Signal", values: [1, 3] }],
},
rows: [
[low, 1],
[high, 3],
],
},
{
input: {
chart: "scatter",
series: [
{
name: "Signal",
points: [
{ x: low, y: 1 },
{ x: high, y: 3 },
],
},
],
},
rows: [
[0, "Signal", 0, null, low, 1, null],
[0, "Signal", 1, null, high, 3, null],
],
},
{ input: { chart: "histogram", bins: [{ from: low, to: high, count: 1 }] }, rows: [[low, high, 1]] },
{ input: { chart: "range", items: [{ label: "Span", start: low, end: high }] }, rows: [["Span", null, low, high]] },
];
for (const fixture of fixtures) {
const input = chart(fixture.input),
before = structuredClone(input),
s = chartScene(input, 380, 250);
verifyScene(input, s);
const ticks = s.commands.filter((c) => c.op === "text" && c.y === s.plot.top + s.plot.height + 13);
assert.ok(ticks.length >= 2, input.chart);
for (const tick of ticks) assert.equal((tick as Extract<CanvasCommand, { op: "text" }>).text, "1e-299");
if (input.chart === "line") {
near(find(s, "x:0").x, s.plot.left);
near(find(s, "x:1").x, s.plot.left + s.plot.width);
} else if (input.chart === "scatter") {
assert.ok(find(s, "series:0:point:1").x - find(s, "series:0:point:0").x > s.plot.width / 2);
} else {
const hit = hitRect(s, input.chart === "histogram" ? "bin:0" : "interval:0");
near(hit.x, s.plot.left);
near(hit.width, s.plot.width);
}
assert.deepEqual(chartDataTable(input).rows, fixture.rows);
assert.deepEqual(input, before);
}
});
test("v1 tiny-domain replay renders the measured native chart and preserves raw data", () => {
const document = legacyVisualDocumentSchema.parse({
version: 1,
title: "Tiny measurements",
summary: "Two distinct finite measurements.",
body: {
kind: "chart",
chart: "line",
categories: ["A", "B"],
series: [{ name: "Signal", values: [1e-299, 1.0000000000000001e-299] }],
},
});
const before = structuredClone(document),
{ ctx } = context(),
render = () => renderArtifact(artifact(document), ctx);
fire(render(), "inline-chart", "onResize", { width: 380, height: 250 });
const commands = node(render(), "inline-chart").commands as CanvasCommand[];
const path = commands.find((c) => c.op === "path");
assert.ok(path && path.op === "path");
assert.ok((path.d[0][2] as number) - (path.d[1][2] as number) > 100);
assert.ok(commands.some((c) => c.op === "text" && c.align === "right" && c.text === "1e-299"));
assert.deepEqual(dataTable(document).rows, [
["A", 1e-299],
["B", 1.0000000000000001e-299],
]);
assert.deepEqual(document, before);
});
test("asymmetric multi-wedge donuts fit the doubled path budget in wide and tall canvases", () => {
for (const count of [2, 3, 7, 24]) {
const input = chart({
chart: "donut",
parts: Array.from({ length: count }, (_, i) => ({ label: `Part ${i}`, value: (i + 1) ** 2 + 0.37 })),
});
for (const [width, height] of [
[320, 1100],
[1400, 300],
]) {
const s = chartScene(input, width, height);
verifyScene(input, s);
assert.equal(s.items.length, count);
for (const item of s.items) assert.equal(inspectAt(s, item.x, item.y)?.id, item.id);
}
}
});
test("vendored math has only the used exports, is readable, and needs no browser or runtime packages", async () => {
const math = await import("./math.js");
assert.deepEqual(Object.keys(math).sort(), [
"arc",
"area",
"curveLinear",
"curveStepAfter",
"interpolateRgb",
"line",
"pie",
"scaleLinear",
"scaleUtc",
]);
const source = readFileSync(new URL("./math.js", import.meta.url), "utf8");
assert.ok(source.length < 100_000);
assert.ok(source.split("\n").length > 1000);
assert.doesNotMatch(source, /\b(?:document|window|Intl|fetch|require|eval)\b|^import /m);
assert.doesNotMatch(source, /\.amp\/tmp/);
const license = readFileSync(new URL("./math.LICENSES.txt", import.meta.url), "utf8");
assert.match(license, /d3-scale@4\.0\.2/);
assert.match(license, /d3-shape@3\.2\.0/);
assert.match(license, /bundle-visuals-math\.mjs/);
});
No comments yet.