: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
refactor(insights): make lifecycle chart transforms bundle-neutral (#62408)
Sam Pennington8986708fa94e
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsxindex 3aa8c457d9ee..bf0103a5c6ff 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx@@ -2,9 +2,10 @@ import { useValues } from 'kea'import { useCallback, useMemo } from 'react'import { ChartLegend, TimeSeriesBarChart, legendItemsFromSeries } from '@posthog/quill-charts'-import type { PointClickData, TimeSeriesBarChartConfig, TooltipContext } from '@posthog/quill-charts'+import type { PointClickData, TooltipContext } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'+import { getBarColorFromStatus } from 'lib/colors'import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'import { InsightEmptyState } from 'scenes/insights/EmptyStates'import { insightLogic } from 'scenes/insights/insightLogic'@@ -16,6 +17,7 @@ import type { IndexedTrendResult } from 'scenes/trends/types'import { InsightVizNode } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'+import type { LifecycleToggle } from '~/types'import { AnnotationsLayer } from '../shared/AnnotationsLayer'import { makeChartErrorHandler } from '../shared/chartErrorHandler'@@ -26,7 +28,7 @@ import {} from '../shared/handleTrendsChartClick'import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'import { TrendsTooltip } from '../shared/TrendsTooltip'-import { buildTrendsLifecycleConfig, buildTrendsLifecycleSeries } from './trendsLifecycleChartTransforms'+import { buildLifecycleChartModel } from './trendsLifecycleChartTransforms'interface TrendsLifecycleChartProps {context?: QueryContext<InsightVizNode>@@ -72,26 +74,20 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi!!indexedResults[0].data &&indexedResults.some((r: IndexedTrendResult) => r.count !== 0)- const { series, labels } = useMemo(() => {- const lifecycleSeries = buildTrendsLifecycleSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {- buildMeta: buildTrendsSeriesMeta,- })- return { series: lifecycleSeries, labels: currentPeriodResult?.labels ?? EMPTY_LABELS }- }, [indexedResults, currentPeriodResult?.labels])-- const legendItems = useMemo(() => legendItemsFromSeries(series, theme), [series, theme])-const valueLabelFormatter = useCallback((value: number) => formatAggregationAxisValue(trendsFilter, value, baseCurrency),[trendsFilter, baseCurrency])- const timeSeriesConfig: TimeSeriesBarChartConfig = useMemo(+ const { series, labels, config } = useMemo(() =>- buildTrendsLifecycleConfig({+ buildLifecycleChartModel<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {+ getColor: (status) => getBarColorFromStatus((status ?? 'new') as LifecycleToggle),+ buildMeta: buildTrendsSeriesMeta,+ labels: currentPeriodResult?.labels ?? EMPTY_LABELS,+ isStacked,trendsFilter,baseCurrency,- isStacked,yAxisScaleType,interval,timezone,@@ -100,18 +96,22 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLitooltip: LIFECYCLE_TOOLTIP_CONFIG,}),[+ indexedResults,+ currentPeriodResult?.labels,+ currentPeriodResult?.days,+ isStacked,trendsFilter,baseCurrency,- isStacked,yAxisScaleType,interval,timezone,- currentPeriodResult?.days,showValuesOnSeries,valueLabelFormatter,])+ const legendItems = useMemo(() => legendItemsFromSeries(series, theme), [series, theme])+const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModalconst clickDeps = useMemo<TrendsChartClickDeps>(@@ -199,7 +199,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi<TimeSeriesBarChart<TrendsSeriesMeta>series={series}labels={labels}- config={timeSeriesConfig}+ config={config}theme={theme}tooltip={renderTooltip}onPointClick={canHandleClick ? onPointClick : undefined}diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.tsindex 85b24bc51c1e..ed9841adb09c 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts@@ -1,22 +1,43 @@-// Static color stub so the test doesn't depend on the runtime CSS variable.-jest.mock('lib/colors', () => ({- ...jest.requireActual('lib/colors'),- getBarColorFromStatus: (status: string): string =>- ({- new: '#11ff11',- resurrecting: '#22ff22',- returning: '#33ff33',- dormant: '#44ff44',- })[status] ?? '#000000',-}))+import type { TimeInterval } from '@posthog/quill-charts'+import type { CurrencyCode, TrendsFilter as SchemaTrendsFilter } from '~/queries/schema/schema-general'+import type { IntervalType } from '~/types'++import type { YFormatterFields } from '../shared/trendsChartDisplayOptions'import {+ buildLifecycleChartModel,buildTrendsLifecycleConfig,buildTrendsLifecycleSeries,+ filterToggledLifecycleResults,shortenLifecycleLabel,type TrendsLifecycleResultLike,} from './trendsLifecycleChartTransforms'+// The neutral structural types in trendsLifecycleChartTransforms.ts exist so the shared chart code+// stays free of `~/` and `lib/` imports (the MCP Vite bundle can't resolve them). These helpers'+// return types enforce that the real schema types stay assignable to the neutral ones — if a schema+// field ever changes shape, the returns fail to compile and flag the drift here.+const asNeutralYFormatterFields = (f: NonNullable<SchemaTrendsFilter>): YFormatterFields => f+const asNeutralCurrency = (c: CurrencyCode): string => c+const asNeutralInterval = (i: IntervalType): TimeInterval => i++// Static color stub injected via `getColor` — the transform no longer reads CSS variables itself.+const STATUS_COLORS: Record<string, string> = {+ new: '#11ff11',+ resurrecting: '#22ff22',+ returning: '#33ff33',+ dormant: '#44ff44',+}+const getColor = (status: string | undefined): string => STATUS_COLORS[status ?? ''] ?? '#000000'++describe('schema type firewall', () => {+ it('keeps the schema TrendsFilter / CurrencyCode / IntervalType assignable to the neutral types', () => {+ expect(asNeutralYFormatterFields({ decimalPlaces: 2 })).toMatchObject({ decimalPlaces: 2 })+ expect(asNeutralCurrency('USD' as CurrencyCode)).toBe('USD')+ expect(asNeutralInterval('day')).toBe('day')+ })+})+describe('buildTrendsLifecycleSeries', () => {it('orders series dormant → returning → resurrecting → new regardless of input order', () => {const results: TrendsLifecycleResultLike[] = [@@ -25,15 +46,16 @@ describe('buildTrendsLifecycleSeries', () => {{ id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1, -2, -3] },{ id: 'resurrecting', status: 'resurrecting', label: 'Pageview - resurrecting', data: [1, 2, 3] },]- const series = buildTrendsLifecycleSeries(results)+ const series = buildTrendsLifecycleSeries(results, { getColor })expect(series.map((s) => s.key)).toEqual(['dormant', 'returning', 'resurrecting', 'new'])})it('preserves dormant data as negative — diverging stack relies on the sign', () => {- const series = buildTrendsLifecycleSeries([- { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-5, -6, -7] },- ])+ const series = buildTrendsLifecycleSeries(+ [{ id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-5, -6, -7] }],+ { getColor }+ )expect(series[0].data).toEqual([-5, -6, -7])})@@ -45,15 +67,18 @@ describe('buildTrendsLifecycleSeries', () => {{ id: 'returning', status: 'returning', label: 'Pageview - returning', data: [1, 2, 3] },{ id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1, -2, -3] },]- const series = buildTrendsLifecycleSeries(results)+ const series = buildTrendsLifecycleSeries(results, { getColor })expect(series.map((s) => s.color)).toEqual(['#44ff44', '#33ff33', '#22ff22', '#11ff11'])})it('shortens series labels to capitalized status — used by both legend and tooltip', () => {- const series = buildTrendsLifecycleSeries([- { id: 'new', status: 'new', label: 'Pageview - new', data: [1] },- { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1] },- ])+ const series = buildTrendsLifecycleSeries(+ [+ { id: 'new', status: 'new', label: 'Pageview - new', data: [1] },+ { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1] },+ ],+ { getColor }+ )expect(series.find((s) => s.key === 'new')?.label).toBe('New')expect(series.find((s) => s.key === 'dormant')?.label).toBe('Dormant')})@@ -65,18 +90,17 @@ describe('buildTrendsLifecycleSeries', () => {]const calls: Array<{ status: string; index: number }> = []buildTrendsLifecycleSeries(results, {+ getColor,buildMeta: (r, i) => {calls.push({ status: r.status!, index: i })return r.status},})// dormant was at original index 0, new at original index 1 — order is preserved in the callback.- expect(calls).toEqual(- expect.arrayContaining([- { status: 'dormant', index: 0 },- { status: 'new', index: 1 },- ])- )+ expect(calls).toEqual([+ { status: 'dormant', index: 0 },+ { status: 'new', index: 1 },+ ])})it('marks excluded series with visibility.excluded so the chart skips them', () => {@@ -85,6 +109,7 @@ describe('buildTrendsLifecycleSeries', () => {{ id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1] },]const series = buildTrendsLifecycleSeries(results, {+ getColor,getHidden: (r) => r.status === 'dormant',})const dormant = series.find((s) => s.key === 'dormant')@@ -94,11 +119,74 @@ describe('buildTrendsLifecycleSeries', () => {})it('falls back to "None" label when the result label is null', () => {- const series = buildTrendsLifecycleSeries([{ id: 'new', status: 'new', label: null, data: [1] }])+ const series = buildTrendsLifecycleSeries([{ id: 'new', status: 'new', label: null, data: [1] }], { getColor })expect(series[0].label).toBe('None')})})+describe('filterToggledLifecycleResults', () => {+ const rows = [+ { status: 'new', data: [1] },+ { status: 'returning', data: [2] },+ { status: 'dormant', data: [-3] },+ ]++ it('returns every row unchanged when no toggle is set', () => {+ expect(filterToggledLifecycleResults(rows, undefined)).toBe(rows)+ })++ it('keeps only rows whose status is toggled on', () => {+ expect(filterToggledLifecycleResults(rows, ['new', 'dormant'])).toEqual([+ { status: 'new', data: [1] },+ { status: 'dormant', data: [-3] },+ ])+ })++ it('drops rows without a status once a toggle is active', () => {+ const withUnstatused = [...rows, { status: undefined, data: [9] }]+ expect(filterToggledLifecycleResults(withUnstatused, ['new'])).toEqual([{ status: 'new', data: [1] }])+ })+})++describe('buildLifecycleChartModel', () => {+ const results: TrendsLifecycleResultLike[] = [+ { id: 'new', status: 'new', label: 'Pageview - new', data: [1, 2] },+ { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1, -2] },+ ]++ it('assembles series + config and passes the host labels through', () => {+ const model = buildLifecycleChartModel(results, {+ getColor,+ labels: ['Jun 1', 'Jun 2'],+ isStacked: true,+ })++ expect(model.labels).toEqual(['Jun 1', 'Jun 2'])+ expect(model.series.map((s) => s.key)).toEqual(['dormant', 'new'])+ expect(model.config.barLayout).toBe('stacked')+ expect(model.config.divergingStack).toBe(true)+ })++ it('applies the toggledLifecycles filter before building series', () => {+ const model = buildLifecycleChartModel(results, {+ getColor,+ labels: ['Jun 1', 'Jun 2'],+ isStacked: false,+ toggledLifecycles: ['new'],+ })++ expect(model.series.map((s) => s.key)).toEqual(['new'])+ expect(model.config.barLayout).toBe('grouped')+ })++ it('forwards the tooltip config through to the chart config', () => {+ const tooltip = { pinnable: true, placement: 'top' as const }+ const model = buildLifecycleChartModel(results, { getColor, labels: [], isStacked: true, tooltip })++ expect(model.config.tooltip).toBe(tooltip)+ })+})+describe('buildTrendsLifecycleConfig', () => {it.each([{ isStacked: true, expectedLayout: 'stacked', expectedDiverging: true },diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.tsindex c28f125c23b8..fa5ef66bccea 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts@@ -1,15 +1,16 @@-import type { Series, TimeSeriesBarChartConfig } from '@posthog/quill-charts'--import { getBarColorFromStatus } from 'lib/colors'-import { capitalizeFirstLetter } from 'lib/utils'--import type { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'-import type { IntervalType, LifecycleToggle } from '~/types'+import type { Series, TimeInterval, TimeSeriesBarChartConfig } from '@posthog/quill-charts'import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'-import { LIFECYCLE_STATUS_ORDER } from '../shared/trendsSeriesMeta'+import type { YFormatterFields } from '../shared/trendsChartDisplayOptions'-// Shape both IndexedTrendResult (kea) and lighter fixtures satisfy.+// Canonical lifecycle status enumeration: new → resurrecting → returning → dormant. Declared here+// (rather than imported from trendsSeriesMeta, which pulls in `~/` types) so this module stays free+// of `~/`/`lib/` deps and compiles in the MCP Vite bundle, which only resolves `products/*` and+// `@posthog/*`. The lifecycle chart renders series in the reverse order (dormant first) to match the+// legacy chart (`trendsDataLogic.ts:197`).+const LIFECYCLE_STATUS_ORDER: readonly string[] = ['new', 'resurrecting', 'returning', 'dormant']++// Shape both IndexedTrendResult (kea) and lighter fixtures (e.g. the MCP UI app) satisfy.export interface TrendsLifecycleResultLike {id?: string | numberlabel?: string | null@@ -20,27 +21,36 @@ export interface TrendsLifecycleResultLike {}function lifecycleStatusOrder(status: string | undefined): number {- const i = LIFECYCLE_STATUS_ORDER.indexOf(status as LifecycleToggle)+ const i = LIFECYCLE_STATUS_ORDER.indexOf(status ?? '')return i === -1 ? LIFECYCLE_STATUS_ORDER.length : i}-// `dormant` is the only lifecycle status whose values are emitted as negatives,-// so a diverging stack lays it below the zero baseline. The non-dormant series-// are pinned to their fixed lifecycle colors regardless of the data-color theme.-// Unknown statuses fall through to `getBarColorFromStatus`, which throws — we-// surface the bad data rather than silently miscoloring it as the "new" series.-function lifecycleColor(status: string | undefined): string {- return getBarColorFromStatus((status ?? 'new') as LifecycleToggle)+/** Drops rows whose lifecycle status is toggled off — mirrors the main app's legend toggles, which+ * the MCP host honors from the query (the web chart toggles interactively instead). With no toggle+ * set every row passes; once a toggle is active, a row without a status is dropped. */+export function filterToggledLifecycleResults<R extends { status?: string }>(+ results: R[],+ toggledLifecycles: readonly string[] | undefined+): R[] {+ if (!toggledLifecycles) {+ return results+ }+ return results.filter((r) => !!r.status && toggledLifecycles.includes(r.status))}export interface BuildTrendsLifecycleSeriesOpts<R extends TrendsLifecycleResultLike, M = unknown> {+ // Injected so the transform stays free of `lib/colors` (the MCP bundle can't resolve it). Web+ // passes `getBarColorFromStatus`, which throws on unknown statuses — surfacing bad data rather+ // than silently miscoloring it. `dormant` is the only status emitted as negatives, so a diverging+ // stack lays it below the zero baseline regardless of color.+ getColor: (status: string | undefined) => stringgetHidden?: (r: R, index: number) => booleanbuildMeta?: (r: R, index: number) => M}export function buildTrendsLifecycleSeries<R extends TrendsLifecycleResultLike, M = unknown>(results: R[],- opts: BuildTrendsLifecycleSeriesOpts<R, M> = {}+ opts: BuildTrendsLifecycleSeriesOpts<R, M>): Series<M>[] {// Stable lifecycle order: dormant → returning → resurrecting → new — matches the// legacy lifecycle chart (`trendsDataLogic.ts:197`) so the legend reads top-down the@@ -60,7 +70,7 @@ export function buildTrendsLifecycleSeries<R extends TrendsLifecycleResultLike,// shortened here so both legend and tooltip pick up the clean form.label: shortenLifecycleLabel(r.label),data: r.data,- color: lifecycleColor(r.status),+ color: opts.getColor(r.status),meta,visibility: excluded ? { excluded: true } : undefined,}@@ -68,11 +78,11 @@ export function buildTrendsLifecycleSeries<R extends TrendsLifecycleResultLike,}export interface BuildTrendsLifecycleConfigOpts {- trendsFilter?: TrendsFilter | null- baseCurrency?: CurrencyCode+ trendsFilter?: YFormatterFields | null+ baseCurrency?: stringisStacked: booleanyAxisScaleType?: string | null- interval?: IntervalType | null+ interval?: TimeInterval | nulltimezone?: stringallDays?: string[]valueLabels?: TimeSeriesBarChartConfig['valueLabels']@@ -99,10 +109,48 @@ export function buildTrendsLifecycleConfig(opts: BuildTrendsLifecycleConfigOpts)}}+export interface BuildLifecycleChartModelOpts<+ R extends TrendsLifecycleResultLike,+ M = unknown,+> extends BuildTrendsLifecycleConfigOpts {+ /** Final x-axis labels (already formatted by the host — kea dates vs the MCP `formatDate`). */+ labels: string[]+ getColor: (status: string | undefined) => string+ /** Client-side legend toggle state. Omit on hosts that toggle interactively (the web chart). */+ toggledLifecycles?: readonly string[]+ getHidden?: (r: R, index: number) => boolean+ buildMeta?: (r: R, index: number) => M+}++/** The complete input a host hands to quill's `TimeSeriesBarChart` for a lifecycle chart. */+export interface LifecycleChartModel<M = unknown> {+ series: Series<M>[]+ labels: string[]+ config: TimeSeriesBarChartConfig+}++/** Assembles the full lifecycle chart model (filter → series → config) so both the web container and+ * the MCP visualizer share one tested path; each injects only host-specific bits (color, labels,+ * tooltip, meta, interactivity flags). */+export function buildLifecycleChartModel<R extends TrendsLifecycleResultLike, M = unknown>(+ results: R[],+ opts: BuildLifecycleChartModelOpts<R, M>+): LifecycleChartModel<M> {+ const visible = filterToggledLifecycleResults(results, opts.toggledLifecycles)+ const series = buildTrendsLifecycleSeries<R, M>(visible, {+ getColor: opts.getColor,+ getHidden: opts.getHidden,+ buildMeta: opts.buildMeta,+ })+ const config = buildTrendsLifecycleConfig(opts)+ return { series, labels: opts.labels, config }+}+/** Lifecycle series labels arrive as "Pageview - new", "Pageview - returning", etc.* Returns just the capitalized status ("New", "Returning"). */export function shortenLifecycleLabel(label: string | null | undefined): string {const parts = label?.split(' - ')const tail = parts?.[parts.length - 1] ?? label ?? 'None'- return capitalizeFirstLetter(tail)+ // Inlined rather than imported from `lib/utils` so this module stays MCP-bundle-safe.+ return tail.charAt(0).toUpperCase() + tail.slice(1)}diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.tsindex b45abdd1e6fd..5748dfd49913 100644--- a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts+++ b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts@@ -2,7 +2,7 @@ import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUimport type { IndexedTrendResult } from 'scenes/trends/types'import type { Noun } from '~/models/groupsModel'-import type { ActionFilter, LifecycleToggle } from '~/types'+import type { ActionFilter } from '~/types'export type TrendsSeriesMeta = {action?: ActionFilter@@ -13,11 +13,6 @@ export type TrendsSeriesMeta = {filter?: SeriesDatum['filter']}-/** Canonical lifecycle status enumeration: new → resurrecting → returning → dormant.- * The lifecycle chart renders series in the reverse order (dormant first) to match the- * legacy chart (`trendsDataLogic.ts:197`); see `trendsLifecycleChartTransforms.ts`. */-export const LIFECYCLE_STATUS_ORDER: readonly LifecycleToggle[] = ['new', 'resurrecting', 'returning', 'dormant']-export const buildTrendsSeriesMeta = (r: IndexedTrendResult): TrendsSeriesMeta => ({action: r.action,breakdown_value: r.breakdown_value,