An open source design system that's fully customizable and agent ready
TypeScript
feat(ChartV2): add tooltip, axis formatters, and tick controls (#2189)
Marie Lucas94768c2517d4
diff --git a/apps/storybook/stories/ChartV2.stories.tsx b/apps/storybook/stories/ChartV2.stories.tsxindex 308752c646..79035538ba 100644--- a/apps/storybook/stories/ChartV2.stories.tsx+++ b/apps/storybook/stories/ChartV2.stories.tsx@@ -2,7 +2,7 @@import type {Meta, StoryObj} from '@storybook/react';import {XDSChartV2 as XDSChart, bar, line, area} from '@xds/lab';-import {XDSChartGrid, XDSChartAxis} from '@xds/lab';+import {XDSChartGrid, XDSChartAxis, currency} from '@xds/lab';const meta: Meta<typeof XDSChart> = {title: 'Lab/XDSChart v2',@@ -36,11 +36,12 @@ export const SimpleBar: StoryObj = {xKey="month"title="Monthly Revenue"series={[bar('revenue', {color: '#3b82f6'})]}+ tooltip={true}grid={<XDSChartGrid horizontal />}axes={<><XDSChartAxis position="bottom" />- <XDSChartAxis position="left" />+ <XDSChartAxis position="left" tickFormat={currency()} /></>}height={300}@@ -143,6 +144,7 @@ export const MixedMarks: StoryObj = {bar('revenue', {color: '#3b82f6', label: 'Revenue'}),line('trend', {color: '#f59e0b', label: 'Trend'}),]}+ tooltip={true}legend={{position: 'end', alignment: 'start'}}grid={<XDSChartGrid horizontal />}axes={diff --git a/apps/storybook/stories/ChartV2Swatch.stories.tsx b/apps/storybook/stories/ChartV2Swatch.stories.tsxnew file mode 100644index 0000000000..25dab1a246--- /dev/null+++ b/apps/storybook/stories/ChartV2Swatch.stories.tsx@@ -0,0 +1,24 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {XDSChartV2Swatch} from '@xds/lab';++const meta: Meta<typeof XDSChartV2Swatch> = {+ title: 'Lab/XDSChart v2/Primitives/Swatch',+ component: XDSChartV2Swatch,+ argTypes: {+ color: {control: 'color'},+ variant: {+ control: 'inline-radio',+ options: ['square', 'line'],+ },+ },+ args: {+ color: '#3b82f6',+ variant: 'square',+ },+};+export default meta;++/** Color swatch primitive — square for bar series, line for line/dot/area and any other non-bar mark. */+export const Swatch: StoryObj = {};diff --git a/apps/storybook/stories/ChartV2Tooltip.stories.tsx b/apps/storybook/stories/ChartV2Tooltip.stories.tsxnew file mode 100644index 0000000000..b44c71187b--- /dev/null+++ b/apps/storybook/stories/ChartV2Tooltip.stories.tsx@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {XDSChartV2 as XDSChart, bar, line} from '@xds/lab';+import {XDSChartGrid, XDSChartAxis, currency} from '@xds/lab';++const meta: Meta = {+ title: 'Lab/XDSChart v2/Primitives/Tooltip',+};+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},+];++const series = [+ bar('revenue', {color: '#3b82f6', label: 'Revenue'}),+ bar('costs', {color: '#ef4444', label: 'Costs'}),+ line('trend', {color: '#f59e0b', label: 'Trend'}),+];++/** Hover over the chart to see the grouped tooltip with all series values at the hovered x-position. */+export const Tooltip: StoryObj = {+ render: () => (+ <XDSChart+ data={monthlyData}+ xKey="month"+ series={series}+ tooltip+ grid={<XDSChartGrid horizontal />}+ axes={+ <>+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" tickFormat={currency()} />+ </>+ }+ height={300}+ />+ ),+};diff --git a/packages/lab/src/Chart/XDSChartAxis.tsx b/packages/lab/src/Chart/XDSChartAxis.tsxindex 10f7bf2d4a..78854ef189 100644--- a/packages/lab/src/Chart/XDSChartAxis.tsx+++ b/packages/lab/src/Chart/XDSChartAxis.tsx@@ -18,8 +18,12 @@ export interface XDSChartAxisProps {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;}@@ -31,13 +35,16 @@ export interface XDSChartAxisProps {* @example* ```* <XDSChartAxis position="bottom" />- * <XDSChartAxis position="left" tickCount={5} />+ * <XDSChartAxis position="left" tickCount={5} tickFormat={currency} />+ * <XDSChartAxis position="bottom" maxTicks={6} truncate={10} />* ```*/export function XDSChartAxis({position,tickCount = 5,+ maxTicks,tickFormat,+ truncate,animated = true,}: XDSChartAxisProps) {const {width, height, xScale, yScale} = useChart();@@ -46,20 +53,30 @@ export function XDSChartAxis({const scale = isHorizontal ? xScale : yScale;const ticks = useMemo(() => {+ let allTicks: {value: unknown; offset: number}[];if (isBandScale(scale)) {- return scale.domain().map(d => ({+ 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),+ }));}- const linearScale = scale as- | ScaleLinear<number, number>- | ScaleTime<number, number>;- return linearScale.ticks(tickCount).map(d => ({- value: d,- offset: linearScale(d as number & Date),- }));- }, [scale, tickCount]);++ // 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'@@ -81,7 +98,13 @@ export function XDSChartAxis({return 0;})();- const format = tickFormat ?? String;+ 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 tickSize = 6;// Transition style for smooth tick movement during streamingdiff --git a/packages/lab/src/Chart/formatters.ts b/packages/lab/src/Chart/formatters.tsnew file mode 100644index 0000000000..2baae3a748--- /dev/null+++ b/packages/lab/src/Chart/formatters.ts@@ -0,0 +1,74 @@+/**+ * @file formatters.ts+ * @output Built-in tick format utilities for common data types+ * @position Utility; consumed by XDSChartAxis via tickFormat prop+ */++/**+ * Compact number formatter (e.g. 1200 → "1.2K", 1500000 → "1.5M")+ */+// Copyright (c) Meta Platforms, Inc. and affiliates.++export function compactNumber(value: unknown): string {+ const n = Number(value);+ if (isNaN(n)) return String(value);+ if (Math.abs(n) >= 1_000_000_000) return `${strip(n / 1_000_000_000)}B`;+ if (Math.abs(n) >= 1_000_000) return `${strip(n / 1_000_000)}M`;+ if (Math.abs(n) >= 1_000) return `${strip(n / 1_000)}K`;+ return n.toString();+}++/**+ * Currency formatter factory. Returns a tick format function.+ *+ * @example+ * ```+ * <XDSChartAxis tickFormat={currency()} /> // $1.5K+ * <XDSChartAxis tickFormat={currency('€')} /> // €1.5K+ * <XDSChartAxis tickFormat={currency('¥')} /> // ¥1.5K+ * ```+ */+export function currency(symbol = '$'): (value: unknown) => string {+ return (value: unknown) => {+ const n = Number(value);+ if (isNaN(n)) return String(value);+ if (Math.abs(n) >= 1_000_000_000)+ return `${symbol}${strip(n / 1_000_000_000)}B`;+ if (Math.abs(n) >= 1_000_000) return `${symbol}${strip(n / 1_000_000)}M`;+ if (Math.abs(n) >= 1_000) return `${symbol}${strip(n / 1_000)}K`;+ return `${symbol}${n.toLocaleString()}`;+ };+}++/** Remove trailing .0 from fixed-point strings */+function strip(n: number): string {+ const s = n.toFixed(1);+ return s.endsWith('.0') ? s.slice(0, -2) : s;+}++/**+ * Percent formatter (e.g. 0.45 → "45%", 1.2 → "120%")+ */+export function percent(value: unknown): string {+ const n = Number(value);+ if (isNaN(n)) return String(value);+ return `${Math.round(n * 100)}%`;+}++/**+ * Date formatter — short date (e.g. "Jan 5", "Mar 12")+ */+export function shortDate(value: unknown): string {+ const d = value instanceof Date ? value : new Date(Number(value));+ if (isNaN(d.getTime())) return String(value);+ return d.toLocaleDateString(undefined, {month: 'short', day: 'numeric'});+}++/**+ * Date formatter — month/year (e.g. "Jan 2024", "Mar 2025")+ */+export function monthYear(value: unknown): string {+ const d = value instanceof Date ? value : new Date(Number(value));+ if (isNaN(d.getTime())) return String(value);+ return d.toLocaleDateString(undefined, {month: 'short', year: 'numeric'});+}diff --git a/packages/lab/src/Chart/index.ts b/packages/lab/src/Chart/index.tsindex a3ca543499..3deacba629 100644--- a/packages/lab/src/Chart/index.ts+++ b/packages/lab/src/Chart/index.ts@@ -2,6 +2,13 @@export {XDSChart, type XDSChartProps, type YBaseline} from './XDSChart';export {XDSChartAxis, type XDSChartAxisProps} from './XDSChartAxis';+export {+ compactNumber,+ currency,+ percent,+ shortDate,+ monthYear,+} from './formatters';export {XDSChartGrid, type XDSChartGridProps} from './XDSChartGrid';export {XDSChartBar, type XDSChartBarProps} from './XDSChartBar';export {XDSChartLine, type XDSChartLineProps} from './XDSChartLine';@@ -71,7 +78,11 @@ export {type BrushMode,type BrushRange,} from './XDSChartBrush';-export {XDSChartZoom, type XDSChartZoomProps, type ZoomToolbarPosition} from './XDSChartZoom';+export {+ XDSChartZoom,+ type XDSChartZoomProps,+ type ZoomToolbarPosition,+} from './XDSChartZoom';export {XDSChartSelect, type XDSChartSelectProps} from './XDSChartSelect';export {XDSChartReferenceLine,diff --git a/packages/lab/src/ChartV2/XDSChart.tsx b/packages/lab/src/ChartV2/XDSChart.tsxindex c0dc5afd8c..736da54cae 100644--- a/packages/lab/src/ChartV2/XDSChart.tsx+++ b/packages/lab/src/ChartV2/XDSChart.tsx@@ -30,6 +30,7 @@ import {XDSVStack, XDSHStack} from '@xds/core';import * as stylex from '@stylexjs/stylex';import {XDSChartLegend, type XDSChartLegendProps} from './XDSChartLegend';import {deriveLegendItems} from './legend';+import {XDSChartTooltip, type XDSChartTooltipProps} from './XDSChartTooltip';export interface XDSChartProps {data: Record<string, unknown>[];@@ -39,17 +40,15 @@ export interface XDSChartProps {margin?: Partial<ChartMargin>;grid?: ReactNode;axes?: ReactNode;- /** Legend configuration. Pass `true` for defaults, or a config object. */legend?: boolean | XDSChartLegendProps;+ tooltip?: boolean | Omit<XDSChartTooltipProps, 'series'>;interactions?: ReactNode;children?: ReactNode;- /** Chart title displayed above the visualization */title?: string;- /** Subtitle displayed below the title */subtitle?: string;}-const DEFAULT_MARGIN: ChartMargin = {top: 16, right: 16, bottom: 32, left: 48};+const DEFAULT_MARGIN: ChartMargin = {top: 24, right: 24, bottom: 32, left: 48};const styles = stylex.create({container: {@@ -74,6 +73,7 @@ export function XDSChart({grid,axes,legend,+ tooltip,interactions,children,title,@@ -163,15 +163,14 @@ export function XDSChart({}const cursor = point.matrixTransform(ctm);+ // Find nearest point by x-distance only (full vertical column is the hover zone)let nearest: ChartPointerEvent['nearest'] = null;- let bestDist = 40 * 40;+ let bestXDist = Infinity;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;+ const xDist = Math.abs(p.px - cursor.x);+ if (xDist < bestXDist) {+ bestXDist = xDist;nearest = {...p, seriesKey};}}@@ -331,7 +330,16 @@ export function XDSChart({/>{interactions}- {/* 5. Escape hatch */}+ {/* 5. Tooltip — declarative shortcut. For full control, render+ <XDSChartTooltip> directly via the `children` slot. */}+ {tooltip && (+ <XDSChartTooltip+ series={series}+ {...(tooltip === true ? {} : tooltip)}+ />+ )}++ {/* 6. Escape hatch */}{children}</g></svg>diff --git a/packages/lab/src/ChartV2/XDSChartTooltip.tsx b/packages/lab/src/ChartV2/XDSChartTooltip.tsxnew file mode 100644index 0000000000..5b5fef9555--- /dev/null+++ b/packages/lab/src/ChartV2/XDSChartTooltip.tsx@@ -0,0 +1,333 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file XDSChartTooltip.tsx+ * @output Grouped chart tooltip — shows all series values at the hovered x-position.+ * Composable: drop into `<XDSChart tooltip>` or render directly inside a chart+ * to take full control of props.+ * @position Reads from ChartV2Context — must render inside an <XDSChart>.+ *+ * @example+ * ```+ * // Default — declarative on XDSChart+ * <XDSChart tooltip />+ *+ * // Custom render function via XDSChart prop+ * <XDSChart tooltip={{render: (x, rows) => <MyCard x={x} rows={rows} />}} />+ *+ * // Composable — drop into the chart's children for full control+ * <XDSChart>+ * <XDSChartTooltip highlightBand={false} placement="top" />+ * </XDSChart>+ * ```+ */++'use client';++import {+ memo,+ useState,+ useEffect,+ useMemo,+ useRef,+ useCallback,+ type ReactNode,+} from 'react';+import {createPortal} from 'react-dom';+import * as stylex from '@stylexjs/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 {+ deriveTooltipSeriesValues,+ shouldRenderHoverDot,+ type TooltipSeriesValue,+} from './tooltip';+import type {SeriesDef, ChartPointerEvent} from './types';+import type {ScaleBand} from 'd3-scale';++export type XDSChartTooltipPlacement = 'auto' | 'right' | 'left' | 'top';++export interface XDSChartTooltipProps {+ /**+ * Series definitions — used to map the hovered datum to per-series rows.+ * When rendered via `<XDSChart tooltip />`, XDSChart injects this automatically.+ * When composing directly, pass the same `series` array you gave XDSChart.+ */+ series?: readonly SeriesDef[];+ /**+ * Custom render function. Receives the x-value and one row per visible series.+ * Returning `null` hides the card while still rendering the band highlight + dots.+ */+ 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`.+ */+ highlightBand?: boolean;+ /**+ * Whether to draw a hover dot at each series' point (skipped for bars).+ * Default: `true`.+ */+ showHoverDots?: boolean;+ /**+ * Card placement relative to the hovered point:+ * - `'auto'` (default): right of the point, flips to left if it would overflow+ * - `'right'` / `'left'` / `'top'`: pinned position+ */+ placement?: XDSChartTooltipPlacement;+}++const styles = stylex.create({+ // Card chrome — static visual styles. Position (left/top/display) is updated+ // 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)',+ borderRadius: radiusVars['--radius-container'],+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ boxShadow: 'var(--shadow-med)',+ pointerEvents: 'none',+ whiteSpace: 'nowrap',+ zIndex: 9999,+ display: 'none',+ },+});++/** Default tooltip body — used when `render` is not provided. */+const DefaultTooltipContent = memo(function DefaultTooltipContent({+ xValue,+ rows,+}: {+ xValue: unknown;+ rows: TooltipSeriesValue[];+}) {+ return (+ <XDSVStack gap={1}>+ <XDSText type="body" weight="semibold">+ {String(xValue)}+ </XDSText>+ {rows.length === 1 ? (+ <XDSText type="supporting">{String(rows[0].value)}</XDSText>+ ) : (+ <XDSVStack gap={1}>+ {rows.map(row => (+ <XDSHStack key={row.key} gap={2} vAlign="center">+ <XDSChartSwatch+ color={row.color}+ variant={swatchVariantForType(row.type)}+ />+ <XDSText type="supporting">{row.label}</XDSText>+ <XDSText type="supporting" weight="semibold">+ {String(row.value)}+ </XDSText>+ </XDSHStack>+ ))}+ </XDSVStack>+ )}+ </XDSVStack>+ );+});++/**+ * Composable grouped tooltip for XDSChart.+ *+ * Subscribes to the chart's pointer event stream and only re-renders when the+ * hovered data index changes (not on every pointer move). Card position is+ * updated imperatively via a ref to keep pointer-move cost ~free.+ */+export function XDSChartTooltip({+ series = [],+ render,+ highlightBand = true,+ showHoverDots = true,+ placement = 'auto',+}: XDSChartTooltipProps) {+ const {+ data,+ xKey,+ resolved,+ onPointer,+ svgRef,+ margin,+ xScale,+ width,+ height,+ } = useChartV2();+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);+ const cardRef = useRef<HTMLDivElement>(null);++ // Stable Set of resolved series keys — used by deriveTooltipSeriesValues.+ // Recomputed only when the resolved map identity changes (per layout pass).+ const resolvedKeys = useMemo(() => new Set(resolved.keys()), [resolved]);++ // ─── Card positioning ──────────────────────────────────────────────────+ // Imperative — the card is portaled, and we don't want pointer-move to+ // trigger React renders.+ const positionCard = useCallback(+ (e: ChartPointerEvent) => {+ const card = cardRef.current;+ const svg = svgRef.current;+ if (!card) return;+ if (!svg || !e.nearest) {+ card.style.display = 'none';+ return;+ }+ const svgRect = svg.getBoundingClientRect();+ const screenX = svgRect.left + margin.left + e.nearest.px;+ const screenY = svgRect.top + margin.top;+ const cardWidth = card.offsetWidth;+ const cardHeight = card.offsetHeight;+ const viewportWidth = window.innerWidth;+ const gap = 8;++ let x: number;+ let y = screenY;+ switch (placement) {+ case 'left':+ x = screenX - cardWidth - gap;+ break;+ case 'right':+ x = screenX + gap;+ break;+ case 'top':+ x = screenX - cardWidth / 2;+ y = screenY - cardHeight - gap;+ break;+ case 'auto':+ default: {+ const rightX = screenX + gap;+ x =+ rightX + cardWidth > viewportWidth+ ? screenX - cardWidth - gap+ : rightX;+ }+ }++ card.style.left = `${x}px`;+ card.style.top = `${y}px`;+ card.style.display = 'block';+ },+ [svgRef, margin, placement],+ );++ // ─── Subscribe to pointer events ───────────────────────────────────────+ useEffect(() => {+ let currentIndex: number | null = null;+ const unsub = onPointer((e: ChartPointerEvent) => {+ const newIndex = e.nearest?.dataIndex ?? null;+ if (newIndex !== currentIndex) {+ currentIndex = newIndex;+ setHoveredIndex(newIndex);+ }+ positionCard(e);+ });+ return unsub;+ }, [onPointer, positionCard]);++ // ─── Derived data ──────────────────────────────────────────────────────+ const datum = hoveredIndex != null ? data[hoveredIndex] : undefined;+ const xValue = datum?.[xKey];++ const seriesValues = useMemo(+ () => deriveTooltipSeriesValues(series, datum, resolvedKeys),+ [series, datum, resolvedKeys],+ );++ // Hover dots — read from the resolved map at the hovered index.+ const dots = useMemo(() => {+ if (!showHoverDots || hoveredIndex == null) return null;+ const elements: ReactNode[] = [];+ for (const s of series) {+ if (!shouldRenderHoverDot(s.type)) continue;+ const points = resolved.get(s.key);+ const point = points?.find(p => p.dataIndex === hoveredIndex);+ if (!point) continue;+ elements.push(+ <circle+ key={s.key}+ cx={point.px}+ cy={point.py}+ r={4}+ fill="var(--color-background-surface)"+ stroke={s.color ?? 'var(--color-border-emphasized)'}+ strokeWidth={2}+ pointerEvents="none"+ />,+ );+ }+ 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;+ const xv = data[hoveredIndex]?.[xKey];+ if (xv == null) return null;+ 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"+ />+ );+ }, [+ highlightBand,+ hoveredIndex,+ xScale,+ data,+ xKey,+ width,+ height,+ margin.top,+ ]);++ // ─── Render ────────────────────────────────────────────────────────────+ if (typeof document === 'undefined') {+ // SSR: no DOM portal target; band highlight + dots still render in SVG.+ return (+ <>+ {bandHighlight}+ {dots}+ </>+ );+ }++ const cardContent =+ hoveredIndex == null ? null : render ? (+ render(xValue, seriesValues)+ ) : (+ <DefaultTooltipContent xValue={xValue} rows={seriesValues} />+ );++ return (+ <>+ {bandHighlight}+ {dots}+ {createPortal(+ <div ref={cardRef} {...stylex.props(styles.card)}>+ {cardContent}+ </div>,+ document.body,+ )}+ </>+ );+}diff --git a/packages/lab/src/ChartV2/index.ts b/packages/lab/src/ChartV2/index.tsindex a309e46147..6bd55e9f3c 100644--- a/packages/lab/src/ChartV2/index.ts+++ b/packages/lab/src/ChartV2/index.ts@@ -14,6 +14,12 @@ export {type XDSChartSwatchProps,type XDSChartSwatchVariant,} from './XDSChartSwatch';+export {+ XDSChartTooltip,+ type XDSChartTooltipProps,+ type XDSChartTooltipPlacement,+} from './XDSChartTooltip';+export {type TooltipSeriesValue} from './tooltip';export {bar,line,diff --git a/packages/lab/src/ChartV2/legend.ts b/packages/lab/src/ChartV2/legend.tsindex a332833316..e65097bf9f 100644--- a/packages/lab/src/ChartV2/legend.ts+++ b/packages/lab/src/ChartV2/legend.ts@@ -6,24 +6,21 @@* @position Used by XDSChart to bridge series → legend items*/-import type {SeriesDef} from './types';+import {isUtilityMarkType, type SeriesDef} from './types';export interface LegendItem {label: string;color: string;- /** Mark type — determines swatch shape (square for bar/area/dot, line for line) */+ /** Mark type — determines swatch shape (square for bar, line for everything else) */type?: string;}-/** Series types that don't appear in the legend */-const SKIP_TYPES = new Set(['referenceLine', 'errorBar', 'band']);-/*** Derive legend items from series definitions.* Skips utility marks and series without a color.*/export function deriveLegendItems(series: readonly SeriesDef[]): LegendItem[] {return series- .filter(s => !SKIP_TYPES.has(s.type) && s.color)+ .filter(s => !isUtilityMarkType(s.type) && s.color).map(s => ({label: s.label ?? s.key, color: s.color!, type: s.type}));}diff --git a/packages/lab/src/ChartV2/tooltip.ts b/packages/lab/src/ChartV2/tooltip.tsnew file mode 100644index 0000000000..dbce3ea0ea--- /dev/null+++ b/packages/lab/src/ChartV2/tooltip.ts@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tooltip.ts+ * @output Tooltip types + series-value derivation+ * @position Used by XDSChart to bridge series + hovered datum → tooltip rows.+ * Mirrors the legend.ts split: data shaping lives here, presentation+ * lives in XDSChartTooltip.tsx.+ */++import {isUtilityMarkType, type SeriesDef} from './types';++/**+ * One row of tooltip data — represents a single series' value at the+ * hovered x-position. Stable shape so custom `render` functions can rely on it.+ */+export interface TooltipSeriesValue {+ /** Series key (matches SeriesDef.key) */+ key: string;+ /** Display label — falls back to key when not set on the series */+ label: string;+ /** Series color token */+ color: string;+ /** Mark type — drives swatch variant in the default render */+ type: string;+ /** Raw value at the hovered x for this series */+ value: unknown;+}++/**+ * Build the ordered list of tooltip rows for a given hovered datum.+ * Skips utility marks and any series the layout couldn't resolve.+ *+ * Pure / synchronous — safe to memoize on the caller.+ */+export function deriveTooltipSeriesValues(+ series: readonly SeriesDef[],+ datum: Record<string, unknown> | undefined,+ resolvedKeys: ReadonlySet<string>,+): TooltipSeriesValue[] {+ if (!datum) return [];+ const out: TooltipSeriesValue[] = [];+ for (const s of series) {+ if (isUtilityMarkType(s.type)) continue;+ if (!resolvedKeys.has(s.key)) continue;+ out.push({+ key: s.key,+ label: s.label ?? s.key,+ color: s.color ?? 'var(--color-text-primary)',+ type: s.type,+ value: datum[s.dataKeys[0]],+ });+ }+ return out;+}++/**+ * Whether a series should render a hover dot at the focused index.+ * Bars get a band-highlight rect instead, and utility marks have no+ * data point to highlight.+ */+export function shouldRenderHoverDot(seriesType: string): boolean {+ return seriesType !== 'bar' && !isUtilityMarkType(seriesType);+}diff --git a/packages/lab/src/ChartV2/types.ts b/packages/lab/src/ChartV2/types.tsindex 646eff26ab..6a9a319176 100644--- a/packages/lab/src/ChartV2/types.ts+++ b/packages/lab/src/ChartV2/types.ts@@ -60,7 +60,7 @@ export interface SeriesDef {readonly color?: string;/** Human-readable label for legend. Falls back to key if not provided. */readonly label?: string;- /** Layout hints the chart root uses for cross-series coordination */+ /** Layout hints the chart root uses for cross-series coordination */readonly layout: {/** Stack group — series with same stack accumulate */stack?: string;@@ -111,3 +111,19 @@ export interface ChartV2Context {onPointer: (handler: (e: ChartPointerEvent) => void) => () => void;svgRef: React.RefObject<SVGSVGElement | null>;}++/**+ * Series mark types that are utility / annotation marks rather than primary+ * data. They're skipped from chrome surfaces (legend, tooltip rows) since+ * they don't represent values the user is comparing.+ */+export const UTILITY_MARK_TYPES: ReadonlySet<string> = new Set([+ 'referenceLine',+ 'errorBar',+ 'band',+]);++/** True if the series type is a utility / annotation mark. */+export function isUtilityMarkType(type: string): boolean {+ return UTILITY_MARK_TYPES.has(type);+}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex b2aa9ba7a0..30115b373c 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -108,6 +108,11 @@ export {type XDSChartColorsAPI,type SequentialHue,type TokenResolver,+ compactNumber,+ currency,+ percent,+ shortDate,+ monthYear,} from './Chart';// Radial charts — spider, pie, donut@@ -201,6 +206,10 @@ export {swatchVariantForType as xdsChartV2SwatchVariantForType,type XDSChartSwatchProps as XDSChartV2SwatchProps,type XDSChartSwatchVariant as XDSChartV2SwatchVariant,+ XDSChartTooltip as XDSChartV2Tooltip,+ type XDSChartTooltipProps as XDSChartV2TooltipProps,+ type XDSChartTooltipPlacement as XDSChartV2TooltipPlacement,+ type TooltipSeriesValue as XDSChartV2TooltipSeriesValue,bar,line,dot,