An open source design system that's fully customizable and agent ready
TypeScript
feat(charts): v2 architecture — config model with series renderers (#1548)
Cindy Zhangc3d0052c4840
diff --git a/apps/storybook/stories/ChartV2.stories.tsx b/apps/storybook/stories/ChartV2.stories.tsxnew file mode 100644index 0000000000..3e0022481e--- /dev/null+++ b/apps/storybook/stories/ChartV2.stories.tsx@@ -0,0 +1,147 @@+import type {Meta, StoryObj} from '@storybook/react';+import {XDSChartV2 as XDSChart, bar, line, dot, area, band} from '@xds/lab';+import {XDSChartGrid, XDSChartAxis} from '@xds/lab';++const meta: Meta<typeof XDSChart> = {+ title: 'Lab/XDSChart v2',+ component: XDSChart,+};+export default meta;++const monthlyData = [+ {month: 'Jan', revenue: 45, costs: 30, trend: 38},+ {month: 'Feb', revenue: 52, costs: 35, trend: 42},+ {month: 'Mar', revenue: 48, costs: 32, trend: 40},+ {month: 'Apr', revenue: 61, costs: 38, trend: 48},+ {month: 'May', revenue: 55, costs: 34, trend: 45},+ {month: 'Jun', revenue: 70, costs: 40, trend: 52},+];++/** Simple bar chart */+export const SimpleBar: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ series={[bar('revenue', {color: '#3b82f6'})]}+ grid={<XDSChartGrid horizontal />}+ axes={+ <>+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ </>+ }+ height={300}+ />+ ),+};++/** Stacked bars */+export const StackedBars: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ series={[+ bar('revenue', {color: '#3b82f6', stack: 'totals'}),+ bar('costs', {color: '#ef4444', stack: 'totals'}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={+ <>+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ </>+ }+ height={300}+ />+ ),+};++/** Grouped bars */+export const GroupedBars: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ series={[+ bar('revenue', {color: '#3b82f6', group: 'compare'}),+ bar('costs', {color: '#ef4444', group: 'compare'}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={+ <>+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ </>+ }+ height={300}+ />+ ),+};++/** Mixed: bars + line */+export const MixedMarks: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ series={[+ bar('revenue', {color: '#3b82f6'}),+ line('trend', {color: '#f59e0b'}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={+ <>+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ </>+ }+ height={300}+ />+ ),+};++/** Area with gradient */+export const AreaGradient: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ series={[+ area('revenue', {color: '#3b82f6', gradient: true}),+ line('revenue', {color: '#3b82f6'}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={+ <>+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ </>+ }+ height={300}+ />+ ),+};++/** Stacked areas */+export const StackedAreas: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ series={[+ area('revenue', {color: '#3b82f6', stack: 'total'}),+ area('costs', {color: '#ef4444', stack: 'total'}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={+ <>+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ </>+ }+ height={300}+ />+ ),+};diff --git a/packages/lab/src/ChartV2/ChartV2Context.ts b/packages/lab/src/ChartV2/ChartV2Context.tsnew file mode 100644index 0000000000..6455fdb767--- /dev/null+++ b/packages/lab/src/ChartV2/ChartV2Context.ts@@ -0,0 +1,18 @@+/**+ * @file ChartV2Context.ts+ * @output React context for v2 chart — used by interaction children+ * @position Provided by XDSChart, consumed by tooltip/crosshair/brush+ */++import {createContext, useContext} from 'react';+import type {ChartV2Context} from './types';++const Ctx = createContext<ChartV2Context | null>(null);++export const ChartV2Provider = Ctx.Provider;++export function useChartV2(): ChartV2Context {+ const ctx = useContext(Ctx);+ if (!ctx) throw new Error('Must be used inside <XDSChart>');+ return ctx;+}diff --git a/packages/lab/src/ChartV2/XDSChart.tsx b/packages/lab/src/ChartV2/XDSChart.tsxnew file mode 100644index 0000000000..6951aad42c--- /dev/null+++ b/packages/lab/src/ChartV2/XDSChart.tsx@@ -0,0 +1,239 @@+/**+ * @file XDSChart.tsx (v2)+ * @output Root chart component — coordinates layout, rendering, and events+ * @position Top-level component; delegates to series renderers and interaction slots+ *+ * The chart root:+ * 1. Measures container width (responsive)+ * 2. Runs layout (scales + transforms + position resolution)+ * 3. Renders chrome (grid, axes) via slots+ * 4. Calls each series config's renderer+ * 5. Renders interaction slot with event dispatch+ * 6. Renders legend slot+ */++import {+ type ReactNode,+ useMemo,+ useRef,+ useState,+ useCallback,+ useLayoutEffect,+} from 'react';+import type {SeriesConfig} from './series';+import type {ChartV2Context, ChartMargin, ChartPointerEvent} from './types';+import {computeLayout} from './layout';+import {ChartV2Provider} from './ChartV2Context';+import {ChartProvider} from '../Chart/ChartContext';+import {renderSeries} from './renderers';++export interface XDSChartProps {+ /** The dataset */+ data: Record<string, unknown>[];+ /** Key for x-axis values */+ xKey: string;+ /** Series configs — defines what marks to render */+ series: SeriesConfig[];+ /** Chart height in pixels */+ height?: number;+ /** Margin overrides */+ margin?: Partial<ChartMargin>;+ /** Grid slot */+ grid?: ReactNode;+ /** Axes slot */+ axes?: ReactNode;+ /** Legend slot — true for auto-generated, or a ReactNode */+ legend?: boolean | ReactNode;+ /** Interactions slot */+ interactions?: ReactNode;+ /** Escape hatch — custom overlay content */+ children?: ReactNode;+}++const DEFAULT_MARGIN: ChartMargin = {top: 16, right: 16, bottom: 32, left: 48};++export function XDSChart({+ data,+ xKey,+ series,+ height = 300,+ margin: marginOverride,+ grid,+ axes,+ legend,+ interactions,+ children,+}: XDSChartProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const svgRef = useRef<SVGSVGElement>(null);+ const [containerWidth, setContainerWidth] = useState(0);+ const pointerHandlers = useRef<Set<(e: ChartPointerEvent) => void>>(+ new Set(),+ );++ // ─── Responsive width ─────────────────────────────────────────────────+ 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);++ // ─── Layout pass ──────────────────────────────────────────────────────+ const layout = useMemo(+ () =>+ computeLayout({+ data,+ xKey,+ series,+ width: innerWidth,+ height: innerHeight,+ }),+ [data, xKey, series, innerWidth, innerHeight],+ );++ // ─── Event dispatch ───────────────────────────────────────────────────+ const onPointer = useCallback((handler: (e: ChartPointerEvent) => void) => {+ pointerHandlers.current.add(handler);+ return () => {+ pointerHandlers.current.delete(handler);+ };+ }, []);++ const dispatch = useCallback((e: ChartPointerEvent) => {+ for (const handler of pointerHandlers.current) handler(e);+ }, []);++ const handlePointerMove = useCallback(+ (e: React.PointerEvent<SVGRectElement>) => {+ const svg = svgRef.current;+ if (!svg) return;+ const point = svg.createSVGPoint();+ point.x = e.clientX;+ point.y = e.clientY;+ const ctm = e.currentTarget.getScreenCTM()?.inverse();+ if (!ctm) return;+ const cursor = point.matrixTransform(ctm);++ // Find nearest resolved point+ let nearest: ChartPointerEvent['nearest'] = null;+ let bestDist = 40 * 40; // 40px snap radius+ for (const [seriesKey, points] of layout.resolved) {+ for (const p of points) {+ const dx = p.px - cursor.x;+ const dy = p.py - cursor.y;+ const dist = dx * dx + dy * dy;+ if (dist < bestDist) {+ bestDist = dist;+ nearest = {...p, seriesKey};+ }+ }+ }++ dispatch({x: cursor.x, y: cursor.y, nearest, active: e.buttons > 0});+ },+ [layout.resolved, dispatch],+ );++ const handlePointerLeave = useCallback(() => {+ dispatch({x: -1, y: -1, nearest: null, active: false});+ }, [dispatch]);++ // ─── Context for interactions ─────────────────────────────────────────+ const ctx: ChartV2Context = useMemo(+ () => ({+ width: innerWidth,+ height: innerHeight,+ margin,+ data,+ xKey,+ xScale: layout.xScale,+ yScale: layout.yScale,+ resolved: layout.resolved,+ onPointer,+ svgRef,+ }),+ [innerWidth, innerHeight, margin, data, xKey, layout, onPointer],+ );++ // ─── Bridge to v1 context (so XDSChartGrid, XDSChartAxis etc. work) ──+ const v1Ctx = useMemo(+ () => ({+ width: innerWidth,+ height: innerHeight,+ margin,+ xKey,+ data,+ xScale: layout.xScale,+ yScale: layout.yScale,+ svgRef,+ pointerToData: (e: React.PointerEvent) => ({+ x: null as string | number | null,+ y: 0,+ px: 0,+ py: 0,+ }),+ pixelToData: (px: number, py: number) => ({+ x: null as string | number | null,+ y: 0,+ px,+ py,+ }),+ }),+ [innerWidth, innerHeight, margin, xKey, data, layout, svgRef],+ );++ // ─── Render ───────────────────────────────────────────────────────────+ if (containerWidth === 0) {+ return <div ref={containerRef} style={{width: '100%', height}} />;+ }++ return (+ <div ref={containerRef} style={{width: '100%'}}>+ <ChartV2Provider value={ctx}>+ <ChartProvider value={v1Ctx}>+ <svg ref={svgRef} width={containerWidth} height={height}>+ <g transform={`translate(${margin.left},${margin.top})`}>+ {/* 1. Grid (background) */}+ {grid}++ {/* 2. Marks (data layer) — each series renders itself */}+ {renderSeries(series, layout, data, xKey)}++ {/* 3. Axes (frame) */}+ {axes}++ {/* 4. Event capture rect + interactions (overlay) */}+ <rect+ x={0}+ y={0}+ width={innerWidth}+ height={innerHeight}+ fill="transparent"+ onPointerMove={handlePointerMove}+ onPointerLeave={handlePointerLeave}+ />+ {interactions}++ {/* 5. Escape hatch */}+ {children}+ </g>+ </svg>++ {/* 6. Legend (outside SVG if needed) */}+ {legend === true ? null /* TODO: auto legend */ : legend}+ </ChartProvider>+ </ChartV2Provider>+ </div>+ );+}diff --git a/packages/lab/src/ChartV2/index.ts b/packages/lab/src/ChartV2/index.tsnew file mode 100644index 0000000000..7b3b87ab4b--- /dev/null+++ b/packages/lab/src/ChartV2/index.ts@@ -0,0 +1,6 @@+// Public API+export {XDSChart, type XDSChartProps} from './XDSChart';+export {bar, line, dot, area, band, candlestick} from './series';+export type {BarConfig, LineConfig, DotConfig, AreaConfig, BandConfig, CandlestickConfig, SeriesConfig} from './series';+export {useChartV2} from './ChartV2Context';+export type {ChartV2Context, ChartPointerEvent, ResolvedPoint, ResolvedPositions} from './types';diff --git a/packages/lab/src/ChartV2/layout.ts b/packages/lab/src/ChartV2/layout.tsnew file mode 100644index 0000000000..ee091b9939--- /dev/null+++ b/packages/lab/src/ChartV2/layout.ts@@ -0,0 +1,248 @@+/**+ * @file layout.ts+ * @output Computes scales, layout transforms, and resolved positions from data + series+ * @position Called by XDSChart root — the single layout pass+ *+ * Pipeline: data + series → scales → transforms (stack, group, dodge) → resolvedPositions+ */++import {scaleLinear, scaleBand} from 'd3-scale';+import {stack as d3Stack, stackOrderNone, stackOffsetNone} from 'd3-shape';+import type {SeriesConfig, BarConfig, DotConfig, AreaConfig} from './series';+import type {+ ChartScale,+ ResolvedPositions,+ ResolvedPoint,+ ChartMargin,+} from './types';++export interface LayoutInput {+ data: Record<string, unknown>[];+ xKey: string;+ series: SeriesConfig[];+ width: number;+ height: number;+}++export interface LayoutResult {+ xScale: ChartScale;+ yScale: ReturnType<typeof scaleLinear<number, number>>;+ resolved: ResolvedPositions;+ /** Bar group info: groupId → {keys[], bandwidth per bar} */+ barGroups: Map<string, {keys: string[]; barWidth: number}>;+}++export function computeLayout({+ data,+ xKey,+ series,+ width,+ height,+}: LayoutInput): LayoutResult {+ // ─── 1. Determine x scale ────────────────────────────────────────────+ const xValues = data.map(d => d[xKey]);+ const isNumericX =+ xValues.length > 0 && xValues.every(v => typeof v === 'number');++ let xScale: ChartScale;+ if (isNumericX) {+ const nums = xValues as number[];+ const xMin = Math.min(...nums);+ const xMax = Math.max(...nums);+ xScale = scaleLinear().domain([xMin, xMax]).range([0, width]).nice();+ } else {+ xScale = scaleBand<string>()+ .domain(xValues.map(String))+ .range([0, width])+ .padding(0.2);+ }++ // ─── 2. Collect all y keys and compute y domain ───────────────────────+ const allYKeys = new Set<string>();+ for (const s of series) {+ for (const k of s.keys) allYKeys.add(k);+ }++ let yMin = Infinity;+ let yMax = -Infinity;+ for (const d of data) {+ for (const k of allYKeys) {+ const v = d[k];+ if (typeof v === 'number') {+ if (v < yMin) yMin = v;+ if (v > yMax) yMax = v;+ }+ }+ }+ // Include zero for bar charts+ if (series.some(s => s.type === 'bar' || s.type === 'area')) {+ if (yMin > 0) yMin = 0;+ if (yMax < 0) yMax = 0;+ }++ const yScale = scaleLinear().domain([yMin, yMax]).range([height, 0]).nice();++ // ─── 3. Compute stacking ─────────────────────────────────────────────+ const stackGroups = new Map<string, string[]>();+ for (const s of series) {+ if ((s.type === 'bar' || s.type === 'area') && 'stack' in s && s.stack) {+ const group = stackGroups.get(s.stack) ?? [];+ group.push(s.dataKey);+ stackGroups.set(s.stack, group);+ }+ }++ // d3-stack produces cumulative y0/y1 per series+ const stackedData = new Map<string, {y0: number; y1: number}[]>();+ for (const [, keys] of stackGroups) {+ const stackGen = d3Stack<Record<string, unknown>>()+ .keys(keys)+ .order(stackOrderNone)+ .offset(stackOffsetNone);+ const stacked = stackGen(data);+ for (const layer of stacked) {+ stackedData.set(+ layer.key,+ layer.map(d => ({y0: d[0], y1: d[1]})),+ );+ }+ }++ // ─── 4. Compute bar grouping ─────────────────────────────────────────+ const barGroups = new Map<string, {keys: string[]; barWidth: number}>();+ const groupedBars = new Map<string, string[]>();+ for (const s of series) {+ if (s.type === 'bar' && 'group' in s && s.group && !s.stack) {+ const group = groupedBars.get(s.group) ?? [];+ group.push(s.dataKey);+ groupedBars.set(s.group, group);+ }+ }+ if ('bandwidth' in xScale) {+ const bw = xScale.bandwidth();+ for (const [groupId, keys] of groupedBars) {+ barGroups.set(groupId, {keys, barWidth: bw / keys.length});+ }+ }++ // ─── 5. Resolve positions for every series ────────────────────────────+ const resolved: ResolvedPositions = new Map();++ for (const s of series) {+ const points: ResolvedPoint[] = [];++ switch (s.type) {+ case 'bar': {+ if (!('bandwidth' in xScale)) break;+ const bw = xScale.bandwidth();+ const stacked = stackedData.get(s.dataKey);+ const groupInfo = s.group ? barGroups.get(s.group) : undefined;+ const barWidth = groupInfo ? groupInfo.barWidth : bw;+ const barIndex = groupInfo ? groupInfo.keys.indexOf(s.dataKey) : 0;++ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ const xPos =+ (xScale(String(d[xKey])) ?? 0) + barIndex * barWidth + barWidth / 2;+ let yPos: number;+ let y0Pos: number;+ if (stacked) {+ yPos = yScale(stacked[i].y1);+ y0Pos = yScale(stacked[i].y0);+ } else {+ const v =+ typeof d[s.dataKey] === 'number' ? (d[s.dataKey] as number) : 0;+ yPos = yScale(v);+ y0Pos = yScale(0);+ }+ points.push({px: xPos, py: yPos, py0: y0Pos, dataIndex: i});+ }+ break;+ }++ case 'line':+ case 'area': {+ const stacked =+ s.type === 'area' && s.stack ? stackedData.get(s.dataKey) : undefined;+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px = (xScale(String(d[xKey])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ let py: number;+ let py0: number;+ if (stacked) {+ py = yScale(stacked[i].y1);+ py0 = yScale(stacked[i].y0);+ } else {+ const v =+ typeof d[s.dataKey] === 'number' ? (d[s.dataKey] as number) : 0;+ py = yScale(v);+ py0 = yScale(0);+ }+ points.push({px, py, py0, dataIndex: i});+ }+ break;+ }++ case 'dot': {+ // TODO: dodge layout goes here+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px = (xScale(String(d[xKey])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ const v =+ typeof d[s.dataKey] === 'number' ? (d[s.dataKey] as number) : 0;+ points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});+ }+ break;+ }++ case 'band': {+ // Band has two sets of points (upper/lower) — resolve upper for hit-testing+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px = (xScale(String(d[xKey])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ const v = typeof d[s.upper] === 'number' ? (d[s.upper] as number) : 0;+ points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});+ }+ break;+ }++ case 'candlestick': {+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px = (xScale(String(d[xKey])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ const close =+ typeof d[s.close] === 'number' ? (d[s.close] as number) : 0;+ points.push({px, py: yScale(close), py0: yScale(0), dataIndex: i});+ }+ break;+ }+ }++ // Use dataKey or a generated key for series that don't have one+ const seriesKey =+ 'dataKey' in s ? s.dataKey : `${s.type}-${s.keys.join('-')}`;+ resolved.set(seriesKey, points);+ }++ return {xScale, yScale, resolved, barGroups};+}diff --git a/packages/lab/src/ChartV2/renderers.tsx b/packages/lab/src/ChartV2/renderers.tsxnew file mode 100644index 0000000000..7ca5654f4a--- /dev/null+++ b/packages/lab/src/ChartV2/renderers.tsx@@ -0,0 +1,412 @@+/**+ * @file renderers.tsx+ * @output Mark renderers — each series type knows how to draw itself+ * @position Called by XDSChart root during render; each renderer returns SVG elements+ *+ * Each renderer receives the layout result and produces SVG.+ * New mark types = new renderers. Chart root never changes.+ */++import type {ReactNode} from 'react';+import {+ area as d3Area,+ line as d3Line,+ curveLinear,+ curveMonotoneX,+ curveNatural,+ curveStep,+} from 'd3-shape';+import type {+ SeriesConfig,+ BarConfig,+ LineConfig,+ DotConfig,+ AreaConfig,+ BandConfig,+ CandlestickConfig,+ CurveType,+} from './series';+import type {LayoutResult} from './layout';++const CURVES = {+ linear: curveLinear,+ monotone: curveMonotoneX,+ natural: curveNatural,+ step: curveStep,+} as const;++/** Dispatch rendering for all series */+export function renderSeries(+ series: SeriesConfig[],+ layout: LayoutResult,+ data: Record<string, unknown>[],+ xKey: string,+): ReactNode {+ return series.map((s, i) => {+ const key = 'dataKey' in s ? s.dataKey : `${s.type}-${i}`;+ switch (s.type) {+ case 'bar':+ return (+ <BarRenderer+ key={key}+ config={s}+ layout={layout}+ data={data}+ xKey={xKey}+ />+ );+ case 'line':+ return (+ <LineRenderer+ key={key}+ config={s}+ layout={layout}+ data={data}+ xKey={xKey}+ />+ );+ case 'dot':+ return (+ <DotRenderer+ key={key}+ config={s}+ layout={layout}+ data={data}+ xKey={xKey}+ />+ );+ case 'area':+ return (+ <AreaRenderer+ key={key}+ config={s}+ layout={layout}+ data={data}+ xKey={xKey}+ />+ );+ case 'band':+ return (+ <BandRenderer+ key={key}+ config={s}+ layout={layout}+ data={data}+ xKey={xKey}+ />+ );+ case 'candlestick':+ return (+ <CandlestickRenderer+ key={key}+ config={s}+ layout={layout}+ data={data}+ xKey={xKey}+ />+ );+ default:+ return null;+ }+ });+}++// ─── Bar Renderer ──────────────────────────────────────────────────────────++function BarRenderer({+ config,+ layout,+ data,+ xKey,+}: {+ config: BarConfig;+ layout: LayoutResult;+ data: Record<string, unknown>[];+ xKey: string;+}) {+ const {xScale, yScale, barGroups} = layout;+ if (!('bandwidth' in xScale)) return null;++ const bw = xScale.bandwidth();+ const groupInfo = config.group ? barGroups.get(config.group) : undefined;+ const barWidth = groupInfo ? groupInfo.barWidth : bw;+ const barIndex = groupInfo ? groupInfo.keys.indexOf(config.dataKey) : 0;++ const resolved = layout.resolved.get(config.dataKey);++ return (+ <g opacity={config.opacity}>+ {data.map((d, i) => {+ const xBase = xScale(String(d[xKey])) ?? 0;+ const x = xBase + barIndex * barWidth;++ const point = resolved?.[i];+ if (!point) return null;++ const barY = Math.min(point.py, point.py0);+ const barHeight = Math.abs(point.py0 - point.py);++ const fill =+ typeof config.color === 'function'+ ? config.color(d, i)+ : config.color;++ return (+ <rect+ key={i}+ x={x}+ y={barY}+ width={barWidth}+ height={Math.max(0, barHeight)}+ fill={fill}+ rx={config.radius}+ ry={config.radius}+ />+ );+ })}+ </g>+ );+}++// ─── Line Renderer ─────────────────────────────────────────────────────────++function LineRenderer({+ config,+ layout,+ data,+ xKey,+}: {+ config: LineConfig;+ layout: LayoutResult;+ data: Record<string, unknown>[];+ xKey: string;+}) {+ const resolved = layout.resolved.get(config.dataKey);+ if (!resolved || resolved.length === 0) return null;++ const curveFactory = CURVES[config.curve];+ const pathGen = d3Line<{px: number; py: number}>()+ .x(d => d.px)+ .y(d => d.py)+ .curve(curveFactory);++ const pathD = pathGen(resolved) ?? '';++ return (+ <g>+ <path+ d={pathD}+ fill="none"+ stroke={config.color}+ strokeWidth={config.strokeWidth}+ />+ {config.dots &&+ resolved.map((p, i) => (+ <circle key={i} cx={p.px} cy={p.py} r={3} fill={config.color} />+ ))}+ </g>+ );+}++// ─── Dot Renderer ──────────────────────────────────────────────────────────++function DotRenderer({+ config,+ layout,+ data,+}: {+ config: DotConfig;+ layout: LayoutResult;+ data: Record<string, unknown>[];+ xKey: string;+}) {+ const resolved = layout.resolved.get(config.dataKey);+ if (!resolved) return null;++ return (+ <g>+ {resolved.map((p, i) => {+ const fill =+ typeof config.color === 'function'+ ? config.color(data[p.dataIndex], p.dataIndex)+ : config.color;+ return (+ <circle+ key={i}+ cx={p.px}+ cy={p.py}+ r={config.radius}+ fill={fill}+ opacity={config.opacity}+ />+ );+ })}+ </g>+ );+}++// ─── Area Renderer ─────────────────────────────────────────────────────────++function AreaRenderer({+ config,+ layout,+}: {+ config: AreaConfig;+ layout: LayoutResult;+ data: Record<string, unknown>[];+ xKey: string;+}) {+ const resolved = layout.resolved.get(config.dataKey);+ if (!resolved || resolved.length === 0) return null;++ const curveFactory = CURVES[config.curve];++ // Area path: uses py0 (stacked baseline) and py (top)+ const areaGen = d3Area<{px: number; py: number; py0: number}>()+ .x(d => d.px)+ .y0(d => d.py0)+ .y1(d => d.py)+ .curve(curveFactory);++ const pathD = areaGen(resolved) ?? '';++ // Stroke: only the top line (not the closed area path)+ const lineGen = d3Line<{px: number; py: number}>()+ .x(d => d.px)+ .y(d => d.py)+ .curve(curveFactory);++ const strokeD = lineGen(resolved) ?? '';+ const gradientId = `area-grad-${config.dataKey}`;++ return (+ <g>+ {config.gradient && (+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">+ <stop+ offset="0%"+ stopColor={config.color}+ stopOpacity={config.opacity}+ />+ <stop offset="100%" stopColor={config.color} stopOpacity={0} />+ </linearGradient>+ </defs>+ )}+ <path+ d={pathD}+ fill={config.gradient ? `url(#${gradientId})` : config.color}+ fillOpacity={config.gradient ? 1 : config.opacity}+ stroke="none"+ />+ {config.stroke && (+ <path d={strokeD} fill="none" stroke={config.color} strokeWidth={2} />+ )}+ </g>+ );+}++// ─── Band Renderer ─────────────────────────────────────────────────────────++function BandRenderer({+ config,+ layout,+ data,+ xKey,+}: {+ config: BandConfig;+ layout: LayoutResult;+ data: Record<string, unknown>[];+ xKey: string;+}) {+ const {xScale, yScale} = layout;++ const areaGen = d3Area<Record<string, unknown>>()+ .x(d => {+ if ('bandwidth' in xScale)+ return (xScale(String(d[xKey])) ?? 0) + xScale.bandwidth() / 2;+ return xScale(d[xKey] as number);+ })+ .y0(d =>+ yScale(+ typeof d[config.lower] === 'number' ? (d[config.lower] as number) : 0,+ ),+ )+ .y1(d =>+ yScale(+ typeof d[config.upper] === 'number' ? (d[config.upper] as number) : 0,+ ),+ )+ .curve(curveMonotoneX);++ const pathD = areaGen(data) ?? '';++ return (+ <path+ d={pathD}+ fill={config.color}+ fillOpacity={config.opacity}+ stroke="none"+ />+ );+}++// ─── Candlestick Renderer ──────────────────────────────────────────────────++function CandlestickRenderer({+ config,+ layout,+ data,+ xKey,+}: {+ config: CandlestickConfig;+ layout: LayoutResult;+ data: Record<string, unknown>[];+ xKey: string;+}) {+ const {xScale, yScale} = layout;+ if (!('bandwidth' in xScale)) return null;++ const bw = xScale.bandwidth();+ const bodyWidth = bw * 0.6;++ return (+ <g>+ {data.map((d, i) => {+ const x = (xScale(String(d[xKey])) ?? 0) + bw / 2;+ const open =+ typeof d[config.open] === 'number' ? (d[config.open] as number) : 0;+ const close =+ typeof d[config.close] === 'number' ? (d[config.close] as number) : 0;+ const high =+ typeof d[config.high] === 'number' ? (d[config.high] as number) : 0;+ const low =+ typeof d[config.low] === 'number' ? (d[config.low] as number) : 0;+ const isUp = close >= open;+ const color = isUp ? config.upColor : config.downColor;++ return (+ <g key={i}>+ {/* Wick */}+ <line+ x1={x}+ x2={x}+ y1={yScale(high)}+ y2={yScale(low)}+ stroke={color}+ strokeWidth={1}+ />+ {/* Body */}+ <rect+ x={x - bodyWidth / 2}+ y={yScale(Math.max(open, close))}+ width={bodyWidth}+ height={Math.max(1, Math.abs(yScale(open) - yScale(close)))}+ fill={color}+ />+ </g>+ );+ })}+ </g>+ );+}diff --git a/packages/lab/src/ChartV2/series.ts b/packages/lab/src/ChartV2/series.tsnew file mode 100644index 0000000000..efe9cf9e2e--- /dev/null+++ b/packages/lab/src/ChartV2/series.ts@@ -0,0 +1,230 @@+/**+ * @file series.ts+ * @output Series config types and helper constructors (bar, line, dot, area, etc.)+ * @position User-facing API — these are the building blocks passed to XDSChart's series prop+ *+ * Each helper returns a SeriesConfig object that bundles:+ * 1. Data binding (which keys to read)+ * 2. Visual encoding (color, opacity, radius, etc.)+ * 3. Layout hints (stack, group, dodge)+ * 4. Renderer reference (how to draw — resolved internally)+ */++// ─── Base Types ────────────────────────────────────────────────────────────++export type ColorAccessor = string | ((datum: Record<string, unknown>, index: number) => string);++export interface SeriesBase {+ readonly type: string;+ /** Data key(s) this series reads from */+ readonly keys: string[];+}++// ─── Bar ───────────────────────────────────────────────────────────────────++export interface BarConfig extends SeriesBase {+ readonly type: 'bar';+ readonly dataKey: string;+ readonly keys: [string];+ readonly color: ColorAccessor;+ readonly opacity: number;+ readonly radius: number;+ readonly stack?: string;+ readonly group?: string;+}++export interface BarOptions {+ color?: ColorAccessor;+ opacity?: number;+ radius?: number;+ /** Stack group ID — bars with same stack accumulate */+ stack?: string;+ /** Group ID — bars with same group subdivide the band */+ group?: string;+}++export function bar(dataKey: string, options: BarOptions = {}): BarConfig {+ return {+ type: 'bar',+ dataKey,+ keys: [dataKey],+ color: options.color ?? 'var(--color-chart-1)',+ opacity: options.opacity ?? 1,+ radius: options.radius ?? 4,+ stack: options.stack,+ group: options.group,+ };+}++// ─── Line ──────────────────────────────────────────────────────────────────++export type CurveType = 'linear' | 'monotone' | 'natural' | 'step';++export interface LineConfig extends SeriesBase {+ readonly type: 'line';+ readonly dataKey: string;+ readonly keys: [string];+ readonly color: string;+ readonly curve: CurveType;+ readonly strokeWidth: number;+ readonly dots: boolean;+}++export interface LineOptions {+ color?: string;+ curve?: CurveType;+ strokeWidth?: number;+ dots?: boolean;+}++export function line(dataKey: string, options: LineOptions = {}): LineConfig {+ return {+ type: 'line',+ dataKey,+ keys: [dataKey],+ color: options.color ?? 'var(--color-chart-1)',+ curve: options.curve ?? 'monotone',+ strokeWidth: options.strokeWidth ?? 2,+ dots: options.dots ?? false,+ };+}++// ─── Dot ───────────────────────────────────────────────────────────────────++export interface DotConfig extends SeriesBase {+ readonly type: 'dot';+ readonly dataKey: string;+ readonly keys: [string];+ readonly color: ColorAccessor;+ readonly radius: number;+ readonly opacity: number;+ readonly dodge: boolean;+}++export interface DotOptions {+ color?: ColorAccessor;+ radius?: number;+ opacity?: number;+ /** Run dodge layout to avoid overlapping dots within bands */+ dodge?: boolean;+}++export function dot(dataKey: string, options: DotOptions = {}): DotConfig {+ return {+ type: 'dot',+ dataKey,+ keys: [dataKey],+ color: options.color ?? 'var(--color-chart-1)',+ radius: options.radius ?? 4,+ opacity: options.opacity ?? 0.8,+ dodge: options.dodge ?? false,+ };+}++// ─── Area ──────────────────────────────────────────────────────────────────++export interface AreaConfig extends SeriesBase {+ readonly type: 'area';+ readonly dataKey: string;+ readonly keys: [string];+ readonly color: string;+ readonly opacity: number;+ readonly curve: CurveType;+ readonly stack?: string;+ readonly gradient: boolean;+ readonly stroke: boolean;+}++export interface AreaOptions {+ color?: string;+ opacity?: number;+ curve?: CurveType;+ stack?: string;+ gradient?: boolean;+ stroke?: boolean;+}++export function area(dataKey: string, options: AreaOptions = {}): AreaConfig {+ return {+ type: 'area',+ dataKey,+ keys: [dataKey],+ color: options.color ?? 'var(--color-chart-1)',+ opacity: options.opacity ?? 0.3,+ curve: options.curve ?? 'monotone',+ stack: options.stack,+ gradient: options.gradient ?? false,+ stroke: options.stroke ?? true,+ };+}++// ─── Band (confidence interval) ────────────────────────────────────────────++export interface BandConfig extends SeriesBase {+ readonly type: 'band';+ readonly upper: string;+ readonly lower: string;+ readonly keys: [string, string];+ readonly color: string;+ readonly opacity: number;+}++export interface BandOptions {+ upper: string;+ lower: string;+ color?: string;+ opacity?: number;+}++export function band(options: BandOptions): BandConfig {+ return {+ type: 'band',+ upper: options.upper,+ lower: options.lower,+ keys: [options.upper, options.lower],+ color: options.color ?? 'var(--color-chart-1)',+ opacity: options.opacity ?? 0.15,+ };+}++// ─── Candlestick ───────────────────────────────────────────────────────────++export interface CandlestickConfig extends SeriesBase {+ readonly type: 'candlestick';+ readonly open: string;+ readonly high: string;+ readonly low: string;+ readonly close: string;+ readonly keys: [string, string, string, string];+ readonly upColor: string;+ readonly downColor: string;+}++export interface CandlestickOptions {+ open: string;+ high: string;+ low: string;+ close: string;+ upColor?: string;+ downColor?: string;+}++export function candlestick(options: CandlestickOptions): CandlestickConfig {+ return {+ type: 'candlestick',+ ...options,+ keys: [options.open, options.high, options.low, options.close],+ upColor: options.upColor ?? 'var(--color-positive)',+ downColor: options.downColor ?? 'var(--color-negative)',+ };+}++// ─── Union Type ────────────────────────────────────────────────────────────++export type SeriesConfig =+ | BarConfig+ | LineConfig+ | DotConfig+ | AreaConfig+ | BandConfig+ | CandlestickConfig;diff --git a/packages/lab/src/ChartV2/types.ts b/packages/lab/src/ChartV2/types.tsnew file mode 100644index 0000000000..8b79337d87--- /dev/null+++ b/packages/lab/src/ChartV2/types.ts@@ -0,0 +1,66 @@+/**+ * @file types.ts+ * @output Core types for the v2 chart architecture+ * @position Foundation — consumed by layout, renderers, and interactions+ */++import type {ScaleLinear, ScaleBand} from 'd3-scale';++export type ChartScale = ScaleLinear<number, number> | ScaleBand<string>;++export interface ChartMargin {+ top: number;+ right: number;+ bottom: number;+ left: number;+}++/** Resolved pixel position for a single data point in a series */+export interface ResolvedPoint {+ /** Pixel x in plot area coordinates */+ px: number;+ /** Pixel y in plot area coordinates (top of mark) */+ py: number;+ /** Pixel y baseline (bottom of mark) — differs from py only when stacked */+ py0: number;+ /** Index into the data array */+ dataIndex: number;+}++/** Resolved positions for all series — the single source of truth */+export type ResolvedPositions = Map<string, ResolvedPoint[]>;++/** Pointer event normalized to plot-area coordinates */+export interface ChartPointerEvent {+ /** Pixel x relative to plot area */+ x: number;+ /** Pixel y relative to plot area */+ y: number;+ /** Nearest resolved point (if within snap radius) */+ nearest: (ResolvedPoint & {seriesKey: string}) | null;+ /** Active (pointer down) */+ active: boolean;+}++/** Context provided by XDSChart to interaction children */+export interface ChartV2Context {+ /** Inner width (after margins) */+ width: number;+ /** Inner height (after margins) */+ height: number;+ margin: ChartMargin;+ /** The full dataset */+ data: Record<string, unknown>[];+ /** X-axis data key */+ xKey: string;+ /** X scale */+ xScale: ChartScale;+ /** Y scale */+ yScale: ScaleLinear<number, number>;+ /** Resolved positions for all series */+ resolved: ResolvedPositions;+ /** Subscribe to pointer events */+ onPointer: (handler: (e: ChartPointerEvent) => void) => () => void;+ /** SVG ref for coordinate transforms */+ svgRef: React.RefObject<SVGSVGElement | null>;+}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 9ea4deb380..b927159394 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -187,3 +187,21 @@ export {type XDSSankeyGridProps,type SankeyContext,} from './Sankey';++// Chart v2 — config model+export {+ XDSChart as XDSChartV2,+ type XDSChartProps as XDSChartV2Props,+ bar,+ line,+ dot,+ area,+ band,+ candlestick,+ useChartV2,+ type SeriesConfig,+ type ChartV2Context,+ type ChartPointerEvent,+ type ResolvedPoint,+ type ResolvedPositions,+} from './ChartV2';