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(insights): drag-to-zoom into a date range on trends charts (#69166)

Sam Penningtonba945a9b636a
diff --git a/frontend/src/lib/charts/hooks.ts b/frontend/src/lib/charts/hooks.ts
index 3581343f48c4..edae5b1330aa 100644
--- a/frontend/src/lib/charts/hooks.ts
+++ b/frontend/src/lib/charts/hooks.ts
@@ -1,7 +1,7 @@
import { useValues } from 'kea'
-import { type DependencyList, useMemo } from 'react'
+import { type DependencyList, useCallback, useMemo } from 'react'
-import type { ChartTheme } from '@posthog/quill-charts'
+import type { ChartTheme, DateRangeZoomData } from '@posthog/quill-charts'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -48,6 +48,39 @@ export function useChartTheme(overrides?: Partial<ChartTheme>): ChartTheme {
)
}
+/** The single rollout gate for chart drag-to-zoom, applied inside `useDateRangeZoom` so every
+ * surface is enabled (and testable) through one check rather than per-host flag reads. */
+export function useDragToZoomEnabled(): boolean {
+ const { featureFlags } = useValues(featureFlagLogic)
+ return !!featureFlags[FEATURE_FLAGS.INSIGHT_DRAG_TO_ZOOM]
+}
+
+/** 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. */
+export function useDateRangeZoom(
+ dates: string[] | undefined,
+ onZoom: ((dateFrom: string, dateTo: string) => void) | undefined
+): ((data: DateRangeZoomData) => void) | undefined {
+ const enabled = useDragToZoomEnabled()
+ const handler = useCallback(
+ ({ startIndex, endIndex }: DateRangeZoomData) => {
+ const start = dates?.[startIndex]
+ const end = dates?.[endIndex]
+ if (!start || !end) {
+ return
+ }
+ // Screen order isn't guaranteed chronological (e.g. unsorted SQL results).
+ const [dateFrom, dateTo] = start <= end ? [start, end] : [end, start]
+ onZoom?.(dateFrom, dateTo)
+ },
+ [dates, onZoom]
+ )
+ return enabled && dates?.length && onZoom ? handler : undefined
+}
+
/** Drop-in replacement for the `useMemo` that builds a chart's config object. On top of memoizing,
* it applies app-level rendering defaults — currently the refreshed style (monotone curve, axis
* lines, tick marks, crosshair, grid) behind `QUILL_CHART_STYLE_REFRESH`. Keys the config sets
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b79ca8b7c3d7..fec89ef28f39 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -336,6 +336,7 @@ export const FEATURE_FLAGS = {
HOGQL_WAREHOUSE_ACCESS_CONTROL: 'hogql-warehouse-access-control', // owner: @a-lider #team-platform-features, gates per-object access control for warehouse tables and views
IDENTITY_MATCHING: 'identity-matching', // owner: @fercgomes #team-growth, gates new identity matching scene on marketing analytics
INBOX_SLACK_NOTIFICATIONS: 'inbox-slack-notifications', // owner: #team-self-driving, gates the Slack notifications config card in the inbox
+ INSIGHT_DRAG_TO_ZOOM: 'insight-drag-to-zoom', // owner: @sampennington #team-product-analytics, gates x-axis drag-to-zoom on insight charts (trends today, SQL to follow)
INSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,test
INTER_PROJECT_TRANSFERS: 'inter-project-transfers', // owner: @reecejones #team-platform-features
JS_SNIPPET_VERSIONING: 'js-snippet-versioning', // owner: #team-client-libraries
diff --git a/frontend/src/scenes/insights/InsightAsScene.tsx b/frontend/src/scenes/insights/InsightAsScene.tsx
index 99693042b4d6..18945f52729b 100644
--- a/frontend/src/scenes/insights/InsightAsScene.tsx
+++ b/frontend/src/scenes/insights/InsightAsScene.tsx
@@ -19,6 +19,7 @@ import { InsightRetentionBanner } from './dataRetention/InsightRetentionBanner'
import { insightDataLogic } from './insightDataLogic'
import { insightLogic } from './insightLogic'
import { InsightSceneHeader } from './InsightSceneHeader'
+import { insightVizDataLogic } from './insightVizDataLogic'
export interface InsightAsSceneProps {
insightId: InsightShortId | 'new'
@@ -45,6 +46,7 @@ export function InsightAsScene({ insightId, attachTo }: InsightAsSceneProps): JS
// insightDataLogic
const { query, showQueryEditor } = useValues(insightDataLogic(insightProps))
const { setQuery: setInsightQuery } = useActions(insightDataLogic(insightProps))
+ const { zoomDateRange } = useActions(insightVizDataLogic(insightProps))
useFileSystemLogView({
type: 'insight',
@@ -104,6 +106,8 @@ export function InsightAsScene({ insightId, attachTo }: InsightAsSceneProps): JS
showQueryEditor: actuallyShowQueryEditor,
showQueryHelp: insightMode === ItemMode.Edit && !containsHogQLQuery(query),
insightProps,
+ // Flag-gated inside the charts' shared useDateRangeZoom hook.
+ onDateRangeZoom: zoomDateRange,
}}
filtersOverride={filtersOverride}
variablesOverride={variablesOverride}
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
index 58f416d817e5..d1215f2fe12d 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
@@ -411,6 +411,38 @@ describe('insightVizDataLogic', () => {
},
})
})
+
+ it.each([
+ ['2024-06-10 08:00:00', '2024-06-10 14:00:00', 'minute'],
+ // A bare same-day pair means "that whole day" and must stay hourly, not 1440 minute buckets
+ ['2024-06-10', '2024-06-10', 'hour'],
+ // A time-carrying range over 12 hours must not go sub-hour
+ ['2024-06-10 08:00:00', '2024-06-11 20:00:00', 'hour'],
+ ['2024-06-01', '2024-07-15', 'day'],
+ ])('auto-adjusts interval for absolute range %s..%s to %s', async (dateFrom, dateTo, expectedInterval) => {
+ await expectLogic(builtInsightDataLogic, () => {
+ builtInsightVizDataLogic.actions.updateDateRange({ date_from: dateFrom, date_to: dateTo }, true)
+ }).toFinishAllListeners()
+
+ expect((builtInsightVizDataLogic.values.querySource as TrendsQuery).interval).toBe(expectedInterval)
+ })
+ })
+
+ 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) => {
+ await expectLogic(builtInsightDataLogic, () => {
+ builtInsightVizDataLogic.actions.zoomDateRange(dateFrom, dateTo)
+ }).toFinishAllListeners()
+
+ expect(builtInsightVizDataLogic.values.dateRange).toEqual({
+ date_from: dateFrom,
+ date_to: dateTo,
+ explicitDate,
+ })
+ })
})
describe('updateBreakdownFilter', () => {
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 33992124f845..f2a2229883f8 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -155,6 +155,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. */
+ zoomDateRange: (dateFrom: string, dateTo: string) => ({ dateFrom, dateTo }),
updateBreakdownFilter: (breakdownFilter: BreakdownFilter) => ({ breakdownFilter }),
updateCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),
updateDisplay: (display: ChartDisplayType | undefined) => ({ display }),
@@ -673,6 +675,15 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
} as Node)
},
+ zoomDateRange: ({ dateFrom, dateTo }) => {
+ // 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) },
+ true
+ )
+ },
+
// query source properties
updateDateRange: async ({ dateRange, ignoreDebounce }, breakpoint) => {
cache.pendingFilterUpdateCancelled = false
@@ -826,6 +837,12 @@ const getActiveUsersMath = (
return null
}
+/** Whether a date string carries a time of day, e.g. drag-to-zoom on an hourly chart emits
+ * `2024-06-10 08:00:00`. A bare `YYYY-MM-DD` means "that whole day". */
+export function hasTimeComponent(date: string): boolean {
+ return /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(date)
+}
+
const handleQuerySourceUpdateSideEffects = (
update: QuerySourceUpdate,
currentState: InsightQueryNode,
@@ -951,7 +968,13 @@ const handleQuerySourceUpdateSideEffects = (
const monthDiff = parsedTo.diff(parsedFrom, 'month')
// 3 years in months; quarter auto-interval kicks in beyond this threshold
const QUARTER_AUTO_INTERVAL_THRESHOLD_MONTHS = 36
- if (parsedTo.diff(parsedFrom, 'day') <= 3) {
+ // A bare date pair like 2024-06-10..2024-06-10 means "that whole day", so only ranges
+ // that carry a time component (e.g. drag-to-zoom on an hourly chart) can go sub-hour.
+ const rangeHasTime = hasTimeComponent(String(date_from)) || hasTimeComponent(String(date_to))
+ if (isTrendsQuery(currentState) && rangeHasTime && parsedTo.diff(parsedFrom, 'hour', true) <= 12) {
+ // Mirrors the is12HoursOrLess rule for relative ranges below.
+ ;(mergedUpdate as TrendsQuery).interval = 'minute'
+ } else if (parsedTo.diff(parsedFrom, 'day') <= 3) {
;(mergedUpdate as TrendsQuery).interval = 'hour'
} else if (monthDiff <= 3) {
;(mergedUpdate as TrendsQuery).interval = 'day'
@@ -1050,22 +1073,19 @@ const handleQuerySourceUpdateSideEffects = (
// If the user changes the interval to 'minute' and the date_range is more than 12 hours, reset it to 1 hour
if (kind == NodeKind.TrendsQuery && (mergedUpdate as TrendsQuery)?.interval == 'minute' && interval !== 'minute') {
const { date_from, date_to } = { ...currentState.dateRange, ...update.dateRange }
+ const isAbsoluteRange = !!date_from && !!date_to && dayjs(date_from).isValid() && dayjs(date_to).isValid()
if (
// When insights are created, they might not have an explicit dateRange set. Change it to an hour if the interval is minute.
(!date_from && !date_to) ||
// If the interval is set manually to a range greater than 12 hours, change it to an hour
- (date_from &&
- date_to &&
- dayjs(date_from).isValid() &&
- dayjs(date_to).isValid() &&
- dayjs(date_to).diff(dayjs(date_from), 'hour') > 12)
+ (isAbsoluteRange && dayjs(date_to).diff(dayjs(date_from), 'hour') > 12) ||
+ // Relative ranges (e.g. -7d) must be 12 hours or less; an absolute range that reaches
+ // here already passed the >12h check above, so it stays (is12HoursOrLess only parses
+ // relative strings and would wrongly reset it).
+ (!isAbsoluteRange && !is12HoursOrLess(date_from))
) {
;(mergedUpdate as TrendsQuery).dateRange = oneHourDateRange
- } else {
- if (!is12HoursOrLess(date_from)) {
- ;(mergedUpdate as TrendsQuery).dateRange = oneHourDateRange
- }
}
}
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index f7118deb5e88..002a2d8863cf 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`/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.
+- `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).
## Testing
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
index 96db857ca3e9..d63bbbb630bf 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
@@ -673,4 +673,38 @@ describe('BarChart', () => {
expect(getHogChart(container).seriesCount).toBe(2)
})
})
+
+ describe('drag-to-zoom', () => {
+ const FIVE_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
+ const FIVE_SERIES: Series[] = [{ key: 'a', label: 'A', data: [10, 20, 30, 40, 50] }]
+
+ it('fires onDateRangeZoom with the dragged label range on vertical bars', () => {
+ const onDateRangeZoom = jest.fn()
+ const { chart } = renderHogChart(
+ <BarChart series={FIVE_SERIES} labels={FIVE_LABELS} theme={THEME} onDateRangeZoom={onDateRangeZoom} />
+ )
+ chart.dragSelection(1, 3)
+ expect(onDateRangeZoom).toHaveBeenCalledWith({
+ startLabel: 'Tue',
+ endLabel: 'Thu',
+ startIndex: 1,
+ endIndex: 3,
+ })
+ })
+
+ it('does not fire on horizontal bars, whose interaction axis is vertical', () => {
+ const onDateRangeZoom = jest.fn()
+ const { chart } = renderHogChart(
+ <BarChart
+ series={FIVE_SERIES}
+ labels={FIVE_LABELS}
+ theme={THEME}
+ config={{ axisOrientation: 'horizontal' }}
+ onDateRangeZoom={onDateRangeZoom}
+ />
+ )
+ chart.dragSelection(1, 3)
+ expect(onDateRangeZoom).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
index d6880a4ced6c..4d29a22cdaf9 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
@@ -26,6 +26,7 @@ import type {
ChartScales,
ChartTheme,
CreateScalesFn,
+ DateRangeZoomData,
DrawHoverResult,
PointClickData,
ResolvedSeries,
@@ -47,6 +48,9 @@ export interface BarChartProps<Meta = unknown> {
theme: ChartTheme
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Enables x-axis drag-to-zoom. Vertical bars only — horizontal bars interact along y,
+ * where the gesture is disabled by the core. See `ChartProps.onDateRangeZoom`. */
+ onDateRangeZoom?: (data: DateRangeZoomData) => void
className?: string
/** `data-attr` applied to the chart wrapper. See `ChartProps.dataAttr`. */
dataAttr?: string
@@ -69,6 +73,7 @@ function BarChartInner<Meta = unknown>({
theme,
tooltip,
onPointClick,
+ onDateRangeZoom,
className,
dataAttr,
children,
@@ -431,6 +436,7 @@ function BarChartInner<Meta = unknown>({
/>
)}
onPointClick={onPointClick}
+ onDateRangeZoom={onDateRangeZoom}
wrapClickData={onPointClick ? wrapClickData : undefined}
resolveHoverIndex={seriesHasTrackCeiling ? resolveHoverIndex : undefined}
className={className}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index f95797a4be90..a63cd3dcbee5 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -7,6 +7,7 @@ import type {
BarFillStyle,
ChartLegendConfig,
ChartTheme,
+ DateRangeZoomData,
PointClickData,
Series,
TooltipConfig,
@@ -64,6 +65,8 @@ export interface TimeSeriesBarChartProps<Meta = unknown> {
config?: TimeSeriesBarChartConfig
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Enables x-axis drag-to-zoom. See `BarChartProps.onDateRangeZoom`. */
+ onDateRangeZoom?: (data: DateRangeZoomData) => void
dataAttr?: string
className?: string
children?: React.ReactNode
@@ -77,6 +80,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
config,
tooltip,
onPointClick,
+ onDateRangeZoom,
dataAttr,
className,
children,
@@ -154,6 +158,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
theme={theme}
tooltip={tooltip}
onPointClick={onPointClick}
+ onDateRangeZoom={onDateRangeZoom}
className={className}
dataAttr={dataAttr}
onError={onError}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index 275fe6df1868..295299934642 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -12,7 +12,7 @@ import {
} from '@posthog/quill-charts'
import type { BarChartConfig, PointClickData, TimeSeriesBarChartConfig, TooltipContext } from '@posthog/quill-charts'
-import { useChartTheme, useChartConfig } from 'lib/charts/hooks'
+import { useChartTheme, useChartConfig, useDateRangeZoom } from 'lib/charts/hooks'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { percentage } from 'lib/utils/numbers'
@@ -362,6 +362,9 @@ export function TrendsBarChart({
[isAggregated, clickDeps]
)
+ // Time-series layouts only — the aggregated bar-value layout has categorical labels, not dates.
+ const onDateRangeZoom = useDateRangeZoom(currentPeriodResult?.days, context?.onDateRangeZoom)
+
const renderTooltip = useCallback(
(ctx: TooltipContext<TrendsSeriesMeta>) => {
// BarTooltip already put the cursor-visible segment at seriesData[0] — keep just that.
@@ -483,6 +486,7 @@ export function TrendsBarChart({
theme={theme}
tooltip={renderTooltip}
onPointClick={canHandleClick ? onPointClick : undefined}
+ onDateRangeZoom={onDateRangeZoom}
className="BarGraph"
dataAttr="trend-bar-graph"
onError={handleChartError}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
index 2c6ddb4573e6..ae0c707bf3c1 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 { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
+import { dragSelection, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -13,9 +13,11 @@ import {
chart,
createInsightTooltipAccessor,
getHogChart,
+ getQuerySource,
legend,
personsModal,
renderInsight,
+ trendsSeries,
} from '~/test/insight-testing'
import { buildAnnotation } from '~/test/insight-testing/test-data'
import { AnnotationScope, ChartDisplayType } from '~/types'
@@ -686,4 +688,47 @@ describe('TrendsLineChart', () => {
expect(legendEl.querySelector('button')).not.toBeInTheDocument()
})
})
+
+ describe('drag-to-zoom', () => {
+ const totalLabels = trendsSeries.pageviews.labels.length
+ const zoomFlag = { [FEATURE_FLAGS.INSIGHT_DRAG_TO_ZOOM]: true }
+
+ async function getChartWrapper(): Promise<HTMLElement> {
+ const canvas = await screen.findByLabelText(/chart with/i)
+ return canvas.parentElement!
+ }
+
+ it('reports the dragged range as day strings to context.onDateRangeZoom', async () => {
+ const onDateRangeZoom = jest.fn()
+ renderInsight({ query: buildTrendsQuery(), context: { onDateRangeZoom }, featureFlags: zoomFlag })
+ const wrapper = await getChartWrapper()
+
+ dragSelection(wrapper, 1, 3, totalLabels)
+
+ await waitFor(() => {
+ // Days, not the formatted axis labels ('Tue'/'Thu') the chart renders with.
+ expect(onDateRangeZoom).toHaveBeenCalledWith('2024-06-11', '2024-06-13')
+ })
+ })
+
+ it('ignores drags when the drag-to-zoom flag is off', async () => {
+ const onDateRangeZoom = jest.fn()
+ renderInsight({ query: buildTrendsQuery(), context: { onDateRangeZoom } })
+ const wrapper = await getChartWrapper()
+
+ dragSelection(wrapper, 1, 3, totalLabels)
+
+ // A regression dropping the flag gate would ship zoom to everyone.
+ expect(onDateRangeZoom).not.toHaveBeenCalled()
+ })
+
+ it('ignores drags when no context handler opts in', async () => {
+ renderInsight({ query: buildTrendsQuery(), featureFlags: zoomFlag })
+ const wrapper = await getChartWrapper()
+
+ dragSelection(wrapper, 1, 3, totalLabels)
+
+ expect(getQuerySource().dateRange).toBeUndefined()
+ })
+ })
})
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index 97dcea64e4de..553b571a621f 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -4,7 +4,7 @@ import { useCallback, useMemo } from 'react'
import { DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from '@posthog/quill-charts'
import type { PointClickData, TooltipContext } from '@posthog/quill-charts'
-import { useChartTheme, useChartConfig } from 'lib/charts/hooks'
+import { useChartTheme, useChartConfig, useDateRangeZoom } from 'lib/charts/hooks'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ciRanges } from 'lib/statistics'
@@ -166,6 +166,8 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
[clickDeps]
)
+ const onDateRangeZoom = useDateRangeZoom(currentPeriodResult?.days, context?.onDateRangeZoom)
+
const renderTooltip = useCallback(
(ctx: TooltipContext<TrendsSeriesMeta>) => {
const onRowClick = canHandleClick
@@ -316,6 +318,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
config={config}
tooltip={renderTooltip}
onPointClick={canHandleClick ? onPointClick : undefined}
+ onDateRangeZoom={onDateRangeZoom}
className="LineGraph"
dataAttr="trend-line-graph"
onError={handleChartError}