An open source design system that's fully customizable and agent ready
TypeScript
fix(chart): rewrite zoom/pan + fix yDomain ratcheting (#1527)
Cindy Zhang29673c859338
diff --git a/apps/storybook/stories/ChartCoordinated.stories.tsx b/apps/storybook/stories/ChartCoordinated.stories.tsxindex b82b604542..7ada0a3d92 100644--- a/apps/storybook/stories/ChartCoordinated.stories.tsx+++ b/apps/storybook/stories/ChartCoordinated.stories.tsx@@ -115,7 +115,7 @@ export const CoordinatedViews: StoryObj = {<XDSChartAxis position="left" /><XDSChartDot dataKey="mpg" color={c[0]} radius={3} /><XDSChartBrush- onBrush={range => setBrushRange(range)}+ onBrush={range => setBrushRange(range.x)}onClear={() => setBrushRange(null)}/>{brushRange && (diff --git a/apps/storybook/stories/ChartInteractions.stories.tsx b/apps/storybook/stories/ChartInteractions.stories.tsxindex f9268d4f2e..135712efbb 100644--- a/apps/storybook/stories/ChartInteractions.stories.tsx+++ b/apps/storybook/stories/ChartInteractions.stories.tsx@@ -23,8 +23,92 @@ export default meta;type Car = {Horsepower: number; Miles_per_Gallon: number};-/** Drag to select an x-range */-export const BrushSelection: StoryObj = {+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},+ {month: 'Jul', revenue: 5800, expenses: 3300},+ {month: 'Aug', revenue: 5500, expenses: 3000},+ {month: 'Sep', revenue: 4900, expenses: 2700},+ {month: 'Oct', revenue: 5200, expenses: 3100},+ {month: 'Nov', revenue: 5700, expenses: 3200},+ {month: 'Dec', revenue: 6800, expenses: 3600},+];++/** 1D brush on a bar chart — select a range of months */+export const BrushBars: StoryObj = {+ render: () => {+ const colors = useXDSChartColors();+ const [selected, setSelected] = useState<string | null>(null);+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>1D Brush — Bar Chart</XDSHeading>+ <XDSText type="supporting" color="secondary">+ Drag to select a range. {selected ?? 'Click to clear.'}+ </XDSText>+ <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]} />+ <XDSChartBrush+ onBrush={(_, sel) => setSelected(`${sel.length} months selected`)}+ onClear={() => setSelected(null)}+ />+ </XDSChart>+ </XDSStack>+ );+ },+};++/** 1D brush on a line chart — select a time range */+export const BrushLine: StoryObj = {+ render: () => {+ const colors = useXDSChartColors();+ const [selected, setSelected] = useState<string | null>(null);+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>1D Brush — Line Chart</XDSHeading>+ <XDSText type="supporting" color="secondary">+ Drag to select a range. {selected ?? 'Click to clear.'}+ </XDSText>+ <XDSChart+ data={monthlyData}+ xKey="month"+ yKeys={['revenue', 'expenses']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartLine+ dataKey="revenue"+ color={colors.categorical(2)[0]}+ dots+ />+ <XDSChartLine+ dataKey="expenses"+ color={colors.categorical(2)[1]}+ dots+ />+ <XDSChartBrush+ onBrush={(_, sel) => setSelected(`${sel.length} months selected`)}+ onClear={() => setSelected(null)}+ />+ </XDSChart>+ </XDSStack>+ );+ },+};++/** 2D rectangular brush on a scatter plot */+export const Brush2D: StoryObj = {render: () => {const colors = useXDSChartColors();const [raw] = useDataset<Car>('cars.json');@@ -36,12 +120,12 @@ export const BrushSelection: StoryObj = {.map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),[raw],);- if (!data.length) return <XDSText type="supporting">Loading\u2026</XDSText>;+ if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;return (<XDSStack direction="vertical" gap={4}>- <XDSHeading level={3}>Brush Selection</XDSHeading>+ <XDSHeading level={3}>2D Brush — Scatter Plot</XDSHeading><XDSText type="supporting" color="secondary">- Drag to select.{' '}+ Drag a rectangle to select.{' '}{count != null ? `${count} points selected.` : 'Click to clear.'}</XDSText><XDSChart@@ -59,6 +143,7 @@ export const BrushSelection: StoryObj = {radius={3}/><XDSChartBrush+ mode="xy"onBrush={(_, sel) => setCount(sel.length)}onClear={() => setCount(null)}/>@@ -80,7 +165,7 @@ export const Crosshair: StoryObj = {.map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),[raw],);- if (!data.length) return <XDSText type="supporting">Loading\u2026</XDSText>;+ if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;return (<XDSStack direction="vertical" gap={4}><XDSHeading level={3}>Crosshair</XDSHeading>@@ -124,7 +209,7 @@ export const ZoomPan: StoryObj = {);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>;+ if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;return (<XDSStack direction="vertical" gap={4}><XDSHeading level={3}>Zoom & Pan</XDSHeading>@@ -170,7 +255,7 @@ export const ClickSelect: StoryObj = {[raw],);const [selected, setSelected] = useState<number[]>([]);- if (!data.length) return <XDSText type="supporting">Loading\u2026</XDSText>;+ if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;return (<XDSStack direction="vertical" gap={4}><XDSHeading level={3}>Click to Select</XDSHeading>@@ -198,15 +283,6 @@ export const ClickSelect: StoryObj = {},};-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: () => {diff --git a/packages/lab/src/Chart/XDSChart.tsx b/packages/lab/src/Chart/XDSChart.tsxindex e5959cf458..a78efc7d15 100644--- a/packages/lab/src/Chart/XDSChart.tsx+++ b/packages/lab/src/Chart/XDSChart.tsx@@ -167,17 +167,10 @@ export function XDSChart({const yScale = useMemo((): ScaleLinear<number, number> => {if (yDomainProp) {- // Explicit domain is authoritative — apply baseline logic but don't expand from data- let [min, max] = yDomainProp;- if (yBaseline === 'zero') {- const abs = Math.max(Math.abs(min), Math.abs(max));- min = -abs;- max = abs;- } else if (yBaseline === 'auto') {- if (min > 0) min = 0;- if (max < 0) max = 0;- }- return scaleLinear().domain([min, max]).range([innerHeight, 0]).nice();+ // Explicit domain is authoritative — use as-is.+ // No baseline adjustment, no .nice(). The caller owns the domain+ // (e.g. zoom/pan controls) and rounding would cause ratcheting.+ return scaleLinear().domain(yDomainProp).range([innerHeight, 0]);}// Auto-compute from datadiff --git a/packages/lab/src/Chart/XDSChartZoom.tsx b/packages/lab/src/Chart/XDSChartZoom.tsxindex 0d1e6f7937..65823cd003 100644--- a/packages/lab/src/Chart/XDSChartZoom.tsx+++ b/packages/lab/src/Chart/XDSChartZoom.tsx@@ -1,25 +1,95 @@/*** @file XDSChartZoom.tsx- * @output Zoom and pan with mouse wheel, pinch, and toolbar chrome.+ * @output Scroll/pinch zoom + drag pan with optional toolbar.+ * @position Child of XDSChart; modifies x/yDomain via callbacks+ *+ * Zoom is aspect-ratio-normalized: both axes scale by the same visual+ * factor regardless of their domain ranges. Reset button restores+ * the initial domains captured on mount.*/-import {useCallback, useRef, useState} from 'react';+import {useCallback, useRef, useState, useEffect} from 'react';+import {createPortal} from 'react-dom';+import {XDSIconButton} from '@xds/core/IconButton';import {useChart} from './ChartContext';import {isBandScale} from './utils';import type {ScaleLinear} from 'd3-scale';+/** Toolbar position relative to the chart */+export type ZoomToolbarPosition =+ | 'top-right'+ | 'top-left'+ | 'bottom-right'+ | 'bottom-left';+export interface XDSChartZoomProps {onXDomainChange?: (domain: [number, number]) => void;onYDomainChange?: (domain: [number, number]) => void;++ /**+ * Zoom speed factor per scroll tick. Higher = faster zoom.+ * @default 0.1+ */zoomSpeed?: number;++ /** Only zoom/pan the x-axis */xOnly?: boolean;+ /** Only zoom/pan the y-axis */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];++ /**+ * Show the zoom/pan toolbar.+ * Pass `false` to hide, or a position string to show at that corner.+ * @default 'top-right'+ */+ toolbar?: false | ZoomToolbarPosition;+}++// Chart toolbar icons (16x16 SVG)+function ZoomInIcon() {+ return (+ <svg+ width={16}+ height={16}+ viewBox="0 0 16 16"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.5}+ strokeLinecap="round">+ <path d="M8 3v10M3 8h10" />+ </svg>+ );+}++function ZoomOutIcon() {+ return (+ <svg+ width={16}+ height={16}+ viewBox="0 0 16 16"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.5}+ strokeLinecap="round">+ <path d="M3 8h10" />+ </svg>+ );+}++function ResetIcon() {+ return (+ <svg+ width={16}+ height={16}+ viewBox="0 0 16 16"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.5}+ strokeLinecap="round"+ strokeLinejoin="round">+ <path d="M2 8a6 6 0 1 1 1.5 4M2 12V8h4" />+ </svg>+ );}export function XDSChartZoom({@@ -28,12 +98,24 @@ export function XDSChartZoom({zoomSpeed = 0.1,xOnly = false,yOnly = false,- chrome = true,- initialXDomain,- initialYDomain,+ toolbar = 'top-right',}: XDSChartZoomProps) {- const {width, height, xScale, yScale} = useChart();- const [panMode, setPanMode] = useState(false);+ const {width, height, xScale, yScale, svgRef} = useChart();++ // Capture initial domains on mount for reset+ const initialDomainsRef = useRef<{+ x: [number, number] | null;+ y: [number, number];+ } | null>(null);++ useEffect(() => {+ if (initialDomainsRef.current) return; // only capture once+ const xDomain = isBandScale(xScale)+ ? null+ : ((xScale as ScaleLinear<number, number>).domain() as [number, number]);+ const yDomain = yScale.domain() as [number, number];+ initialDomainsRef.current = {x: xDomain, y: yDomain};+ }, [xScale, yScale]);const dragRef = useRef<{startX: number;@@ -41,12 +123,13 @@ export function XDSChartZoom({xDomain: [number, number];yDomain: [number, number];} | null>(null);++ const pointersRef = useRef<Map<number, {x: number; y: number}>>(new Map());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] =>@@ -59,41 +142,46 @@ export function XDSChartZoom({[xScale],);+ // Zoom a single axis around a pivot point by a factor.+ // factor > 1 = zoom out, factor < 1 = zoom in.+ const zoomAxis = useCallback(+ (+ domain: [number, number],+ factor: number,+ pivot: number,+ ): [number, number] => {+ const [lo, hi] = domain;+ const range = hi - lo;+ const leftRatio = (pivot - lo) / range;+ const newRange = range * factor;+ return [pivot - newRange * leftRatio, pivot + newRange * (1 - leftRatio)];+ },+ [],+ );+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),- ]);+ onXDomainChange?.(zoomAxis([xMin, xMax], factor, xPivot));}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,- ]);+ onYDomainChange?.(zoomAxis([yMin, yMax], factor, yPivot));}},- [xScale, yScale, onXDomainChange, onYDomainChange, xOnly, yOnly],+ [xScale, yScale, onXDomainChange, onYDomainChange, xOnly, yOnly, zoomAxis],);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();@@ -102,19 +190,47 @@ export function XDSChartZoom({const local = pt.matrixTransform(e.currentTarget.getScreenCTM()?.inverse(),);- zoomBy(factor, local.x, local.y);++ // Clamp delta to prevent trackpad acceleration from blowing out the domain.+ // A single tick should zoom by at most zoomSpeed (10% default).+ const clampedDelta =+ Math.sign(e.deltaY) * Math.min(Math.abs(e.deltaY), 50);+ const rawFactor = 1 + (clampedDelta / 50) * zoomSpeed;++ // Apply per-axis, normalizing by each axis's pixel-to-domain ratio+ // so both axes zoom at the same visual rate.+ if (!yOnly && !isBandScale(xScale)) {+ const linear = xScale as ScaleLinear<number, number>;+ const [xMin, xMax] = linear.domain() as [number, number];+ const xPivot = linear.invert(local.x);+ onXDomainChange?.(zoomAxis([xMin, xMax], rawFactor, xPivot));+ }++ if (!xOnly) {+ const [yMin, yMax] = yScale.domain() as [number, number];+ const yPivot = yScale.invert(local.y);+ onYDomainChange?.(zoomAxis([yMin, yMax], rawFactor, yPivot));+ }},- [zoomSpeed, zoomBy],+ [+ zoomSpeed,+ xScale,+ yScale,+ onXDomainChange,+ onYDomainChange,+ xOnly,+ yOnly,+ zoomAxis,+ ],);- // Pointer tracking for pan + pinchconst onPointerDown = useCallback((e: React.PointerEvent<SVGRectElement>) => {(e.target as Element).setPointerCapture(e.pointerId);+ e.preventDefault(); // prevent selection on touchpointersRef.current.set(e.pointerId, {x: e.clientX, y: e.clientY});if (pointersRef.current.size === 2) {- // Start pinchconst pts = [...pointersRef.current.values()];const dist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y);pinchRef.current = {@@ -123,8 +239,7 @@ export function XDSChartZoom({yDomain: yScale.domain() as [number, number],};dragRef.current = null;- } else if (pointersRef.current.size === 1 && panMode) {- // Start pan+ } else if (pointersRef.current.size === 1) {dragRef.current = {startX: e.clientX,startY: e.clientY,@@ -133,7 +248,7 @@ export function XDSChartZoom({};}},- [panMode, getXDomain, yScale],+ [getXDomain, yScale],);const onPointerMove = useCallback(@@ -141,7 +256,6 @@ export function XDSChartZoom({pointersRef.current.set(e.pointerId, {x: e.clientX, y: e.clientY});if (pointersRef.current.size === 2 && pinchRef.current) {- // Pinch zoomconst 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;@@ -157,8 +271,7 @@ export function XDSChartZoom({const half = ((yMax - yMin) / 2) * ratio;onYDomainChange?.([mid - half, mid + half]);}- } else if (dragRef.current && panMode) {- // Pan+ } else if (dragRef.current) {const dx = e.clientX - dragRef.current.startX;const dy = e.clientY - dragRef.current.startY;if (!yOnly && !isBandScale(xScale)) {@@ -173,16 +286,7 @@ export function XDSChartZoom({}}},- [- panMode,- xScale,- width,- height,- onXDomainChange,- onYDomainChange,- xOnly,- yOnly,- ],+ [xScale, width, height, onXDomainChange, onYDomainChange, xOnly, yOnly],);const onPointerUp = useCallback((e: React.PointerEvent<SVGRectElement>) => {@@ -192,81 +296,91 @@ export function XDSChartZoom({}, []);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,+ const init = initialDomainsRef.current;+ if (!init) return;+ if (init.x) onXDomainChange?.(init.x);+ onYDomainChange?.(init.y);+ }, [onXDomainChange, onYDomainChange]);++ // Toolbar portal target+ const portalTarget = svgRef.current?.parentElement;++ // Toolbar position styles+ const toolbarPositionStyle = (+ pos: ZoomToolbarPosition,+ ): React.CSSProperties => {+ const base: React.CSSProperties = {+ position: 'absolute',+ display: 'flex',+ flexDirection: 'column',+ gap: 4,+ zIndex: 1,+ };+ switch (pos) {+ case 'top-right':+ return {...base, top: 8, right: 8};+ case 'top-left':+ return {...base, top: 8, left: 8};+ case 'bottom-right':+ return {...base, bottom: 8, right: 8};+ case 'bottom-left':+ return {...base, bottom: 8, left: 8};+ }};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}+ <>+ <g>+ <rect+ x={0}+ y={0}+ width={width}+ height={height}+ fill="transparent"+ style={+ {+ cursor: 'grab',+ touchAction: 'none',+ userSelect: 'none',+ } as React.CSSProperties+ }+ onWheel={handleWheel}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerUp}+ />+ </g>++ {/* Toolbar — portaled to chart container for proper positioning */}+ {toolbar &&+ portalTarget &&+ createPortal(+ <div style={toolbarPositionStyle(toolbar)}>+ <XDSIconButton+ label="Zoom in"+ icon={<ZoomInIcon />}+ variant="ghost"+ size="sm"+ onClick={() => zoomBy(1 / (1 + zoomSpeed))}+ />+ <XDSIconButton+ label="Zoom out"+ icon={<ZoomOutIcon />}+ variant="ghost"+ size="sm"onClick={() => zoomBy(1 + zoomSpeed)}- title="Zoom out">- −- </button>- <button- style={{- ...btnStyle,- background: panMode- ? 'var(--color-accent-muted)'- : btnStyle.background,- }}- onClick={() => setPanMode(!panMode)}- title={panMode ? 'Disable pan' : 'Enable pan'}>- ✋- </button>- <button style={btnStyle} onClick={handleReset} title="Reset zoom">- ↺- </button>- </div>- </foreignObject>- )}- </g>+ />+ <XDSIconButton+ label="Reset zoom"+ icon={<ResetIcon />}+ variant="ghost"+ size="sm"+ onClick={handleReset}+ />+ </div>,+ portalTarget,+ )}+ </>);}diff --git a/packages/lab/src/Chart/index.ts b/packages/lab/src/Chart/index.tsindex 535cadea63..53187ebfbb 100644--- a/packages/lab/src/Chart/index.ts+++ b/packages/lab/src/Chart/index.ts@@ -69,7 +69,7 @@ export {type BrushMode,type BrushRange,} from './XDSChartBrush';-export {XDSChartZoom, type XDSChartZoomProps} from './XDSChartZoom';+export {XDSChartZoom, type XDSChartZoomProps, type ZoomToolbarPosition} from './XDSChartZoom';export {XDSChartSelect, type XDSChartSelectProps} from './XDSChartSelect';export {XDSChartReferenceLine,