Skip to content

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

TypeScript

refactor(charts): self-contained mark types (#1697)

Cindy Zhange141892341f3
diff --git a/packages/lab/src/ChartV2/ChartV2Context.ts b/packages/lab/src/ChartV2/ChartV2Context.ts
index 6455fdb767..2781c3fba1 100644
--- a/packages/lab/src/ChartV2/ChartV2Context.ts
+++ b/packages/lab/src/ChartV2/ChartV2Context.ts
@@ -1,14 +1,7 @@
-/**
- * @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 {
diff --git a/packages/lab/src/ChartV2/XDSChart.tsx b/packages/lab/src/ChartV2/XDSChart.tsx
index 6951aad42c..ec89e4c66b 100644
--- a/packages/lab/src/ChartV2/XDSChart.tsx
+++ b/packages/lab/src/ChartV2/XDSChart.tsx
@@ -1,15 +1,12 @@
/**
* @file XDSChart.tsx (v2)
- * @output Root chart component — coordinates layout, rendering, and events
- * @position Top-level component; delegates to series renderers and interaction slots
+ * @output Root chart — coordinates layout, rendering, and events
+ * @position Top-level; delegates everything to series configs 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
+ * The chart root has ZERO knowledge of mark types. It:
+ * 1. Runs the layout engine (scales + stacking + grouping)
+ * 2. Calls each series' resolve() and render() methods
+ * 3. Provides a single event layer for interaction children
*/
import {
@@ -20,58 +17,36 @@ import {
useCallback,
useLayoutEffect,
} from 'react';
-import type {SeriesConfig} from './series';
+import type {SeriesDef} from './types';
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 */
+ series: SeriesDef[];
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,
+ 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(),
- );
+ const pointerHandlers = useRef<Set<(e: ChartPointerEvent) => void>>(new Set());
- // ─── Responsive width ─────────────────────────────────────────────────
useLayoutEffect(() => {
if (!containerRef.current) return;
const observer = new ResizeObserver(entries => {
@@ -82,116 +57,75 @@ export function XDSChart({
return () => observer.disconnect();
}, []);
- const margin = useMemo(
- () => ({...DEFAULT_MARGIN, ...marginOverride}),
- [marginOverride],
- );
+ 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,
- }),
+ () => computeLayout({data, xKey, series, width: innerWidth, height: innerHeight}),
[data, xKey, series, innerWidth, innerHeight],
);
+ const seriesCtx = useMemo(() => ({
+ data, xKey, xScale: layout.xScale, yScale: layout.yScale,
+ width: innerWidth, height: innerHeight,
+ }), [data, xKey, layout, innerWidth, innerHeight]);
+
// ─── Event dispatch ───────────────────────────────────────────────────
const onPointer = useCallback((handler: (e: ChartPointerEvent) => void) => {
pointerHandlers.current.add(handler);
- return () => {
- pointerHandlers.current.delete(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};
- }
+ 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);
+
+ let nearest: ChartPointerEvent['nearest'] = null;
+ let bestDist = 40 * 40;
+ 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],
- );
+ }
+ 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],
- );
+ // ─── Context for interactions + v1 chrome ─────────────────────────────
+ 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 v1 context for XDSChartGrid/Axis compatibility
+ const v1Ctx = useMemo(() => ({
+ width: innerWidth, height: innerHeight, margin, xKey, data,
+ xScale: layout.xScale, yScale: layout.yScale, svgRef,
+ pointerToData: () => ({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) {
@@ -204,34 +138,31 @@ export function XDSChart({
<ChartProvider value={v1Ctx}>
<svg ref={svgRef} width={containerWidth} height={height}>
<g transform={`translate(${margin.left},${margin.top})`}>
- {/* 1. Grid (background) */}
+ {/* 1. Grid */}
{grid}
- {/* 2. Marks (data layer) — each series renders itself */}
- {renderSeries(series, layout, data, xKey)}
+ {/* 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 (frame) */}
+ {/* 3. Axes */}
{axes}
- {/* 4. Event capture rect + interactions (overlay) */}
- <rect
- x={0}
- y={0}
- width={innerWidth}
- height={innerHeight}
+ {/* 4. Event capture + interactions */}
+ <rect x={0} y={0} width={innerWidth} height={innerHeight}
fill="transparent"
onPointerMove={handlePointerMove}
- onPointerLeave={handlePointerLeave}
- />
+ onPointerLeave={handlePointerLeave} />
{interactions}
{/* 5. Escape hatch */}
{children}
</g>
</svg>
-
- {/* 6. Legend (outside SVG if needed) */}
- {legend === true ? null /* TODO: auto legend */ : legend}
+ {legend === true ? null : legend}
</ChartProvider>
</ChartV2Provider>
</div>
diff --git a/packages/lab/src/ChartV2/index.ts b/packages/lab/src/ChartV2/index.ts
index 7b3b87ab4b..a30944f44a 100644
--- a/packages/lab/src/ChartV2/index.ts
+++ b/packages/lab/src/ChartV2/index.ts
@@ -1,6 +1,5 @@
-// 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 {bar, line, dot, area, band, candlestick} from './marks';
+export type {BarOptions, LineOptions, DotOptions, AreaOptions, BandOptions, CandlestickOptions} from './marks';
export {useChartV2} from './ChartV2Context';
-export type {ChartV2Context, ChartPointerEvent, ResolvedPoint, ResolvedPositions} from './types';
+export type {SeriesDef, ChartV2Context, ChartPointerEvent, ResolvedPoint, ResolvedPositions, SeriesContext} from './types';
diff --git a/packages/lab/src/ChartV2/layout.ts b/packages/lab/src/ChartV2/layout.ts
index ee091b9939..eac7d6ade1 100644
--- a/packages/lab/src/ChartV2/layout.ts
+++ b/packages/lab/src/ChartV2/layout.ts
@@ -1,25 +1,21 @@
/**
* @file layout.ts
- * @output Computes scales, layout transforms, and resolved positions from data + series
+ * @output Computes scales, stacking, grouping, then delegates to each series.resolve()
* @position Called by XDSChart root — the single layout pass
*
- * Pipeline: data + series → scales → transforms (stack, group, dodge) → resolvedPositions
+ * The layout engine does NOT know about specific mark types.
+ * It handles cross-series coordination (scales, stacking, grouping)
+ * then calls each series' own resolve() method.
*/
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';
+import type {SeriesDef, ChartScale, ResolvedPoint, SeriesContext} from './types';
export interface LayoutInput {
data: Record<string, unknown>[];
xKey: string;
- series: SeriesConfig[];
+ series: SeriesDef[];
width: number;
height: number;
}
@@ -27,46 +23,33 @@ export interface LayoutInput {
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}>;
+ resolved: Map<string, ResolvedPoint[]>;
}
-export function computeLayout({
- data,
- xKey,
- series,
- width,
- height,
-}: LayoutInput): LayoutResult {
- // ─── 1. Determine x scale ────────────────────────────────────────────
+export function computeLayout({data, xKey, series, width, height}: LayoutInput): LayoutResult {
+ // ─── 1. X scale ──────────────────────────────────────────────────────
const xValues = data.map(d => d[xKey]);
- const isNumericX =
- xValues.length > 0 && xValues.every(v => typeof v === 'number');
+ 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();
+ xScale = scaleLinear().domain([Math.min(...nums), Math.max(...nums)]).range([0, width]).nice();
} else {
- xScale = scaleBand<string>()
- .domain(xValues.map(String))
- .range([0, width])
- .padding(0.2);
+ 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>();
+ // ─── 2. Y domain from all series dataKeys ────────────────────────────
+ const allKeys = new Set<string>();
+ let includeZero = false;
for (const s of series) {
- for (const k of s.keys) allYKeys.add(k);
+ for (const k of s.dataKeys) allKeys.add(k);
+ if (s.layout.includeZero) includeZero = true;
}
- let yMin = Infinity;
- let yMax = -Infinity;
+ let yMin = Infinity, yMax = -Infinity;
for (const d of data) {
- for (const k of allYKeys) {
+ for (const k of allKeys) {
const v = d[k];
if (typeof v === 'number') {
if (v < yMin) yMin = v;
@@ -74,175 +57,60 @@ export function computeLayout({
}
}
}
- // Include zero for bar charts
- if (series.some(s => s.type === 'bar' || s.type === 'area')) {
+ if (includeZero) {
if (yMin > 0) yMin = 0;
if (yMax < 0) yMax = 0;
}
-
const yScale = scaleLinear().domain([yMin, yMax]).range([height, 0]).nice();
- // ─── 3. Compute stacking ─────────────────────────────────────────────
+ // ─── 3. 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);
+ if (s.layout.stack) {
+ const group = stackGroups.get(s.layout.stack) ?? [];
+ group.push(s.dataKeys[0]);
+ stackGroups.set(s.layout.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);
+ .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]})),
- );
+ 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[]>();
+ // ─── 4. Bar grouping ─────────────────────────────────────────────────
+ const barGroups = 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});
+ if (s.type === 'bar' && s.layout.group && !s.layout.stack) {
+ const group = barGroups.get(s.layout.group) ?? [];
+ group.push(s.key);
+ barGroups.set(s.layout.group, group);
}
}
- // ─── 5. Resolve positions for every series ────────────────────────────
- const resolved: ResolvedPositions = new Map();
+ // ─── 5. Resolve each series ──────────────────────────────────────────
+ const ctx: SeriesContext = {data, xKey, xScale, yScale, width, height};
+ const resolved = new Map<string, ResolvedPoint[]>();
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;
- }
+ const stackOffsets = stackedData.get(s.dataKeys[0]);
- 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;
+ let groupInfo: {index: number; count: number} | undefined;
+ if (s.layout.group) {
+ const groupKeys = barGroups.get(s.layout.group);
+ if (groupKeys) {
+ groupInfo = {index: groupKeys.indexOf(s.key), count: groupKeys.length};
}
}
- // 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);
+ const points = s.resolve(ctx, stackOffsets, groupInfo);
+ resolved.set(s.key, points);
}
- return {xScale, yScale, resolved, barGroups};
+ return {xScale, yScale, resolved};
}
diff --git a/packages/lab/src/ChartV2/marks/area.tsx b/packages/lab/src/ChartV2/marks/area.tsx
new file mode 100644
index 0000000000..a48eb9caf7
--- /dev/null
+++ b/packages/lab/src/ChartV2/marks/area.tsx
@@ -0,0 +1,91 @@
+/**
+ * @file marks/area.tsx
+ * @output Area series — fill under line with stacking + gradient support
+ */
+
+import {area as d3Area, curveLinear, curveMonotoneX, curveNatural, curveStep} from 'd3-shape';
+import {line as d3Line} from 'd3-shape';
+import type {SeriesDef, ResolvedPoint} from '../types';
+import type {ScaleBand} from 'd3-scale';
+
+const CURVES = {linear: curveLinear, monotone: curveMonotoneX, natural: curveNatural, step: curveStep} as const;
+
+export interface AreaOptions {
+ color?: string;
+ opacity?: number;
+ curve?: keyof typeof CURVES;
+ stack?: string;
+ gradient?: boolean;
+ stroke?: boolean;
+}
+
+export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {
+ const color = options.color ?? 'var(--color-chart-1)';
+ const opacity = options.opacity ?? 0.3;
+ const curve = options.curve ?? 'monotone';
+ const gradient = options.gradient ?? false;
+ const stroke = options.stroke ?? true;
+
+ return {
+ type: 'area',
+ key: dataKey,
+ dataKeys: [dataKey],
+ layout: {stack: options.stack, includeZero: true},
+
+ resolve(ctx, stackOffsets) {
+ const {data, xKey, xScale, yScale} = ctx;
+ const points: ResolvedPoint[] = [];
+ for (let i = 0; i < data.length; i++) {
+ const d = data[i];
+ let px: number;
+ if ('bandwidth' in xScale) {
+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ } else {
+ px = xScale(d[xKey] as number);
+ }
+ let py: number, py0: number;
+ if (stackOffsets) {
+ py = yScale(stackOffsets[i].y1);
+ py0 = yScale(stackOffsets[i].y0);
+ } else {
+ const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;
+ py = yScale(v);
+ py0 = yScale(0);
+ }
+ points.push({px, py, py0, dataIndex: i});
+ }
+ return points;
+ },
+
+ render(resolved) {
+ if (resolved.length === 0) return null;
+ const curveFactory = CURVES[curve];
+
+ const areaGen = d3Area<ResolvedPoint>()
+ .x(d => d.px).y0(d => d.py0).y1(d => d.py).curve(curveFactory);
+ const pathD = areaGen(resolved) ?? '';
+
+ const lineGen = d3Line<ResolvedPoint>()
+ .x(d => d.px).y(d => d.py).curve(curveFactory);
+ const strokeD = lineGen(resolved) ?? '';
+
+ const gradientId = `area-grad-${dataKey}`;
+
+ return (
+ <g>
+ {gradient && (
+ <defs>
+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor={color} stopOpacity={opacity} />
+ <stop offset="100%" stopColor={color} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ )}
+ <path d={pathD} fill={gradient ? `url(#${gradientId})` : color}
+ fillOpacity={gradient ? 1 : opacity} stroke="none" />
+ {stroke && <path d={strokeD} fill="none" stroke={color} strokeWidth={2} />}
+ </g>
+ );
+ },
+ };
+}
diff --git a/packages/lab/src/ChartV2/marks/band.tsx b/packages/lab/src/ChartV2/marks/band.tsx
new file mode 100644
index 0000000000..39f7383dd9
--- /dev/null
+++ b/packages/lab/src/ChartV2/marks/band.tsx
@@ -0,0 +1,53 @@
+/**
+ * @file marks/band.tsx
+ * @output Band (confidence interval) series
+ */
+
+import {area as d3Area, curveMonotoneX} from 'd3-shape';
+import type {SeriesDef, ResolvedPoint} from '../types';
+import type {ScaleBand} from 'd3-scale';
+
+export interface BandOptions {
+ upper: string;
+ lower: string;
+ color?: string;
+ opacity?: number;
+}
+
+export function band(options: BandOptions): SeriesDef {
+ const color = options.color ?? 'var(--color-chart-1)';
+ const opacity = options.opacity ?? 0.15;
+
+ return {
+ type: 'band',
+ key: `band-${options.upper}-${options.lower}`,
+ dataKeys: [options.upper, options.lower],
+ layout: {},
+
+ resolve(ctx) {
+ const {data, xKey, xScale, yScale} = ctx;
+ const points: ResolvedPoint[] = [];
+ for (let i = 0; i < data.length; i++) {
+ const d = data[i];
+ let px: number;
+ if ('bandwidth' in xScale) {
+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ } else {
+ px = xScale(d[xKey] as number);
+ }
+ const upper = typeof d[options.upper] === 'number' ? (d[options.upper] as number) : 0;
+ const lower = typeof d[options.lower] === 'number' ? (d[options.lower] as number) : 0;
+ points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});
+ }
+ return points;
+ },
+
+ render(resolved) {
+ if (resolved.length === 0) return null;
+ const areaGen = d3Area<ResolvedPoint>()
+ .x(d => d.px).y0(d => d.py0).y1(d => d.py).curve(curveMonotoneX);
+ const pathD = areaGen(resolved) ?? '';
+ return <path d={pathD} fill={color} fillOpacity={opacity} stroke="none" />;
+ },
+ };
+}
diff --git a/packages/lab/src/ChartV2/marks/bar.tsx b/packages/lab/src/ChartV2/marks/bar.tsx
new file mode 100644
index 0000000000..454e344c08
--- /dev/null
+++ b/packages/lab/src/ChartV2/marks/bar.tsx
@@ -0,0 +1,96 @@
+/**
+ * @file marks/bar.ts
+ * @output Bar series — self-contained resolve + render
+ * @position Standalone mark; chart root calls resolve() then render()
+ */
+
+import type {SeriesDef, SeriesContext, ResolvedPoint} from '../types';
+import type {ScaleBand} from 'd3-scale';
+
+export type ColorAccessor = string | ((datum: Record<string, unknown>, index: number) => string);
+
+export interface BarOptions {
+ color?: ColorAccessor;
+ opacity?: number;
+ radius?: number;
+ stack?: string;
+ group?: string;
+}
+
+export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {
+ const color = options.color ?? 'var(--color-chart-1)';
+ const opacity = options.opacity ?? 1;
+ const radius = options.radius ?? 4;
+
+ // Shared between resolve and render via closure
+ let barWidth = 0;
+ let barOffset = 0;
+
+ return {
+ type: 'bar',
+ key: dataKey,
+ dataKeys: [dataKey],
+ layout: {
+ stack: options.stack,
+ group: options.group,
+ includeZero: true,
+ },
+
+ resolve(ctx, stackOffsets, groupInfo) {
+ const {data, xKey, xScale, yScale} = ctx;
+ if (!('bandwidth' in xScale)) return [];
+
+ const bandScale = xScale as ScaleBand<string>;
+ const bw = bandScale.bandwidth();
+ barWidth = groupInfo ? bw / groupInfo.count : bw;
+ barOffset = groupInfo ? groupInfo.index * barWidth : 0;
+
+ const points: ResolvedPoint[] = [];
+ for (let i = 0; i < data.length; i++) {
+ const d = data[i];
+ const xBase = bandScale(String(d[xKey])) ?? 0;
+ const px = xBase + barOffset + barWidth / 2;
+
+ let py: number;
+ let py0: number;
+ if (stackOffsets) {
+ py = yScale(stackOffsets[i].y1);
+ py0 = yScale(stackOffsets[i].y0);
+ } else {
+ const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;
+ py = yScale(v);
+ py0 = yScale(0);
+ }
+ points.push({px, py, py0, dataIndex: i});
+ }
+ return points;
+ },
+
+ render(resolved, ctx) {
+ const {data} = ctx;
+ return (
+ <g opacity={opacity}>
+ {resolved.map((p, i) => {
+ const d = data[p.dataIndex];
+ const fill = typeof color === 'function' ? color(d, p.dataIndex) : color;
+ const barY = Math.min(p.py, p.py0);
+ const barHeight = Math.abs(p.py0 - p.py);
+
+ return (
+ <rect
+ key={i}
+ x={p.px - barWidth / 2}
+ y={barY}
+ width={barWidth}
+ height={Math.max(0, barHeight)}
+ fill={fill}
+ rx={radius}
+ ry={radius}
+ />
+ );
+ })}
+ </g>
+ );
+ },
+ };
+}
diff --git a/packages/lab/src/ChartV2/marks/candlestick.tsx b/packages/lab/src/ChartV2/marks/candlestick.tsx
new file mode 100644
index 0000000000..a5a507e4b4
--- /dev/null
+++ b/packages/lab/src/ChartV2/marks/candlestick.tsx
@@ -0,0 +1,69 @@
+/**
+ * @file marks/candlestick.tsx
+ * @output Candlestick (OHLC) series
+ */
+
+import type {SeriesDef, ResolvedPoint} from '../types';
+import type {ScaleBand} from 'd3-scale';
+
+export interface CandlestickOptions {
+ open: string; high: string; low: string; close: string;
+ upColor?: string; downColor?: string;
+}
+
+export function candlestick(options: CandlestickOptions): SeriesDef {
+ const upColor = options.upColor ?? 'var(--color-positive)';
+ const downColor = options.downColor ?? 'var(--color-negative)';
+
+ return {
+ type: 'candlestick',
+ key: `ohlc-${options.close}`,
+ dataKeys: [options.open, options.high, options.low, options.close],
+ layout: {},
+
+ resolve(ctx) {
+ const {data, xKey, xScale, yScale} = ctx;
+ const points: ResolvedPoint[] = [];
+ for (let i = 0; i < data.length; i++) {
+ const d = data[i];
+ let px: number;
+ if ('bandwidth' in xScale) {
+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ } else {
+ px = xScale(d[xKey] as number);
+ }
+ const close = typeof d[options.close] === 'number' ? (d[options.close] as number) : 0;
+ points.push({px, py: yScale(close), py0: yScale(0), dataIndex: i});
+ }
+ return points;
+ },
+
+ render(resolved, ctx) {
+ const {data, xKey, xScale, yScale} = ctx;
+ if (!('bandwidth' in xScale)) return null;
+ const bw = (xScale as ScaleBand<string>).bandwidth();
+ const bodyWidth = bw * 0.6;
+
+ return (
+ <g>
+ {resolved.map((p, i) => {
+ const d = data[p.dataIndex];
+ const o = typeof d[options.open] === 'number' ? (d[options.open] as number) : 0;
+ const c = typeof d[options.close] === 'number' ? (d[options.close] as number) : 0;
+ const h = typeof d[options.high] === 'number' ? (d[options.high] as number) : 0;
+ const l = typeof d[options.low] === 'number' ? (d[options.low] as number) : 0;
+ const isUp = c >= o;
+ const col = isUp ? upColor : downColor;
+ return (
+ <g key={i}>
+ <line x1={p.px} x2={p.px} y1={yScale(h)} y2={yScale(l)} stroke={col} strokeWidth={1} />
+ <rect x={p.px - bodyWidth / 2} y={yScale(Math.max(o, c))}
+ width={bodyWidth} height={Math.max(1, Math.abs(yScale(o) - yScale(c)))} fill={col} />
+ </g>
+ );
+ })}
+ </g>
+ );
+ },
+ };
+}
diff --git a/packages/lab/src/ChartV2/marks/dot.tsx b/packages/lab/src/ChartV2/marks/dot.tsx
new file mode 100644
index 0000000000..b79aaea154
--- /dev/null
+++ b/packages/lab/src/ChartV2/marks/dot.tsx
@@ -0,0 +1,59 @@
+/**
+ * @file marks/dot.tsx
+ * @output Dot/scatter series — self-contained resolve + render
+ */
+
+import type {SeriesDef, ResolvedPoint} from '../types';
+import type {ScaleBand} from 'd3-scale';
+
+export type ColorAccessor = string | ((datum: Record<string, unknown>, index: number) => string);
+
+export interface DotOptions {
+ color?: ColorAccessor;
+ radius?: number;
+ opacity?: number;
+ dodge?: boolean;
+}
+
+export function dot(dataKey: string, options: DotOptions = {}): SeriesDef {
+ const color = options.color ?? 'var(--color-chart-1)';
+ const radius = options.radius ?? 4;
+ const opacity = options.opacity ?? 0.8;
+
+ return {
+ type: 'dot',
+ key: dataKey,
+ dataKeys: [dataKey],
+ layout: {},
+
+ resolve(ctx) {
+ const {data, xKey, xScale, yScale} = ctx;
+ const points: ResolvedPoint[] = [];
+ for (let i = 0; i < data.length; i++) {
+ const d = data[i];
+ let px: number;
+ if ('bandwidth' in xScale) {
+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ } else {
+ px = xScale(d[xKey] as number);
+ }
+ const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;
+ points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});
+ }
+ // TODO: dodge layout runs here — has access to radius + all points
+ return points;
+ },
+
+ render(resolved, ctx) {
+ const {data} = ctx;
+ return (
+ <g>
+ {resolved.map((p, i) => {
+ const fill = typeof color === 'function' ? color(data[p.dataIndex], p.dataIndex) : color;
+ return <circle key={i} cx={p.px} cy={p.py} r={radius} fill={fill} opacity={opacity} />;
+ })}
+ </g>
+ );
+ },
+ };
+}
diff --git a/packages/lab/src/ChartV2/marks/index.ts b/packages/lab/src/ChartV2/marks/index.ts
new file mode 100644
index 0000000000..252f47bfd3
--- /dev/null
+++ b/packages/lab/src/ChartV2/marks/index.ts
@@ -0,0 +1,6 @@
+export {bar, type BarOptions} from './bar';
+export {line, type LineOptions} from './line';
+export {dot, type DotOptions} from './dot';
+export {area, type AreaOptions} from './area';
+export {band, type BandOptions} from './band';
+export {candlestick, type CandlestickOptions} from './candlestick';
diff --git a/packages/lab/src/ChartV2/marks/line.tsx b/packages/lab/src/ChartV2/marks/line.tsx
new file mode 100644
index 0000000000..1ff0a45986
--- /dev/null
+++ b/packages/lab/src/ChartV2/marks/line.tsx
@@ -0,0 +1,68 @@
+/**
+ * @file marks/line.tsx
+ * @output Line series — self-contained resolve + render
+ */
+
+import {line as d3Line, curveLinear, curveMonotoneX, curveNatural, curveStep} from 'd3-shape';
+import type {SeriesDef, SeriesContext, ResolvedPoint} from '../types';
+import type {ScaleBand} from 'd3-scale';
+
+const CURVES = {linear: curveLinear, monotone: curveMonotoneX, natural: curveNatural, step: curveStep} as const;
+export type CurveType = keyof typeof CURVES;
+
+export interface LineOptions {
+ color?: string;
+ curve?: CurveType;
+ strokeWidth?: number;
+ dots?: boolean;
+}
+
+export function line(dataKey: string, options: LineOptions = {}): SeriesDef {
+ const color = options.color ?? 'var(--color-chart-1)';
+ const curve = options.curve ?? 'monotone';
+ const strokeWidth = options.strokeWidth ?? 2;
+ const dots = options.dots ?? false;
+
+ return {
+ type: 'line',
+ key: dataKey,
+ dataKeys: [dataKey],
+ layout: {},
+
+ resolve(ctx) {
+ const {data, xKey, xScale, yScale} = ctx;
+ const points: ResolvedPoint[] = [];
+ for (let i = 0; i < data.length; i++) {
+ const d = data[i];
+ let px: number;
+ if ('bandwidth' in xScale) {
+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ } else {
+ px = xScale(d[xKey] as number);
+ }
+ const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;
+ points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});
+ }
+ return points;
+ },
+
+ render(resolved) {
+ if (resolved.length === 0) return null;
+ const curveFactory = CURVES[curve];
+ const pathGen = d3Line<ResolvedPoint>()
+ .x(d => d.px)
+ .y(d => d.py)
+ .curve(curveFactory);
+
+ const pathD = pathGen(resolved) ?? '';
+ return (
+ <g>
+ <path d={pathD} fill="none" stroke={color} strokeWidth={strokeWidth} />
+ {dots && resolved.map((p, i) => (
+ <circle key={i} cx={p.px} cy={p.py} r={3} fill={color} />
+ ))}
+ </g>
+ );
+ },
+ };
+}
diff --git a/packages/lab/src/ChartV2/renderers.tsx b/packages/lab/src/ChartV2/renderers.tsx
deleted file mode 100644
index 7ca5654f4a..0000000000
--- a/packages/lab/src/ChartV2/renderers.tsx
+++ /dev/null
@@ -1,412 +0,0 @@
-/**
- * @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.ts
deleted file mode 100644
index efe9cf9e2e..0000000000
--- a/packages/lab/src/ChartV2/series.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-/**
- * @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.ts
index 8b79337d87..98bd1956ed 100644
--- a/packages/lab/src/ChartV2/types.ts
+++ b/packages/lab/src/ChartV2/types.ts
@@ -4,6 +4,7 @@
* @position Foundation — consumed by layout, renderers, and interactions
*/
+import type {ReactNode} from 'react';
import type {ScaleLinear, ScaleBand} from 'd3-scale';
export type ChartScale = ScaleLinear<number, number> | ScaleBand<string>;
@@ -21,46 +22,87 @@ export interface ResolvedPoint {
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 */
+ /** Pixel y baseline (bottom of mark) — differs from py when stacked */
py0: number;
/** Index into the data array */
dataIndex: number;
}
-/** Resolved positions for all series — the single source of truth */
+/** Context passed to resolve() and render() on each series */
+export interface SeriesContext {
+ data: Record<string, unknown>[];
+ xKey: string;
+ xScale: ChartScale;
+ yScale: ScaleLinear<number, number>;
+ /** Width of the plot area */
+ width: number;
+ /** Height of the plot area */
+ height: number;
+}
+
+/**
+ * The standardized shape every mark helper returns.
+ * Each mark type is self-contained: it knows how to resolve positions
+ * and how to render itself. The chart root just iterates and calls.
+ */
+export interface SeriesDef {
+ /** Mark type identifier */
+ readonly type: string;
+ /** Unique key for this series (typically the dataKey) */
+ readonly key: string;
+ /** Data keys this series reads from — used to compute y domain */
+ readonly dataKeys: string[];
+ /** Layout hints the chart root uses for cross-series coordination */
+ readonly layout: {
+ /** Stack group — series with same stack accumulate */
+ stack?: string;
+ /** Bar group — series with same group subdivide bandwidth */
+ group?: string;
+ /** Whether this series contributes to y-domain zero inclusion */
+ includeZero?: boolean;
+ };
+ /**
+ * Resolve pixel positions for each data point.
+ * Called by the chart root during the layout pass.
+ * Receives pre-computed stack offsets if stacked.
+ */
+ resolve(
+ ctx: SeriesContext,
+ stackOffsets?: {y0: number; y1: number}[],
+ groupInfo?: {index: number; count: number},
+ ): ResolvedPoint[];
+ /**
+ * Render the mark given resolved positions.
+ * Called by the chart root during the render pass.
+ * Returns SVG elements (or manages its own canvas for WebGL).
+ */
+ render(
+ resolved: ResolvedPoint[],
+ ctx: SeriesContext,
+ ): ReactNode;
+}
+
+/** Resolved positions for all series */
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 */
+ resolved: Map<string, ResolvedPoint[]>;
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.ts
index b927159394..7664bb3a47 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -199,9 +199,10 @@ export {
band,
candlestick,
useChartV2,
- type SeriesConfig,
+ type SeriesDef,
type ChartV2Context,
type ChartPointerEvent,
type ResolvedPoint,
type ResolvedPositions,
+ type SeriesContext,
} from './ChartV2';