Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(quill-charts): drag-to-zoom on TimeSeriesLineChart (#62021)

Sam Penningtona1967f7b9a19
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 05709a6ee475..26ca0afbbf69 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -69,6 +69,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `Legend` is presentational: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
+- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis.
## Maintenance
diff --git a/packages/quill/packages/charts/src/README.md b/packages/quill/packages/charts/src/README.md
index a90fd49490fd..0ebe24806708 100644
--- a/packages/quill/packages/charts/src/README.md
+++ b/packages/quill/packages/charts/src/README.md
@@ -77,6 +77,26 @@ Pass a render prop to `tooltip`. It receives `TooltipContext` — `seriesData`,
/>
```
+## Drag-to-zoom
+
+Pass `onDateRangeZoom` to let the user drag a horizontal range across the plot.
+The chart emits `{ startLabel, endLabel, startIndex, endIndex }` from the
+labels array — it does not manage zoom state itself, so the parent decides
+what to do with the range (typically updating a date filter).
+
+```tsx
+<TimeSeriesLineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ onDateRangeZoom={({ startLabel, endLabel }) => updateDateRange(startLabel, endLabel)}
+/>
+```
+
+The cursor switches to `crosshair` while enabled, except over an
+actionable point (`onPointClick` is set) where it stays `pointer`. A
+plain click without movement still pins the tooltip or fires `onPointClick`.
+
## Custom overlays
Render any React component as a child of the chart and read layout / hover state through hooks:
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx
index 9acfcaf7f363..ab1fe8827b60 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx
@@ -1,6 +1,6 @@
import type { ChartTheme, Series } from '../../core/types'
import { ReferenceLine } from '../../overlays/ReferenceLine'
-import { renderHogChart } from '../../testing'
+import { dimensions as testDimensions, rawDrag, renderHogChart } from '../../testing'
import { LineChart } from './LineChart'
const THEME: ChartTheme = {
@@ -268,6 +268,184 @@ describe('LineChart', () => {
})
})
+ describe('drag-to-zoom', () => {
+ const LONG_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
+ const LONG_SERIES: Series[] = [{ key: 'a', label: 'A', data: [10, 20, 30, 40, 50] }]
+
+ it('fires onDateRangeZoom with the start and end labels of the dragged range', () => {
+ const onDateRangeZoom = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart series={LONG_SERIES} labels={LONG_LABELS} theme={THEME} onDateRangeZoom={onDateRangeZoom} />
+ )
+ chart.dragSelection(1, 3)
+ expect(onDateRangeZoom).toHaveBeenCalledTimes(1)
+ expect(onDateRangeZoom).toHaveBeenCalledWith({
+ startLabel: 'Tue',
+ endLabel: 'Thu',
+ startIndex: 1,
+ endIndex: 3,
+ })
+ })
+
+ it('normalizes a right-to-left drag', () => {
+ const onDateRangeZoom = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart series={LONG_SERIES} labels={LONG_LABELS} theme={THEME} onDateRangeZoom={onDateRangeZoom} />
+ )
+ chart.dragSelection(3, 1)
+ expect(onDateRangeZoom).toHaveBeenCalledWith({
+ startLabel: 'Tue',
+ endLabel: 'Thu',
+ startIndex: 1,
+ endIndex: 3,
+ })
+ })
+
+ it('does not fire onPointClick when a drag completes', () => {
+ const onDateRangeZoom = jest.fn()
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart
+ series={LONG_SERIES}
+ labels={LONG_LABELS}
+ theme={THEME}
+ onDateRangeZoom={onDateRangeZoom}
+ onPointClick={onPointClick}
+ />
+ )
+ chart.dragSelection(1, 3)
+ expect(onDateRangeZoom).toHaveBeenCalled()
+ expect(onPointClick).not.toHaveBeenCalled()
+ })
+
+ it('still fires onPointClick on a plain click when onDateRangeZoom is set', async () => {
+ const onDateRangeZoom = jest.fn()
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart
+ series={LONG_SERIES}
+ labels={LONG_LABELS}
+ theme={THEME}
+ onDateRangeZoom={onDateRangeZoom}
+ onPointClick={onPointClick}
+ />
+ )
+ await chart.clickAtIndex(2)
+ expect(onDateRangeZoom).not.toHaveBeenCalled()
+ expect(onPointClick).toHaveBeenCalledWith(expect.objectContaining({ dataIndex: 2, label: 'Wed' }))
+ })
+
+ it('switches the wrapper cursor to crosshair when onDateRangeZoom is provided', () => {
+ const { chart } = renderHogChart(
+ <LineChart series={LONG_SERIES} labels={LONG_LABELS} theme={THEME} onDateRangeZoom={jest.fn()} />
+ )
+ expect(chart.element.classList).toContain('cursor-crosshair')
+ })
+
+ it('a drag that releases outside the wrapper does not swallow the next unrelated click', async () => {
+ const onDateRangeZoom = jest.fn()
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart
+ series={LONG_SERIES}
+ labels={LONG_LABELS}
+ theme={THEME}
+ onDateRangeZoom={onDateRangeZoom}
+ onPointClick={onPointClick}
+ />
+ )
+
+ const y = testDimensions.plotTop + testDimensions.plotHeight / 2
+ rawDrag(chart.element, {
+ from: { x: testDimensions.plotLeft + 10, y },
+ to: { x: testDimensions.plotLeft + 200, y },
+ release: { x: 9999, y: 9999 },
+ })
+ expect(onDateRangeZoom).toHaveBeenCalledTimes(1)
+
+ await new Promise<void>((resolve) => setTimeout(resolve, 0))
+
+ await chart.clickAtIndex(2)
+ expect(onPointClick).toHaveBeenCalledTimes(1)
+ })
+
+ it('click-without-drag still dismisses a pinned tooltip when onDateRangeZoom is set', async () => {
+ const onDateRangeZoom = jest.fn()
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart
+ series={[
+ { key: 'a', label: 'A', data: [10, 20, 30, 40, 50] },
+ { key: 'b', label: 'B', data: [5, 15, 25, 35, 45] },
+ ]}
+ labels={LONG_LABELS}
+ theme={THEME}
+ config={{ tooltip: { pinnable: true } }}
+ onDateRangeZoom={onDateRangeZoom}
+ onPointClick={onPointClick}
+ />
+ )
+ await chart.clickAtIndex(2)
+ const pinned = await chart.waitForTooltip()
+ expect(pinned.isPinned).toBe(true)
+
+ await chart.clickAtIndex(2)
+ expect(onDateRangeZoom).not.toHaveBeenCalled()
+ expect(onPointClick).not.toHaveBeenCalled()
+ })
+
+ it('treats a sub-threshold mousedown+move as a click, not a drag', async () => {
+ const onDateRangeZoom = jest.fn()
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart
+ series={LONG_SERIES}
+ labels={LONG_LABELS}
+ theme={THEME}
+ onDateRangeZoom={onDateRangeZoom}
+ onPointClick={onPointClick}
+ />
+ )
+ const y = testDimensions.plotTop + testDimensions.plotHeight / 2
+ // Move only 2px — below DRAG_THRESHOLD_PX, so the gesture must stay a click.
+ rawDrag(chart.element, {
+ from: { x: testDimensions.plotLeft + 100, y },
+ to: { x: testDimensions.plotLeft + 102, y },
+ })
+ expect(onDateRangeZoom).not.toHaveBeenCalled()
+
+ await chart.clickAtIndex(2)
+ expect(onPointClick).toHaveBeenCalledWith(expect.objectContaining({ dataIndex: 2, label: 'Wed' }))
+ })
+
+ it('ignores a non-primary-button drag', () => {
+ const onDateRangeZoom = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart series={LONG_SERIES} labels={LONG_LABELS} theme={THEME} onDateRangeZoom={onDateRangeZoom} />
+ )
+ const y = testDimensions.plotTop + testDimensions.plotHeight / 2
+ rawDrag(chart.element, {
+ from: { x: testDimensions.plotLeft + 50, y },
+ to: { x: testDimensions.plotLeft + 300, y },
+ button: 2,
+ })
+ expect(onDateRangeZoom).not.toHaveBeenCalled()
+ })
+
+ it('does not start a drag from outside the plot area', () => {
+ const onDateRangeZoom = jest.fn()
+ const { chart } = renderHogChart(
+ <LineChart series={LONG_SERIES} labels={LONG_LABELS} theme={THEME} onDateRangeZoom={onDateRangeZoom} />
+ )
+ const yAbovePlot = testDimensions.plotTop - 5
+ rawDrag(chart.element, {
+ from: { x: testDimensions.plotLeft + 50, y: yAbovePlot },
+ to: { x: testDimensions.plotLeft + 300, y: yAbovePlot },
+ })
+ expect(onDateRangeZoom).not.toHaveBeenCalled()
+ })
+ })
+
describe('children & error boundary', () => {
it('renders custom overlay children', () => {
const { chart } = renderHogChart(
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index cbf4070f7535..4ad7cdee796c 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -23,6 +23,7 @@ import type {
ChartScales,
ChartTheme,
CreateScalesFn,
+ DateRangeZoomData,
LineChartConfig,
PointClickData,
ResolvedSeries,
@@ -43,6 +44,7 @@ export interface LineChartProps<Meta = unknown> {
theme: ChartTheme
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ onDateRangeZoom?: (data: DateRangeZoomData) => void
className?: string
/** `data-attr` applied to the chart wrapper. See `ChartProps.dataAttr`. */
dataAttr?: string
@@ -65,6 +67,7 @@ function LineChartInner<Meta = unknown>({
theme,
tooltip,
onPointClick,
+ onDateRangeZoom,
className,
dataAttr,
children,
@@ -231,6 +234,7 @@ function LineChartInner<Meta = unknown>({
drawHover={drawHover}
tooltip={tooltip}
onPointClick={onPointClick}
+ onDateRangeZoom={onDateRangeZoom}
className={className}
dataAttr={dataAttr}
resolveValue={resolveValue}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
index 658e6a9b5b47..8fbeee1fa133 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
@@ -1,4 +1,5 @@
import { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
import type { Series } from '../../core/types'
import { Stage, useReactiveTheme } from '../../story-helpers'
@@ -47,6 +48,30 @@ export const Basic: Story = {
},
}
+export const DragToZoom: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const [range, setRange] = useState<[string, string] | null>(null)
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
+ <span className="text-xs text-muted">
+ {range ? `Selected: ${range[0]} → ${range[1]}` : 'Drag a horizontal range to zoom'}
+ </span>
+ <Stage>
+ <TimeSeriesLineChart
+ series={SERIES}
+ labels={DAYS}
+ theme={theme}
+ config={{ yAxis: { showGrid: true } }}
+ onDateRangeZoom={({ startLabel, endLabel }) => setRange([startLabel, endLabel])}
+ />
+ </Stage>
+ </div>
+ )
+ },
+}
+
interface DateAxisCellProps {
title: string
labels: string[]
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 913e9f80d9e1..d2dafad07aed 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react'
import type {
ChartTheme,
+ DateRangeZoomData,
LineChartConfig,
PointClickData,
Series,
@@ -59,6 +60,7 @@ export interface TimeSeriesLineChartProps<Meta = unknown> {
config?: TimeSeriesLineChartConfig
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ onDateRangeZoom?: (data: DateRangeZoomData) => void
dataAttr?: string
className?: string
children?: React.ReactNode
@@ -72,6 +74,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
config,
tooltip,
onPointClick,
+ onDateRangeZoom,
dataAttr,
className,
children,
@@ -137,6 +140,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
theme={theme}
tooltip={tooltip}
onPointClick={onPointClick}
+ onDateRangeZoom={onDateRangeZoom}
className={className}
dataAttr={dataAttr}
onError={onError}
diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsx
index 4277f1cb2232..5866962e26b6 100644
--- a/packages/quill/packages/charts/src/core/Chart.tsx
+++ b/packages/quill/packages/charts/src/core/Chart.tsx
@@ -5,7 +5,7 @@ import { AxisTitles } from '../overlays/AxisTitles'
import { DefaultTooltip } from '../overlays/DefaultTooltip'
import { Tooltip } from '../overlays/Tooltip'
import { normalizeAxisLabel } from '../utils/axis-labels'
-import { composeDrawHoverWithCrosshair } from './canvas-renderer'
+import { composeDrawHoverWithCrosshair, composeDrawHoverWithSelection } from './canvas-renderer'
import { ChartHoverContext, ChartLayoutContext } from './chart-context'
import type { ChartHoverContextValue, ChartLayoutContextValue } from './chart-context'
import { ChartShell, countVisibleSeries, useCanvasBounds, useColoredSeries } from './chart-shell'
@@ -22,6 +22,7 @@ import type {
ChartScales,
ChartTheme,
CreateScalesFn,
+ DateRangeZoomData,
DrawHoverResult,
PointClickData,
ResolveValueFn,
@@ -55,6 +56,9 @@ export interface ChartProps<Meta = unknown> {
drawHover: (args: ChartDrawArgs) => DrawHoverResult
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Enables x-axis drag-to-zoom. Fired with the label range the user dragged across.
+ * x-axis only — has no effect on charts with a vertical (`interactionAxis: 'y'`) interaction. */
+ onDateRangeZoom?: (data: DateRangeZoomData) => void
className?: string
dataAttr?: string
children?: React.ReactNode
@@ -95,6 +99,7 @@ export function Chart<Meta = unknown>({
drawHover,
tooltip: renderTooltip = DefaultTooltip,
onPointClick,
+ onDateRangeZoom,
className,
dataAttr,
children,
@@ -155,7 +160,7 @@ export function Chart<Meta = unknown>({
const resolvedYFormatter = useResolvedYFormatter(scales, yTickFormatter)
- const { hoverIndex, hoverPosition, tooltipCtx, handlers } = useChartInteraction<Meta>({
+ const { hoverIndex, hoverPosition, tooltipCtx, dragRect, handlers } = useChartInteraction<Meta>({
scales,
dimensions,
labels,
@@ -165,6 +170,7 @@ export function Chart<Meta = unknown>({
showTooltip,
pinnable: pinnableTooltip,
onPointClick,
+ onDateRangeZoom,
resolveValue,
resolvePositionValue,
interactionAxis,
@@ -174,16 +180,15 @@ export function Chart<Meta = unknown>({
// ref keeps composedDrawHover stable across drawHover identity changes
const drawHoverRef = useLatest(drawHover)
- const composedDrawHover = useMemo(
- () =>
- composeDrawHoverWithCrosshair(() => drawHoverRef.current, {
- crosshairColor: theme.crosshairColor,
- showCrosshair,
- axisOrientation,
- labelToCoord,
- }),
- [showCrosshair, theme.crosshairColor, axisOrientation, labelToCoord, drawHoverRef.current]
- )
+ const composedDrawHover = useMemo(() => {
+ const withCrosshair = composeDrawHoverWithCrosshair(() => drawHoverRef.current, {
+ crosshairColor: theme.crosshairColor,
+ showCrosshair,
+ axisOrientation,
+ labelToCoord,
+ })
+ return composeDrawHoverWithSelection(withCrosshair)
+ }, [showCrosshair, theme.crosshairColor, axisOrientation, labelToCoord, drawHoverRef.current])
useChartDraw({
ctx,
@@ -195,6 +200,7 @@ export function Chart<Meta = unknown>({
hoverIndex,
hoverPosition,
theme,
+ dragRect,
drawStatic,
drawHover: composedDrawHover,
hoverAnimationMs,
@@ -253,6 +259,7 @@ export function Chart<Meta = unknown>({
className={className}
dataAttr={dataAttr}
pointer={hoverIndex >= 0 && !!onPointClick}
+ crosshair={!!onDateRangeZoom}
ariaLabel={ariaLabel}
handlers={handlers}
showOverlay={!!(dimensions && scales)}
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
index a4af25e07a53..f493ba5ec194 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
@@ -1,8 +1,16 @@
import { scaleLinear, scalePoint } from 'd3-scale'
import { dimensions, makeSeries } from '../testing'
-import { composeDrawHoverWithCrosshair, drawArea, drawGrid, drawLine, type DrawContext } from './canvas-renderer'
-import type { ChartDrawArgs, ChartScales, ChartTheme } from './types'
+import {
+ composeDrawHoverWithCrosshair,
+ composeDrawHoverWithSelection,
+ type DrawContext,
+ drawArea,
+ drawGrid,
+ drawLine,
+ drawSelectionRect,
+} from './canvas-renderer'
+import type { ChartDrawArgs, ChartTheme } from './types'
function mockCanvasContext(): jest.Mocked<CanvasRenderingContext2D> {
return {
@@ -13,6 +21,8 @@ function mockCanvasContext(): jest.Mocked<CanvasRenderingContext2D> {
fill: jest.fn(),
closePath: jest.fn(),
arc: jest.fn(),
+ fillRect: jest.fn(),
+ strokeRect: jest.fn(),
setLineDash: jest.fn(),
createPattern: jest.fn(() => ({}) as CanvasPattern),
strokeStyle: '',
@@ -44,6 +54,22 @@ function dashCalls(ctx: jest.Mocked<CanvasRenderingContext2D>): number[][] {
return ctx.setLineDash.mock.calls.map(([p]) => p as number[])
}
+function makeDrawArgs(ctx: CanvasRenderingContext2D, overrides: Partial<ChartDrawArgs> = {}): ChartDrawArgs {
+ return {
+ ctx,
+ dimensions,
+ scales: { x: () => undefined, y: () => 0, yTicks: () => [] },
+ series: [],
+ labels: ['Mon', 'Tue', 'Wed'],
+ hoverIndex: -1,
+ hoverPosition: null,
+ theme: {} as ChartTheme,
+ hoverProgress: 1,
+ resetHoverFade: () => 0,
+ ...overrides,
+ }
+}
+
describe('hog-charts canvas-renderer', () => {
describe('drawLine — gap handling', () => {
it.each([
@@ -637,23 +663,7 @@ describe('hog-charts canvas-renderer', () => {
hoverIndex: number,
xValue: number | undefined
): ChartDrawArgs {
- const scales: ChartScales = {
- x: () => xValue,
- y: () => 0,
- yTicks: () => [],
- }
- return {
- ctx,
- dimensions,
- scales,
- series: [],
- labels: ['Mon', 'Tue', 'Wed'],
- hoverIndex,
- hoverPosition: null,
- theme: {} as ChartTheme,
- hoverProgress: 1,
- resetHoverFade: () => 0,
- }
+ return makeDrawArgs(ctx, { hoverIndex, scales: { x: () => xValue, y: () => 0, yTicks: () => [] } })
}
it('always invokes the underlying drawHover', () => {
@@ -756,4 +766,87 @@ describe('hog-charts canvas-renderer', () => {
expect(second).toHaveBeenCalledTimes(1)
})
})
+
+ describe('drawSelectionRect', () => {
+ it('draws a fill and a stroke for a positive rect', () => {
+ const ctx = mockCanvasContext()
+ drawSelectionRect(ctx, { x: 100, y: 20, width: 50, height: 200 })
+ expect(ctx.fillRect).toHaveBeenCalledWith(100, 20, 50, 200)
+ // Stroke is inset by half a pixel so the 1px border lands on whole pixels.
+ expect(ctx.strokeRect).toHaveBeenCalledWith(100.5, 20.5, 49, 199)
+ })
+
+ it('is a no-op for a zero-width rect', () => {
+ const ctx = mockCanvasContext()
+ drawSelectionRect(ctx, { x: 100, y: 20, width: 0, height: 200 })
+ expect(ctx.fillRect).not.toHaveBeenCalled()
+ expect(ctx.strokeRect).not.toHaveBeenCalled()
+ })
+
+ it('is a no-op for a zero-height rect', () => {
+ const ctx = mockCanvasContext()
+ drawSelectionRect(ctx, { x: 100, y: 20, width: 50, height: 0 })
+ expect(ctx.fillRect).not.toHaveBeenCalled()
+ expect(ctx.strokeRect).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('composeDrawHoverWithSelection', () => {
+ const plotLeft = dimensions.plotLeft
+ const plotTop = dimensions.plotTop
+ const plotWidth = dimensions.plotWidth
+ const plotHeight = dimensions.plotHeight
+
+ function makeSelectionArgs(
+ ctx: CanvasRenderingContext2D,
+ dragRect: { x0: number; x1: number } | null
+ ): ChartDrawArgs {
+ return makeDrawArgs(ctx, { dragRect })
+ }
+
+ it('always invokes the underlying drawHover', () => {
+ const ctx = mockCanvasContext()
+ const base = jest.fn()
+ composeDrawHoverWithSelection(base)(makeSelectionArgs(ctx, null))
+ expect(base).toHaveBeenCalledTimes(1)
+ })
+
+ it('draws nothing when there is no active drag', () => {
+ const ctx = mockCanvasContext()
+ composeDrawHoverWithSelection(jest.fn())(makeSelectionArgs(ctx, null))
+ expect(ctx.fillRect).not.toHaveBeenCalled()
+ })
+
+ it('draws a full-plot-height band spanning the dragged range', () => {
+ const ctx = mockCanvasContext()
+ composeDrawHoverWithSelection(jest.fn())(
+ makeSelectionArgs(ctx, { x0: plotLeft + 100, x1: plotLeft + 250 })
+ )
+ expect(ctx.fillRect).toHaveBeenCalledWith(plotLeft + 100, plotTop, 150, plotHeight)
+ })
+
+ it('normalizes a right-to-left drag before drawing', () => {
+ const ctx = mockCanvasContext()
+ composeDrawHoverWithSelection(jest.fn())(
+ makeSelectionArgs(ctx, { x0: plotLeft + 250, x1: plotLeft + 100 })
+ )
+ expect(ctx.fillRect).toHaveBeenCalledWith(plotLeft + 100, plotTop, 150, plotHeight)
+ })
+
+ it('clamps a drag that extends past the plot edges', () => {
+ const ctx = mockCanvasContext()
+ composeDrawHoverWithSelection(jest.fn())(
+ makeSelectionArgs(ctx, { x0: -500, x1: plotLeft + plotWidth + 500 })
+ )
+ expect(ctx.fillRect).toHaveBeenCalledWith(plotLeft, plotTop, plotWidth, plotHeight)
+ })
+
+ it('draws nothing when the selection collapses to zero width', () => {
+ const ctx = mockCanvasContext()
+ composeDrawHoverWithSelection(jest.fn())(
+ makeSelectionArgs(ctx, { x0: plotLeft + 10, x1: plotLeft + 10 })
+ )
+ expect(ctx.fillRect).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.ts
index d7028d0222e8..78ece4c1642b 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts
@@ -927,3 +927,47 @@ export function composeDrawHoverWithCrosshair(
return getDrawHover()(args)
}
}
+
+// Drag-selection band styling. Intentionally a fixed accent rather than a theme token: there's no
+// selection color in the design tokens yet, and the band is a transient interaction affordance, not
+// chart data. Add a `--color-graph-selection-*` token and thread it through here if it needs theming.
+const SELECTION_FILL = 'rgba(59, 130, 246, 0.15)'
+const SELECTION_STROKE = 'rgba(59, 130, 246, 0.5)'
+const SELECTION_LINE_WIDTH = 1
+
+export function drawSelectionRect(
+ ctx: CanvasRenderingContext2D,
+ rect: { x: number; y: number; width: number; height: number }
+): void {
+ if (rect.width <= 0 || rect.height <= 0) {
+ return
+ }
+ ctx.fillStyle = SELECTION_FILL
+ ctx.fillRect(rect.x, rect.y, rect.width, rect.height)
+ ctx.strokeStyle = SELECTION_STROKE
+ ctx.lineWidth = SELECTION_LINE_WIDTH
+ ctx.strokeRect(rect.x + 0.5, rect.y + 0.5, rect.width - 1, rect.height - 1)
+}
+
+// The selection always spans the full plot height — this is x-axis range selection only.
+export function composeDrawHoverWithSelection(baseDrawHover: DrawHoverFn): DrawHoverFn {
+ return (args) => {
+ const result = baseDrawHover(args)
+ const dragRect = args.dragRect
+ if (!dragRect) {
+ return result
+ }
+ const x0 = Math.max(args.dimensions.plotLeft, Math.min(dragRect.x0, dragRect.x1))
+ const x1 = Math.min(args.dimensions.plotLeft + args.dimensions.plotWidth, Math.max(dragRect.x0, dragRect.x1))
+ if (x1 <= x0) {
+ return result
+ }
+ drawSelectionRect(args.ctx, {
+ x: x0,
+ y: args.dimensions.plotTop,
+ width: x1 - x0,
+ height: args.dimensions.plotHeight,
+ })
+ return result
+ }
+}
diff --git a/packages/quill/packages/charts/src/core/chart-shell.tsx b/packages/quill/packages/charts/src/core/chart-shell.tsx
index 199a5dc15a91..600ca1f71960 100644
--- a/packages/quill/packages/charts/src/core/chart-shell.tsx
+++ b/packages/quill/packages/charts/src/core/chart-shell.tsx
@@ -34,15 +34,29 @@ export interface ChartShellProps {
overlayCanvasRef: React.RefObject<HTMLCanvasElement>
className?: string
dataAttr?: string
- /** Show the pointer cursor — the hovered element is clickable. */
+ /** Show the pointer cursor — the hovered element is clickable. Takes precedence over `crosshair`. */
pointer: boolean
+ /** Show the crosshair cursor — a drag gesture (e.g. drag-to-zoom) is available. */
+ crosshair?: boolean
ariaLabel: string
- handlers: Required<Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseMove' | 'onMouseLeave' | 'onClick'>>
+ handlers: Required<Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseMove' | 'onMouseLeave' | 'onClick'>> &
+ Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseDown'>
/** Render the overlay layer — bases gate this on layout readiness (dimensions + scales). */
showOverlay: boolean
children?: React.ReactNode
}
+// Literal cursor classes (no runtime concat) so Tailwind v4's source scan sees them — see the package's tailwind contract.
+function cursorClass(pointer: boolean, crosshair: boolean): string {
+ if (pointer) {
+ return 'cursor-pointer'
+ }
+ if (crosshair) {
+ return 'cursor-crosshair'
+ }
+ return 'cursor-default'
+}
+
/** Shared DOM shell of the chart bases — behavior (interaction, drawing, contexts) stays in the bases. */
export function ChartShell({
wrapperRef,
@@ -51,6 +65,7 @@ export function ChartShell({
className,
dataAttr,
pointer,
+ crosshair = false,
ariaLabel,
handlers,
showOverlay,
@@ -59,10 +74,9 @@ export function ChartShell({
return (
<div
ref={wrapperRef}
- className={[WRAPPER_CLASS, pointer ? 'cursor-pointer' : 'cursor-default', className]
- .filter(Boolean)
- .join(' ')}
+ className={[WRAPPER_CLASS, cursorClass(pointer, crosshair), className].filter(Boolean).join(' ')}
data-attr={dataAttr}
+ onMouseDown={handlers.onMouseDown}
onMouseMove={handlers.onMouseMove}
onMouseLeave={handlers.onMouseLeave}
onClick={handlers.onClick}
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts b/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts
index d41cc5570c18..7ae08871f204 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartDraw.ts
@@ -1,6 +1,14 @@
import { useEffect, useRef } from 'react'
-import type { ChartDimensions, ChartDrawArgs, ChartScales, ChartTheme, DrawHoverResult, ResolvedSeries } from '../types'
+import type {
+ ChartDimensions,
+ ChartDrawArgs,
+ ChartScales,
+ ChartTheme,
+ DragRect,
+ DrawHoverResult,
+ ResolvedSeries,
+} from '../types'
import { clearAndPrepare } from './clearCanvas'
import { useHoverAnimation } from './useHoverAnimation'
@@ -16,6 +24,7 @@ interface UseChartDrawOptions {
hoverIndex: number
hoverPosition: { x: number; y: number } | null
theme: ChartTheme
+ dragRect?: DragRect | null
drawStatic: (args: ChartDrawArgs) => void
drawHover: (args: ChartDrawArgs) => DrawHoverResult
/** Duration (ms) of the hover-overlay fade-in/out. `0` disables. */
@@ -32,6 +41,7 @@ export function useChartDraw({
hoverIndex,
hoverPosition,
theme,
+ dragRect = null,
drawStatic,
drawHover,
hoverAnimationMs = 0,
@@ -84,6 +94,7 @@ export function useChartDraw({
hoverIndex,
hoverPosition,
theme,
+ dragRect,
drawHover,
hoverAnimationMs,
})
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
index 9e2afa72737c..16b2cd7cd335 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
@@ -11,11 +11,14 @@ import { defaultResolveValue } from '../types'
import type {
ChartDimensions,
ChartScales,
+ DateRangeZoomData,
+ DragRect,
PointClickData,
ResolvedSeries,
ResolveValueFn,
TooltipContext,
} from '../types'
+import { useDragToZoom } from './useDragToZoom'
import { useLatest } from './useLatest'
import { useTooltipLifecycle } from './useTooltipLifecycle'
@@ -29,6 +32,7 @@ interface UseChartInteractionOptions<Meta> {
showTooltip: boolean
pinnable: boolean
onPointClick?: (data: PointClickData<Meta>) => void
+ onDateRangeZoom?: (data: DateRangeZoomData) => void
resolveValue?: ResolveValueFn
/** Value used to *anchor* the tooltip per series. Defaults to `resolveValue`. Stacked
* charts pass the stacked-top resolver so the anchor lands at the visual top of each
@@ -46,7 +50,9 @@ interface UseChartInteractionResult<Meta> {
hoverIndex: number
hoverPosition: { x: number; y: number } | null
tooltipCtx: TooltipContext<Meta> | null
+ dragRect: DragRect | null
handlers: {
+ onMouseDown: (e: React.MouseEvent<HTMLDivElement>) => void
onMouseMove: (e: React.MouseEvent<HTMLDivElement>) => void
onMouseLeave: () => void
onClick: () => void
@@ -63,6 +69,7 @@ export function useChartInteraction<Meta = unknown>({
showTooltip,
pinnable,
onPointClick,
+ onDateRangeZoom,
resolveValue = defaultResolveValue,
resolvePositionValue,
interactionAxis = 'x',
@@ -101,9 +108,7 @@ export function useChartInteraction<Meta = unknown>({
prev.hoverPosition,
effectivePositionResolveRef.current,
scales.extent?.(labels[prev.dataIndex]),
- prev.hoverPosition
- ? scales.bandSlotAtCursor?.(labels[prev.dataIndex], prev.hoverPosition)
- : undefined
+ prev.hoverPosition ? scales.bandSlotAtCursor?.(labels[prev.dataIndex], prev.hoverPosition) : undefined
)
},
// resolveValueRef / effectivePositionResolveRef are stable
@@ -138,9 +143,25 @@ export function useChartInteraction<Meta = unknown>({
[labels, scales, labelToCoord]
)
+ const {
+ dragRect,
+ onMouseDown,
+ handleMouseMove: handleDragMouseMove,
+ shouldSwallowClick,
+ } = useDragToZoom({
+ onDateRangeZoom,
+ scales,
+ dimensions,
+ labels,
+ labelPositions,
+ wrapperRef,
+ interactionAxis,
+ onDragActivate: clearTooltip,
+ })
+
const onMouseMove = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
- if (!scales || !dimensions || isPinned) {
+ if (!scales || !dimensions) {
return
}
@@ -148,6 +169,15 @@ export function useChartInteraction<Meta = unknown>({
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
+ // An active drag-to-zoom owns the gesture — skip hover handling.
+ if (handleDragMouseMove(mouseX, mouseY)) {
+ return
+ }
+
+ if (isPinned) {
+ return
+ }
+
if (!isInPlotArea(mouseX, mouseY, dimensions)) {
clearTooltip()
return
@@ -190,6 +220,7 @@ export function useChartInteraction<Meta = unknown>({
canvasRef,
isPinned,
clearTooltip,
+ handleDragMouseMove,
labelPositions,
labelToCoord,
interactionAxis,
@@ -206,6 +237,10 @@ export function useChartInteraction<Meta = unknown>({
}, [isPinned, clearTooltip])
const onClick = useCallback(() => {
+ // A click that closes out a drag-to-zoom gesture must not also pin/unpin or fire onPointClick.
+ if (shouldSwallowClick()) {
+ return
+ }
const currentIndex = hoverIndexRef.current
if (currentIndex < 0) {
return
@@ -241,13 +276,17 @@ export function useChartInteraction<Meta = unknown>({
isPinned,
clearTooltip,
pin,
+ shouldSwallowClick,
hoverIndexRef,
hoverPositionRef,
wrapClickData,
scales,
])
- const handlers = useMemo(() => ({ onMouseMove, onMouseLeave, onClick }), [onMouseMove, onMouseLeave, onClick])
+ const handlers = useMemo(
+ () => ({ onMouseDown, onMouseMove, onMouseLeave, onClick }),
+ [onMouseDown, onMouseMove, onMouseLeave, onClick]
+ )
- return { hoverIndex, hoverPosition, tooltipCtx, handlers }
+ return { hoverIndex, hoverPosition, tooltipCtx, dragRect, handlers }
}
diff --git a/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts b/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts
new file mode 100644
index 000000000000..08733638887e
--- /dev/null
+++ b/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts
@@ -0,0 +1,165 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react'
+
+import { dragRectToLabelRange, isInPlotArea } from '../interaction'
+import type { LabelPosition } from '../interaction'
+import type { ChartDimensions, ChartScales, DateRangeZoomData, DragRect } from '../types'
+import { useLatest } from './useLatest'
+
+// Movement (px) required before a mousedown becomes a drag rather than a click.
+const DRAG_THRESHOLD_PX = 4
+
+interface UseDragToZoomOptions {
+ onDateRangeZoom?: (data: DateRangeZoomData) => void
+ scales: ChartScales | null
+ dimensions: ChartDimensions | null
+ labels: string[]
+ labelPositions: LabelPosition[]
+ wrapperRef: React.RefObject<HTMLDivElement>
+ /** Drag-to-zoom only operates on a horizontal x-axis; it's disabled when the chart's
+ * interaction axis is vertical. */
+ interactionAxis?: 'x' | 'y'
+ /** Fired once when a drag crosses the activation threshold (used to dismiss the hover tooltip). */
+ onDragActivate: () => void
+}
+
+interface UseDragToZoomResult {
+ /** Live pixel range of the in-progress selection, or null when no drag is active. */
+ dragRect: DragRect | null
+ onMouseDown: (e: React.MouseEvent<HTMLDivElement>) => void
+ /** Feed each mousemove's plot-relative coords. Returns true when the move was consumed by an
+ * active drag — the caller should then skip its own hover handling for this event. */
+ handleMouseMove: (mouseX: number, mouseY: number) => boolean
+ /** Returns true when the click immediately follows a completed drag and should be swallowed. */
+ shouldSwallowClick: () => boolean
+}
+
+/** Drag-to-zoom gesture for the x-axis, factored out of `useChartInteraction`. Tracks a horizontal
+ * selection from mousedown to mouseup and emits the spanned label range via `onDateRangeZoom`. */
+export function useDragToZoom({
+ onDateRangeZoom,
+ scales,
+ dimensions,
+ labels,
+ labelPositions,
+ wrapperRef,
+ interactionAxis = 'x',
+ onDragActivate,
+}: UseDragToZoomOptions): UseDragToZoomResult {
+ const [dragRect, setDragRect] = useState<DragRect | null>(null)
+ const dragOriginRef = useRef<{ x: number; y: number; active: boolean } | null>(null)
+ const dragJustCompletedRef = useRef(false)
+ const swallowResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const labelsRef = useLatest(labels)
+ const labelPositionsRef = useLatest(labelPositions)
+ const onDateRangeZoomRef = useLatest(onDateRangeZoom)
+ const onDragActivateRef = useLatest(onDragActivate)
+
+ const completeDrag = useCallback(
+ (mouseX: number) => {
+ const origin = dragOriginRef.current
+ if (!origin) {
+ return
+ }
+ if (origin.active) {
+ const range = dragRectToLabelRange({ x0: origin.x, x1: mouseX }, labelPositionsRef.current)
+ if (range && onDateRangeZoomRef.current) {
+ const currentLabels = labelsRef.current
+ onDateRangeZoomRef.current({
+ startLabel: currentLabels[range.startIndex],
+ endLabel: currentLabels[range.endIndex],
+ startIndex: range.startIndex,
+ endIndex: range.endIndex,
+ })
+ }
+ // Swallow the trailing `click` that the browser fires after the gesture's mouseup.
+ // shouldSwallowClick() clears this synchronously on that click; the timer is the
+ // fallback for when no click follows (drag released off-target), cleared on unmount.
+ dragJustCompletedRef.current = true
+ if (swallowResetTimerRef.current) {
+ clearTimeout(swallowResetTimerRef.current)
+ }
+ swallowResetTimerRef.current = setTimeout(() => {
+ dragJustCompletedRef.current = false
+ swallowResetTimerRef.current = null
+ }, 0)
+ }
+ dragOriginRef.current = null
+ setDragRect(null)
+ },
+ [labelPositionsRef, labelsRef, onDateRangeZoomRef]
+ )
+
+ // Global mouseup catches gestures that end outside the chart wrapper. Gate on a stable
+ // boolean rather than the `onDateRangeZoom` identity so an inline-arrow prop (the common
+ // case) doesn't re-subscribe this window listener on every parent render.
+ const zoomEnabled = !!onDateRangeZoom && interactionAxis === 'x'
+ useEffect(() => {
+ if (!zoomEnabled) {
+ return
+ }
+ const handler = (e: MouseEvent): void => {
+ if (!dragOriginRef.current) {
+ return
+ }
+ const wrapper = wrapperRef.current
+ const mouseX = wrapper ? e.clientX - wrapper.getBoundingClientRect().left : 0
+ completeDrag(mouseX)
+ }
+ window.addEventListener('mouseup', handler)
+ return () => window.removeEventListener('mouseup', handler)
+ }, [zoomEnabled, wrapperRef, completeDrag])
+
+ useEffect(
+ () => () => {
+ if (swallowResetTimerRef.current) {
+ clearTimeout(swallowResetTimerRef.current)
+ }
+ },
+ []
+ )
+
+ const onMouseDown = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (!zoomEnabled || !scales || !dimensions || e.button !== 0) {
+ return
+ }
+ const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
+ const mouseX = e.clientX - rect.left
+ const mouseY = e.clientY - rect.top
+ if (!isInPlotArea(mouseX, mouseY, dimensions)) {
+ return
+ }
+ dragOriginRef.current = { x: mouseX, y: mouseY, active: false }
+ },
+ [zoomEnabled, scales, dimensions]
+ )
+
+ const handleMouseMove = useCallback(
+ (mouseX: number, mouseY: number): boolean => {
+ const origin = dragOriginRef.current
+ if (!origin) {
+ return false
+ }
+ if (!origin.active && Math.hypot(mouseX - origin.x, mouseY - origin.y) >= DRAG_THRESHOLD_PX) {
+ origin.active = true
+ onDragActivateRef.current()
+ }
+ if (origin.active) {
+ setDragRect({ x0: origin.x, x1: mouseX })
+ return true
+ }
+ return false
+ },
+ [onDragActivateRef]
+ )
+
+ const shouldSwallowClick = useCallback((): boolean => {
+ if (dragJustCompletedRef.current) {
+ dragJustCompletedRef.current = false
+ return true
+ }
+ return false
+ }, [])
+
+ return { dragRect, onMouseDown, handleMouseMove, shouldSwallowClick }
+}
diff --git a/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts b/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts
index 728f0dff656e..cd332eb72da5 100644
--- a/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useHoverAnimation.ts
@@ -1,6 +1,14 @@
import { useEffect, useRef } from 'react'
-import type { ChartDimensions, ChartDrawArgs, ChartScales, ChartTheme, DrawHoverResult, ResolvedSeries } from '../types'
+import type {
+ ChartDimensions,
+ ChartDrawArgs,
+ ChartScales,
+ ChartTheme,
+ DragRect,
+ DrawHoverResult,
+ ResolvedSeries,
+} from '../types'
import { clearAndPrepare } from './clearCanvas'
import { useLatest } from './useLatest'
@@ -14,6 +22,7 @@ interface UseHoverAnimationOptions {
hoverIndex: number
hoverPosition: { x: number; y: number } | null
theme: ChartTheme
+ dragRect?: DragRect | null
drawHover: (args: ChartDrawArgs) => DrawHoverResult
/** Duration (ms) of the hover-overlay fade-in. `0` snaps instantly. */
hoverAnimationMs: number
@@ -33,6 +42,7 @@ export function useHoverAnimation({
hoverIndex,
hoverPosition,
theme,
+ dragRect = null,
drawHover,
hoverAnimationMs,
}: UseHoverAnimationOptions): void {
@@ -50,6 +60,7 @@ export function useHoverAnimation({
const seriesRef = useLatest(series)
const labelsRef = useLatest(labels)
const themeRef = useLatest(theme)
+ const dragRectRef = useLatest(dragRect)
// The RAF loop ticks until hoverProgress reaches 1, then exits and waits for the next
// dep change. Timer is held in a ref so cancel/restart cycles resume the fade smoothly.
@@ -91,6 +102,7 @@ export function useHoverAnimation({
theme: themeRef.current,
hoverProgress,
resetHoverFade,
+ dragRect: dragRectRef.current,
})
overlayCtx.restore()
drewVisibleRef.current = drewVisible
@@ -116,7 +128,8 @@ export function useHoverAnimation({
// `drawHover`, and entering a bar from canvas-empty-space doesn't change hoverIndex.
// The fade timer only resets on hoverIndex change (see check above), so re-running
// the effect per mousemove doesn't restart the animation.
- // series/labels/theme/drawHover are read via refs — see top of hook.
+ // series/labels/theme/drawHover/dragRect are read via refs — dragRect is also in the dep
+ // array below so the overlay repaints the selection as the drag rectangle changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [overlayCtx, dimensions, scales, hoverIndex, hoverPosition, hoverAnimationMs])
+ }, [overlayCtx, dimensions, scales, hoverIndex, hoverPosition, hoverAnimationMs, dragRect])
}
diff --git a/packages/quill/packages/charts/src/core/interaction.test.ts b/packages/quill/packages/charts/src/core/interaction.test.ts
index 480e0846532d..c5bdee47e7ec 100644
--- a/packages/quill/packages/charts/src/core/interaction.test.ts
+++ b/packages/quill/packages/charts/src/core/interaction.test.ts
@@ -1,5 +1,12 @@
import { dimensions, makeSeries } from '../testing'
-import { buildPointClickData, buildTooltipContext, findNearestIndex, isInPlotArea } from './interaction'
+import {
+ buildLabelPositions,
+ buildPointClickData,
+ buildTooltipContext,
+ dragRectToLabelRange,
+ findNearestIndex,
+ isInPlotArea,
+} from './interaction'
import type { ResolveValueFn } from './types'
const defaultResolveValue: ResolveValueFn = (s, i) => s.data[i]
@@ -287,6 +294,44 @@ describe('hog-charts interaction', () => {
})
})
+ describe('dragRectToLabelRange', () => {
+ const xScale = (label: string): number | undefined => ({ a: 100, b: 200, c: 300, d: 400, e: 500 })[label]
+ const positions = buildLabelPositions(['a', 'b', 'c', 'd', 'e'], xScale)
+ const single = buildLabelPositions(['a'], xScale)
+
+ it.each([
+ { desc: 'fewer than two labels are positioned', rect: { x0: 50, x1: 500 }, pos: single, expected: null },
+ // 160 → nearest 200 (index 1); 340 → nearest 300 (index 2)
+ {
+ desc: 'a left-to-right drag',
+ rect: { x0: 160, x1: 340 },
+ pos: positions,
+ expected: { startIndex: 1, endIndex: 2 },
+ },
+ {
+ desc: 'a right-to-left drag (normalized)',
+ rect: { x0: 340, x1: 160 },
+ pos: positions,
+ expected: { startIndex: 1, endIndex: 2 },
+ },
+ {
+ desc: 'a drag past the plot edges (clamped to outermost labels)',
+ rect: { x0: -100, x1: 9999 },
+ pos: positions,
+ expected: { startIndex: 0, endIndex: 4 },
+ },
+ {
+ desc: 'both edges landing on the same label',
+ rect: { x0: 195, x1: 205 },
+ pos: positions,
+ expected: null,
+ },
+ { desc: 'a zero-width drag', rect: { x0: 250, x1: 250 }, pos: positions, expected: null },
+ ])('returns $expected for $desc', ({ rect, pos, expected }) => {
+ expect(dragRectToLabelRange(rect, pos)).toEqual(expected)
+ })
+ })
+
describe('buildPointClickData', () => {
it.each([
{ index: -1, desc: 'negative dataIndex' },
diff --git a/packages/quill/packages/charts/src/core/interaction.ts b/packages/quill/packages/charts/src/core/interaction.ts
index abc4f9385488..4f3c6ac808e6 100644
--- a/packages/quill/packages/charts/src/core/interaction.ts
+++ b/packages/quill/packages/charts/src/core/interaction.ts
@@ -4,6 +4,7 @@ import { barColorAt } from './color-utils'
import type {
BandSlot,
ChartDimensions,
+ DragRect,
PointClickData,
ResolvedSeries,
ResolveValueFn,
@@ -12,6 +13,8 @@ import type {
} from './types'
import { DEFAULT_Y_AXIS_ID } from './types'
+export type { DragRect } from './types'
+
export interface LabelPosition {
x: number
index: number
@@ -61,6 +64,25 @@ export function isInPlotArea(mouseX: number, mouseY: number, dimensions: ChartDi
)
}
+// Returns null when fewer than 2 distinct labels are spanned.
+export function dragRectToLabelRange(
+ rect: DragRect,
+ labelPositions: LabelPosition[]
+): { startIndex: number; endIndex: number } | null {
+ if (labelPositions.length < 2) {
+ return null
+ }
+ const lo = Math.min(rect.x0, rect.x1)
+ const hi = Math.max(rect.x0, rect.x1)
+ const startIndex = findNearestIndexFromPositions(lo, labelPositions)
+ const endIndex = findNearestIndexFromPositions(hi, labelPositions)
+ if (startIndex < 0 || endIndex < 0 || startIndex === endIndex) {
+ return null
+ }
+ const [s, e] = startIndex < endIndex ? [startIndex, endIndex] : [endIndex, startIndex]
+ return { startIndex: s, endIndex: e }
+}
+
export function buildTooltipContext<Meta = unknown>(
dataIndex: number,
series: ResolvedSeries<Meta>[],
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index 98e499038fb7..2397963da01c 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -330,6 +330,22 @@ export interface ChartDrawArgs {
/** Restart the hover-fade at progress 0; returns the new value to use this frame.
* Call when the chart type detects a visible-state change at the same hoverIndex. */
resetHoverFade: () => number
+ /** Live pixel range of an in-progress drag-to-zoom selection, x-axis only. Null when
+ * no drag is active. Only the hover overlay reads this — the static layer ignores it. */
+ dragRect?: DragRect | null
+}
+
+// x0/x1 are canvas pixels, not necessarily ordered.
+export interface DragRect {
+ x0: number
+ x1: number
+}
+
+export interface DateRangeZoomData {
+ startLabel: string
+ endLabel: string
+ startIndex: number
+ endIndex: number
}
/** `true` = drew a visible highlight; `false` = nothing visible (freeze the fade timer). */
diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.md
index 206552fbec1c..4ffcee4b0bc9 100644
--- a/packages/quill/packages/charts/src/docs/TESTING.md
+++ b/packages/quill/packages/charts/src/docs/TESTING.md
@@ -55,9 +55,10 @@ For interactions, use the module-level helpers:
- `hoverAtIndex(wrapper, i, totalLabels)` — `mouseMove` over labels[i].
- `clickAtIndex(wrapper, i, totalLabels)` — hover-then-click. Resolves after the click handler runs.
+- `dragSelection(wrapper, fromIndex, toIndex, totalLabels)` — simulates a drag-to-zoom gesture between two label indices.
- `waitForHogChartTooltip()` — resolves with the rendered tooltip element once it mounts in the `FloatingPortal`.
-`chart.hoverAtIndex(i)` and `chart.waitForTooltip()` (returning a structured `TooltipSnapshot` with `seriesData`, `isPinned`, etc.) need `renderHogChart` — they read label count and the captured `TooltipContext` that only the library's own render wrapper sets up. For most consumer tests, DOM assertions through the accessor are enough.
+`chart.hoverAtIndex(i)`, `chart.dragSelection(i, j)`, and `chart.waitForTooltip()` (returning a structured `TooltipSnapshot` with `seriesData`, `isPinned`, etc.) need `renderHogChart` — they read label count and the captured `TooltipContext` that only the library's own render wrapper sets up. For most consumer tests, DOM assertions through the accessor are enough.
## Testing the library itself
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index 2611b980d1ec..162fcff3ffe6 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -83,6 +83,8 @@ export type {
ChartScales,
ChartTheme,
CreateScalesFn,
+ DateRangeZoomData,
+ DragRect,
LineChartConfig,
PointClickData,
ResolvedSeries,
diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.ts
index 969ca15db129..88109d41bae9 100644
--- a/packages/quill/packages/charts/src/testing/accessor.ts
+++ b/packages/quill/packages/charts/src/testing/accessor.ts
@@ -9,7 +9,8 @@
import { fireEvent } from '@testing-library/react'
import type { TooltipContext } from '../core/types'
-import { dimensions } from './jsdom'
+import { dragSelection } from './interactions'
+import { clientForIndex } from './jsdom'
import { type HogChartTooltip, waitForHogChartTooltip } from './tooltip'
/** A single entry of `TooltipContext.seriesData`. */
@@ -97,6 +98,7 @@ export interface HogChart<Meta = unknown> {
/** Hover at the index, wait for the tooltip to settle, then click. Mirrors the
* hover-then-click sequence the chart's onClick handler relies on. */
clickAtIndex(index: number): Promise<void>
+ dragSelection(fromIndex: number, toIndex: number): void
/** Wait for the tooltip to mount, then return a snapshot — every `TooltipContext` field
* plus the rendered portal element and an `isPinned` getter. Only available when the
* chart was rendered via `renderHogChart`; throws otherwise. */
@@ -150,14 +152,6 @@ function readReferenceLine(el: HTMLElement): ReferenceLineSummary {
return { color, orientation, position, label }
}
-function clientForIndex(totalLabels: number, index: number): { clientX: number; clientY: number } {
- const step = dimensions.plotWidth / Math.max(1, totalLabels - 1)
- return {
- clientX: dimensions.plotLeft + step * index,
- clientY: dimensions.plotTop + dimensions.plotHeight / 2,
- }
-}
-
export function getHogChart<Meta = unknown>(
scope: HTMLElement = document.body,
options: GetHogChartOptions<Meta> = {}
@@ -250,18 +244,24 @@ export function getHogChart<Meta = unknown>(
if (totalLabels === undefined) {
throw new Error('chart.hoverAtIndex requires renderHogChart (which captures labels.length)')
}
- fireEvent.mouseMove(wrapper, clientForIndex(totalLabels, index))
+ fireEvent.mouseMove(wrapper, clientForIndex(index, totalLabels))
},
async clickAtIndex(index: number): Promise<void> {
if (totalLabels === undefined) {
throw new Error('chart.clickAtIndex requires renderHogChart (which captures labels.length)')
}
- fireEvent.mouseMove(wrapper, clientForIndex(totalLabels, index))
+ fireEvent.mouseMove(wrapper, clientForIndex(index, totalLabels))
// Wait for the hover state to flush — the click handler reads live tooltipCtx
// synchronously to choose between pinning and onPointClick.
await waitForHogChartTooltip()
fireEvent.click(wrapper)
},
+ dragSelection(fromIndex: number, toIndex: number): void {
+ if (totalLabels === undefined) {
+ throw new Error('chart.dragSelection requires renderHogChart (which captures labels.length)')
+ }
+ dragSelection(wrapper, fromIndex, toIndex, totalLabels)
+ },
async waitForTooltip(timeout?: number): Promise<TooltipSnapshot<Meta>> {
const element = await waitForHogChartTooltip(timeout)
const ctx = getLastTooltipContext?.() ?? null
diff --git a/packages/quill/packages/charts/src/testing/index.ts b/packages/quill/packages/charts/src/testing/index.ts
index 343d918e3084..101145e317d6 100644
--- a/packages/quill/packages/charts/src/testing/index.ts
+++ b/packages/quill/packages/charts/src/testing/index.ts
@@ -1,5 +1,5 @@
export { dimensions, ensureJsdom, makeSeries, mockRect, setupJsdom, setupSyncRaf } from './jsdom'
-export { clickAtIndex, hoverAtIndex, hoverUntilTooltip } from './interactions'
+export { clickAtIndex, dragSelection, hoverAtIndex, hoverUntilTooltip, rawDrag } from './interactions'
export { getHogChart } from './accessor'
export type { GetHogChartOptions, HogChart, TooltipSnapshot } from './accessor'
export { renderHogChart } from './render'
diff --git a/packages/quill/packages/charts/src/testing/interactions.ts b/packages/quill/packages/charts/src/testing/interactions.ts
index cf63a4331682..b1436ad5d55d 100644
--- a/packages/quill/packages/charts/src/testing/interactions.ts
+++ b/packages/quill/packages/charts/src/testing/interactions.ts
@@ -1,17 +1,13 @@
import { act, fireEvent } from '@testing-library/react'
-import { dimensions } from './jsdom'
+import { clientForIndex } from './jsdom'
import { waitForHogChartTooltip } from './tooltip'
/** Fire a mouseMove on a chart wrapper element at the pixel position
* corresponding to the given label index. */
export function hoverAtIndex(wrapper: HTMLElement, index: number, totalLabels: number): void {
- const step = dimensions.plotWidth / (totalLabels - 1)
act(() => {
- fireEvent.mouseMove(wrapper, {
- clientX: dimensions.plotLeft + step * index,
- clientY: dimensions.plotTop + dimensions.plotHeight / 2,
- })
+ fireEvent.mouseMove(wrapper, clientForIndex(index, totalLabels))
})
}
@@ -36,3 +32,36 @@ export async function clickAtIndex(wrapper: HTMLElement, index: number, totalLab
await hoverUntilTooltip(wrapper, index, totalLabels)
fireEvent.click(wrapper)
}
+
+// Fires mouseup on window (the chart's drag handler listens globally).
+export function dragSelection(wrapper: HTMLElement, fromIndex: number, toIndex: number, totalLabels: number): void {
+ const from = clientForIndex(fromIndex, totalLabels)
+ const to = clientForIndex(toIndex, totalLabels)
+ act(() => {
+ fireEvent.mouseDown(wrapper, { button: 0, ...from })
+ fireEvent.mouseMove(wrapper, to)
+ fireEvent(window, new MouseEvent('mouseup', { bubbles: true, clientX: to.clientX, clientY: to.clientY }))
+ fireEvent.click(wrapper, to)
+ })
+}
+
+interface RawDragOptions {
+ from: { x: number; y: number }
+ to: { x: number; y: number }
+ /** Mouse button for the mousedown. Defaults to 0 (primary). */
+ button?: number
+ /** Window mouseup coordinates, for releases outside the wrapper. Defaults to `to`. */
+ release?: { x: number; y: number }
+}
+
+/** Pixel-precise drag with explicit client coords — for edge cases `dragSelection` can't express
+ * (sub-threshold moves, non-primary buttons, out-of-plot starts, off-wrapper releases). The mouseup
+ * fires on window since the chart's drag handler listens globally; no trailing click is dispatched. */
+export function rawDrag(wrapper: HTMLElement, { from, to, button = 0, release }: RawDragOptions): void {
+ const releaseAt = release ?? to
+ act(() => {
+ fireEvent.mouseDown(wrapper, { button, clientX: from.x, clientY: from.y })
+ fireEvent.mouseMove(wrapper, { clientX: to.x, clientY: to.y })
+ fireEvent(window, new MouseEvent('mouseup', { bubbles: true, clientX: releaseAt.x, clientY: releaseAt.y }))
+ })
+}
diff --git a/packages/quill/packages/charts/src/testing/jsdom.ts b/packages/quill/packages/charts/src/testing/jsdom.ts
index 2316012538d1..f6737602b7df 100644
--- a/packages/quill/packages/charts/src/testing/jsdom.ts
+++ b/packages/quill/packages/charts/src/testing/jsdom.ts
@@ -26,6 +26,15 @@ export function makeSeries(overrides: Partial<Series> & { key: string; data: num
return { label: overrides.key, color: '#000', ...overrides }
}
+/** Pixel position (client coords) of a given label index, vertically centered in the plot. */
+export function clientForIndex(index: number, totalLabels: number): { clientX: number; clientY: number } {
+ const step = dimensions.plotWidth / Math.max(1, totalLabels - 1)
+ return {
+ clientX: dimensions.plotLeft + step * index,
+ clientY: dimensions.plotTop + dimensions.plotHeight / 2,
+ }
+}
+
/** Mock ResizeObserver and getBoundingClientRect so hog-charts components
* render with real dimensions in jsdom. Call in beforeEach, and call the
* returned cleanup function in afterEach. */