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(retention): port retention line graph to hog-charts (#59586)

Sam Penningtonfc97aefdac88
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1be3ff3ed6fb..a95843947efe 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4579,13 +4579,13 @@ snapshots:
scenes-app-insights-funnels--funnel-historical-trends-edit--light:
hash: v1.k794b7964.fa67675b6f95f0ae9c46eb0e803f9db69702419bb4ccc2d21ea973f9fe49d9cc.Zz4siV83g7nIXf96Nfvy6eN5rRtzwO3CEmv24KSztlA
scenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--dark:
- hash: v1.k794b7964.f6de0cbb8ff4db4abb374918743a1b38393b06926ea7207a60d6abc9bb2e44db.e7-4xmfdXMqJXpPCBmNg9NgnvNs0FUKUeQXo_9SfJgM
+ hash: v1.k794b7964.da7408ac759f81d6f806ad8994073060aeb28223f270e4a56fa0967acf741486.0hk563fxOgKIbDMQGLOr5V6tz4DB_FAWR96ASmtYcqE
scenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--light:
hash: v1.k794b7964.414326f685dca45885b93d728ae8a75c7d8b600af35d76c9512a74a27e453006.IyZ8qHUwOv6qsBYvdUR1ZsK1Md_GNFCftDGvNZj78BQ
scenes-app-insights-funnels--funnel-left-to-right-edit--dark:
hash: v1.k794b7964.b018c83c850711c9ec18c2bf6613e4412aece8bfddcaef16bd6045909b551111.DqurIx1t3SZ5ai2h5rVn589syUhmx87W93eKPMIaTnA
scenes-app-insights-funnels--funnel-left-to-right-edit--light:
- hash: v1.k794b7964.b064f0872c3d2f28a37fc2e35d6df7b343068dbb76e001be1262ec621a716f0b.mjq7RAGWI7rRQMgNsLwECFKQq2qQEZtq91bUDeQ0E_Q
+ hash: v1.k794b7964.1a564a7e326dd6ce74422aeec8cc336763529a54aac381e2c3039c950f73e0b9.wumhgGqgZsmHlAU_iVgKRQ3b3hEQXtCDIIvV5YMwt3g
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--medium--dark:
hash: v1.k794b7964.36814bd223fdaa124f92bbc2b45de89865c13890bf5f7a14179029dc7f33ca27.jq91_V-Z1EaJWopXWnh8EuqryG4eGkFxCIgXLCwkpv8
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--medium--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index f3a59de2fddd..be648967beb0 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -419,6 +419,7 @@ export const FEATURE_FLAGS = {
PRODUCT_ANALYTICS_HOG_CHARTS: 'product-analytics-hog-charts', // owner: @sampennington #team-product-analytics
PRODUCT_ANALYTICS_HOG_CHARTS_BAR: 'product-analytics-hog-charts-bar', // owner: @sampennington #team-product-analytics
PRODUCT_ANALYTICS_HOG_CHARTS_FUNNEL: 'product-analytics-hog-charts-funnel', // owner: @sampennington #team-product-analytics
+ PRODUCT_ANALYTICS_HOG_CHARTS_RETENTION_LINE: 'product-analytics-hog-charts-retention-line', // owner: @sampennington #team-product-analytics
PRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics
PRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analytics
PRODUCT_ANALYTICS_RETENTION_AGGREGATION: 'retention-aggregation', // owner: @anirudhpillai #team-product-analytics
diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.scss b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
index 121e4295f981..4acf3e4b7f9f 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightViz.scss
+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
@@ -160,7 +160,13 @@
width: 100%;
.RetentionContainer__graph {
+ // Flex column so the hog-charts wrapper (inline `flex: 1`) fills it.
+ // min-height lives here, not on .LineGraph, because the wrapper's inline
+ // `min-height: 0` would override a class rule set directly on .LineGraph.
+ display: flex;
flex: 1;
+ flex-direction: column;
+ min-height: 30vh;
margin: 0.5rem;
}
@@ -171,17 +177,18 @@
.LineGraph {
position: relative !important;
width: 100% !important;
- height: 100%;
- min-height: 30vh;
}
.NotebookNode &,
.InsightCard &,
.ExportedInsight &,
.WebAnalyticsDashboard & {
+ .RetentionContainer__graph {
+ min-height: 100px;
+ }
+
.LineGraph {
position: relative;
- min-height: 100px;
}
}
}
diff --git a/frontend/src/scenes/retention/RetentionGraph.tsx b/frontend/src/scenes/retention/RetentionGraph.tsx
index 43e7d59e24f6..371f8f758d10 100644
--- a/frontend/src/scenes/retention/RetentionGraph.tsx
+++ b/frontend/src/scenes/retention/RetentionGraph.tsx
@@ -1,5 +1,7 @@
import { useActions, useValues } from 'kea'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { roundToDecimal } from 'lib/utils'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -8,6 +10,7 @@ import { ChartDisplayType, GraphDataset, GraphType } from '~/types'
import { InsightEmptyState } from '../insights/EmptyStates'
import { LineGraph } from '../insights/views/LineGraph/LineGraph'
+import { RetentionGraphHogCharts } from './RetentionGraphHogCharts'
import { retentionGraphLogic } from './retentionGraphLogic'
import { retentionModalLogic } from './retentionModalLogic'
@@ -27,6 +30,7 @@ function displayTypeToGraphType(displayType: ChartDisplayType): GraphType {
export function RetentionGraph({ inSharedMode = false }: RetentionGraphProps): JSX.Element | null {
const { insightProps } = useValues(insightLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
const {
hasValidBreakdown,
retentionFilter,
@@ -43,6 +47,12 @@ export function RetentionGraph({ inSharedMode = false }: RetentionGraphProps): J
const isPercentage = !retentionFilter?.aggregationType || retentionFilter.aggregationType === 'count'
+ const isBarDisplay = retentionFilter?.display === ChartDisplayType.ActionsBar
+ // Bar display still uses the legacy d3 graph — the hog-charts bar path lands separately.
+ if (!isBarDisplay && featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_RETENTION_LINE]) {
+ return <RetentionGraphHogCharts inSharedMode={inSharedMode} />
+ }
+
if (filteredTrendSeries.length === 0 && hasValidBreakdown) {
return (
<p className="w-full m-0 text-center text-sm text-gray-500">
diff --git a/frontend/src/scenes/retention/RetentionGraphHogCharts.tsx b/frontend/src/scenes/retention/RetentionGraphHogCharts.tsx
new file mode 100644
index 000000000000..e0fa16b56d0f
--- /dev/null
+++ b/frontend/src/scenes/retention/RetentionGraphHogCharts.tsx
@@ -0,0 +1,174 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useCallback, useMemo, type ErrorInfo } from 'react'
+
+import { buildTheme } from 'lib/charts/utils/theme'
+import { TimeSeriesLineChart } from 'lib/hog-charts'
+import type { PointClickData, TooltipConfig, TooltipContext } from 'lib/hog-charts'
+import { insightLogic } from 'scenes/insights/insightLogic'
+import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+import { groupsModel } from '~/models/groupsModel'
+import type { GoalLine } from '~/queries/schema/schema-general'
+import type { GroupTypeIndex, LabelGroupType } from '~/types'
+
+import {
+ buildRetentionLineChartConfig,
+ buildRetentionSeries,
+ type RetentionSeriesMeta,
+ type RetentionTrendSeriesEntry,
+} from './retentionChartTransforms'
+import { retentionGraphLogic } from './retentionGraphLogic'
+import { retentionModalLogic } from './retentionModalLogic'
+import { RetentionTooltip } from './RetentionTooltip'
+
+interface RetentionGraphHogChartsProps {
+ inSharedMode?: boolean
+}
+
+const TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'top' }
+const EMPTY_GOAL_LINES: GoalLine[] = []
+
+const handleChartError = (error: Error, info: ErrorInfo): void => {
+ posthog.captureException(error, {
+ feature: 'retention-graph',
+ componentStack: info.componentStack ?? undefined,
+ })
+}
+
+function resolveGroupTypeLabel(
+ labelGroupType: LabelGroupType | 'none',
+ aggregationLabel: (index: GroupTypeIndex) => { plural: string }
+): string {
+ if (labelGroupType === 'people') {
+ return 'people'
+ }
+ if (labelGroupType === 'none') {
+ return ''
+ }
+ return aggregationLabel(labelGroupType).plural
+}
+
+export function RetentionGraphHogCharts({ inSharedMode = false }: RetentionGraphHogChartsProps): JSX.Element | null {
+ const { insightProps } = useValues(insightLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+
+ const {
+ hasValidBreakdown,
+ retentionFilter,
+ filteredTrendSeries,
+ incompletenessOffsetFromEnd,
+ labelGroupType,
+ shouldShowMeanPerBreakdown,
+ showTrendLines,
+ xAxisLabels,
+ } = useValues(retentionGraphLogic(insightProps))
+ const { openModal } = useActions(retentionModalLogic(insightProps))
+ const { aggregationLabel } = useValues(groupsModel)
+
+ const selectedInterval = retentionFilter?.selectedInterval ?? null
+ const period = retentionFilter?.period
+ const isPercentage = !retentionFilter?.aggregationType || retentionFilter.aggregationType === 'count'
+ const isIntervalView = selectedInterval !== null
+ // Shared (public) views don't have the persons modal mounted — disable click-to-open there.
+ const canClick = !shouldShowMeanPerBreakdown && !inSharedMode
+
+ const series = useMemo(
+ () =>
+ buildRetentionSeries(filteredTrendSeries as RetentionTrendSeriesEntry[], {
+ incompletenessOffsetFromEnd,
+ isIntervalView,
+ }),
+ [filteredTrendSeries, incompletenessOffsetFromEnd, isIntervalView]
+ )
+
+ const groupTypeLabel = resolveGroupTypeLabel(labelGroupType, aggregationLabel)
+
+ const onRowClick = useCallback(
+ (datum: SeriesDatum) => {
+ if (shouldShowMeanPerBreakdown) {
+ return
+ }
+ // In interval view each x-position is a different cohort, otherwise each series is.
+ const rowIndex = isIntervalView
+ ? datum.dataIndex
+ : (series[datum.datasetIndex]?.meta?.rowIndex ?? datum.datasetIndex)
+ if (rowIndex !== undefined) {
+ openModal(rowIndex)
+ }
+ },
+ [shouldShowMeanPerBreakdown, isIntervalView, series, openModal]
+ )
+
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext<RetentionSeriesMeta>) => (
+ <RetentionTooltip
+ context={ctx}
+ xAxisLabels={xAxisLabels}
+ period={period}
+ selectedInterval={selectedInterval}
+ shouldShowMeanPerBreakdown={shouldShowMeanPerBreakdown}
+ isPercentage={isPercentage}
+ groupTypeLabel={groupTypeLabel}
+ onRowClick={canClick ? onRowClick : undefined}
+ />
+ ),
+ [
+ xAxisLabels,
+ period,
+ selectedInterval,
+ shouldShowMeanPerBreakdown,
+ isPercentage,
+ groupTypeLabel,
+ onRowClick,
+ canClick,
+ ]
+ )
+
+ const onPointClick = useCallback(
+ (clickData: PointClickData<RetentionSeriesMeta>) => {
+ if (shouldShowMeanPerBreakdown) {
+ return
+ }
+ const rowIndex = isIntervalView
+ ? clickData.dataIndex
+ : (clickData.series.meta?.rowIndex ?? clickData.seriesIndex)
+ if (rowIndex !== undefined) {
+ openModal(rowIndex)
+ }
+ },
+ [shouldShowMeanPerBreakdown, isIntervalView, openModal]
+ )
+
+ const goalLines = retentionFilter?.goalLines ?? EMPTY_GOAL_LINES
+
+ const lineConfig = useMemo(
+ () =>
+ buildRetentionLineChartConfig({ isPercentage, goalLines, showTrendLines, series, tooltip: TOOLTIP_CONFIG }),
+ [isPercentage, goalLines, showTrendLines, series]
+ )
+
+ if (filteredTrendSeries.length === 0 && hasValidBreakdown) {
+ return (
+ <p className="w-full m-0 text-center text-sm text-gray-500">
+ Select a breakdown to see the retention graph
+ </p>
+ )
+ }
+
+ return (
+ <TimeSeriesLineChart<RetentionSeriesMeta>
+ series={series}
+ labels={xAxisLabels}
+ theme={theme}
+ config={lineConfig}
+ tooltip={renderTooltip}
+ onPointClick={canClick ? onPointClick : undefined}
+ className="LineGraph"
+ dataAttr="trend-line-graph"
+ onError={handleChartError}
+ />
+ )
+}
diff --git a/frontend/src/scenes/retention/RetentionTooltip.tsx b/frontend/src/scenes/retention/RetentionTooltip.tsx
new file mode 100644
index 000000000000..2450c97a87f7
--- /dev/null
+++ b/frontend/src/scenes/retention/RetentionTooltip.tsx
@@ -0,0 +1,83 @@
+import { useCallback, useMemo } from 'react'
+
+import type { TooltipContext } from 'lib/hog-charts'
+import { roundToDecimal } from 'lib/utils'
+import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
+import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
+
+import type { RetentionSeriesMeta } from './retentionChartTransforms'
+
+const NOOP = (): void => {}
+
+interface RetentionTooltipProps {
+ context: TooltipContext<RetentionSeriesMeta>
+ xAxisLabels: string[]
+ period?: string
+ selectedInterval: number | null
+ shouldShowMeanPerBreakdown: boolean
+ isPercentage: boolean
+ groupTypeLabel?: string
+ onRowClick?: (datum: SeriesDatum) => void
+}
+
+export function RetentionTooltip({
+ context,
+ xAxisLabels,
+ period,
+ selectedInterval,
+ shouldShowMeanPerBreakdown,
+ isPercentage,
+ groupTypeLabel,
+ onRowClick,
+}: RetentionTooltipProps): React.ReactElement {
+ const seriesData = useMemo<SeriesDatum[]>(
+ () =>
+ context.seriesData
+ .map((entry, idx) => ({
+ id: idx,
+ dataIndex: context.dataIndex,
+ datasetIndex: idx,
+ order: entry.series.meta?.rowIndex ?? idx,
+ label: entry.series.label,
+ color: entry.color,
+ count: entry.value,
+ breakdown_value:
+ entry.series.meta?.breakdown_value != null
+ ? String(entry.series.meta.breakdown_value)
+ : undefined,
+ }))
+ // Show highest values first, matching the legacy LineGraph tooltip.
+ .sort((a, b) => b.count - a.count || (a.label ?? '').localeCompare(b.label ?? ''))
+ .map((datum, id) => ({ ...datum, id })),
+ [context.seriesData, context.dataIndex]
+ )
+
+ const renderCount = useCallback(
+ (value: number): string => (isPercentage ? `${roundToDecimal(value)}%` : `${roundToDecimal(value)}`),
+ [isPercentage]
+ )
+
+ const renderSeries = useCallback(
+ (value: React.ReactNode): React.ReactElement => {
+ const showCohortPrefix = selectedInterval !== null || !shouldShowMeanPerBreakdown
+ return <>{showCohortPrefix ? <>Cohort {value}</> : value}</>
+ },
+ [selectedInterval, shouldShowMeanPerBreakdown]
+ )
+
+ const title =
+ selectedInterval !== null ? `${period} ${selectedInterval}` : (xAxisLabels[context.dataIndex] ?? context.label)
+
+ return (
+ <InsightTooltip
+ altTitle={title}
+ seriesData={seriesData}
+ groupTypeLabel={groupTypeLabel}
+ onClose={context.onUnpin ?? NOOP}
+ renderSeries={renderSeries}
+ renderCount={renderCount}
+ onRowClick={onRowClick}
+ hideInspectActorsSection={!onRowClick}
+ />
+ )
+}
diff --git a/frontend/src/scenes/retention/retentionChartTransforms.ts b/frontend/src/scenes/retention/retentionChartTransforms.ts
new file mode 100644
index 000000000000..1a8410dc558b
--- /dev/null
+++ b/frontend/src/scenes/retention/retentionChartTransforms.ts
@@ -0,0 +1,94 @@
+import type { GoalLineConfig, Series, TimeSeriesLineChartConfig, TooltipConfig, TrendLineConfig } from 'lib/hog-charts'
+
+import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'
+
+import { schemaGoalLinesToConfigs } from '../trends/viz/shared/goalLinesAdapter'
+import type { RetentionTrendPayload } from './types'
+
+// `retentionGraphLogic.trendSeries` spreads `cohortRetention` onto each entry, so the
+// runtime shape includes a cohort `label` field that the declared type doesn't list.
+export type RetentionTrendSeriesEntry = RetentionTrendPayload & { label?: string }
+
+export interface RetentionSeriesMeta {
+ /** Original row index from the unfiltered results — drives modal opens in non-interval view. */
+ rowIndex: number
+ breakdown_value?: string | number | null
+ days?: string[]
+ cohortLabel?: string
+ cohortCount: number
+}
+
+export interface BuildRetentionSeriesOpts {
+ /** Negative — index from the end where the in-progress tail begins. Omit to skip. */
+ incompletenessOffsetFromEnd?: number
+ /** True when an interval is selected (x-axis is cohorts, not interval offsets).
+ * In this layout the partial-stroke "in-progress" segment doesn't apply per-series. */
+ isIntervalView: boolean
+}
+
+export function buildRetentionSeries(
+ seriesPayloads: RetentionTrendSeriesEntry[],
+ opts: BuildRetentionSeriesOpts
+): Series<RetentionSeriesMeta>[] {
+ const { incompletenessOffsetFromEnd, isIntervalView } = opts
+ return seriesPayloads.map((s, i) => {
+ const rowIndex = s.index ?? i
+ const dataLength = s.data.length
+ const isInProgress =
+ !isIntervalView && incompletenessOffsetFromEnd !== undefined && incompletenessOffsetFromEnd < 0
+ const dashedFromIndex = isInProgress ? dataLength + (incompletenessOffsetFromEnd as number) : undefined
+
+ const breakdown = s.breakdown_value != null && s.breakdown_value !== '' ? String(s.breakdown_value) : null
+ // `label` is the cohort date in normal view; absent in interval view (use breakdown instead).
+ const label = breakdown ?? s.label ?? `Cohort ${rowIndex}`
+
+ return {
+ key: `retention-${rowIndex}`,
+ label,
+ data: s.data,
+ meta: {
+ rowIndex,
+ breakdown_value: s.breakdown_value,
+ days: s.days,
+ cohortLabel: s.label,
+ cohortCount: s.count,
+ },
+ stroke: dashedFromIndex !== undefined ? { partial: { fromIndex: dashedFromIndex } } : undefined,
+ }
+ })
+}
+
+export interface BuildRetentionChartConfigOpts {
+ isPercentage: boolean
+ goalLines?: SchemaGoalLine[] | null
+ showTrendLines?: boolean
+ series: Series<RetentionSeriesMeta>[]
+ tooltip?: TooltipConfig
+}
+
+function buildTrendLines(
+ series: Series<RetentionSeriesMeta>[],
+ enabled: boolean | undefined
+): TrendLineConfig[] | undefined {
+ if (!enabled || series.length === 0) {
+ return undefined
+ }
+ return series.map((s) => ({ seriesKey: s.key, kind: 'linear' }))
+}
+
+function buildGoalLines(goalLines: SchemaGoalLine[] | null | undefined): GoalLineConfig[] | undefined {
+ return schemaGoalLinesToConfigs(goalLines)
+}
+
+export function buildRetentionLineChartConfig(opts: BuildRetentionChartConfigOpts): TimeSeriesLineChartConfig {
+ return {
+ yAxis: {
+ format: opts.isPercentage ? 'percentage' : 'numeric',
+ scale: 'linear',
+ showGrid: true,
+ },
+ goalLines: buildGoalLines(opts.goalLines),
+ trendLines: buildTrendLines(opts.series, opts.showTrendLines),
+ tooltip: opts.tooltip,
+ }
+}