diff --git a/.changeset/mosaic-chart-component.md b/.changeset/mosaic-chart-component.md
new file mode 100644
index 00000000000..abc96e9eef2
--- /dev/null
+++ b/.changeset/mosaic-chart-component.md
@@ -0,0 +1,49 @@
+---
+'@clerk/mosaic': minor
+---
+
+Add a styled `Chart` at `@clerk/mosaic/components/chart`. `BarChart.Root` takes rows, a category key and series that each name a color. With no children it draws the legend, a dotted grid, the bars, both axes and a tooltip with one row per series. It handles values above and below zero, a projected total, dimming through `highlight`, an empty state and a retry when the Canvas fails to paint.
+
+```tsx
+import { BarChart, type ChartSeries } from '@clerk/mosaic/components/chart';
+
+const series: ChartSeries[] = [
+ { key: 'signups', label: 'Sign-ups', color: 1, value: row => row.signups },
+ { key: 'churned', label: 'Churned', color: 3, value: row => row.churned, negative: true },
+];
+
+ row.week}
+ series={series}
+/>;
+```
+
+Each series names its color: a palette slot from `1` to `6` or a CSS color. `negative: true` marks a series drawn below zero. The legend lists the series top to bottom as the bars draw, and the tooltip lists a zero value with the section its series is drawn in. The `tooltip` prop renders a custom tooltip body, typed from `data`.
+
+Children set the layout. `BarChart.Legend` goes anywhere, such as in a row beside an action, and `BarChart.Plot` holds the layers drawn on the plot. Each axis reserves its own room beside the plot, so leaving one out needs no `margin`. Leaving out `BarChart.Tooltip` gives a chart that takes no focus.
+
+```tsx
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+The chart's styles ship in their own sheet, `@clerk/mosaic/chart.css`, so `styles.css` does not grow for apps that render no chart. Import it into the same cascade layer as `styles.css`:
+
+```css
+@import '@clerk/mosaic/styles.css' layer(components);
+@import '@clerk/mosaic/chart.css' layer(components);
+```
+
+The palette ships in `chart.css` as six new tokens, `--cl-color-chart-1` to `--cl-color-chart-6`, with separate light and dark values that meet the data-viz contrast and color-blind separation checks.
diff --git a/.changeset/mosaic-chart-fluid-tooltip.md b/.changeset/mosaic-chart-fluid-tooltip.md
new file mode 100644
index 00000000000..2e13d952e2a
--- /dev/null
+++ b/.changeset/mosaic-chart-fluid-tooltip.md
@@ -0,0 +1,7 @@
+---
+'@clerk/mosaic': minor
+---
+
+The chart tooltip now slides between bars instead of jumping, and stays put when it first opens. With reduced motion it only fades. While the selected bar is scrolled out of view the tooltip hides, and it comes back when the bar does. Moving the pointer within one bar no longer rerenders the chart.
+
+`Chart.Tooltip` carries two new attributes for styling: `data-moving`, from the first change of bar until it closes, and `data-anchor-hidden`, while the selected bar is out of view.
diff --git a/packages/mosaic/README.md b/packages/mosaic/README.md
index 541149e62c2..6cbeb533ca0 100644
--- a/packages/mosaic/README.md
+++ b/packages/mosaic/README.md
@@ -81,6 +81,8 @@ If you want to use custom CSS to theme the components, instead import the styles
This ensures your unlayered custom CSS takes priority. Expect more documentation on custom theming soon.
+If you render `BarChart` from `@clerk/mosaic/components/chart`, also import `@clerk/mosaic/chart.css` after `styles.css`, into the same layer. `styles.css` does not include the chart's styles.
+
### Set a color scheme
Mosaic's colors use [`light-dark()`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/light-dark), which resolves against the `color-scheme` in scope. Mosaic does not set one, so your app must:
diff --git a/packages/mosaic/bundlewatch.config.json b/packages/mosaic/bundlewatch.config.json
index 348a6666f53..69a24ebffb3 100644
--- a/packages/mosaic/bundlewatch.config.json
+++ b/packages/mosaic/bundlewatch.config.json
@@ -4,6 +4,7 @@
"files": [
{ "path": "./dist/.bundlewatch/eager/ui.js", "maxSize": "54KB" },
{ "path": "./dist/.bundlewatch/total/ui.js", "maxSize": "347KB" },
- { "path": "./dist/styles.css", "maxSize": "20KB" }
+ { "path": "./dist/styles.css", "maxSize": "20KB" },
+ { "path": "./dist/chart.css", "maxSize": "2KB" }
]
}
diff --git a/packages/mosaic/chart.css.d.ts b/packages/mosaic/chart.css.d.ts
new file mode 100644
index 00000000000..cb0ff5c3b54
--- /dev/null
+++ b/packages/mosaic/chart.css.d.ts
@@ -0,0 +1 @@
+export {};
diff --git a/packages/mosaic/docs/theming.md b/packages/mosaic/docs/theming.md
index 04955302f3a..94f73dfac8f 100644
--- a/packages/mosaic/docs/theming.md
+++ b/packages/mosaic/docs/theming.md
@@ -36,7 +36,7 @@ A theme's CSS wins without any prop because the consumer imports the sheet into
## Tokens
-Tokens are `stylex.defineVars` groups in `src/tokens.stylex.ts`, one exported `*Vars` const per group; the file is the list, and its comments explain each group. Keys that start with `--cl-` are emitted verbatim, so they are stable handles. `space` keys are not `--cl-*` names, so its steps are hashed and internal. The derived name unions (`ColorVarName`, …) live in `src/styles/index.ts`, because a `.stylex.ts` file may export only define-primitives.
+Tokens are `stylex.defineVars` groups in `src/tokens.stylex.ts`, one exported `*Vars` const per group; the file is the list, and its comments explain each group. A component with its own sheet keeps its tokens beside it ([CSS build](#css-build)). Keys that start with `--cl-` are emitted verbatim, so they are stable handles. `space` keys are not `--cl-*` names, so its steps are hashed and internal. The derived name unions (`ColorVarName`, …) live in `src/styles/index.ts`, because a `.stylex.ts` file may export only define-primitives.
The color model, which decides which token a new style uses:
@@ -75,7 +75,18 @@ Components render and style without a provider. `MosaicProvider` (`src/mosaic-pr
## CSS build
-`src/styles/index.ts` is a StyleX-only barrel of every component, token group and styling helper. The build walks it with the StyleX rollup plugin and extracts one `dist/styles.css`, exported as `@clerk/mosaic/styles.css`. Run it with `pnpm build` in `packages/mosaic`.
+`src/styles/index.ts` is a StyleX-only barrel of every component, token group and styling helper. The build walks it with the StyleX rollup plugin and extracts `dist/styles.css`, exported as `@clerk/mosaic/styles.css`. Run it with `pnpm build` in `packages/mosaic`.
+
+A component that Clerk's own components do not render ships its own sheet, so `styles.css` does not carry it. The chart components are the ones today. `src/styles/chart.ts` is its barrel, and the build emits `dist/chart.css`, exported as `@clerk/mosaic/chart.css`. A sheet holds only the rules its barrel reaches that an earlier sheet in `tsdown.css.config.mts` does not hold, so the atoms the chart shares with `Tooltip` or `Button` stay in `styles.css`. A consumer imports both sheets into the same layer:
+
+```css
+@import '@clerk/mosaic/styles.css' layer(components);
+@import '@clerk/mosaic/chart.css' layer(components);
+```
+
+StyleX names a layer `priorityN` by its position among the priority levels in the sheet, so the build gives each sheet every level. `priority3` means the same priority in both files, and each file names all the levels in order, so the sublayer order holds whichever sheet loads first. Within each layer the chart's rules now follow the core rules. A conditional atom outranks a plain one by specificity, not by order, so the move is safe until a chart part carries a chart-only atom and a core atom for the same property at equal specificity. Give such a state its own selector rather than relying on the order.
+
+A component's sheet carries its own tokens. The chart palette, `--cl-color-chart-1` to `-6`, lives in `src/components/chart/chart.vars.stylex.ts`, not `src/tokens.stylex.ts`.
Swingset consumes Mosaic from source instead. `@stylexjs/unplugin/webpack` in its `next.config` compiles the StyleX calls, and `@stylexjs/postcss-plugin` extracts the CSS by replacing `@stylex;` in `globals.css`. Both contexts must use the same StyleX babel version and options, or the atom hashes will not line up.
diff --git a/packages/mosaic/package.json b/packages/mosaic/package.json
index 37e8d2f8c1a..3d6e6b49be1 100644
--- a/packages/mosaic/package.json
+++ b/packages/mosaic/package.json
@@ -22,7 +22,8 @@
"license": "MIT",
"author": "Clerk",
"sideEffects": [
- "./dist/styles.css"
+ "./dist/styles.css",
+ "./dist/chart.css"
],
"type": "module",
"exports": {
@@ -71,6 +72,11 @@
"import": "./dist/components/card.js",
"default": "./dist/components/card.js"
},
+ "./components/chart": {
+ "types": "./dist/components/chart.d.ts",
+ "import": "./dist/components/chart.js",
+ "default": "./dist/components/chart.js"
+ },
"./components/checkbox": {
"types": "./dist/components/checkbox.d.ts",
"import": "./dist/components/checkbox.js",
@@ -505,6 +511,10 @@
"types": "./styles.css.d.ts",
"default": "./dist/styles.css"
},
+ "./chart.css": {
+ "types": "./chart.css.d.ts",
+ "default": "./dist/chart.css"
+ },
"./package.json": "./package.json"
},
"types": "dist/index.d.ts",
@@ -514,6 +524,7 @@
"!dist/**/*.d.mts.map",
"!dist/.bundlewatch",
"styles.css.d.ts",
+ "chart.css.d.ts",
"CHANGELOG.md"
],
"scripts": {
@@ -529,7 +540,7 @@
"format": "node ../../scripts/format-package.mjs",
"format:check": "node ../../scripts/format-package.mjs --check",
"lint": "oxlint -c oxlint.config.mjs src",
- "lint:attw": "attw --pack . --exclude-entrypoints styles.css --profile esm-only",
+ "lint:attw": "attw --pack . --exclude-entrypoints styles.css chart.css --profile esm-only",
"lint:publint": "publint",
"test": "vitest run --project primitives --project lint-rules --project mosaic",
"test:browser": "vitest run --project browser",
@@ -548,6 +559,7 @@
},
"devDependencies": {
"@clerk/clerk-js": "workspace:^",
+ "@stylexjs/babel-plugin": "0.19.2",
"@stylexjs/eslint-plugin": "0.19.2",
"@stylexjs/rollup-plugin": "0.19.2",
"@stylexjs/stylex": "0.19.2",
@@ -566,6 +578,7 @@
"eslint-plugin-boundaries": "7.3.0",
"eslint-plugin-react-you-might-not-need-an-effect": "1.0.2",
"happy-dom": "^20.8.9",
+ "lightningcss": "1.33.0",
"msw": "2.15.0",
"playwright": "1.62.1",
"qrcode.react": "4.2.0",
diff --git a/packages/mosaic/src/components/chart/__tests__/__screenshots__/chart.visual.test.tsx/chart-dark-chromium-linux.png b/packages/mosaic/src/components/chart/__tests__/__screenshots__/chart.visual.test.tsx/chart-dark-chromium-linux.png
new file mode 100644
index 00000000000..f8330306ea4
Binary files /dev/null and b/packages/mosaic/src/components/chart/__tests__/__screenshots__/chart.visual.test.tsx/chart-dark-chromium-linux.png differ
diff --git a/packages/mosaic/src/components/chart/__tests__/__screenshots__/chart.visual.test.tsx/chart-light-chromium-linux.png b/packages/mosaic/src/components/chart/__tests__/__screenshots__/chart.visual.test.tsx/chart-light-chromium-linux.png
new file mode 100644
index 00000000000..7025355f1f9
Binary files /dev/null and b/packages/mosaic/src/components/chart/__tests__/__screenshots__/chart.visual.test.tsx/chart-light-chromium-linux.png differ
diff --git a/packages/mosaic/src/components/chart/__tests__/chart-palette.test.ts b/packages/mosaic/src/components/chart/__tests__/chart-palette.test.ts
new file mode 100644
index 00000000000..c51df9dcbfc
--- /dev/null
+++ b/packages/mosaic/src/components/chart/__tests__/chart-palette.test.ts
@@ -0,0 +1,47 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { assertChartPalette, oklchToSrgb8, type PaletteMode, type Srgb8 } from './palette-checks';
+
+const tokens = readFileSync(resolve(import.meta.dirname, '../chart.vars.stylex.ts'), 'utf8');
+
+const OKLCH = String.raw`oklch\(([\d.]+) ([\d.]+) ([\d.]+)\)`;
+const TOKEN = new RegExp(String.raw`'--cl-color-chart-(\d+)': 'light-dark\(${OKLCH}, ${OKLCH}\)'`, 'g');
+
+function palette(mode: PaletteMode): Srgb8[] {
+ const slots = [...tokens.matchAll(TOKEN)];
+ return slots.map(([, , ...values]) => {
+ const [l, c, h] = (mode === 'light' ? values.slice(0, 3) : values.slice(3)).map(Number);
+ return oklchToSrgb8(l, c, h);
+ });
+}
+
+const white = oklchToSrgb8(1, 0, 0);
+// `--cl-color-surface` in dark mode: 5% of the white neutral mixed in OKLab into the 0.16 page.
+const darkSurface = oklchToSrgb8(0.95 * 0.16 + 0.05, 0, 0);
+const darkPage = oklchToSrgb8(0.16, 0, 0);
+
+describe('chart palette tokens', () => {
+ it('defines six slots, in order, each as one light-dark value', () => {
+ expect([...tokens.matchAll(TOKEN)].map(([, slot]) => slot)).toEqual(['1', '2', '3', '4', '5', '6']);
+ });
+
+ it('passes the data-viz checks in light mode on the surface', () => {
+ expect(() => assertChartPalette(palette('light'), 'light', white)).not.toThrow();
+ });
+
+ it('passes the data-viz checks in dark mode on the surface and on the page', () => {
+ expect(() => assertChartPalette(palette('dark'), 'dark', darkSurface)).not.toThrow();
+ expect(() => assertChartPalette(palette('dark'), 'dark', darkPage)).not.toThrow();
+ });
+
+ it('rejects the original story hues, which fail the band and chroma checks', () => {
+ const channel = (value: string, at: number) => parseInt(value.slice(at, at + 2), 16) / 255;
+ const hex = (value: string): Srgb8 => [channel(value, 0), channel(value, 2), channel(value, 4)];
+ const original = ['7c3aed', '0ea5e9', 'f97316', '06b6d4', 'eab308', '64748b'].map(hex);
+
+ expect(() => assertChartPalette(original, 'light', white)).toThrow(/slot 5: lightness .*\n.*slot 6: chroma/s);
+ });
+});
diff --git a/packages/mosaic/src/components/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/components/chart/__tests__/chart.browser.test.tsx
new file mode 100644
index 00000000000..543dab47c97
--- /dev/null
+++ b/packages/mosaic/src/components/chart/__tests__/chart.browser.test.tsx
@@ -0,0 +1,594 @@
+import { cleanup, render, screen, within } from '@testing-library/react';
+import type {} from '@vitest/browser-playwright';
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { cdp, page } from 'vitest/browser';
+
+import { MosaicLocalizationProvider, resolveLocalization } from '../../../localization';
+import {
+ type ActiveBar,
+ BarChart,
+ type BarChartHighlight,
+ type BarChartProjection,
+ type ChartSeries,
+ type ChartTooltipData,
+} from '..';
+
+type Row = { period: string; a: number; b: number; c: number };
+
+const rows: Row[] = [
+ { period: 'A', a: 10, b: 10, c: 10 },
+ { period: 'B', a: 10, b: 10, c: 10 },
+ { period: 'C', a: 10, b: 10, c: 10 },
+];
+
+const series: ChartSeries[] = [
+ { key: 'a', label: 'Series A', color: 1, value: row => row.a },
+ { key: 'b', label: 'Series B', color: 2, value: row => row.b },
+ { key: 'c', label: 'Series C', color: 3, value: row => row.c },
+];
+
+const index = (row: Row) => row.period;
+
+type Rgba = readonly [number, number, number, number];
+
+// The palette and its 40% mix with the surface, as tokens.md lists them.
+const VIOLET: Rgba = [124, 58, 237, 255];
+const SKY: Rgba = [1, 132, 188, 255];
+const ORANGE: Rgba = [212, 94, 0, 255];
+const VIOLET_DIMMED: Rgba = [197, 183, 254, 255];
+const VIOLET_DARK: Rgba = [139, 86, 249, 255];
+
+beforeAll(async () => {
+ await page.viewport(1280, 900);
+});
+
+afterEach(async () => {
+ cleanup();
+ await cdp().send('Emulation.setEmulatedMedia', { features: [] });
+});
+
+function GrowthChart({
+ series: growthSeries = series,
+ highlight,
+ onRenderError,
+}: Readonly<{
+ series?: ChartSeries[];
+ highlight?: BarChartHighlight;
+ onRenderError?: (error: Error) => void;
+}>) {
+ return (
+
+
+
+ );
+}
+
+async function renderChart(element: React.ReactElement) {
+ const view = render(element);
+ await expect.poll(() => screen.queryByRole('img', { name: 'Growth' })).toBeTruthy();
+ return view;
+}
+
+function canvas() {
+ const element = screen.getByRole('img', { name: 'Growth' });
+ if (!(element instanceof HTMLCanvasElement)) {
+ throw new Error('The chart image is not a canvas');
+ }
+ return element;
+}
+
+/** The interaction surface: a group, or a button when the chart has `onActivate`. */
+function surface() {
+ return screen.queryByRole('button', { name: 'Growth' }) ?? screen.getByRole('group', { name: 'Growth' });
+}
+
+function plot() {
+ return surface().getBoundingClientRect();
+}
+
+/** The middle of a series' segment in a category, in client coordinates. */
+function segmentCenter(category: number, position: number) {
+ const box = plot();
+ const step = box.width / rows.length;
+ return { x: box.left + step * (category + 0.5), y: box.bottom - (box.height * (position + 0.5)) / 3 };
+}
+
+function canvasPixel({ x, y }: { x: number; y: number }): Rgba {
+ const element = canvas();
+ const box = element.getBoundingClientRect();
+ const ratio = element.width / box.width;
+ const data = element
+ .getContext('2d')
+ ?.getImageData(Math.round((x - box.left) * ratio), Math.round((y - box.top) * ratio), 1, 1).data;
+ return [data?.[0] ?? -1, data?.[1] ?? -1, data?.[2] ?? -1, data?.[3] ?? -1];
+}
+
+/** The composited pixel on screen, so layers above and below the Canvas count. */
+async function screenPixel({ x, y }: { x: number; y: number }): Promise {
+ const target = document.body;
+ const base64 = await page.screenshot({ element: target, save: false });
+ const bitmap = await createImageBitmap(await (await fetch(`data:image/png;base64,${base64}`)).blob());
+ const ratio = bitmap.width / target.getBoundingClientRect().width;
+ const scratch = new OffscreenCanvas(1, 1);
+ const context = scratch.getContext('2d');
+ context?.drawImage(bitmap, Math.round(x * ratio), Math.round(y * ratio), 1, 1, 0, 0, 1, 1);
+ const data = context?.getImageData(0, 0, 1, 1).data;
+ return [data?.[0] ?? -1, data?.[1] ?? -1, data?.[2] ?? -1, data?.[3] ?? -1];
+}
+
+function near(actual: Rgba, expected: Rgba) {
+ return actual.every((channel, i) => Math.abs(channel - (expected[i] ?? 0)) <= 1);
+}
+
+function hover({ x, y }: { x: number; y: number }) {
+ surface().dispatchEvent(
+ new PointerEvent('pointermove', { bubbles: true, clientX: x, clientY: y, pointerType: 'mouse' }),
+ );
+}
+
+describe('BarChart.Legend', () => {
+ it('grows a described item to a fingertip-sized target under a coarse pointer', async () => {
+ await cdp().send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 1 });
+ try {
+ render(
+
+
+
,
+ );
+ const trigger = screen.getByRole('button', { name: 'Series A' });
+ const box = trigger.getBoundingClientRect();
+ const reach = (44 - box.height) / 2 - 1;
+
+ expect(reach).toBeGreaterThan(0);
+ expect(document.elementFromPoint(box.left + box.width / 2, box.top - reach)).toBe(trigger);
+ expect(document.elementFromPoint(box.left + box.width / 2, box.bottom + reach)).toBe(trigger);
+ } finally {
+ await cdp().send('Emulation.setTouchEmulationEnabled', { enabled: false });
+ }
+ });
+});
+
+describe('Chart parts', () => {
+ it('paints each series in its palette slot', async () => {
+ await renderChart();
+ expect(document.querySelector('.cl-chart')).toHaveAttribute('data-state', 'ready');
+
+ for (const [position, color] of [VIOLET, SKY, ORANGE].entries()) {
+ await expect.poll(() => near(canvasPixel(segmentCenter(1, position)), color)).toBe(true);
+ }
+ });
+
+ it('dims the bars outside the highlight with an opaque mix that hides the grid line', async () => {
+ await renderChart();
+ const gridLine = [...document.querySelectorAll('.cl-chart-grid-line')].find(line => {
+ const y = line.getBoundingClientRect().top;
+ const bottom = plot().bottom;
+ return y < bottom - 10 && y > bottom - plot().height / 3 + 10;
+ });
+ if (!gridLine) {
+ throw new Error('No grid line crosses the first segment');
+ }
+ const onLine = { x: segmentCenter(0, 0).x, y: gridLine.getBoundingClientRect().top + 0.5 };
+
+ await expect.poll(() => near(canvasPixel(onLine), VIOLET_DIMMED)).toBe(true);
+ expect(near(await screenPixel(onLine), VIOLET_DIMMED)).toBe(true);
+ expect(near(canvasPixel(segmentCenter(1, 0)), VIOLET)).toBe(true);
+ });
+
+ it('keeps the highlighted series at full strength and dims the others', async () => {
+ await renderChart();
+
+ await expect.poll(() => near(canvasPixel(segmentCenter(1, 1)), SKY)).toBe(true);
+ expect(near(canvasPixel(segmentCenter(1, 0)), VIOLET_DIMMED)).toBe(true);
+ });
+
+ it('colors the grid, labels and tooltip from the border, secondary text and surface tokens', async () => {
+ const root = document.documentElement.style;
+ const tokens = {
+ '--cl-color-border': 'rgb(255, 0, 0)',
+ '--cl-color-foreground-secondary': 'rgb(0, 128, 0)',
+ '--cl-color-surface': 'rgb(0, 0, 255)',
+ };
+ for (const [name, value] of Object.entries(tokens)) {
+ root.setProperty(name, value);
+ }
+ try {
+ await renderChart();
+
+ expect(getComputedStyle(document.querySelector('.cl-chart-grid-line') as Element).stroke).toBe('rgb(255, 0, 0)');
+ expect(getComputedStyle(document.querySelector('.cl-chart-y-tick') as Element).fill).toBe('rgb(0, 128, 0)');
+
+ hover(segmentCenter(1, 1));
+ await expect.poll(() => document.querySelector('.cl-chart-tooltip')).toBeTruthy();
+ expect(getComputedStyle(document.querySelector('.cl-chart-tooltip') as Element).backgroundColor).toBe(
+ 'rgb(0, 0, 255)',
+ );
+ } finally {
+ for (const name of Object.keys(tokens)) {
+ root.removeProperty(name);
+ }
+ }
+ });
+
+ it('does not dim on hover without a highlight, and draws the hover band behind the bars', async () => {
+ await renderChart();
+ const bar = segmentCenter(1, 0);
+ await expect.poll(() => near(canvasPixel(bar), VIOLET)).toBe(true);
+ const besideBar = { x: bar.x + 40, y: bar.y };
+ const bandBefore = await screenPixel(besideBar);
+
+ hover(bar);
+
+ await expect.poll(() => document.querySelector('.cl-chart-cursor')).toBeTruthy();
+ await expect.poll(async () => near(await screenPixel(besideBar), bandBefore)).toBe(false);
+ expect(near(await screenPixel(bar), VIOLET)).toBe(true);
+ expect(near(canvasPixel(segmentCenter(0, 0)), VIOLET)).toBe(true);
+ expect(document.elementFromPoint(bar.x, bar.y)).toBe(surface());
+ });
+
+ it('opens a tooltip with the period and one row per series, top of the stack first', async () => {
+ await renderChart();
+
+ hover(segmentCenter(1, 1));
+
+ await expect.poll(() => document.querySelector('.cl-chart-tooltip-content')).toBeTruthy();
+ const content = document.querySelector('.cl-chart-tooltip-content');
+ expect(content?.querySelector('.cl-chart-tooltip-heading')?.textContent).toBe('B');
+ expect([...(content?.querySelectorAll('.cl-chart-tooltip-row') ?? [])].map(row => row.textContent)).toEqual([
+ 'Series C10',
+ 'Series B10',
+ 'Series A10',
+ ]);
+ });
+
+ it('repaints when the preferred color scheme flips to dark', async () => {
+ await cdp().send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'light' }] });
+ await renderChart();
+ const bar = segmentCenter(1, 0);
+ await expect.poll(() => near(canvasPixel(bar), VIOLET)).toBe(true);
+
+ await cdp().send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
+
+ await expect.poll(() => near(canvasPixel(bar), VIOLET_DARK)).toBe(true);
+ });
+
+ it('offers a retry when the Canvas cannot paint, and paints again after it', async () => {
+ const getContext = HTMLCanvasElement.prototype.getContext;
+ const errors: Error[] = [];
+ HTMLCanvasElement.prototype.getContext = () => null;
+ try {
+ render( errors.push(error)} />);
+ expect(within(await screen.findByRole('alert')).getByText('The chart could not be displayed.')).toBeVisible();
+ expect(document.querySelector('.cl-chart')).toHaveAttribute('data-state', 'error');
+ expect(errors.map(error => error.name)).toEqual(['CanvasRenderError']);
+ } finally {
+ HTMLCanvasElement.prototype.getContext = getContext;
+ }
+
+ screen.getByRole('button', { name: 'Try again' }).click();
+
+ await expect.poll(() => screen.queryByRole('img', { name: 'Growth' })).toBeTruthy();
+ await expect.poll(() => near(canvasPixel(segmentCenter(1, 0)), VIOLET)).toBe(true);
+ expect(document.querySelector('.cl-chart')).toHaveAttribute('data-state', 'ready');
+ });
+
+ it('repaints when a series changes color', async () => {
+ const { rerender } = await renderChart();
+ const bar = segmentCenter(1, 0);
+ await expect.poll(() => near(canvasPixel(bar), VIOLET)).toBe(true);
+
+ rerender( (entry.key === 'a' ? { ...entry, color: 3 } : entry))} />);
+
+ await expect.poll(() => near(canvasPixel(bar), ORANGE)).toBe(true);
+ });
+});
+
+type Week = { week: string; signups: number; returning: number };
+
+const weeks: Week[] = [{ week: '2026-01-05', signups: 40, returning: 22 }];
+
+const weekSeries: ChartSeries[] = [
+ { key: 'signups', label: 'Sign-ups', color: 1, value: row => row.signups },
+ { key: 'returning', label: 'Returning', color: 2, value: row => row.returning },
+];
+
+const getWeek = (row: Week) => row.week;
+
+function WeekChart({
+ data = weeks,
+ projection,
+ renderEmptyState,
+ children,
+}: Readonly<{
+ data?: Week[];
+ projection?: BarChartProjection;
+ renderEmptyState?: () => React.ReactNode;
+ children?: React.ReactNode;
+}>) {
+ return (
+
+ {children}
+
+ );
+}
+
+type Flow = { week: string; retained: number; added: number; lost: number; returned: number };
+
+const flows: Flow[] = [{ week: '2026-01-05', retained: 30, added: 12, lost: -9, returned: -4 }];
+
+// Stack order, bottom first: `lost` sits against the zero line and `returned` below it.
+const flowSeries: ChartSeries[] = [
+ { key: 'lost', label: 'Lost', color: 4, value: row => row.lost, negative: true },
+ { key: 'retained', label: 'Retained', color: 1, value: row => row.retained },
+ { key: 'returned', label: 'Returned', color: 5, value: row => row.returned, negative: true },
+ { key: 'added', label: 'Added', color: 2, value: row => row.added },
+];
+
+const getFlowWeek = (row: Flow) => row.week;
+
+function FlowChart({ children }: Readonly<{ children?: React.ReactNode }>) {
+ return (
+
+ {children}
+
+ );
+}
+
+const legendLabels = () => screen.getAllByRole('listitem').map(item => item.textContent);
+
+describe('BarChart.Legend in a chart', () => {
+ it('lists the series top to bottom as the bars draw, above the plot', () => {
+ render();
+
+ expect(legendLabels()).toEqual(['Returning', 'Sign-ups']);
+ const legend = document.querySelector('.cl-chart-legend');
+ const plot = document.querySelector('.cl-chart-plot');
+ expect(legend?.closest('.cl-chart-plot')).toBeNull();
+ expect(legend && plot && legend.compareDocumentPosition(plot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ });
+
+ it('adds a labelled projection as a dashed entry', () => {
+ render();
+
+ expect(legendLabels()).toEqual(['Returning', 'Sign-ups', 'Projected']);
+ expect(screen.getByText('Projected').querySelector('.cl-chart-swatch')).toHaveAttribute('data-swatch', 'dashed');
+ });
+
+ it('renders each label through its children and keeps the swatch', () => {
+ render({{item => `${item.label} (weekly)`}});
+
+ const items = screen.getAllByRole('listitem');
+ expect(items.map(item => item.textContent)).toEqual(['Returning (weekly)', 'Sign-ups (weekly)']);
+ expect(items[0]?.querySelector('.cl-chart-swatch')).toHaveAttribute('data-swatch', 'square');
+ });
+
+ it('lists negative series after the stack above zero, from the zero line down', () => {
+ render();
+
+ expect(legendLabels()).toEqual(['Added', 'Retained', 'Lost', 'Returned', 'Projected']);
+ });
+
+ it('goes wherever the layout places it, such as in a row beside an action', () => {
+ render(
+
+
+
+
+
+
+ ,
+ );
+
+ expect(document.querySelector('.cl-chart-legend')?.parentElement).toHaveClass('chart-header');
+ expect(legendLabels()).toEqual(['Added', 'Retained', 'Lost', 'Returned', 'Projected']);
+ });
+
+ it('leaves out a projection whose category is not in the data', () => {
+ render();
+
+ expect(legendLabels()).toEqual(['Returning', 'Sign-ups']);
+ });
+});
+
+describe('BarChart.Root states', () => {
+ it('is ready with rows', () => {
+ render();
+
+ expect(document.querySelector('.cl-chart')).toHaveAttribute('data-state', 'ready');
+ expect(document.querySelector('.cl-chart')).toHaveAttribute('data-chart', 'bar');
+ expect(screen.queryByText('No data to show')).toBeNull();
+ });
+
+ it('shows the default empty state without rows', () => {
+ render();
+
+ expect(screen.getByText('No data to show')).toBeInTheDocument();
+ expect(document.querySelector('.cl-chart')).toHaveAttribute('data-state', 'empty');
+ });
+
+ it('renders the caller empty state instead', () => {
+ render(
+
Connect a data source
}
+ />,
+ );
+
+ expect(screen.getByText('Connect a data source')).toBeInTheDocument();
+ expect(screen.queryByText('No data to show')).toBeNull();
+ });
+});
+
+function renderCustomTooltip({ heading, active }: ChartTooltipData>) {
+ return
+ );
+}
+
+/** A chart with only the layers given, so a test can leave an axis or the tooltip out. */
+function LayeredChart({ children }: Readonly<{ children: React.ReactNode }>) {
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+/** How far the plot sits from the left and bottom of `cl-chart-plot`: the room the axes take. */
+function plotInset() {
+ const root = document.querySelector('.cl-chart-plot')?.getBoundingClientRect();
+ const box = plot();
+ if (!root) {
+ throw new Error('No plot');
+ }
+ return { left: Math.round(box.left - root.left), bottom: Math.round(root.bottom - box.bottom) };
+}
+
+describe('BarChart.Plot', () => {
+ it('leaves room beside the plot only for the axes it draws', async () => {
+ const { rerender } = await renderChart(
+
+
+
+
+
+ ,
+ );
+ expect(plotInset()).toEqual({ left: 44, bottom: 32 });
+
+ rerender(
+
+
+
+
+ ,
+ );
+ await expect.poll(plotInset).toEqual({ left: 0, bottom: 32 });
+
+ rerender(
+
+
+
+ ,
+ );
+ await expect.poll(plotInset).toEqual({ left: 0, bottom: 0 });
+ });
+
+ it('takes no focus without BarChart.Tooltip', async () => {
+ await renderChart(
+
+
+ ,
+ );
+
+ expect(screen.queryByRole('group', { name: 'Growth' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Growth' })).toBeNull();
+ expect(document.querySelector('.cl-chart-selection')).toBeNull();
+ });
+});
+
+describe('BarChart.Tooltip keyboard', () => {
+ it('describes the keys in the language of the localization', async () => {
+ await renderChart(
+
+
+ ,
+ );
+ expect(surface()).toHaveAccessibleDescription('Gauche et Droite choisissent une période. Échap ferme.');
+ });
+
+ it('announces the focused period with each series label and value', async () => {
+ await renderChart();
+ surface().focus();
+ await expect.poll(() => screen.getByRole('status').textContent).toBe('A, Series A 10, Series B 10, Series C 10');
+ });
+});
+
+describe('BarChart.TooltipContent', () => {
+ // Floats like a tooltip: an absolutely positioned box sizes to its content.
+ const Floating = ({ footer }: Readonly<{ footer?: React.ReactNode }>) => (
+
+
+
+ );
+ const contentWidth = () => document.querySelector('.cl-chart-tooltip-content')?.getBoundingClientRect().width;
+
+ it('wraps a long footer to the width of the rows', () => {
+ const { rerender } = render();
+ const width = contentWidth();
+
+ rerender(Churned users were active last period but did not return this period
} />);
+
+ expect(contentWidth()).toBe(width);
+ expect(screen.getByText(/Churned users/).getBoundingClientRect().height).toBeGreaterThan(30);
+ });
+});
+
+describe('BarChart.Root tooltip', () => {
+ it('renders the tooltip prop with the selected period instead of the default rows', async () => {
+ await renderChart();
+
+ hover(segmentCenter(1, 1));
+
+ await expect.poll(() => document.querySelector('.custom-tooltip')?.textContent).toBe('B: 20');
+ expect(document.querySelector('.cl-chart-tooltip-content')).toBeNull();
+ });
+});
diff --git a/packages/mosaic/src/components/chart/__tests__/chart.test.tsx b/packages/mosaic/src/components/chart/__tests__/chart.test.tsx
new file mode 100644
index 00000000000..04002a8db5c
--- /dev/null
+++ b/packages/mosaic/src/components/chart/__tests__/chart.test.tsx
@@ -0,0 +1,125 @@
+import { act, cleanup, render, renderHook, screen, within } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { BarChart, type ChartSeries } from '..';
+import { bridgeSeries } from '../internal/series-bridge';
+import { useChartFormat } from '../internal/use-chart-format';
+
+afterEach(() => cleanup());
+
+type Row = { signups: number; churned: number };
+
+const signups: ChartSeries = { key: 'signups', label: 'Sign-ups', color: 1, value: row => row.signups };
+
+const series: ChartSeries[] = [
+ signups,
+ { key: 'churned', label: 'Churned', color: 'var(--brand-red)', value: row => row.churned, description: 'Lost users' },
+];
+
+describe('BarChart.Legend', () => {
+ it('lists each series by label, keyed by its series key', () => {
+ render();
+
+ const items = screen.getAllByRole('listitem');
+ expect(items.map(item => item.textContent)).toEqual(['Sign-ups', 'Churned']);
+ expect(items.map(item => item.getAttribute('data-series'))).toEqual(['signups', 'churned']);
+ });
+
+ it('makes an item with a description a button that shows it in a tooltip', async () => {
+ render();
+
+ const trigger = screen.getByRole('button', { name: 'Churned' });
+ await act(() => trigger.focus());
+
+ expect(await screen.findByRole('tooltip')).toHaveTextContent('Lost users');
+ expect(screen.queryByRole('button', { name: 'Sign-ups' })).toBeNull();
+ });
+
+ it('draws a dashed swatch for a projection entry', () => {
+ render(
+ ,
+ );
+
+ expect(screen.getByRole('listitem').querySelector('.cl-chart-swatch')).toHaveAttribute('data-swatch', 'dashed');
+ });
+});
+
+describe('Chart parts outside their container', () => {
+ it('throws, naming the part', () => {
+ expect(() => render()).toThrow(' must be used within a chart root, such as ');
+ });
+
+ it('throws for a drawn layer outside the plot', () => {
+ expect(() =>
+ render(
+ ''}
+ series={series}
+ >
+
+ ,
+ ),
+ ).toThrow(' must be used within ');
+ });
+});
+
+describe('BarChart.TooltipContent', () => {
+ it('shows the heading, the metrics and one row per series with its value', () => {
+ render(
+ +12%}
+ metrics={[{ label: 'Total', value: '1,204' }]}
+ rows={[
+ { key: 'signups', label: 'Sign-ups', color: 1, value: '1,000' },
+ { key: 'returning', label: 'Returning', color: 2, value: '204' },
+ ]}
+ footer={
Incomplete period
}
+ />,
+ );
+
+ expect(screen.getByText('Jan 5, 2026').parentElement).toHaveTextContent('Jan 5, 2026+12%');
+ expect(screen.getByRole('term')).toHaveTextContent('Total');
+ expect(screen.getByRole('definition')).toHaveTextContent('1,204');
+ const rows = within(screen.getByRole('list')).getAllByRole('listitem');
+ expect(rows.map(row => [row.getAttribute('data-series'), row.textContent])).toEqual([
+ ['signups', 'Sign-ups1,000'],
+ ['returning', 'Returning204'],
+ ]);
+ expect(screen.getByText('Incomplete period')).toBeInTheDocument();
+ });
+});
+
+describe('series boundary', () => {
+ it('rejects a repeated key', () => {
+ expect(() => bridgeSeries([...series, signups])).toThrow('Two chart series share the key "signups"');
+ });
+
+ it('rejects more series than the chart has slots, naming the fix', () => {
+ const many = Array.from({ length: 9 }, (_, i): ChartSeries => ({ ...signups, key: `s${i}` }));
+
+ expect(() => bridgeSeries(many)).toThrow(/at most 8 series, and got 9. Fold the smallest into one "Other" series/);
+ });
+});
+
+describe('default formatting', () => {
+ it('formats a UTC date key as a date in UTC, and any other key as is', () => {
+ const { result } = renderHook(() => useChartFormat({}));
+
+ expect(result.current.category('2026-01-05', 'axis')).toBe('Jan 5');
+ expect(result.current.category('2026-01-05T00:00:00Z', 'tooltip')).toBe('Jan 5, 2026');
+ expect(result.current.category('Week 2', 'tooltip')).toBe('Week 2');
+ expect(result.current.category('2026-13-45', 'axis')).toBe('2026-13-45');
+ });
+
+ it('formats values compactly on the axis and in full in the tooltip', () => {
+ const { result } = renderHook(() => useChartFormat({}));
+
+ expect(result.current.value(12_500, 'axis')).toBe('13K');
+ expect(result.current.value(12_500, 'tooltip')).toBe('12,500');
+ });
+});
diff --git a/packages/mosaic/src/components/chart/__tests__/chart.visual.test.tsx b/packages/mosaic/src/components/chart/__tests__/chart.visual.test.tsx
new file mode 100644
index 00000000000..25d211fbb52
--- /dev/null
+++ b/packages/mosaic/src/components/chart/__tests__/chart.visual.test.tsx
@@ -0,0 +1,82 @@
+import { render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { BarChart, type ChartSeries } from '..';
+
+const weeks = [
+ { week: '2026-01-05', signups: 40, returning: 22, churned: -14 },
+ { week: '2026-01-12', signups: 52, returning: 30, churned: -18 },
+ { week: '2026-01-19', signups: 36, returning: 26, churned: -22 },
+ { week: '2026-01-26', signups: 61, returning: 34, churned: -12 },
+ { week: '2026-02-02', signups: 48, returning: 29, churned: -25 },
+ { week: '2026-02-09', signups: 55, returning: 41, churned: -17 },
+];
+
+type Week = (typeof weeks)[number];
+
+const series: ChartSeries[] = [
+ { key: 'signups', label: 'Sign-ups', color: 1, value: week => week.signups },
+ { key: 'returning', label: 'Returning', color: 2, value: week => week.returning },
+ { key: 'churned', label: 'Churned', color: 3, value: week => week.churned, negative: true },
+];
+
+const getWeek = (week: Week) => week.week;
+
+afterEach(() => {
+ document.documentElement.style.colorScheme = '';
+});
+
+function WeeklyGrowth() {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+async function renderChart() {
+ render(
+
+
+
,
+ );
+ await screen.findByRole('img', { name: 'Weekly growth' });
+ return screen.getByTestId('frame');
+}
+
+describe('Chart visual states', () => {
+ it('draws the palette, a dimmed highlight and a projection in light mode', async () => {
+ const chart = await renderChart();
+
+ await expect(page.elementLocator(chart)).toMatchScreenshot('chart-light');
+ });
+
+ it('draws the palette, a dimmed highlight and a projection in dark mode', async () => {
+ document.documentElement.style.colorScheme = 'dark';
+ const chart = await renderChart();
+
+ await expect(page.elementLocator(chart)).toMatchScreenshot('chart-dark');
+ });
+});
diff --git a/packages/mosaic/src/components/chart/__tests__/palette-checks.ts b/packages/mosaic/src/components/chart/__tests__/palette-checks.ts
new file mode 100644
index 00000000000..199f6102475
--- /dev/null
+++ b/packages/mosaic/src/components/chart/__tests__/palette-checks.ts
@@ -0,0 +1,139 @@
+// The computable checks of the data-viz palette validator (dataviz skill, `validate_palette.js`),
+// ported with its thresholds and its Machado 2009 CVD model so the token test fails where the
+// validator would.
+
+type Vector = readonly [number, number, number];
+
+export type PaletteMode = 'light' | 'dark';
+
+const BAND: Record = { light: [0.43, 0.77], dark: [0.48, 0.67] };
+const CHROMA_FLOOR = 0.1;
+const CVD_TARGET = 8;
+const NORMAL_FLOOR = 15;
+const CONTRAST_MIN = 3;
+
+const MACHADO = {
+ protan: [
+ [0.152286, 1.052583, -0.204868],
+ [0.114503, 0.786281, 0.099216],
+ [-0.003882, -0.048116, 1.051998],
+ ],
+ deutan: [
+ [0.367322, 0.860646, -0.227968],
+ [0.280085, 0.672501, 0.047413],
+ [-0.01182, 0.04294, 0.968881],
+ ],
+} as const;
+
+const multiply = (matrix: readonly (readonly number[])[], [r, g, b]: Vector): Vector => [
+ matrix[0][0] * r + matrix[0][1] * g + matrix[0][2] * b,
+ matrix[1][0] * r + matrix[1][1] * g + matrix[1][2] * b,
+ matrix[2][0] * r + matrix[2][1] * g + matrix[2][2] * b,
+];
+
+const clamp = (value: number) => Math.min(1, Math.max(0, value));
+const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
+const toGamma = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
+
+/** An sRGB color quantized to 8 bits per channel, as the validator reads a hex value. */
+export type Srgb8 = Vector;
+
+export function oklchToSrgb8(l: number, c: number, h: number): Srgb8 {
+ const rad = (h * Math.PI) / 180;
+ const a = c * Math.cos(rad);
+ const b = c * Math.sin(rad);
+ const lms: Vector = [
+ (l + 0.3963377774 * a + 0.2158037573 * b) ** 3,
+ (l - 0.1055613458 * a - 0.0638541728 * b) ** 3,
+ (l - 0.0894841775 * a - 1.291485548 * b) ** 3,
+ ];
+ const linear = multiply(
+ [
+ [4.0767416621, -3.3077115913, 0.2309699292],
+ [-1.2684380046, 2.6097574011, -0.3413193965],
+ [-0.0041960863, -0.7034186147, 1.707614701],
+ ],
+ lms,
+ );
+ if (linear.some(channel => channel < -1e-4 || channel > 1 + 1e-4)) {
+ throw new Error(`oklch(${l} ${c} ${h}) is outside sRGB`);
+ }
+ const [r, g, bl] = linear.map(channel => Math.round(toGamma(clamp(channel)) * 255) / 255);
+ return [r, g, bl];
+}
+
+const linearOf = (color: Srgb8): Vector => [toLinear(color[0]), toLinear(color[1]), toLinear(color[2])];
+
+function oklabOfLinear([r, g, b]: Vector): Vector {
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
+ return [
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
+ ];
+}
+
+function deltaE(first: Srgb8, second: Srgb8, kind?: keyof typeof MACHADO) {
+ const view = (color: Srgb8) => {
+ const linear = linearOf(color);
+ if (!kind) {
+ return oklabOfLinear(linear);
+ }
+ const [r, g, b] = multiply(MACHADO[kind], linear);
+ return oklabOfLinear([clamp(r), clamp(g), clamp(b)]);
+ };
+ const [l1, a1, b1] = view(first);
+ const [l2, a2, b2] = view(second);
+ return 100 * Math.hypot(l1 - l2, a1 - a2, b1 - b2);
+}
+
+function contrast(first: Srgb8, second: Srgb8) {
+ const luminance = (color: Srgb8) => {
+ const [r, g, b] = linearOf(color);
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ };
+ const [high, low] = [luminance(first), luminance(second)].sort((x, y) => y - x);
+ return (high + 0.05) / (low + 0.05);
+}
+
+/**
+ * Throws with every failed check when a categorical palette, in slot order, fails the validator's
+ * adjacent-pair checks against a surface: lightness band, chroma floor, CVD separation (protan and
+ * deutan), the normal-vision floor and 3:1 contrast.
+ */
+export function assertChartPalette(palette: readonly Srgb8[], mode: PaletteMode, surface: Srgb8) {
+ const failures: string[] = [];
+ const [low, high] = BAND[mode];
+ palette.forEach((color, index) => {
+ const [l, a, b] = oklabOfLinear(linearOf(color));
+ const slot = index + 1;
+ if (l < low || l > high) {
+ failures.push(`slot ${slot}: lightness ${l.toFixed(3)} outside ${low}-${high}`);
+ }
+ if (Math.hypot(a, b) < CHROMA_FLOOR) {
+ failures.push(`slot ${slot}: chroma ${Math.hypot(a, b).toFixed(3)} below ${CHROMA_FLOOR}`);
+ }
+ if (contrast(color, surface) < CONTRAST_MIN) {
+ failures.push(`slot ${slot}: contrast ${contrast(color, surface).toFixed(2)} below ${CONTRAST_MIN}:1`);
+ }
+ });
+ for (let index = 1; index < palette.length; index++) {
+ const pair = `slots ${index} and ${index + 1}`;
+ const cvd = Math.min(
+ deltaE(palette[index - 1], palette[index], 'protan'),
+ deltaE(palette[index - 1], palette[index], 'deutan'),
+ );
+ if (cvd < CVD_TARGET) {
+ failures.push(`${pair}: CVD ΔE ${cvd.toFixed(1)} below ${CVD_TARGET}`);
+ }
+ const normal = deltaE(palette[index - 1], palette[index]);
+ if (normal < NORMAL_FLOOR) {
+ failures.push(`${pair}: ΔE ${normal.toFixed(1)} below ${NORMAL_FLOOR}`);
+ }
+ }
+ if (failures.length > 0) {
+ throw new Error(`The ${mode} chart palette fails the data-viz checks:\n${failures.join('\n')}`);
+ }
+}
diff --git a/packages/mosaic/src/components/chart/bar-chart.parts.ts b/packages/mosaic/src/components/chart/bar-chart.parts.ts
new file mode 100644
index 00000000000..974ee274506
--- /dev/null
+++ b/packages/mosaic/src/components/chart/bar-chart.parts.ts
@@ -0,0 +1,13 @@
+export { BarChartRoot as Root } from './bars/bar-chart-root';
+export { ChartPlot as Plot } from './chart-root';
+export { ChartLegend as Legend, ChartTooltipContent as TooltipContent } from './chart';
+export {
+ ChartGrid as Grid,
+ ChartTooltip as Tooltip,
+ ChartXAxis as XAxis,
+ ChartXTick as XTick,
+ ChartYAxis as YAxis,
+ ChartYLine as YLine,
+ ChartYTick as YTick,
+} from './chart-parts';
+export { ChartBar as Bar, ChartBars as Bars, ChartProjectionOutline as ProjectionOutline } from './bars/chart-bars';
diff --git a/packages/mosaic/src/components/chart/bars/__tests__/bar-tooltip.test.ts b/packages/mosaic/src/components/chart/bars/__tests__/bar-tooltip.test.ts
new file mode 100644
index 00000000000..e97a128c031
--- /dev/null
+++ b/packages/mosaic/src/components/chart/bars/__tests__/bar-tooltip.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ActiveBar } from '../../../../primitives/chart';
+import type { ChartSeries } from '../../chart-series';
+import type { ChartFormat } from '../../internal/use-chart-format';
+import { barTooltip } from '../bar-tooltip';
+
+type Row = { week: string; signups: number; returning: number; churned?: number };
+
+const week: Row = { week: '2026-01-05', signups: 40, returning: 22, churned: -14 };
+
+const series: ChartSeries[] = [
+ { key: 'signups', label: 'Sign-ups', color: 1, value: row => row.signups },
+ { key: 'returning', label: 'Returning', color: 2, value: row => row.returning },
+ { key: 'churned', label: 'Churned', color: 3, value: row => row.churned, negative: true },
+];
+
+describe('the default tooltip', () => {
+ const format: ChartFormat = { value: value => `${value}`, category: key => `Week of ${key}` };
+ const active = (section: 'positive' | 'negative', projected = false): ActiveBar => ({
+ category: '2026-01-05',
+ datumIndex: 0,
+ datum: week,
+ section,
+ projected,
+ hasValues: { positive: true, negative: true },
+ });
+
+ it('lists the positive section top of the stack first', () => {
+ expect(barTooltip({ active: active('positive'), series, projection: undefined, format })).toEqual({
+ active: active('positive'),
+ heading: 'Week of 2026-01-05',
+ metrics: [],
+ rows: [
+ { key: 'returning', label: 'Returning', color: 2, value: '22' },
+ { key: 'signups', label: 'Sign-ups', color: 1, value: '40' },
+ ],
+ });
+ });
+
+ it('lists only the negative series for the negative section', () => {
+ expect(barTooltip({ active: active('negative'), series, projection: undefined, format })?.rows).toEqual([
+ { key: 'churned', label: 'Churned', color: 3, value: '-14' },
+ ]);
+ });
+
+ it('adds the projection as a metric only where it is drawn and labelled', () => {
+ const projection = { datumIndex: 0, value: 80, label: 'Projected' };
+
+ expect(barTooltip({ active: active('positive', true), series, projection, format })?.metrics).toEqual([
+ { label: 'Projected', value: '80' },
+ ]);
+ expect(barTooltip({ active: active('positive'), series, projection, format })?.metrics).toEqual([]);
+ expect(
+ barTooltip({ active: active('positive', true), series, projection: { ...projection, label: undefined }, format })
+ ?.metrics,
+ ).toEqual([]);
+ });
+
+ it('lists a zero value in the section its series is drawn in', () => {
+ const quiet = (section: 'positive' | 'negative') => ({
+ ...active(section),
+ datum: { ...week, returning: 0, churned: 0 },
+ });
+
+ expect(barTooltip({ active: quiet('positive'), series, projection: undefined, format })?.rows).toEqual([
+ { key: 'returning', label: 'Returning', color: 2, value: '0' },
+ { key: 'signups', label: 'Sign-ups', color: 1, value: '40' },
+ ]);
+ expect(barTooltip({ active: quiet('negative'), series, projection: undefined, format })?.rows).toEqual([
+ { key: 'churned', label: 'Churned', color: 3, value: '0' },
+ ]);
+ });
+
+ it('hides the tooltip for a period with nothing to show', () => {
+ const empty = { ...active('negative'), datum: { ...week, churned: undefined } };
+
+ expect(barTooltip({ active: empty, series, projection: undefined, format })).toBeNull();
+ });
+});
diff --git a/packages/mosaic/src/components/chart/bars/bar-chart-root.tsx b/packages/mosaic/src/components/chart/bars/bar-chart-root.tsx
new file mode 100644
index 00000000000..96afd3870fd
--- /dev/null
+++ b/packages/mosaic/src/components/chart/bars/bar-chart-root.tsx
@@ -0,0 +1,78 @@
+'use client';
+
+import React from 'react';
+
+import { ChartTooltipContent } from '../chart';
+import { ChartFrame, type ChartFrameProps } from '../chart-root';
+import { type ChartTooltipData, useAxisGutters } from '../internal/chart-style';
+import { type BarChartOptions, useBarChart } from './use-bar-chart';
+
+export type BarChartRootProps = ChartFrameProps & BarChartOptions;
+
+function renderTooltipContent({ heading, metrics, rows }: ChartTooltipData) {
+ return (
+
+ );
+}
+
+/**
+ * A stacked bar chart. Without children it draws the legend, a grid, the bars, both axes and a
+ * tooltip; with children, place `BarChart.Legend` and `BarChart.Plot` yourself.
+ */
+// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter, which `data` sets for `series` and `tooltip`.
+export const BarChartRoot = React.forwardRef>(
+ function BarChartRoot(props, ref) {
+ const {
+ data,
+ index,
+ series,
+ projection,
+ highlight,
+ formatValue,
+ formatCategory,
+ categoryGap,
+ margin,
+ tooltip = renderTooltipContent,
+ selection,
+ defaultSelection,
+ onSelectionChange,
+ onActivate,
+ disabled,
+ ...frame
+ } = props;
+ const { x, y, registerAxis } = useAxisGutters();
+ const { chart, style } = useBarChart(
+ {
+ data,
+ index,
+ series,
+ projection,
+ highlight,
+ formatValue,
+ formatCategory,
+ categoryGap,
+ margin,
+ selection,
+ defaultSelection,
+ onSelectionChange,
+ onActivate,
+ disabled,
+ },
+ { x, y },
+ tooltip,
+ );
+ return (
+
+ );
+ },
+) as (props: BarChartRootProps & { ref?: React.Ref }) => React.ReactElement | null;
diff --git a/packages/mosaic/src/components/chart/bars/bar-tooltip.ts b/packages/mosaic/src/components/chart/bars/bar-tooltip.ts
new file mode 100644
index 00000000000..1cad09d58a3
--- /dev/null
+++ b/packages/mosaic/src/components/chart/bars/bar-tooltip.ts
@@ -0,0 +1,87 @@
+import type { ActiveBar, BarIdentity, BarSection } from '../../../primitives/chart';
+import type { ChartSeries } from '../chart-series';
+import type { ChartTooltipData } from '../internal/chart-style';
+import type { SeriesBridge } from '../internal/series-bridge';
+import type { ChartFormat } from '../internal/use-chart-format';
+
+/** The bars that keep full strength. A bar is active when it matches every field given. */
+export type BarChartHighlight = Readonly<{
+ /** A category key, as `index` returns it. */
+ category?: string;
+ section?: BarSection;
+ /** A series key. */
+ series?: string;
+}>;
+
+/**
+ * The primitive's `isBarActive` for a highlight, or undefined when nothing is dimmed. Takes the
+ * highlight's fields, not the object, so an inline highlight does not repaint.
+ */
+export function barActivity(
+ bridge: SeriesBridge,
+ index: (datum: TDatum, index: number) => string,
+ { category, section, series }: BarChartHighlight,
+): ((bar: BarIdentity) => boolean) | undefined {
+ if (category === undefined && section === undefined && series === undefined) {
+ return undefined;
+ }
+ return bar =>
+ (category === undefined || index(bar.datum, bar.datumIndex) === category) &&
+ (section === undefined || bar.positive === (section === 'positive')) &&
+ (series === undefined || bridge.seriesAt(bar.seriesKey).key === series);
+}
+
+/** A projected total for one row, drawn when it rises above that row's positive stack. */
+export interface BarChartProjection {
+ /** The row's category key, as `index` returns it. */
+ category: string;
+ value: number;
+ /** Names the projection in the legend and tooltip. Without it neither mentions the projection. */
+ label?: string;
+ /** Shown in a tooltip on the legend entry. */
+ description?: string;
+}
+
+/** Returns null when the period has no rows and no projection, which hides the tooltip. */
+export function barTooltip({
+ active,
+ series,
+ projection,
+ format,
+}: Readonly<{
+ active: ActiveBar;
+ series: readonly ChartSeries[];
+ projection: Readonly<{ value: number; label?: string }> | undefined;
+ format: ChartFormat;
+}>): ChartTooltipData> | null {
+ const positive = active.section === 'positive';
+ const inSection = series.flatMap(entry => {
+ const value = entry.value(active.datum);
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ return [];
+ }
+ // A zero belongs to its series' side of the zero line, so a period lists every series it tracks.
+ const below = value < 0 || (value === 0 && entry.negative === true);
+ if (below === positive) {
+ return [];
+ }
+ return [{ key: entry.key, label: entry.label, color: entry.color, value: format.value(value, 'tooltip') }];
+ });
+ const rows = positive ? inSection.reverse() : inSection;
+ const metrics =
+ projection?.label !== undefined && active.projected
+ ? [{ label: projection.label, value: format.value(projection.value, 'tooltip') }]
+ : [];
+ if (rows.length === 0 && metrics.length === 0) {
+ return null;
+ }
+ return { active, heading: format.category(active.category, 'tooltip'), metrics, rows };
+}
+
+/** Thinner gaps as rows grow, so dense ranges keep visible bars. */
+export function categoryGapFor(rowCount: number): number {
+ if (rowCount > 180) {
+ return 0.08;
+ }
+ return rowCount > 90 ? 0.14 : 0.28;
+}
diff --git a/packages/mosaic/src/components/chart/bars/chart-bars.styles.ts b/packages/mosaic/src/components/chart/bars/chart-bars.styles.ts
new file mode 100644
index 00000000000..e98254a11d0
--- /dev/null
+++ b/packages/mosaic/src/components/chart/bars/chart-bars.styles.ts
@@ -0,0 +1,34 @@
+import * as stylex from '@stylexjs/stylex';
+
+import { colorVars, radiusVars, space } from '../../../tokens.stylex';
+
+const mark = 'var(--_cl-chart-mark)';
+
+// `BarChart.Bar` is hidden; the Canvas paints every bar from its computed color and geometry.
+// Dimmed and projection fills are opaque mixes with the surface, so grid lines never show through.
+export const barStyles = stylex.create({
+ // Above the cursor, so the hover band shows only in the gaps and bar colors stay exact. The
+ // interaction surface below still takes the pointer, because nothing here does.
+ bars: {
+ pointerEvents: 'none',
+ zIndex: 1,
+ },
+ bar: {
+ color: {
+ default: mark,
+ ':where([data-inactive])': `color-mix(in oklab, ${mark} 40%, ${colorVars['--cl-color-surface']})`,
+ ':where([data-projection])': `color-mix(in oklab, ${colorVars['--cl-color-neutral']} 8%, ${colorVars['--cl-color-surface']})`,
+ },
+ rowGap: space['0.5'],
+ borderBottomLeftRadius: '2px',
+ borderBottomRightRadius: '2px',
+ borderTopLeftRadius: radiusVars['--cl-radius-sm'],
+ borderTopRightRadius: radiusVars['--cl-radius-sm'],
+ maxWidth: space['8'],
+ },
+ projectionOutline: {
+ stroke: colorVars['--cl-color-foreground-secondary'],
+ strokeDasharray: '3 3',
+ strokeWidth: 1,
+ },
+});
diff --git a/packages/mosaic/src/components/chart/bars/chart-bars.tsx b/packages/mosaic/src/components/chart/bars/chart-bars.tsx
new file mode 100644
index 00000000000..8a887c5079e
--- /dev/null
+++ b/packages/mosaic/src/components/chart/bars/chart-bars.tsx
@@ -0,0 +1,76 @@
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import React from 'react';
+
+import {
+ Chart as Primitive,
+ type ChartBarProps as PrimitiveChartBarProps,
+ type ChartBarsProps as PrimitiveChartBarsProps,
+ type ChartProjectionOutlineProps as PrimitiveChartProjectionOutlineProps,
+} from '../../../primitives/chart';
+import type { MosaicStyleProps } from '../../../props';
+import { mergeStyleProps, themeProps } from '../../../props';
+import { ChartYLine } from '../chart-parts';
+import { seriesMark } from '../internal/series.styles';
+import { barStyles } from './chart-bars.styles';
+
+export type ChartBarsProps = Omit & MosaicStyleProps;
+
+/**
+ * Paints the bars on Canvas above the cursor, so the hover band shows only in the gaps. Without
+ * children it renders `BarChart.Bar`, `BarChart.ProjectionOutline` and a zero line.
+ */
+export const ChartBars = React.forwardRef(function ChartBars(
+ { children, xstyle, ...rest },
+ ref,
+) {
+ return (
+
+ {children ?? (
+ <>
+
+
+
+ >
+ )}
+
+ );
+});
+
+export type ChartBarProps = Omit & MosaicStyleProps;
+
+/**
+ * The hidden element the Canvas reads. Its `color` is the series color, mixed toward the surface
+ * under `data-inactive`; its `max-width`, `row-gap` and corner radii set the bar geometry.
+ */
+export const ChartBar = React.forwardRef(function ChartBar({ xstyle, ...rest }, ref) {
+ return (
+
+ );
+});
+
+export type ChartProjectionOutlineProps = Omit &
+ MosaicStyleProps;
+
+/** A dashed outline around the projected total. */
+export const ChartProjectionOutline = React.forwardRef(
+ function ChartProjectionOutline({ xstyle, ...rest }, ref) {
+ return (
+
+ );
+ },
+);
diff --git a/packages/mosaic/src/components/chart/bars/use-bar-chart.ts b/packages/mosaic/src/components/chart/bars/use-bar-chart.ts
new file mode 100644
index 00000000000..29f8c43e922
--- /dev/null
+++ b/packages/mosaic/src/components/chart/bars/use-bar-chart.ts
@@ -0,0 +1,162 @@
+'use client';
+
+import React from 'react';
+
+import { useMessages } from '../../../localization/context';
+import {
+ type ActiveBar,
+ type BarChartInstance,
+ Chart as Primitive,
+ type UseBarChartOptions as PrimitiveUseBarChartOptions,
+} from '../../../primitives/chart';
+import type { ChartFormatPlace, ChartLegendItem, ChartSeries } from '../chart-series';
+import type { ChartStyle, ChartTooltipData } from '../internal/chart-style';
+import { bridgeSeries } from '../internal/series-bridge';
+import { useChartFormat } from '../internal/use-chart-format';
+import {
+ barActivity,
+ type BarChartHighlight,
+ type BarChartProjection,
+ barTooltip,
+ categoryGapFor,
+} from './bar-tooltip';
+
+export interface BarChartOptions extends Omit<
+ PrimitiveUseBarChartOptions,
+ 'series' | 'projection' | 'isBarActive' | 'formatCategory' | 'formatValue' | 'messages'
+> {
+ /** Stack order, bottom first. Define it at module level or memoize it. */
+ series: readonly ChartSeries[];
+ /** A projected total for one row, drawn when it rises above the row. `label` names it in the legend and tooltip. */
+ projection?: BarChartProjection;
+ /**
+ * The bars that keep full strength. Every other bar is dimmed with an opaque mix toward
+ * `--cl-color-surface`. Without it no bar is dimmed.
+ */
+ highlight?: BarChartHighlight | null;
+ /** Formats a value. `place` is `'axis'` for a tick and `'tooltip'` for a tooltip row and announcements. */
+ formatValue?: (value: number, place: ChartFormatPlace) => string;
+ /**
+ * Formats a category key. The `'tooltip'` form also names the period in announcements. Default:
+ * a UTC date key such as `2026-01-05` as a date, any other key as is
+ */
+ formatCategory?: (key: string, place: ChartFormatPlace) => string;
+ /** Renders the tooltip body. Return null to hide it. Default: `BarChart.TooltipContent` with the rows */
+ tooltip?: (tooltip: ChartTooltipData>) => React.ReactNode;
+}
+
+/** Which axes `BarChart.Plot` draws, so the margin leaves room only for those. */
+type AxisGutters = Readonly<{ x: boolean; y: boolean }>;
+
+const TOP_MARGIN = 8;
+const X_AXIS_GUTTER = 32;
+const Y_AXIS_GUTTER = 44;
+
+const PROJECTION_COLOR = 'var(--cl-color-foreground-secondary)';
+
+/**
+ * Top to bottom as the bars draw: the stack above zero from its top, then the `negative` series
+ * from the zero line down, which is the order the tooltip lists a period's rows in.
+ */
+function legendOrder(series: readonly ChartSeries[]): ChartLegendItem[] {
+ return [...series.filter(entry => !entry.negative).reverse(), ...series.filter(entry => entry.negative)];
+}
+
+/** The headless bar chart, plus the colors, legend, formatting and tooltip the styled parts read. */
+export function useBarChart(
+ options: Omit, 'tooltip'>,
+ axes: AxisGutters,
+ renderTooltip: (tooltip: ChartTooltipData>) => React.ReactNode,
+): { chart: BarChartInstance; style: ChartStyle } {
+ const { data, index, series, projection, highlight, formatValue, formatCategory, categoryGap, margin, ...selection } =
+ options;
+ const bridge = React.useMemo(() => bridgeSeries(series), [series]);
+ const format = useChartFormat({ formatValue, formatCategory });
+
+ const { category, section, series: highlightSeries } = highlight ?? {};
+ const isBarActive = React.useMemo(
+ () => barActivity(bridge, index, { category, section, series: highlightSeries }),
+ [bridge, index, category, section, highlightSeries],
+ );
+ const projectionCategory = projection?.category;
+ const projectionIndex = React.useMemo(
+ () =>
+ projectionCategory === undefined
+ ? -1
+ : data.findIndex((datum, position) => index(datum, position) === projectionCategory),
+ [data, index, projectionCategory],
+ );
+ const projectionValue = projection?.value;
+ const projectionLabel = projection?.label;
+ const projectionDescription = projection?.description;
+ const projected = React.useMemo(
+ () =>
+ projectionIndex === -1 || projectionValue === undefined
+ ? undefined
+ : { datumIndex: projectionIndex, value: projectionValue, label: projectionLabel },
+ [projectionIndex, projectionLabel, projectionValue],
+ );
+
+ const announceCategory = React.useCallback((key: string) => format.category(key, 'tooltip'), [format]);
+ const announceValue = React.useCallback((value: number) => format.value(value, 'tooltip'), [format]);
+ const text = useMessages('chart');
+ const chart = Primitive.useBarChart({
+ ...selection,
+ data,
+ index,
+ series: bridge.positioned,
+ projection: projected,
+ isBarActive,
+ categoryGap: categoryGap ?? categoryGapFor(data.length),
+ margin: {
+ top: TOP_MARGIN,
+ right: 0,
+ bottom: axes.x ? X_AXIS_GUTTER : 0,
+ left: axes.y ? Y_AXIS_GUTTER : 0,
+ ...margin,
+ },
+ formatCategory: announceCategory,
+ formatValue: announceValue,
+ messages: {
+ navigate: text.keyboardNavigate,
+ vertical: text.keyboardSections,
+ activate: text.keyboardActivate,
+ dismiss: text.keyboardDismiss,
+ noValues: text.noValues,
+ positiveValues: text.positiveValues,
+ negativeValues: text.negativeValues,
+ projected: text.projected,
+ },
+ });
+
+ const legendProjection = projected?.label;
+ const legend = React.useMemo(
+ (): readonly ChartLegendItem[] =>
+ legendProjection === undefined
+ ? legendOrder(series)
+ : [
+ ...legendOrder(series),
+ {
+ key: 'projection',
+ label: legendProjection,
+ description: projectionDescription,
+ color: PROJECTION_COLOR,
+ swatch: 'dashed',
+ },
+ ],
+ [legendProjection, projectionDescription, series],
+ );
+ const active = chart.selected;
+ const tooltipData = React.useMemo(
+ () => (active ? barTooltip({ active, series, projection: projected, format }) : null),
+ [active, series, projected, format],
+ );
+ const tooltip = tooltipData ? renderTooltip(tooltipData) : null;
+ const empty = data.length === 0;
+ const activatable = selection.onActivate !== undefined;
+ const style = React.useMemo(
+ (): ChartStyle => ({ type: 'bar', colors: bridge.colors, legend, format, empty, activatable, tooltip }),
+ [activatable, bridge.colors, empty, format, legend, tooltip],
+ );
+ return { chart, style };
+}
diff --git a/packages/mosaic/src/components/chart/chart-parts.styles.ts b/packages/mosaic/src/components/chart/chart-parts.styles.ts
new file mode 100644
index 00000000000..792dee04f1f
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart-parts.styles.ts
@@ -0,0 +1,61 @@
+import * as stylex from '@stylexjs/stylex';
+
+import { colorVars, durationVars, easingVars, radiusVars, shadowVars, space } from '../../tokens.stylex';
+
+export const partStyles = stylex.create({
+ gridLine: {
+ stroke: colorVars['--cl-color-border'],
+ strokeDasharray: '1 3',
+ strokeLinecap: 'round',
+ strokeWidth: 1,
+ },
+ yLine: {
+ stroke: colorVars['--cl-color-foreground'],
+ strokeWidth: 2,
+ },
+ tick: {
+ fill: {
+ default: colorVars['--cl-color-foreground-secondary'],
+ ':where([data-active])': colorVars['--cl-color-foreground'],
+ },
+ fontVariantNumeric: 'tabular-nums',
+ },
+ selection: {
+ borderRadius: radiusVars['--cl-radius-md'],
+ },
+ activatable: {
+ cursor: 'pointer',
+ },
+ cursor: {
+ borderRadius: radiusVars['--cl-radius-sm'],
+ backgroundColor: colorVars['--cl-color-neutral-alpha-200'],
+ },
+ tooltip: {
+ padding: space['3'],
+ borderRadius: radiusVars['--cl-radius-lg'],
+ backgroundColor: colorVars['--cl-color-surface'],
+ boxShadow: shadowVars['--cl-shadow-md'],
+ color: colorVars['--cl-color-foreground'],
+ opacity: {
+ default: 1,
+ ':where([data-starting-style], [data-ending-style])': 0,
+ },
+ transitionDuration: {
+ default: durationVars['--cl-duration-fast'],
+ ':where([data-moving])': `${durationVars['--cl-duration-fast']}, ${durationVars['--cl-duration-slow']}, ${durationVars['--cl-duration-slow']}`,
+ },
+ transitionProperty: {
+ default: 'opacity',
+ ':where([data-moving])': 'opacity, top, left',
+ '@media (prefers-reduced-motion: reduce)': {
+ default: 'opacity',
+ ':where([data-moving])': 'opacity',
+ },
+ },
+ transitionTimingFunction: {
+ default: easingVars['--cl-ease-enter'],
+ ':where([data-ending-style])': easingVars['--cl-ease-exit'],
+ },
+ zIndex: 10,
+ },
+});
diff --git a/packages/mosaic/src/components/chart/chart-parts.tsx b/packages/mosaic/src/components/chart/chart-parts.tsx
new file mode 100644
index 00000000000..96ff33400be
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart-parts.tsx
@@ -0,0 +1,202 @@
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import React from 'react';
+
+import {
+ Chart as Primitive,
+ type ChartGridProps as PrimitiveChartGridProps,
+ type ChartTooltipProps as PrimitiveChartTooltipProps,
+ type ChartXAxisProps as PrimitiveChartXAxisProps,
+ type ChartXTickProps as PrimitiveChartXTickProps,
+ type ChartYAxisProps as PrimitiveChartYAxisProps,
+ type ChartYLineProps as PrimitiveChartYLineProps,
+ type ChartYTickProps as PrimitiveChartYTickProps,
+} from '../../primitives/chart';
+import type { MosaicStyleProps } from '../../props';
+import { mergeStyleProps, themeProps } from '../../props';
+import { focusOutline } from '../../styles/focus-outline.styles';
+import { reset } from '../../styles/reset.styles';
+import { partStyles } from './chart-parts.styles';
+import { type ChartAxis, usePlotStyle } from './internal/chart-style';
+
+type Styled = Omit & MosaicStyleProps;
+
+/** Reserves an axis gutter beside the plot while the axis is mounted. */
+function useAxisGutter(axis: ChartAxis, part: string) {
+ const context = usePlotStyle(part);
+ const { registerAxis } = context;
+ React.useLayoutEffect(() => registerAxis(axis), [axis, registerAxis]);
+ return context;
+}
+
+export type ChartGridProps = Styled;
+
+/** Dotted lines at the Y ticks, below the bars. Children replace the lines. */
+export const ChartGrid = React.forwardRef(function ChartGrid(
+ { children, xstyle, ...rest },
+ ref,
+) {
+ usePlotStyle('Grid');
+ return (
+
+ {children ??
+ (ticks =>
+ ticks.map(tick => (
+
+ )))}
+
+ );
+});
+
+export type ChartYLineProps = Styled;
+
+/** A solid line at a Y value, such as the zero line inside `BarChart.Bars`. */
+export const ChartYLine = React.forwardRef(function ChartYLine(
+ { xstyle, ...rest },
+ ref,
+) {
+ return (
+
+ );
+});
+
+export type ChartYTickProps = Styled;
+
+export const ChartYTick = React.forwardRef(function ChartYTick(
+ { xstyle, ...rest },
+ ref,
+) {
+ return (
+
+ );
+});
+
+export type ChartYAxisProps = Styled;
+
+/**
+ * Value labels beside the plot, formatted with the chart's `formatValue`. Leaves them out while
+ * the chart has no rows. Children replace the labels.
+ */
+export const ChartYAxis = React.forwardRef(function ChartYAxis(
+ { format, children, xstyle, ...rest },
+ ref,
+) {
+ const { style } = useAxisGutter('y', 'YAxis');
+ const formatValue = style.format.value;
+ const formatTick = React.useCallback((value: number) => formatValue(value, 'axis'), [formatValue]);
+ return (
+
+ {children ??
+ (ticks =>
+ style.empty
+ ? null
+ : ticks.map(tick => (
+
+ )))}
+
+ );
+});
+
+export type ChartXTickProps = Styled;
+
+export const ChartXTick = React.forwardRef(function ChartXTick(
+ { xstyle, ...rest },
+ ref,
+) {
+ return (
+
+ );
+});
+
+export type ChartXAxisProps = Styled;
+
+/** Category labels below the plot, formatted with the chart's `formatCategory`. Children replace the labels. */
+export const ChartXAxis = React.forwardRef(function ChartXAxis(
+ { format, children, xstyle, ...rest },
+ ref,
+) {
+ const { style } = useAxisGutter('x', 'XAxis');
+ const formatCategory = style.format.category;
+ const formatTick = React.useCallback((key: string) => formatCategory(key, 'axis'), [formatCategory]);
+ return (
+
+ {children ??
+ (ticks =>
+ ticks.map(tick => (
+
+ )))}
+
+ );
+});
+
+/** The hover band behind the bars. */
+function ChartCursor() {
+ return ;
+}
+
+export type ChartTooltipProps = Styled> & {
+ /**
+ * Draws the hover band behind the bars.
+ *
+ * @default true
+ */
+ cursor?: boolean;
+};
+
+/**
+ * Pointer and keyboard selection, the hover band and the tooltip, which shows what the chart's
+ * `tooltip` prop renders. Leave it out for a chart that takes no focus.
+ */
+export const ChartTooltip = React.forwardRef(function ChartTooltip(
+ { cursor = true, xstyle, ...rest },
+ ref,
+) {
+ const { style } = usePlotStyle('Tooltip');
+ return (
+
+ {cursor ? : null}
+
+ {() => style.tooltip}
+
+
+ );
+});
diff --git a/packages/mosaic/src/components/chart/chart-root.styles.ts b/packages/mosaic/src/components/chart/chart-root.styles.ts
new file mode 100644
index 00000000000..557551bdf57
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart-root.styles.ts
@@ -0,0 +1,34 @@
+import * as stylex from '@stylexjs/stylex';
+
+import { space, typeScaleVars } from '../../tokens.stylex';
+
+export const rootStyles = stylex.create({
+ root: {
+ gap: space['4'],
+ display: 'flex',
+ flexDirection: 'column',
+ minWidth: 0,
+ width: '100%',
+ },
+ height: (height: string) => ({ height }),
+ plotArea: {
+ flexGrow: 1,
+ position: 'relative',
+ minHeight: 0,
+ },
+ plot: {
+ fontSize: typeScaleVars['--cl-text-xs-size'],
+ isolation: 'isolate',
+ },
+ overlay: {
+ inset: 0,
+ alignItems: 'center',
+ display: 'flex',
+ justifyContent: 'center',
+ position: 'absolute',
+ zIndex: 2,
+ },
+ retry: {
+ alignSelf: 'flex-start',
+ },
+});
diff --git a/packages/mosaic/src/components/chart/chart-root.tsx b/packages/mosaic/src/components/chart/chart-root.tsx
new file mode 100644
index 00000000000..abc1a15a1f2
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart-root.tsx
@@ -0,0 +1,264 @@
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import React from 'react';
+
+import { useMessages } from '../../localization/context';
+import { Chart as Primitive, type ChartInstance } from '../../primitives/chart';
+import type { MosaicElementProps } from '../../props';
+import { mergeStyleProps, themeProps } from '../../props';
+import { reset } from '../../styles/reset.styles';
+import { Banner } from '../banner';
+import { Button } from '../button';
+import { EmptyState } from '../empty-state';
+import { ChartBars } from './bars/chart-bars';
+import { ChartLegend } from './chart';
+import { ChartGrid, ChartTooltip, ChartXAxis, ChartYAxis } from './chart-parts';
+import { rootStyles } from './chart-root.styles';
+import {
+ type ChartAxis,
+ ChartPlotContext,
+ type ChartStyle,
+ ChartStyleContext,
+ type ChartStyleContextValue,
+ useChartStyle,
+} from './internal/chart-style';
+import { seriesColors } from './internal/series.styles';
+import { SERIES_SLOTS } from './internal/series-bridge';
+
+/** `ready` once there is data to draw, `empty` without rows, `error` when painting failed. */
+export type ChartState = 'ready' | 'empty' | 'error';
+
+/** The props every styled chart type shares. */
+export interface ChartFrameProps extends Omit, 'aria-label'> {
+ /** Names the chart for assistive technology. */
+ 'aria-label': string;
+ /**
+ * Total height, legend included, so the legend wrapping never changes the footprint.
+ *
+ * @default 320
+ */
+ height?: number | string;
+ /** Replaces the default `EmptyState` shown when the chart has no rows. */
+ renderEmptyState?: () => React.ReactNode;
+ /** Called when the Canvas fails to paint, before the built-in retry appears. */
+ onRenderError?: (error: Error) => void;
+ /**
+ * The layout: `BarChart.Legend`, `BarChart.Plot` and anything beside them. Default: the legend when
+ * there are two entries or more, then the plot
+ */
+ children?: React.ReactNode;
+}
+
+interface PlotState {
+ renderError: Error | null;
+ attempt: number;
+ fail: (error: Error) => void;
+ retry: () => void;
+ renderEmptyState: (() => React.ReactNode) | undefined;
+}
+
+const PlotStateContext = React.createContext(null);
+
+type FrameProps = ChartFrameProps &
+ Readonly<{
+ chart: ChartInstance;
+ chartStyle: ChartStyle;
+ registerAxis: (axis: ChartAxis) => () => void;
+ forwardedRef: React.ForwardedRef;
+ }>;
+
+/**
+ * The `cl-chart` root of a styled chart type: a column that sets each series color, reflects
+ * `data-chart` and `data-state`, and gives its parts the chart.
+ */
+export function ChartFrame({
+ chart,
+ chartStyle: style,
+ registerAxis,
+ forwardedRef,
+ 'aria-label': ariaLabel,
+ height = 320,
+ renderEmptyState,
+ onRenderError,
+ children,
+ xstyle,
+ ...rest
+}: FrameProps) {
+ const [renderError, setRenderError] = React.useState(null);
+ const [attempt, setAttempt] = React.useState(0);
+ const context = React.useMemo(
+ (): ChartStyleContextValue => ({ chart, style, ariaLabel, registerAxis }),
+ [ariaLabel, chart, registerAxis, style],
+ );
+ const plotState = React.useMemo(
+ (): PlotState => ({
+ renderError,
+ attempt,
+ fail: error => {
+ onRenderError?.(error);
+ setRenderError(error);
+ },
+ retry: () => {
+ setRenderError(null);
+ setAttempt(count => count + 1);
+ },
+ renderEmptyState,
+ }),
+ [attempt, onRenderError, renderEmptyState, renderError],
+ );
+ const state: ChartState = renderError ? 'error' : style.empty ? 'empty' : 'ready';
+ const colorStyles = style.colors.flatMap((color, position) => {
+ const slot = SERIES_SLOTS[position];
+ return slot === undefined ? [] : [seriesColors[slot](color)];
+ });
+
+ return (
+
+ );
+}
+
+export interface ChartPlotProps extends MosaicElementProps<'div'> {
+ /** The layers drawn on the plot, in paint order. Default: grid, bars, both axes and the tooltip */
+ children?: React.ReactNode;
+}
+
+/**
+ * The plot area (`cl-chart-plot-area`): takes the height the column leaves and holds the drawn
+ * layers on the headless root (`cl-chart-plot`). It shows the empty state without rows and offers a
+ * retry when the Canvas fails.
+ */
+export const ChartPlot = React.forwardRef(function ChartPlot(
+ { children, xstyle, ...rest },
+ ref,
+) {
+ const { chart, ariaLabel, style } = useChartStyle('Plot');
+ const plotState = React.useContext(PlotStateContext);
+ const messages = useMessages('chart');
+ if (!plotState) {
+ throw new Error(' must be used within a chart root, such as ');
+ }
+ const { renderError, attempt, fail, retry, renderEmptyState } = plotState;
+
+ return (
+
+ );
+});
+
+/** Covers the plot, for the empty and error states. */
+function ChartOverlay({ slot, children }: Readonly<{ slot: string; children: React.ReactNode }>) {
+ return
{children}
;
+}
+
+interface CanvasErrorBoundaryProps {
+ onError: (error: Error) => void;
+ children: React.ReactNode;
+}
+
+/** Catches a lost or missing Canvas context. Any other error keeps propagating. */
+class CanvasErrorBoundary extends React.Component {
+ override state: { error: unknown } = { error: null };
+
+ static getDerivedStateFromError(error: unknown) {
+ return { error };
+ }
+
+ override componentDidCatch(error: unknown) {
+ if (error instanceof Primitive.CanvasRenderError) {
+ this.props.onError(error);
+ }
+ }
+
+ override render() {
+ const { error } = this.state;
+ if (error === null) {
+ return this.props.children;
+ }
+ if (error instanceof Primitive.CanvasRenderError) {
+ return null;
+ }
+ // eslint-disable-next-line typescript/only-throw-error -- Rethrows what a child threw, unchanged, so the next boundary up handles it.
+ throw error;
+ }
+}
diff --git a/packages/mosaic/src/components/chart/chart-series.ts b/packages/mosaic/src/components/chart/chart-series.ts
new file mode 100644
index 00000000000..ed012775bca
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart-series.ts
@@ -0,0 +1,91 @@
+import type React from 'react';
+
+import { chartColorVars } from './chart.vars.stylex';
+
+type ChartTokenName = Extract;
+
+/**
+ * A palette slot, `n` for `--cl-color-chart-n`. Derived from the tokens, so a new slot token widens
+ * it and nothing else lists the slots.
+ */
+export type ChartPaletteSlot = ChartTokenName extends `--cl-color-chart-${infer Slot extends number}` ? Slot : never;
+
+/**
+ * A color outside the palette, for a series whose color carries meaning, such as a ramp or a brand
+ * color. A bare keyword such as `'purple'` does not compile, which also catches a misspelled slot.
+ */
+export type ChartCustomColor =
+ | `var(--${string})`
+ | `light-dark(${string})`
+ | `oklch(${string})`
+ | `oklab(${string})`
+ | `color-mix(${string})`
+ | `rgb(${string})`
+ | `hsl(${string})`
+ | `#${string}`;
+
+export type ChartColor = ChartPaletteSlot | ChartCustomColor;
+
+/**
+ * Slot `n` becomes `var(--cl-color-chart-n)`. A custom color passes through. Reading the slot from
+ * `chartColorVars` keeps the palette in the module graph, so a StyleX build that follows imports
+ * emits it.
+ */
+export function resolveChartColor(color: ChartColor): string {
+ return typeof color === 'number' ? chartColorVars[`--cl-color-chart-${color}`] : color;
+}
+
+/**
+ * One series, for any chart type. The series owns its color: marks, legend and tooltip all read
+ * this field, so filtering the list never repaints the series that remain.
+ */
+export interface ChartSeries {
+ /** Unique within the chart. Reflected as `data-series` on legend items and tooltip rows. */
+ key: string;
+ /** Shown in the legend and tooltip. */
+ label: string;
+ /** A palette slot or a CSS color. There is no default by position. */
+ color: ChartColor;
+ /** Reads the value from a row. Missing or non-finite values count as zero. */
+ value: (datum: TDatum) => number | null | undefined;
+ /** Shown in a tooltip on the legend item, which becomes focusable. */
+ description?: string;
+ /**
+ * Drawn below the zero line, such as churn. The legend lists it after the series above zero, top
+ * to bottom as the bars draw, and the tooltip lists its zero values with the negative section.
+ * Default: `false`
+ */
+ negative?: boolean;
+}
+
+/** `square` mirrors a bar, `line` a line, `dashed` a projection. */
+export type ChartSwatch = 'square' | 'line' | 'dashed';
+
+/** What a legend shows. A `ChartSeries` is assignable to it. */
+export interface ChartLegendItem {
+ key: string;
+ label: string;
+ color: ChartColor;
+ description?: string;
+ /** Default: 'square' */
+ swatch?: ChartSwatch;
+}
+
+/** One series row in a tooltip. `value` is already formatted. */
+export interface ChartTooltipRow {
+ key: string;
+ label: string;
+ color: ChartColor;
+ value: React.ReactNode;
+ /** Default: 'line' */
+ swatch?: ChartSwatch;
+}
+
+/** A summary row above the series rows, such as a total or a projection. */
+export interface ChartTooltipMetric {
+ label: string;
+ value: React.ReactNode;
+}
+
+/** Where a formatted string appears. An axis wants the short form, a tooltip the full one. */
+export type ChartFormatPlace = 'axis' | 'tooltip';
diff --git a/packages/mosaic/src/components/chart/chart.doc.ts b/packages/mosaic/src/components/chart/chart.doc.ts
new file mode 100644
index 00000000000..b17ed8292ca
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart.doc.ts
@@ -0,0 +1,360 @@
+import type { ComponentDoc } from '../../docs-schema';
+import type { BarChartRootProps } from './bars/bar-chart-root';
+import type { ChartBarProps, ChartBarsProps, ChartProjectionOutlineProps } from './bars/chart-bars';
+import type { ChartLegendProps, ChartTooltipContentProps } from './chart';
+import type {
+ ChartGridProps,
+ ChartTooltipProps,
+ ChartXAxisProps,
+ ChartXTickProps,
+ ChartYAxisProps,
+ ChartYLineProps,
+ ChartYTickProps,
+} from './chart-parts';
+import type { ChartPlotProps } from './chart-root';
+
+export default {
+ name: 'BarChart',
+ description:
+ 'Styled charts on the headless `Chart` primitive. `BarChart.Root` takes rows, a category key and series that each name a color. With no children it draws the whole chart: the legend, a dotted grid, the bars with their projection and zero line, both axes, and a tooltip with one row per series behind a hover band. Children replace that layout: `BarChart.Legend` goes anywhere, and `BarChart.Plot` holds the drawn layers. Each axis reserves its own room beside the plot. The chart sets each series color, reflects `data-chart` and `data-state` (`ready`, `empty` or `error`), shows the empty state and offers a retry when the Canvas fails. A series color is a palette slot `1` to `6`, which reads `--cl-color-chart-`, or any CSS color. Its styles and palette ship in `@clerk/mosaic/chart.css`, not `styles.css`. Import that sheet into the same cascade layer as `styles.css`.',
+ useFor: [
+ 'a stacked bar chart over a category or time axis',
+ 'bars with values above and below zero, such as sign-ups and churn',
+ 'a chart that dims every bar but the selected period or series',
+ 'a projected total for the current period',
+ 'a chart legend in a row beside an action, such as Export',
+ 'a preview chart without a tooltip or an axis',
+ 'a custom chart tooltip with a total, a change badge or a banner',
+ ],
+ keywords: [
+ 'chart',
+ 'bar chart',
+ 'stacked bars',
+ 'graph',
+ 'data viz',
+ 'legend',
+ 'tooltip',
+ 'projection',
+ 'series',
+ 'palette',
+ 'swatch',
+ ],
+ practices: [
+ {
+ do: true,
+ text: 'Start from `` with no children. Add children only to change the layout, and write the `BarChart.Plot` layers in paint order: `BarChart.Grid`, `BarChart.Bars`, `BarChart.YAxis`, `BarChart.XAxis`, then `BarChart.Tooltip` last.',
+ },
+ {
+ do: true,
+ text: 'Define `series` and `index` at module level or memoize them. A new array or function prepares the stacks again.',
+ },
+ { do: true, text: 'Give every series a `color`: a palette slot `1` to `6`, or a CSS color with meaning.' },
+ {
+ do: true,
+ text: 'Assign palette slots in order. Avoid slot 2 beside 4, 2 beside 6 and 3 beside 5 in one stack: those pairs are close for some color-blind readers.',
+ },
+ {
+ do: true,
+ text: 'Fold anything past eight series into one "Other" series. The chart throws on a ninth series and on a repeated key.',
+ },
+ {
+ do: true,
+ text: 'Leave out `BarChart.Tooltip` for a decorative chart, such as a preview. It then takes no focus.',
+ },
+ {
+ do: true,
+ text: 'Render a `Skeleton` with the same `height` while the data loads. The chart has no loading state.',
+ },
+ {
+ do: false,
+ text: 'Recolor a series from CSS. `cl-chart-bar` carries a position, not your key; change `series[i].color` or a `--cl-color-chart-` token.',
+ },
+ { do: false, text: 'Use the status colors for series. They mean success, failure and warning.' },
+ ],
+ parts: {
+ 'BarChart.Root': {
+ description:
+ 'A column (`cl-chart`) of the legend and the plot. Carries `data-chart="bar"` and `data-state`, and sets `--_cl-chart-series-` for each series.',
+ slot: 'cl-chart',
+ props: {
+ data: { type: 'readonly TDatum[]', doc: 'The rows, one per category.' },
+ index: {
+ type: '(datum: TDatum, index: number) => string',
+ doc: 'Returns a unique, stable category key. Define it at module level or memoize it.',
+ },
+ series: {
+ type: 'readonly ChartSeries[]',
+ doc: 'Stack order, bottom first: `{ key, label, color, value, description?, negative? }`. Define it at module level or memoize it.',
+ },
+ 'aria-label': { type: 'string', doc: 'Names the chart for assistive technology.' },
+ highlight: {
+ type: 'BarChartHighlight | null',
+ doc: '`{ category?, section?, series? }`. Keeps the matching bars at full strength and dims the rest.',
+ },
+ projection: {
+ type: 'BarChartProjection',
+ doc: '`{ category, value, label?, description? }`. A projected total for the row with that category key. `label` names it in the legend and tooltip.',
+ },
+ tooltip: {
+ type: '(tooltip: ChartTooltipData>) => React.ReactNode',
+ doc: 'Renders the tooltip body from `{ active, heading, metrics, rows }`. Return null to hide it.',
+ default: '`BarChart.TooltipContent` with the heading, metrics and rows',
+ },
+ onActivate: {
+ type: '(active: ActiveBar, event) => void',
+ doc: 'Called on click, Enter or Space. Makes the plot a button.',
+ },
+ formatValue: {
+ type: "(value: number, place: 'axis' | 'tooltip') => string",
+ doc: 'Formats a value for an axis tick or a tooltip row and announcement.',
+ },
+ formatCategory: {
+ type: "(key: string, place: 'axis' | 'tooltip') => string",
+ doc: 'Formats a category key.',
+ default: 'a UTC date key as a date, any other key as is',
+ },
+ margin: {
+ type: 'Partial',
+ doc: 'Overrides the room around the plot. Each axis reserves its own by default.',
+ },
+ height: { type: 'number | string', doc: 'Total height, legend included.', default: '320' },
+ renderEmptyState: {
+ type: '() => React.ReactNode',
+ doc: 'Replaces the default `EmptyState` shown when the chart has no rows.',
+ },
+ onRenderError: {
+ type: '(error: Error) => void',
+ doc: 'Called when the Canvas fails to paint, before the built-in retry appears.',
+ },
+ children: {
+ type: 'React.ReactNode',
+ doc: 'The layout: `BarChart.Legend`, `BarChart.Plot` and anything beside them.',
+ default: 'the legend from two entries, then `BarChart.Plot`',
+ },
+ },
+ },
+ 'BarChart.Plot': {
+ description:
+ 'The plot area (`cl-chart-plot-area`), which takes the height the column leaves and holds the headless root (`cl-chart-plot`). Covers the plot with `cl-chart-empty` without rows, and with `cl-chart-error`, a negative `Banner` with a retry, when the Canvas fails.',
+ slot: 'cl-chart-plot-area',
+ props: {
+ children: {
+ type: 'React.ReactNode',
+ doc: 'The drawn layers, in paint order.',
+ default: '`BarChart.Grid`, `BarChart.Bars`, `BarChart.YAxis`, `BarChart.XAxis` and `BarChart.Tooltip`',
+ },
+ },
+ },
+ 'BarChart.Legend': {
+ description:
+ 'A `ul` of swatch and label pairs. Inside a chart it lists the chart series top to bottom as the bars draw (the stack above zero from its top, then `negative` series from the zero line down), then a labelled projection as a dashed entry, wherever the layout places it. Elsewhere it takes `items`, such as beside a skeleton. Each item is `cl-chart-legend-item` with `data-series`, and `data-described` when it has a description, which makes it a focusable tooltip trigger. Swatches are `cl-chart-swatch` with `data-swatch`.',
+ slot: 'cl-chart-legend',
+ props: {
+ items: {
+ type: 'readonly ChartLegendItem[]',
+ doc: 'The entries, in order: `{ key, label, color, description?, swatch? }`. A `ChartSeries` fits as is.',
+ default: "the chart's series and projection",
+ },
+ children: {
+ type: '(item: ChartLegendItem) => React.ReactNode',
+ doc: 'Renders an item label. The swatch stays.',
+ default: 'item.label',
+ },
+ },
+ },
+ 'BarChart.Grid': {
+ description: 'Dotted lines (`cl-chart-grid-line`) at the Y ticks, below the bars.',
+ slot: 'cl-chart-grid',
+ props: {
+ children: {
+ type: '(ticks: readonly ChartTick[]) => React.ReactNode',
+ doc: 'Replaces the dotted lines.',
+ },
+ },
+ },
+ 'BarChart.YLine': {
+ description: 'A solid line at a Y value, such as the zero line inside `BarChart.Bars`.',
+ slot: 'cl-chart-y-line',
+ props: {
+ value: { type: 'number', doc: 'The value on the Y axis the line marks.' },
+ },
+ },
+ 'BarChart.Bars': {
+ description:
+ 'Paints the bars on Canvas above the cursor, so the hover band shows only in the gaps. Without children it renders `BarChart.Bar`, `BarChart.ProjectionOutline` and a zero `BarChart.YLine`.',
+ slot: 'cl-chart-bars',
+ },
+ 'BarChart.Bar': {
+ description:
+ 'The hidden element the Canvas reads. Its `color` is the series color, an opaque mix toward `--cl-color-surface` under `data-inactive` that keeps 40% of it; its `max-width`, `row-gap` and corner radii set the bar geometry.',
+ slot: 'cl-chart-bar',
+ },
+ 'BarChart.ProjectionOutline': {
+ description:
+ "A dashed outline around the projected total. The Canvas paints it from this hidden element's `stroke`, `stroke-width` and `stroke-dasharray`.",
+ slot: 'cl-chart-projection-outline',
+ },
+ 'BarChart.YAxis': {
+ description: 'Value labels beside the plot, left out while the chart has no rows.',
+ slot: 'cl-chart-y-axis',
+ props: {
+ format: {
+ type: '(value: number) => React.ReactNode',
+ doc: 'Formats a tick value.',
+ default: "the chart's `formatValue(value, 'axis')`",
+ },
+ children: {
+ type: '(ticks: readonly ChartYTickItem[]) => React.ReactNode',
+ doc: 'Replaces the labels, usually with one `BarChart.YTick` per entry.',
+ },
+ },
+ },
+ 'BarChart.YTick': {
+ description: 'One value label, in the secondary color with tabular figures.',
+ slot: 'cl-chart-y-tick',
+ props: { tick: { type: 'ChartYTickItem', doc: 'An entry from the `BarChart.YAxis` children function.' } },
+ },
+ 'BarChart.XAxis': {
+ description: 'Category labels below the plot.',
+ slot: 'cl-chart-x-axis',
+ props: {
+ ticks: {
+ type: "'category' | 'calendar'",
+ doc: '`category` thins labels to fit. `calendar` labels calendar boundaries, and needs UTC date keys.',
+ default: "'category'",
+ },
+ format: {
+ type: '(value: string) => string | null',
+ doc: 'Returns the label for a category key, or null to omit it.',
+ default: "the chart's `formatCategory(key, 'axis')`",
+ },
+ children: {
+ type: '(ticks: readonly XTick[]) => React.ReactNode',
+ doc: 'Replaces the labels, usually with one `BarChart.XTick` per entry.',
+ },
+ },
+ },
+ 'BarChart.XTick': {
+ description: 'One category label. Takes the foreground color under `data-active`.',
+ slot: 'cl-chart-x-tick',
+ props: { tick: { type: 'XTick', doc: 'An entry from the `BarChart.XAxis` children function.' } },
+ },
+ 'BarChart.Tooltip': {
+ description:
+ "Pointer and keyboard selection (`cl-chart-selection`), with a focus ring and a pointer cursor when the chart has `onActivate`, the hover band behind the bars (`cl-chart-cursor`), and the tooltip surface for the selected period, fading in and out. The body is what the chart's `tooltip` prop renders.",
+ slot: 'cl-chart-tooltip',
+ props: {
+ cursor: { type: 'boolean', doc: 'Draws the hover band behind the bars.', default: 'true' },
+ side: { type: "'left' | 'right'", doc: 'The side tried first.', default: "'right'" },
+ sideOffset: { type: 'number', doc: 'Distance in px from the period center.', default: '16' },
+ collisionPadding: { type: 'number', doc: 'Space in px kept from the boundary edges.', default: '8' },
+ collisionBoundary: {
+ type: 'React.RefObject',
+ doc: 'Element the tooltip stays inside.',
+ default: 'the chart',
+ },
+ pinned: {
+ type: "boolean | 'auto'",
+ doc: 'Pins the tooltip to the top left of the boundary. `auto` below a 416px plot.',
+ default: "'auto'",
+ },
+ },
+ },
+ 'BarChart.TooltipContent': {
+ description:
+ 'The body of a chart tooltip (`cl-chart-tooltip-content`): a heading row (`cl-chart-tooltip-heading`), metrics (`cl-chart-tooltip-metric`), one row per series (`cl-chart-tooltip-row` with `data-series`) and a footer (`cl-chart-tooltip-footer`) that wraps to the width the heading and rows set, so a long `Banner` never widens the tooltip. Values use tabular figures in the foreground color; labels use the secondary color.',
+ slot: 'cl-chart-tooltip-content',
+ props: {
+ heading: { type: 'ReactNode', doc: 'The period or category the tooltip describes.' },
+ trailing: { type: 'ReactNode', doc: 'Sits at the end of the heading row, such as a change `Badge`.' },
+ metrics: {
+ type: 'readonly ChartTooltipMetric[]',
+ doc: 'Summary rows, `{ label, value }`, above the series rows.',
+ default: '[]',
+ },
+ rows: {
+ type: 'readonly ChartTooltipRow[]',
+ doc: 'One row per series: `{ key, label, color, value, swatch? }`, with `value` already formatted.',
+ default: '[]',
+ },
+ footer: { type: 'ReactNode', doc: 'Sits below the rows, such as a `Banner`, and wraps to their width.' },
+ },
+ },
+ },
+ examples: [
+ {
+ title: 'A stacked bar chart',
+ code: `
+const series: ChartSeries[] = [
+ { key: 'signups', label: 'Sign-ups', color: 1, value: row => row.signups },
+ { key: 'churned', label: 'Churned', color: 3, value: row => row.churned, negative: true },
+];
+
+
+`,
+ },
+ {
+ title: 'A highlight and a projection',
+ code: `
+
+`,
+ },
+ {
+ title: 'A tooltip with a total',
+ code: `
+ (
+
+ )}
+/>
+`,
+ },
+ {
+ title: 'A legend beside an action, without a Y axis',
+ code: `
+
+
+
+
+
+
+
+
+
+
+
+
+`,
+ },
+ ],
+ related: ['Tooltip', 'EmptyState'],
+} satisfies ComponentDoc<{
+ 'BarChart.Root': BarChartRootProps;
+ 'BarChart.Plot': ChartPlotProps;
+ 'BarChart.Legend': ChartLegendProps;
+ 'BarChart.Grid': ChartGridProps;
+ 'BarChart.YLine': ChartYLineProps;
+ 'BarChart.Bars': ChartBarsProps;
+ 'BarChart.Bar': ChartBarProps;
+ 'BarChart.ProjectionOutline': ChartProjectionOutlineProps;
+ 'BarChart.YAxis': ChartYAxisProps;
+ 'BarChart.YTick': ChartYTickProps;
+ 'BarChart.XAxis': ChartXAxisProps;
+ 'BarChart.XTick': ChartXTickProps;
+ 'BarChart.Tooltip': ChartTooltipProps;
+ 'BarChart.TooltipContent': ChartTooltipContentProps;
+}>;
diff --git a/packages/mosaic/src/components/chart/chart.messages.ts b/packages/mosaic/src/components/chart/chart.messages.ts
new file mode 100644
index 00000000000..64b0437b35f
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart.messages.ts
@@ -0,0 +1,13 @@
+export const chartMessages = {
+ empty: 'No data to show',
+ renderError: 'The chart could not be displayed.',
+ retry: 'Try again',
+ keyboardNavigate: 'Use Left and Right to choose a period, or Home and End to jump to the first or last.',
+ keyboardSections: 'Use Up and Down to choose positive or negative values.',
+ keyboardActivate: 'Press Enter or Space to open the selected period.',
+ keyboardDismiss: 'Press Escape to dismiss.',
+ noValues: 'No values for this period',
+ positiveValues: 'positive values',
+ negativeValues: 'negative values',
+ projected: 'Projected',
+} as const;
diff --git a/packages/mosaic/src/components/chart/chart.styles.ts b/packages/mosaic/src/components/chart/chart.styles.ts
new file mode 100644
index 00000000000..38b9c63fe19
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart.styles.ts
@@ -0,0 +1,106 @@
+import * as stylex from '@stylexjs/stylex';
+
+import { colorVars, fontWeightVars, space, typeScaleVars } from '../../tokens.stylex';
+
+const swatchColor = 'var(--_cl-chart-swatch)';
+
+export const legendStyles = stylex.create({
+ root: {
+ listStyle: 'none',
+ alignItems: 'center',
+ color: colorVars['--cl-color-foreground-secondary'],
+ columnGap: space['4'],
+ display: 'flex',
+ flexWrap: 'wrap',
+ fontSize: typeScaleVars['--cl-text-sm-size'],
+ lineHeight: typeScaleVars['--cl-text-sm-leading'],
+ rowGap: space['1.5'],
+ },
+ item: {
+ gap: space['1.5'],
+ alignItems: 'center',
+ display: 'inline-flex',
+ },
+ trigger: {
+ borderWidth: 0,
+ gap: space['1.5'],
+ alignItems: 'center',
+ backgroundColor: 'transparent',
+ cursor: 'help',
+ display: 'inline-flex',
+ textDecorationLine: 'underline',
+ textDecorationStyle: 'dotted',
+ textUnderlineOffset: '0.2em',
+ },
+});
+
+export const swatchStyles = stylex.create({
+ base: {
+ display: 'inline-block',
+ flexShrink: 0,
+ },
+ square: {
+ borderRadius: '2px',
+ backgroundColor: swatchColor,
+ height: '0.625rem',
+ width: '0.625rem',
+ },
+ line: {
+ borderRadius: '1px',
+ backgroundColor: swatchColor,
+ height: '0.875rem',
+ width: '0.25rem',
+ },
+ dashed: {
+ borderTopColor: swatchColor,
+ borderTopStyle: 'dashed',
+ borderTopWidth: '2px',
+ height: 0,
+ width: '0.875rem',
+ },
+ color: (color: string) => ({ '--_cl-chart-swatch': color }),
+});
+
+export const tooltipContentStyles = stylex.create({
+ root: {
+ gap: space['2'],
+ color: colorVars['--cl-color-foreground'],
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: typeScaleVars['--cl-text-sm-size'],
+ lineHeight: typeScaleVars['--cl-text-sm-leading'],
+ minWidth: '10rem',
+ },
+ heading: {
+ gap: space['3'],
+ alignItems: 'center',
+ display: 'flex',
+ fontWeight: fontWeightVars['--cl-font-medium'],
+ justifyContent: 'space-between',
+ },
+ list: {
+ gap: space['1'],
+ listStyle: 'none',
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ row: {
+ gap: space['2'],
+ alignItems: 'center',
+ display: 'flex',
+ },
+ label: {
+ color: colorVars['--cl-color-foreground-secondary'],
+ flexGrow: 1,
+ },
+ value: {
+ fontVariantNumeric: 'tabular-nums',
+ fontWeight: fontWeightVars['--cl-font-medium'],
+ textAlign: 'end',
+ },
+ // Takes the width the heading and rows set, so a long footer wraps instead of widening the tooltip.
+ footer: {
+ minWidth: '100%',
+ width: 0,
+ },
+});
diff --git a/packages/mosaic/src/components/chart/chart.test-d.tsx b/packages/mosaic/src/components/chart/chart.test-d.tsx
new file mode 100644
index 00000000000..e0d20c62f36
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart.test-d.tsx
@@ -0,0 +1,86 @@
+import { expectTypeOf, test } from 'vitest';
+
+import { type ActiveBar, BarChart, type ChartSeries, type ChartTooltipData } from '.';
+
+type Energy = { week: string; solar: number };
+type Growth = { week: string; signups: number };
+
+const energy: Energy[] = [{ week: 'W1', solar: 18 }];
+const sources: ChartSeries[] = [{ key: 'solar', label: 'Solar', color: 5, value: row => row.solar }];
+const growth: ChartSeries[] = [{ key: 'signups', label: 'Sign-ups', color: 1, value: row => row.signups }];
+const getWeek = (row: Energy) => row.week;
+
+test('a series names its color: a palette slot or a CSS color', () => {
+ const custom: ChartSeries = {
+ key: 'grid',
+ label: 'Grid',
+ color: 'var(--overview-grid)',
+ value: row => row.solar,
+ };
+ void custom;
+ // @ts-expect-error A color is required. There is no default by position.
+ const missing: ChartSeries = { key: 'solar', label: 'Solar', value: row => row.solar };
+ // @ts-expect-error The palette has six slots.
+ const seventh: ChartSeries = { key: 'solar', label: 'Solar', color: 7, value: row => row.solar };
+ // @ts-expect-error A bare keyword is not a chart color.
+ const keyword: ChartSeries = { key: 'solar', label: 'Solar', color: 'violet', value: row => row.solar };
+ void [missing, seventh, keyword];
+});
+
+test('series read rows of the chart type', () => {
+ void (
+
+ );
+});
+
+test('the chart needs a name for assistive technology', () => {
+ void (
+ (
+ // @ts-expect-error The chart needs a name for assistive technology.
+
+ )
+ );
+});
+
+test('the tooltip receives the typed active bar without a type argument', () => {
+ void (
+ {
+ expectTypeOf(tooltip).toEqualTypeOf>>();
+ expectTypeOf(tooltip.active.datum.solar).toEqualTypeOf();
+ return (
+
+ );
+ }}
+ />
+ );
+});
+
+test('the activate handler receives the typed active bar', () => {
+ void (
+ expectTypeOf(bar.datum).toEqualTypeOf()}
+ />
+ );
+});
diff --git a/packages/mosaic/src/components/chart/chart.tsx b/packages/mosaic/src/components/chart/chart.tsx
new file mode 100644
index 00000000000..4acdeaa0fe9
--- /dev/null
+++ b/packages/mosaic/src/components/chart/chart.tsx
@@ -0,0 +1,185 @@
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import React from 'react';
+
+import type { MosaicElementProps } from '../../props';
+import { mergeStyleProps, themeProps } from '../../props';
+import { focusOutline } from '../../styles/focus-outline.styles';
+import { reset } from '../../styles/reset.styles';
+import { styles as buttonStyles } from '../button/button.styles';
+import { Tooltip } from '../tooltip';
+import { legendStyles, swatchStyles, tooltipContentStyles } from './chart.styles';
+import {
+ type ChartColor,
+ type ChartLegendItem,
+ type ChartSwatch,
+ type ChartTooltipMetric,
+ type ChartTooltipRow,
+ resolveChartColor,
+} from './chart-series';
+import { ChartStyleContext } from './internal/chart-style';
+
+function Swatch({ color, swatch }: Readonly<{ color: ChartColor; swatch: ChartSwatch }>) {
+ return (
+
+ );
+}
+
+export interface ChartLegendProps extends Omit, 'children'> {
+ /** The entries, in order. Default: the chart's series, then a labelled projection */
+ items?: readonly ChartLegendItem[];
+ /** Renders an item's label. The swatch stays. Default: `item.label` */
+ children?: (item: ChartLegendItem) => React.ReactNode;
+}
+
+/**
+ * A row of swatch and label pairs. Inside a chart it lists the chart's series, wherever the layout
+ * places it. Elsewhere it takes `items`, such as beside a skeleton.
+ */
+export const ChartLegend = React.forwardRef(function ChartLegend(
+ { items, children, xstyle, ...rest },
+ ref,
+) {
+ const chart = React.useContext(ChartStyleContext);
+ const entries = items ?? chart?.style.legend;
+ if (!entries) {
+ throw new Error('