An open source design system that's fully customizable and agent ready
TypeScript
feat(ChartV2): add title, subtitle, accessibility, and legend (#2188)
Marie Lucasffb57fd3074f
diff --git a/apps/storybook/stories/ChartV2.stories.tsx b/apps/storybook/stories/ChartV2.stories.tsxindex 9b72f9b772..308752c646 100644--- a/apps/storybook/stories/ChartV2.stories.tsx+++ b/apps/storybook/stories/ChartV2.stories.tsx@@ -34,6 +34,7 @@ export const SimpleBar: StoryObj = {<XDSChartdata={monthlyData}xKey="month"+ title="Monthly Revenue"series={[bar('revenue', {color: '#3b82f6'})]}grid={<XDSChartGrid horizontal />}axes={@@ -53,10 +54,13 @@ export const StackedBars: StoryObj = {<XDSChartdata={monthlyData}xKey="month"+ title="Revenue & Costs"+ subtitle="Stacked by category"series={[- bar('revenue', {color: '#3b82f6', stack: 'totals'}),- bar('costs', {color: '#ef4444', stack: 'totals'}),+ bar('revenue', {color: '#3b82f6', stack: 'totals', label: 'Revenue'}),+ bar('costs', {color: '#ef4444', stack: 'totals', label: 'Costs'}),]}+ legend={{position: 'bottom', alignment: 'center'}}grid={<XDSChartGrid horizontal />}axes={<>@@ -75,10 +79,12 @@ export const GroupedBars: StoryObj = {<XDSChartdata={monthlyData}xKey="month"+ title="Revenue vs Costs"series={[- bar('revenue', {color: '#3b82f6', group: 'compare'}),- bar('costs', {color: '#ef4444', group: 'compare'}),+ bar('revenue', {color: '#3b82f6', group: 'compare', label: 'Revenue'}),+ bar('costs', {color: '#ef4444', group: 'compare', label: 'Costs'}),]}+ legend={{position: 'top', alignment: 'end'}}grid={<XDSChartGrid horizontal />}axes={<>@@ -131,10 +137,13 @@ export const MixedMarks: StoryObj = {<XDSChartdata={monthlyData}xKey="month"+ title="Revenue vs Trend"+ subtitle="Bar chart with trendline overlay"series={[- bar('revenue', {color: '#3b82f6'}),- line('trend', {color: '#f59e0b'}),+ bar('revenue', {color: '#3b82f6', label: 'Revenue'}),+ line('trend', {color: '#f59e0b', label: 'Trend'}),]}+ legend={{position: 'end', alignment: 'start'}}grid={<XDSChartGrid horizontal />}axes={<>@@ -153,6 +162,7 @@ export const AreaGradient: StoryObj = {<XDSChartdata={monthlyData}xKey="month"+ title="Revenue Over Time"series={[area('revenue', {color: '#3b82f6', gradient: true}),line('revenue', {color: '#3b82f6'}),@@ -175,10 +185,12 @@ export const StackedAreas: StoryObj = {<XDSChartdata={monthlyData}xKey="month"+ title="Revenue & Costs Over Time"series={[- area('revenue', {color: '#3b82f6', stack: 'total'}),- area('costs', {color: '#ef4444', stack: 'total'}),+ area('revenue', {color: '#3b82f6', stack: 'total', label: 'Revenue'}),+ area('costs', {color: '#ef4444', stack: 'total', label: 'Costs'}),]}+ legend={true}grid={<XDSChartGrid horizontal />}axes={<>diff --git a/apps/storybook/stories/ChartV2Legend.stories.tsx b/apps/storybook/stories/ChartV2Legend.stories.tsxnew file mode 100644index 0000000000..6b711228b0--- /dev/null+++ b/apps/storybook/stories/ChartV2Legend.stories.tsx@@ -0,0 +1,37 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {XDSChartV2Legend} from '@xds/lab';++const sampleItems = [+ {label: 'Revenue', color: '#3b82f6', type: 'bar'},+ {label: 'Costs', color: '#ef4444', type: 'bar'},+ {label: 'Trend', color: '#f59e0b', type: 'line'},+];++const meta: Meta<typeof XDSChartV2Legend> = {+ title: 'Lab/XDSChart v2/Primitives/Legend',+ component: XDSChartV2Legend,+ argTypes: {+ position: {+ control: 'inline-radio',+ options: ['top', 'bottom', 'start', 'end'],+ },+ alignment: {+ control: 'inline-radio',+ options: ['start', 'center', 'end'],+ },+ items: {table: {disable: true}},+ },+ args: {+ items: sampleItems,+ alignment: 'start',+ },+ render: args => <XDSChartV2Legend {...args} />,+};+export default meta;++/** Standalone chart legend. Use the Controls panel to switch position and alignment. */+export const Legend: StoryObj = {+ args: {position: 'bottom'},+};diff --git a/packages/lab/src/ChartV2/XDSChart.tsx b/packages/lab/src/ChartV2/XDSChart.tsxindex 275fbead77..c0dc5afd8c 100644--- a/packages/lab/src/ChartV2/XDSChart.tsx+++ b/packages/lab/src/ChartV2/XDSChart.tsx@@ -13,6 +13,7 @@import {type ReactNode,+ useId,useMemo,useRef,useState,@@ -24,6 +25,11 @@ import type {ChartV2Context, ChartMargin, ChartPointerEvent} from './types';import {computeLayout} from './layout';import {ChartV2Provider} from './ChartV2Context';import {ChartProvider} from '../Chart/ChartContext';+import {XDSText} from '@xds/core';+import {XDSVStack, XDSHStack} from '@xds/core';+import * as stylex from '@stylexjs/stylex';+import {XDSChartLegend, type XDSChartLegendProps} from './XDSChartLegend';+import {deriveLegendItems} from './legend';export interface XDSChartProps {data: Record<string, unknown>[];@@ -33,13 +39,32 @@ export interface XDSChartProps {margin?: Partial<ChartMargin>;grid?: ReactNode;axes?: ReactNode;- legend?: boolean | ReactNode;+ /** Legend configuration. Pass `true` for defaults, or a config object. */+ legend?: boolean | XDSChartLegendProps;interactions?: ReactNode;children?: ReactNode;+ /** Chart title displayed above the visualization */+ title?: string;+ /** Subtitle displayed below the title */+ subtitle?: string;}const DEFAULT_MARGIN: ChartMargin = {top: 16, right: 16, bottom: 32, left: 48};+const styles = stylex.create({+ container: {+ width: '100%',+ },+ title: {+ marginBottom: 16,+ },+ chartArea: {+ flex: 1,+ minWidth: 0,+ overflow: 'hidden',+ },+});+export function XDSChart({data,xKey,@@ -51,7 +76,11 @@ export function XDSChart({legend,interactions,children,+ title,+ subtitle,}: XDSChartProps) {+ const chartId = useId();+ const descId = `${chartId}-desc`;const containerRef = useRef<HTMLDivElement>(null);const svgRef = useRef<SVGSVGElement>(null);const [containerWidth, setContainerWidth] = useState(0);@@ -200,51 +229,112 @@ export function XDSChart({[innerWidth, innerHeight, margin, xKey, data, layout, svgRef],);+ // ─── Legend ────────────────────────────────────────────────────────────+ const legendConfig = legend === true ? {} : legend || null;++ const legendElement = legendConfig ? (+ <XDSChartLegend+ items={legendConfig.items ?? deriveLegendItems(series)}+ position={legendConfig.position}+ alignment={legendConfig.alignment}+ />+ ) : null;++ const legendPosition = legendConfig?.position ?? 'bottom';+ const isLegendHorizontal =+ legendPosition === 'start' || legendPosition === 'end';+// ─── Render ───────────────────────────────────────────────────────────if (containerWidth === 0) {- return <div ref={containerRef} style={{width: '100%', height}} />;+ return (+ <div+ ref={containerRef}+ {...stylex.props(styles.container)}+ style={{height}}+ />+ );}return (- <div ref={containerRef} style={{width: '100%'}}>+ <div ref={containerRef} {...stylex.props(styles.container)}>+ {(title || subtitle) && (+ <div {...stylex.props(styles.title)}>+ {title && (+ <XDSText type="body" weight="semibold" display="block">+ {title}+ </XDSText>+ )}+ {subtitle && (+ <XDSText type="supporting" display="block">+ {subtitle}+ </XDSText>+ )}+ </div>+ )}<ChartV2Provider value={ctx}><ChartProvider value={v1Ctx}>- <svg ref={svgRef} width={containerWidth} height={height}>- <g transform={`translate(${margin.left},${margin.top})`}>- {/* 1. Grid */}- {grid}-- {/* 2. Marks — each series renders itself */}- {series.map(s => {- const resolved = layout.resolved.get(s.key);- if (!resolved) {- return null;- }- return <g key={s.key}>{s.render(resolved, seriesCtx)}</g>;- })}-- {/* 3. Axes */}- {axes}-- {/* 4. Event capture + interactions */}- <rect- x={0}- y={0}- width={innerWidth}- height={innerHeight}- fill="transparent"- onPointerMove={handlePointerMove}- onPointerLeave={handlePointerLeave}- />- {interactions}-- {/* 5. Escape hatch */}- {children}- </g>- </svg>- {legend === true ? null : legend}+ {legendConfig == null ? (+ renderSvg()+ ) : isLegendHorizontal ? (+ <XDSHStack gap={4}>+ {legendPosition === 'start' && legendElement}+ <div {...stylex.props(styles.chartArea)}>{renderSvg()}</div>+ {legendPosition === 'end' && legendElement}+ </XDSHStack>+ ) : (+ <XDSVStack gap={4}>+ {legendPosition === 'top' && legendElement}+ {renderSvg()}+ {legendPosition === 'bottom' && legendElement}+ </XDSVStack>+ )}</ChartProvider></ChartV2Provider></div>);++ function renderSvg() {+ return (+ <svg+ ref={svgRef}+ width="100%"+ height={height}+ aria-label={title ?? undefined}+ aria-describedby={subtitle ? descId : undefined}>+ {title && <title>{title}</title>}+ {subtitle && <desc id={descId}>{subtitle}</desc>}+ <g transform={`translate(${margin.left},${margin.top})`}>+ {/* 1. Grid */}+ {grid}++ {/* 2. Marks — each series renders itself */}+ {series.map(s => {+ const resolved = layout.resolved.get(s.key);+ if (!resolved) {+ return null;+ }+ return <g key={s.key}>{s.render(resolved, seriesCtx)}</g>;+ })}++ {/* 3. Axes */}+ {axes}++ {/* 4. Event capture + interactions */}+ <rect+ x={0}+ y={0}+ width={innerWidth}+ height={innerHeight}+ fill="transparent"+ onPointerMove={handlePointerMove}+ onPointerLeave={handlePointerLeave}+ />+ {interactions}++ {/* 5. Escape hatch */}+ {children}+ </g>+ </svg>+ );+ }}diff --git a/packages/lab/src/ChartV2/XDSChartLegend.tsx b/packages/lab/src/ChartV2/XDSChartLegend.tsxnew file mode 100644index 0000000000..08e04f093c--- /dev/null+++ b/packages/lab/src/ChartV2/XDSChartLegend.tsx@@ -0,0 +1,67 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file XDSChartLegend.tsx+ * @output Standalone chart legend component+ * @position Can be used inside XDSChart via the `legend` prop, or independently+ *+ * @example+ * // Via XDSChart+ * <XDSChart legend={{position: 'top', alignment: 'start'}} ... />+ *+ * // Standalone+ * <XDSChartLegend items={[{label: 'Revenue', color: '#3b82f6'}]} />+ */++import {XDSText} from '@xds/core';+import {XDSVStack, XDSHStack} from '@xds/core';+import {XDSChartSwatch, swatchVariantForType} from './XDSChartSwatch';+import type {LegendItem} from './legend';++export type {LegendItem};++export type LegendPosition = 'top' | 'bottom' | 'start' | 'end';+export type LegendAlignment = 'start' | 'center' | 'end';++export interface XDSChartLegendProps {+ /** Legend items to display */+ items?: LegendItem[];+ /** Position of the legend relative to the chart. Default: 'bottom' */+ position?: LegendPosition;+ /** Alignment of the legend within its position. Default: 'start' */+ alignment?: LegendAlignment;+}++export function XDSChartLegend({+ items = [],+ position = 'bottom',+ alignment = 'start',+}: XDSChartLegendProps) {+ if (items.length === 0) return null;++ const isVertical = position === 'start' || position === 'end';++ const legendItems = items.map(item => (+ <XDSHStack key={item.label} gap={2} vAlign="center">+ <XDSChartSwatch+ color={item.color}+ variant={swatchVariantForType(item.type)}+ />+ <XDSText type="supporting">{item.label}</XDSText>+ </XDSHStack>+ ));++ if (isVertical) {+ return (+ <XDSVStack gap={2} hAlign={alignment}>+ {legendItems}+ </XDSVStack>+ );+ }++ return (+ <XDSHStack gap={4} justify={alignment} vAlign="center" wrap="wrap">+ {legendItems}+ </XDSHStack>+ );+}diff --git a/packages/lab/src/ChartV2/XDSChartSwatch.tsx b/packages/lab/src/ChartV2/XDSChartSwatch.tsxnew file mode 100644index 0000000000..06b36f2465--- /dev/null+++ b/packages/lab/src/ChartV2/XDSChartSwatch.tsx@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file XDSChartSwatch.tsx+ * @output Color swatch primitive for legends, tooltips, and standalone use+ * @position Composable primitive — used by XDSChartLegend (and future+ * XDSChartTooltip), or independently anywhere a series indicator+ * is needed.+ *+ * @example+ * ```+ * <XDSChartSwatch color="#3b82f6" variant="square" />+ * <XDSChartSwatch color="#f59e0b" variant="line" />+ * ```+ */++import {memo} from 'react';+import * as stylex from '@stylexjs/stylex';++/**+ * Visual variant — drives shape.+ * - `'square'` — square chip (bar series)+ * - `'line'` — short stroke (line, dot, area, and other non-bar series)+ */+export type XDSChartSwatchVariant = 'square' | 'line';++export interface XDSChartSwatchProps {+ /** Fill color — typically a series color token */+ color: string;+ /** Visual variant. Default: `'square'`. */+ variant?: XDSChartSwatchVariant;+}++const styles = stylex.create({+ base: {+ flexShrink: 0,+ },+ square: {+ width: 8,+ height: 8,+ borderRadius: 2,+ marginInline: 1,+ },+ line: {+ width: 10,+ height: 3,+ borderRadius: 1.5,+ },+});++/**+ * Color swatch primitive.+ *+ * Used by XDSChartLegend (and XDSChartTooltip) to render the colored+ * indicator next to a series label. Exported as a primitive so consumers+ * can build their own custom legend/tooltip layouts while keeping visuals+ * consistent.+ */+function XDSChartSwatchImpl({color, variant = 'square'}: XDSChartSwatchProps) {+ return (+ <div+ aria-hidden+ {...stylex.props(styles.base, styles[variant])}+ style={{backgroundColor: color}}+ />+ );+}++/**+ * Memoized — swatches are static for a given (color, variant) tuple+ * and can render many times in a tooltip/legend with several series.+ */+export const XDSChartSwatch = memo(XDSChartSwatchImpl);++/**+ * Map a SeriesDef.type string to its swatch variant.+ *+ * Bar series get a square chip; everything else (line, dot, area, and any+ * other non-bar mark) gets a short stroke. Centralized so legend, tooltip,+ * and any custom chrome stay consistent.+ */+export function swatchVariantForType(+ type: string | undefined,+): XDSChartSwatchVariant {+ return type === 'bar' ? 'square' : 'line';+}diff --git a/packages/lab/src/ChartV2/index.ts b/packages/lab/src/ChartV2/index.tsindex a356c7c139..a309e46147 100644--- a/packages/lab/src/ChartV2/index.ts+++ b/packages/lab/src/ChartV2/index.ts@@ -1,7 +1,54 @@// Copyright (c) Meta Platforms, Inc. and affiliates.export {XDSChart, type XDSChartProps} from './XDSChart';-export {bar, line, dot, area, band, candlestick, errorBar, referenceLine, dotGL, dotGLInteractive, heatmapGL, streamGL} from './marks';-export type {BarOptions, LineOptions, DotOptions, AreaOptions, BandOptions, CandlestickOptions, ErrorBarOptions, ReferenceLineOptions, DotGLOptions, DotGLInteractiveOptions, HeatmapGLOptions, StreamGLOptions, StreamGLHandle} from './marks';+export {+ XDSChartLegend,+ type XDSChartLegendProps,+ type LegendPosition,+ type LegendAlignment,+} from './XDSChartLegend';+export {type LegendItem} from './legend';+export {+ XDSChartSwatch,+ swatchVariantForType,+ type XDSChartSwatchProps,+ type XDSChartSwatchVariant,+} from './XDSChartSwatch';+export {+ bar,+ line,+ dot,+ area,+ band,+ candlestick,+ errorBar,+ referenceLine,+ dotGL,+ dotGLInteractive,+ heatmapGL,+ streamGL,+} from './marks';+export type {+ BarOptions,+ LineOptions,+ DotOptions,+ AreaOptions,+ BandOptions,+ CandlestickOptions,+ ErrorBarOptions,+ ReferenceLineOptions,+ DotGLOptions,+ DotGLInteractiveOptions,+ HeatmapGLOptions,+ StreamGLOptions,+ StreamGLHandle,+} from './marks';export {useChartV2} from './ChartV2Context';-export type {SeriesDef, ChartV2Context, ChartPointerEvent, ResolvedPoint, ResolvedPositions, SeriesContext} from './types';+export type {+ SeriesDef,+ ChartV2Context,+ ChartPointerEvent,+ ResolvedPoint,+ ResolvedPositions,+ SeriesContext,+} from './types';diff --git a/packages/lab/src/ChartV2/legend.ts b/packages/lab/src/ChartV2/legend.tsnew file mode 100644index 0000000000..a332833316--- /dev/null+++ b/packages/lab/src/ChartV2/legend.ts@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file legend.ts+ * @output Legend utility — derives legend items from series definitions+ * @position Used by XDSChart to bridge series → legend items+ */++import type {SeriesDef} from './types';++export interface LegendItem {+ label: string;+ color: string;+ /** Mark type — determines swatch shape (square for bar/area/dot, line for line) */+ type?: string;+}++/** Series types that don't appear in the legend */+const SKIP_TYPES = new Set(['referenceLine', 'errorBar', 'band']);++/**+ * Derive legend items from series definitions.+ * Skips utility marks and series without a color.+ */+export function deriveLegendItems(series: readonly SeriesDef[]): LegendItem[] {+ return series+ .filter(s => !SKIP_TYPES.has(s.type) && s.color)+ .map(s => ({label: s.label ?? s.key, color: s.color!, type: s.type}));+}diff --git a/packages/lab/src/ChartV2/marks/area.tsx b/packages/lab/src/ChartV2/marks/area.tsxindex 337d9601c4..b37d4e5053 100644--- a/packages/lab/src/ChartV2/marks/area.tsx+++ b/packages/lab/src/ChartV2/marks/area.tsx@@ -30,6 +30,7 @@ export interface AreaOptions {stack?: string;gradient?: boolean;stroke?: boolean;+ label?: string;}export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {@@ -43,6 +44,8 @@ export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {type: 'area',key: dataKey,dataKeys: [dataKey],+ color,+ label: options.label ?? dataKey,layout: {stack: options.stack, includeZero: true},resolve(ctx, stackOffsets) {diff --git a/packages/lab/src/ChartV2/marks/bar.tsx b/packages/lab/src/ChartV2/marks/bar.tsxindex bb444f5ddd..847ea5fa66 100644--- a/packages/lab/src/ChartV2/marks/bar.tsx+++ b/packages/lab/src/ChartV2/marks/bar.tsx@@ -19,6 +19,7 @@ export interface BarOptions {radius?: number;stack?: string;group?: string;+ label?: string;}/**@@ -79,6 +80,8 @@ export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {type: 'bar',key: dataKey,dataKeys: [dataKey],+ color: typeof color === 'string' ? color : undefined,+ label: options.label ?? dataKey,layout: {stack: options.stack,group: options.group,diff --git a/packages/lab/src/ChartV2/marks/dot.tsx b/packages/lab/src/ChartV2/marks/dot.tsxindex 41f1e7f3cc..342a55ab18 100644--- a/packages/lab/src/ChartV2/marks/dot.tsx+++ b/packages/lab/src/ChartV2/marks/dot.tsx@@ -15,6 +15,7 @@ export interface DotOptions {radius?: number;opacity?: number;dodge?: boolean;+ label?: string;}export function dot(dataKey: string, options: DotOptions = {}): SeriesDef {@@ -26,6 +27,8 @@ export function dot(dataKey: string, options: DotOptions = {}): SeriesDef {type: 'dot',key: dataKey,dataKeys: [dataKey],+ color: typeof color === 'string' ? color : undefined,+ label: options.label ?? dataKey,layout: {},resolve(ctx) {diff --git a/packages/lab/src/ChartV2/marks/line.tsx b/packages/lab/src/ChartV2/marks/line.tsxindex 23a48ce131..e1f7a8115a 100644--- a/packages/lab/src/ChartV2/marks/line.tsx+++ b/packages/lab/src/ChartV2/marks/line.tsx@@ -28,6 +28,7 @@ export interface LineOptions {curve?: CurveType;strokeWidth?: number;dots?: boolean;+ label?: string;}export function line(dataKey: string, options: LineOptions = {}): SeriesDef {@@ -40,6 +41,8 @@ export function line(dataKey: string, options: LineOptions = {}): SeriesDef {type: 'line',key: dataKey,dataKeys: [dataKey],+ color,+ label: options.label ?? dataKey,layout: {},resolve(ctx) {diff --git a/packages/lab/src/ChartV2/types.ts b/packages/lab/src/ChartV2/types.tsindex 9c79a052d9..646eff26ab 100644--- a/packages/lab/src/ChartV2/types.ts+++ b/packages/lab/src/ChartV2/types.ts@@ -56,7 +56,11 @@ export interface SeriesDef {readonly dataKeys: string[];/** Whether this series is the topmost in its stack (set during layout) */_isTopOfStack?: boolean;- /** Layout hints the chart root uses for cross-series coordination */+ /** Static color for legend display. Undefined if color is dynamic (accessor function). */+ readonly color?: string;+ /** Human-readable label for legend. Falls back to key if not provided. */+ readonly label?: string;+ /** Layout hints the chart root uses for cross-series coordination */readonly layout: {/** Stack group — series with same stack accumulate */stack?: string;diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex ea79b291c3..b2aa9ba7a0 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -194,6 +194,13 @@ export {export {XDSChart as XDSChartV2,type XDSChartProps as XDSChartV2Props,+ XDSChartLegend as XDSChartV2Legend,+ type XDSChartLegendProps as XDSChartV2LegendProps,+ type LegendItem as XDSChartV2LegendItem,+ XDSChartSwatch as XDSChartV2Swatch,+ swatchVariantForType as xdsChartV2SwatchVariantForType,+ type XDSChartSwatchProps as XDSChartV2SwatchProps,+ type XDSChartSwatchVariant as XDSChartV2SwatchVariant,bar,line,dot,