: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(tracing): wire heatmap 2D brush to date range and duration filters (#71576)
Jon McCallum8cdbb757d657
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex cc3781367e82..0ac6ffa1f1ca 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -89,6 +89,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- 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. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `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. 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).+- `onAreaSelect` (base `Chart`, chart-type adapters only) is the 2D-brush sibling of `onDateRangeZoom`: the drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the y pixel span (with the committed scales, so the adapter maps pixels onto its own bands). `Heatmap` exposes it as `onBrush` with row/column index ranges; a near-horizontal drag (<8px vertical) spans every row. Takes precedence over `onDateRangeZoom` when both are set.## Testingdiff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsxindex fecbbc611c65..73c84bbdd766 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx@@ -80,6 +80,31 @@ export const LinearColorScale: Story = {},}+export const BrushSelection: Story = {+ // Skipped from visual regression: the brush overlay only appears mid-drag, so a static+ // snapshot is just a plain heatmap with no incremental coverage. The story stays for+ // interactive documentation of onBrush.+ tags: ['test-skip'],+ render: function Render() {+ const theme = useReactiveTheme()+ return (+ <Stage width={720} height={320}>+ <Heatmap+ xLabels={X_LABELS}+ yLabels={Y_LABELS}+ cells={CELLS}+ theme={theme}+ config={{ xTickFormatter: (label, i) => (i % 6 === 0 ? label : null) }}+ // Drag a rectangle: a diagonal drag selects columns + rows; a near-flat drag+ // selects columns across every row.+ // eslint-disable-next-line no-console+ onBrush={(selection) => console.info('brushed', selection)}+ />+ </Stage>+ )+ },+}+export const ClickableCells: Story = {render: function Render() {const theme = useReactiveTheme()diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsxindex 7478593aff94..8e6618170f71 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx@@ -1,6 +1,8 @@+import { waitFor } from '@testing-library/react'+import type { ChartTheme } from '../../core/types'-import { renderHogChart } from '../../testing'-import { Heatmap } from './Heatmap'+import { rawDrag, renderHogChart } from '../../testing'+import { Heatmap, type HeatmapBrushData } from './Heatmap'const THEME: ChartTheme = {colors: ['#1f77b4', '#ff7f0e'],@@ -58,4 +60,38 @@ describe('Heatmap', () => {)expect(chart.seriesCount).toBe(Y_LABELS.length)})++ // The jsdom chart mounts at 800x400; coordinates well inside the plot area are safe for drags.+ describe('onBrush', () => {+ async function brush(from: { x: number; y: number }, to: { x: number; y: number }): Promise<HeatmapBrushData> {+ const onBrush = jest.fn()+ const { chart } = renderHogChart(+ <Heatmap xLabels={X_LABELS} yLabels={Y_LABELS} cells={CELLS} theme={THEME} onBrush={onBrush} />+ )+ // The chart commits scales in a post-render effect; retry the drag until it lands.+ await waitFor(() => {+ rawDrag(chart.element, { from, to })+ expect(onBrush).toHaveBeenCalled()+ })+ return onBrush.mock.calls[onBrush.mock.calls.length - 1][0]+ }++ it('reports ordered in-bounds column and row ranges for a diagonal drag', async () => {+ const sel = await brush({ x: 200, y: 300 }, { x: 600, y: 120 })+ expect(sel.x.startIndex).toBeLessThanOrEqual(sel.x.endIndex)+ expect(sel.x.startIndex).toBeGreaterThanOrEqual(0)+ expect(sel.x.endIndex).toBeLessThan(X_LABELS.length)+ expect(sel.y.startIndex).toBeLessThanOrEqual(sel.y.endIndex)+ expect(sel.y.startIndex).toBeGreaterThanOrEqual(0)+ expect(sel.y.endIndex).toBeLessThan(Y_LABELS.length)+ // A drag that stops short of the plot top must NOT reach the top row — rows are+ // resolved bottom-up from the pixel range, not defaulted to full height.+ expect(sel.y.endIndex).toBeLessThan(Y_LABELS.length - 1)+ })++ it('spans every row for a near-horizontal drag (time-range selection)', async () => {+ const sel = await brush({ x: 200, y: 200 }, { x: 600, y: 203 })+ expect(sel.y).toEqual({ startIndex: 0, endIndex: Y_LABELS.length - 1 })+ })+ })})diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsxindex d03719ca8889..155a11990654 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx@@ -4,6 +4,7 @@ import { Chart } from '../../core/Chart'import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'import { resolveCssColor } from '../../core/color-utils'import type {+ AreaSelectData,ChartConfig,ChartDimensions,ChartDrawArgs,@@ -26,6 +27,7 @@ import {maxCellValue,normalizeCount,rowAtY,+ rowAtYClamped,type HeatmapColorScale,type HeatmapLayout,} from './heatmap-layout'@@ -78,6 +80,18 @@ export interface HeatmapConfig {}}+/** Inclusive index ranges of a completed 2D brush, in grid coordinates. */+export interface HeatmapBrushData {+ /** Column range into `xLabels`. */+ x: { startIndex: number; endIndex: number }+ /** Row range into `yLabels` (0 = bottom row). */+ y: { startIndex: number; endIndex: number }+}++// A drag flatter than this reads as a time-range selection, so it spans every row instead of+// pinning the brush to one sliver of a bucket.+const FULL_HEIGHT_MIN_Y_DRAG_PX = 8+export interface HeatmapCellDatum {/** Column index into `xLabels`. */xIndex: number@@ -104,6 +118,10 @@ export interface HeatmapProps {tooltip?: (ctx: HeatmapTooltipContext) => React.ReactNode/** Fired when the user clicks a cell. */onCellClick?: (cell: HeatmapCellDatum) => void+ /** Enables the 2D brush: drag a rectangle to select a column range and a row range at once.+ * A near-horizontal drag (under ~8px of vertical travel) selects every row, so a sloppy+ * time-range drag doesn't pin the selection to one bucket sliver. */+ onBrush?: (selection: HeatmapBrushData) => voidclassName?: stringdataAttr?: stringchildren?: React.ReactNode@@ -126,6 +144,7 @@ function HeatmapInner({config,tooltip,onCellClick,+ onBrush,className,dataAttr,children,@@ -286,6 +305,34 @@ function HeatmapInner({[])+ // Map the core's label-range + y-pixel-span brush payload onto grid indices.+ const handleAreaSelect = useCallback(+ (data: AreaSelectData, scales: ChartScales): void => {+ const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap+ if (!priv || !onBrush) {+ return+ }+ const { layout } = priv+ if (layout.rows === 0) {+ return+ }+ let startRow = 0+ let endRow = layout.rows - 1+ if (Math.abs(data.yPixel1 - data.yPixel0) >= FULL_HEIGHT_MIN_Y_DRAG_PX) {+ // yPixel0 is the top of the drag → the higher row index (rows count bottom-up).+ const top = rowAtYClamped(layout, data.yPixel0)+ const bottom = rowAtYClamped(layout, data.yPixel1)+ startRow = Math.min(top, bottom)+ endRow = Math.max(top, bottom)+ }+ onBrush({+ x: { startIndex: data.startIndex, endIndex: data.endIndex },+ y: { startIndex: startRow, endIndex: endRow },+ })+ },+ [onBrush]+ )+const handlePointClick = useCallback((data: PointClickData<HeatmapRowMeta>): void => {const rowIndex = data.series.meta?.rowIndex@@ -382,6 +429,7 @@ function HeatmapInner({drawHover={drawHover}tooltip={renderTooltip}onPointClick={onCellClick ? handlePointClick : undefined}+ onAreaSelect={onBrush ? handleAreaSelect : undefined}wrapClickData={wrapClickData}resolvePositionValue={resolvePositionValue}resolveBottomValue={resolveBottomValue}diff --git a/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.tsindex bdfd48cb6aa3..ae276bfb74c5 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts+++ b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts@@ -57,6 +57,16 @@ export function rowAtY(layout: HeatmapLayout, y: number): number {return row >= 0 && row < layout.rows ? row : -1}+/** Like `rowAtY`, but pixels beyond the plot clamp to the edge rows — for gestures (brush+ * releases) that legitimately end outside the plot area. */+export function rowAtYClamped(layout: HeatmapLayout, y: number): number {+ if (layout.rows === 0 || layout.rowHeight <= 0) {+ return -1+ }+ const row = Math.floor((layout.plotTop + layout.plotHeight - y) / layout.rowHeight)+ return Math.max(0, Math.min(layout.rows - 1, row))+}+export function maxCellValue(cells: number[][]): number {let max = 0for (const row of cells) {diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsxindex e1bc012be282..bff40866e9ac 100644--- a/packages/quill/packages/charts/src/core/Chart.tsx+++ b/packages/quill/packages/charts/src/core/Chart.tsx@@ -29,6 +29,7 @@ import { useResolvedYFormatter } from './hooks/useResolvedYFormatters'import { useStableResolveValue } from './hooks/useStableResolveValue'import { useYAxisMaps } from './hooks/useYAxisMaps'import type {+ AreaSelectData,ChartConfig,ChartDrawArgs,ChartScales,@@ -72,6 +73,12 @@ export interface ChartProps<Meta = unknown> {/** 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+ /** Enables a 2D brush: the drag tracks both axes, the selection rect clamps to the dragged+ * vertical range, and the completed gesture reports the x label range plus the y pixel+ * span, with the committed `scales` so chart-type adapters can map pixels onto their own+ * bands. Takes precedence over `onDateRangeZoom`. Chart-type adapters provide this and+ * expose a domain-shaped callback (e.g. Heatmap's `onBrush`); consumers do not. */+ onAreaSelect?: (data: AreaSelectData, scales: ChartScales) => voidclassName?: stringdataAttr?: stringchildren?: React.ReactNode@@ -120,6 +127,7 @@ export function Chart<Meta = unknown>({tooltip: renderTooltipProp,onPointClick,onDateRangeZoom,+ onAreaSelect,className,dataAttr,children,@@ -322,6 +330,7 @@ export function Chart<Meta = unknown>({resolveClickToNearestSeries,onPointClick,onDateRangeZoom,+ onAreaSelect,resolveValue,resolvePositionValue,resolveBottomValue,@@ -421,7 +430,7 @@ export function Chart<Meta = unknown>({className={className}dataAttr={dataAttr}pointer={hoverIndex >= 0 && !!onPointClick}- crosshair={!!onDateRangeZoom}+ crosshair={!!onDateRangeZoom || !!onAreaSelect}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.tsindex 76a7da0a1e80..e469f919ba54 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts@@ -1084,7 +1084,7 @@ describe('hog-charts canvas-renderer', () => {function makeSelectionArgs(ctx: CanvasRenderingContext2D,- dragRect: { x0: number; x1: number } | null+ dragRect: { x0: number; x1: number; y0?: number; y1?: number } | null): ChartDrawArgs {return makeDrawArgs(ctx, { dragRect })}@@ -1127,6 +1127,27 @@ describe('hog-charts canvas-renderer', () => {composeDrawHoverWithSelection(jest.fn())(makeSelectionArgs(ctx, { x0: plotLeft + 10, x1: plotLeft + 10 }))expect(ctx.fillRect).not.toHaveBeenCalled()})++ it('clamps a 2D drag rect to its vertical range instead of the full plot height', () => {+ const ctx = mockCanvasContext()+ composeDrawHoverWithSelection(jest.fn())(+ makeSelectionArgs(ctx, {+ x0: plotLeft + 100,+ x1: plotLeft + 250,+ y0: plotTop + 150, // unordered on purpose — bottom first+ y1: plotTop + 50,+ })+ )+ expect(ctx.fillRect).toHaveBeenCalledWith(plotLeft + 100, plotTop + 50, 150, 100)+ })++ it('clamps a 2D drag that extends past the vertical plot edges', () => {+ const ctx = mockCanvasContext()+ composeDrawHoverWithSelection(jest.fn())(+ makeSelectionArgs(ctx, { x0: plotLeft + 100, x1: plotLeft + 250, y0: -500, y1: plotTop + plotHeight + 500 })+ )+ expect(ctx.fillRect).toHaveBeenCalledWith(plotLeft + 100, plotTop, 150, plotHeight)+ })})describe('drawLineSeriesLayer — clipLeftEdge', () => {diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.tsindex c7d35e78a788..6535d5a1d7b0 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts@@ -1393,7 +1393,8 @@ export function drawSelectionRect(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.+// x-only drags (`onDateRangeZoom`) span the full plot height; a 2D drag (`onAreaSelect`)+// carries `y0`/`y1` on the rect and the band clamps to that vertical range too.export function composeDrawHoverWithSelection(baseDrawHover: DrawHoverFn): DrawHoverFn {return (args) => {const result = baseDrawHover(args)@@ -1403,14 +1404,20 @@ export function composeDrawHoverWithSelection(baseDrawHover: DrawHoverFn): DrawH}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) {+ const plotBottom = args.dimensions.plotTop + args.dimensions.plotHeight+ const hasY = dragRect.y0 != null && dragRect.y1 != null+ const y0 = hasY+ ? Math.max(args.dimensions.plotTop, Math.min(dragRect.y0 ?? 0, dragRect.y1 ?? 0))+ : args.dimensions.plotTop+ const y1 = hasY ? Math.min(plotBottom, Math.max(dragRect.y0 ?? 0, dragRect.y1 ?? 0)) : plotBottom+ if (x1 <= x0 || y1 <= y0) {return result}drawSelectionRect(args.ctx, {x: x0,- y: args.dimensions.plotTop,+ y: y0,width: x1 - x0,- height: args.dimensions.plotHeight,+ height: y1 - y0,})return result}diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.tsindex e6c0d7904d85..10de1fe4ee2d 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts@@ -10,6 +10,7 @@ import {} from '../interaction'import { defaultResolveValue } from '../types'import type {+ AreaSelectData,ChartDimensions,ChartScales,DateRangeZoomData,@@ -43,6 +44,9 @@ interface UseChartInteractionOptions<Meta> {resolveClickToNearestSeries?: booleanonPointClick?: (data: PointClickData<Meta>) => voidonDateRangeZoom?: (data: DateRangeZoomData) => void+ /** 2D brush — see `ChartProps.onAreaSelect`. Receives the committed `scales` so chart-type+ * adapters can map the y pixel range onto their own bands. */+ onAreaSelect?: (data: AreaSelectData, scales: ChartScales) => voidresolveValue?: 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@@ -118,6 +122,7 @@ export function useChartInteraction<Meta = unknown>({resolveClickToNearestSeries = false,onPointClick,onDateRangeZoom,+ onAreaSelect,resolveValue = defaultResolveValue,resolvePositionValue,resolveBottomValue,@@ -196,6 +201,14 @@ export function useChartInteraction<Meta = unknown>({[labels, scales, labelToCoord])+ // Bind the committed scales into the 2D-brush callback so chart-type adapters can map the+ // y pixel range onto their own bands (the core has no y-band concept).+ const onAreaSelectWithScales = useMemo(+ () =>+ onAreaSelect && scales ? (data: AreaSelectData): void => onAreaSelect(data, scales) : undefined,+ [onAreaSelect, scales]+ )+const {dragRect,onMouseDown,@@ -203,6 +216,7 @@ export function useChartInteraction<Meta = unknown>({shouldSwallowClick,} = useDragToZoom({onDateRangeZoom,+ onAreaSelect: onAreaSelectWithScales,scales,dimensions,labels,diff --git a/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts b/packages/quill/packages/charts/src/core/hooks/useDragToZoom.tsindex 08733638887e..3f5170f88cff 100644--- a/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts+++ b/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts@@ -2,7 +2,7 @@ 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 type { AreaSelectData, ChartDimensions, ChartScales, DateRangeZoomData, DragRect } from '../types'import { useLatest } from './useLatest'// Movement (px) required before a mousedown becomes a drag rather than a click.@@ -10,6 +10,10 @@ const DRAG_THRESHOLD_PX = 4interface UseDragToZoomOptions {onDateRangeZoom?: (data: DateRangeZoomData) => void+ /** 2D brush: the drag also tracks the vertical range, the selection rect clamps to it, and+ * the completed gesture reports the y pixel span alongside the label range. Takes+ * precedence over `onDateRangeZoom` when both are set. */+ onAreaSelect?: (data: AreaSelectData) => voidscales: ChartScales | nulldimensions: ChartDimensions | nulllabels: string[]@@ -37,6 +41,7 @@ interface UseDragToZoomResult {* selection from mousedown to mouseup and emits the spanned label range via `onDateRangeZoom`. */export function useDragToZoom({onDateRangeZoom,+ onAreaSelect,scales,dimensions,labels,@@ -52,17 +57,30 @@ export function useDragToZoom({const labelsRef = useLatest(labels)const labelPositionsRef = useLatest(labelPositions)const onDateRangeZoomRef = useLatest(onDateRangeZoom)+ const onAreaSelectRef = useLatest(onAreaSelect)const onDragActivateRef = useLatest(onDragActivate)+ // Stable across renders — flips only when the consumer adds/removes the callback, like zoomEnabled.+ const trackY = !!onAreaSelectconst completeDrag = useCallback(- (mouseX: number) => {+ (mouseX: number, mouseY: number) => {const origin = dragOriginRef.currentif (!origin) {return}if (origin.active) {const range = dragRectToLabelRange({ x0: origin.x, x1: mouseX }, labelPositionsRef.current)- if (range && onDateRangeZoomRef.current) {+ if (range && onAreaSelectRef.current) {+ const currentLabels = labelsRef.current+ onAreaSelectRef.current({+ startLabel: currentLabels[range.startIndex],+ endLabel: currentLabels[range.endIndex],+ startIndex: range.startIndex,+ endIndex: range.endIndex,+ yPixel0: Math.min(origin.y, mouseY),+ yPixel1: Math.max(origin.y, mouseY),+ })+ } else if (range && onDateRangeZoomRef.current) {const currentLabels = labelsRef.currentonDateRangeZoomRef.current({startLabel: currentLabels[range.startIndex],@@ -86,13 +104,13 @@ export function useDragToZoom({dragOriginRef.current = nullsetDragRect(null)},- [labelPositionsRef, labelsRef, onDateRangeZoomRef]+ [labelPositionsRef, labelsRef, onDateRangeZoomRef, onAreaSelectRef])// 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'+ // boolean rather than the callback identities so an inline-arrow prop (the common case)+ // doesn't re-subscribe this window listener on every parent render.+ const zoomEnabled = (!!onDateRangeZoom || !!onAreaSelect) && interactionAxis === 'x'useEffect(() => {if (!zoomEnabled) {return@@ -102,8 +120,10 @@ export function useDragToZoom({return}const wrapper = wrapperRef.current- const mouseX = wrapper ? e.clientX - wrapper.getBoundingClientRect().left : 0- completeDrag(mouseX)+ const rect = wrapper?.getBoundingClientRect()+ const mouseX = rect ? e.clientX - rect.left : 0+ const mouseY = rect ? e.clientY - rect.top : 0+ completeDrag(mouseX, mouseY)}window.addEventListener('mouseup', handler)return () => window.removeEventListener('mouseup', handler)@@ -145,12 +165,14 @@ export function useDragToZoom({onDragActivateRef.current()}if (origin.active) {- setDragRect({ x0: origin.x, x1: mouseX })+ setDragRect(+ trackY ? { x0: origin.x, x1: mouseX, y0: origin.y, y1: mouseY } : { x0: origin.x, x1: mouseX }+ )return true}return false},- [onDragActivateRef]+ [onDragActivateRef, trackY])const shouldSwallowClick = useCallback((): boolean => {diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 52038f447042..717169219f3b 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -513,6 +513,10 @@ export interface ChartDrawArgs {export interface DragRect {x0: numberx1: number+ /** Present only during a 2D (`onAreaSelect`) drag — the vertical pixel range, unordered.+ * When absent the selection spans the full plot height. */+ y0?: number+ y1?: number}export interface DateRangeZoomData {@@ -522,6 +526,21 @@ export interface DateRangeZoomData {endIndex: number}+/** Payload of a completed 2D brush ({@link ChartProps.onAreaSelect}). The x axis resolves to+ * labels like `onDateRangeZoom`; the y axis stays in canvas pixels — the core is label-generic+ * and has no y-band concept, so chart-type adapters map the pixel range onto their own scales+ * (e.g. the Heatmap converts it to row indices). */+export interface AreaSelectData {+ startLabel: string+ endLabel: string+ startIndex: number+ endIndex: number+ /** Top of the dragged range in canvas pixels (always <= yPixel1). */+ yPixel0: number+ /** Bottom of the dragged range in canvas pixels. */+ yPixel1: number+}+/** `true` = drew a visible highlight; `false` = nothing visible (freeze the fade timer). */export type DrawHoverResult = booleandiff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex db83fa78c8e2..5c543a372218 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -62,6 +62,7 @@ export type { BoxPlotTooltipProps } from './charts/BoxPlot/BoxPlotTooltip'// Heatmapexport { Heatmap } from './charts/Heatmap/Heatmap'export type {+ HeatmapBrushData,HeatmapCellDatum,HeatmapConfig,HeatmapProps,@@ -114,6 +115,7 @@ export type {ChartMargins,ChartScales,ChartTheme,+ AreaSelectData,ComboChartConfig,CreateScalesFn,DateRangeZoomData,diff --git a/products/tracing/frontend/TracingLatencyHeatmap.tsx b/products/tracing/frontend/TracingLatencyHeatmap.tsxindex 79ca537abc2b..e038cd8a9207 100644--- a/products/tracing/frontend/TracingLatencyHeatmap.tsx+++ b/products/tracing/frontend/TracingLatencyHeatmap.tsx@@ -1,7 +1,7 @@import { useCallback, useMemo } from 'react'import { SpinnerOverlay } from '@posthog/lemon-ui'-import { Heatmap, useChartTheme } from '@posthog/quill-charts'+import { Heatmap, type HeatmapBrushData, useChartTheme } from '@posthog/quill-charts'import { dayjs } from 'lib/dayjs'import { shortTimeZone } from 'lib/utils/timezones'@@ -14,9 +14,16 @@ interface TracingLatencyHeatmapProps {data: TracingLatencyHeatmapDataloading: booleandisplayTimezone: string+ /** Enables the 2D brush: drag a rectangle to select a time window + duration range. */+ onBrush?: (selection: HeatmapBrushData) => void}-export function TracingLatencyHeatmap({ data, loading, displayTimezone }: TracingLatencyHeatmapProps): JSX.Element {+export function TracingLatencyHeatmap({+ data,+ loading,+ displayTimezone,+ onBrush,+}: TracingLatencyHeatmapProps): JSX.Element {const theme = useChartTheme()// Same tick density logic as TracingSparkline: pick a format for the window size and thin@@ -71,6 +78,7 @@ export function TracingLatencyHeatmap({ data, loading, displayTimezone }: Tracincells={data.cells}theme={theme}config={config}+ onBrush={onBrush}dataAttr="tracing-latency-heatmap"/>) : !loading ? (diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 0edfb1043300..b95d538e9659 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -113,6 +113,7 @@ function TracingSceneContents(): JSX.Element {setVisibleRowRange,setSort,setChartType,+ applyHeatmapBrush,} = useActions(tracingSceneLogic())const { addProductIntent } = useActions(teamLogic)const { facetRailCollapsed } = useValues(tracingConfigLogic)@@ -210,6 +211,7 @@ function TracingSceneContents(): JSX.Element {onChartTypeChange={heatmapEnabled ? setChartType : undefined}latencyHeatmap={showHeatmap ? latencyHeatmapData : null}latencyHeatmapLoading={latencyHeatmapLoading}+ onHeatmapBrush={applyHeatmapBrush}heatmapDisabledReason={compareActive ? 'The heatmap is unavailable while comparing time windows' : null}diff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsxindex 2b77e7dd0c6a..15ac0b17129d 100644--- a/products/tracing/frontend/TracingSparkline.tsx+++ b/products/tracing/frontend/TracingSparkline.tsx@@ -2,6 +2,7 @@ import { useCallback, useMemo, useState } from 'react'import { IconChevronDown } from '@posthog/icons'import { LemonButton, LemonSegmentedButton, SpinnerOverlay } from '@posthog/lemon-ui'+import type { HeatmapBrushData } from '@posthog/quill-charts'import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'import { dayjs } from 'lib/dayjs'@@ -66,6 +67,8 @@ interface TracingSparklineProps {* it only when the heatmap should actually show (chartType 'heatmap' and no comparison). */latencyHeatmap?: TracingLatencyHeatmapData | nulllatencyHeatmapLoading?: boolean+ /** Enables the heatmap's 2D brush (time window + duration range selection). */+ onHeatmapBrush?: (selection: HeatmapBrushData) => void/** Disables the heatmap option with an explanation (e.g. while a comparison is active). */heatmapDisabledReason?: string | null}@@ -83,6 +86,7 @@ export function TracingSparkline({onChartTypeChange,latencyHeatmap,latencyHeatmapLoading = false,+ onHeatmapBrush,heatmapDisabledReason,}: TracingSparklineProps): JSX.Element | null {const [collapsed, setCollapsed] = useState(false)@@ -260,6 +264,7 @@ export function TracingSparkline({data={latencyHeatmap}loading={latencyHeatmapLoading}displayTimezone={displayTimezone}+ onBrush={onHeatmapBrush}/></div>)}diff --git a/products/tracing/frontend/heatmapBrush.test.ts b/products/tracing/frontend/heatmapBrush.test.tsnew file mode 100644index 000000000000..23e7ec962c0c--- /dev/null+++ b/products/tracing/frontend/heatmapBrush.test.ts@@ -0,0 +1,140 @@+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'++import type { TracingLatencyHeatmapData } from './durationBuckets'+import { heatmapBrushToFilters } from './heatmapBrush'++const MS = 1_000_000++const DATA: TracingLatencyHeatmapData = {+ timeBuckets: ['t0', 't1', 't2', 't3'],+ bucketsNs: [1 * MS, 2 * MS, 5 * MS, 10 * MS],+ labels: ['1ms', '2ms', '5ms', '10ms'],+ cells: [],+}++const EMPTY_GROUP: UniversalFiltersGroup = {+ type: FilterLogicalOperator.And,+ values: [{ type: FilterLogicalOperator.And, values: [] }],+}++describe('heatmapBrushToFilters', () => {+ it('maps columns to bucket-edge dates and rows to a ms duration chip pair', () => {+ const result = heatmapBrushToFilters(+ DATA,+ { x: { startIndex: 1, endIndex: 2 }, y: { startIndex: 1, endIndex: 2 } },+ EMPTY_GROUP,+ '2026-06-02T09:00:00Z'+ )+ // date_to is the START of the bucket after the last selected column.+ expect(result?.dateRange).toEqual({ date_from: 't1', date_to: 't3' })+ expect((result?.filterGroup?.values[0] as UniversalFiltersGroup).values).toEqual([+ // 2ms..5ms rows cover [2ms, 10ms) — the upper edge is the bucket after the last row.+ { type: PropertyFilterType.Span, key: 'duration', operator: PropertyOperator.GreaterThanOrEqual, value: 2 },+ { type: PropertyFilterType.Span, key: 'duration', operator: PropertyOperator.LessThan, value: 10 },+ ])+ })++ it('falls back to the current range end when the selection reaches the last column', () => {+ const result = heatmapBrushToFilters(+ DATA,+ { x: { startIndex: 2, endIndex: 3 }, y: { startIndex: 0, endIndex: 1 } },+ EMPTY_GROUP,+ '2026-06-02T09:00:00Z'+ )+ expect(result?.dateRange).toEqual({ date_from: 't2', date_to: '2026-06-02T09:00:00Z' })+ })++ it('treats a full-height selection as a time zoom with no duration filters', () => {+ const result = heatmapBrushToFilters(+ DATA,+ { x: { startIndex: 0, endIndex: 1 }, y: { startIndex: 0, endIndex: 3 } },+ EMPTY_GROUP,+ null+ )+ expect(result).toEqual({ dateRange: { date_from: 't0', date_to: 't2' } })+ })++ it('replaces a prior brush duration pair instead of stacking, keeping other filters', () => {+ const groupWithFilters: UniversalFiltersGroup = {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: PropertyFilterType.Span,+ key: 'name',+ operator: PropertyOperator.Exact,+ value: ['GET /api'],+ },+ {+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.GreaterThanOrEqual,+ value: 1,+ },+ {+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.LessThan,+ value: 2,+ },+ ],+ },+ ],+ }+ const result = heatmapBrushToFilters(+ DATA,+ { x: { startIndex: 0, endIndex: 0 }, y: { startIndex: 2, endIndex: 2 } },+ groupWithFilters,+ null+ )+ expect((result?.filterGroup?.values[0] as UniversalFiltersGroup).values).toEqual([+ { type: PropertyFilterType.Span, key: 'name', operator: PropertyOperator.Exact, value: ['GET /api'] },+ { type: PropertyFilterType.Span, key: 'duration', operator: PropertyOperator.GreaterThanOrEqual, value: 5 },+ { type: PropertyFilterType.Span, key: 'duration', operator: PropertyOperator.LessThan, value: 10 },+ ])+ })++ it('drops a duration filter with any operator so no stale bound contradicts the brushed range', () => {+ const groupWithOtherOperator: UniversalFiltersGroup = {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ // A > bound the old >=/< matcher missed — left in place it would AND with+ // the brushed pair and could empty the result set.+ {+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.GreaterThan,+ value: 100,+ },+ ],+ },+ ],+ }+ const result = heatmapBrushToFilters(+ DATA,+ { x: { startIndex: 0, endIndex: 0 }, y: { startIndex: 0, endIndex: 1 } },+ groupWithOtherOperator,+ null+ )+ expect((result?.filterGroup?.values[0] as UniversalFiltersGroup).values).toEqual([+ { type: PropertyFilterType.Span, key: 'duration', operator: PropertyOperator.GreaterThanOrEqual, value: 1 },+ { type: PropertyFilterType.Span, key: 'duration', operator: PropertyOperator.LessThan, value: 5 },+ ])+ })++ it('returns null when the selection resolves to no start bucket', () => {+ expect(+ heatmapBrushToFilters(+ { timeBuckets: [], bucketsNs: [], labels: [], cells: [] },+ { x: { startIndex: 0, endIndex: 0 }, y: { startIndex: 0, endIndex: 0 } },+ EMPTY_GROUP,+ null+ )+ ).toBeNull()+ })+})diff --git a/products/tracing/frontend/heatmapBrush.ts b/products/tracing/frontend/heatmapBrush.tsnew file mode 100644index 000000000000..0b7e25a52483--- /dev/null+++ b/products/tracing/frontend/heatmapBrush.ts@@ -0,0 +1,103 @@+// Pure mapping from a heatmap 2D brush onto the tracing filters. Kept out of the kea logic so+// the geometry → filter translation is unit-testable without the logic's import graph.++import { DateRange } from '~/queries/schema/schema-general'+import {+ FilterLogicalOperator,+ PropertyFilterType,+ PropertyOperator,+ SpanPropertyFilter,+ UniversalFiltersGroup,+} from '~/types'++import { selectionToDurationRange, type TracingLatencyHeatmapData } from './durationBuckets'+import type { DurationRange } from './operationFilters'++const NS_PER_MS = 1_000_000++export interface HeatmapBrushSelection {+ /** Inclusive column range into the heatmap's time buckets. */+ x: { startIndex: number; endIndex: number }+ /** Inclusive row range into the heatmap's duration buckets (0 = bottom/smallest). */+ y: { startIndex: number; endIndex: number }+}++function isDurationFilter(filter: unknown): boolean {+ const f = filter as Partial<SpanPropertyFilter> | null+ return f?.type === PropertyFilterType.Span && f?.key === 'duration'+}++/** The current filter group with the brushed duration range applied as a >=min / <max pair of+ * `duration` span filters (ms — the unit the chips and the backend translation use). The brush+ * owns the duration axis: any existing `duration` filter (whatever its operator) is dropped and+ * replaced by the brushed pair, so successive brushes refine instead of stacking and no stale+ * bound can contradict the new range. The brushed range is always within the heatmap's rendered+ * duration extent, which already reflects the current filters, so this never widens the query. */+function withDurationFilters(group: UniversalFiltersGroup, range: DurationRange): UniversalFiltersGroup {+ const inner = group.values[0] as UniversalFiltersGroup | undefined+ const keptValues = (inner?.values ?? []).filter((filter) => !isDurationFilter(filter))+ const durationFilters: SpanPropertyFilter[] = [+ {+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.GreaterThanOrEqual,+ value: range.minNs / NS_PER_MS,+ },+ {+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.LessThan,+ value: range.maxNs / NS_PER_MS,+ },+ ]+ return {+ ...group,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [...keptValues, ...durationFilters],+ } as UniversalFiltersGroup,+ ...group.values.slice(1),+ ],+ }+}++/**+ * Filter updates for a completed heatmap brush, or null when the selection resolves to nothing.+ *+ * x maps to a date range using the same bucket-edge convention as the sparkline's time selection:+ * `date_to` is the START of the bucket after the last selected column (buckets are anchored at+ * their start), falling back to the current range's end on the final column. y maps to a+ * `duration` chip pair via the 1-2-5 bucket edges — unless the brush spans every row, which reads+ * as a plain time-range zoom and leaves the filters untouched.+ *+ * Returned as one object so the caller can dispatch a single `setFilters` (one re-query), with+ * the chips appearing in the filter bar as ordinary removable filters.+ */+export function heatmapBrushToFilters(+ data: TracingLatencyHeatmapData,+ selection: HeatmapBrushSelection,+ currentFilterGroup: UniversalFiltersGroup,+ currentDateTo: string | null | undefined+): { dateRange: DateRange; filterGroup?: UniversalFiltersGroup } | null {+ const dateFrom = data.timeBuckets[selection.x.startIndex]+ if (!dateFrom) {+ return null+ }+ const dateRange: DateRange = {+ date_from: dateFrom,+ date_to: data.timeBuckets[selection.x.endIndex + 1] ?? currentDateTo ?? null,+ }++ const spansAllRows = selection.y.startIndex <= 0 && selection.y.endIndex >= data.bucketsNs.length - 1+ if (spansAllRows) {+ return { dateRange }+ }++ const durationRange = selectionToDurationRange(data.bucketsNs, selection.y.startIndex, selection.y.endIndex)+ if (!durationRange) {+ return { dateRange }+ }++ return { dateRange, filterGroup: withDurationFilters(currentFilterGroup, durationRange) }+}diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex af77a87378d0..c903d7b432a7 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -39,6 +39,7 @@ import {type VisibleDurationRange,visibleDurationRange,} from './durationBuckets'+import { type HeatmapBrushSelection, heatmapBrushToFilters } from './heatmapBrush'import { traceLookupDateRange } from './traceLinks'import {type TracingFilters,@@ -237,6 +238,9 @@ export interface tracingDataLogicActions {current: OverlayWindowprevious: OverlayWindow} // tracingFiltersLogic+ applyHeatmapBrush: (selection: HeatmapBrushSelection) => {+ selection: HeatmapBrushSelection+ }cancelInProgressAggregation: (controller: AbortController | null) => {controller: AbortController | null}@@ -662,6 +666,8 @@ export const tracingDataLogic = kea<tracingDataLogicType>([// listeners below; the scene logic additionally listens to this to sync the URL.// Mirrors the logs viewer's handleQueryChange.handleFilterChange: (filterType: string, extraProps?: Record<string, unknown>) => ({ filterType, extraProps }),+ // A completed 2D brush on the latency heatmap — maps to a date range + duration chips.+ applyHeatmapBrush: (selection: HeatmapBrushSelection) => ({ selection }),runQuery: true,fetchNextPage: true,loadMoreTraceSpans: true,@@ -1396,6 +1402,30 @@ export const tracingDataLogic = kea<tracingDataLogicType>([}),// Bulk restores (URL params, saved views) re-query without an interaction capture.setFilters: () => actions.runQuery(),+ applyHeatmapBrush: ({ selection }) => {+ // While a refetch is in flight the rendered heatmap still shows the previous query's+ // buckets. Ignore brushes until it settles so the selection maps against the buckets+ // actually on screen rather than a stale grid.+ if (values.latencyHeatmapLoading) {+ return+ }+ const updates = heatmapBrushToFilters(+ values.latencyHeatmapData,+ selection,+ values.filters.filterGroup,+ values.utcDateRange.date_to+ )+ if (!updates) {+ return+ }+ posthog.capture('tracing filter changed', {+ filter_type: 'heatmap_brush',+ with_duration: !!updates.filterGroup,+ })+ // One dispatch → one re-query via the setFilters listener (and one URL write in the+ // scene logic) — separate setDateRange + setFilterGroup would each run the query.+ actions.setFilters(updates)+ },// Feature flags land asynchronously (posthog.js /flags), potentially after the first// runQuery. If that flip just made the heatmap visible (?chart=heatmap deep link with// the flag on), fetch the data the earlier runQuery skipped.diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex 03f78a3fb628..836d901dd29a 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -97,6 +97,9 @@ export interface tracingSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingSceneLogicActions {+ applyHeatmapBrush: (selection: import('./heatmapBrush').HeatmapBrushSelection) => {+ selection: import('./heatmapBrush').HeatmapBrushSelection+ } // tracingDataLogicfetchAggregation: (options?:| {@@ -274,6 +277,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['fetchSpanTree','setVisibleRowRange','handleFilterChange',+ 'applyHeatmapBrush',],tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),[