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 bar graph to hog-charts (#59678)

Sam Penningtond986707bdaec
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d5c97bccccaf..0d8af292509f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4583,13 +4583,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.da7408ac759f81d6f806ad8994073060aeb28223f270e4a56fa0967acf741486.0hk563fxOgKIbDMQGLOr5V6tz4DB_FAWR96ASmtYcqE
+ hash: v1.k794b7964.945ed16d72ed2ec67559ed2a478237267bf3fae0ec5437202145e4bbddaa99c2.Pl63KVs13EuxFB41jKCVv-dOTSP27veYuLRl7pFf7UQ
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.1a564a7e326dd6ce74422aeec8cc336763529a54aac381e2c3039c950f73e0b9.wumhgGqgZsmHlAU_iVgKRQ3b3hEQXtCDIIvV5YMwt3g
+ hash: v1.k794b7964.85c3472bdf5bbb2cc4192dcbb94e08f9e0a0bab75c0cb9ab33f73159f57145dc.cQyIslgEmojkd0sw2qGxsPbg8HA8mquQaXYqPJCh6Ds
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:
@@ -4666,6 +4666,10 @@ snapshots:
hash: v1.k794b7964.02ffa288b3f9fc2dde2fa1732bd164ccf771ef3a35ca9177d592571bc045e62e.PJ1SdvfwVPJtkFHwRSBMnqje3CP0ne57BD3kgWh-YvQ
scenes-app-insights-retention--retention--light:
hash: v1.k794b7964.a47c3c899143d4e9846757e32e67bb0945a2781233c79e44d0356ea43a59d2cd.70yC-geHj-Zl5tKxqL4DcS4R6lxJRlvlK1ftwBcxSZg
+ scenes-app-insights-retention--retention-bar--dark:
+ hash: v1.k794b7964.f15eb090aaf7506732f662ac5393bf40f606560750b9e458cac5844936bcf30b.Nmwikb-TXVhUdC2ZdeRPjiG8JV_8_vaUYbTrwrUxtbQ
+ scenes-app-insights-retention--retention-bar--light:
+ hash: v1.k794b7964.ae10238ad7f8c6e506f56fac7a184b390aa3b502f01539b9c12b37ff6686a97a.iYj-zHd0v8dv2JTna2_MuGlQTgHU2NdVIYrzxs3BGkU
scenes-app-insights-retention--retention-edit--dark:
hash: v1.k794b7964.f462cd65020702c381cbd29c4c7bf74283348383048ac6f1f26d31b565f4380f.jqXlFe9kyIfOs-PWEbkaAhi1sD8lQFfn_UBW9MjOuIM
scenes-app-insights-retention--retention-edit--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index be648967beb0..d68cd973f924 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_BAR: 'product-analytics-hog-charts-retention-bar', // 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
diff --git a/frontend/src/scenes/insights/Retention.stories.tsx b/frontend/src/scenes/insights/Retention.stories.tsx
index 2a121447e742..527758cb5e3c 100644
--- a/frontend/src/scenes/insights/Retention.stories.tsx
+++ b/frontend/src/scenes/insights/Retention.stories.tsx
@@ -2,9 +2,13 @@ import { samplePersonProperties, sampleRetentionPeopleResponse } from 'scenes/in
import { Meta, StoryObj } from '@storybook/react'
+import { FEATURE_FLAGS } from 'lib/constants'
import { createInsightStory } from 'scenes/insights/__mocks__/createInsightScene'
import { mswDecorator } from '~/mocks/browser'
+import type { InsightVizNode, RetentionQuery } from '~/queries/schema/schema-general'
+import type { QueryBasedInsightModel } from '~/types'
+import { ChartDisplayType } from '~/types'
type Story = StoryObj<{}>
const meta: Meta = {
@@ -65,4 +69,45 @@ RetentionEditViewports.parameters = {
},
}
+const retentionInsight =
+ require('../../mocks/fixtures/api/projects/team_id/insights/retention.json') as QueryBasedInsightModel
+const retentionBaseQuery = retentionInsight.query as InsightVizNode
+const retentionBaseSource = retentionBaseQuery.source as RetentionQuery
+const retentionBarQuery: InsightVizNode = {
+ ...retentionBaseQuery,
+ source: {
+ ...retentionBaseSource,
+ retentionFilter: { ...retentionBaseSource.retentionFilter, display: ChartDisplayType.ActionsBar },
+ },
+}
+
+// Realistic retention curve: 100% baseline, ~55% day 1, decaying to ~13% by day 7. Slight
+// per-cohort jitter so adjacent bars don't all look identical.
+const retentionCurve = [1.0, 0.58, 0.42, 0.32, 0.26, 0.22, 0.18, 0.15]
+const cohortSeeds = [1024, 1150, 980, 870, 1320, 1080, 940, 760, 1210, 1340, 1450]
+const retentionBarResult = cohortSeeds.map((seed, cohortIndex) => {
+ const periodCount = Math.max(1, cohortSeeds.length - cohortIndex)
+ const jitter = 1 + ((cohortIndex % 3) - 1) * 0.04
+ return {
+ label: `Day ${cohortIndex}`,
+ date: `2022-03-${String(cohortIndex + 1).padStart(2, '0')}T00:00:00Z`,
+ values: retentionCurve.slice(0, Math.min(periodCount, retentionCurve.length)).map((r, i) => ({
+ count: i === 0 ? seed : Math.round(seed * r * jitter),
+ people: [],
+ })),
+ people_url: '',
+ }
+})
+const retentionBarInsight: QueryBasedInsightModel = {
+ ...retentionInsight,
+ query: retentionBarQuery,
+ result: retentionBarResult,
+}
+
+export const RetentionBar: Story = createInsightStory(retentionBarInsight)
+RetentionBar.parameters = {
+ featureFlags: [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_RETENTION_BAR],
+ testOptions: { waitForSelector: '[data-attr=trend-line-graph] > canvas' },
+}
+
/* eslint-enable @typescript-eslint/no-var-requires */
diff --git a/frontend/src/scenes/retention/RetentionGraph.tsx b/frontend/src/scenes/retention/RetentionGraph.tsx
index 371f8f758d10..f73beab71a5a 100644
--- a/frontend/src/scenes/retention/RetentionGraph.tsx
+++ b/frontend/src/scenes/retention/RetentionGraph.tsx
@@ -10,9 +10,10 @@ 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'
+import { RetentionBarChart } from './viz/retention-bar-chart/RetentionBarChart'
+import { RetentionLineChart } from './viz/retention-line-chart/RetentionLineChart'
interface RetentionGraphProps {
inSharedMode?: boolean
@@ -48,9 +49,11 @@ 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_BAR]) {
+ return <RetentionBarChart inSharedMode={inSharedMode} />
+ }
if (!isBarDisplay && featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_RETENTION_LINE]) {
- return <RetentionGraphHogCharts inSharedMode={inSharedMode} />
+ return <RetentionLineChart inSharedMode={inSharedMode} />
}
if (filteredTrendSeries.length === 0 && hasValidBreakdown) {
diff --git a/frontend/src/scenes/retention/viz/retention-bar-chart/RetentionBarChart.tsx b/frontend/src/scenes/retention/viz/retention-bar-chart/RetentionBarChart.tsx
new file mode 100644
index 000000000000..74b66331dea1
--- /dev/null
+++ b/frontend/src/scenes/retention/viz/retention-bar-chart/RetentionBarChart.tsx
@@ -0,0 +1,171 @@
+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 { TimeSeriesBarChart } 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 { retentionGraphLogic } from '../../retentionGraphLogic'
+import { retentionModalLogic } from '../../retentionModalLogic'
+import {
+ buildRetentionBarChartConfig,
+ buildRetentionSeries,
+ type RetentionSeriesMeta,
+ type RetentionTrendSeriesEntry,
+} from '../shared/retentionChartTransforms'
+import { RetentionTooltip } from '../shared/RetentionTooltip'
+
+interface RetentionBarChartProps {
+ 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 RetentionBarChart({ inSharedMode = false }: RetentionBarChartProps): JSX.Element | null {
+ const { insightProps } = useValues(insightLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+
+ const {
+ hasValidBreakdown,
+ retentionFilter,
+ filteredTrendSeries,
+ incompletenessOffsetFromEnd,
+ labelGroupType,
+ shouldShowMeanPerBreakdown,
+ 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
+ }
+ 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 barConfig = useMemo(
+ () => buildRetentionBarChartConfig({ isPercentage, goalLines, series, tooltip: TOOLTIP_CONFIG }),
+ [isPercentage, goalLines, 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 (
+ <TimeSeriesBarChart<RetentionSeriesMeta>
+ series={series}
+ labels={xAxisLabels}
+ theme={theme}
+ config={barConfig}
+ tooltip={renderTooltip}
+ onPointClick={canClick ? onPointClick : undefined}
+ className="LineGraph"
+ dataAttr="trend-line-graph"
+ onError={handleChartError}
+ />
+ )
+}
diff --git a/frontend/src/scenes/retention/RetentionGraphHogCharts.tsx b/frontend/src/scenes/retention/viz/retention-line-chart/RetentionLineChart.tsx
similarity index 93%
rename from frontend/src/scenes/retention/RetentionGraphHogCharts.tsx
rename to frontend/src/scenes/retention/viz/retention-line-chart/RetentionLineChart.tsx
index e0fa16b56d0f..c12fd036b8e2 100644
--- a/frontend/src/scenes/retention/RetentionGraphHogCharts.tsx
+++ b/frontend/src/scenes/retention/viz/retention-line-chart/RetentionLineChart.tsx
@@ -13,17 +13,17 @@ import { groupsModel } from '~/models/groupsModel'
import type { GoalLine } from '~/queries/schema/schema-general'
import type { GroupTypeIndex, LabelGroupType } from '~/types'
+import { retentionGraphLogic } from '../../retentionGraphLogic'
+import { retentionModalLogic } from '../../retentionModalLogic'
import {
buildRetentionLineChartConfig,
buildRetentionSeries,
type RetentionSeriesMeta,
type RetentionTrendSeriesEntry,
-} from './retentionChartTransforms'
-import { retentionGraphLogic } from './retentionGraphLogic'
-import { retentionModalLogic } from './retentionModalLogic'
-import { RetentionTooltip } from './RetentionTooltip'
+} from '../shared/retentionChartTransforms'
+import { RetentionTooltip } from '../shared/RetentionTooltip'
-interface RetentionGraphHogChartsProps {
+interface RetentionLineChartProps {
inSharedMode?: boolean
}
@@ -50,7 +50,7 @@ function resolveGroupTypeLabel(
return aggregationLabel(labelGroupType).plural
}
-export function RetentionGraphHogCharts({ inSharedMode = false }: RetentionGraphHogChartsProps): JSX.Element | null {
+export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartProps): JSX.Element | null {
const { insightProps } = useValues(insightLogic)
const { isDarkModeOn } = useValues(themeLogic)
const theme = useMemo(() => buildTheme(), [isDarkModeOn])
diff --git a/frontend/src/scenes/retention/RetentionTooltip.tsx b/frontend/src/scenes/retention/viz/shared/RetentionTooltip.tsx
similarity index 100%
rename from frontend/src/scenes/retention/RetentionTooltip.tsx
rename to frontend/src/scenes/retention/viz/shared/RetentionTooltip.tsx
diff --git a/frontend/src/scenes/retention/viz/shared/retentionChartTransforms.test.ts b/frontend/src/scenes/retention/viz/shared/retentionChartTransforms.test.ts
new file mode 100644
index 000000000000..27e5e62fff05
--- /dev/null
+++ b/frontend/src/scenes/retention/viz/shared/retentionChartTransforms.test.ts
@@ -0,0 +1,202 @@
+import type { Series, TooltipConfig } from 'lib/hog-charts'
+
+import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'
+
+import {
+ buildRetentionBarChartConfig,
+ buildRetentionLineChartConfig,
+ buildRetentionSeries,
+ type RetentionSeriesMeta,
+ type RetentionTrendSeriesEntry,
+} from './retentionChartTransforms'
+
+const makeEntry = (overrides: Partial<RetentionTrendSeriesEntry> = {}): RetentionTrendSeriesEntry => ({
+ count: 100,
+ data: [100, 80, 60, 40, 20],
+ days: ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'],
+ labels: ['Day 0', 'Day 1', 'Day 2', 'Day 3', 'Day 4'],
+ index: 0,
+ label: '2024-01-01',
+ ...overrides,
+})
+
+const TOOLTIP: TooltipConfig = { pinnable: true, placement: 'top' }
+
+describe('retentionChartTransforms', () => {
+ describe('buildRetentionSeries', () => {
+ it('builds one series per payload, keyed by row index', () => {
+ const series = buildRetentionSeries([makeEntry({ index: 0 }), makeEntry({ index: 1 })], {
+ isIntervalView: false,
+ })
+
+ expect(series).toHaveLength(2)
+ expect(series.map((s) => s.key)).toEqual(['retention-0', 'retention-1'])
+ expect(series[0].data).toEqual([100, 80, 60, 40, 20])
+ })
+
+ it('uses the payload index as the row index, not the array position', () => {
+ const series = buildRetentionSeries([makeEntry({ index: 7 })], { isIntervalView: false })
+
+ expect(series[0].key).toBe('retention-7')
+ expect(series[0].meta?.rowIndex).toBe(7)
+ })
+
+ it('falls back to the array position when the payload has no index', () => {
+ const series = buildRetentionSeries([makeEntry({ index: undefined })], { isIntervalView: false })
+
+ expect(series[0].key).toBe('retention-0')
+ expect(series[0].meta?.rowIndex).toBe(0)
+ })
+
+ it.each<[string, Partial<RetentionTrendSeriesEntry>, string]>([
+ [
+ 'breakdown value wins over the cohort label',
+ { breakdown_value: 'Chrome', label: '2024-01-01' },
+ 'Chrome',
+ ],
+ [
+ 'cohort label is used when there is no breakdown',
+ { breakdown_value: null, label: '2024-01-01' },
+ '2024-01-01',
+ ],
+ [
+ 'empty-string breakdown falls through to the cohort label',
+ { breakdown_value: '', label: '2024-01-01' },
+ '2024-01-01',
+ ],
+ ])('label: %s', (_name, overrides, expected) => {
+ const series = buildRetentionSeries([makeEntry(overrides)], { isIntervalView: false })
+ expect(series[0].label).toBe(expected)
+ })
+
+ it('falls back to a "Cohort {index}" label when there is no breakdown or cohort label', () => {
+ const series = buildRetentionSeries([makeEntry({ index: 3, breakdown_value: null, label: undefined })], {
+ isIntervalView: false,
+ })
+ expect(series[0].label).toBe('Cohort 3')
+ })
+
+ it('dashes the in-progress tail at dataLength + offset for the normal view', () => {
+ const series = buildRetentionSeries([makeEntry({ data: [1, 2, 3, 4, 5] })], {
+ isIntervalView: false,
+ incompletenessOffsetFromEnd: -2,
+ })
+ expect(series[0].stroke).toEqual({ partial: { fromIndex: 3 } })
+ })
+
+ it('skips the in-progress tail in interval view (each x-position is a different cohort)', () => {
+ const series = buildRetentionSeries([makeEntry({ data: [1, 2, 3, 4, 5] })], {
+ isIntervalView: true,
+ incompletenessOffsetFromEnd: -2,
+ })
+ expect(series[0].stroke).toBeUndefined()
+ })
+
+ it.each<[string, number | undefined]>([
+ ['no offset', undefined],
+ ['a zero offset', 0],
+ ['a positive offset', 1],
+ ])('skips the in-progress tail for %s', (_name, incompletenessOffsetFromEnd) => {
+ const series = buildRetentionSeries([makeEntry()], { isIntervalView: false, incompletenessOffsetFromEnd })
+ expect(series[0].stroke).toBeUndefined()
+ })
+
+ it('carries cohort metadata through to series meta', () => {
+ const series = buildRetentionSeries(
+ [makeEntry({ index: 2, breakdown_value: 'Chrome', count: 42, label: '2024-01-03' })],
+ { isIntervalView: false }
+ )
+ expect(series[0].meta).toEqual({
+ rowIndex: 2,
+ breakdown_value: 'Chrome',
+ days: ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'],
+ cohortLabel: '2024-01-03',
+ cohortCount: 42,
+ })
+ })
+ })
+
+ describe('buildRetentionLineChartConfig', () => {
+ const baseSeries: Series<RetentionSeriesMeta>[] = buildRetentionSeries(
+ [makeEntry({ index: 0 }), makeEntry({ index: 1 })],
+ { isIntervalView: false }
+ )
+
+ it.each<[boolean, 'percentage' | 'numeric']>([
+ [true, 'percentage'],
+ [false, 'numeric'],
+ ])('formats the y-axis based on isPercentage=%s -> %s', (isPercentage, format) => {
+ const config = buildRetentionLineChartConfig({ isPercentage, series: baseSeries })
+ expect(config.yAxis).toEqual({ format, scale: 'linear', showGrid: true })
+ })
+
+ it('emits one linear trend line per series when showTrendLines is true', () => {
+ const config = buildRetentionLineChartConfig({
+ isPercentage: true,
+ series: baseSeries,
+ showTrendLines: true,
+ })
+ expect(config.trendLines).toEqual([
+ { seriesKey: 'retention-0', kind: 'linear' },
+ { seriesKey: 'retention-1', kind: 'linear' },
+ ])
+ })
+
+ it('omits trend lines when showTrendLines is false', () => {
+ const config = buildRetentionLineChartConfig({ isPercentage: true, series: baseSeries })
+ expect(config.trendLines).toBeUndefined()
+ })
+
+ it('omits trend lines when there are no series even if showTrendLines is true', () => {
+ const config = buildRetentionLineChartConfig({ isPercentage: true, series: [], showTrendLines: true })
+ expect(config.trendLines).toBeUndefined()
+ })
+
+ it('maps schema goal lines onto the config', () => {
+ const goalLines: SchemaGoalLine[] = [{ label: 'Target', value: 50 }]
+ const config = buildRetentionLineChartConfig({ isPercentage: true, series: baseSeries, goalLines })
+ expect(config.goalLines).toEqual([expect.objectContaining({ label: 'Target', value: 50 })])
+ })
+
+ it.each<[string, SchemaGoalLine[] | null]>([
+ ['null', null],
+ ['an empty array', []],
+ ])('leaves goal lines undefined when goalLines is %s', (_name, goalLines) => {
+ const config = buildRetentionLineChartConfig({ isPercentage: true, series: baseSeries, goalLines })
+ expect(config.goalLines).toBeUndefined()
+ })
+
+ it('passes the tooltip config through unchanged', () => {
+ const config = buildRetentionLineChartConfig({ isPercentage: true, series: baseSeries, tooltip: TOOLTIP })
+ expect(config.tooltip).toBe(TOOLTIP)
+ })
+ })
+
+ describe('buildRetentionBarChartConfig', () => {
+ const baseSeries: Series<RetentionSeriesMeta>[] = buildRetentionSeries([makeEntry()], { isIntervalView: false })
+
+ it('lays bars out grouped so per-cohort bars stay side-by-side', () => {
+ const config = buildRetentionBarChartConfig({ isPercentage: true, series: baseSeries })
+ expect(config.barLayout).toBe('grouped')
+ })
+
+ it.each<[boolean, 'percentage' | 'numeric']>([
+ [true, 'percentage'],
+ [false, 'numeric'],
+ ])('formats the y-axis based on isPercentage=%s -> %s', (isPercentage, format) => {
+ const config = buildRetentionBarChartConfig({ isPercentage, series: baseSeries })
+ expect(config.yAxis).toEqual({ format, scale: 'linear', showGrid: true })
+ })
+
+ it('maps schema goal lines onto the config', () => {
+ const goalLines: SchemaGoalLine[] = [{ label: 'Target', value: 50 }]
+ const config = buildRetentionBarChartConfig({ isPercentage: true, series: baseSeries, goalLines })
+ expect(config.goalLines).toEqual([expect.objectContaining({ label: 'Target', value: 50 })])
+ })
+
+ it('passes the tooltip config through unchanged', () => {
+ const config = buildRetentionBarChartConfig({ isPercentage: true, series: baseSeries, tooltip: TOOLTIP })
+ expect(config.tooltip).toBe(TOOLTIP)
+ })
+ })
+})
diff --git a/frontend/src/scenes/retention/retentionChartTransforms.ts b/frontend/src/scenes/retention/viz/shared/retentionChartTransforms.ts
similarity index 83%
rename from frontend/src/scenes/retention/retentionChartTransforms.ts
rename to frontend/src/scenes/retention/viz/shared/retentionChartTransforms.ts
index 8fa73bb5684a..ee7c5e393d08 100644
--- a/frontend/src/scenes/retention/retentionChartTransforms.ts
+++ b/frontend/src/scenes/retention/viz/shared/retentionChartTransforms.ts
@@ -1,10 +1,17 @@
-import type { GoalLineConfig, Series, TimeSeriesLineChartConfig, TooltipConfig, TrendLineConfig } from 'lib/hog-charts'
+import type {
+ GoalLineConfig,
+ Series,
+ TimeSeriesBarChartConfig,
+ TimeSeriesLineChartConfig,
+ TooltipConfig,
+ TrendLineConfig,
+} from 'lib/hog-charts'
import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'
import { schemaGoalLinesToConfigs } from 'products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter'
-import type { RetentionTrendPayload } from './types'
+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.
@@ -93,3 +100,17 @@ export function buildRetentionLineChartConfig(opts: BuildRetentionChartConfigOpt
tooltip: opts.tooltip,
}
}
+
+export function buildRetentionBarChartConfig(opts: BuildRetentionChartConfigOpts): TimeSeriesBarChartConfig {
+ return {
+ yAxis: {
+ format: opts.isPercentage ? 'percentage' : 'numeric',
+ scale: 'linear',
+ showGrid: true,
+ },
+ // Bars side-by-side so the retention trend per cohort stays distinguishable.
+ barLayout: 'grouped',
+ goalLines: buildGoalLines(opts.goalLines),
+ tooltip: opts.tooltip,
+ }
+}