Skip to content

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

TypeScript

fix(charts): harden Chart contract (#6247)

Cindy Zhang2247368d3a63
diff --git a/.changeset/chart-audit-contract.md b/.changeset/chart-audit-contract.md
new file mode 100644
index 0000000000..dc8cf84773
--- /dev/null
+++ b/.changeset/chart-audit-contract.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Localize Chart accessibility text and complete its consumer guidance.
+
+@cixzhang
diff --git a/apps/storybook/stories/charts/Chart.stories.tsx b/apps/storybook/stories/charts/Chart.stories.tsx
new file mode 100644
index 0000000000..a06c517d26
--- /dev/null
+++ b/apps/storybook/stories/charts/Chart.stories.tsx
@@ -0,0 +1,108 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {Chart, ChartAxis, ChartGrid, bar, line} from '@astryxdesign/charts';
+
+const monthlyData = [
+ {month: 'Jan', revenue: 42, trend: 38},
+ {month: 'Feb', revenue: 58, trend: 46},
+ {month: 'Mar', revenue: 51, trend: 49},
+ {month: 'Apr', revenue: 74, trend: 61},
+ {month: 'May', revenue: 68, trend: 65},
+ {month: 'Jun', revenue: 86, trend: 72},
+];
+
+const largeData = Array.from({length: 51}, (_, index) => ({
+ month: `Period ${index + 1}`,
+ revenue: 40 + (index % 8) * 6,
+ trend: 42 + index * 0.75,
+}));
+
+type DataState = 'default' | 'empty' | 'large';
+type TitleState = 'default' | 'none' | 'long';
+type LegendPosition = 'off' | 'top' | 'bottom' | 'start' | 'end';
+
+interface ChartStoryArgs {
+ dataState: DataState;
+ titleState: TitleState;
+ legendPosition: LegendPosition;
+ hasTooltip: boolean;
+ height: number;
+}
+
+const meta: Meta<ChartStoryArgs> = {
+ title: 'Charts/Chart',
+ tags: ['autodocs'],
+ argTypes: {
+ dataState: {
+ control: 'inline-radio',
+ options: ['default', 'empty', 'large'],
+ },
+ titleState: {control: 'inline-radio', options: ['default', 'none', 'long']},
+ legendPosition: {
+ control: 'inline-radio',
+ options: ['off', 'top', 'bottom', 'start', 'end'],
+ },
+ hasTooltip: {control: 'boolean'},
+ height: {control: {type: 'range', min: 160, max: 480, step: 20}},
+ },
+ args: {
+ dataState: 'default',
+ titleState: 'default',
+ legendPosition: 'bottom',
+ hasTooltip: true,
+ height: 300,
+ },
+};
+
+export default meta;
+
+type Story = StoryObj<ChartStoryArgs>;
+
+/**
+ * Reusable Chart-root fixture for normal, empty, large-data, long-text,
+ * legend-position, tooltip, and height evidence.
+ */
+export const Playground: Story = {
+ render: ({dataState, titleState, legendPosition, hasTooltip, height}) => {
+ const data =
+ dataState === 'empty'
+ ? []
+ : dataState === 'large'
+ ? largeData
+ : monthlyData;
+ const title =
+ titleState === 'none'
+ ? undefined
+ : titleState === 'long'
+ ? 'Monthly revenue across every regional sales program and reporting period'
+ : 'Monthly revenue';
+ const subtitle =
+ titleState === 'long'
+ ? 'A deliberately expanded description that verifies the chart heading wraps without hiding the plot or creating horizontal scrolling.'
+ : undefined;
+
+ return (
+ <Chart
+ data={data}
+ xKey="month"
+ series={[
+ bar('revenue', {group: 'comparison', label: 'Revenue'}),
+ line('trend', {label: 'Trend'}),
+ ]}
+ title={title}
+ subtitle={subtitle}
+ legend={legendPosition === 'off' ? false : {position: legendPosition}}
+ tooltip={hasTooltip}
+ grid={<ChartGrid horizontal />}
+ axes={
+ <>
+ <ChartAxis position="bottom" />
+ <ChartAxis position="left" />
+ </>
+ }
+ height={height}
+ />
+ );
+ },
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 980194dd84..45a5f35ae0 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -1411,6 +1411,11 @@
"path": "examples/center/vertical-horizontal-center",
"aliases": []
},
+ {
+ "name": "example-chart-trend-comparison",
+ "path": "examples/chart/trend-comparison",
+ "aliases": []
+ },
{
"name": "example-chat-composer-drawer-attachments",
"path": "examples/chat-composer-drawer/attachments",
diff --git a/packages/charts/blocks/ChartTrendComparison.template.mjs b/packages/charts/blocks/ChartTrendComparison.template.mjs
new file mode 100644
index 0000000000..56d127fcc3
--- /dev/null
+++ b/packages/charts/blocks/ChartTrendComparison.template.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: 'Chart - Trend Comparison',
+ displayName: 'Chart - Trend Comparison',
+ description:
+ 'Compares actual values with a planned trend on one shared chart scale.',
+ exampleFor: 'Chart',
+ aspectRatio: 16 / 10,
+ isShowcase: false,
+ componentsUsed: ['Chart', 'ChartAxis', 'ChartGrid'],
+};
diff --git a/packages/charts/blocks/ChartTrendComparison.tsx b/packages/charts/blocks/ChartTrendComparison.tsx
new file mode 100644
index 0000000000..87ba1aa5e9
--- /dev/null
+++ b/packages/charts/blocks/ChartTrendComparison.tsx
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {Chart, ChartAxis, ChartGrid, bar, line} from '@astryxdesign/charts';
+
+const quarterlyResults = [
+ {quarter: 'Q1', actual: 48, plan: 45},
+ {quarter: 'Q2', actual: 57, plan: 54},
+ {quarter: 'Q3', actual: 62, plan: 66},
+ {quarter: 'Q4', actual: 78, plan: 72},
+];
+
+export default function ChartTrendComparison() {
+ return (
+ <Chart
+ data={quarterlyResults}
+ xKey="quarter"
+ series={[bar('actual', {label: 'Actual'}), line('plan', {label: 'Plan'})]}
+ title="Quarterly results"
+ subtitle="Actual revenue compared with plan"
+ legend
+ tooltip
+ grid={<ChartGrid horizontal />}
+ axes={
+ <>
+ <ChartAxis position="bottom" />
+ <ChartAxis position="left" />
+ </>
+ }
+ height={280}
+ />
+ );
+}
diff --git a/packages/charts/src/Chart.doc.mjs b/packages/charts/src/Chart.doc.mjs
index 58c0704f6e..99ded9e055 100644
--- a/packages/charts/src/Chart.doc.mjs
+++ b/packages/charts/src/Chart.doc.mjs
@@ -7,10 +7,287 @@ export const docs = {
displayName: 'Chart',
group: 'Charts',
category: 'Data Visualization',
+ keywords: [
+ 'chart',
+ 'graph',
+ 'plot',
+ 'visualization',
+ 'bar chart',
+ 'line chart',
+ 'data',
+ ],
usage: {
- description: '',
+ description:
+ 'Chart lays out one or more mark definitions against shared responsive x and y scales. Use it for data visualizations that combine Astryx chart marks, axes, grids, legends, tooltips, and custom interaction layers.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Give the chart a concise title that states what is measured, and use subtitle for the comparison, time range, or other context needed to interpret it.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use the same series array for Chart and any directly composed ChartTooltip so labels, colors, and resolved points stay aligned.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use color as the only way to distinguish series or communicate status. Pair color with labels, mark shapes, direct annotations, or another visible cue.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Reuse one mark definition object across multiple Chart instances. Mark definitions currently carry per-chart layout metadata and are single-use.',
+ },
+ ],
+ accessibility: [
+ {
+ name: 'Accessible chart name',
+ category: 'Semantics',
+ criterion: '1.1.1 Non-text Content',
+ requirement: 'Required',
+ states: ['All'],
+ description:
+ 'Provide title when a product-specific name is available. Without it, Chart derives a localized name from the primary series labels and xKey.',
+ },
+ {
+ name: 'Small-data table',
+ category: 'Content',
+ criterion: '1.1.1 Non-text Content',
+ requirement: 'Required for supported small datasets',
+ states: ['1–100 row × series cells'],
+ description:
+ 'Chart mirrors small datasets into a visually hidden table. For larger datasets, provide an equivalent nearby summary or data view because the built-in table is intentionally omitted.',
+ },
+ {
+ name: 'Meaningful chart graphics',
+ category: 'Color contrast',
+ criterion: '1.4.11 Non-text Contrast',
+ requirement: '3:1 when the graphic carries information',
+ states: ['Light', 'Dark', 'Supported themes'],
+ description:
+ 'Measure meaningful marks and state indicators against their rendered backdrop. Decorative grid lines are not required to meet the non-text threshold.',
+ },
+ {
+ name: 'Tooltip information',
+ category: 'Keyboard',
+ criterion: '2.1.1 Keyboard and 2.5.1 Pointer Gestures',
+ requirement: 'Supplemental only',
+ states: ['Tooltip enabled'],
+ description:
+ 'Do not make hover-only tooltip content the only way to obtain important values. Keep the hidden table or another equivalent data view available.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'Header',
+ required: false,
+ description:
+ 'Optional visible title and supporting subtitle above the plot.',
+ },
+ {
+ name: 'Plot',
+ required: true,
+ description:
+ 'Responsive SVG coordinate space containing the clipped series marks.',
+ },
+ {
+ name: 'Grid and axes',
+ required: false,
+ description:
+ 'Caller-supplied ChartGrid and ChartAxis elements that share the plot scales.',
+ },
+ {
+ name: 'Legend',
+ required: false,
+ description:
+ 'Derived or caller-supplied series labels and swatches placed above, below, at the start, or at the end of the plot.',
+ },
+ {
+ name: 'Tooltip and interactions',
+ required: false,
+ description:
+ 'Pointer-driven overlays that consume the chart interaction stream.',
+ },
+ {
+ name: 'Data table',
+ required: false,
+ description:
+ 'Visually hidden tabular alternative rendered for small datasets.',
+ },
+ ],
},
- props: [],
+ props: [
+ {
+ name: 'data',
+ type: 'Record<string, unknown>[]',
+ description:
+ 'Rows to visualize. Each row may contain the x field and one or more series fields.',
+ required: true,
+ },
+ {
+ name: 'xKey',
+ type: 'string',
+ description: 'Field name read from each data row for the shared x scale.',
+ required: true,
+ },
+ {
+ name: 'series',
+ type: 'SeriesDef[]',
+ description:
+ 'Mark definitions created by helpers such as bar(), line(), area(), or dot(). Build a fresh array for each Chart.',
+ required: true,
+ },
+ {
+ name: 'height',
+ type: 'number',
+ description: 'Chart height in CSS pixels.',
+ default: '300',
+ },
+ {
+ name: 'margin',
+ type: 'Partial<ChartMargin>',
+ description:
+ 'Plot inset overrides in CSS pixels for top, right, bottom, and left.',
+ default: '{top: 24, right: 24, bottom: 32, left: 48}',
+ },
+ {
+ name: 'yBaseline',
+ type: "'auto' | 'zero' | 'data'",
+ description:
+ 'How Chart derives the y-domain when yDomain is omitted: mark-aware zero/headroom, symmetric around zero, or tight to the data extent.',
+ default: "'auto'",
+ },
+ {
+ name: 'yDomain',
+ type: '[number, number]',
+ description:
+ 'Explicit y-domain. When set, it takes precedence over yBaseline, automatic headroom, and scale nicening.',
+ },
+ {
+ name: 'xDomain',
+ type: '[number, number]',
+ description:
+ 'Explicit x-domain for numeric scales, including an empty streaming window. Categorical scales ignore it.',
+ },
+ {
+ name: 'grid',
+ type: 'ReactNode',
+ description:
+ 'Grid content rendered behind the series, normally ChartGrid.',
+ slotElements: [{__element: 'ChartGrid', props: {horizontal: true}}],
+ },
+ {
+ name: 'axes',
+ type: 'ReactNode',
+ description:
+ 'Axis content rendered after the series, normally one or more ChartAxis elements.',
+ slotElements: [
+ {__element: 'ChartAxis', props: {position: 'bottom'}},
+ {__element: 'ChartAxis', props: {position: 'left'}},
+ ],
+ },
+ {
+ name: 'legend',
+ type: 'boolean | ChartLegendProps',
+ description:
+ 'Set true for a derived bottom legend, or pass items, position, and alignment.',
+ default: 'false',
+ },
+ {
+ name: 'tooltip',
+ type: "boolean | Omit<ChartTooltipProps, 'series'>",
+ description:
+ 'Set true for the grouped pointer tooltip, or pass render and presentation options.',
+ default: 'false',
+ },
+ {
+ name: 'interactions',
+ type: 'ReactNode',
+ description:
+ 'Interaction overlays rendered above the pointer-capture layer.',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description:
+ 'Additional SVG content rendered after the built-in tooltip for advanced composition.',
+ },
+ {
+ name: 'title',
+ type: 'string',
+ description:
+ 'Visible heading and accessible name for the chart image. A localized fallback is derived when omitted.',
+ },
+ {
+ name: 'subtitle',
+ type: 'string',
+ description:
+ 'Visible supporting text that also describes the chart image.',
+ },
+ {
+ name: 'ref',
+ type: 'Ref<HTMLDivElement>',
+ description: 'Ref forwarded to the root chart container.',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value, not an inline style object like style={{}}.',
+ },
+ {
+ name: 'className',
+ type: 'string',
+ description: 'CSS class name appended to the root chart container.',
+ },
+ {
+ name: 'style',
+ type: 'CSSProperties',
+ description:
+ 'Inline styles merged onto the root chart container after the component styles.',
+ },
+ ],
+
+ examples: [
+ {
+ label: 'Bar and trend line',
+ code: `import {Chart, ChartAxis, ChartGrid, bar, line} from '@astryxdesign/charts';
+
+const series = [
+ bar('revenue', {label: 'Revenue'}),
+ line('trend', {label: 'Trend'}),
+];
+
+<Chart
+ data={monthlyRevenue}
+ xKey="month"
+ series={series}
+ title="Monthly revenue"
+ grid={<ChartGrid horizontal />}
+ axes={
+ <>
+ <ChartAxis position="bottom" />
+ <ChartAxis position="left" />
+ </>
+ }
+ legend
+ tooltip
+/>;`,
+ },
+ {
+ label: 'Stable numeric window',
+ code: `<Chart
+ data={streamedValues}
+ xKey="timestamp"
+ series={[line('value')]}
+ xDomain={[windowStart, windowEnd]}
+ yDomain={[0, 100]}
+ title="Live utilization"
+/>;`,
+ },
+ ],
};
diff --git a/packages/charts/src/Chart.spec.md b/packages/charts/src/Chart.spec.md
new file mode 100644
index 0000000000..fae12eb57e
--- /dev/null
+++ b/packages/charts/src/Chart.spec.md
@@ -0,0 +1,208 @@
+---
+schema_version: 3
+template_version: 4
+kind: component
+id: component:Chart
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, layout, theming, accessibility]
+verified_by:
+ [
+ packages/charts/src/Chart.test.tsx,
+ apps/storybook/stories/charts/Chart.stories.tsx,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:component-test-sufficiency,
+ architecture:component-theming-surface,
+ ]
+contributing: []
+system_specs: [spec:AST-002, spec:AST-029]
+---
+
+# Chart component contract
+
+## Intent
+
+Chart coordinates one responsive Cartesian plot. It derives shared scales,
+assigns default series colors, delegates drawing to series definitions, and hosts
+optional chart chrome and interaction layers.
+
+## Compatibility and migration
+
+- Released default preserved: `not yet stable`; `@astryxdesign/charts` is canary-only.
+- Compatibility class: existing props, defaults, render order, and output remain unchanged by this observational backfill.
+- Controlled/uncontrolled behavior: not applicable.
+- Migration decision: none; this draft does not authorize a public API change.
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- Measuring the chart container and deriving one plot area and scale set.
+- Ordering, clipping, and coordinating series, chart chrome, and interaction slots.
+- The chart image's accessible name and small-data table fallback.
+
+**Does not own / non-goals**
+
+- Mark-specific geometry or rendering; each series definition owns those details.
+- Axis, grid, legend, or tooltip presentation beyond their placement in the root.
+- Product-specific interpretation, summary, or analysis of the supplied data.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ---------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | -------------------------------------------- | ----------------- | ------------ | ----------------------------------------------------------------------------------------------------- |
+| Data model | `data`, `xKey`, `series` | Rows, shared x field, and mark definitions for one plot. | Always required. | none | `component:Chart` | experimental | Missing fields are rejected by TypeScript; malformed row values are handled by each mark. |
+| Height | finite number | Outer SVG height in CSS pixels. | All charts. | `300` | `component:Chart` | experimental | Negative or non-finite values resolve to `0`. |
+| Plot margin | partial `top`, `right`, `bottom`, `left` numbers | Insets the shared plot area. | All charts. | `{top: 24, right: 24, bottom: 32, left: 48}` | `component:Chart` | experimental | Non-finite resulting geometry is clamped to `0`; the physical field names remain an open API finding. |
+| Y baseline | `auto`, `zero`, `data` | Chooses mark-aware zero/headroom, symmetric zero, or tight data extent. | Used when `yDomain` is absent. | `auto` | `component:Chart` | experimental | Unknown values are rejected by TypeScript. |
+| Explicit domains | `xDomain`, `yDomain` finite numeric pairs | Pins numeric scale domains. | `xDomain` is ignored for categorical x; `yDomain` overrides baseline and nicening. | absent | `component:Chart` | experimental | Non-finite pairs fall back to automatic derivation. |
+| Chart chrome | `grid`, `axes`, `legend`, `tooltip` | Places caller-supplied or built-in chart context consumers around the series. | Optional. | off/absent | `component:Chart` | experimental | False/omitted boolean-or-config values disable the built-in surface. |
+| Extension slots | `interactions`, `children` | Adds interaction overlays and advanced SVG content in defined paint order. | Optional. | absent | `component:Chart` | experimental | Caller content renders as supplied. |
+| Accessible text | `title`, `subtitle`, generated fallback | Names and describes the chart image. | All charts; visible when supplied. | localized generated name | `component:Chart` | experimental | A generic localized name is used when no primary series exists. |
+| Root DOM surface | `BaseProps<HTMLDivElement>`, `ref` | Forwards standard DOM, data, ARIA, class, style, StyleX, events, and the root element ref. | All charts. | absent | `component:Chart` | experimental | Component-owned SVG semantics remain on the SVG. |
+
+## Behavioral and layout contract
+
+Draft requirements identify their basis so observed code is not mistaken for an intentional decision.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- | ------------------ |
+| FR1 | Chart MUST reserve its configured height while width is zero, then recompute plot geometry after container resizes. | current implementation and `Chart measurement gate` tests | verify |
+| FR2 | All series, axes, grid lines, tooltips, and interactions MUST consume one shared scale set derived from the current data, domains, baseline, and measured plot size. | README, implementation, and package tests | verify |
+| FR3 | Paint order MUST remain grid → clipped series → axes → pointer layer → interactions → built-in tooltip → children. | current implementation and render-delegation tests | verify |
+| FR4 | Primary series without a static color MUST receive deterministic colors from the active theme palette; utility marks MUST NOT consume palette or legend slots. | implementation, palette test, and browser evidence | verify |
+| FR5 | Pointer movement MUST be normalized into plot coordinates and dispatch the nearest x-position; leaving the plot MUST clear the pointer state. | current implementation and tooltip browser evidence | verify |
+| FR6 | `legend=true` MUST derive items from primary series; legend and tooltip config objects MUST enable their surfaces while overriding supported options. | current implementation and focused tests | verify |
+| FR7 | The chart MUST expose a named `role="img"`; a supplied subtitle MUST be its description; datasets up to 100 row×series cells MUST also be mirrored in a visually hidden table. | current implementation, WCAG 1.1.1, and accessibility tests | verify |
+| FR8 | Root DOM props and `ref` MUST reach the root container while Chart's own SVG name and description remain authoritative. | shared BaseProps convention and focused regression test | verify |
+
+### Allowed variation
+
+- **AV1 — Series output.** Mark definitions may render different SVG or canvas content while preserving the shared layout and render-order seams.
+- **AV2 — Consumer chrome.** Grid, axes, interaction, and children slots may be absent or contain any valid chart-context consumer.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------ |
+| Width not measured | Height-reserving root only; no invalid SVG geometry. | Consumer root styling and DOM props remain applied. |
+| Normal data | Shared finite scales and one clipped group per resolved series. | Mark shape, color, and content come from series definitions. |
+| Empty data | Finite fallback scales; no invalid mark geometry. | Visible empty-state treatment remains unsettled. |
+| Small data | Named image plus hidden data table. | Cell text follows supplied row values. |
+| More than 100 cells | Named image; built-in hidden table omitted. | Equivalent large-data alternative remains unsettled. |
+| Title and subtitle | Visible header; SVG title/description associations. | Consumer text content. |
+| Legend enabled | Derived or explicit items at top, bottom, start, or end. | Alignment and supplied items. |
+| Tooltip enabled | Pointer updates the indicator and grouped tooltip; leave clears it. | Custom renderer and placement. |
+| Narrow / RTL | No horizontal page overflow; logical stack placement follows direction. | Physical chart-domain order remains data-owned. |
+
+### Transformation and precedence order
+
+- **ORD1 — Dimensions.** Merge default and supplied margins → clamp height and inner dimensions → derive scales → resolve series → render in FR3 order.
+- **ORD2 — Domains.** A finite explicit domain wins; otherwise derive finite data extent → expand degenerate extent → apply the requested baseline/headroom → apply nicening only to automatic domains.
+- **ORD3 — Accessible name.** Supplied title wins; otherwise format primary-series labels with the provider locale and interpolate them with `xKey`; with no primary series, use the localized generic name.
+
+### Performance and resources
+
+- **PR1 — Resize observation.** Each mounted chart observes its root with a dedicated `ResizeObserver` and disconnects it on unmount; migration to the shared observer remains an audit FIX.
+- **PR2 — Pointer dispatch.** Pointer movement updates subscribers directly; tooltip React state changes only when the nearest data index changes.
+
+## Accessibility contract
+
+- **AR1 — Named image.** The SVG MUST expose `role="img"` with the resolved accessible name.
+- **AR2 — Description.** A supplied subtitle MUST be linked through `aria-describedby` to an SVG `desc`.
+- **AR3 — Small-data alternative.** Up to 100 row×primary-series cells MUST be mirrored in a semantically headed, visually hidden table.
+- **AR4 — Large-data gap.** The current name-only path above the table cutoff does not guarantee an equivalent alternative; resolution requires owner review and remains an audit finding.
+- **AR5 — Tooltip supplement.** Pointer tooltip content MUST NOT be the only available source for required chart information.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ------------------------------------------------------- | ---------------------------------------------------------- | -------------- | ------------------ |
+| Header | Core Text roles | delegated to `component:Text` | supporting | FR7 |
+| Plot and marks | Meaningful graphics meet rendered contrast requirements | objective WCAG threshold; mark representation is unsettled | primary | FR2, FR4 |
+| Legend | Labels and swatches preserve series association | delegated to `component:ChartLegend` | supporting | FR6 |
+| Tooltip | Temporal overlay | current Design Conventions | supporting | FR5, FR6, AR5 |
+| Hidden table | Nonvisual data alternative | objective accessibility semantics | supporting | AR3, AR4 |
+
+### Theming anatomy
+
+<!-- anatomy-theming:v1 -->
+
+```json
+{
+ "Header": {
+ "none": {
+ "reason": "intentional: Text owns the visible title and subtitle styling."
+ }
+ },
+ "Plot": {
+ "none": {
+ "reason": "unsettled: Chart does not currently expose a public theme target for the SVG plot root."
+ }
+ },
+ "Grid and axes": {
+ "none": {
+ "reason": "unsettled: ChartGrid and ChartAxis own their output but do not yet have current component contracts."
+ }
+ },
+ "Legend": {
+ "none": {
+ "reason": "unsettled: ChartLegend owns the visible legend but does not yet have a current component contract."
+ }
+ },
+ "Tooltip and interactions": {
+ "none": {
+ "reason": "unsettled: ChartTooltip and consumer interaction layers own their painting surfaces."
+ }
+ },
+ "Data table": {
+ "none": {
+ "reason": "intentional: The small-data table is visually hidden accessibility content."
+ }
+ }
+}
+```
+
+## Family and system relationships
+
+- `architecture:component-test-sufficiency` owns evidence quality and rational state partitioning.
+- `architecture:component-theming-surface` owns anatomy-to-theme reachability.
+- `spec:AST-002` owns public API admission and operation shape.
+- `spec:AST-029` owns observational audit backfill and the external evidence receipt.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------ | ------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
+| FR1, PR1 | `Chart.test.tsx`; Chromium narrow captures | zero and positive width; resize; 320 px | Removing measurement or cleanup leaves a blank/stale plot or a leaked observer. | `audit:Chart/responsive-code-health` |
+| FR2–FR4, ORD1–ORD2 | Chart and package tests; light/dark browser matrix | band and linear x; automatic/explicit domains; grouped/stacked/utility marks | A scale diverges, geometry becomes non-finite, clipping/order changes, or palette ownership drifts. | `audit:Chart/behavior-theming` |
+| FR5–FR6, PR2 | tooltip/legend tests; Chromium hover and layout captures | hover/leave; derived/configured legend; all placements | Tooltip state goes stale, pointer work causes per-move commits, or chrome renders in the wrong layer. | `audit:Chart/behavior` |
+| FR7, AR1–AR5, ORD3 | accessible-name/table tests; package-specific axe; browser receipts | title/subtitle; generated name; small, empty, and large data | Name/description disappears, the small-data table is lost, localization regresses, or the large-data gap is hidden. | `audit:Chart/accessibility-i18n` |
+| FR8 | root-prop/ref regression test and package typecheck | placeholder and measured render | DOM props or ref stop reaching the root, or consumer styling replaces component styling. | `audit:Chart/public-api` |
+
+## Decision log
+
+None. This draft records observed behavior and open gaps only.
+
+## Open questions
+
+- **OQ1 — Large-data alternative.** What equivalent nonvisual data or summary contract must Chart guarantee after the 100-cell table cutoff? (`human-api`)
+- **OQ2 — Directional margins.** Should the experimental physical `left`/`right` margin fields migrate to logical names before a stable release? (`human-api`)
+- **OQ3 — Series metadata.** How should per-chart identity, stack state, and resolved colors move behind a private boundary before the canary API stabilizes? (`human-api`)
+- **OQ4 — Theming root.** Should Chart expose a public target for its plot/root surface, or intentionally remain token-only? (`human-design`)
+
+## Content boundary
+
+This file does not duplicate consumer prop tables/examples, current audit results,
+implementation steps, or shared system rules. It links to their owners.
diff --git a/packages/charts/src/Chart.test.tsx b/packages/charts/src/Chart.test.tsx
index b95446c102..dcee800e83 100644
--- a/packages/charts/src/Chart.test.tsx
+++ b/packages/charts/src/Chart.test.tsx
@@ -3,17 +3,20 @@
/**
* @file Chart.test.tsx
* @input Uses vitest, @testing-library/react, Chart root + bar/line marks
- * @output Unit tests for Chart accessibility (WCAG 1.1.1) and the chart
- * root's functional contract — measurement gate, per-series render
+ * @output Unit tests for Chart accessibility (WCAG 1.1.1), localized fallback
+ * text, root DOM/ref passthrough, and the chart root's functional
+ * contract — measurement gate, per-series render
* delegation, event layer geometry, palette assignment, and the
* declarative legend/tooltip slots (issue #4295 viz coverage)
* @position Testing; validates Chart.tsx accessible name + data-table fallback
*/
+import {createRef} from 'react';
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
-import {render, screen, act, within} from '@testing-library/react';
+import {render, screen, act, within, fireEvent} from '@testing-library/react';
import {Chart} from './Chart';
import {bar, line} from './marks';
+import {InternationalizationProvider} from '@astryxdesign/core';
const data = [
{month: 'Jan', revenue: 100, profit: 20},
@@ -23,16 +26,20 @@ const data = [
// Capture the ResizeObserver callback so tests can drive the reported width.
let resizeCallback: ResizeObserverCallback | undefined;
+let observedElement: Element | undefined;
beforeEach(() => {
resizeCallback = undefined;
+ observedElement = undefined;
vi.stubGlobal(
'ResizeObserver',
class {
constructor(cb: ResizeObserverCallback) {
resizeCallback = cb;
}
- observe() {}
+ observe(element: Element) {
+ observedElement = element;
+ }
unobserve() {}
disconnect() {}
},
@@ -44,9 +51,17 @@ afterEach(() => {
});
function reportWidth(width: number) {
+ if (!observedElement) {
+ throw new Error('Chart did not subscribe to ResizeObserver');
+ }
act(() => {
resizeCallback?.(
- [{contentRect: {width}} as unknown as ResizeObserverEntry],
+ [
+ {
+ target: observedElement,
+ contentRect: {width},
+ } as unknown as ResizeObserverEntry,
+ ],
{} as ResizeObserver,
);
});
@@ -64,7 +79,7 @@ describe('Chart accessible name', () => {
reportWidth(600);
expect(
- screen.getByRole('img', {name: 'Chart of revenue, profit by month'}),
+ screen.getByRole('img', {name: 'Chart of revenue and profit by month'}),
).toBeInTheDocument();
});
@@ -102,6 +117,37 @@ describe('Chart accessible name', () => {
expect(desc.textContent).toBe('Revenue per month');
expect(svg.getAttribute('aria-describedby')).toBe(desc.id);
});
+
+ it('localizes the generated name, list, and data-table caption', () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ messages={{
+ fr: {
+ '@astryx.chart.label': {defaultMessage: 'Graphique'},
+ '@astryx.chart.labelWithSeries': {
+ defaultMessage: 'Graphique de {series} par {xKey}',
+ },
+ '@astryx.chart.dataTableCaption': {
+ defaultMessage: 'Données pour {label}',
+ },
+ },
+ }}>
+ <Chart
+ data={data}
+ xKey="month"
+ series={[bar('revenue'), bar('profit')]}
+ />
+ </InternationalizationProvider>,
+ );
+ reportWidth(600);
+
+ const label = 'Graphique de revenue et profit par month';
+ expect(screen.getByRole('img', {name: label})).toBeInTheDocument();
+ expect(screen.getByRole('table')).toHaveAccessibleName(
+ `Données pour ${label}`,
+ );
+ });
});
describe('Chart data table fallback', () => {
@@ -164,6 +210,35 @@ describe('Chart measurement gate', () => {
});
});
+describe('Chart root contract', () => {
+ it('forwards DOM props and the ref to the root container', () => {
+ const ref = createRef<HTMLDivElement>();
+ const onClick = vi.fn();
+
+ render(
+ <Chart
+ ref={ref}
+ data-testid="chart-root"
+ className="consumer-chart"
+ style={{maxWidth: 480}}
+ onClick={onClick}
+ data={data}
+ xKey="month"
+ series={[bar('revenue')]}
+ />,
+ );
+ reportWidth(600);
+
+ const root = screen.getByTestId('chart-root');
+ expect(ref.current).toBe(root);
+ expect(root).toHaveClass('consumer-chart');
+ expect(root).toHaveStyle({maxWidth: '480px'});
+
+ fireEvent.click(root);
+ expect(onClick).toHaveBeenCalledOnce();
+ });
+});
+
describe('Chart render delegation', () => {
it('renders one clipped group per series', () => {
const {container} = render(
diff --git a/packages/charts/src/Chart.tsx b/packages/charts/src/Chart.tsx
index f95617c6fc..465dcfdac8 100644
--- a/packages/charts/src/Chart.tsx
+++ b/packages/charts/src/Chart.tsx
@@ -2,6 +2,7 @@
/**
* @file Chart.tsx (v2)
+ * @input Data, scale configuration, series definitions, optional chrome, and root DOM props
* @output Root chart — coordinates layout, rendering, and events
* @position Top-level; delegates everything to series configs and interaction slots
*
@@ -19,6 +20,7 @@
import {
type ReactNode,
+ type Ref,
useId,
useMemo,
useRef,
@@ -30,23 +32,40 @@ import type {SeriesDef, YBaseline} from './types';
import type {ChartContext, ChartMargin, ChartPointerEvent} from './types';
import {computeLayout} from './layout';
import {ChartProvider} from './ChartContext';
-import {Text} from '@astryxdesign/core';
-import {VStack, HStack} from '@astryxdesign/core';
-import {VisuallyHidden} from '@astryxdesign/core';
+import {
+ Text,
+ VStack,
+ HStack,
+ VisuallyHidden,
+ useLocale,
+ useTranslator,
+ type BaseProps,
+} from '@astryxdesign/core';
+import {useMergedRefs} from '@astryxdesign/core/hooks';
+import {mergeProps} from '@astryxdesign/core/utils';
+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
import * as stylex from '@stylexjs/stylex';
import {ChartLegend, type ChartLegendProps} from './ChartLegend';
import {deriveLegendItems} from './legend';
import {ChartTooltip, type ChartTooltipProps} from './ChartTooltip';
import {useChartColors} from './useChartColors';
+import {formatList} from './formatters';
import {isUtilityMarkType} from './types';
-export interface ChartProps {
+export interface ChartProps extends BaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root chart container. */
+ ref?: Ref<HTMLDivElement>;
+ /** Rows to visualize. Each row may contain the x field and one or more series fields. */
data: Record<string, unknown>[];
+ /** Field name read from each data row for the shared x scale. */
xKey: string;
+ /** Mark definitions rendered against the chart's shared scales. */
series: SeriesDef[];
+ /** Chart height in CSS pixels. Non-finite and negative values resolve to 0. @default 300 */
height?: number;
+ /** Partial plot inset override in CSS pixels. */
margin?: Partial<ChartMargin>;
- /** How the y-domain is derived when `yDomain` is not set. Default `'auto'`. */
+ /** How the y-domain is derived when `yDomain` is not set. @default 'auto' */
yBaseline?: YBaseline;
/** Explicit y-domain [min, max]. Authoritative — disables baseline/headroom. */
yDomain?: [number, number];
@@ -55,13 +74,21 @@ export interface ChartProps {
* is empty (stable streaming window). Ignored for categorical (band) scales.
*/
xDomain?: [number, number];
+ /** Grid content rendered behind the series, normally `ChartGrid`. */
grid?: ReactNode;
+ /** Axis content rendered after the series, normally one or more `ChartAxis` elements. */
axes?: ReactNode;
+ /** Show the derived legend, or configure its items and layout. @default false */
legend?: boolean | ChartLegendProps;
+ /** Show the grouped pointer tooltip, or configure its presentation. @default false */
tooltip?: boolean | Omit<ChartTooltipProps, 'series'>;
+ /** Interaction overlays rendered above the pointer-capture layer. */
interactions?: ReactNode;
+ /** Additional SVG content rendered after the built-in tooltip. */
children?: ReactNode;
+ /** Visible chart heading and accessible name for the SVG image. */
title?: string;
+ /** Visible supporting text and accessible description for the SVG image. */
subtitle?: string;
}
@@ -84,15 +111,32 @@ const styles = stylex.create({
width: '100%',
},
title: {
- marginBottom: 16,
+ marginBlockEnd: spacingVars['--spacing-4'],
},
chartArea: {
flex: 1,
minWidth: 0,
- overflow: 'hidden',
+ overflow: 'clip',
},
});
+/**
+ * Renders several series against one responsive x/y coordinate system.
+ *
+ * @example
+ * ```
+ * <Chart
+ * data={monthlyRevenue}
+ * xKey="month"
+ * series={[bar('revenue'), line('trend')]}
+ * title="Monthly revenue"
+ * grid={<ChartGrid horizontal />}
+ * axes={<><ChartAxis position="bottom" /><ChartAxis position="left" /></>}
+ * legend
+ * tooltip
+ * />
+ * ```
+ */
export function Chart({
data,
xKey,
@@ -110,13 +154,21 @@ export function Chart({
children,
title,
subtitle,
+ ref,
+ xstyle,
+ className,
+ style,
+ ...rest
}: ChartProps) {
const chartId = useId();
const descId = `${chartId}-desc`;
// useId() can contain ':' which is invalid in an SVG url(#id) reference.
const clipId = `plot-${chartId.replace(/:/g, '')}`;
const containerRef = useRef<HTMLDivElement>(null);
+ const mergedContainerRef = useMergedRefs(containerRef, ref);
const svgRef = useRef<SVGSVGElement>(null);
+ const t = useTranslator();
+ const locale = useLocale();
const [containerWidth, setContainerWidth] = useState(0);
const pointerHandlers = useRef<Set<(e: ChartPointerEvent) => void>>(
new Set(),
@@ -269,15 +321,19 @@ export function Chart({
// ─── Accessibility ─────────────────────────────────────────────────────
// The svg is exposed as a named image. `title` (when given) is the name;
- // otherwise an English default is derived from the primary series + x key.
+ // otherwise a localized default is derived from the primary series + x key.
const primarySeries = series.filter(s => !isUtilityMarkType(s.type));
const accessibleLabel =
title ??
(primarySeries.length > 0
- ? `Chart of ${primarySeries
- .map(s => s.label ?? s.key)
- .join(', ')} by ${xKey}`
- : 'Chart');
+ ? t('@astryx.chart.labelWithSeries', {
+ series: formatList(
+ primarySeries.map(s => s.label ?? s.key),
+ locale,
+ ),
+ xKey,
+ })
+ : t('@astryx.chart.label'));
const tableKeys = Array.from(new Set(primarySeries.flatMap(s => s.dataKeys)));
const showDataTable =
data.length > 0 &&
@@ -303,15 +359,23 @@ export function Chart({
if (containerWidth === 0) {
return (
<div
- ref={containerRef}
- {...stylex.props(styles.container)}
- style={{height: safeHeight}}
+ ref={mergedContainerRef}
+ {...mergeProps(
+ stylex.props(styles.container, xstyle),
+ {style: {height: safeHeight}},
+ className,
+ style,
+ )}
+ {...rest}
/>
);
}
return (
- <div ref={containerRef} {...stylex.props(styles.container)}>
+ <div
+ ref={mergedContainerRef}
+ {...mergeProps(stylex.props(styles.container, xstyle), className, style)}
+ {...rest}>
{(title || subtitle) && (
<div {...stylex.props(styles.title)}>
{title && (
@@ -417,7 +481,9 @@ export function Chart({
return (
<VisuallyHidden as="div">
<table>
- <caption>{`${accessibleLabel} data`}</caption>
+ <caption>
+ {t('@astryx.chart.dataTableCaption', {label: accessibleLabel})}
+ </caption>
<thead>
<tr>
<th scope="col">{xKey}</th>
@@ -443,3 +509,5 @@ export function Chart({
);
}
}
+
+Chart.displayName = 'Chart';
diff --git a/packages/charts/src/ChartLegend.test.tsx b/packages/charts/src/ChartLegend.test.tsx
index b950ee3cc8..225be75307 100644
--- a/packages/charts/src/ChartLegend.test.tsx
+++ b/packages/charts/src/ChartLegend.test.tsx
@@ -3,13 +3,14 @@
/**
* @file ChartLegend.test.tsx
* @input Uses vitest, @testing-library/react, ChartLegend
- * @output Functional tests for the standalone chart legend
+ * @output Functional tests for chart legend semantics, localization, and layout
* @position Colocated test for ChartLegend.tsx (issue #4295 viz coverage)
*/
import {describe, it, expect} from 'vitest';
import {render, screen, within} from '@testing-library/react';
import {ChartLegend} from './ChartLegend';
+import {InternationalizationProvider} from '@astryxdesign/core';
const items = [
{label: 'Revenue', color: '#ff0000', type: 'bar'},
@@ -26,6 +27,26 @@ describe('ChartLegend', () => {
expect(within(rows[1]).getByText('Profit')).toBeInTheDocument();
});
+ it('localizes the list label', () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ messages={{
+ fr: {
+ '@astryx.chartLegend.label': {
+ defaultMessage: 'Légende du graphique',
+ },
+ },
+ }}>
+ <ChartLegend items={items} />
+ </InternationalizationProvider>,
+ );
+
+ expect(
+ screen.getByRole('list', {name: 'Légende du graphique'}),
+ ).toBeInTheDocument();
+ });
+
it('renders a decorative swatch in each entry with the item color', () => {
render(<ChartLegend items={items} />);
const rows = screen.getAllByRole('listitem');
diff --git a/packages/charts/src/ChartLegend.tsx b/packages/charts/src/ChartLegend.tsx
index 828c54947b..6f6bc71f44 100644
--- a/packages/charts/src/ChartLegend.tsx
+++ b/packages/charts/src/ChartLegend.tsx
@@ -2,19 +2,24 @@
/**
* @file ChartLegend.tsx
+ * @input Legend items plus logical position and alignment
* @output Standalone chart legend component
* @position Can be used inside Chart via the `legend` prop, or independently
*
* @example
- * // Via Chart
- * <Chart legend={{position: 'top', alignment: 'start'}} ... />
- *
- * // Standalone
- * <ChartLegend items={[{label: 'Revenue', color: '#3b82f6'}]} />
+ * ```
+ * <Chart
+ * data={data}
+ * xKey="month"
+ * series={series}
+ * legend={{position: 'top', alignment: 'start'}}
+ * />
+ * ```
*/
-import {Text} from '@astryxdesign/core';
-import {VStack, HStack} from '@astryxdesign/core';
+'use client';
+
+import {HStack, Text, useTranslator, VStack} from '@astryxdesign/core';
import {ChartSwatch, swatchVariantForType} from './ChartSwatch';
import type {LegendItem} from './legend';
@@ -37,6 +42,8 @@ export function ChartLegend({
position = 'bottom',
alignment = 'start',
}: ChartLegendProps) {
+ const t = useTranslator();
+
if (items.length === 0) {
return null;
}
@@ -57,7 +64,11 @@ export function ChartLegend({
if (isVertical) {
return (
- <VStack gap={2} hAlign={alignment} role="list" aria-label="Chart legend">
+ <VStack
+ gap={2}
+ hAlign={alignment}
+ role="list"
+ aria-label={t('@astryx.chartLegend.label')}>
{legendItems}
</VStack>
);
@@ -70,7 +81,7 @@ export function ChartLegend({
vAlign="center"
wrap="wrap"
role="list"
- aria-label="Chart legend">
+ aria-label={t('@astryx.chartLegend.label')}>
{legendItems}
</HStack>
);
diff --git a/packages/charts/src/formatters.ts b/packages/charts/src/formatters.ts
index 780bc69b05..e4186fed07 100644
--- a/packages/charts/src/formatters.ts
+++ b/packages/charts/src/formatters.ts
@@ -2,8 +2,8 @@
/**
* @file formatters.ts
- * @output Built-in, locale-aware tick/value format utilities for common data types
- * @position Utility; consumed by ChartAxis via tickFormat prop
+ * @output Built-in locale-aware tick, value, and list format utilities
+ * @position Utility; consumed by Chart and ChartAxis
*
* Formatters degrade gracefully: non-finite numbers (NaN/±Infinity) and
* unparseable values are passed through as-is rather than producing garbage
@@ -63,6 +63,15 @@ const getMonthYearFormat = byLocale(
}),
);
+const getListFormat = byLocale(
+ locale => new Intl.ListFormat(locale, {style: 'long', type: 'conjunction'}),
+);
+
+/** Format labels as a conjunction list using the provider locale. */
+export function formatList(values: readonly string[], locale: Locale): string {
+ return getListFormat(locale).format(values);
+}
+
/**
* Compact number formatter (e.g. 1200 → "1.2K", 1500000 → "1.5M", 1e12 → "1T").
*
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 87df859ae8..5ef1e6ac81 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -347,6 +347,22 @@
"defaultMessage": "Slide {current, number} of {total, number}",
"description": "Screen-reader accessible name for one slide in a Carousel, giving its position. `current` is the 1-based slide number; `total` is the slide count."
},
+ "@astryx.chart.label": {
+ "defaultMessage": "Chart",
+ "description": "Generic screen-reader name for a Chart with no primary series and no consumer-supplied title. Noun (a data visualization), not a verb."
+ },
+ "@astryx.chart.labelWithSeries": {
+ "defaultMessage": "Chart of {series} by {xKey}",
+ "description": "Generated screen-reader name for a Chart without a consumer-supplied title. `{series}` is a locale-formatted list of series labels; `{xKey}` is the consumer's horizontal data-field name."
+ },
+ "@astryx.chart.dataTableCaption": {
+ "defaultMessage": "{label} data",
+ "description": "Screen-reader-only caption for the small-data table that mirrors a Chart. `{label}` is the Chart's resolved accessible name."
+ },
+ "@astryx.chartLegend.label": {
+ "defaultMessage": "Chart legend",
+ "description": "Screen-reader-only accessible name for the list of series labels and swatches rendered by ChartLegend."
+ },
"@astryx.chat.status.sending": {
"defaultMessage": "Sending",
"description": "Chat send-status caption under an outgoing message while it is being transmitted. Part of the set sending → sent → delivered → read (or failed) — keep tense/aspect consistent."