: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
feat(insights): port lifecycle chart to hog-charts behind a flag (#59811)
Sam Pennington1e1ac6c6bde4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 26eeb3039626..224f7b140ba6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1936,6 +1936,14 @@ snapshots:hash: v1.k794b7964.68689d02aa245c2ccd04888b1c2bc578136eda4117f2fff911bde3f5c276b9da.svBnhEDDJ61_Vp6T3AUEjT3wlS2aamf9o-YNooKTRlwinsights-trendsbarchart--compare--light:hash: v1.k794b7964.08db5d36c08b26300a7cd09fddd8f02e9ba973ffcf42e556e7f8ae01a27e907b.jN5qaeiDphtPJ90-0-bNC0jmD0MVkSCj6zjO8XzvZkI+ insights-trendslifecyclechart--stacked--dark:+ hash: v1.k794b7964.f01dae4d665fea93c451e5bb48d6409d586c89856ffb1fff155937c7eb9119d9.coUQ2-TFqEqeP38cPDoiz5RbwkfznST9H3pR5TRbpvg+ insights-trendslifecyclechart--stacked--light:+ hash: v1.k794b7964.06299a8e05030704231ec0ab4031ff3193330c613a3b7f9688db9ce7e932fe49.-8nYhPa8-aLNwcTVGon6dY_Rn4KRC-l_frb-ikmvk1I+ insights-trendslifecyclechart--unstacked--dark:+ hash: v1.k794b7964.2a10bee9748692b8389454027a29ca4aae1fd5ec54df435f337658ccb14e88ac.byw6nfFw97UeuEpXKPkAlWMXDYhMvcqzPgZFGxST0hk+ insights-trendslifecyclechart--unstacked--light:+ hash: v1.k794b7964.3467d1d62a847176237a5278030dcd296df1283111f6260f86f2d467e2cc457b.xxTvFm43ZodSjCbtbMNLpjn20JZLLK6h4-MElnqQa5Iinsights-trendslinechart--breakdown--dark:hash: v1.k794b7964.4228a311a626ebf45a34acead267954b6b05686aa012ed54242b7a0c5ba298f1.MC_47zRRkXLTsrbhhq1hf2BuXmW8uRCu4fohSF303Isinsights-trendslinechart--breakdown--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex a6081675b70b..8b671a8c1373 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -419,6 +419,7 @@ export const FEATURE_FLAGS = {PRODUCT_ANALYTICS_HIDE_WEEKENDS: 'product-analytics-hide-weekends', // owner: @kliment-slice #team-irl-eventsPRODUCT_ANALYTICS_HOG_CHARTS_TRENDS: 'product-analytics-hog-charts-trends', // owner: @sampennington #team-product-analyticsPRODUCT_ANALYTICS_HOG_CHARTS_FUNNEL: 'product-analytics-hog-charts-funnel', // owner: @sampennington #team-product-analytics+ PRODUCT_ANALYTICS_HOG_CHARTS_LIFECYCLE: 'product-analytics-hog-charts-lifecycle', // owner: @sampennington #team-product-analyticsPRODUCT_ANALYTICS_HOG_CHARTS_RETENTION: 'product-analytics-hog-charts-retention', // owner: @sampennington #team-product-analyticsPRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analyticsPRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analyticsdiff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsxindex c9248a6e9483..31d67520ab08 100644--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx@@ -16,6 +16,7 @@ import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'import {buildSegmentResolveValue,buildStackedPositionValue,+ computeDivergingStackData,computePercentStackData,computeStackData,createBarScales,@@ -97,6 +98,7 @@ function BarChartInner<Meta = unknown>({barTrack = false,axisOrientation = 'vertical',xTickFormatter,+ divergingStack = false,} = config ?? {}const isHorizontal = axisOrientation === 'horizontal'@@ -105,10 +107,10 @@ function BarChartInner<Meta = unknown>({return computePercentStackData(series, labels)}if (barLayout === 'stacked') {- return computeStackData(series, labels)+ return divergingStack ? computeDivergingStackData(series, labels) : computeStackData(series, labels)}return undefined- }, [barLayout, series, labels])+ }, [barLayout, series, labels, divergingStack])// Cap rounding is per-axis: buildStackData stacks each yAxisId independently, so each// axis has its own topmost visible series. Iteration order matches d3.stack's key order,@@ -143,11 +145,23 @@ function BarChartInner<Meta = unknown>({(coloredSeries: ResolvedSeries[], scaleLabels: string[], dimensions: ChartDimensions): ChartScales => {// For stacked/percent, the value-axis domain must reflect cumulative sums, not// individual series ranges — pass a synthetic series whose data is each layer's top.+ // Diverging stacks also need each layer's bottom so negative columns extend the domain+ // below 0 (the bottom of a positive-only stack is always 0, but a diverging stack with+ // negative values pushes the bottom below 0).let stackedSeries: Series[] | undefinedif (stackedData && barLayout === 'stacked') {- stackedSeries = coloredSeries.map((s) => {+ stackedSeries = coloredSeries.flatMap((s) => {const band = stackedData.get(s.key)- return band ? { ...s, data: band.top } : s+ if (!band) {+ return [s]+ }+ if (divergingStack) {+ return [+ { ...s, data: band.top },+ { ...s, key: `${s.key}__bottom`, data: band.bottom },+ ]+ }+ return [{ ...s, data: band.top }]})}@@ -185,7 +199,7 @@ function BarChartInner<Meta = unknown>({_private: barChartPrivate,}},- [yScaleType, barLayout, axisOrientation, stackedData, isHorizontal]+ [yScaleType, barLayout, axisOrientation, stackedData, isHorizontal, divergingStack])const drawStatic = useCallback(diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsxindex 3e277d2cbb56..67c6d9596cef 100644--- a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx@@ -39,6 +39,8 @@ export interface TimeSeriesBarChartConfig {showCrosshair?: boolean/** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */tooltip?: TooltipConfig+ /** Stacked layout only — stack negatives below the zero baseline (d3.stackOffsetDiverging). */+ divergingStack?: boolean}export interface TimeSeriesBarChartProps<Meta = unknown> {@@ -76,6 +78,7 @@ export function TimeSeriesBarChart<Meta = unknown>({barCornerRadius,showCrosshair,tooltip: tooltipConfig,+ divergingStack,} = config ?? {}const xTickFormatter = useXTickFormatter(xAxis, labels)const yTickFormatter = useYTickFormatter(yAxis)@@ -110,6 +113,7 @@ export function TimeSeriesBarChart<Meta = unknown>({axisOrientation,showCrosshair,tooltip: tooltipConfig,+ divergingStack,}return (diff --git a/frontend/src/lib/hog-charts/core/scales.test.ts b/frontend/src/lib/hog-charts/core/scales.test.tsindex 9898f070ebd1..c6229a097a47 100644--- a/frontend/src/lib/hog-charts/core/scales.test.ts+++ b/frontend/src/lib/hog-charts/core/scales.test.ts@@ -3,6 +3,7 @@ import {autoFormatYTick,buildSegmentResolveValue,buildStackedPositionValue,+ computeDivergingStackData,computePercentStackData,computeStackData,createScales,@@ -427,6 +428,18 @@ describe('hog-charts scales', () => {expect(result.get('s2')!.top).toEqual([30, 30])})+ it('computeDivergingStackData preserves negative values, stacking them below 0', () => {+ const positive = makeSeries({ key: 'pos', data: [10, 20] })+ const negative = makeSeries({ key: 'neg', data: [-5, -7] })+ const result = computeDivergingStackData([positive, negative], ['a', 'b'])+ // Positive stacks above zero, negative stacks below zero — diverging offset+ // keeps both signs intact instead of clamping the negative to 0.+ expect(result.get('pos')!.bottom).toEqual([0, 0])+ expect(result.get('pos')!.top).toEqual([10, 20])+ expect(result.get('neg')!.bottom).toEqual([-5, -7])+ expect(result.get('neg')!.top).toEqual([0, 0])+ })+it('stacks per yAxisId so series on different axes do not contaminate each others totals', () => {const left = makeSeries({ key: 'l', data: [10, 20], yAxisId: DEFAULT_Y_AXIS_ID })const right = makeSeries({ key: 'r', data: [1000, 2000], yAxisId: 'y1' })diff --git a/frontend/src/lib/hog-charts/core/scales.ts b/frontend/src/lib/hog-charts/core/scales.tsindex aa22ea86c8fa..fb739e6471d7 100644--- a/frontend/src/lib/hog-charts/core/scales.ts+++ b/frontend/src/lib/hog-charts/core/scales.ts@@ -193,8 +193,9 @@ export interface StackedBand {function buildStackData(series: Series[],labels: string[],- offset?: typeof d3.stackOffsetNone+ options: { offset?: typeof d3.stackOffsetNone; allowNegative?: boolean } = {}): Map<string, StackedBand> {+ const { offset, allowNegative = false } = optionsconst visibleSeries = series.filter((s) => !s.visibility?.excluded && !s.fill?.lowerData && !s.overlay)if (visibleSeries.length === 0) {return new Map()@@ -217,7 +218,8 @@ function buildStackData(const tableData = labels.map((_, i) => {const row: Record<string, number> = {}for (const s of axisSeries) {- row[s.key] = Math.max(0, s.data[i] ?? 0)+ const raw = s.data[i] ?? 0+ row[s.key] = allowNegative ? raw : Math.max(0, raw)}return row})@@ -245,7 +247,14 @@ export function computeStackData(series: Series[], labels: string[]): Map<string}export function computePercentStackData(series: Series[], labels: string[]): Map<string, StackedBand> {- return buildStackData(series, labels, d3.stackOffsetExpand)+ return buildStackData(series, labels, { offset: d3.stackOffsetExpand })+}++/** Stack that preserves negative segments — positives accumulate upward from 0, negatives+ * downward from 0 (d3.stackOffsetDiverging). Used by Lifecycle, where `dormant` is emitted+ * as a negative series so it renders below the zero baseline. */+export function computeDivergingStackData(series: Series[], labels: string[]): Map<string, StackedBand> {+ return buildStackData(series, labels, { offset: d3.stackOffsetDiverging, allowNegative: true })}/** Returns the stacked top of each series so the tooltip anchor and value-label positiondiff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.tsindex 68814b2ec210..4eaf25f476e2 100644--- a/frontend/src/lib/hog-charts/core/types.ts+++ b/frontend/src/lib/hog-charts/core/types.ts@@ -196,6 +196,9 @@ export interface BarChartConfig extends ChartConfig {* `barLayout: 'grouped'`; ignored for stacked/percent (the "share of a whole"* semantics don't apply when bars share a band). Defaults to `false`. */barTrack?: boolean+ /** Stacked layout only — use d3.stackOffsetDiverging so negative values stack+ * below the zero baseline (positives above). Default `false` clamps negatives to 0. */+ divergingStack?: boolean}export interface LineChartConfig extends ChartConfig {diff --git a/frontend/src/scenes/trends/Trends.tsx b/frontend/src/scenes/trends/Trends.tsxindex c85b394e94a4..db4e062d0046 100644--- a/frontend/src/scenes/trends/Trends.tsx+++ b/frontend/src/scenes/trends/Trends.tsx@@ -34,6 +34,13 @@ const TrendsBarChart = lazy(() =>default: m.TrendsBarChart,})))+const TrendsLifecycleChart = lazy(() =>+ import('products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart').then(+ (m) => ({+ default: m.TrendsLifecycleChart,+ })+ )+)interface Props {view: InsightType@@ -61,8 +68,13 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }const hogChartsTrendsEnabled =featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_TRENDS] && !isLifecycle && !isStickiness+ const hogChartsLifecycleEnabled =+ !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_LIFECYCLE] && isLifecycleconst renderViz = (): JSX.Element | undefined => {+ if (hogChartsLifecycleEnabled) {+ return <TrendsLifecycleChart context={context} inSharedMode={inSharedMode} />+ }if (!display ||display === ChartDisplayType.ActionsLineGraph ||diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsxindex 5cd72e55e02b..ac8922db479b 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx@@ -1,6 +1,5 @@import { useValues } from 'kea'-import posthog from 'posthog-js'-import { useCallback, useMemo, type ErrorInfo } from 'react'+import { useCallback, useMemo } from 'react'import { buildTheme } from 'lib/charts/utils/theme'import {@@ -27,11 +26,12 @@ import { QueryContext } from '~/queries/types'import { ChartDisplayType } from '~/types'import { AnnotationsLayer } from '../shared/AnnotationsLayer'+import { makeChartErrorHandler } from '../shared/chartErrorHandler'import { goalLinesToReferenceLines } from '../shared/goalLinesAdapter'import { handleTrendsChartClick, type TrendsChartClickDeps } from '../shared/handleTrendsChartClick'import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'import { trendsFilterToYFormatterConfig } from '../shared/trendsAxisFormat'-import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'+import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'import { TrendsTooltip } from '../shared/TrendsTooltip'import { handleTrendsBarAggregatedChartClick } from './handleTrendsBarAggregatedChartClick'import {@@ -49,15 +49,6 @@ const EMPTY_LABELS: string[] = []const TIME_SERIES_TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }const AGGREGATED_TOOLTIP_CONFIG = { pinnable: false }-const buildBarMeta = (r: IndexedTrendResult): TrendsSeriesMeta => ({- action: r.action,- breakdown_value: r.breakdown_value,- compare_label: r.compare_label,- days: r.days,- order: r.action?.order ?? r.id,- filter: r.filter,-})-type AggregationLabelFn = (groupTypeIndex: number | null | undefined) => { plural: string }const resolveGroupTypeLabel = (@@ -77,12 +68,7 @@ const resolveGroupTypeLabel = (return aggregationLabel(labelGroupType).plural}-const handleChartError = (error: Error, info: ErrorInfo): void => {- posthog.captureException(error, {- feature: 'trends-bar-chart',- componentStack: info.componentStack ?? undefined,- })-}+const handleChartError = makeChartErrorHandler('trends-bar-chart')export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChartProps): JSX.Element | null {const theme = useMemo(() => buildTheme(), [])@@ -131,13 +117,13 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChartreturn buildTrendsBarAggregatedSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {getColor: getTrendsColor,getHidden: getTrendsHidden,- buildMeta: buildBarMeta,+ buildMeta: buildTrendsSeriesMeta,})}const timeSeries = buildTrendsBarTimeSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {getColor: getTrendsColor,getHidden: getTrendsHidden,- buildMeta: buildBarMeta,+ buildMeta: buildTrendsSeriesMeta,})return { series: timeSeries, labels: currentPeriodResult?.labels ?? EMPTY_LABELS }}, [isAggregated, indexedResults, getTrendsColor, getTrendsHidden, currentPeriodResult?.labels])diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.stories.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.stories.tsxnew file mode 100644index 000000000000..d1564ac6a1f4--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.stories.tsx@@ -0,0 +1,165 @@+import { Meta, StoryObj } from '@storybook/react'+import { BindLogic } from 'kea'+import { useState } from 'react'++import { insightLogic } from 'scenes/insights/insightLogic'++import { mswDecorator } from '~/mocks/browser'+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import type { DataNodeLogicProps } from '~/queries/nodes/DataNode/dataNodeLogic'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'+import { getCachedResults } from '~/queries/nodes/InsightViz/utils'+import type { InsightLogicProps, InsightShortId } from '~/types'++import { TrendsLifecycleChart } from './TrendsLifecycleChart'++type Story = StoryObj<{}>++const meta: Meta = {+ title: 'Insights/TrendsLifecycleChart',+ component: TrendsLifecycleChart,+ parameters: {+ layout: 'centered',+ mockDate: '2023-07-11',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/annotations/': {+ count: 0,+ next: null,+ previous: null,+ results: [],+ },+ },+ }),+ ],+}+export default meta++let uniqueNode = 0++function Stage({ children }: { children: React.ReactNode }): JSX.Element {+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ height: 360, width: 720, display: 'flex', flexDirection: 'column' }}>{children}</div>+ )+}++function LifecycleStory({ insightFixture }: { insightFixture: any }): JSX.Element {+ const [dashboardItemId] = useState(() => `TrendsLifecycleChartStory.${uniqueNode++}` as InsightShortId)+ const cachedInsight = { ...insightFixture, short_id: dashboardItemId }++ const insightProps: InsightLogicProps = { dashboardItemId, doNotLoad: true, cachedInsight }+ const dataNodeLogicProps: DataNodeLogicProps = {+ query: cachedInsight.query.source,+ key: insightVizDataNodeKey(insightProps),+ cachedResults: getCachedResults(cachedInsight, cachedInsight.query.source),+ doNotLoad: true,+ }++ return (+ <BindLogic logic={insightLogic} props={insightProps}>+ <BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>+ <Stage>+ <TrendsLifecycleChart />+ </Stage>+ </BindLogic>+ </BindLogic>+ )+}++const LIFECYCLE_DAYS = [+ '2023-07-04',+ '2023-07-05',+ '2023-07-06',+ '2023-07-07',+ '2023-07-08',+ '2023-07-09',+ '2023-07-10',+]+const LIFECYCLE_LABELS = [+ '4-Jul-2023',+ '5-Jul-2023',+ '6-Jul-2023',+ '7-Jul-2023',+ '8-Jul-2023',+ '9-Jul-2023',+ '10-Jul-2023',+]++const ACTION = {+ id: '$pageview',+ type: 'events',+ order: 0,+ name: '$pageview',+ custom_name: null,+ math: 'total',+ math_property: null,+ math_hogql: null,+ math_group_type_index: null,+ properties: {},+}++const lifecycleSeries = (status: 'new' | 'returning' | 'resurrecting' | 'dormant', data: number[]): object => ({+ action: ACTION,+ label: `$pageview - ${status}`,+ count: data.reduce((a, b) => a + b, 0),+ aggregated_value: data.reduce((a, b) => a + b, 0),+ data,+ labels: LIFECYCLE_LABELS,+ days: LIFECYCLE_DAYS,+ status,+})++function lifecycleInsight(stacked: boolean, id: number, shortId: string): object {+ return {+ id,+ short_id: shortId,+ name: stacked ? 'Lifecycle stacked' : 'Lifecycle unstacked',+ derived_name: 'Lifecycle',+ filters: {},+ last_refresh: '2023-07-11T12:00:00Z',+ refreshing: false,+ saved: true,+ is_sample: false,+ description: '',+ tags: [],+ favorited: false,+ created_at: '2023-07-11T12:00:00Z',+ updated_at: '2023-07-11T12:00:00Z',+ last_modified_at: '2023-07-11T12:00:00Z',+ dashboards: [],+ dashboard_tiles: [],+ // The order intentionally does NOT match the canonical new → resurrecting → returning →+ // dormant order — the transform sorts by status, so the chart should look the same.+ result: [+ lifecycleSeries('returning', [42, 38, 45, 40, 50, 47, 44]),+ lifecycleSeries('new', [22, 30, 18, 24, 28, 20, 26]),+ lifecycleSeries('dormant', [-12, -10, -8, -14, -10, -9, -11]),+ lifecycleSeries('resurrecting', [6, 8, 5, 9, 7, 6, 8]),+ ],+ query: {+ kind: 'InsightVizNode',+ source: {+ dateRange: { date_from: '2023-07-04', date_to: '2023-07-10' },+ filterTestAccounts: false,+ interval: 'day',+ kind: 'LifecycleQuery',+ series: [{ event: '$pageview', kind: 'EventsNode', math: 'total', name: '$pageview' }],+ lifecycleFilter: { stacked },+ version: 2,+ },+ full: true,+ },+ }+}++export const Stacked: Story = {+ render: () => <LifecycleStory insightFixture={lifecycleInsight(true, 300, 'lifecycleStacked')} />,+}++export const Unstacked: Story = {+ render: () => <LifecycleStory insightFixture={lifecycleInsight(false, 301, 'lifecycleUnstacked')} />,+}diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsxnew file mode 100644index 000000000000..8935f59b7ad3--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx@@ -0,0 +1,147 @@+import '@testing-library/jest-dom'++import { cleanup, screen, waitFor } from '@testing-library/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { setupJsdom, setupSyncRaf } from 'lib/hog-charts/testing'++import { LifecycleQuery, LifecycleQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { chart, type InsightQuery, type MockResponse, personsModal, renderInsight } from '~/test/insight-testing'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ personsModal.cleanupAll()+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++const HOG_CHARTS_FLAG = { [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_LIFECYCLE]: true }++const LIFECYCLE_DAYS = ['2024-06-10', '2024-06-11', '2024-06-12', '2024-06-13', '2024-06-14']+const LIFECYCLE_LABELS = ['10-Jun', '11-Jun', '12-Jun', '13-Jun', '14-Jun']++const buildLifecycleSeries = (status: 'new' | 'returning' | 'resurrecting' | 'dormant', data: number[]): object => ({+ action: { id: '$pageview', type: 'events', name: '$pageview', order: 0 },+ label: `$pageview - ${status}`,+ count: data.reduce((a, b) => a + b, 0),+ aggregated_value: data.reduce((a, b) => a + b, 0),+ data,+ labels: LIFECYCLE_LABELS,+ days: LIFECYCLE_DAYS,+ status,+})++const lifecycleResponse: LifecycleQueryResponse = {+ results: [+ buildLifecycleSeries('new', [10, 12, 8, 14, 9]),+ buildLifecycleSeries('returning', [5, 6, 7, 5, 6]),+ buildLifecycleSeries('resurrecting', [2, 3, 4, 2, 3]),+ buildLifecycleSeries('dormant', [-3, -4, -2, -5, -3]),+ ],+} as LifecycleQueryResponse++const buildLifecycleQuery = (overrides: Partial<LifecycleQuery> = {}): LifecycleQuery => ({+ kind: NodeKind.LifecycleQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }],+ ...overrides,+})++const lifecycleMocks: MockResponse[] = [+ {+ match: (q) => q.kind === NodeKind.LifecycleQuery,+ response: lifecycleResponse,+ },+]++describe('TrendsLifecycleChart', () => {+ it('renders a stacked bar series for each lifecycle status', async () => {+ renderInsight({+ query: buildLifecycleQuery() as unknown as InsightQuery,+ featureFlags: HOG_CHARTS_FLAG,+ mocks: { additionalMockResponses: lifecycleMocks },+ })++ await waitFor(() => {+ expect(screen.getByTestId('trend-lifecycle-graph')).toBeInTheDocument()+ })+ await waitFor(() => {+ expect(screen.getByRole('img', { name: /chart with 4 data series/i })).toBeInTheDocument()+ })+ })++ it('shows the shortened lifecycle status in the tooltip rows', async () => {+ renderInsight({+ query: buildLifecycleQuery() as unknown as InsightQuery,+ featureFlags: HOG_CHARTS_FLAG,+ mocks: { additionalMockResponses: lifecycleMocks },+ })++ await screen.findByTestId('trend-lifecycle-graph')+ const tooltip = await chart.hoverTooltip(2)+ // Lifecycle status names appear capitalized — "New", "Returning", "Resurrecting", "Dormant".+ expect(tooltip.row('New')).toBeTruthy()+ expect(tooltip.row('Returning')).toBeTruthy()+ expect(tooltip.row('Resurrecting')).toBeTruthy()+ expect(tooltip.row('Dormant')).toBeTruthy()+ })++ it('uses "Users" as the group type label in the tooltip', async () => {+ renderInsight({+ query: buildLifecycleQuery() as unknown as InsightQuery,+ featureFlags: HOG_CHARTS_FLAG,+ mocks: { additionalMockResponses: lifecycleMocks },+ })++ await screen.findByTestId('trend-lifecycle-graph')+ const tooltip = await chart.hoverTooltip(2)+ expect(tooltip.element.textContent).toMatch(/Users/)+ })++ it('renders InsightEmptyState when every series count is zero', async () => {+ renderInsight({+ query: buildLifecycleQuery() as unknown as InsightQuery,+ featureFlags: HOG_CHARTS_FLAG,+ mocks: {+ additionalMockResponses: [+ {+ match: (q) => q.kind === NodeKind.LifecycleQuery,+ response: {+ results: [+ buildLifecycleSeries('new', [0, 0, 0, 0, 0]),+ buildLifecycleSeries('returning', [0, 0, 0, 0, 0]),+ buildLifecycleSeries('resurrecting', [0, 0, 0, 0, 0]),+ buildLifecycleSeries('dormant', [0, 0, 0, 0, 0]),+ ],+ } as LifecycleQueryResponse,+ },+ ],+ },+ })++ await waitFor(() => {+ expect(screen.getByTestId('insight-empty-state')).toBeInTheDocument()+ })+ })++ it('falls back to the legacy renderer when the flag is off', async () => {+ renderInsight({+ query: buildLifecycleQuery() as unknown as InsightQuery,+ featureFlags: {},+ mocks: { additionalMockResponses: lifecycleMocks },+ })++ // Without the flag the hog-charts data-attr is never rendered; the Chart.js LineGraph+ // renders a <canvas> instead.+ await waitFor(() => {+ expect(screen.queryByTestId('trend-lifecycle-graph')).not.toBeInTheDocument()+ })+ })+})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsxnew file mode 100644index 000000000000..5e8e840e6652--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx@@ -0,0 +1,190 @@+import { useValues } from 'kea'+import { useCallback, useMemo } from 'react'++import { buildTheme } from 'lib/charts/utils/theme'+import { TimeSeriesBarChart } from 'lib/hog-charts'+import type { PointClickData, TimeSeriesBarChartConfig, TooltipContext } from 'lib/hog-charts'+import { InsightEmptyState } from 'scenes/insights/EmptyStates'+import { insightLogic } from 'scenes/insights/insightLogic'+import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'+import { teamLogic } from 'scenes/teamLogic'+import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'+import type { IndexedTrendResult } from 'scenes/trends/types'++import { InsightVizNode } from '~/queries/schema/schema-general'+import { QueryContext } from '~/queries/types'++import { AnnotationsLayer } from '../shared/AnnotationsLayer'+import { makeChartErrorHandler } from '../shared/chartErrorHandler'+import {+ handleTrendsChartClick,+ LIFECYCLE_PERSONS_MODAL_OPTIONS,+ type TrendsChartClickDeps,+} from '../shared/handleTrendsChartClick'+import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'+import { TrendsTooltip } from '../shared/TrendsTooltip'+import { buildTrendsLifecycleConfig, buildTrendsLifecycleSeries } from './trendsLifecycleChartTransforms'++interface TrendsLifecycleChartProps {+ context?: QueryContext<InsightVizNode>+ inSharedMode?: boolean+}++const EMPTY_LABELS: string[] = []+const LIFECYCLE_TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }++const handleChartError = makeChartErrorHandler('trends-lifecycle-chart')++// Lifecycle rows label themselves by status ("New", "Returning", ...) — not by+// the underlying event/action. The row's ribbon color already identifies the+// series, so we render the label as plain text and skip InsightLabel (which+// would otherwise prefer `action.name` like "$pageview").+const renderLifecycleSeriesLabel = (datum: SeriesDatum): React.ReactNode => datum.label++export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLifecycleChartProps): JSX.Element | null {+ const theme = useMemo(() => buildTheme(), [])+ const { insightProps, insight } = useValues(insightLogic)++ const {+ indexedResults,+ interval,+ yAxisScaleType,+ currentPeriodResult,+ breakdownFilter,+ insightData,+ trendsFilter,+ lifecycleFilter,+ formula,+ hasPersonsModal,+ querySource,+ } = useValues(trendsDataLogic(insightProps))+ const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)++ const isStacked = lifecycleFilter?.stacked ?? true++ const hasData =+ !!indexedResults?.[0] &&+ !!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 timeSeriesConfig: TimeSeriesBarChartConfig = useMemo(+ () =>+ buildTrendsLifecycleConfig({+ trendsFilter,+ baseCurrency,+ isStacked,+ yAxisScaleType,+ interval,+ timezone,+ allDays: currentPeriodResult?.days ?? [],+ tooltip: LIFECYCLE_TOOLTIP_CONFIG,+ }),+ [trendsFilter, baseCurrency, isStacked, yAxisScaleType, interval, timezone, currentPeriodResult?.days]+ )++ const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal++ const clickDeps = useMemo<TrendsChartClickDeps>(+ () => ({+ context,+ hasPersonsModal: !!hasPersonsModal,+ interval,+ timezone,+ weekStartDay,+ resolvedDateRange: insightData?.resolved_date_range ?? null,+ querySource,+ indexedResults: indexedResults ?? [],+ openPersonsModal,+ }),+ [+ context,+ hasPersonsModal,+ interval,+ timezone,+ weekStartDay,+ insightData?.resolved_date_range,+ querySource,+ indexedResults,+ ]+ )++ const onPointClick = useCallback(+ (clickData: PointClickData<TrendsSeriesMeta>) => {+ handleTrendsChartClick(+ clickData.series.key,+ clickData.dataIndex,+ clickDeps,+ LIFECYCLE_PERSONS_MODAL_OPTIONS+ )+ },+ [clickDeps]+ )++ const renderTooltip = useCallback(+ (ctx: TooltipContext<TrendsSeriesMeta>) => {+ const onRowClick = canHandleClick+ ? (datum: SeriesDatum) => {+ const seriesKey = ctx.seriesData[datum.datasetIndex].series.key+ handleTrendsChartClick(seriesKey, datum.dataIndex, clickDeps, LIFECYCLE_PERSONS_MODAL_OPTIONS)+ }+ : undefined+ return (+ <TrendsTooltip+ context={ctx}+ timezone={timezone}+ interval={interval ?? undefined}+ breakdownFilter={breakdownFilter ?? undefined}+ dateRange={insightData?.resolved_date_range ?? undefined}+ trendsFilter={trendsFilter}+ formula={formula}+ baseCurrency={baseCurrency}+ groupTypeLabel="Users"+ onRowClick={onRowClick}+ renderSeriesOverride={renderLifecycleSeriesLabel}+ />+ )+ },+ [+ timezone,+ interval,+ breakdownFilter,+ insightData?.resolved_date_range,+ trendsFilter,+ formula,+ baseCurrency,+ canHandleClick,+ clickDeps,+ ]+ )++ if (!hasData) {+ return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />+ }++ const showAnnotations = !inSharedMode+ const annotationsDates = currentPeriodResult?.days ?? []++ return (+ <TimeSeriesBarChart<TrendsSeriesMeta>+ series={series}+ labels={labels}+ config={timeSeriesConfig}+ theme={theme}+ tooltip={renderTooltip}+ onPointClick={canHandleClick ? onPointClick : undefined}+ className="BarGraph"+ dataAttr="trend-lifecycle-graph"+ onError={handleChartError}+ >+ {showAnnotations && <AnnotationsLayer insightNumericId={insight.id || 'new'} dates={annotationsDates} />}+ </TimeSeriesBarChart>+ )+}diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.tsnew file mode 100644index 000000000000..27fac8cd6f98--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts@@ -0,0 +1,157 @@+// 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 {+ buildTrendsLifecycleConfig,+ buildTrendsLifecycleSeries,+ shortenLifecycleLabel,+ type TrendsLifecycleResultLike,+} from './trendsLifecycleChartTransforms'++describe('buildTrendsLifecycleSeries', () => {+ it('orders series new → resurrecting → returning → dormant regardless of input order', () => {+ const results: TrendsLifecycleResultLike[] = [+ { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1, -2, -3] },+ { id: 'returning', status: 'returning', label: 'Pageview - returning', data: [1, 2, 3] },+ { id: 'new', status: 'new', label: 'Pageview - new', data: [1, 2, 3] },+ { id: 'resurrecting', status: 'resurrecting', label: 'Pageview - resurrecting', data: [1, 2, 3] },+ ]+ const series = buildTrendsLifecycleSeries(results)++ expect(series.map((s) => s.key)).toEqual(['new', 'resurrecting', 'returning', 'dormant'])+ })++ 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] },+ ])++ expect(series[0].data).toEqual([-5, -6, -7])+ })++ it('uses fixed colors per lifecycle status, ignoring the data-color theme', () => {+ const results: TrendsLifecycleResultLike[] = [+ { id: 'new', status: 'new', label: 'Pageview - new', data: [1, 2, 3] },+ { id: 'resurrecting', status: 'resurrecting', label: 'Pageview - resurrecting', data: [1, 2, 3] },+ { 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)+ expect(series.map((s) => s.color)).toEqual(['#11ff11', '#22ff22', '#33ff33', '#44ff44'])+ })++ 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] },+ ])+ expect(series.find((s) => s.key === 'new')?.label).toBe('New')+ expect(series.find((s) => s.key === 'dormant')?.label).toBe('Dormant')+ })++ it('attaches meta from buildMeta with the original (pre-sort) index', () => {+ const results: TrendsLifecycleResultLike[] = [+ { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1] },+ { id: 'new', status: 'new', label: 'Pageview - new', data: [1] },+ ]+ const calls: Array<{ status: string; index: number }> = []+ buildTrendsLifecycleSeries(results, {+ 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 },+ ])+ )+ })++ it('marks excluded series with visibility.excluded so the chart skips them', () => {+ const results: TrendsLifecycleResultLike[] = [+ { id: 'new', status: 'new', label: 'Pageview - new', data: [1] },+ { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-1] },+ ]+ const series = buildTrendsLifecycleSeries(results, {+ getHidden: (r) => r.status === 'dormant',+ })+ const dormant = series.find((s) => s.key === 'dormant')+ const newSeries = series.find((s) => s.key === 'new')+ expect(dormant?.visibility).toEqual({ excluded: true })+ expect(newSeries?.visibility).toBeUndefined()+ })++ it('falls back to "None" label when the result label is null', () => {+ const series = buildTrendsLifecycleSeries([{ id: 'new', status: 'new', label: null, data: [1] }])+ expect(series[0].label).toBe('None')+ })+})++describe('buildTrendsLifecycleConfig', () => {+ it.each([+ { isStacked: true, expectedLayout: 'stacked', expectedDiverging: true },+ { isStacked: false, expectedLayout: 'grouped', expectedDiverging: false },+ ])(+ 'maps isStacked=$isStacked to barLayout=$expectedLayout / divergingStack=$expectedDiverging',+ ({ isStacked, expectedLayout, expectedDiverging }) => {+ const cfg = buildTrendsLifecycleConfig({ isStacked })+ expect(cfg.barLayout).toBe(expectedLayout)+ expect(cfg.divergingStack).toBe(expectedDiverging)+ }+ )++ it('builds the xAxis from interval/timezone/allDays', () => {+ const cfg = buildTrendsLifecycleConfig({+ isStacked: true,+ interval: 'day',+ timezone: 'UTC',+ allDays: ['2024-06-10', '2024-06-11'],+ })+ expect(cfg.xAxis).toEqual({+ timezone: 'UTC',+ interval: 'day',+ allDays: ['2024-06-10', '2024-06-11'],+ })+ })++ it('defaults interval to day and allDays to empty when omitted', () => {+ const cfg = buildTrendsLifecycleConfig({ isStacked: true })+ expect(cfg.xAxis).toEqual({ timezone: undefined, interval: 'day', allDays: [] })+ })++ it('forwards yAxisScaleType into the y-axis scale', () => {+ const cfg = buildTrendsLifecycleConfig({ isStacked: true, yAxisScaleType: 'log10' })+ expect(cfg.yAxis?.scale).toBe('log')+ })++ it('passes the tooltip config through unchanged', () => {+ const tooltip = { pinnable: true, placement: 'top' as const }+ const cfg = buildTrendsLifecycleConfig({ isStacked: true, tooltip })+ expect(cfg.tooltip).toEqual(tooltip)+ })+})++describe('shortenLifecycleLabel', () => {+ it.each([+ { input: 'Pageview - new', expected: 'New' },+ { input: 'Pageview - dormant', expected: 'Dormant' },+ { input: 'Logged in - returning', expected: 'Returning' },+ { input: 'just-a-label', expected: 'Just-a-label' },+ { input: undefined, expected: 'None' },+ { input: null, expected: 'None' },+ ])('returns $expected for $input', ({ input, expected }) => {+ expect(shortenLifecycleLabel(input)).toBe(expected)+ })+})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.tsnew file mode 100644index 000000000000..07fa1755e277--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts@@ -0,0 +1,104 @@+import { getBarColorFromStatus } from 'lib/colors'+import type { Series, TimeSeriesBarChartConfig } from 'lib/hog-charts'+import { capitalizeFirstLetter } from 'lib/utils'++import type { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'+import type { IntervalType, LifecycleToggle } from '~/types'++import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'+import { LIFECYCLE_STATUS_ORDER } from '../shared/trendsSeriesMeta'++// Shape both IndexedTrendResult (kea) and lighter fixtures satisfy.+export interface TrendsLifecycleResultLike {+ id?: string | number+ label?: string | null+ data: number[]+ status?: string+ days?: string[]+ action?: { order?: number } | null+}++function lifecycleStatusOrder(status: string | undefined): number {+ const i = LIFECYCLE_STATUS_ORDER.indexOf(status as LifecycleToggle)+ 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)+}++export interface BuildTrendsLifecycleSeriesOpts<R extends TrendsLifecycleResultLike, M = unknown> {+ getHidden?: (r: R, index: number) => boolean+ buildMeta?: (r: R, index: number) => M+}++export function buildTrendsLifecycleSeries<R extends TrendsLifecycleResultLike, M = unknown>(+ results: R[],+ opts: BuildTrendsLifecycleSeriesOpts<R, M> = {}+): Series<M>[] {+ // Stable lifecycle order: new → resurrecting → returning → dormant.+ // d3.stack emits layers in series order, so dormant ends up at the bottom of the+ // diverging stack (its data is negative) and renders below the zero baseline.+ const ordered = results+ .map((r, index) => ({ r, originalIndex: index }))+ .sort((a, b) => lifecycleStatusOrder(a.r.status) - lifecycleStatusOrder(b.r.status))++ return ordered.map(({ r, originalIndex }) => {+ const excluded = opts.getHidden ? opts.getHidden(r, originalIndex) : false+ const meta = opts.buildMeta ? opts.buildMeta(r, originalIndex) : undefined+ return {+ key: String(r.id ?? originalIndex),+ // Labels arrive as "Pageview - new" / "Pageview - returning"; the row's color+ // already identifies the underlying event, so we keep just the status —+ // shortened here so both legend and tooltip pick up the clean form.+ label: shortenLifecycleLabel(r.label),+ data: r.data,+ color: lifecycleColor(r.status),+ meta,+ visibility: excluded ? { excluded: true } : undefined,+ }+ })+}++export interface BuildTrendsLifecycleConfigOpts {+ trendsFilter?: TrendsFilter | null+ baseCurrency?: CurrencyCode+ isStacked: boolean+ yAxisScaleType?: string | null+ interval?: IntervalType | null+ timezone?: string+ allDays?: string[]+ tooltip?: TimeSeriesBarChartConfig['tooltip']+}++export function buildTrendsLifecycleConfig(opts: BuildTrendsLifecycleConfigOpts): TimeSeriesBarChartConfig {+ const yAxis = buildTrendsYAxisConfig(opts.trendsFilter, false, opts.baseCurrency, {+ yAxisScaleType: opts.yAxisScaleType,+ showGrid: true,+ })+ return {+ xAxis: {+ timezone: opts.timezone,+ interval: opts.interval ?? 'day',+ allDays: opts.allDays ?? [],+ },+ yAxis,+ barLayout: opts.isStacked ? 'stacked' : 'grouped',+ // Only meaningful in stacked layout — dormant stacks below 0.+ divergingStack: opts.isStacked,+ tooltip: opts.tooltip,+ }+}++/** 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)+}diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex 4e863479fb1e..eafa5e52e6aa 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -1,6 +1,5 @@import { useValues } from 'kea'-import posthog from 'posthog-js'-import { useCallback, useMemo, type ErrorInfo } from 'react'+import { useCallback, useMemo } from 'react'import { buildTheme } from 'lib/charts/utils/theme'import { DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from 'lib/hog-charts'@@ -20,9 +19,10 @@ import { InsightVizNode } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'import { AnnotationsLayer } from '../shared/AnnotationsLayer'+import { makeChartErrorHandler } from '../shared/chartErrorHandler'import { handleTrendsChartClick } from '../shared/handleTrendsChartClick'import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'-import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'+import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'import { TrendsTooltip } from '../shared/TrendsTooltip'import { buildTrendsLineTimeSeriesConfig, buildTrendsSeries } from './trendsChartTransforms'@@ -33,12 +33,7 @@ interface TrendsLineChartProps {const TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'top' }-const handleChartError = (error: Error, info: ErrorInfo): void => {- posthog.captureException(error, {- feature: 'trends-line-chart',- componentStack: info.componentStack ?? undefined,- })-}+const handleChartError = makeChartErrorHandler('trends-line-chart')export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChartProps): JSX.Element | null {const { isDarkModeOn } = useValues(themeLogic)@@ -101,14 +96,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaisStickiness,getColor: getTrendsColor,getHidden: getTrendsHidden,- buildMeta: (rr) => ({- action: rr.action,- breakdown_value: rr.breakdown_value,- compare_label: rr.compare_label,- days: rr.days,- order: rr.action?.order ?? rr.id,- filter: rr.filter,- }),+ buildMeta: buildTrendsSeriesMeta,}),[indexedResults,diff --git a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsxindex 9ce08d8f491f..19e313600ba6 100644--- a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx@@ -28,6 +28,11 @@ interface TrendsTooltipProps {formatCompareLabel?: (label: string, dateLabel?: string) => stringonRowClick?: (datum: SeriesDatum) => voidshowHeader?: boolean+ // Overrides the default SeriesLetter + InsightLabel row renderer. Mirrors the+ // legacy ActionsLineGraph escape hatch used for lifecycle, where the label+ // is the lifecycle status itself (e.g. "New") and InsightLabel's action.name+ // would otherwise mask it.+ renderSeriesOverride?: (datum: SeriesDatum) => React.ReactNode}/** Bridges hog-charts TooltipContext to the legacy InsightTooltip.@@ -48,6 +53,7 @@ export function TrendsTooltip({formatCompareLabel,onRowClick,showHeader,+ renderSeriesOverride,}: TrendsTooltipProps): React.ReactElement {const seriesData = useMemo<SeriesDatum[]>(() =>@@ -91,6 +97,9 @@ export function TrendsTooltip({const renderSeries = useCallback((value: React.ReactNode, datum: SeriesDatum): React.ReactElement => {+ if (renderSeriesOverride) {+ return <div className="datum-label-column">{renderSeriesOverride(datum)}</div>+ }const hasBreakdown = datum.breakdown_value !== undefined && !!datum.breakdown_valueif (hasBreakdown && !hasMultipleSeries) {@@ -112,7 +121,7 @@ export function TrendsTooltip({</div>)},- [hasMultipleSeries, breakdownFilter, formatCompareLabel, formula]+ [hasMultipleSeries, breakdownFilter, formatCompareLabel, formula, renderSeriesOverride])return (diff --git a/products/product_analytics/frontend/insights/trends/shared/chartErrorHandler.ts b/products/product_analytics/frontend/insights/trends/shared/chartErrorHandler.tsnew file mode 100644index 000000000000..0232663fe37a--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/chartErrorHandler.ts@@ -0,0 +1,13 @@+import posthog from 'posthog-js'+import type { ErrorInfo } from 'react'++/** `onError` handler for hog-charts trends adapters. Captures the React error+ * boundary's error/info to PostHog, tagged with the chart `feature` name. */+export function makeChartErrorHandler(feature: string): (error: Error, info: ErrorInfo) => void {+ return (error, info) => {+ posthog.captureException(error, {+ feature,+ componentStack: info.componentStack ?? undefined,+ })+ }+}diff --git a/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsx b/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsxindex c23589db86b7..b6487c8d1c67 100644--- a/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsx@@ -20,13 +20,38 @@ export interface TrendsChartClickDeps {openPersonsModal: (props: OpenPersonsModalProps) => void}+/** Persons-modal overrides for the click handler. The default targets bar/line trends —+ * actor rows show event count, are recordings-aware, and sort by event count desc.+ * Lifecycle uses {@link LIFECYCLE_PERSONS_MODAL_OPTIONS}: the underlying actor query+ * already carries the lifecycle `status` (via `datasetToActorsQuery`), so no extra+ * columns or ordering are needed. */+export type TrendsPersonsModalOptions = Pick<OpenPersonsModalProps, 'additionalSelect' | 'orderBy'>++export const DEFAULT_PERSONS_MODAL_OPTIONS: TrendsPersonsModalOptions = {+ additionalSelect: {+ value_at_data_point: 'event_count',+ matched_recordings: 'matched_recordings',+ },+ orderBy: ['event_count DESC, actor_id DESC'],+}++export const LIFECYCLE_PERSONS_MODAL_OPTIONS: TrendsPersonsModalOptions = {+ additionalSelect: {},+ orderBy: undefined,+}+// Adapters key each hog-charts Series by `${r.id}`, so we can resolve back// to the source IndexedTrendResult without stashing it on meta.-function resolveDataset(seriesKey: string, indexedResults: IndexedTrendResult[]): IndexedTrendResult | null {+export function resolveDataset(seriesKey: string, indexedResults: IndexedTrendResult[]): IndexedTrendResult | null {return indexedResults.find((r) => String(r.id) === seriesKey) ?? null}-export function handleTrendsChartClick(seriesKey: string, dataIndex: number, deps: TrendsChartClickDeps): void {+export function handleTrendsChartClick(+ seriesKey: string,+ dataIndex: number,+ deps: TrendsChartClickDeps,+ personsModalOptions: TrendsPersonsModalOptions = DEFAULT_PERSONS_MODAL_OPTIONS+): void {const dataset = resolveDataset(seriesKey, deps.indexedResults)if (!dataset) {return@@ -70,10 +95,7 @@ export function handleTrendsChartClick(seriesKey: string, dataIndex: number, depdeps.openPersonsModal({title,query: datasetToActorsQuery({ dataset, query: deps.querySource, day }),- additionalSelect: {- value_at_data_point: 'event_count',- matched_recordings: 'matched_recordings',- },- orderBy: ['event_count DESC, actor_id DESC'],+ additionalSelect: personsModalOptions.additionalSelect,+ orderBy: personsModalOptions.orderBy,})}diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.tsindex 338d62dd1e27..f8b9bb0fbee3 100644--- a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts+++ b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts@@ -1,6 +1,7 @@import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'+import type { IndexedTrendResult } from 'scenes/trends/types'-import type { ActionFilter } from '~/types'+import type { ActionFilter, LifecycleToggle } from '~/types'export type TrendsSeriesMeta = {action?: ActionFilter@@ -10,3 +11,18 @@ export type TrendsSeriesMeta = {order?: numberfilter?: SeriesDatum['filter']}++/** Canonical lifecycle order: new → resurrecting → returning → dormant.+ * Used both as a status enumeration and as the stack order for the diverging stack —+ * dormant ends up at the bottom because its data is negative. Callers that need the+ * legacy descending order (`trendsDataLogic.ts:197`) can iterate in reverse. */+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,+ compare_label: r.compare_label,+ days: r.days,+ order: r.action?.order ?? r.id,+ filter: r.filter,+})