Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test(storybook): add chart theming evidence (#7486)

rubyycheung17306ce7a4a3
diff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.js
index 85525db744..2b5eb53c39 100644
--- a/.github/scripts/story-play-guard.js
+++ b/.github/scripts/story-play-guard.js
@@ -74,6 +74,41 @@ const TARGETS = [
'ChartTooltip stays continuously open across content-bearing points in ' +
'nested Theme/MediaTheme scope above a native modal with nonzero geometry',
},
+ {
+ component: 'ChartTheming',
+ story: 'lab-charttheming-colorpicker--end-user-choices',
+ guards:
+ 'Automatic, theme, custom, mode switching, and Reset update the selected chart color',
+ },
+ {
+ component: 'ChartTheming',
+ story: 'lab-charttheming-recharts--theme-tokens',
+ guards:
+ 'Recharts resolves theme-aware resting colors and a same-series active-state tint in the browser',
+ },
+ {
+ component: 'ChartTheming',
+ story: 'lab-charttheming-recharts--runtime-theme-switch',
+ guards:
+ 'Recharts keeps its SVG and focused chart surface while authored data colors switch modes',
+ },
+ {
+ component: 'ChartTheming',
+ story: 'lab-charttheming-recharts--square-bars',
+ guards:
+ 'A chart can opt its bar geometry out of the theme radius without mutating the theme',
+ },
+ {
+ component: 'ChartTheming',
+ story: 'lab-charttheming-canvas--runtime-theme-switch',
+ guards: 'Canvas redraws concrete theme colors on the same drawing surface',
+ },
+ {
+ component: 'ChartTheming',
+ story: 'lab-charttheming-vega--serialized-canvas-config',
+ guards:
+ 'Vega receives serialized concrete values and explicitly rebuilds its View when config changes',
+ },
{
component: 'ChatToolCalls',
story: 'core-chattoolcalls--focused-grouped-detail',
diff --git a/apps/storybook/package.json b/apps/storybook/package.json
index ececf512e6..ff357edae7 100644
--- a/apps/storybook/package.json
+++ b/apps/storybook/package.json
@@ -24,6 +24,7 @@
"@astryxdesign/vega": "*",
"react": "^19.2.7",
"react-dom": "^19.2.7",
+ "recharts": "^3.9.2",
"unplugin": "^3.0.0",
"vega": "^6.2.0",
"vega-datasets": "^3.2.1",
diff --git a/apps/storybook/stories/ChartThemingCanvas.stories.tsx b/apps/storybook/stories/ChartThemingCanvas.stories.tsx
new file mode 100644
index 0000000000..416161afd2
--- /dev/null
+++ b/apps/storybook/stories/ChartThemingCanvas.stories.tsx
@@ -0,0 +1,166 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useEffect, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {Meta, StoryObj} from '@storybook/react';
+import {expect, waitFor} from 'storybook/test';
+import {Button, Card, Stack, Text} from '@astryxdesign/core';
+import {Theme, defineTheme, useTheme} from '@astryxdesign/core/theme';
+import {Heading} from '@astryxdesign/core/Text';
+import {useCssLengthInPixels} from './chartThemingUtils';
+
+const meta: Meta = {
+ title: 'Lab/ChartTheming/Canvas',
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Guide evidence for Canvas: `useTheme().token()` provides concrete theme values, and the same canvas redraws when mode changes.',
+ },
+ },
+ },
+};
+export default meta;
+
+type Story = StoryObj;
+
+const styles = stylex.create({
+ canvas: {
+ display: 'block',
+ height: 'auto',
+ maxWidth: '100%',
+ width: 480,
+ },
+});
+
+const canvasTheme = defineTheme({
+ name: 'chart-theming-canvas',
+ tokens: {
+ '--color-data-categorical-blue': ['#005A4E', '#72E1C1'],
+ },
+});
+
+let nextCanvasInstance = 1;
+
+function NativeCanvasChart() {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const instance = useRef(nextCanvasInstance++);
+ const drawCount = useRef(0);
+ const {token} = useTheme();
+ const color = token('--color-data-categorical-blue');
+ const fontFamily = token('--font-family-body');
+ const fontSize = token('--text-supporting-size');
+ const radius = useCssLengthInPixels(token('--radius-element'));
+
+ // Synchronize the canvas 2D bitmap with the resolved theme values.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ const context = canvas?.getContext('2d');
+ if (!canvas || !context) {
+ return;
+ }
+
+ context.clearRect(0, 0, canvas.width, canvas.height);
+ context.fillStyle = color;
+ context.beginPath();
+ context.roundRect(64, 64, 96, 112, [radius, radius, 0, 0]);
+ context.roundRect(240, 24, 96, 152, [radius, radius, 0, 0]);
+ context.fill();
+ context.fillStyle = token('--color-text-secondary');
+ context.font = `${fontSize} ${fontFamily}`;
+ context.fillText('Q1', 96, 204);
+ context.fillText('Q2', 272, 204);
+
+ drawCount.current += 1;
+ canvas.dataset.drawCount = String(drawCount.current);
+ }, [color, fontFamily, fontSize, radius, token]);
+
+ return (
+ <>
+ <canvas
+ {...stylex.props(styles.canvas)}
+ aria-label="Q1 is 112 units. Q2 is 152 units."
+ data-color={color}
+ data-font-family={fontFamily}
+ data-instance={instance.current}
+ data-radius={radius}
+ height={240}
+ ref={canvasRef}
+ role="img"
+ width={480}
+ />
+ <Text>Q1: 112 units · Q2: 152 units</Text>
+ </>
+ );
+}
+
+function RuntimeCanvasThemeSwitch() {
+ const [mode, setMode] = useState<'light' | 'dark'>('light');
+ return (
+ <Theme theme={canvasTheme} mode={mode}>
+ <Card>
+ <Stack direction="vertical" gap={4}>
+ <Stack direction="vertical" gap={1}>
+ <Heading level={3}>Quarterly comparison</Heading>
+ <Text type="supporting" color="secondary">
+ Canvas uses a concrete color and redraws without replacing its
+ drawing surface.
+ </Text>
+ </Stack>
+ <Button
+ label={`Switch to ${mode === 'light' ? 'dark' : 'light'} mode`}
+ onClick={() =>
+ setMode(current => (current === 'light' ? 'dark' : 'light'))
+ }
+ />
+ <NativeCanvasChart />
+ </Stack>
+ </Card>
+ </Theme>
+ );
+}
+
+function sampledBarPixel(canvas: HTMLCanvasElement): number[] {
+ const context = canvas.getContext('2d');
+ if (!context) {
+ throw new Error('Canvas 2D context is unavailable.');
+ }
+ return Array.from(context.getImageData(80, 80, 1, 1).data);
+}
+
+export const RuntimeThemeSwitch: Story = {
+ render: () => <RuntimeCanvasThemeSwitch />,
+ play: async ({canvasElement}) => {
+ const canvas = canvasElement.querySelector('canvas');
+ expect(canvas).not.toBeNull();
+ if (!canvas) {
+ return;
+ }
+
+ const instance = canvas.dataset.instance;
+ expect(canvasElement).toHaveTextContent('Q1: 112 units · Q2: 152 units');
+ let initialDrawCount = 0;
+ await waitFor(() => {
+ expect(canvas.dataset.color).toBe('#005A4E');
+ expect(canvas.dataset.fontFamily).not.toBe('');
+ expect(Number(canvas.dataset.radius)).toBeGreaterThan(5);
+ initialDrawCount = Number(canvas.dataset.drawCount);
+ expect(initialDrawCount).toBeGreaterThan(0);
+ expect(sampledBarPixel(canvas)).toEqual([0, 90, 78, 255]);
+ });
+
+ const button = canvasElement.querySelector('button');
+ expect(button).toHaveTextContent('Switch to dark mode');
+ button?.click();
+
+ await waitFor(() => {
+ expect(canvasElement.querySelector('canvas')).toBe(canvas);
+ expect(canvas.dataset.instance).toBe(instance);
+ expect(canvas.dataset.color).toBe('#72E1C1');
+ expect(Number(canvas.dataset.drawCount)).toBeGreaterThan(
+ initialDrawCount,
+ );
+ expect(sampledBarPixel(canvas)).toEqual([114, 225, 193, 255]);
+ });
+ },
+};
diff --git a/apps/storybook/stories/ChartThemingColorPicker.stories.tsx b/apps/storybook/stories/ChartThemingColorPicker.stories.tsx
new file mode 100644
index 0000000000..94eaa8bc6d
--- /dev/null
+++ b/apps/storybook/stories/ChartThemingColorPicker.stories.tsx
@@ -0,0 +1,303 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {Meta, StoryObj} from '@storybook/react';
+import {expect, fireEvent, userEvent, waitFor, within} from 'storybook/test';
+import {Button, Card, Stack, Text} from '@astryxdesign/core';
+import {Theme, defineTheme, useTheme} from '@astryxdesign/core/theme';
+import {dataVars} from '@astryxdesign/core/theme/dataTokens.stylex';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {Heading} from '@astryxdesign/core/Text';
+
+const meta: Meta = {
+ title: 'Lab/ChartTheming/ColorPicker',
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Product-owned chart color workflow using existing Astryx theme APIs: Automatic, curated theme choices, an exact custom color, and Reset.',
+ },
+ },
+ },
+};
+export default meta;
+
+type Story = StoryObj;
+
+const styles = stylex.create({
+ actions: {
+ alignItems: 'center',
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: spacingVars['--spacing-2'],
+ },
+ chart: {
+ alignItems: 'end',
+ backgroundColor: colorVars['--color-background-muted'],
+ borderRadius: radiusVars['--radius-container'],
+ display: 'flex',
+ gap: spacingVars['--spacing-4'],
+ height: 220,
+ padding: spacingVars['--spacing-6'],
+ },
+ bar: (color: string, height: number) => ({
+ backgroundColor: color,
+ borderRadius: `${radiusVars['--radius-element']} ${radiusVars['--radius-element']} 0 0`,
+ height,
+ width: 72,
+ }),
+ colorInput: {
+ blockSize: 36,
+ borderColor: colorVars['--color-border'],
+ borderRadius: radiusVars['--radius-element'],
+ borderStyle: 'solid',
+ borderWidth: 1,
+ inlineSize: 48,
+ padding: 2,
+ },
+ swatchOption: {
+ alignItems: 'center',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-1'],
+ },
+ swatch: (color: string, selected: boolean) => ({
+ backgroundColor: color,
+ borderColor: selected
+ ? colorVars['--color-border-emphasized']
+ : colorVars['--color-border'],
+ borderRadius: radiusVars['--radius-full'],
+ borderStyle: 'solid',
+ borderWidth: selected ? 3 : 1,
+ blockSize: 36,
+ cursor: 'pointer',
+ inlineSize: 36,
+ }),
+});
+
+const pickerTheme = defineTheme({
+ name: 'chart-color-picker',
+ tokens: {
+ '--color-data-categorical-blue': ['#005A4E', '#72E1C1'],
+ '--color-data-categorical-orange': ['#7A2E00', '#FFB280'],
+ '--color-data-categorical-purple': ['#5A21A8', '#C6A7FF'],
+ },
+});
+
+const productChartColors = [
+ {id: '--color-data-categorical-blue', label: 'Blue'},
+ {id: '--color-data-categorical-orange', label: 'Orange'},
+ {id: '--color-data-categorical-purple', label: 'Purple'},
+] as const;
+
+type ProductChartToken = (typeof productChartColors)[number]['id'];
+type ProductChartColorChoice =
+ {kind: 'theme'; token: ProductChartToken} | {kind: 'custom'; color: string};
+
+const automaticToken: ProductChartToken = productChartColors[0].id;
+
+function normalizeProductCustomColor(input: string): string | undefined {
+ return /^#[0-9A-F]{6}$/i.test(input) ? input.toUpperCase() : undefined;
+}
+
+function PickerContents({
+ mode,
+ onModeChange,
+}: {
+ mode: 'light' | 'dark';
+ onModeChange: () => void;
+}) {
+ const {token} = useTheme();
+ const [choice, setChoice] = useState<ProductChartColorChoice | undefined>();
+ const [customInput, setCustomInput] = useState('#336699');
+ const resolvedColor =
+ choice?.kind === 'custom'
+ ? choice.color
+ : token(choice?.token ?? automaticToken);
+ const paintColor =
+ choice?.kind === 'custom'
+ ? choice.color
+ : dataVars[choice?.token ?? automaticToken];
+ const state = choice?.kind ?? 'automatic';
+ const applyCustom = () => {
+ const normalized = normalizeProductCustomColor(customInput);
+ if (normalized) {
+ setChoice({kind: 'custom', color: normalized});
+ }
+ };
+
+ return (
+ <Card>
+ <Stack direction="vertical" gap={4}>
+ <Stack direction="vertical" gap={1}>
+ <Heading level={3}>Series color</Heading>
+ <Text type="supporting" color="secondary">
+ Theme choices follow the current mode. Exact custom colors stay
+ fixed.
+ </Text>
+ </Stack>
+
+ <div {...stylex.props(styles.chart)}>
+ <div
+ {...stylex.props(styles.bar(paintColor, 112))}
+ data-chart-color-preview
+ />
+ <div
+ {...stylex.props(
+ styles.bar(dataVars['--color-data-categorical-orange'], 164),
+ )}
+ />
+ </div>
+
+ <div
+ {...stylex.props(styles.actions)}
+ aria-label="Theme color choices"
+ role="group">
+ <Button
+ aria-pressed={choice === undefined}
+ label="Automatic"
+ onClick={() => setChoice(undefined)}
+ variant={choice === undefined ? 'primary' : 'secondary'}
+ />
+ {productChartColors.map(option => {
+ const selected =
+ choice?.kind === 'theme' && choice.token === option.id;
+ return (
+ <div {...stylex.props(styles.swatchOption)} key={option.id}>
+ <button
+ {...stylex.props(
+ styles.swatch(dataVars[option.id], selected),
+ )}
+ aria-label={`${option.label} chart color`}
+ aria-pressed={selected}
+ data-color-token={option.id}
+ onClick={() => setChoice({kind: 'theme', token: option.id})}
+ type="button"
+ />
+ <Text type="supporting">{option.label}</Text>
+ </div>
+ );
+ })}
+ </div>
+
+ <div {...stylex.props(styles.actions)}>
+ <input
+ {...stylex.props(styles.colorInput)}
+ aria-label="Exact custom color"
+ onChange={event => setCustomInput(event.currentTarget.value)}
+ type="color"
+ value={customInput}
+ />
+ <Button label="Apply custom color" onClick={applyCustom} />
+ <Button
+ label="Reset"
+ onClick={() => setChoice(undefined)}
+ variant="secondary"
+ />
+ <Button
+ label={`Switch to ${mode === 'light' ? 'dark' : 'light'} mode`}
+ onClick={onModeChange}
+ variant="secondary"
+ />
+ </div>
+
+ <Text>
+ <span data-choice-state={state} data-preview-color={resolvedColor}>
+ {state === 'automatic'
+ ? 'Automatic'
+ : state === 'theme'
+ ? 'Theme color'
+ : 'Custom color'}
+ : {resolvedColor}
+ </span>
+ </Text>
+ </Stack>
+ </Card>
+ );
+}
+
+function ColorPickerExample() {
+ const [mode, setMode] = useState<'light' | 'dark'>('light');
+ return (
+ <Theme theme={pickerTheme} mode={mode}>
+ <PickerContents
+ mode={mode}
+ onModeChange={() =>
+ setMode(current => (current === 'light' ? 'dark' : 'light'))
+ }
+ />
+ </Theme>
+ );
+}
+
+export const EndUserChoices: Story = {
+ render: () => <ColorPickerExample />,
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const state = () =>
+ canvasElement.querySelector<HTMLElement>('[data-choice-state]');
+ const previewBar = () =>
+ canvasElement.querySelector<HTMLElement>('[data-chart-color-preview]');
+ const expectPreviewBarColor = (color: string) => {
+ const bar = previewBar();
+ expect(bar).not.toBeNull();
+ if (!bar) {
+ return;
+ }
+ expect(getComputedStyle(bar).backgroundColor).toBe(color);
+ };
+ expect(state()).toHaveAttribute('data-choice-state', 'automatic');
+ expect(state()).toHaveAttribute('data-preview-color', '#005A4E');
+ expectPreviewBarColor('rgb(0, 90, 78)');
+ expect(canvas.getByRole('button', {name: 'Automatic'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+
+ const purple = canvas.getByRole('button', {name: 'Purple chart color'});
+ await userEvent.click(purple);
+ expect(purple).toHaveAttribute('aria-pressed', 'true');
+ expect(state()).toHaveAttribute('data-choice-state', 'theme');
+ expect(state()).toHaveAttribute('data-preview-color', '#5A21A8');
+ expectPreviewBarColor('rgb(90, 33, 168)');
+
+ await userEvent.click(
+ canvas.getByRole('button', {name: 'Switch to dark mode'}),
+ );
+ await waitFor(() => {
+ expect(state()).toHaveAttribute('data-preview-color', '#C6A7FF');
+ expectPreviewBarColor('rgb(198, 167, 255)');
+ });
+
+ fireEvent.change(canvas.getByLabelText('Exact custom color'), {
+ target: {value: '#33aaff'},
+ });
+ await userEvent.click(
+ canvas.getByRole('button', {name: 'Apply custom color'}),
+ );
+ expect(state()).toHaveAttribute('data-choice-state', 'custom');
+ expect(state()).toHaveAttribute('data-preview-color', '#33AAFF');
+ expectPreviewBarColor('rgb(51, 170, 255)');
+
+ await userEvent.click(
+ canvas.getByRole('button', {name: 'Switch to light mode'}),
+ );
+ await waitFor(() =>
+ expect(state()).toHaveAttribute('data-preview-color', '#33AAFF'),
+ );
+
+ await userEvent.click(canvas.getByRole('button', {name: 'Reset'}));
+ expect(state()).toHaveAttribute('data-choice-state', 'automatic');
+ expect(state()).toHaveAttribute('data-preview-color', '#005A4E');
+ expectPreviewBarColor('rgb(0, 90, 78)');
+ expect(canvas.getByRole('button', {name: 'Automatic'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ },
+};
diff --git a/apps/storybook/stories/ChartThemingRecharts.stories.tsx b/apps/storybook/stories/ChartThemingRecharts.stories.tsx
new file mode 100644
index 0000000000..8bb929af34
--- /dev/null
+++ b/apps/storybook/stories/ChartThemingRecharts.stories.tsx
@@ -0,0 +1,566 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {Meta, StoryObj} from '@storybook/react';
+import {expect, fireEvent, userEvent, waitFor, within} from 'storybook/test';
+import {Button, Card, Stack, Text} from '@astryxdesign/core';
+import {Theme, defineTheme, useTheme} from '@astryxdesign/core/theme';
+import {Heading} from '@astryxdesign/core/Text';
+import {useCssLengthInPixels} from './chartThemingUtils';
+import {dataVars} from '@astryxdesign/core/theme/dataTokens.stylex';
+import {
+ colorVars,
+ radiusVars,
+ shadowVars,
+ spacingVars,
+ typographyVars,
+ typeScaleVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ type TooltipContentProps,
+ XAxis,
+ YAxis,
+} from 'recharts';
+
+const meta: Meta = {
+ title: 'Lab/ChartTheming/Recharts',
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'This example passes public Astryx values to verified Recharts SVG and HTML paint props without an Astryx-specific adapter.',
+ },
+ },
+ },
+};
+export default meta;
+
+type Story = StoryObj;
+
+const styles = stylex.create({
+ chart: {
+ height: 320,
+ width: '100%',
+ },
+ legendItem: {
+ alignItems: 'center',
+ display: 'flex',
+ gap: spacingVars['--spacing-1'],
+ },
+ legendList: {
+ display: 'flex',
+ gap: spacingVars['--spacing-3'],
+ justifyContent: 'center',
+ listStyle: 'none',
+ margin: 0,
+ padding: 0,
+ },
+ table: {
+ borderCollapse: 'collapse',
+ width: '100%',
+ },
+ tableCell: {
+ borderBottomColor: colorVars['--color-border'],
+ borderBottomStyle: 'solid',
+ borderBottomWidth: 1,
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ textAlign: 'start',
+ },
+ tooltip: {
+ backgroundColor: colorVars['--color-background-card'],
+ borderColor: colorVars['--color-border'],
+ borderRadius: radiusVars['--radius-element'],
+ borderStyle: 'solid',
+ borderWidth: 1,
+ boxShadow: shadowVars['--shadow-med'],
+ color: colorVars['--color-text-primary'],
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ padding: spacingVars['--spacing-2'],
+ },
+ tooltipRow: {
+ alignItems: 'center',
+ display: 'flex',
+ gap: spacingVars['--spacing-1'],
+ justifyContent: 'space-between',
+ },
+});
+
+const data = [
+ {quarter: 'Q1', revenue: 128, costs: 82},
+ {quarter: 'Q2', revenue: 156, costs: 94},
+ {quarter: 'Q3', revenue: 143, costs: 101},
+ {quarter: 'Q4', revenue: 184, costs: 112},
+];
+
+const series = {
+ revenue: dataVars['--color-data-categorical-blue'],
+ costs: dataVars['--color-data-categorical-orange'],
+};
+
+const hoverSeries = {
+ revenue: `color-mix(in srgb, ${series.revenue} 88%, ${colorVars['--color-tint-hover']})`,
+ costs: `color-mix(in srgb, ${series.costs} 88%, ${colorVars['--color-tint-hover']})`,
+};
+
+const seriesDefinitions = [
+ {key: 'revenue', label: 'Revenue', color: series.revenue, dash: undefined},
+ {key: 'costs', label: 'Costs', color: series.costs, dash: '6 4'},
+] as const;
+
+function SeriesCue({color, dash}: {color: string; dash: string | undefined}) {
+ return (
+ <svg aria-hidden="true" focusable="false" height="12" width="28">
+ <line
+ stroke={color}
+ strokeDasharray={dash}
+ strokeWidth="3"
+ x1="1"
+ x2="27"
+ y1="6"
+ y2="6"
+ />
+ </svg>
+ );
+}
+
+function SeriesLegend() {
+ return (
+ <ul {...stylex.props(styles.legendList)} aria-label="Chart series">
+ {seriesDefinitions.map(definition => (
+ <li {...stylex.props(styles.legendItem)} key={definition.key}>
+ <SeriesCue color={definition.color} dash={definition.dash} />
+ <Text type="supporting">{definition.label}</Text>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+function SeriesTooltip({active, label, payload}: TooltipContentProps) {
+ if (!active || !payload?.length) {
+ return null;
+ }
+
+ return (
+ <div {...stylex.props(styles.tooltip)} data-chart-tooltip role="status">
+ <Text type="supporting">{label}</Text>
+ {payload.map(entry => {
+ const definition = seriesDefinitions.find(
+ candidate => candidate.key === String(entry.dataKey),
+ );
+ if (!definition) {
+ return null;
+ }
+ return (
+ <div
+ {...stylex.props(styles.tooltipRow)}
+ data-series-cue={definition.key}
+ key={definition.key}>
+ <span {...stylex.props(styles.legendItem)}>
+ <SeriesCue color={definition.color} dash={definition.dash} />
+ {definition.label}
+ </span>
+ <span>{String(entry.value)}</span>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function ExactValuesTable() {
+ return (
+ <table {...stylex.props(styles.table)}>
+ <caption>Quarterly performance values</caption>
+ <thead>
+ <tr>
+ <th {...stylex.props(styles.tableCell)} scope="col">
+ Quarter
+ </th>
+ <th {...stylex.props(styles.tableCell)} scope="col">
+ Revenue
+ </th>
+ <th {...stylex.props(styles.tableCell)} scope="col">
+ Costs
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {data.map(row => (
+ <tr key={row.quarter}>
+ <th {...stylex.props(styles.tableCell)} scope="row">
+ {row.quarter}
+ </th>
+ <td {...stylex.props(styles.tableCell)}>{row.revenue}</td>
+ <td {...stylex.props(styles.tableCell)}>{row.costs}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+}
+
+const customSeriesTheme = defineTheme({
+ name: 'chart-theming-custom-series',
+ tokens: {
+ '--color-data-categorical-blue': ['#005A4E', '#72E1C1'],
+ '--color-data-categorical-orange': ['#7A2E00', '#FFB280'],
+ },
+});
+
+const axisTickStyle = {
+ fill: colorVars['--color-text-secondary'],
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+};
+
+function ThemeAwareRechartsExample({
+ highlightRevenue = false,
+ useThemeRadius = true,
+}: {
+ highlightRevenue?: boolean;
+ useThemeRadius?: boolean;
+} = {}) {
+ const {token} = useTheme();
+ const themeRadius = useCssLengthInPixels(token('--radius-element'));
+ const barRadius = useThemeRadius ? themeRadius : 0;
+
+ return (
+ <Card>
+ <Stack direction="vertical" gap={4}>
+ <Stack direction="vertical" gap={1}>
+ <Heading level={3}>
+ {useThemeRadius
+ ? 'Quarterly performance'
+ : 'Quarterly performance — square bars'}
+ </Heading>
+ <Text type="supporting" color="secondary">
+ {useThemeRadius
+ ? 'Recharts uses the active Astryx theme for series, typography, hover, tooltip radius, and bar radius.'
+ : 'This opt-out keeps the bars square while the rest of the chart continues to use the active Astryx theme.'}
+ </Text>
+ </Stack>
+ <div
+ {...stylex.props(styles.chart)}
+ aria-label="Quarterly performance chart"
+ data-bar-radius={barRadius}
+ role="group">
+ <ResponsiveContainer>
+ <BarChart
+ data={data}
+ accessibilityLayer
+ desc="Revenue and costs for Q1 through Q4"
+ title="Quarterly performance">
+ <CartesianGrid
+ stroke={colorVars['--color-border']}
+ strokeDasharray="4 4"
+ vertical={false}
+ />
+ <XAxis
+ dataKey="quarter"
+ axisLine={{
+ stroke: colorVars['--color-border-emphasized'],
+ }}
+ tick={axisTickStyle}
+ tickLine={{
+ stroke: colorVars['--color-border-emphasized'],
+ }}
+ />
+ <YAxis axisLine={false} tick={axisTickStyle} tickLine={false} />
+ <Tooltip
+ content={props => <SeriesTooltip {...props} />}
+ cursor={{
+ fill: colorVars['--color-tint-hover'],
+ fillOpacity: 0.05,
+ }}
+ />
+ <Legend content={<SeriesLegend />} />
+ <Bar
+ activeBar={{
+ fill: hoverSeries.revenue,
+ stroke: colorVars['--color-text-primary'],
+ strokeWidth: 2,
+ }}
+ dataKey="revenue"
+ fill={highlightRevenue ? hoverSeries.revenue : series.revenue}
+ isAnimationActive={false}
+ name="Revenue"
+ radius={[barRadius, barRadius, 0, 0]}
+ stroke={
+ highlightRevenue
+ ? colorVars['--color-border-emphasized']
+ : colorVars['--color-text-primary']
+ }
+ strokeWidth={highlightRevenue ? 2 : 1}
+ />
+ <Bar
+ activeBar={{
+ fill: hoverSeries.costs,
+ stroke: colorVars['--color-text-primary'],
+ strokeDasharray: '6 4',
+ strokeWidth: 2,
+ }}
+ dataKey="costs"
+ fill={series.costs}
+ isAnimationActive={false}
+ name="Costs"
+ radius={[barRadius, barRadius, 0, 0]}
+ stroke={colorVars['--color-text-primary']}
+ strokeDasharray="6 4"
+ strokeWidth={1}
+ />
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ <ExactValuesTable />
+ </Stack>
+ </Card>
+ );
+}
+
+function CustomDataTokenThemeExample() {
+ return (
+ <Theme theme={customSeriesTheme} mode="light">
+ <ThemeAwareRechartsExample />
+ </Theme>
+ );
+}
+
+function RuntimeThemeSwitchExample() {
+ const [mode, setMode] = useState<'light' | 'dark'>('light');
+ return (
+ <Theme theme={customSeriesTheme} mode={mode}>
+ <Stack direction="vertical" gap={3}>
+ <Button
+ label={`Switch to ${mode === 'light' ? 'dark' : 'light'} mode`}
+ onClick={() =>
+ setMode(current => (current === 'light' ? 'dark' : 'light'))
+ }
+ />
+ <ThemeAwareRechartsExample />
+ </Stack>
+ </Theme>
+ );
+}
+
+function ThemeTokensExample() {
+ const [highlightRevenue, setHighlightRevenue] = useState(false);
+ return (
+ <Stack direction="vertical" gap={3}>
+ <Button
+ label={
+ highlightRevenue ? 'Clear Revenue highlight' : 'Highlight Revenue'
+ }
+ onClick={() => setHighlightRevenue(current => !current)}
+ />
+ <ThemeAwareRechartsExample highlightRevenue={highlightRevenue} />
+ </Stack>
+ );
+}
+
+const BAR_SELECTORS = {
+ revenue: `.recharts-bar-rectangle path[fill="${series.revenue}"]`,
+ costs: `.recharts-bar-rectangle path[fill="${series.costs}"]`,
+} as const;
+
+async function barFills(
+ canvasElement: HTMLElement,
+): Promise<Record<keyof typeof BAR_SELECTORS, string>> {
+ const fills = {revenue: '', costs: ''};
+ await waitFor(() => {
+ for (const [seriesName, selector] of Object.entries(BAR_SELECTORS)) {
+ const bar = canvasElement.querySelector<SVGElement>(selector);
+ expect(bar).not.toBeNull();
+ if (bar) {
+ fills[seriesName as keyof typeof BAR_SELECTORS] =
+ getComputedStyle(bar).fill;
+ }
+ }
+ expect(Object.values(fills)).not.toContain('');
+ });
+ return fills;
+}
+
+function resolveSvgFill(reference: SVGElement, fill: string): string {
+ const svg = reference.ownerSVGElement;
+ if (!svg) {
+ throw new Error('Expected the chart bar to belong to an SVG surface.');
+ }
+ const probe = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ probe.setAttribute('fill', fill);
+ probe.setAttribute('height', '1');
+ probe.setAttribute('width', '1');
+ probe.setAttribute('x', '-2');
+ probe.setAttribute('y', '-2');
+ probe.style.visibility = 'hidden';
+ svg.appendChild(probe);
+ const resolved = getComputedStyle(probe).fill;
+ probe.remove();
+ return resolved;
+}
+
+export const ThemeTokens: Story = {
+ render: () => <ThemeTokensExample />,
+ play: async ({canvasElement}) => {
+ const restingFills = await barFills(canvasElement);
+ expect(
+ within(canvasElement).getByRole('group', {
+ name: 'Quarterly performance chart',
+ }),
+ ).toBeVisible();
+ const revenueBar = canvasElement.querySelector<SVGElement>(
+ BAR_SELECTORS.revenue,
+ );
+ expect(revenueBar).not.toBeNull();
+ if (revenueBar) {
+ const expectedActiveFill = resolveSvgFill(
+ revenueBar,
+ hoverSeries.revenue,
+ );
+ const bounds = revenueBar.getBoundingClientRect();
+ fireEvent.mouseMove(revenueBar, {
+ clientX: bounds.left + bounds.width / 2,
+ clientY: bounds.top + bounds.height / 2,
+ });
+ await waitFor(() => {
+ const cursor = canvasElement.querySelector('.recharts-tooltip-cursor');
+ expect(cursor).toHaveAttribute('fill', colorVars['--color-tint-hover']);
+ expect(cursor).toHaveAttribute('fill-opacity', '0.05');
+ const activeBar = canvasElement.querySelector(
+ '.recharts-active-bar path',
+ );
+ expect(activeBar).toHaveAttribute('fill', hoverSeries.revenue);
+ expect(activeBar).toHaveAttribute(
+ 'stroke',
+ colorVars['--color-text-primary'],
+ );
+ expect(
+ canvasElement.querySelector('[data-chart-tooltip]'),
+ ).toBeVisible();
+ expect(
+ canvasElement.querySelector('[data-series-cue="costs"]'),
+ ).toBeVisible();
+ });
+ expect(expectedActiveFill).not.toBe(restingFills.revenue);
+ await userEvent.click(
+ within(canvasElement).getByRole('button', {
+ name: 'Highlight Revenue',
+ }),
+ );
+ await waitFor(() => {
+ const highlightedRevenueBar = Array.from(
+ canvasElement.querySelectorAll<SVGElement>(
+ '.recharts-bar-rectangle path',
+ ),
+ ).find(bar => bar.getAttribute('fill') === hoverSeries.revenue);
+ expect(highlightedRevenueBar).not.toBeUndefined();
+ if (highlightedRevenueBar) {
+ expect(getComputedStyle(highlightedRevenueBar).fill).toBe(
+ expectedActiveFill,
+ );
+ expect(highlightedRevenueBar).toHaveAttribute(
+ 'stroke',
+ colorVars['--color-border-emphasized'],
+ );
+ }
+ });
+ }
+ const radius = Number(
+ canvasElement
+ .querySelector('[data-bar-radius]')
+ ?.getAttribute('data-bar-radius'),
+ );
+ expect(Number.isFinite(radius)).toBe(true);
+ expect(radius).toBeGreaterThan(5);
+ expect(revenueBar?.getAttribute('d')).toContain(`A ${radius},${radius}`);
+ expect(
+ canvasElement.querySelector('.recharts-cartesian-grid line'),
+ ).toHaveAttribute('stroke', colorVars['--color-border']);
+ expect(
+ canvasElement.querySelector('.recharts-cartesian-axis-tick-value'),
+ ).toHaveAttribute('fill', colorVars['--color-text-secondary']);
+ const legend = within(canvasElement).getByRole('list', {
+ name: 'Chart series',
+ });
+ expect(legend).toBeVisible();
+ expect(legend.querySelector('li:last-child line')).toHaveAttribute(
+ 'stroke-dasharray',
+ '6 4',
+ );
+ expect(
+ within(canvasElement).getByText('Quarterly performance values'),
+ ).toBeVisible();
+ },
+};
+
+export const SquareBars: Story = {
+ render: () => <ThemeAwareRechartsExample useThemeRadius={false} />,
+ play: async ({canvasElement}) => {
+ await barFills(canvasElement);
+ expect(canvasElement.querySelector('[data-bar-radius]')).toHaveAttribute(
+ 'data-bar-radius',
+ '0',
+ );
+ expect(
+ canvasElement
+ .querySelector<SVGElement>(BAR_SELECTORS.revenue)
+ ?.getAttribute('d'),
+ ).not.toContain('A ');
+ expect(
+ within(canvasElement).getByRole('heading', {
+ name: 'Quarterly performance — square bars',
+ }),
+ ).toBeVisible();
+ },
+};
+
+export const CustomDataTokens: Story = {
+ render: () => <CustomDataTokenThemeExample />,
+ play: async ({canvasElement}) => {
+ expect(await barFills(canvasElement)).toEqual({
+ revenue: 'rgb(0, 90, 78)',
+ costs: 'rgb(122, 46, 0)',
+ });
+ },
+};
+
+export const RuntimeThemeSwitch: Story = {
+ render: () => <RuntimeThemeSwitchExample />,
+ play: async ({canvasElement}) => {
+ expect(await barFills(canvasElement)).toEqual({
+ revenue: 'rgb(0, 90, 78)',
+ costs: 'rgb(122, 46, 0)',
+ });
+
+ const surface = canvasElement.querySelector<SVGSVGElement>(
+ 'svg.recharts-surface',
+ );
+ const focusTarget = surface;
+ expect(surface).not.toBeNull();
+ expect(focusTarget).not.toBeNull();
+ focusTarget?.focus();
+ expect(document.activeElement).toBe(focusTarget);
+
+ const button = canvasElement.querySelector('button');
+ expect(button).toHaveTextContent('Switch to dark mode');
+ button?.click();
+
+ await waitFor(async () => {
+ expect(await barFills(canvasElement)).toEqual({
+ revenue: 'rgb(114, 225, 193)',
+ costs: 'rgb(255, 178, 128)',
+ });
+ });
+ expect(canvasElement.querySelector('svg.recharts-surface')).toBe(surface);
+ expect(document.activeElement).toBe(focusTarget);
+ },
+};
diff --git a/apps/storybook/stories/ChartThemingVega.stories.tsx b/apps/storybook/stories/ChartThemingVega.stories.tsx
new file mode 100644
index 0000000000..699fa4758f
--- /dev/null
+++ b/apps/storybook/stories/ChartThemingVega.stories.tsx
@@ -0,0 +1,253 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useMemo, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {Meta, StoryObj} from '@storybook/react';
+import {expect, userEvent, waitFor, within} from 'storybook/test';
+import {Button, Card, Stack, Text} from '@astryxdesign/core';
+import {Theme, defineTheme, useTheme} from '@astryxdesign/core/theme';
+import {radiusVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {VegaChart, type AnySpec} from '@astryxdesign/vega';
+import type {Config} from 'vega-lite';
+import {Heading} from '@astryxdesign/core/Text';
+import {useCssLengthInPixels} from './chartThemingUtils';
+
+const meta: Meta<typeof VegaChart> = {
+ title: 'Lab/ChartTheming/Vega',
+ component: VegaChart,
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Guide evidence for configuration-driven rendering with the existing Astryx Vega package. Theme values are concrete and JSON-safe; changing compile configuration rebuilds the current Vega View and can reset renderer-owned state.',
+ },
+ },
+ },
+};
+export default meta;
+
+type Story = StoryObj;
+
+const styles = stylex.create({
+ chart: {
+ borderRadius: radiusVars['--radius-container'],
+ overflow: 'hidden',
+ },
+});
+
+const vegaTheme = defineTheme({
+ name: 'chart-theming-vega',
+ tokens: {
+ '--color-data-categorical-blue': ['#005A4E', '#72E1C1'],
+ '--color-data-categorical-orange': ['#7A2E00', '#FFB280'],
+ },
+});
+
+function useVegaLiteThemeConfig(): Config {
+ const {token} = useTheme();
+ return useMemo(
+ () => ({
+ background: token('--color-background-card'),
+ axis: {
+ domainColor: token('--color-border-emphasized'),
+ gridColor: token('--color-border'),
+ labelColor: token('--color-text-secondary'),
+ labelFont: token('--font-family-body'),
+ titleColor: token('--color-text-primary'),
+ titleFont: token('--font-family-heading'),
+ },
+ legend: {
+ labelColor: token('--color-text-secondary'),
+ labelFont: token('--font-family-body'),
+ titleColor: token('--color-text-primary'),
+ titleFont: token('--font-family-heading'),
+ },
+ range: {
+ category: [
+ token('--color-data-categorical-blue'),
+ token('--color-data-categorical-orange'),
+ token('--color-data-categorical-purple'),
+ token('--color-data-categorical-green'),
+ ],
+ },
+ title: {
+ color: token('--color-text-primary'),
+ font: token('--font-family-heading'),
+ },
+ view: {stroke: null},
+ }),
+ [token],
+ );
+}
+
+const values = [
+ {quarter: 'Q1', series: 'Revenue', value: 128},
+ {quarter: 'Q1', series: 'Costs', value: 82},
+ {quarter: 'Q2', series: 'Revenue', value: 156},
+ {quarter: 'Q2', series: 'Costs', value: 94},
+ {quarter: 'Q3', series: 'Revenue', value: 143},
+ {quarter: 'Q3', series: 'Costs', value: 101},
+ {quarter: 'Q4', series: 'Revenue', value: 184},
+ {quarter: 'Q4', series: 'Costs', value: 112},
+];
+
+function VegaThemeExample() {
+ const {token} = useTheme();
+ const [generation, setGeneration] = useState(0);
+ const latestView = useRef<unknown>(null);
+ const radius = useCssLengthInPixels(token('--radius-element'));
+ const categoryColor = token('--color-data-categorical-blue');
+
+ const config = useVegaLiteThemeConfig();
+ const serializedConfig = JSON.stringify(config);
+
+ const spec = useMemo<AnySpec>(
+ () => ({
+ $schema: 'https://vega.github.io/schema/vega-lite/v6.json',
+ data: {name: 'table'},
+ description:
+ 'Quarterly revenue and costs: Q1 128 and 82, Q2 156 and 94, Q3 143 and 101, Q4 184 and 112.',
+ title: 'Quarterly performance',
+ mark: {
+ type: 'bar',
+ cornerRadiusTopLeft: radius,
+ cornerRadiusTopRight: radius,
+ },
+ encoding: {
+ x: {
+ axis: {title: 'Quarter'},
+ field: 'quarter',
+ type: 'ordinal',
+ },
+ y: {
+ axis: {title: 'Value'},
+ field: 'value',
+ type: 'quantitative',
+ },
+ color: {
+ field: 'series',
+ legend: {title: 'Series'},
+ type: 'nominal',
+ },
+ tooltip: [
+ {field: 'quarter', type: 'ordinal'},
+ {field: 'series', type: 'nominal'},
+ {field: 'value', type: 'quantitative'},
+ ],
+ },
+ }),
+ [radius],
+ );
+
+ return (
+ <Stack direction="vertical" gap={3}>
+ <div
+ {...stylex.props(styles.chart)}
+ data-category-color={categoryColor}
+ data-config={serializedConfig}
+ data-radius={radius}
+ data-view-generation={generation}>
+ <VegaChart
+ compileOptions={{config}}
+ data={{table: values}}
+ onReady={view => {
+ if (latestView.current !== view) {
+ latestView.current = view;
+ setGeneration(current => current + 1);
+ }
+ }}
+ spec={spec}
+ viewOptions={{renderer: 'canvas'}}
+ />
+ </div>
+ <Text type="supporting" color="secondary">
+ View generation: {generation}. Changing concrete config rebuilds the
+ Vega View, so products must restore any zoom, hover, or signal state
+ they own.
+ </Text>
+ </Stack>
+ );
+}
+
+function RuntimeVegaThemeSwitch() {
+ const [mode, setMode] = useState<'light' | 'dark'>('light');
+ return (
+ <Theme theme={vegaTheme} mode={mode}>
+ <Card>
+ <Stack direction="vertical" gap={4}>
+ <Stack direction="vertical" gap={1}>
+ <Heading level={3}>Quarterly revenue</Heading>
+ <Text type="supporting" color="secondary">
+ Vega receives concrete, serializable colors and theme typography.
+ </Text>
+ </Stack>
+ <Button
+ label={`Switch to ${mode === 'light' ? 'dark' : 'light'} mode`}
+ onClick={() =>
+ setMode(current => (current === 'light' ? 'dark' : 'light'))
+ }
+ />
+ <VegaThemeExample />
+ </Stack>
+ </Card>
+ </Theme>
+ );
+}
+
+export const SerializedCanvasConfig: Story = {
+ render: () => <RuntimeVegaThemeSwitch />,
+ play: async ({canvasElement}) => {
+ const wrapper = canvasElement.querySelector<HTMLElement>(
+ '[data-view-generation]',
+ );
+ expect(wrapper).not.toBeNull();
+ if (!wrapper) {
+ return;
+ }
+
+ const readConfig = () =>
+ JSON.parse(wrapper.dataset.config ?? '{}') as Config & {
+ axis?: {
+ domainColor?: string;
+ gridColor?: string;
+ titleFont?: string;
+ };
+ range?: {category?: string[]};
+ };
+
+ await waitFor(() => {
+ expect(Number(wrapper.dataset.viewGeneration)).toBeGreaterThan(0);
+ expect(wrapper.dataset.categoryColor).toBe('#005A4E');
+ expect(Number(wrapper.dataset.radius)).toBeGreaterThan(5);
+ expect(wrapper.dataset.config).not.toContain('var(');
+ const config = readConfig();
+ expect(config.axis?.domainColor).toBeTruthy();
+ expect(config.axis?.gridColor).toBeTruthy();
+ expect(config.axis?.titleFont).toBeTruthy();
+ expect(config.range?.category?.slice(0, 2)).toEqual([
+ '#005A4E',
+ '#7A2E00',
+ ]);
+ expect(wrapper.querySelector('canvas')).not.toBeNull();
+ });
+ const firstGeneration = Number(wrapper.dataset.viewGeneration);
+ const firstCanvas = wrapper.querySelector('canvas');
+
+ const modeButton = within(canvasElement).getByRole('button', {
+ name: 'Switch to dark mode',
+ });
+ await userEvent.click(modeButton);
+
+ await waitFor(() => {
+ expect(wrapper.dataset.categoryColor).toBe('#72E1C1');
+ expect(readConfig().range?.category?.slice(0, 2)).toEqual([
+ '#72E1C1',
+ '#FFB280',
+ ]);
+ expect(Number(wrapper.dataset.viewGeneration)).toBeGreaterThan(
+ firstGeneration,
+ );
+ expect(wrapper.querySelector('canvas')).not.toBe(firstCanvas);
+ });
+ },
+};
diff --git a/apps/storybook/stories/chartThemingUtils.ts b/apps/storybook/stories/chartThemingUtils.ts
new file mode 100644
index 0000000000..df352b4de2
--- /dev/null
+++ b/apps/storybook/stories/chartThemingUtils.ts
@@ -0,0 +1,36 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useLayoutEffect, useState} from 'react';
+
+/** Resolve a concrete CSS length before passing it to a numeric renderer API. */
+function cssLengthToPixels(value: string): number {
+ if (typeof document === 'undefined' || !document.body) {
+ return 0;
+ }
+
+ const probe = document.createElement('div');
+ probe.style.blockSize = '0';
+ probe.style.inlineSize = value;
+ probe.style.pointerEvents = 'none';
+ probe.style.position = 'fixed';
+ probe.style.visibility = 'hidden';
+ if (!probe.style.inlineSize) {
+ return 0;
+ }
+
+ document.body.appendChild(probe);
+ const pixels = probe.getBoundingClientRect().width;
+ probe.remove();
+ return Number.isFinite(pixels) ? pixels : 0;
+}
+
+export function useCssLengthInPixels(value: string): number {
+ const [pixels, setPixels] = useState(0);
+
+ // Measure the hidden probe's laid-out inline size before the renderer paints.
+ useLayoutEffect(() => {
+ setPixels(cssLengthToPixels(value));
+ }, [value]);
+
+ return pixels;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 447e7650c6..5fc09c6cd9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -448,6 +448,9 @@ importers:
react-dom:
specifier: ^19.2.7
version: 19.2.7([email protected])
+ recharts:
+ specifier: ^3.9.2
unplugin:
specifier: ^3.0.0