Skip to content

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

TypeScript

feat(ChartV2): introduce v2 axis + grid with composable styling (#2287)

Marie Lucasa7f350d64262
diff --git a/apps/storybook/stories/ChartV2.stories.tsx b/apps/storybook/stories/ChartV2.stories.tsx
index 9188e78b67..7483bfc84c 100644
--- a/apps/storybook/stories/ChartV2.stories.tsx
+++ b/apps/storybook/stories/ChartV2.stories.tsx
@@ -2,7 +2,11 @@
import type {Meta, StoryObj} from '@storybook/react';
import {XDSChartV2 as XDSChart, bar, line, area} from '@xds/lab';
-import {XDSChartGrid, XDSChartAxis, currency} from '@xds/lab';
+import {
+ XDSChartV2Grid as XDSChartGrid,
+ XDSChartV2Axis as XDSChartAxis,
+ currency,
+} from '@xds/lab';
const meta: Meta<typeof XDSChart> = {
title: 'Lab/ChartV2',
@@ -37,7 +41,7 @@ export const SimpleBar: StoryObj = {
title="Monthly Revenue"
series={[bar('revenue', {color: '#3b82f6'})]}
tooltip={true}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -49,6 +53,26 @@ export const SimpleBar: StoryObj = {
),
};
+/** Simple line chart */
+export const SimpleLine: StoryObj = {
+ render: () => (
+ <XDSChart
+ data={monthlyData}
+ xKey="month"
+ series={[line('trend', {color: '#3b82f6'})]}
+ tooltip={true}
+ grid={<XDSChartGrid />}
+ axes={
+ <>
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ </>
+ }
+ height={300}
+ />
+ ),
+};
+
/** Stacked bars */
export const StackedBars: StoryObj = {
render: () => (
@@ -62,7 +86,7 @@ export const StackedBars: StoryObj = {
bar('costs', {color: '#ef4444', stack: 'totals', label: 'Costs'}),
]}
legend={{position: 'bottom', alignment: 'center'}}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -86,7 +110,7 @@ export const GroupedBars: StoryObj = {
bar('costs', {color: '#ef4444', group: 'compare', label: 'Costs'}),
]}
legend={{position: 'top', alignment: 'end'}}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -120,7 +144,7 @@ export const GroupedStackedBars: StoryObj = {
}),
bar('costsB', {color: '#fca5a5', stack: 'stackB', group: 'comparison'}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -146,7 +170,7 @@ export const MixedMarks: StoryObj = {
]}
tooltip={true}
legend={{position: 'end', alignment: 'start'}}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -169,7 +193,7 @@ export const AreaGradient: StoryObj = {
area('revenue', {color: '#3b82f6', gradient: true}),
line('revenue', {color: '#3b82f6'}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -193,7 +217,7 @@ export const StackedAreas: StoryObj = {
area('costs', {color: '#ef4444', stack: 'total', label: 'Costs'}),
]}
legend={true}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -224,7 +248,7 @@ export const NegativeValues: StoryObj = {
bar('profit', {color: '#3b82f6'}),
line('trend', {color: '#f59e0b', dots: true, strokeWidth: 2}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
diff --git a/apps/storybook/stories/ChartV2Advanced.stories.tsx b/apps/storybook/stories/ChartV2Advanced.stories.tsx
index d91575ff50..fb3fe62fcb 100644
--- a/apps/storybook/stories/ChartV2Advanced.stories.tsx
+++ b/apps/storybook/stories/ChartV2Advanced.stories.tsx
@@ -15,7 +15,10 @@ import {
streamGL,
type StreamGLHandle,
} from '@xds/lab';
-import {XDSChartGrid, XDSChartAxis} from '@xds/lab';
+import {
+ XDSChartV2Grid as XDSChartGrid,
+ XDSChartV2Axis as XDSChartAxis,
+} from '@xds/lab';
const meta: Meta<typeof XDSChart> = {
title: 'Lab/ChartV2Advanced',
@@ -102,7 +105,7 @@ export const Candlestick: StoryObj = {
downColor: '#ef4444',
}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -154,7 +157,7 @@ export const FinancialComposite: StoryObj = {
line('ma5', {color: '#f59e0b', strokeWidth: 1.5}),
bar('volume', {color: '#94a3b8', opacity: 0.3}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -188,7 +191,7 @@ export const ConfidenceBands: StoryObj = {
}),
line('mean', {color: '#3b82f6', strokeWidth: 2}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -219,7 +222,7 @@ export const ErrorBarsWithTarget: StoryObj = {
bandOpacity: 0.1,
}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -301,7 +304,7 @@ export const StreamingLine: StoryObj = {
data={[]}
xKey="x"
series={[streamGL({handleRef, color: '#3b82f6'})]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
@@ -352,7 +355,7 @@ export const KitchenSink: StoryObj = {
errorBar({high: 'errorHigh', low: 'errorLow', color: '#1e3a5f'}),
line('runAvg', {color: '#f59e0b', strokeWidth: 2}),
]}
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
diff --git a/apps/storybook/stories/ChartV2Grid.stories.tsx b/apps/storybook/stories/ChartV2Grid.stories.tsx
new file mode 100644
index 0000000000..9c1c56d069
--- /dev/null
+++ b/apps/storybook/stories/ChartV2Grid.stories.tsx
@@ -0,0 +1,90 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSChartV2 as XDSChart, bar} from '@xds/lab';
+import {
+ XDSChartV2Grid as XDSChartGrid,
+ XDSChartV2Axis as XDSChartAxis,
+} from '@xds/lab';
+
+interface AxesAndGridsArgs {
+ /** Show horizontal grid lines */
+ horizontalGrid: boolean;
+ /** Show vertical grid lines */
+ verticalGrid: boolean;
+ /** Show the bottom (x) axis edge line */
+ bottomAxisLine: boolean;
+ /** Show the left (y) axis edge line */
+ leftAxisLine: boolean;
+ /** Show perpendicular tick marks on both axes */
+ showTicks: boolean;
+}
+
+const meta: Meta<AxesAndGridsArgs> = {
+ title: 'Lab/XDSChart v2/Primitives/Axes & Grids',
+ argTypes: {
+ horizontalGrid: {control: 'boolean'},
+ verticalGrid: {control: 'boolean'},
+ bottomAxisLine: {control: 'boolean'},
+ leftAxisLine: {control: 'boolean'},
+ showTicks: {control: 'boolean'},
+ },
+ args: {
+ horizontalGrid: true,
+ verticalGrid: false,
+ bottomAxisLine: true,
+ leftAxisLine: false,
+ showTicks: false,
+ },
+};
+export default meta;
+
+const monthlyData = [
+ {month: 'Jan', revenue: 45},
+ {month: 'Feb', revenue: 52},
+ {month: 'Mar', revenue: 48},
+ {month: 'Apr', revenue: 61},
+ {month: 'May', revenue: 55},
+ {month: 'Jun', revenue: 70},
+];
+
+/**
+ * Toggle grid lines, axis edge lines, and tick marks independently.
+ *
+ * - Grid lines use `--color-border-emphasized`; the y=0 / domain axis line
+ * uses `--color-icon-primary`.
+ * - The bottom axis edge line is on by default; the left/top/right are off.
+ * - When showing vertical grid lines, enable `leftAxisLine` so the grid
+ * has a clear left edge to anchor against.
+ */
+export const AxesAndGrids: StoryObj<AxesAndGridsArgs> = {
+ name: 'Axes & Grids',
+ render: args => (
+ <XDSChart
+ data={monthlyData}
+ xKey="month"
+ series={[bar('revenue', {color: '#3b82f6'})]}
+ grid={
+ <XDSChartGrid
+ horizontal={args.horizontalGrid}
+ vertical={args.verticalGrid}
+ />
+ }
+ axes={
+ <>
+ <XDSChartAxis
+ position="bottom"
+ showAxisLine={args.bottomAxisLine}
+ showTicks={args.showTicks}
+ />
+ <XDSChartAxis
+ position="left"
+ showAxisLine={args.leftAxisLine}
+ showTicks={args.showTicks}
+ />
+ </>
+ }
+ height={300}
+ />
+ ),
+};
diff --git a/apps/storybook/stories/ChartV2Tooltip.stories.tsx b/apps/storybook/stories/ChartV2Tooltip.stories.tsx
index 6716561e09..311b647f0d 100644
--- a/apps/storybook/stories/ChartV2Tooltip.stories.tsx
+++ b/apps/storybook/stories/ChartV2Tooltip.stories.tsx
@@ -2,7 +2,11 @@
import type {Meta, StoryObj} from '@storybook/react';
import {XDSChartV2 as XDSChart, bar, line} from '@xds/lab';
-import {XDSChartGrid, XDSChartAxis, currency} from '@xds/lab';
+import {
+ XDSChartV2Grid as XDSChartGrid,
+ XDSChartV2Axis as XDSChartAxis,
+ currency,
+} from '@xds/lab';
const meta: Meta = {
title: 'Lab/ChartV2Tooltip',
@@ -32,7 +36,7 @@ export const Tooltip: StoryObj = {
xKey="month"
series={series}
tooltip
- grid={<XDSChartGrid horizontal />}
+ grid={<XDSChartGrid />}
axes={
<>
<XDSChartAxis position="bottom" />
diff --git a/packages/lab/src/ChartV2/XDSChartAxis.tsx b/packages/lab/src/ChartV2/XDSChartAxis.tsx
new file mode 100644
index 0000000000..4d2278cbdd
--- /dev/null
+++ b/packages/lab/src/ChartV2/XDSChartAxis.tsx
@@ -0,0 +1,207 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XDSChartAxis.tsx (v2)
+ * @output Renders an axis (top, right, bottom, left) using the chart's scales
+ * @position Child of XDSChart v2; reads scales from chart context
+ *
+ * The axis edge line and tick marks are independently toggleable so callers
+ * can compose: line-only, line + ticks, or line + ticks + grid (paired with
+ * `<XDSChartGrid>`). To stay consistent with most charts, the bottom axis
+ * draws its edge line by default and other positions don't.
+ *
+ * Ticks use CSS transitions for smooth sliding during streaming updates.
+ */
+
+import {useMemo} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {colorVars} from '@xds/core/theme/tokens.stylex';
+import {useChart} from '../Chart/ChartContext';
+import {isBandScale} from '../Chart/utils';
+import type {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;
+ /** Maximum number of tick labels to show. Labels are evenly skipped when exceeded. */
+ maxTicks?: number;
+ /** Custom tick formatter */
+ tickFormat?: (value: unknown) => string;
+ /** Truncate labels to this many characters (appends "\u2026"). */
+ truncate?: number;
+ /** Enable smooth transitions for streaming (default: true) */
+ animated?: boolean;
+ /**
+ * Show the axis edge line. Defaults to `true` for `position="bottom"`,
+ * `false` otherwise. Forced to `true` when `showTicks` is enabled.
+ * Pair with `<XDSChartGrid vertical />` and pass `showAxisLine` on the
+ * corresponding side axis to keep the visual edge grounded.
+ */
+ showAxisLine?: boolean;
+ /** Show perpendicular tick marks at each tick label. Default: `false`. */
+ showTicks?: boolean;
+}
+
+const styles = stylex.create({
+ axisLine: {
+ stroke: colorVars['--color-text-primary'],
+ strokeWidth: 1,
+ },
+ tickMark: {
+ stroke: colorVars['--color-text-primary'],
+ strokeWidth: 1,
+ },
+});
+
+const TICK_SIZE = 6;
+
+/**
+ * Chart axis. Always draws tick labels; the axis edge line and tick marks
+ * are independently toggleable. Pair with `<XDSChartGrid>` for grid lines.
+ *
+ * @example
+ * ```
+ * <XDSChartAxis position="bottom" /> // edge line + labels
+ * <XDSChartAxis position="left" /> // labels only (no edge line)
+ * <XDSChartAxis position="left" showAxisLine showTicks />
+ * ```
+ */
+export function XDSChartAxis({
+ position,
+ tickCount = 5,
+ maxTicks,
+ tickFormat,
+ truncate,
+ animated = true,
+ showAxisLine = position === 'bottom',
+ showTicks = false,
+}: XDSChartAxisProps) {
+ // Tick marks need an axis line to anchor against; force it on when ticks
+ // are enabled so the two visuals stay coherent.
+ const renderAxisLine = showAxisLine || showTicks;
+ const {width, height, xScale, yScale} = useChart();
+
+ const isHorizontal = position === 'top' || position === 'bottom';
+ const scale = isHorizontal ? xScale : yScale;
+
+ const ticks = useMemo(() => {
+ let allTicks: {value: unknown; offset: number}[];
+ if (isBandScale(scale)) {
+ allTicks = scale.domain().map(d => ({
+ value: d,
+ offset: (scale(d) ?? 0) + scale.bandwidth() / 2,
+ }));
+ } else {
+ const linearScale = scale as
+ | ScaleLinear<number, number>
+ | ScaleTime<number, number>;
+ allTicks = linearScale.ticks(tickCount).map(d => ({
+ value: d,
+ offset: linearScale(d as number & Date),
+ }));
+ }
+
+ // Auto-skip: show every Nth label if maxTicks is exceeded
+ if (maxTicks && allTicks.length > maxTicks) {
+ const step = Math.ceil(allTicks.length / maxTicks);
+ allTicks = allTicks.filter((_, i) => i % step === 0);
+ }
+
+ return allTicks;
+ }, [scale, tickCount, maxTicks]);
+
+ const transform =
+ position === 'bottom'
+ ? `translate(0,${height})`
+ : position === 'right'
+ ? `translate(${width},0)`
+ : undefined;
+
+ // For the bottom axis, draw the axis line at y=0 when the domain spans
+ // negative values (so the axis line still represents zero, not the chart edge).
+ const axisLineY = (() => {
+ if (position !== 'bottom') return 0;
+ const domain = yScale.domain();
+ if (domain[0] < 0 && domain[1] > 0) {
+ return yScale(0) - height;
+ }
+ return 0;
+ })();
+
+ const baseFormat = tickFormat ?? String;
+ const format = truncate
+ ? (value: unknown) => {
+ const str = baseFormat(value);
+ return str.length > truncate ? str.slice(0, truncate) + '\u2026' : str;
+ }
+ : baseFormat;
+
+ const tickTransition = animated
+ ? 'transform 150ms linear, opacity 150ms ease'
+ : undefined;
+
+ return (
+ <g transform={transform}>
+ {renderAxisLine && (
+ <line
+ x1={0}
+ x2={isHorizontal ? width : 0}
+ y1={isHorizontal ? axisLineY : 0}
+ y2={isHorizontal ? axisLineY : height}
+ {...stylex.props(styles.axisLine)}
+ />
+ )}
+ {ticks.map(({value, offset}) => {
+ const label = format(value);
+ const isVisible = isHorizontal
+ ? offset >= -10 && offset <= width + 10
+ : offset >= -10 && offset <= height + 10;
+
+ if (isHorizontal) {
+ const y = position === 'bottom' ? TICK_SIZE : -TICK_SIZE;
+ return (
+ <g
+ key={label}
+ style={{
+ transform: `translateX(${offset}px)`,
+ transition: tickTransition,
+ opacity: isVisible ? 1 : 0,
+ }}>
+ {showTicks && <line y2={y} {...stylex.props(styles.tickMark)} />}
+ <text
+ y={position === 'bottom' ? TICK_SIZE + 12 : -(TICK_SIZE + 4)}
+ textAnchor="middle"
+ fill="var(--color-text-secondary)"
+ fontSize={12}>
+ {label}
+ </text>
+ </g>
+ );
+ }
+ // Vertical axis
+ const x = position === 'left' ? -TICK_SIZE : TICK_SIZE;
+ return (
+ <g
+ key={label}
+ style={{
+ transform: `translateY(${offset}px)`,
+ transition: tickTransition,
+ opacity: isVisible ? 1 : 0,
+ }}>
+ {showTicks && <line x2={x} {...stylex.props(styles.tickMark)} />}
+ <text
+ x={position === 'left' ? -(TICK_SIZE + 4) : TICK_SIZE + 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/ChartV2/XDSChartGrid.tsx b/packages/lab/src/ChartV2/XDSChartGrid.tsx
new file mode 100644
index 0000000000..5e06c24247
--- /dev/null
+++ b/packages/lab/src/ChartV2/XDSChartGrid.tsx
@@ -0,0 +1,95 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XDSChartGrid.tsx (v2)
+ * @output Grid lines behind chart marks
+ * @position Child of XDSChart v2; reads scales from chart context
+ */
+
+import {useMemo} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {colorVars} from '@xds/core/theme/tokens.stylex';
+import {useChart} from '../Chart/ChartContext';
+import {isBandScale} from '../Chart/utils';
+import type {ScaleLinear, ScaleTime} from 'd3-scale';
+
+export interface XDSChartGridProps {
+ /** Show horizontal grid lines. Default: `true`. */
+ horizontal?: boolean;
+ /** Show vertical grid lines. Default: `false`. */
+ vertical?: boolean;
+}
+
+const styles = stylex.create({
+ gridLine: {
+ stroke: colorVars['--color-border-emphasized'],
+ strokeWidth: 1,
+ },
+});
+
+/**
+ * Grid lines behind chart marks.
+ *
+ * Pair with `<XDSChartAxis>` so users always see an axis line beside the
+ * grid — the components are designed to be used together.
+ *
+ * @example
+ * ```
+ * <XDSChartGrid /> // horizontal grid lines (default)
+ * <XDSChartGrid horizontal vertical />
+ * ```
+ */
+export function XDSChartGrid({
+ horizontal = true,
+ vertical = false,
+}: XDSChartGridProps) {
+ const {width, height, xScale, yScale} = useChart();
+
+ // Skip the y=0 line when emphasizing it via the axis. Without this we'd
+ // double-draw on top of the axis line.
+ const hLines = useMemo(() => {
+ if (!horizontal) return [];
+ return yScale
+ .ticks(5)
+ .filter(tick => tick !== 0)
+ .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}
+ {...stylex.props(styles.gridLine)}
+ />
+ ))}
+ {vLines.map(x => (
+ <line
+ key={`v-${x}`}
+ x1={x}
+ x2={x}
+ y1={0}
+ y2={height}
+ {...stylex.props(styles.gridLine)}
+ />
+ ))}
+ </g>
+ );
+}
diff --git a/packages/lab/src/ChartV2/XDSChartTooltip.tsx b/packages/lab/src/ChartV2/XDSChartTooltip.tsx
index 0a41a801a1..413758dcc0 100644
--- a/packages/lab/src/ChartV2/XDSChartTooltip.tsx
+++ b/packages/lab/src/ChartV2/XDSChartTooltip.tsx
@@ -17,7 +17,7 @@
*
* // Composable — drop into the chart's children for full control
* <XDSChart>
- * <XDSChartTooltip highlightBand={false} placement="top" />
+ * <XDSChartTooltip hoverIndicator={false} placement="top" />
* </XDSChart>
* ```
*/
@@ -35,9 +35,14 @@ import {
} from 'react';
import {createPortal} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ radiusVars,
+ shadowVars,
+ spacingVars,
+} from '@xds/core/theme/tokens.stylex';
import {XDSText} from '@xds/core';
import {XDSVStack, XDSHStack} from '@xds/core';
-import {radiusVars, spacingVars} from '@xds/core/theme/tokens.stylex';
import {useChartV2} from './ChartV2Context';
import {XDSChartSwatch, swatchVariantForType} from './XDSChartSwatch';
import {
@@ -63,10 +68,14 @@ export interface XDSChartTooltipProps {
*/
render?: (xValue: unknown, seriesValues: TooltipSeriesValue[]) => ReactNode;
/**
- * Whether to draw the soft column highlight behind the hovered band.
- * Only takes effect on band-scale x-axes. Default: `true`.
+ * Whether to draw a hover indicator at the focused x-position.
+ * Picks the right shape automatically:
+ * - **band-highlight rect** when the chart includes bar series on a band scale
+ * - **vertical crosshair line** for line / area / dot charts
+ *
+ * Default: `true`.
*/
- highlightBand?: boolean;
+ hoverIndicator?: boolean;
/**
* Whether to draw a hover dot at each series' point (skipped for bars).
* Default: `true`.
@@ -85,17 +94,21 @@ const styles = stylex.create({
// imperatively via ref to keep pointer-move cost free of React renders.
card: {
position: 'fixed',
- background: 'var(--color-background-popover)',
- border: '1px solid var(--color-border)',
+ backgroundColor: colorVars['--color-background-popover'],
+ border: `1px solid ${colorVars['--color-border']}`,
borderRadius: radiusVars['--radius-container'],
paddingBlock: spacingVars['--spacing-2'],
paddingInline: spacingVars['--spacing-3'],
- boxShadow: 'var(--shadow-med)',
+ boxShadow: shadowVars['--shadow-med'],
pointerEvents: 'none',
whiteSpace: 'nowrap',
zIndex: 9999,
display: 'none',
},
+ crosshair: {
+ stroke: colorVars['--color-text-primary'],
+ strokeWidth: 1,
+ },
});
/** Default tooltip body — used when `render` is not provided. */
@@ -143,7 +156,7 @@ const DefaultTooltipContent = memo(function DefaultTooltipContent({
export function XDSChartTooltip({
series = [],
render,
- highlightBand = true,
+ hoverIndicator = true,
showHoverDots = true,
placement = 'auto',
}: XDSChartTooltipProps) {
@@ -172,9 +185,7 @@ export function XDSChartTooltip({
(e: ChartPointerEvent) => {
const card = cardRef.current;
const svg = svgRef.current;
- if (!card) {
- return;
- }
+ if (!card) return;
if (!svg || !e.nearest) {
card.style.display = 'none';
return;
@@ -242,19 +253,13 @@ export function XDSChartTooltip({
// Hover dots — read from the resolved map at the hovered index.
const dots = useMemo(() => {
- if (!showHoverDots || hoveredIndex == null) {
- return null;
- }
+ if (!showHoverDots || hoveredIndex == null) return null;
const elements: ReactNode[] = [];
for (const s of series) {
- if (!shouldRenderHoverDot(s.type)) {
- continue;
- }
+ if (!shouldRenderHoverDot(s.type)) continue;
const points = resolved.get(s.key);
const point = points?.find(p => p.dataIndex === hoveredIndex);
- if (!point) {
- continue;
- }
+ if (!point) continue;
elements.push(
<circle
key={s.key}
@@ -271,41 +276,59 @@ export function XDSChartTooltip({
return elements;
}, [showHoverDots, hoveredIndex, series, resolved]);
- // Band highlight — only on band scales (categorical x-axis).
- const bandHighlight = useMemo(() => {
- if (!highlightBand || hoveredIndex == null) {
- return null;
- }
- if (!('bandwidth' in xScale)) {
- return null;
- }
+ // Hover indicator — band-highlight rect for bar charts, vertical crosshair
+ // line for line/area charts. Same source-of-truth (hoveredIndex), distinct
+ // visual idioms picked automatically based on the series mix.
+ const hoverIndicatorElement = useMemo(() => {
+ if (!hoverIndicator || hoveredIndex == null) return null;
const xv = data[hoveredIndex]?.[xKey];
- if (xv == null) {
- return null;
+ if (xv == null) return null;
+ const isBandScale = 'bandwidth' in xScale;
+ const hasBars = series.some(s => s.type === 'bar');
+
+ // Bar charts on a band scale → soft column highlight.
+ if (hasBars && isBandScale) {
+ const bandScale = xScale as ScaleBand<string>;
+ const x = bandScale(String(xv)) ?? 0;
+ const bw = bandScale.bandwidth();
+ const pad = 8;
+ const rectX = Math.max(0, x - pad);
+ const rectRight = Math.min(width, x + bw + pad);
+ const rectWidth = rectRight - rectX;
+ const topPad = Math.min(pad, margin.top);
+ return (
+ <rect
+ x={rectX}
+ y={-topPad}
+ width={rectWidth}
+ height={height + topPad}
+ fill="currentColor"
+ opacity={0.06}
+ rx={4}
+ pointerEvents="none"
+ />
+ );
}
- const bandScale = xScale as ScaleBand<string>;
- const x = bandScale(String(xv)) ?? 0;
- const bw = bandScale.bandwidth();
- const pad = 8;
- const rectX = Math.max(0, x - pad);
- const rectRight = Math.min(width, x + bw + pad);
- const rectWidth = rectRight - rectX;
- const topPad = Math.min(pad, margin.top);
+
+ // Line / area / dot charts → vertical crosshair through the point.
+ const px = isBandScale
+ ? ((xScale as ScaleBand<string>)(String(xv)) ?? 0) +
+ (xScale as ScaleBand<string>).bandwidth() / 2
+ : (xScale as (v: number) => number)(xv as number);
return (
- <rect
- x={rectX}
- y={-topPad}
- width={rectWidth}
- height={height + topPad}
- fill="currentColor"
- opacity={0.06}
- rx={4}
+ <line
+ x1={px}
+ x2={px}
+ y1={0}
+ y2={height}
+ {...stylex.props(styles.crosshair)}
pointerEvents="none"
/>
);
}, [
- highlightBand,
+ hoverIndicator,
hoveredIndex,
+ series,
xScale,
data,
xKey,
@@ -319,7 +342,7 @@ export function XDSChartTooltip({
// SSR: no DOM portal target; band highlight + dots still render in SVG.
return (
<>
- {bandHighlight}
+ {hoverIndicatorElement}
{dots}
</>
);
@@ -334,7 +357,7 @@ export function XDSChartTooltip({
return (
<>
- {bandHighlight}
+ {hoverIndicatorElement}
{dots}
{createPortal(
<div ref={cardRef} {...stylex.props(styles.card)}>
diff --git a/packages/lab/src/ChartV2/index.ts b/packages/lab/src/ChartV2/index.ts
index 6bd55e9f3c..b5e665b222 100644
--- a/packages/lab/src/ChartV2/index.ts
+++ b/packages/lab/src/ChartV2/index.ts
@@ -1,6 +1,8 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
export {XDSChart, type XDSChartProps} from './XDSChart';
+export {XDSChartAxis, type XDSChartAxisProps} from './XDSChartAxis';
+export {XDSChartGrid, type XDSChartGridProps} from './XDSChartGrid';
export {
XDSChartLegend,
type XDSChartLegendProps,
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index f235f4010c..97559a1639 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -205,6 +205,10 @@ export {
XDSChartLegend as XDSChartV2Legend,
type XDSChartLegendProps as XDSChartV2LegendProps,
type LegendItem as XDSChartV2LegendItem,
+ XDSChartAxis as XDSChartV2Axis,
+ type XDSChartAxisProps as XDSChartV2AxisProps,
+ XDSChartGrid as XDSChartV2Grid,
+ type XDSChartGridProps as XDSChartV2GridProps,
XDSChartSwatch as XDSChartV2Swatch,
swatchVariantForType as xdsChartV2SwatchVariantForType,
type XDSChartSwatchProps as XDSChartV2SwatchProps,