An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): XDSChart — composable d3-based chart components (#1389)
Cindy Zhang18e877c38322
diff --git a/apps/storybook/stories/Chart.stories.tsx b/apps/storybook/stories/Chart.stories.tsxnew file mode 100644index 0000000000..a368b98344--- /dev/null+++ b/apps/storybook/stories/Chart.stories.tsx@@ -0,0 +1,114 @@+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSChart,+ XDSChartAxis,+ XDSChartGrid,+ XDSChartBar,+ XDSChartLine,+ XDSChartDot,+ XDSChartTooltip,+ XDSChartLegend,+ XDSChartColors,+} from '@xds/lab';++const meta: Meta = {+ title: 'Lab/XDSChart',+};++export default meta;++const monthlyData = [+ {month: 'Jan', revenue: 4200, expenses: 2800, trend: 3800},+ {month: 'Feb', revenue: 3800, expenses: 2600, trend: 3900},+ {month: 'Mar', revenue: 5100, expenses: 3200, trend: 4200},+ {month: 'Apr', revenue: 4600, expenses: 2900, trend: 4400},+ {month: 'May', revenue: 5400, expenses: 3100, trend: 4600},+ {month: 'Jun', revenue: 6200, expenses: 3400, trend: 5000},+];++const colors = XDSChartColors.categorical(3);++/** Bar chart with axes and grid */+export const BarChart: StoryObj = {+ render: () => (+ <XDSChart data={monthlyData} xKey="month" yKeys={['revenue']} height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartBar dataKey="revenue" color={colors[0]} />+ <XDSChartTooltip />+ </XDSChart>+ ),+};++/** Line chart with dots */+export const LineChart: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ yKeys={['revenue', 'expenses']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartLine dataKey="revenue" color={colors[0]} dots />+ <XDSChartLine dataKey="expenses" color={colors[1]} dots />+ <XDSChartLegend+ items={[+ {label: 'Revenue', color: colors[0]},+ {label: 'Expenses', color: colors[1]},+ ]}+ />+ <XDSChartTooltip />+ </XDSChart>+ ),+};++/** Mixed bar + line chart */+export const MixedChart: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ yKeys={['revenue', 'trend']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartBar dataKey="revenue" color={colors[0]} />+ <XDSChartLine dataKey="trend" color={colors[2]} dots />+ <XDSChartLegend+ items={[+ {label: 'Revenue', color: colors[0]},+ {label: 'Trend', color: colors[2]},+ ]}+ />+ <XDSChartTooltip />+ </XDSChart>+ ),+};++/** Scatter plot */+export const ScatterPlot: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ yKeys={['revenue', 'expenses']}+ height={300}>+ <XDSChartGrid horizontal vertical />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartDot dataKey="revenue" color={colors[0]} radius={5} />+ <XDSChartDot dataKey="expenses" color={colors[1]} radius={5} />+ <XDSChartLegend+ items={[+ {label: 'Revenue', color: colors[0]},+ {label: 'Expenses', color: colors[1]},+ ]}+ />+ <XDSChartTooltip />+ </XDSChart>+ ),+};diff --git a/packages/lab/package.json b/packages/lab/package.jsonindex 8b7aa5595a..f137acc4f8 100644--- a/packages/lab/package.json+++ b/packages/lab/package.json@@ -2,7 +2,7 @@"name": "@xds/lab","version": "0.0.12","private": true,- "description": "Experimental XDS components \u2014 not published, available in storybook and sandbox for testing",+ "description": "Experimental XDS components — not published, available in storybook and sandbox for testing","main": "./src/index.ts","types": "./src/index.ts","sideEffects": false,@@ -11,5 +11,15 @@"@xds/core": "*","react": ">=19.0.0","react-dom": ">=19.0.0"+ },+ "dependencies": {+ "d3-array": "^3.2.4",+ "d3-scale": "^4.0.2",+ "d3-shape": "^3.2.0"+ },+ "devDependencies": {+ "@types/d3-array": "^3.2.2",+ "@types/d3-scale": "^4.0.9",+ "@types/d3-shape": "^3.1.8"}}diff --git a/packages/lab/src/Chart/ChartContext.ts b/packages/lab/src/Chart/ChartContext.tsnew file mode 100644index 0000000000..f1fc068ce0--- /dev/null+++ b/packages/lab/src/Chart/ChartContext.ts@@ -0,0 +1,21 @@+/**+ * @file ChartContext.ts+ * @output React context for sharing scales and dimensions between chart components+ * @position Consumed by XDSChart (provider) and all child components (consumers)+ */++import {createContext, useContext} from 'react';+import type {ChartContext} from './types';++const ChartCtx = createContext<ChartContext | null>(null);++export const ChartProvider = ChartCtx.Provider;++/** Access the chart context. Throws if used outside <XDSChart>. */+export function useChart(): ChartContext {+ const ctx = useContext(ChartCtx);+ if (!ctx) {+ throw new Error('Chart components must be used inside <XDSChart>');+ }+ return ctx;+}diff --git a/packages/lab/src/Chart/XDSChart.tsx b/packages/lab/src/Chart/XDSChart.tsxnew file mode 100644index 0000000000..2b0ed786d1--- /dev/null+++ b/packages/lab/src/Chart/XDSChart.tsx@@ -0,0 +1,145 @@+/**+ * @file XDSChart.tsx+ * @output Root chart container — sets up SVG, scales, and context+ * @position Parent component; all chart marks/axes/interactions are children+ *+ * Handles the d3 margin convention: outer SVG at full size, inner <g> translated+ * by margins. Children receive scales and dimensions via context.+ */++import {+ type ReactNode,+ useMemo,+ useRef,+ useState,+ useLayoutEffect,+} from 'react';+import {scaleLinear, scaleBand} from 'd3-scale';+import type {ScaleLinear} from 'd3-scale';+import {ChartProvider} from './ChartContext';+import type {ChartMargin, ChartScale} from './types';++export interface XDSChartProps {+ /** The dataset — array of objects with consistent keys */+ data: Record<string, unknown>[];+ /**+ * Key for the x-axis domain values.+ * String values produce a band scale; numeric values produce a linear scale.+ */+ xKey: string;+ /**+ * Key(s) for the y-axis domain values.+ * Used to compute the y-domain across all series.+ */+ yKeys: string[];+ /** Chart height in pixels. Width is responsive (fills container). */+ height?: number;+ /** Override default margins */+ margin?: Partial<ChartMargin>;+ /** Chart contents — axes, marks, tooltips */+ children: ReactNode;+}++const DEFAULT_MARGIN: ChartMargin = {top: 16, right: 16, bottom: 32, left: 48};++/**+ * Root chart container. Computes scales from data and provides them to children.+ *+ * @example+ * ```+ * <XDSChart data={data} xKey="month" yKeys={['revenue']} height={300}>+ * <XDSChartAxis position="bottom" />+ * <XDSChartAxis position="left" />+ * <XDSChartBar dataKey="revenue" color={XDSChartColors.categorical(1)[0]} />+ * </XDSChart>+ * ```+ */+export function XDSChart({+ data,+ xKey,+ yKeys,+ height = 300,+ margin: marginOverride,+ children,+}: XDSChartProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const [containerWidth, setContainerWidth] = useState(0);++ useLayoutEffect(() => {+ if (!containerRef.current) return;+ const observer = new ResizeObserver(entries => {+ const entry = entries[0];+ if (entry) setContainerWidth(entry.contentRect.width);+ });+ observer.observe(containerRef.current);+ return () => observer.disconnect();+ }, []);++ const margin = useMemo(+ () => ({...DEFAULT_MARGIN, ...marginOverride}),+ [marginOverride],+ );++ const innerWidth = Math.max(0, containerWidth - margin.left - margin.right);+ const innerHeight = Math.max(0, height - margin.top - margin.bottom);++ const xScale = useMemo((): ChartScale => {+ const xValues = data.map(d => d[xKey]);+ const isNumeric = xValues.every(v => typeof v === 'number');++ if (isNumeric) {+ const nums = xValues as number[];+ return scaleLinear()+ .domain([Math.min(...nums), Math.max(...nums)])+ .range([0, innerWidth])+ .nice();+ }++ // Categorical / string+ return scaleBand<string>()+ .domain(xValues.map(String))+ .range([0, innerWidth])+ .padding(0.2);+ }, [data, xKey, innerWidth]);++ const yScale = useMemo((): ScaleLinear<number, number> => {+ let min = Infinity;+ let max = -Infinity;+ for (const d of data) {+ for (const key of yKeys) {+ const v = d[key];+ if (typeof v === 'number') {+ if (v < min) min = v;+ if (v > max) max = v;+ }+ }+ }+ // Always include 0 in bar-friendly charts+ if (min > 0) min = 0;+ return scaleLinear().domain([min, max]).range([innerHeight, 0]).nice();+ }, [data, yKeys, innerHeight]);++ const ctx = useMemo(+ () => ({+ width: innerWidth,+ height: innerHeight,+ margin,+ data,+ xScale,+ yScale,+ }),+ [innerWidth, innerHeight, margin, data, xScale, yScale],+ );++ return (+ <div ref={containerRef} style={{width: '100%'}}>+ {containerWidth > 0 && (+ <svg width={containerWidth} height={height}>+ <g transform={`translate(${margin.left},${margin.top})`}>+ <ChartProvider value={ctx}>{children}</ChartProvider>+ </g>+ </svg>+ )}+ </div>+ );+}diff --git a/packages/lab/src/Chart/XDSChartAxis.tsx b/packages/lab/src/Chart/XDSChartAxis.tsxnew file mode 100644index 0000000000..38dc83bdbe--- /dev/null+++ b/packages/lab/src/Chart/XDSChartAxis.tsx@@ -0,0 +1,115 @@+/**+ * @file XDSChartAxis.tsx+ * @output Renders an axis (top, right, bottom, left) using the chart's scales+ * @position Child of XDSChart; reads scales from context+ */++import {useMemo} from 'react';+import {useChart} from './ChartContext';+import type {ScaleBand, ScaleLinear, ScaleTime} from 'd3-scale';++export interface XDSChartAxisProps {+ /** Which edge to render the axis on */+ position: 'top' | 'right' | 'bottom' | 'left';+ /** Number of ticks (approximate — d3 decides final count) */+ tickCount?: number;+ /** Custom tick formatter */+ tickFormat?: (value: unknown) => string;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Chart axis. Renders tick marks and labels for the x or y dimension.+ *+ * @example+ * ```+ * <XDSChartAxis position="bottom" />+ * <XDSChartAxis position="left" tickCount={5} />+ * ```+ */+export function XDSChartAxis({+ position,+ tickCount = 5,+ tickFormat,+}: XDSChartAxisProps) {+ const {width, height, xScale, yScale} = useChart();++ const isHorizontal = position === 'top' || position === 'bottom';+ const scale = isHorizontal ? xScale : yScale;++ const ticks = useMemo(() => {+ if (isBandScale(scale)) {+ return scale.domain().map(d => ({+ value: d,+ offset: (scale(d) ?? 0) + scale.bandwidth() / 2,+ }));+ }+ const linearScale = scale as+ | ScaleLinear<number, number>+ | ScaleTime<number, number>;+ return linearScale.ticks(tickCount).map(d => ({+ value: d,+ offset: linearScale(d as number & Date),+ }));+ }, [scale, tickCount]);++ const transform =+ position === 'bottom'+ ? `translate(0,${height})`+ : position === 'right'+ ? `translate(${width},0)`+ : undefined;++ const format = tickFormat ?? String;+ const tickSize = 6;++ return (+ <g transform={transform}>+ {/* Axis line */}+ <line+ x1={isHorizontal ? 0 : 0}+ x2={isHorizontal ? width : 0}+ y1={isHorizontal ? 0 : 0}+ y2={isHorizontal ? 0 : height}+ stroke="var(--color-border)"+ strokeWidth={1}+ />+ {ticks.map(({value, offset}) => {+ const label = format(value);+ if (isHorizontal) {+ const y = position === 'bottom' ? tickSize : -tickSize;+ return (+ <g key={label} transform={`translate(${offset},0)`}>+ <line y2={y} stroke="var(--color-border)" strokeWidth={1} />+ <text+ y={position === 'bottom' ? tickSize + 12 : -(tickSize + 4)}+ textAnchor="middle"+ fill="var(--color-text-secondary)"+ fontSize={12}>+ {label}+ </text>+ </g>+ );+ }+ // Vertical axis+ const x = position === 'left' ? -tickSize : tickSize;+ return (+ <g key={label} transform={`translate(0,${offset})`}>+ <line x2={x} stroke="var(--color-border)" strokeWidth={1} />+ <text+ x={position === 'left' ? -(tickSize + 4) : tickSize + 4}+ dy="0.32em"+ textAnchor={position === 'left' ? 'end' : 'start'}+ fill="var(--color-text-secondary)"+ fontSize={12}>+ {label}+ </text>+ </g>+ );+ })}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartBar.tsx b/packages/lab/src/Chart/XDSChartBar.tsxnew file mode 100644index 0000000000..b9e5b6e56a--- /dev/null+++ b/packages/lab/src/Chart/XDSChartBar.tsx@@ -0,0 +1,62 @@+/**+ * @file XDSChartBar.tsx+ * @output Renders vertical bars for a data key+ * @position Child of XDSChart; reads scales from context+ */++import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartBarProps {+ /** Which data key to visualize */+ dataKey: string;+ /** Bar fill color (hex string, CSS var, etc.) */+ color: string;+ /** Corner radius on bar tops */+ radius?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Bar marks. Requires a band xScale (categorical x-axis).+ *+ * @example+ * ```+ * <XDSChartBar dataKey="revenue" color={XDSChartColors.categorical(1)[0]} />+ * ```+ */+export function XDSChartBar({dataKey, color, radius = 4}: XDSChartBarProps) {+ const {data, xScale, yScale, height} = useChart();++ if (!isBandScale(xScale)) return null;++ return (+ <g>+ {data.map((d, i) => {+ const xVal = xScale(String(Object.values(d)[0]));+ if (xVal == null) return null;++ const yVal =+ typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ const barHeight = height - yScale(yVal);+ const barY = yScale(yVal);++ return (+ <rect+ key={i}+ x={xVal}+ y={barY}+ width={xScale.bandwidth()}+ height={Math.max(0, barHeight)}+ fill={color}+ rx={radius}+ ry={radius}+ />+ );+ })}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartDot.tsx b/packages/lab/src/Chart/XDSChartDot.tsxnew file mode 100644index 0000000000..5bd81b3d6c--- /dev/null+++ b/packages/lab/src/Chart/XDSChartDot.tsx@@ -0,0 +1,53 @@+/**+ * @file XDSChartDot.tsx+ * @output Renders scatter dots for a pair of data keys+ * @position Child of XDSChart; reads scales from context+ */++import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartDotProps {+ /** Which data key for the y values */+ dataKey: string;+ /** Dot fill color */+ color: string;+ /** Dot radius */+ radius?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Scatter dot marks.+ *+ * @example+ * ```+ * <XDSChartDot dataKey="outliers" color={XDSChartColors.categorical(3)[2]} />+ * ```+ */+export function XDSChartDot({dataKey, color, radius = 4}: XDSChartDotProps) {+ const {data, xScale, yScale} = useChart();++ return (+ <g>+ {data.map((d, i) => {+ let x: number;+ if (isBandScale(xScale)) {+ x =+ (xScale(String(Object.values(d)[0])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ const xVal = Object.values(d)[0];+ x = (xScale as (v: number) => number)(xVal as number);+ }+ const yVal =+ typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ return (+ <circle key={i} cx={x} cy={yScale(yVal)} r={radius} fill={color} />+ );+ })}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartGrid.tsx b/packages/lab/src/Chart/XDSChartGrid.tsxnew file mode 100644index 0000000000..656dd2534d--- /dev/null+++ b/packages/lab/src/Chart/XDSChartGrid.tsx@@ -0,0 +1,83 @@+/**+ * @file XDSChartGrid.tsx+ * @output Renders horizontal and/or vertical grid lines+ * @position Child of XDSChart; reads scales from context+ */++import {useMemo} from 'react';+import {useChart} from './ChartContext';+import type {ScaleBand, ScaleLinear, ScaleTime} from 'd3-scale';++export interface XDSChartGridProps {+ /** Show horizontal grid lines (default: true) */+ horizontal?: boolean;+ /** Show vertical grid lines */+ vertical?: boolean;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Grid lines behind chart marks.+ *+ * @example+ * ```+ * <XDSChartGrid horizontal />+ * <XDSChartGrid horizontal vertical />+ * ```+ */+export function XDSChartGrid({+ horizontal = true,+ vertical = false,+}: XDSChartGridProps) {+ const {width, height, xScale, yScale} = useChart();++ const hLines = useMemo(() => {+ if (!horizontal) return [];+ return yScale.ticks(5).map(tick => yScale(tick));+ }, [horizontal, yScale]);++ const vLines = useMemo(() => {+ if (!vertical) return [];+ if (isBandScale(xScale)) {+ return xScale+ .domain()+ .map(d => (xScale(d) ?? 0) + xScale.bandwidth() / 2);+ }+ const linear = xScale as+ | ScaleLinear<number, number>+ | ScaleTime<number, number>;+ return linear.ticks(5).map(d => linear(d as number & Date));+ }, [vertical, xScale]);++ return (+ <g>+ {hLines.map(y => (+ <line+ key={`h-${y}`}+ x1={0}+ x2={width}+ y1={y}+ y2={y}+ stroke="var(--color-border)"+ strokeOpacity={0.5}+ strokeDasharray="4 4"+ />+ ))}+ {vLines.map(x => (+ <line+ key={`v-${x}`}+ x1={x}+ x2={x}+ y1={0}+ y2={height}+ stroke="var(--color-border)"+ strokeOpacity={0.5}+ strokeDasharray="4 4"+ />+ ))}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartLegend.tsx b/packages/lab/src/Chart/XDSChartLegend.tsxnew file mode 100644index 0000000000..7202ef81cd--- /dev/null+++ b/packages/lab/src/Chart/XDSChartLegend.tsx@@ -0,0 +1,64 @@+/**+ * @file XDSChartLegend.tsx+ * @output Renders a legend with color swatches and labels+ * @position Child of XDSChart or standalone+ */++export interface XDSChartLegendItem {+ label: string;+ color: string;+}++export interface XDSChartLegendProps {+ items: XDSChartLegendItem[];+ /** Position relative to chart (default: bottom) */+ position?: 'top' | 'bottom';+}++/**+ * Chart legend. Renders a row of color swatches with labels.+ *+ * @example+ * ```+ * <XDSChartLegend items={[+ * { label: 'Revenue', color: XDSChartColors.categorical(2)[0] },+ * { label: 'Expenses', color: XDSChartColors.categorical(2)[1] },+ * ]} />+ * ```+ */+export function XDSChartLegend({items}: XDSChartLegendProps) {+ return (+ <foreignObject+ x={0}+ y={-4}+ width="100%"+ height={24}+ style={{overflow: 'visible'}}>+ <div+ style={{+ display: 'flex',+ gap: 16,+ justifyContent: 'center',+ fontSize: 12,+ color: 'var(--color-text-secondary)',+ }}>+ {items.map(item => (+ <div+ key={item.label}+ style={{display: 'flex', alignItems: 'center', gap: 4}}>+ <div+ style={{+ width: 10,+ height: 10,+ borderRadius: 2,+ backgroundColor: item.color,+ flexShrink: 0,+ }}+ />+ <span>{item.label}</span>+ </div>+ ))}+ </div>+ </foreignObject>+ );+}diff --git a/packages/lab/src/Chart/XDSChartLine.tsx b/packages/lab/src/Chart/XDSChartLine.tsxnew file mode 100644index 0000000000..c8fd81f8fb--- /dev/null+++ b/packages/lab/src/Chart/XDSChartLine.tsx@@ -0,0 +1,78 @@+/**+ * @file XDSChartLine.tsx+ * @output Renders a line for a data key+ * @position Child of XDSChart; reads scales from context+ */++import {useMemo} from 'react';+import {line, curveMonotoneX} from 'd3-shape';+import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartLineProps {+ /** Which data key to visualize */+ dataKey: string;+ /** Line stroke color */+ color: string;+ /** Stroke width */+ strokeWidth?: number;+ /** Show dots at data points */+ dots?: boolean;+ /** Dot radius */+ dotRadius?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Line mark. Works with both band and linear x-scales.+ *+ * @example+ * ```+ * <XDSChartLine dataKey="trend" color={XDSChartColors.categorical(2)[1]} />+ * <XDSChartLine dataKey="trend" color="#0171E3" dots />+ * ```+ */+export function XDSChartLine({+ dataKey,+ color,+ strokeWidth = 2,+ dots = false,+ dotRadius = 3,+}: XDSChartLineProps) {+ const {data, xScale, yScale} = useChart();++ const points = useMemo(() => {+ return data.map((d, i) => {+ let x: number;+ if (isBandScale(xScale)) {+ x = (xScale(String(Object.values(d)[0])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ const xVal = Object.values(d)[0];+ x = (xScale as (v: number) => number)(xVal as number);+ }+ const yVal = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ return {x, y: yScale(yVal), index: i};+ });+ }, [data, dataKey, xScale, yScale]);++ const pathD = useMemo(() => {+ const generator = line<{x: number; y: number}>()+ .x(d => d.x)+ .y(d => d.y)+ .curve(curveMonotoneX);+ return generator(points) ?? '';+ }, [points]);++ return (+ <g>+ <path d={pathD} fill="none" stroke={color} strokeWidth={strokeWidth} />+ {dots &&+ points.map(p => (+ <circle key={p.index} cx={p.x} cy={p.y} r={dotRadius} fill={color} />+ ))}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartTooltip.tsx b/packages/lab/src/Chart/XDSChartTooltip.tsxnew file mode 100644index 0000000000..3a1e0bba84--- /dev/null+++ b/packages/lab/src/Chart/XDSChartTooltip.tsx@@ -0,0 +1,169 @@+/**+ * @file XDSChartTooltip.tsx+ * @output Hover tooltip that follows the nearest data point+ * @position Child of XDSChart; reads scales from context+ */++import {useState, useCallback, type ReactNode} from 'react';+import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartTooltipProps {+ /**+ * Custom render function for tooltip content.+ * Receives the hovered data point.+ * Default: renders all yKeys as "key: value" lines.+ */+ render?: (datum: Record<string, unknown>, index: number) => ReactNode;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Tooltip overlay. Renders a floating card near the hovered data point.+ * Place as the last child inside XDSChart so it renders on top.+ *+ * @example+ * ```+ * <XDSChartTooltip />+ * <XDSChartTooltip render={(d) => <span>{d.month}: ${d.revenue}</span>} />+ * ```+ */+export function XDSChartTooltip({render}: XDSChartTooltipProps) {+ const {data, xScale, yScale, width, height} = useChart();+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);++ const handleMouseMove = useCallback(+ (e: React.MouseEvent<SVGRectElement>) => {+ const svg = e.currentTarget.ownerSVGElement;+ if (!svg) return;+ const point = svg.createSVGPoint();+ point.x = e.clientX;+ point.y = e.clientY;+ const cursor = point.matrixTransform(+ e.currentTarget.getScreenCTM()?.inverse(),+ );++ // Find nearest data index by x position+ if (isBandScale(xScale)) {+ const domain = xScale.domain();+ const step = xScale.step();+ const idx = Math.min(+ domain.length - 1,+ Math.max(0, Math.floor(cursor.x / step)),+ );+ setHoverIndex(idx);+ } else {+ // Linear — find closest point+ const linearScale = xScale as (v: number) => number;+ let closest = 0;+ let minDist = Infinity;+ data.forEach((d, i) => {+ const xVal = Object.values(d)[0] as number;+ const dist = Math.abs(linearScale(xVal) - cursor.x);+ if (dist < minDist) {+ minDist = dist;+ closest = i;+ }+ });+ setHoverIndex(closest);+ }+ },+ [data, xScale],+ );++ const handleMouseLeave = useCallback(() => setHoverIndex(null), []);++ const datum = hoverIndex !== null ? data[hoverIndex] : null;++ // Compute tooltip position+ let tooltipX = 0;+ let tooltipY = 0;+ if (datum && hoverIndex !== null) {+ if (isBandScale(xScale)) {+ tooltipX =+ (xScale(String(Object.values(datum)[0])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ tooltipX = (xScale as (v: number) => number)(+ Object.values(datum)[0] as number,+ );+ }+ // Find the max y value across all numeric keys for positioning+ const yVals = Object.values(datum).filter(+ (v): v is number => typeof v === 'number',+ );+ tooltipY = yScale(Math.max(...yVals));+ }++ const defaultRender = (d: Record<string, unknown>) => (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: 2,+ fontSize: 12,+ }}>+ {Object.entries(d).map(([k, v]) => (+ <div key={k}>+ <span style={{color: 'var(--color-text-secondary)'}}>{k}:</span>{' '}+ <span style={{fontWeight: 500}}>{String(v)}</span>+ </div>+ ))}+ </div>+ );++ return (+ <g>+ {/* Invisible overlay to capture mouse events */}+ <rect+ x={0}+ y={0}+ width={width}+ height={height}+ fill="transparent"+ onMouseMove={handleMouseMove}+ onMouseLeave={handleMouseLeave}+ />++ {/* Vertical crosshair */}+ {hoverIndex !== null && (+ <line+ x1={tooltipX}+ x2={tooltipX}+ y1={0}+ y2={height}+ stroke="var(--color-border-emphasized)"+ strokeWidth={1}+ strokeDasharray="4 4"+ pointerEvents="none"+ />+ )}++ {/* Tooltip card via foreignObject */}+ {datum && hoverIndex !== null && (+ <foreignObject+ x={tooltipX + 8}+ y={Math.max(0, tooltipY - 40)}+ width={180}+ height={120}+ pointerEvents="none"+ style={{overflow: 'visible'}}>+ <div+ style={{+ background: 'var(--color-background-popover)',+ border: '1px solid var(--color-border)',+ borderRadius: 8,+ padding: '8px 12px',+ boxShadow: 'var(--shadow-med)',+ whiteSpace: 'nowrap',+ width: 'fit-content',+ }}>+ {render ? render(datum, hoverIndex) : defaultRender(datum)}+ </div>+ </foreignObject>+ )}+ </g>+ );+}diff --git a/packages/lab/src/Chart/index.ts b/packages/lab/src/Chart/index.tsnew file mode 100644index 0000000000..714659584f--- /dev/null+++ b/packages/lab/src/Chart/index.ts@@ -0,0 +1,14 @@+export {XDSChart, type XDSChartProps} from './XDSChart';+export {XDSChartAxis, type XDSChartAxisProps} from './XDSChartAxis';+export {XDSChartGrid, type XDSChartGridProps} from './XDSChartGrid';+export {XDSChartBar, type XDSChartBarProps} from './XDSChartBar';+export {XDSChartLine, type XDSChartLineProps} from './XDSChartLine';+export {XDSChartDot, type XDSChartDotProps} from './XDSChartDot';+export {XDSChartTooltip, type XDSChartTooltipProps} from './XDSChartTooltip';+export {+ XDSChartLegend,+ type XDSChartLegendProps,+ type XDSChartLegendItem,+} from './XDSChartLegend';+export {useChart} from './ChartContext';+export type {ChartContext, ChartMargin, ChartScale} from './types';diff --git a/packages/lab/src/Chart/types.ts b/packages/lab/src/Chart/types.tsnew file mode 100644index 0000000000..a1d468b8b6--- /dev/null+++ b/packages/lab/src/Chart/types.ts@@ -0,0 +1,37 @@+/**+ * @file types.ts+ * @output Chart types, scale context, and margin convention+ * @position Foundation types consumed by all chart sub-components+ */++import type {ScaleLinear, ScaleBand, ScaleTime} from 'd3-scale';++/** Margin convention for chart SVG */+export interface ChartMargin {+ top: number;+ right: number;+ bottom: number;+ left: number;+}++/** Any d3 scale that maps a domain to a pixel range */+export type ChartScale =+ | ScaleLinear<number, number>+ | ScaleBand<string>+ | ScaleTime<number, number>;++/** Scale context provided by XDSChart to children */+export interface ChartContext {+ /** Inner width (SVG width minus margins) */+ width: number;+ /** Inner height (SVG height minus margins) */+ height: number;+ /** Margin offsets */+ margin: ChartMargin;+ /** The full dataset */+ data: Record<string, unknown>[];+ /** X scale — band for categorical, linear/time for continuous */+ xScale: ChartScale;+ /** Y scale — typically linear */+ yScale: ScaleLinear<number, number>;+}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 128381ec58..455bea16c1 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -57,3 +57,28 @@ export {// Chart colors — palette accessor for data visualizationexport {XDSChartColors, type SequentialHue} from './ChartColors';++// Chart components — composable d3-based data visualization+export {+ XDSChart,+ type XDSChartProps,+ XDSChartAxis,+ type XDSChartAxisProps,+ XDSChartGrid,+ type XDSChartGridProps,+ XDSChartBar,+ type XDSChartBarProps,+ XDSChartLine,+ type XDSChartLineProps,+ XDSChartDot,+ type XDSChartDotProps,+ XDSChartTooltip,+ type XDSChartTooltipProps,+ XDSChartLegend,+ type XDSChartLegendProps,+ type XDSChartLegendItem,+ useChart,+ type ChartContext,+ type ChartMargin,+ type ChartScale,+} from './Chart';diff --git a/yarn.lock b/yarn.lockindex f434649969..e94e2f73ca 100644--- a/yarn.lock+++ b/yarn.lock@@ -2375,7 +2375,7 @@dependencies:"@babel/types" "^7.28.2"-"@types/d3-array@^3.0.3":+"@types/d3-array@^3.0.3", "@types/d3-array@^3.2.2":version "3.2.2"resolved "https://registry.yarnpkg.com/@types/d3-array/-/d3-array-3.2.2.tgz#e02151464d02d4a1b44646d0fcdb93faf88fde8c"integrity sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==@@ -2402,14 +2402,14 @@resolved "https://registry.yarnpkg.com/@types/d3-path/-/d3-path-3.1.1.tgz#f632b380c3aca1dba8e34aa049bcd6a4af23df8a"integrity sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==-"@types/d3-scale@^4.0.2":+"@types/d3-scale@^4.0.2", "@types/d3-scale@^4.0.9":version "4.0.9"resolved "https://registry.yarnpkg.com/@types/d3-scale/-/d3-scale-4.0.9.tgz#57a2f707242e6fe1de81ad7bfcccaaf606179afb"integrity sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==dependencies:"@types/d3-time" "*"-"@types/d3-shape@^3.1.0":+"@types/d3-shape@^3.1.0", "@types/d3-shape@^3.1.8":version "3.1.8"resolved "https://registry.yarnpkg.com/@types/d3-shape/-/d3-shape-3.1.8.tgz#d1516cc508753be06852cd06758e3bb54a22b0e3"integrity sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==@@ -5122,7 +5122,12 @@ prelude-ls@^1.2.1:resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz"integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==-prettier@^2.7.1, prettier@^3.8.2:+prettier@^2.7.1:+ version "2.8.8"+ resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.8.tgz#e8c5d7e98a4305ffe3de2e1fc4aca1a71c28b1da"+ integrity sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==++prettier@^3.8.2:version "3.8.2"resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.8.2.tgz#4f52e502193c9aa5b384c3d00852003e551bbd9f"integrity sha512-8c3mgTe0ASwWAJK+78dpviD+A8EqhndQPUBpNUIPt6+xWlIigCwfN01lWr9MAede4uqXGTEKeQWTvzb3vjia0Q==