: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
fix(insights): let drag-to-zoom select a single chart bucket (#69981)
Sam Pennington0aec93314253
diff --git a/frontend/src/lib/charts/hooks.ts b/frontend/src/lib/charts/hooks.tsindex edae5b1330aa..4bf83694f597 100644--- a/frontend/src/lib/charts/hooks.ts+++ b/frontend/src/lib/charts/hooks.ts@@ -57,9 +57,11 @@ export function useDragToZoomEnabled(): boolean {/** Adapts a quill chart's drag-to-zoom callback to the host's `onZoom(dateFrom, dateTo)` by mapping* the dragged label indices into `dates` — the date value for each x position (trends result days,- * a SQL date column's values). Returns undefined when zooming is unavailable — drag-to-zoom is- * opt-in: it only surfaces behind the rollout flag, where the host passes a handler, and when the- * x positions map to dates. */+ * a SQL date column's values). Both emitted dates are bucket *starts*; widening the end to the+ * last bucket's end is the host's job (insights do it in `zoomDateRange`, which knows the query's+ * interval). Returns undefined when zooming is unavailable — drag-to-zoom is opt-in: it only+ * surfaces behind the rollout flag, where the host passes a handler, and when the x positions map+ * to dates. */export function useDateRangeZoom(dates: string[] | undefined,onZoom: ((dateFrom: string, dateTo: string) => void) | undefineddiff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 1ae1330a7e3a..8a33cdfb9f1e 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -430,6 +430,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportPropertyGroupFilterRemoved: true,reportPropertyGroupFilterDuplicated: true,reportInsightDateRangeChanged: (queryKind: string | undefined) => ({ queryKind }),+ reportInsightDragToZoomed: (queryKind: string | undefined) => ({ queryKind }),reportInsightBreakdownChanged: (queryKind: string | undefined) => ({ queryKind }),reportInsightCompareChanged: (queryKind: string | undefined) => ({ queryKind }),reportChangeOuterPropertyGroupFiltersType: (type: FilterLogicalOperator, groupsLength: number) => ({@@ -1938,6 +1939,9 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportInsightDateRangeChanged: ({ queryKind }) => {posthog.capture('insight date range changed', { query_kind: queryKind })},+ reportInsightDragToZoomed: ({ queryKind }) => {+ posthog.capture('insight drag to zoomed', { query_kind: queryKind })+ },reportInsightBreakdownChanged: ({ queryKind }) => {posthog.capture('insight breakdown changed', { query_kind: queryKind })},diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.tsindex bfaaf7211c32..dc4fede3131f 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts@@ -479,16 +479,24 @@ describe('insightVizDataLogic', () => {describe('zoomDateRange', () => {it.each([- ['2024-06-10', '2024-06-12', false],- ['2024-06-10 08:00:00', '2024-06-10 14:00:00', true],- ])('zooms %s..%s with explicitDate=%s', async (dateFrom, dateTo, explicitDate) => {+ // [interval, dateFrom, dateTo (bucket start), expected date_to, explicitDate]+ ['day', '2024-06-10', '2024-06-12', '2024-06-12', false],+ // Coarser-than-day buckets: the end widens to the bucket's last day, so a+ // single-bucket drag (e.g. over one monthly bar) zooms into the whole bucket.+ ['week', '2024-06-09', '2024-06-09', '2024-06-15', false],+ ['month', '2024-04-01', '2024-04-01', '2024-04-30', false],+ // Sub-day buckets widen to the bucket's last second and pin explicitDate.+ ['hour', '2024-06-10 08:00:00', '2024-06-10 14:00:00', '2024-06-10 14:59:59', true],+ ])('zooms %s buckets %s..%s', async (interval, dateFrom, dateTo, expectedDateTo, explicitDate) => {+ builtInsightVizDataLogic.actions.updateQuerySource({ interval } as Partial<TrendsQuery>)+await expectLogic(builtInsightDataLogic, () => {builtInsightVizDataLogic.actions.zoomDateRange(dateFrom, dateTo)}).toFinishAllListeners()expect(builtInsightVizDataLogic.values.dateRange).toEqual({date_from: dateFrom,- date_to: dateTo,+ date_to: expectedDateTo,explicitDate,})})diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 1e4a7f3a7569..92cbda9f515d 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -106,6 +106,7 @@ import {ChartDisplayType,FunnelVizType,InsightLogicProps,+ IntervalType,LabelGroupType,SlowQueryPossibilities,} from '~/types'@@ -155,7 +156,8 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([updateQuerySource: (querySource: QuerySourceUpdate) => ({ querySource }),updateInsightFilter: (insightFilter: InsightFilter) => ({ insightFilter }),updateDateRange: (dateRange: DateRange, ignoreDebounce: boolean = false) => ({ dateRange, ignoreDebounce }),- /** Apply a drag-to-zoom date range to the insight's query. */+ /** Apply a drag-to-zoom date range to the insight's query. Both dates are bucket starts;+ * the end is widened to its bucket's end using the query's interval. */zoomDateRange: (dateFrom: string, dateTo: string) => ({ dateFrom, dateTo }),updateBreakdownFilter: (breakdownFilter: BreakdownFilter) => ({ breakdownFilter }),updateCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),@@ -676,10 +678,17 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([},zoomDateRange: ({ dateFrom, dateTo }) => {+ eventUsageLogic.actions.reportInsightDragToZoomed(values.querySource?.kind)+ // Charts emit bucket starts — widen the end to the last selected bucket's end, so+ // e.g. dragging over the "May" bar of a monthly chart zooms to all of May.// Sub-day buckets carry a time component; explicitDate stops the backend from// rounding them back out to whole days.actions.updateDateRange(- { date_from: dateFrom, date_to: dateTo, explicitDate: hasTimeComponent(dateFrom) },+ {+ date_from: dateFrom,+ date_to: dateRangeZoomEnd(dateTo, values.interval),+ explicitDate: hasTimeComponent(dateFrom),+ },true)},@@ -843,6 +852,25 @@ export function hasTimeComponent(date: string): boolean {return /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(date)}+/** Last moment of the bucket starting at `bucketStart`, so a zoom keeps all the data the user+ * selected. Drag-to-zoom emits bucket *starts*, so without widening only the last bucket's first+ * day/instant survives — e.g. selecting the "May" bar of a monthly chart must zoom to+ * `2026-05-01..2026-05-31`, not `..2026-05-01`. Day buckets need no widening (a bare date+ * already means the whole day), and without a known interval the start is returned as-is. */+export function dateRangeZoomEnd(bucketStart: string, interval: IntervalType | null | undefined): string {+ if (!interval || interval === 'day') {+ return bucketStart+ }+ const start = dayjs(bucketStart)+ if (!start.isValid()) {+ return bucketStart+ }+ if (interval === 'second' || interval === 'minute' || interval === 'hour') {+ return start.add(1, interval).subtract(1, 'second').format('YYYY-MM-DD HH:mm:ss')+ }+ return start.add(1, interval).subtract(1, 'day').format('YYYY-MM-DD')+}+const handleQuerySourceUpdateSideEffects = (update: QuerySourceUpdate,currentState: InsightQueryNode,diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 002a2d8863cf..eacd38e2140c 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -84,7 +84,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. 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. 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/core/interaction.test.ts b/packages/quill/packages/charts/src/core/interaction.test.tsindex c5bdee47e7ec..a6d61f3521d7 100644--- a/packages/quill/packages/charts/src/core/interaction.test.ts+++ b/packages/quill/packages/charts/src/core/interaction.test.ts@@ -300,7 +300,12 @@ describe('hog-charts interaction', () => {const single = buildLabelPositions(['a'], xScale)it.each([- { desc: 'fewer than two labels are positioned', rect: { x0: 50, x1: 500 }, pos: single, expected: null },+ {+ desc: 'a wide drag on a single-label chart (zooms into the only bucket)',+ rect: { x0: 50, x1: 500 },+ pos: single,+ expected: { startIndex: 0, endIndex: 0 },+ },// 160 → nearest 200 (index 1); 340 → nearest 300 (index 2){desc: 'a left-to-right drag',@@ -320,9 +325,19 @@ describe('hog-charts interaction', () => {pos: positions,expected: { startIndex: 0, endIndex: 4 },},+ // Sparse charts snap both drag edges to one label — a deliberate horizontal+ // drag selects that single bucket.{desc: 'both edges landing on the same label',- rect: { x0: 195, x1: 205 },+ rect: { x0: 180, x1: 220 },+ pos: positions,+ expected: { startIndex: 1, endIndex: 1 },+ },+ // A few px of x drift from a vertical-ish gesture must not zoom into the+ // hovered bucket.+ {+ desc: 'a same-label drag narrower than the single-bucket threshold',+ rect: { x0: 198, x1: 203 },pos: positions,expected: null,},diff --git a/packages/quill/packages/charts/src/core/interaction.ts b/packages/quill/packages/charts/src/core/interaction.tsindex f12961190117..9e075838f45e 100644--- a/packages/quill/packages/charts/src/core/interaction.ts+++ b/packages/quill/packages/charts/src/core/interaction.ts@@ -64,19 +64,29 @@ export function isInPlotArea(mouseX: number, mouseY: number, dimensions: ChartDi)}-// Returns null when fewer than 2 distinct labels are spanned.+// Horizontal extent (px) a same-label drag must span to count as a deliberate single-bucket+// zoom. On sparse charts both drag edges snap to one label, so without this a vertical-ish+// gesture (whose x drift is a few px) would zoom into the hovered bucket.+const SINGLE_LABEL_MIN_DRAG_PX = 8++/** Maps a drag selection to the spanned label range. A drag whose edges both snap to the same+ * label selects that single bucket, provided it spans enough horizontal distance to read as+ * intentional. Returns null when no labels are positioned or the drag is too narrow. */export function dragRectToLabelRange(rect: DragRect,labelPositions: LabelPosition[]): { startIndex: number; endIndex: number } | null {- if (labelPositions.length < 2) {+ if (labelPositions.length === 0) {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) {+ if (startIndex < 0 || endIndex < 0) {+ return null+ }+ if (startIndex === endIndex && hi - lo < SINGLE_LABEL_MIN_DRAG_PX) {return null}const [s, e] = startIndex < endIndex ? [startIndex, endIndex] : [endIndex, startIndex]diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsxindex ae0c707bf3c1..0582b2c2b208 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx@@ -2,7 +2,7 @@ import '@testing-library/jest-dom'import { cleanup, configure, screen, waitFor } from '@testing-library/react'-import { dragSelection, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'+import { dimensions, dragSelection, rawDrag, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'import { FEATURE_FLAGS } from 'lib/constants'@@ -711,6 +711,23 @@ describe('TrendsLineChart', () => {})})+ it('reports a drag that stays within a single bucket as that bucket', async () => {+ const onDateRangeZoom = jest.fn()+ renderInsight({ query: buildTrendsQuery(), context: { onDateRangeZoom }, featureFlags: zoomFlag })+ const wrapper = await getChartWrapper()++ // Both drag edges snap to the same label — the common case on sparse charts+ // (e.g. a 3-bar monthly chart), where this used to be a silent no-op.+ const step = dimensions.plotWidth / (totalLabels - 1)+ const x = dimensions.plotLeft + step+ const y = dimensions.plotTop + dimensions.plotHeight / 2+ rawDrag(wrapper, { from: { x: x - 40, y }, to: { x: x + 40, y } })++ await waitFor(() => {+ expect(onDateRangeZoom).toHaveBeenCalledWith('2024-06-11', '2024-06-11')+ })+ })+it('ignores drags when the drag-to-zoom flag is off', async () => {const onDateRangeZoom = jest.fn()renderInsight({ query: buildTrendsQuery(), context: { onDateRangeZoom } })