Skip to content

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

TypeScript

feat(lab): chart interactions — brush, crosshair, zoom, select, highlight, reference lines (#1463)

Cindy Zhang003f4ac7a313
diff --git a/apps/storybook/stories/ChartCoordinated.stories.tsx b/apps/storybook/stories/ChartCoordinated.stories.tsx
new file mode 100644
index 0000000000..b82b604542
--- /dev/null
+++ b/apps/storybook/stories/ChartCoordinated.stories.tsx
@@ -0,0 +1,188 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState, useMemo} from 'react';
+import {
+ XDSChart,
+ XDSChartAxis,
+ XDSChartGrid,
+ XDSChartDot,
+ XDSChartBar,
+ XDSChartBrush,
+ XDSChartReferenceLine,
+ useXDSChartColors,
+} from '@xds/lab';
+import {XDSStack, XDSText} from '@xds/core';
+import {XDSHeading} from '@xds/core/Text';
+import {useDataset} from './useDataset';
+
+const meta: Meta = {title: 'Lab/XDSChart Interactions/Coordinated Views'};
+export default meta;
+
+type Car = {
+ Name: string;
+ Miles_per_Gallon: number;
+ Horsepower: number;
+ Weight_in_lbs: number;
+ Origin: string;
+ Cylinders: number;
+};
+
+/** Brush on scatter filters bar chart + table — coordinated views */
+export const CoordinatedViews: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const [raw] = useDataset<Car>('cars.json');
+ const [brushRange, setBrushRange] = useState<[number, number] | null>(null);
+
+ const allData = useMemo(
+ () =>
+ raw.filter(
+ d =>
+ d.Horsepower != null &&
+ d.Miles_per_Gallon != null &&
+ d.Origin != null,
+ ),
+ [raw],
+ );
+
+ const filteredData = useMemo(() => {
+ if (!brushRange) return allData;
+ return allData.filter(
+ d => d.Horsepower >= brushRange[0] && d.Horsepower <= brushRange[1],
+ );
+ }, [allData, brushRange]);
+
+ // Scatter data
+ const scatterData = useMemo(
+ () => allData.map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),
+ [allData],
+ );
+
+ // Bar data — average MPG by origin, from filtered set
+ const barData = useMemo(() => {
+ const byOrigin = new Map<string, {sum: number; count: number}>();
+ for (const d of filteredData) {
+ const e = byOrigin.get(d.Origin) ?? {sum: 0, count: 0};
+ e.sum += d.Miles_per_Gallon;
+ e.count += 1;
+ byOrigin.set(d.Origin, e);
+ }
+ return [...byOrigin.entries()]
+ .map(([origin, {sum, count}]) => ({
+ origin,
+ avgMpg: Math.round((sum / count) * 10) / 10,
+ }))
+ .sort((a, b) => b.avgMpg - a.avgMpg);
+ }, [filteredData]);
+
+ // Table data — top 10 from filtered set
+ const tableData = useMemo(
+ () =>
+ filteredData.slice(0, 10).map(d => ({
+ name: d.Name,
+ hp: d.Horsepower,
+ mpg: d.Miles_per_Gallon,
+ origin: d.Origin,
+ })),
+ [filteredData],
+ );
+
+ if (!allData.length)
+ return <XDSText type="supporting">Loading\u2026</XDSText>;
+
+ const c = colors.categorical(3);
+
+ return (
+ <XDSStack direction="vertical" gap={6}>
+ <XDSHeading level={3}>Coordinated Views</XDSHeading>
+ <XDSText type="supporting" color="secondary">
+ Brush on the scatter to filter the bar chart and table below.
+ {brushRange
+ ? ` Showing ${filteredData.length} cars with ${Math.round(brushRange[0])}\u2013${Math.round(brushRange[1])} HP.`
+ : ` Showing all ${allData.length} cars.`}
+ </XDSText>
+
+ {/* Scatter with brush */}
+ <XDSStack direction="vertical" gap={1}>
+ <XDSText type="label">Horsepower vs MPG</XDSText>
+ <XDSChart
+ data={scatterData}
+ xKey="hp"
+ yKeys={['mpg']}
+ yBaseline="data"
+ height={280}>
+ <XDSChartGrid horizontal vertical />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartDot dataKey="mpg" color={c[0]} radius={3} />
+ <XDSChartBrush
+ onBrush={range => setBrushRange(range)}
+ onClear={() => setBrushRange(null)}
+ />
+ {brushRange && (
+ <>
+ <XDSChartReferenceLine
+ x={brushRange[0]}
+ color={c[0]}
+ strokeDasharray="none"
+ />
+ <XDSChartReferenceLine
+ x={brushRange[1]}
+ color={c[0]}
+ strokeDasharray="none"
+ />
+ </>
+ )}
+ </XDSChart>
+ </XDSStack>
+
+ {/* Bar chart — reacts to brush */}
+ <XDSStack direction="vertical" gap={1}>
+ <XDSText type="label">Average MPG by Origin (filtered)</XDSText>
+ <XDSChart
+ data={barData}
+ xKey="origin"
+ yKeys={['avgMpg']}
+ height={200}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartBar dataKey="avgMpg" color={c[1]} />
+ </XDSChart>
+ </XDSStack>
+
+ {/* Table — reacts to brush */}
+ <XDSStack direction="vertical" gap={1}>
+ <XDSText type="label">Top 10 cars (filtered)</XDSText>
+ <div style={{fontSize: 12, overflow: 'auto'}}>
+ <table style={{width: '100%', borderCollapse: 'collapse'}}>
+ <thead>
+ <tr
+ style={{
+ borderBottom: '1px solid var(--color-border)',
+ textAlign: 'left',
+ }}>
+ <th style={{padding: '4px 8px'}}>Name</th>
+ <th style={{padding: '4px 8px'}}>HP</th>
+ <th style={{padding: '4px 8px'}}>MPG</th>
+ <th style={{padding: '4px 8px'}}>Origin</th>
+ </tr>
+ </thead>
+ <tbody>
+ {tableData.map((d, i) => (
+ <tr
+ key={i}
+ style={{borderBottom: '1px solid var(--color-border)'}}>
+ <td style={{padding: '4px 8px'}}>{d.name}</td>
+ <td style={{padding: '4px 8px'}}>{d.hp}</td>
+ <td style={{padding: '4px 8px'}}>{d.mpg}</td>
+ <td style={{padding: '4px 8px'}}>{d.origin}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </XDSStack>
+ </XDSStack>
+ );
+ },
+};
diff --git a/apps/storybook/stories/ChartInteractions.stories.tsx b/apps/storybook/stories/ChartInteractions.stories.tsx
new file mode 100644
index 0000000000..0a86ccab5f
--- /dev/null
+++ b/apps/storybook/stories/ChartInteractions.stories.tsx
@@ -0,0 +1,240 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState, useMemo} from 'react';
+import {
+ XDSChart,
+ XDSChartAxis,
+ XDSChartGrid,
+ XDSChartLine,
+ XDSChartDot,
+ XDSChartBar,
+ XDSChartBrush,
+ XDSChartCrosshair,
+ XDSChartZoom,
+ XDSChartSelect,
+ XDSChartReferenceLine,
+ useXDSChartColors,
+} from '@xds/lab';
+import {XDSStack, XDSText} from '@xds/core';
+import {XDSHeading} from '@xds/core/Text';
+import {useDataset} from './useDataset';
+
+const meta: Meta = {title: 'Lab/XDSChart Interactions', tags: ['autodocs']};
+export default meta;
+
+type Car = {Horsepower: number; Miles_per_Gallon: number};
+
+/** Drag to select an x-range */
+export const BrushSelection: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const [raw] = useDataset<Car>('cars.json');
+ const [count, setCount] = useState<number | null>(null);
+ const data = useMemo(
+ () =>
+ raw
+ .filter(d => d.Horsepower != null && d.Miles_per_Gallon != null)
+ .map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),
+ [raw],
+ );
+ if (!data.length) return <XDSText type="supporting">Loading\u2026</XDSText>;
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Brush Selection</XDSHeading>
+ <XDSText type="supporting" color="secondary">
+ Drag to select.{' '}
+ {count != null ? `${count} points selected.` : 'Click to clear.'}
+ </XDSText>
+ <XDSChart
+ data={data}
+ xKey="hp"
+ yKeys={['mpg']}
+ yBaseline="data"
+ height={350}>
+ <XDSChartGrid horizontal vertical />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartDot
+ dataKey="mpg"
+ color={colors.categorical(1)[0]}
+ radius={3}
+ />
+ <XDSChartBrush
+ onBrush={(_, sel) => setCount(sel.length)}
+ onClear={() => setCount(null)}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
+
+/** Crosshair with value readouts */
+export const Crosshair: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const [raw] = useDataset<Car>('cars.json');
+ const data = useMemo(
+ () =>
+ raw
+ .filter(d => d.Horsepower != null && d.Miles_per_Gallon != null)
+ .map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),
+ [raw],
+ );
+ if (!data.length) return <XDSText type="supporting">Loading\u2026</XDSText>;
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Crosshair</XDSHeading>
+ <XDSChart
+ data={data}
+ xKey="hp"
+ yKeys={['mpg']}
+ yBaseline="data"
+ height={350}>
+ <XDSChartGrid horizontal vertical />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartDot
+ dataKey="mpg"
+ color={colors.categorical(1)[0]}
+ radius={3}
+ />
+ <XDSChartCrosshair
+ xFormat={v => `${Math.round(v)} hp`}
+ yFormat={v => `${Math.round(v)} mpg`}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
+
+/** Scroll to zoom, drag to pan */
+export const ZoomPan: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const [raw] = useDataset<Car>('cars.json');
+ const data = useMemo(
+ () =>
+ raw
+ .filter(d => d.Horsepower != null && d.Miles_per_Gallon != null)
+ .map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),
+ [raw],
+ );
+ const [xDomain, setXDomain] = useState<[number, number]>([40, 230]);
+ const [yDomain, setYDomain] = useState<[number, number]>([8, 47]);
+ if (!data.length) return <XDSText type="supporting">Loading\u2026</XDSText>;
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Zoom & Pan</XDSHeading>
+ <XDSText type="supporting" color="secondary">
+ Scroll to zoom, drag to pan. x: [{Math.round(xDomain[0])},{' '}
+ {Math.round(xDomain[1])}]
+ </XDSText>
+ <XDSChart
+ data={data}
+ xKey="hp"
+ yKeys={['mpg']}
+ xDomain={xDomain}
+ yDomain={yDomain}
+ height={350}>
+ <XDSChartGrid horizontal vertical />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartDot
+ dataKey="mpg"
+ color={colors.categorical(1)[0]}
+ radius={3}
+ />
+ <XDSChartZoom
+ onXDomainChange={setXDomain}
+ onYDomainChange={setYDomain}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
+
+/** Click to select points */
+export const ClickSelect: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const [raw] = useDataset<Car>('cars.json');
+ const data = useMemo(
+ () =>
+ raw
+ .filter(d => d.Horsepower != null && d.Miles_per_Gallon != null)
+ .map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),
+ [raw],
+ );
+ const [selected, setSelected] = useState<number[]>([]);
+ if (!data.length) return <XDSText type="supporting">Loading\u2026</XDSText>;
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Click to Select</XDSHeading>
+ <XDSText type="supporting" color="secondary">
+ Click a point. Shift-click for multi. {selected.length} selected.
+ </XDSText>
+ <XDSChart
+ data={data}
+ xKey="hp"
+ yKeys={['mpg']}
+ yBaseline="data"
+ height={350}>
+ <XDSChartGrid horizontal vertical />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartDot
+ dataKey="mpg"
+ color={colors.categorical(1)[0]}
+ radius={3}
+ />
+ <XDSChartSelect selected={selected} onSelectionChange={setSelected} />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
+
+const monthlyData = [
+ {month: 'Jan', revenue: 4200, expenses: 2800},
+ {month: 'Feb', revenue: 3800, expenses: 2600},
+ {month: 'Mar', revenue: 5100, expenses: 3200},
+ {month: 'Apr', revenue: 4600, expenses: 2900},
+ {month: 'May', revenue: 5400, expenses: 3100},
+ {month: 'Jun', revenue: 6200, expenses: 3400},
+];
+
+
+
+/** Reference lines for target and average */
+export const ReferenceLines: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Reference Lines</XDSHeading>
+ <XDSChart
+ data={monthlyData}
+ xKey="month"
+ yKeys={['revenue']}
+ height={300}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartBar dataKey="revenue" color={colors.categorical(1)[0]} />
+ <XDSChartReferenceLine
+ y={5000}
+ label="Target"
+ color={colors.semantic.positive}
+ />
+ <XDSChartReferenceLine
+ y={4700}
+ label="Average"
+ color={colors.semantic.neutral}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
diff --git a/packages/lab/src/Chart/XDSChart.tsx b/packages/lab/src/Chart/XDSChart.tsx
index e1ebb510bb..e5959cf458 100644
--- a/packages/lab/src/Chart/XDSChart.tsx
+++ b/packages/lab/src/Chart/XDSChart.tsx
@@ -12,10 +12,12 @@ import {
useMemo,
useRef,
useState,
+ useCallback,
useLayoutEffect,
} from 'react';
import {scaleLinear, scaleBand} from 'd3-scale';
import type {ScaleLinear} from 'd3-scale';
+import {isBandScale} from './utils';
import {ChartProvider} from './ChartContext';
import type {ChartMargin, ChartScale} from './types';
@@ -64,6 +66,12 @@ export interface XDSChartProps {
* Ignored for band (categorical) scales.
*/
xDomain?: [number, number];
+ /**
+ * Set touch-action on the chart container. Use 'none' when interactive
+ * components (brush, zoom, crosshair) are present to prevent scroll
+ * interference on mobile.
+ */
+ interactive?: boolean;
/** Chart contents — axes, marks, tooltips */
children: ReactNode;
}
@@ -91,9 +99,11 @@ export function XDSChart({
yBaseline = 'auto',
yDomain: yDomainProp,
xDomain: xDomainProp,
+ interactive = false,
children,
}: XDSChartProps) {
const containerRef = useRef<HTMLDivElement>(null);
+ const svgRef = useRef<SVGSVGElement>(null);
const [containerWidth, setContainerWidth] = useState(0);
useLayoutEffect(() => {
@@ -106,6 +116,20 @@ export function XDSChart({
return () => observer.disconnect();
}, []);
+ // Block scroll/zoom on the container when interactive.
+ // Must be non-passive to actually prevent default on touch events.
+ useLayoutEffect(() => {
+ const el = containerRef.current;
+ if (!el || !interactive) return;
+ const prevent = (e: TouchEvent) => e.preventDefault();
+ el.addEventListener('touchstart', prevent, {passive: false});
+ el.addEventListener('touchmove', prevent, {passive: false});
+ return () => {
+ el.removeEventListener('touchstart', prevent);
+ el.removeEventListener('touchmove', prevent);
+ };
+ }, [interactive]);
+
const margin = useMemo(
() => ({...DEFAULT_MARGIN, ...marginOverride}),
[marginOverride],
@@ -181,6 +205,39 @@ export function XDSChart({
return scaleLinear().domain([min, max]).range([innerHeight, 0]).nice();
}, [data, yKeys, innerHeight, yBaseline, yDomainProp]);
+ const pixelToData = useCallback(
+ (px: number, py: number) => {
+ const y = yScale.invert(py);
+ let x: number | string | null = null;
+ if (isBandScale(xScale)) {
+ const domain = xScale.domain();
+ const step = xScale.step();
+ const idx = Math.min(domain.length - 1, Math.max(0, Math.floor(px / step)));
+ x = domain[idx];
+ } else {
+ x = (xScale as ScaleLinear<number, number>).invert(px);
+ }
+ return {x, y, px, py};
+ },
+ [xScale, yScale],
+ );
+
+ const pointerToData = useCallback(
+ (e: React.PointerEvent) => {
+ const svg = svgRef.current;
+ if (!svg) return {x: null, y: 0, px: 0, py: 0};
+ const pt = svg.createSVGPoint();
+ pt.x = e.clientX;
+ pt.y = e.clientY;
+ // Transform to the inner <g> coordinate space (accounts for margins)
+ const gEl = svg.querySelector('g');
+ const ctm = gEl?.getScreenCTM?.()?.inverse();
+ const local = ctm ? pt.matrixTransform(ctm) : {x: 0, y: 0};
+ return pixelToData(local.x, local.y);
+ },
+ [pixelToData],
+ );
+
const ctx = useMemo(
() => ({
width: innerWidth,
@@ -190,14 +247,17 @@ export function XDSChart({
data,
xScale,
yScale,
+ svgRef,
+ pointerToData,
+ pixelToData,
}),
- [innerWidth, innerHeight, margin, xKey, data, xScale, yScale],
+ [innerWidth, innerHeight, margin, xKey, data, xScale, yScale, pointerToData, pixelToData],
);
return (
- <div ref={containerRef} style={{width: '100%'}}>
+ <div ref={containerRef} style={{width: '100%', touchAction: interactive ? 'none' : undefined, userSelect: interactive ? 'none' : undefined} as React.CSSProperties}>
{containerWidth > 0 && (
- <svg width={containerWidth} height={height}>
+ <svg ref={svgRef} width={containerWidth} height={height} style={interactive ? {touchAction: 'none'} : undefined}>
<defs>
<clipPath id="xds-chart-plot">
<rect x={0} y={0} width={innerWidth} height={innerHeight} />
diff --git a/packages/lab/src/Chart/XDSChartBrush.tsx b/packages/lab/src/Chart/XDSChartBrush.tsx
new file mode 100644
index 0000000000..46f2e7e93a
--- /dev/null
+++ b/packages/lab/src/Chart/XDSChartBrush.tsx
@@ -0,0 +1,106 @@
+/**
+ * @file XDSChartBrush.tsx
+ * @output Drag to select an x-range. Pointer events (mouse + touch + pen).
+ */
+
+import {useState, useCallback, useRef, useEffect} from 'react';
+import {useChart} from './ChartContext';
+import {isBandScale} from './utils';
+import type {ScaleLinear} from 'd3-scale';
+
+export interface XDSChartBrushProps {
+ onBrush?: (range: [number, number], data: Record<string, unknown>[]) => void;
+ onClear?: () => void;
+ color?: string;
+ opacity?: number;
+}
+
+function localX(e: React.PointerEvent<SVGRectElement>): number {
+ const svg = e.currentTarget.ownerSVGElement;
+ if (!svg) return 0;
+ const pt = svg.createSVGPoint();
+ pt.x = e.clientX;
+ pt.y = e.clientY;
+ return pt.matrixTransform(e.currentTarget.getScreenCTM()?.inverse()).x;
+}
+
+export function XDSChartBrush({
+ onBrush,
+ onClear,
+ color = 'var(--color-accent)',
+ opacity = 0.15,
+}: XDSChartBrushProps) {
+ const {width, height, data, xKey, xScale} = useChart();
+ const [brush, setBrush] = useState<{x0: number; x1: number} | null>(null);
+ const dragging = useRef(false);
+
+ const startXRef = useRef(0);
+
+ const onPointerDown = useCallback((e: React.PointerEvent<SVGRectElement>) => {
+ (e.target as Element).setPointerCapture(e.pointerId);
+ dragging.current = true;
+ const x = localX(e);
+ startXRef.current = x;
+ setBrush({x0: x, x1: x});
+ }, []);
+
+ const onPointerMove = useCallback((e: React.PointerEvent<SVGRectElement>) => {
+ if (!dragging.current) return;
+ const x = localX(e);
+ setBrush({
+ x0: Math.min(startXRef.current, x),
+ x1: Math.max(startXRef.current, x),
+ });
+ }, []);
+
+ const onPointerUp = useCallback(() => {
+ dragging.current = false;
+ if (!brush || Math.abs(brush.x1 - brush.x0) < 3) {
+ setBrush(null);
+ onClear?.();
+ return;
+ }
+ if (!isBandScale(xScale)) {
+ const linear = xScale as ScaleLinear<number, number>;
+ const min = linear.invert(brush.x0);
+ const max = linear.invert(brush.x1);
+ const selected = data.filter(d => {
+ const v = d[xKey];
+ return typeof v === 'number' && v >= min && v <= max;
+ });
+ onBrush?.([min, max], selected);
+ }
+ }, [brush, xScale, data, xKey, onBrush, onClear]);
+
+ return (
+ <g>
+ <rect
+ x={0}
+ y={0}
+ width={width}
+ height={height}
+ fill="transparent"
+ style={{cursor: 'crosshair'}}
+ onTouchStart={e => e.preventDefault()}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerUp}
+ />
+ {brush && Math.abs(brush.x1 - brush.x0) > 1 && (
+ <rect
+ x={brush.x0}
+ y={0}
+ width={brush.x1 - brush.x0}
+ height={height}
+ fill={color}
+ fillOpacity={opacity}
+ stroke={color}
+ strokeWidth={1}
+ strokeOpacity={0.4}
+ pointerEvents="none"
+ />
+ )}
+ </g>
+ );
+}
diff --git a/packages/lab/src/Chart/XDSChartCrosshair.tsx b/packages/lab/src/Chart/XDSChartCrosshair.tsx
new file mode 100644
index 0000000000..7d6da538a9
--- /dev/null
+++ b/packages/lab/src/Chart/XDSChartCrosshair.tsx
@@ -0,0 +1,75 @@
+/**
+ * @file XDSChartCrosshair.tsx
+ * @output Cursor-tracking lines with value readouts. Uses chart context.
+ */
+
+import {useState, useCallback, useRef} from 'react';
+import {useChart} from './ChartContext';
+import type {DataPoint} from './types';
+
+export interface XDSChartCrosshairProps {
+ vertical?: boolean;
+ horizontal?: boolean;
+ labels?: boolean;
+ xFormat?: (value: number | string | null) => string;
+ yFormat?: (value: number) => string;
+ color?: string;
+}
+
+export function XDSChartCrosshair({
+ vertical = true, horizontal = true, labels = true,
+ xFormat, yFormat, color = 'var(--color-border-emphasized)',
+}: XDSChartCrosshairProps) {
+ const {width, height, pointerToData} = useChart();
+ const [point, setPoint] = useState<DataPoint | null>(null);
+ const active = useRef(false);
+
+ const onPointerDown = useCallback((e: React.PointerEvent<SVGRectElement>) => {
+ (e.target as Element).setPointerCapture(e.pointerId);
+ active.current = true;
+ setPoint(pointerToData(e));
+ }, [pointerToData]);
+
+ const onPointerMove = useCallback((e: React.PointerEvent<SVGRectElement>) => {
+ if (e.pointerType === 'mouse' || active.current) {
+ setPoint(pointerToData(e));
+ }
+ }, [pointerToData]);
+
+ const onPointerUp = useCallback(() => {
+ active.current = false;
+ setPoint(null);
+ }, []);
+
+ const fmtX = xFormat ?? ((v: number | string | null) => v != null ? (typeof v === 'number' ? v.toFixed(1) : v) : '');
+ const fmtY = yFormat ?? ((v: number) => v.toFixed(1));
+
+ return (
+ <g>
+ <rect x={0} y={0} width={width} height={height} fill="transparent"
+ onPointerDown={onPointerDown} onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp} onPointerCancel={onPointerUp}
+ onPointerLeave={() => { if (!active.current) setPoint(null); }} />
+ {point && (<>
+ {vertical && <line x1={point.px} x2={point.px} y1={0} y2={height}
+ stroke={color} strokeWidth={1} strokeDasharray="3 3" pointerEvents="none" />}
+ {horizontal && <line x1={0} x2={width} y1={point.py} y2={point.py}
+ stroke={color} strokeWidth={1} strokeDasharray="3 3" pointerEvents="none" />}
+ {labels && point.x != null && (
+ <g transform={`translate(${point.px},${height})`} pointerEvents="none">
+ <rect x={-24} y={2} width={48} height={14} rx={3}
+ fill="var(--color-background-popover)" fillOpacity={0.85} stroke={color} strokeWidth={0.5} />
+ <text y={13} textAnchor="middle" fontSize={10} fill="var(--color-text-primary)">{fmtX(point.x)}</text>
+ </g>
+ )}
+ {labels && (
+ <g transform={`translate(0,${point.py})`} pointerEvents="none">
+ <rect x={-48} y={-7} width={44} height={14} rx={3}
+ fill="var(--color-background-popover)" fillOpacity={0.85} stroke={color} strokeWidth={0.5} />
+ <text x={-26} dy="0.35em" textAnchor="middle" fontSize={10} fill="var(--color-text-primary)">{fmtY(point.y)}</text>
+ </g>
+ )}
+ </>)}
+ </g>
+ );
+}
diff --git a/packages/lab/src/Chart/XDSChartReferenceLine.tsx b/packages/lab/src/Chart/XDSChartReferenceLine.tsx
new file mode 100644
index 0000000000..5b7bc8c7ff
--- /dev/null
+++ b/packages/lab/src/Chart/XDSChartReferenceLine.tsx
@@ -0,0 +1,74 @@
+/**
+ * @file XDSChartReferenceLine.tsx
+ * @output Horizontal or vertical reference line with crosshair-style badge label
+ */
+
+import {useChart} from './ChartContext';
+import {isBandScale} from './utils';
+import type {ScaleLinear} from 'd3-scale';
+
+export interface XDSChartReferenceLineProps {
+ y?: number;
+ x?: number;
+ color?: string;
+ strokeWidth?: number;
+ strokeDasharray?: string;
+ label?: string;
+ labelPosition?: 'start' | 'end';
+}
+
+export function XDSChartReferenceLine({
+ y, x, color = 'var(--color-border-emphasized)',
+ strokeWidth = 1, strokeDasharray = '6 3', label, labelPosition = 'end',
+}: XDSChartReferenceLineProps) {
+ const {width, height, xScale, yScale} = useChart();
+
+ // Shared badge dimensions — matches crosshair label style
+ const badgeH = 14;
+ const badgeRx = 3;
+ const fontSize = 10;
+
+ if (y != null) {
+ const py = yScale(y);
+ const textW = label ? label.length * 5.5 + 8 : 0;
+ const bx = labelPosition === 'end' ? width - textW - 2 : 2;
+ return (
+ <g>
+ <line x1={0} x2={width} y1={py} y2={py}
+ stroke={color} strokeWidth={strokeWidth} strokeDasharray={strokeDasharray} />
+ {label && (
+ <g transform={`translate(${bx},${py})`} pointerEvents="none">
+ <rect x={0} y={-badgeH / 2} width={textW} height={badgeH} rx={badgeRx}
+ fill="var(--color-background-popover)" fillOpacity={0.85}
+ stroke={color} strokeWidth={0.5} />
+ <text x={textW / 2} dy="0.35em" textAnchor="middle"
+ fontSize={fontSize} fontWeight={500} fill={color}>{label}</text>
+ </g>
+ )}
+ </g>
+ );
+ }
+
+ if (x != null && !isBandScale(xScale)) {
+ const px = (xScale as ScaleLinear<number, number>)(x);
+ const textW = label ? label.length * 5.5 + 8 : 0;
+ const by = labelPosition === 'end' ? 4 : height - badgeH - 4;
+ return (
+ <g>
+ <line x1={px} x2={px} y1={0} y2={height}
+ stroke={color} strokeWidth={strokeWidth} strokeDasharray={strokeDasharray} />
+ {label && (
+ <g transform={`translate(${px - textW / 2},${by})`} pointerEvents="none">
+ <rect x={0} y={0} width={textW} height={badgeH} rx={badgeRx}
+ fill="var(--color-background-popover)" fillOpacity={0.85}
+ stroke={color} strokeWidth={0.5} />
+ <text x={textW / 2} y={badgeH / 2} dy="0.35em" textAnchor="middle"
+ fontSize={fontSize} fontWeight={500} fill={color}>{label}</text>
+ </g>
+ )}
+ </g>
+ );
+ }
+
+ return null;
+}
diff --git a/packages/lab/src/Chart/XDSChartSelect.tsx b/packages/lab/src/Chart/XDSChartSelect.tsx
new file mode 100644
index 0000000000..9b7935508e
--- /dev/null
+++ b/packages/lab/src/Chart/XDSChartSelect.tsx
@@ -0,0 +1,103 @@
+/**
+ * @file XDSChartSelect.tsx
+ * @output Click/tap to select data points. Pointer events.
+ */
+
+import {useCallback} from 'react';
+import {useChart} from './ChartContext';
+import {xPixel} from './utils';
+
+export interface XDSChartSelectProps {
+ onSelect?: (datum: Record<string, unknown>, index: number) => void;
+ onSelectionChange?: (indices: number[]) => void;
+ selected?: number[];
+ color?: string;
+ radius?: number;
+}
+
+export function XDSChartSelect({
+ onSelect,
+ onSelectionChange,
+ selected = [],
+ color = 'var(--color-accent)',
+ radius = 6,
+}: XDSChartSelectProps) {
+ const {width, height, data, xKey, xScale, yScale} = useChart();
+
+ const handlePointerUp = useCallback(
+ (e: React.PointerEvent<SVGRectElement>) => {
+ const svg = e.currentTarget.ownerSVGElement;
+ if (!svg) return;
+ const pt = svg.createSVGPoint();
+ pt.x = e.clientX;
+ pt.y = e.clientY;
+ const local = pt.matrixTransform(
+ e.currentTarget.getScreenCTM()?.inverse(),
+ );
+
+ let closest = 0,
+ minDist = Infinity;
+ data.forEach((d, i) => {
+ const px = xPixel(d, xKey, xScale);
+ const numKeys = Object.keys(d).filter(
+ k => k !== xKey && typeof d[k] === 'number',
+ );
+ const py = numKeys.length > 0 ? yScale(d[numKeys[0]] as number) : 0;
+ const dist = Math.hypot(px - local.x, py - local.y);
+ if (dist < minDist) {
+ minDist = dist;
+ closest = i;
+ }
+ });
+ if (minDist > 30) return;
+ onSelect?.(data[closest], closest);
+ if (onSelectionChange) {
+ if (e.shiftKey || e.metaKey) {
+ onSelectionChange(
+ selected.includes(closest)
+ ? selected.filter(i => i !== closest)
+ : [...selected, closest],
+ );
+ } else {
+ onSelectionChange([closest]);
+ }
+ }
+ },
+ [data, xKey, xScale, yScale, selected, onSelect, onSelectionChange],
+ );
+
+ return (
+ <g>
+ <rect
+ x={0}
+ y={0}
+ width={width}
+ height={height}
+ fill="transparent"
+ style={{cursor: 'pointer'}}
+ onPointerUp={handlePointerUp}
+ />
+ {selected.map(idx => {
+ if (idx < 0 || idx >= data.length) return null;
+ const d = data[idx];
+ const px = xPixel(d, xKey, xScale);
+ const yKey = Object.keys(d).find(
+ k => k !== xKey && typeof d[k] === 'number',
+ );
+ const py = yKey ? yScale(d[yKey] as number) : 0;
+ return (
+ <circle
+ key={idx}
+ cx={px}
+ cy={py}
+ r={radius}
+ fill="none"
+ stroke={color}
+ strokeWidth={2}
+ pointerEvents="none"
+ />
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/lab/src/Chart/XDSChartZoom.tsx b/packages/lab/src/Chart/XDSChartZoom.tsx
new file mode 100644
index 0000000000..0d1e6f7937
--- /dev/null
+++ b/packages/lab/src/Chart/XDSChartZoom.tsx
@@ -0,0 +1,272 @@
+/**
+ * @file XDSChartZoom.tsx
+ * @output Zoom and pan with mouse wheel, pinch, and toolbar chrome.
+ */
+
+import {useCallback, useRef, useState} from 'react';
+import {useChart} from './ChartContext';
+import {isBandScale} from './utils';
+import type {ScaleLinear} from 'd3-scale';
+
+export interface XDSChartZoomProps {
+ onXDomainChange?: (domain: [number, number]) => void;
+ onYDomainChange?: (domain: [number, number]) => void;
+ zoomSpeed?: number;
+ xOnly?: boolean;
+ yOnly?: boolean;
+ /** Show zoom/pan toolbar (default: true) */
+ chrome?: boolean;
+ /** Initial x domain for reset */
+ initialXDomain?: [number, number];
+ /** Initial y domain for reset */
+ initialYDomain?: [number, number];
+}
+
+export function XDSChartZoom({
+ onXDomainChange,
+ onYDomainChange,
+ zoomSpeed = 0.1,
+ xOnly = false,
+ yOnly = false,
+ chrome = true,
+ initialXDomain,
+ initialYDomain,
+}: XDSChartZoomProps) {
+ const {width, height, xScale, yScale} = useChart();
+ const [panMode, setPanMode] = useState(false);
+
+ const dragRef = useRef<{
+ startX: number;
+ startY: number;
+ xDomain: [number, number];
+ yDomain: [number, number];
+ } | null>(null);
+ const pinchRef = useRef<{
+ dist: number;
+ xDomain: [number, number];
+ yDomain: [number, number];
+ } | null>(null);
+ const pointersRef = useRef<Map<number, {x: number; y: number}>>(new Map());
+
+ const getXDomain = useCallback(
+ (): [number, number] =>
+ isBandScale(xScale)
+ ? [0, 0]
+ : ((xScale as ScaleLinear<number, number>).domain() as [
+ number,
+ number,
+ ]),
+ [xScale],
+ );
+
+ const zoomBy = useCallback(
+ (factor: number, pivotX?: number, pivotY?: number) => {
+ if (!yOnly && !isBandScale(xScale)) {
+ const linear = xScale as ScaleLinear<number, number>;
+ const [xMin, xMax] = linear.domain() as [number, number];
+ const xRange = xMax - xMin;
+ const xPivot =
+ pivotX != null ? linear.invert(pivotX) : (xMin + xMax) / 2;
+ const leftRatio = (xPivot - xMin) / xRange;
+ const newRange = xRange * factor;
+ onXDomainChange?.([
+ xPivot - newRange * leftRatio,
+ xPivot + newRange * (1 - leftRatio),
+ ]);
+ }
+ if (!xOnly) {
+ const [yMin, yMax] = yScale.domain() as [number, number];
+ const yRange = yMax - yMin;
+ const yPivot =
+ pivotY != null ? yScale.invert(pivotY) : (yMin + yMax) / 2;
+ const topRatio = (yMax - yPivot) / yRange;
+ const newRange = yRange * factor;
+ onYDomainChange?.([
+ yPivot - newRange * (1 - topRatio),
+ yPivot + newRange * topRatio,
+ ]);
+ }
+ },
+ [xScale, yScale, onXDomainChange, onYDomainChange, xOnly, yOnly],
+ );
+
+ const handleWheel = useCallback(
+ (e: React.WheelEvent<SVGRectElement>) => {
+ e.preventDefault();
+ const factor = e.deltaY > 0 ? 1 + zoomSpeed : 1 - zoomSpeed;
+ const svg = e.currentTarget.ownerSVGElement;
+ if (!svg) return;
+ const pt = svg.createSVGPoint();
+ pt.x = e.clientX;
+ pt.y = e.clientY;
+ const local = pt.matrixTransform(
+ e.currentTarget.getScreenCTM()?.inverse(),
+ );
+ zoomBy(factor, local.x, local.y);
+ },
+ [zoomSpeed, zoomBy],
+ );
+
+ // Pointer tracking for pan + pinch
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<SVGRectElement>) => {
+ (e.target as Element).setPointerCapture(e.pointerId);
+ pointersRef.current.set(e.pointerId, {x: e.clientX, y: e.clientY});
+
+ if (pointersRef.current.size === 2) {
+ // Start pinch
+ const pts = [...pointersRef.current.values()];
+ const dist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y);
+ pinchRef.current = {
+ dist,
+ xDomain: getXDomain(),
+ yDomain: yScale.domain() as [number, number],
+ };
+ dragRef.current = null;
+ } else if (pointersRef.current.size === 1 && panMode) {
+ // Start pan
+ dragRef.current = {
+ startX: e.clientX,
+ startY: e.clientY,
+ xDomain: getXDomain(),
+ yDomain: yScale.domain() as [number, number],
+ };
+ }
+ },
+ [panMode, getXDomain, yScale],
+ );
+
+ const onPointerMove = useCallback(
+ (e: React.PointerEvent<SVGRectElement>) => {
+ pointersRef.current.set(e.pointerId, {x: e.clientX, y: e.clientY});
+
+ if (pointersRef.current.size === 2 && pinchRef.current) {
+ // Pinch zoom
+ const pts = [...pointersRef.current.values()];
+ const dist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y);
+ const ratio = pinchRef.current.dist / dist;
+ if (!yOnly && !isBandScale(xScale)) {
+ const [xMin, xMax] = pinchRef.current.xDomain;
+ const mid = (xMin + xMax) / 2;
+ const half = ((xMax - xMin) / 2) * ratio;
+ onXDomainChange?.([mid - half, mid + half]);
+ }
+ if (!xOnly) {
+ const [yMin, yMax] = pinchRef.current.yDomain;
+ const mid = (yMin + yMax) / 2;
+ const half = ((yMax - yMin) / 2) * ratio;
+ onYDomainChange?.([mid - half, mid + half]);
+ }
+ } else if (dragRef.current && panMode) {
+ // Pan
+ const dx = e.clientX - dragRef.current.startX;
+ const dy = e.clientY - dragRef.current.startY;
+ if (!yOnly && !isBandScale(xScale)) {
+ const [xMin, xMax] = dragRef.current.xDomain;
+ const xShift = -(dx / width) * (xMax - xMin);
+ onXDomainChange?.([xMin + xShift, xMax + xShift]);
+ }
+ if (!xOnly) {
+ const [yMin, yMax] = dragRef.current.yDomain;
+ const yShift = (dy / height) * (yMax - yMin);
+ onYDomainChange?.([yMin + yShift, yMax + yShift]);
+ }
+ }
+ },
+ [
+ panMode,
+ xScale,
+ width,
+ height,
+ onXDomainChange,
+ onYDomainChange,
+ xOnly,
+ yOnly,
+ ],
+ );
+
+ const onPointerUp = useCallback((e: React.PointerEvent<SVGRectElement>) => {
+ pointersRef.current.delete(e.pointerId);
+ if (pointersRef.current.size < 2) pinchRef.current = null;
+ if (pointersRef.current.size === 0) dragRef.current = null;
+ }, []);
+
+ const handleReset = useCallback(() => {
+ if (initialXDomain) onXDomainChange?.(initialXDomain);
+ if (initialYDomain) onYDomainChange?.(initialYDomain);
+ }, [initialXDomain, initialYDomain, onXDomainChange, onYDomainChange]);
+
+ const btnStyle: React.CSSProperties = {
+ width: 28,
+ height: 28,
+ border: '1px solid var(--color-border)',
+ borderRadius: 6,
+ background: 'var(--color-background-popover)',
+ color: 'var(--color-text-primary)',
+ fontSize: 14,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ lineHeight: 1,
+ };
+
+ return (
+ <g>
+ <rect
+ x={0}
+ y={0}
+ width={width}
+ height={height}
+ fill="transparent"
+ style={{
+ cursor: panMode ? 'grab' : 'default',
+ touchAction: panMode ? 'none' : 'pan-y',
+ }}
+ onWheel={handleWheel}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerUp}
+ />
+
+ {chrome && (
+ <foreignObject
+ x={width - 36}
+ y={4}
+ width={32}
+ height={140}
+ style={{overflow: 'visible'}}>
+ <div style={{display: 'flex', flexDirection: 'column', gap: 4}}>
+ <button
+ style={btnStyle}
+ onClick={() => zoomBy(1 - zoomSpeed)}
+ title="Zoom in">
+ +
+ </button>
+ <button
+ style={btnStyle}
+ onClick={() => zoomBy(1 + zoomSpeed)}
+ title="Zoom out">
+ &minus;
+ </button>
+ <button
+ style={{
+ ...btnStyle,
+ background: panMode
+ ? 'var(--color-accent-muted)'
+ : btnStyle.background,
+ }}
+ onClick={() => setPanMode(!panMode)}
+ title={panMode ? 'Disable pan' : 'Enable pan'}>
+ &#9995;
+ </button>
+ <button style={btnStyle} onClick={handleReset} title="Reset zoom">
+ &#8634;
+ </button>
+ </div>
+ </foreignObject>
+ )}
+ </g>
+ );
+}
diff --git a/packages/lab/src/Chart/index.ts b/packages/lab/src/Chart/index.ts
index ea393b80ba..4b912a2bd7 100644
--- a/packages/lab/src/Chart/index.ts
+++ b/packages/lab/src/Chart/index.ts
@@ -31,7 +31,7 @@ export {
type XDSChartLegendItem,
} from './XDSChartLegend';
export {useChart} from './ChartContext';
-export type {ChartContext, ChartMargin, ChartScale} from './types';
+export type {ChartContext, ChartMargin, ChartScale, DataPoint} from './types';
export {m4Reduce, type M4Point} from './m4';
export {isBandScale, xPixel} from './utils';
export {useXDSChartColors} from './useXDSChartColors';
@@ -59,3 +59,14 @@ export {
CIRCLE_FRAG_BODY,
POINT_SIZE_COMPENSATION,
} from './webgl';
+export {XDSChartBrush, type XDSChartBrushProps} from './XDSChartBrush';
+export {
+ XDSChartCrosshair,
+ type XDSChartCrosshairProps,
+} from './XDSChartCrosshair';
+export {XDSChartZoom, type XDSChartZoomProps} from './XDSChartZoom';
+export {XDSChartSelect, type XDSChartSelectProps} from './XDSChartSelect';
+export {
+ XDSChartReferenceLine,
+ type XDSChartReferenceLineProps,
+} from './XDSChartReferenceLine';
diff --git a/packages/lab/src/Chart/types.ts b/packages/lab/src/Chart/types.ts
index 7365df7edd..442439ba76 100644
--- a/packages/lab/src/Chart/types.ts
+++ b/packages/lab/src/Chart/types.ts
@@ -20,6 +20,18 @@ export type ChartScale =
| ScaleBand<string>
| ScaleTime<number, number>;
+/** Resolved data coordinates from pixel position */
+export interface DataPoint {
+ /** X value in data space (number for linear, string for band) */
+ x: number | string | null;
+ /** Y value in data space */
+ y: number;
+ /** Pixel x within the plot area */
+ px: number;
+ /** Pixel y within the plot area */
+ py: number;
+}
+
/** Scale context provided by XDSChart to children */
export interface ChartContext {
/** Inner width (SVG width minus margins) */
@@ -36,4 +48,15 @@ export interface ChartContext {
xScale: ChartScale;
/** Y scale — typically linear */
yScale: ScaleLinear<number, number>;
+ /** Ref to the SVG element — used for coordinate transforms */
+ svgRef: React.RefObject<SVGSVGElement | null>;
+ /**
+ * Convert a pointer event to data coordinates.
+ * Handles SVG coordinate transform (margin offset) automatically.
+ */
+ pointerToData: (e: React.PointerEvent) => DataPoint;
+ /**
+ * Convert pixel coordinates (relative to plot area) to data values.
+ */
+ pixelToData: (px: number, py: number) => DataPoint;
}
diff --git a/packages/lab/src/Radial/XDSRadialChart.tsx b/packages/lab/src/Radial/XDSRadialChart.tsx
index acd1bd0b1c..338b1aa529 100644
--- a/packages/lab/src/Radial/XDSRadialChart.tsx
+++ b/packages/lab/src/Radial/XDSRadialChart.tsx
@@ -46,6 +46,10 @@ export interface XDSRadialChartProps {
*/
padAngle?: number;
/** Chart contents */
+ /**
+ * Enable touch interaction mode — blocks scroll on mobile.
+ */
+ interactive?: boolean;
children: ReactNode;
}
diff --git a/packages/lab/src/ThreeD/XDS3DChart.tsx b/packages/lab/src/ThreeD/XDS3DChart.tsx
index fae19d7855..44a244bcae 100644
--- a/packages/lab/src/ThreeD/XDS3DChart.tsx
+++ b/packages/lab/src/ThreeD/XDS3DChart.tsx
@@ -204,7 +204,7 @@ export function XDS3DChart({
);
return (
- <div ref={containerRef} style={{width: '100%'}}>
+ <div ref={containerRef} style={{width: '100%', touchAction: interactive ? 'none' : undefined, userSelect: interactive ? 'none' : undefined} as React.CSSProperties}>
{containerWidth > 0 && (
<svg
width={containerWidth}
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index dadcbad200..31c489c2c3 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -146,3 +146,17 @@ export {
type Point3D,
type ProjectedPoint,
} from './ThreeD';
+
+// Chart interactions
+export {
+ XDSChartBrush,
+ type XDSChartBrushProps,
+ XDSChartCrosshair,
+ type XDSChartCrosshairProps,
+ XDSChartZoom,
+ type XDSChartZoomProps,
+ XDSChartSelect,
+ type XDSChartSelectProps,
+ XDSChartReferenceLine,
+ type XDSChartReferenceLineProps,
+} from './Chart';