: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(quill): add HighlightedRange overlay and per-bar hatch fill to charts (#70223)
Sam Penningtonf2218147c5f0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex feee305e9107..7b271f6fa23c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -528,6 +528,10 @@ snapshots:hash: v1.k794b7964.7399c9de00dfaa6c03cc526b9f87c442d294a5abbe87f94a4767ac2818290273.CibMfsALN7_rP9b-1akLvDlvpuTidNKP45HB3fNzGcscomponents-hogcharts-barchart--grouped--light:hash: v1.k794b7964.03cf5aea076941f1c72940a8ef54320900b81e98ca85e6674d3bcffb1248ecc9.9jxIF7qRonS1YfjjqPD0m8UQc-Ud-3ew5RUtQh5IOqk+ components-hogcharts-barchart--hatched-bars--dark:+ hash: v1.k794b7964.66d8f6d3f831677b1c9456d0ce3366582ebcf34609e444441671e875f50cd190.NRzrg-Us0qAtTYR26S42eR88Faqld0pTbOXVO6uPe2o+ components-hogcharts-barchart--hatched-bars--light:+ hash: v1.k794b7964.073920f88142793533a52faa925fc1b0eef7ef8236cbe23f330ab7b28e79a58e.0tcVwLSfb_hZIgxGSNzSeP0siFbwthVTeee1is2PrF0components-hogcharts-barchart--hidden-series--dark:hash: v1.k794b7964.99ce82756e391d6b976a7445b5fc1e1bc4edad1442ec4d52b51839043213276b.7bLI7A3z7IA7Zk95GtSkf9qrAuRx6ghxPmoH8cR8ZZMcomponents-hogcharts-barchart--hidden-series--light:@@ -652,6 +656,18 @@ snapshots:hash: v1.k794b7964.fb81cb2f84f1c695d9bf3410b3e007dfb0c8835c7d5559782549eb512d4de370.NyKEsje9NjASsmSair_05neuK4jjxTnDau697twbsEUcomponents-hogcharts-defaulttooltip--total-excludes-overlay--light:hash: v1.k794b7964.0ef742f50f4f5cebd2c50b24b514c90a101012d53f3cb61e3b461f5ff0864d9c.h-i6FX0wnz_8r7gxr3pus1F2U1i-hcsuXZQ8drcM35E+ components-hogcharts-highlightedrange--mirroring-drag-selection--dark:+ hash: v1.k794b7964.64a7d4555eda0a387b3b7b159397ed36aec00739db9ca101281ace1d84ea742e.t3Qju4H0HxPL1ROhKqavpuowJ_DeePAa0O0r5eIHeBs+ components-hogcharts-highlightedrange--mirroring-drag-selection--light:+ hash: v1.k794b7964.03f4058be87285b0fbdc6629fdfa9dbce0da29f8fc4324bffb1f07728ec6db81.OGVCGy23d8dlHRbbU4PlWhxHgt6vh1xfwocv1VOJ-l4+ components-hogcharts-highlightedrange--on-bars--dark:+ hash: v1.k794b7964.efaf68b4eb32b221ae531db377bf827b910265554b84d11f79c1ef82e0ed993e.yQ_xf9baQN6097kANyUNNAMid7GCMZiEvh95rH-SLnc+ components-hogcharts-highlightedrange--on-bars--light:+ hash: v1.k794b7964.e0a823a427ee54a7278a1fdee89742773a3a9fd7d3388450f7d97c613b90c269.J6hD0tXG7HRexOfygxyH8k4R7xfeSK3tud8a2bTDZsQ+ components-hogcharts-highlightedrange--on-lines--dark:+ hash: v1.k794b7964.6bf0d21adf0b87933776d278a8e4ea31d7ab54c452c244793c6c3a042b225560.BvqQ3qui00__3Cu-35hrZrFNdP9IQOh4KUg_uHhXY3A+ components-hogcharts-highlightedrange--on-lines--light:+ hash: v1.k794b7964.815503e58c42cc37a4cf639967e43b91ea35f50589cb24c4a1e3ece3ea5d3ac0.YMwb2P1d5jzswg0b85kEPc1GA7Z2rgUNKLm5DR1CJzscomponents-hogcharts-legend--built-in-toggle-bottom--dark:hash: v1.k794b7964.bb7fd009c6bea74119d317347fe7d6dcd977f59e10bfe73d641e305c8df1c949.YlAqy3cuOfkX3u0lLP5gPrBnCIwk5tPeoZFbe67G6uscomponents-hogcharts-legend--built-in-toggle-bottom--light:diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex eacd38e2140c..93ae54a58432 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -44,7 +44,7 @@ const series: Series[] = [- `key` (React key + stacking identity), `label` (legend/tooltip), `data` are required.- Line-only options: `points`, `stroke.pattern` (dashes/projections), `fill.opacity` / `fill.gradient` (area), `fill.lowerData` (ribbon).-- Bar-only options: `bars` (per-bar `color`/`label`/`meta` overrides); `trackData` caps each bar's interactive extent at a per-bar ceiling in value units — the region beyond `trackData[i]` is a fully inert gap: no hover, tooltip, pointer cursor, highlight, or click (the chart vetoes the hover there via `resolveHoverIndex`). On grouped charts with `bars.track` the hatched "share of a whole" track also fills only to the ceiling; on stacked charts no track is drawn — the ceiling only bounds interactivity. Funnel compare uses it to draw a shorter period's volume gap as empty space rather than drop-off, in both its grouped (left-to-right) and stacked (top-to-bottom) charts.+- Bar-only options: `bars` (per-bar `color`/`label`/`meta` overrides, plus `hatch: true` to fill that bar with a diagonal-hatch pattern in its resolved color — flags individual not-final bars, e.g. buckets still being ingested, at arbitrary indices; for a contiguous trailing range `stroke.partial.fromIndex` does the same); `trackData` caps each bar's interactive extent at a per-bar ceiling in value units — the region beyond `trackData[i]` is a fully inert gap: no hover, tooltip, pointer cursor, highlight, or click (the chart vetoes the hover there via `resolveHoverIndex`). On grouped charts with `bars.track` the hatched "share of a whole" track also fills only to the ceiling; on stacked charts no track is drawn — the ceiling only bounds interactivity. Funnel compare uses it to draw a shorter period's volume gap as empty space rather than drop-off, in both its grouped (left-to-right) and stacked (top-to-bottom) charts.- `yAxisId` scales a series against a second axis; `meta` carries arbitrary data into tooltips.## Sizing@@ -68,7 +68,8 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei</TimeSeriesLineChart>```-- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`) compose as children.+- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`, `HighlightedRange`) compose as children.+- `HighlightedRange` draws a translucent box spanning an x-axis range — pass `start`/`end` as data indices or labels (e.g. straight from `onDateRangeZoom`'s `startIndex`/`endIndex`). Use it to mirror an external selection (the rows visible in a paired virtualized list, a picked time window) onto the chart. On band (bar) charts the box covers the endpoints' full bands; on point (line) charts it runs point to point. `color`, `fillOpacity`, and `borderOpacity` tune the look (`borderOpacity: 0` drops the edge border); it clamps to the plot area and renders null when an endpoint doesn't resolve.- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) from the sum and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.- BarChart sets `TooltipContext.hoveredSeriesKey` — the key of the bar/segment under the cursor (stacked: the visible segment; grouped: the band-slot hit). Stacked `seriesData` keeps every segment in declaration order, so a custom tooltip that describes a single segment (e.g. a funnel breakdown) must select by `hoveredSeriesKey`, not `seriesData[0]`. It may reference a series hidden from `seriesData` via `visibility.tooltip: false` (e.g. a drop-off filler), and is `undefined` on other chart types and pinned rebuilds without a cursor.- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, resolveClickToNearestSeries, placement, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint). `resolveClickToNearestSeries` (default false) changes what a click on a `pinnable` multi-series chart does: instead of always pinning first (letting the user then click a specific row), it resolves the series nearest the cursor and fires `onPointClick` for it directly — skip pinning only where a click's target series is visually unambiguous by position (e.g. funnel breakdown areas, one per breakdown value); leave it off where series overlap closely and a wrong guess is costly (e.g. trend lines).@@ -84,7 +85,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.-- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/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. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).+- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/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. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).## Testingdiff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsxindex 749a9ebbb989..40aa12a4d7b0 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx@@ -50,7 +50,12 @@ export const Grouped: Story = {export const WithBarTrack: Story = {render: () => {const theme = useReactiveTheme()- const config: BarChartConfig = { barLayout: 'grouped', showGrid: true, barCornerRadius: 6, bars: { track: true } }+ const config: BarChartConfig = {+ barLayout: 'grouped',+ showGrid: true,+ barCornerRadius: 6,+ bars: { track: true },+ }return (<Stage><BarChart series={THREE_SERIES} labels={DAYS} config={config} theme={theme} />@@ -250,6 +255,25 @@ export const IncompletePeriod: Story = {},}+/** Individual bars flagged via `bars[i].hatch` — e.g. buckets still being ingested. Unlike+ * `stroke.partial` (IncompletePeriod above), the flagged indices need not be contiguous. */+export const HatchedBars: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const config: BarChartConfig = { barLayout: 'stacked', showGrid: true }+ const hatched = new Set([2, 5, 6])+ const series: Series[] = TWO_SERIES.map((s) => ({+ ...s,+ bars: DAYS.map((_, i) => (hatched.has(i) ? { hatch: true } : {})),+ }))+ return (+ <Stage>+ <BarChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}+export const HiddenSeries: Story = {render: () => {const theme = useReactiveTheme()diff --git a/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.tsindex c9ecec62bdb6..8fc6b1ed951b 100644--- a/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.ts+++ b/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.ts@@ -161,7 +161,12 @@ describe('hog-charts canvas-renderer (bars)', () => {it('falls back to a solid color for dashed (hatched) bars regardless of fillStyle', () => {const ctx = mockCanvasContext()- const dashed = makeSeries({ key: 's', data: [1], color: '#abcdef', stroke: { partial: { fromIndex: 0 } } })+ const dashed = makeSeries({+ key: 's',+ data: [1],+ color: '#abcdef',+ stroke: { partial: { fromIndex: 0 } },+ })drawBars(makeDrawContext(ctx, ['a']), dashed, [BASE_BAR], 0, 'gloss')expect(ctx.createRadialGradient).not.toHaveBeenCalled()})@@ -263,6 +268,39 @@ describe('hog-charts canvas-renderer (bars)', () => {expect(typeof fillStyleSeen[2]).not.toBe('string')})+ it('hatches individual bars flagged via bars[i].hatch, including non-contiguous indices', () => {+ const ctx = mockCanvasContext()+ const drawCtx = makeDrawContext(ctx, ['a', 'b', 'c'])+ const series = makeSeries({+ key: 's',+ data: [1, 2, 3],+ color: '#55667788',+ bars: [{ hatch: true }, {}, { hatch: true }],+ })+ const fillStyleSeen: (string | CanvasPattern)[] = []+ const original = Object.getOwnPropertyDescriptor(ctx, 'fillStyle')+ Object.defineProperty(ctx, 'fillStyle', {+ set(v) {+ fillStyleSeen.push(v)+ },+ get() {+ return ''+ },+ })+ try {+ drawBars(drawCtx, series, [+ bar({ x: 0, dataIndex: 0 }),+ bar({ x: 60, dataIndex: 1 }),+ bar({ x: 120, dataIndex: 2 }),+ ])+ } finally {+ Object.defineProperty(ctx, 'fillStyle', original!)+ }+ expect(typeof fillStyleSeen[0]).not.toBe('string')+ expect(fillStyleSeen[1]).toBe('#55667788')+ expect(typeof fillStyleSeen[2]).not.toBe('string')+ })+it('respects the cornerRadius option', () => {const ctx = mockCanvasContext()const drawCtx = makeDrawContext(ctx, ['a'])diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.tsindex 3f98fa0ab1b2..c7d35e78a788 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts@@ -1098,16 +1098,19 @@ export function drawBars(const dataLength = series.data.lengthconst dashedFrom = resolvePartialIndex(series.stroke?.partial?.fromIndex, dataLength)const dashedTo = resolvePartialIndex(series.stroke?.partial?.toIndex, dataLength)- const hatch = dashedFrom !== null || dashedTo !== null ? getHatchPattern(ctx, series.color) : nullfor (const bar of bars) {if (bar.width <= 0 || bar.height <= 0) {continue}const useHatch =- hatch !== null &&- ((dashedFrom !== null && bar.dataIndex >= dashedFrom) || (dashedTo !== null && bar.dataIndex <= dashedTo))- ctx.fillStyle = useHatch ? hatch : makeBarFill(ctx, barColorAt(series, bar.dataIndex), bar, fillStyle)+ (dashedFrom !== null && bar.dataIndex >= dashedFrom) ||+ (dashedTo !== null && bar.dataIndex <= dashedTo) ||+ !!series.bars?.[bar.dataIndex]?.hatch+ // The hatch keeps the bar's own resolved color (per-bar override included) so a+ // flagged bar still reads as belonging to its series. Pattern lookups are cached.+ const barColor = barColorAt(series, bar.dataIndex)+ ctx.fillStyle = useHatch ? getHatchPattern(ctx, barColor) : makeBarFill(ctx, barColor, bar, fillStyle)ctx.beginPath()traceRoundedBarPath(ctx, bar.x, bar.y, bar.width, bar.height, cornerRadius, bar.corners)ctx.fill()diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 2f99adee876e..a2bad77b85ec 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -51,8 +51,11 @@ export interface Series<Meta = unknown> {/** Bar charts only: per-bar overrides of the series-level `color`/`label`/`meta`, indexed by* data index. Lets one series draw bars with distinct identity (e.g. an aggregated breakdown,* one bar per breakdown value) instead of paying the O(n²) cost of one series per bar. Read by- * bar fill, hover highlight, and the tooltip; not by track decorations (`drawBarTracks`). */- bars?: { color?: string; label?: string; meta?: Meta }[]+ * bar fill, hover highlight, and the tooltip; not by track decorations (`drawBarTracks`).+ * `hatch` fills that bar with the diagonal-hatch pattern (in the bar's resolved color) instead+ * of a solid fill — for flagging individual not-final bars (e.g. a bucket still being+ * ingested) without the contiguous-range constraint of `stroke.partial`. */+ bars?: { color?: string; label?: string; meta?: Meta; hatch?: boolean }[]/** Bar charts only: per-bar ceiling (in value-axis units) of the bar's interactive extent. The* region beyond the ceiling is a blank, fully inert gap — no hover, tooltip, highlight, or* click (`onPointClick` passes through). On grouped charts with `bars.track`, the hatcheddiff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex fa87502a2a42..8b6dbbd5aa9c 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -137,6 +137,8 @@ export type {ReferenceLineStyle,ReferenceLineVariant,} from './overlays/ReferenceLine'+export { HighlightedRange } from './overlays/HighlightedRange'+export type { HighlightedRangeProps } from './overlays/HighlightedRange'export { ValueLabels } from './overlays/ValueLabels'export type { ValueLabelContext, ValueLabelFormatter, ValueLabelsProps } from './overlays/ValueLabels'export { AxisTitles } from './overlays/AxisTitles'diff --git a/packages/quill/packages/charts/src/overlays/HighlightedRange.stories.tsx b/packages/quill/packages/charts/src/overlays/HighlightedRange.stories.tsxnew file mode 100644index 000000000000..76564d30088f--- /dev/null+++ b/packages/quill/packages/charts/src/overlays/HighlightedRange.stories.tsx@@ -0,0 +1,61 @@+import { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import { BarChart } from '../charts/BarChart/BarChart'+import { LineChart } from '../charts/LineChart/LineChart'+import type { DateRangeZoomData, Series } from '../core/types'+import { Stage, useReactiveTheme } from '../story-helpers'+import { HighlightedRange } from './HighlightedRange'++const LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']++const SERIES: Series[] = [{ key: 'visits', label: 'Visits', color: '', data: [20, 35, 28, 60, 45, 70, 52] }]++const meta: Meta = {+ title: 'Components/HogCharts/HighlightedRange',+ parameters: { layout: 'centered' },+}+export default meta++type Story = StoryObj<{}>++export const OnBars: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <BarChart series={SERIES} labels={LABELS} theme={theme}>+ <HighlightedRange start="Tue" end="Thu" />+ </BarChart>+ </Stage>+ )+ },+}++export const OnLines: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <LineChart series={SERIES} labels={LABELS} theme={theme}>+ <HighlightedRange start={1} end={4} color="var(--data-color-1)" />+ </LineChart>+ </Stage>+ )+ },+}++/** Drag across the bars — the selection persists as a highlighted range. */+export const MirroringDragSelection: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const [range, setRange] = useState<DateRangeZoomData | null>(null)+ return (+ <Stage>+ <BarChart series={SERIES} labels={LABELS} theme={theme} onDateRangeZoom={(data) => setRange(data)}>+ {range && <HighlightedRange start={range.startIndex} end={range.endIndex} />}+ </BarChart>+ </Stage>+ )+ },+}diff --git a/packages/quill/packages/charts/src/overlays/HighlightedRange.test.tsx b/packages/quill/packages/charts/src/overlays/HighlightedRange.test.tsxnew file mode 100644index 000000000000..216ffbf1c314--- /dev/null+++ b/packages/quill/packages/charts/src/overlays/HighlightedRange.test.tsx@@ -0,0 +1,105 @@+import { cleanup } from '@testing-library/react'++import type { BaseChartContext } from '../core/chart-context'+import type { ChartScales } from '../core/types'+import { makeOverlayContext, renderOverlayInChart } from '../testing'+import { HighlightedRange } from './HighlightedRange'++const DIMENSIONS = {+ width: 800,+ height: 400,+ plotLeft: 48,+ plotTop: 16,+ plotWidth: 720,+ plotHeight: 352,+}++const LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']+const X_POSITIONS: Record<string, number> = { Mon: 100, Tue: 250, Wed: 400, Thu: 550, Fri: 700 }+const BAND_WIDTH = 100++function makeContext(scales: Partial<ChartScales> = {}): BaseChartContext {+ return makeOverlayContext(+ {+ x: (label: string) => X_POSITIONS[label],+ y: (v: number) => v,+ yTicks: () => [],+ extent: () => BAND_WIDTH,+ ...scales,+ },+ { dimensions: DIMENSIONS, labels: LABELS }+ )+}++function fillBox(container: HTMLElement): HTMLDivElement | null {+ return container.querySelector<HTMLDivElement>('[data-attr="hog-chart-highlighted-range"]')+}++describe('HighlightedRange', () => {+ afterEach(() => cleanup())++ it('covers the full bands of both endpoints on a band (bar) chart', () => {+ const { container } = renderOverlayInChart(<HighlightedRange start="Tue" end="Thu" />, makeContext())+ const box = fillBox(container)!+ // Tue center 250 - half band 50 = 200; Thu center 550 + 50 = 600.+ expect(box.style.left).toBe('200px')+ expect(box.style.width).toBe('400px')+ expect(box.style.top).toBe('16px')+ expect(box.style.height).toBe('352px')+ })++ it('runs point-to-point when the chart has no band extent (line chart)', () => {+ const { container } = renderOverlayInChart(+ <HighlightedRange start="Tue" end="Thu" />,+ makeContext({ extent: undefined })+ )+ const box = fillBox(container)!+ expect(box.style.left).toBe('250px')+ expect(box.style.width).toBe('300px')+ })++ it('resolves numeric endpoints as data indices into the labels array', () => {+ const { container } = renderOverlayInChart(<HighlightedRange start={1} end={3} />, makeContext())+ expect(fillBox(container)!.style.left).toBe('200px')+ expect(fillBox(container)!.style.width).toBe('400px')+ })++ it('normalizes reversed endpoints', () => {+ const { container } = renderOverlayInChart(<HighlightedRange start="Thu" end="Tue" />, makeContext())+ expect(fillBox(container)!.style.left).toBe('200px')+ expect(fillBox(container)!.style.width).toBe('400px')+ })++ it('clamps the box to the plot area when the range spills past its edges', () => {+ // Edge bands centered at 60 and 740 spill outside the plot ([48, 768]) once+ // expanded by half a 100px band: lo = 10, hi = 790.+ const { container } = renderOverlayInChart(+ <HighlightedRange start="Mon" end="Fri" />,+ makeContext({ x: (label: string) => ({ ...X_POSITIONS, Mon: 60, Fri: 740 })[label] })+ )+ const box = fillBox(container)!+ expect(box.style.left).toBe('48px')+ expect(box.style.width).toBe('720px')+ })++ it.each([+ ['unknown label', { start: 'Nope', end: 'Thu' }],+ ['out-of-range index', { start: 1, end: 99 }],+ ])('renders null for an endpoint that does not resolve (%s)', (_name, props) => {+ const { container } = renderOverlayInChart(<HighlightedRange {...props} />, makeContext())+ expect(container.firstChild).toBeNull()+ })++ it('renders the border box by default and omits it at borderOpacity=0', () => {+ const withBorder = renderOverlayInChart(<HighlightedRange start="Tue" end="Thu" />, makeContext())+ const borderDiv = withBorder.container.querySelectorAll('div')[1] as HTMLDivElement+ expect(borderDiv.style.borderWidth).toBe('1px')+ expect(borderDiv.style.borderColor).toBe('#8f8f8f')+ cleanup()+ const noBorder = renderOverlayInChart(+ <HighlightedRange start="Tue" end="Thu" borderOpacity={0} />,+ makeContext()+ )+ expect(noBorder.container.querySelectorAll('div')[1]).toBeUndefined()+ })+})diff --git a/packages/quill/packages/charts/src/overlays/HighlightedRange.tsx b/packages/quill/packages/charts/src/overlays/HighlightedRange.tsxnew file mode 100644index 000000000000..956396a62f74--- /dev/null+++ b/packages/quill/packages/charts/src/overlays/HighlightedRange.tsx@@ -0,0 +1,85 @@+/* eslint-disable react/forbid-dom-props -- dynamic pixel positions from d3 scales */+import React from 'react'++import { useChartLayout } from '../core/chart-context'++/** Neutral gray matching the classic sparkline highlight, readable on light and dark surfaces. */+const DEFAULT_HIGHLIGHT_COLOR = '#8f8f8f'++export interface HighlightedRangeProps {+ /** Start of the range — a data index (number) or an x-axis label (string). */+ start: number | string+ /** End of the range, inclusive — a data index (number) or an x-axis label (string). */+ end: number | string+ /** CSS color for the fill and border. Supports `var(--my-color)`. */+ color?: string+ /** Opacity 0-1 of the translucent fill. Defaults to 0.1. */+ fillOpacity?: number+ /** Opacity 0-1 of the 1px border marking the range edges. Defaults to 0.8. Pass 0 for no border. */+ borderOpacity?: number+}++/** Translucent box spanning an x-axis label/index range — mirrors an external selection+ * (e.g. the rows currently visible in a paired virtualized list) onto the chart. On band+ * (bar) charts the box covers the full bands of both endpoints; on point (line) charts it+ * runs from point to point. Composes as a chart child like {@link ReferenceLine}; renders+ * null when an endpoint doesn't resolve to a positioned label. */+export function HighlightedRange({+ start,+ end,+ color = DEFAULT_HIGHLIGHT_COLOR,+ fillOpacity = 0.1,+ borderOpacity = 0.8,+}: HighlightedRangeProps): React.ReactElement | null {+ const { labels, scales, dimensions } = useChartLayout()++ const startLabel = typeof start === 'number' ? labels[start] : start+ const endLabel = typeof end === 'number' ? labels[end] : end+ if (startLabel == null || endLabel == null) {+ return null+ }++ const startX = scales.x(startLabel)+ const endX = scales.x(endLabel)+ if (startX == null || endX == null || !isFinite(startX) || !isFinite(endX)) {+ return null+ }++ // Expand each endpoint by half its band so the box covers whole bars; extent is+ // unset on point-style (line) charts, where the box runs from point to point.+ const startHalfBand = (scales.extent?.(startLabel) ?? 0) / 2+ const endHalfBand = (scales.extent?.(endLabel) ?? 0) / 2+ const lo = Math.min(startX - startHalfBand, endX - endHalfBand)+ const hi = Math.max(startX + startHalfBand, endX + endHalfBand)++ const { plotLeft, plotTop, plotWidth, plotHeight } = dimensions+ const plotRight = plotLeft + plotWidth+ const left = Math.max(lo, plotLeft)+ const right = Math.min(hi, plotRight)+ if (right <= left) {+ return null+ }++ const rect: React.CSSProperties = { left, top: plotTop, width: right - left, height: plotHeight }+ return (+ <>+ <div+ data-attr="hog-chart-highlighted-range"+ className="absolute pointer-events-none"+ style={{ ...rect, backgroundColor: color, opacity: fillOpacity }}+ />+ {borderOpacity > 0 && (+ <div+ className="absolute pointer-events-none"+ style={{+ ...rect,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: color,+ opacity: borderOpacity,+ }}+ />+ )}+ </>+ )+}