: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(funnels): migrate FunnelLineGraph to hog-charts TimeSeriesLineChart (#59667)
Sam Pennington54b9dee24214
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b60700d89e3e..14428cb67e53 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1864,6 +1864,18 @@ snapshots:hash: v1.k794b7964.85a7028e6729988dedf767a52640b16c94aa48baf0ab9c89b1085c38d4e8cc8e.wDERvaZQvyEVwZsoj2q7nTwZSDswGOq-6dnRNcvuRpwinsights-funnelcorrelationtable--default--light:hash: v1.k794b7964.a5ccf40b74b63001bb7383ff53cb81b8f4f4a07308e0b6a2ad590ff821efc3ee.wCJ8wpYAyHJfnQB7k7qNZZKqiPtIq2sppx3qVS4IGQQ+ insights-funnellinechart--default--dark:+ hash: v1.k794b7964.88b532c89fa992eac628ca0a779b0889d74e00e650284960e1d935f5e7e8704c.9XjpRbnpuvI56K35oITlbW-Z4_d8VXboPy03ork9yaY+ insights-funnellinechart--default--light:+ hash: v1.k794b7964.bc3e2e9caee13301c07d79564d2c7e01a29c748a1f382496585f58f2ac283389.SDhk8kXtp9imHhdiYpRwgQfwSXvcH_oeQ8m1K729q0Q+ insights-funnellinechart--goal-line--dark:+ hash: v1.k794b7964.bda4551694dc54902b3e46ffb327e0d713af760b1a53ae7b7453779fa1e26bbf.pFfUWaxERw1KCaA9ZcqwB0R8TKC4CDiD5ift8kApZM4+ insights-funnellinechart--goal-line--light:+ hash: v1.k794b7964.35b2f6e08b22e8b95c561f10f4a3eeee0ec5355d91aa166db2cc3595f2acc4ae.iqDGpipKH0res85GZFCYszkpygWdzEM7lweEmg62j6M+ insights-funnellinechart--value-labels--dark:+ hash: v1.k794b7964.0c55587cfcea1fc34a6aede2eccbaac54ac296aa405d1272fc3c09efc1d02a6b.7kVLiv-W7Mk_5t8YKcXB2IM_ikwvMm5ssyT_uxoJvfw+ insights-funnellinechart--value-labels--light:+ hash: v1.k794b7964.746ea8a29d8e924baa6e7384d7a3a4a357727d37877668d15caae4fe2fcb4398.NoQWMVJ_C7Tw-ejmNiYdWnToUC5v0SdTi7OL5e6TrIoinsights-funnelpropertycorrelationtable--default--dark:hash: v1.k794b7964.49a465be8c619b1b05298a08904f554cb8636e8080dece84b8a37f85e1fefa8f.XYyBv_BrMjUV6Vqt_JHcot038t7pXgyS7FSXNBV7wJsinsights-funnelpropertycorrelationtable--default--light:diff --git a/frontend/src/scenes/funnels/Funnel.tsx b/frontend/src/scenes/funnels/Funnel.tsxindex d1d0067f0b4d..ae057ebf59cd 100644--- a/frontend/src/scenes/funnels/Funnel.tsx+++ b/frontend/src/scenes/funnels/Funnel.tsx@@ -3,6 +3,7 @@ import './Funnel.scss'import { useValues } from 'kea'import { FunnelLayout } from 'lib/constants'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { FunnelLineGraph } from 'scenes/funnels/FunnelLineGraph'import { insightLogic } from 'scenes/insights/insightLogic'@@ -13,15 +14,17 @@ import { FunnelBarVertical } from './FunnelBarVertical/FunnelBarVertical'import { funnelDataLogic } from './funnelDataLogic'import { FunnelFlowGraph } from './FunnelFlowGraph/FunnelFlowGraph'import { FunnelHistogram } from './FunnelHistogram'+import { FunnelLineChart } from './viz/funnel-line-chart/FunnelLineChart'export function Funnel(props: ChartParams): JSX.Element {const { insightProps } = useValues(insightLogic)const { funnelsFilter } = useValues(funnelDataLogic(insightProps))+ const hogChartsFunnelEnabled = useFeatureFlag('PRODUCT_ANALYTICS_HOG_CHARTS_FUNNEL')const { funnelVizType, layout } = funnelsFilter || {}let viz: JSX.Element | null = nullif (funnelVizType == FunnelVizType.Trends) {- viz = <FunnelLineGraph {...props} />+ viz = hogChartsFunnelEnabled ? <FunnelLineChart {...props} /> : <FunnelLineGraph {...props} />} else if (funnelVizType == FunnelVizType.TimeToConvert) {viz = <FunnelHistogram />} else if (funnelVizType === FunnelVizType.Flow) {diff --git a/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.stories.tsx b/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.stories.tsxnew file mode 100644index 000000000000..5c09b7c03527--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.stories.tsx@@ -0,0 +1,115 @@+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 { FunnelsFilter } from '~/queries/schema/schema-general'+import { InsightLogicProps, InsightShortId } from '~/types'++import { FunnelLineChart } from './FunnelLineChart'++type Story = StoryObj<{}>++const meta: Meta = {+ title: 'Insights/FunnelLineChart',+ component: FunnelLineChart,+ parameters: {+ layout: 'centered',+ mockDate: '2022-03-12',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/annotations/': {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: 1,+ content: 'Funnel optimization shipped',+ date_marker: '2022-03-10T12:00:00Z',+ creation_type: 'USR',+ dashboard_item: null,+ created_by: {+ id: 1,+ uuid: '0188cbcf-2391-0000-1868-14fb987285c5',+ distinct_id: 'storybook-user',+ first_name: 'Story',+ email: '[email protected]',+ },+ created_at: '2022-03-10T12:00:00Z',+ updated_at: '2022-03-10T12:00:00Z',+ deleted: false,+ scope: 'project',+ },+ ],+ },+ },+ }),+ ],+}+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 renderFunnelLineChart(insightFixture: any, funnelsFilterOverrides?: Partial<FunnelsFilter>): JSX.Element {+ const [dashboardItemId] = useState(() => `FunnelLineChartStory.${uniqueNode++}` as InsightShortId)+ const source = {+ ...insightFixture.query.source,+ funnelsFilter: { ...insightFixture.query.source.funnelsFilter, ...funnelsFilterOverrides },+ }+ const cachedInsight = { ...insightFixture, short_id: dashboardItemId, query: { ...insightFixture.query, source } }++ const insightProps: InsightLogicProps = { dashboardItemId, doNotLoad: true, cachedInsight }+ const dataNodeLogicProps: DataNodeLogicProps = {+ query: source,+ key: insightVizDataNodeKey(insightProps),+ cachedResults: getCachedResults(cachedInsight, source),+ doNotLoad: true,+ }++ return (+ <BindLogic logic={insightLogic} props={insightProps}>+ <BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>+ <Stage>+ <FunnelLineChart />+ </Stage>+ </BindLogic>+ </BindLogic>+ )+}++/* eslint-disable @typescript-eslint/no-var-requires */+const funnelTrendsInsight = (): any =>+ require('../../../../mocks/fixtures/api/projects/team_id/insights/funnelHistoricalTrends.json')++export const Default: Story = {+ render: () => renderFunnelLineChart(funnelTrendsInsight()),+}++export const ValueLabels: Story = {+ render: () => renderFunnelLineChart(funnelTrendsInsight(), { showValuesOnSeries: true }),+}++export const GoalLine: Story = {+ render: () =>+ renderFunnelLineChart(funnelTrendsInsight(), {+ goalLines: [{ label: 'Target', value: 10, displayIfCrossed: true }],+ }),+}+/* eslint-enable @typescript-eslint/no-var-requires */diff --git a/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.test.tsx b/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.test.tsxnew file mode 100644index 000000000000..599e664da1b5--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.test.tsx@@ -0,0 +1,181 @@+import '@testing-library/jest-dom'++import { cleanup, screen, waitFor } from '@testing-library/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { ensureJsdom, waitForHogChartTooltip } from 'lib/hog-charts/testing'+import { FUNNEL_CONVERSION_SERIES_LABEL } from 'scenes/funnels/viz/shared/funnelSeriesMeta'++import { buildFunnelsQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'+import { buildAnnotation } from '~/test/insight-testing/test-data'+import { AnnotationScope } from '~/types'++ensureJsdom()++afterEach(() => {+ personsModal.cleanupAll()+ cleanup()+})++const HOG_CHARTS_FUNNEL_FLAG = { [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_FUNNEL]: true }++describe('FunnelLineChart', () => {+ describe('series rendering', () => {+ it('renders a single conversion series with percentage values in the tooltip', async () => {+ renderInsight({ query: buildFunnelsQuery(), featureFlags: HOG_CHARTS_FUNNEL_FLAG })++ const tooltip = await chart.hoverTooltip(2)++ expect(getHogChart().seriesCount).toBe(1)+ expect(tooltip.element.textContent).toContain(FUNNEL_CONVERSION_SERIES_LABEL)+ expect(tooltip.element.textContent).toContain('40%')+ })++ it('renders a series per breakdown variant', async () => {+ renderInsight({+ query: buildFunnelsQuery({+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },+ }),+ featureFlags: HOG_CHARTS_FUNNEL_FLAG,+ })++ await waitFor(() => {+ expect(getHogChart().seriesCount).toBe(2)+ })+ })++ it('shows the breakdown label on each tooltip row when broken down', async () => {+ renderInsight({+ query: buildFunnelsQuery({+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },+ }),+ featureFlags: HOG_CHARTS_FUNNEL_FLAG,+ })++ await chart.clickAtIndex(2)+ const tooltip = await waitForHogChartTooltip()+ expect(tooltip.textContent).toContain('Spike')+ expect(tooltip.textContent).toContain('Bramble')+ })+ })++ describe('click → persons modal', () => {+ it('opens the persons modal with the day-scoped actors for a single-series chart', async () => {+ renderInsight({ query: buildFunnelsQuery(), featureFlags: HOG_CHARTS_FUNNEL_FLAG })++ await chart.clickAtIndex(2)++ await waitFor(() => {+ expect(personsModal.actorNames()).toEqual(['[email protected]', '[email protected]'])+ })+ expect(personsModal.title()).toMatch(/12 Jun/)+ })++ it('opens the persons modal scoped to the clicked breakdown row', async () => {+ renderInsight({+ query: buildFunnelsQuery({+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },+ }),+ featureFlags: HOG_CHARTS_FUNNEL_FLAG,+ })++ await chart.clickAtIndex(2)+ await chart.clickTooltipRow('Spike')++ await waitFor(() => {+ expect(personsModal.actorNames()).toEqual(['[email protected]'])+ })+ })+ })++ describe('value labels overlay', () => {+ it('renders percentage value labels when showValuesOnSeries is enabled', async () => {+ renderInsight({+ query: buildFunnelsQuery({ funnelsFilter: { showValuesOnSeries: true } }),+ featureFlags: HOG_CHARTS_FUNNEL_FLAG,+ })++ await screen.findByRole('img', { name: /chart with/i })+ await waitFor(() => {+ const texts = getHogChart()+ .valueLabels()+ .map((l) => l.text)+ // default fixture data [10, 25, 40, 60, 35] rendered as percentages+ expect([...texts].sort()).toEqual(['10%', '25%', '35%', '40%', '60%'])+ })+ })+ })++ describe('goal lines', () => {+ it('renders configured goal lines on the chart', async () => {+ renderInsight({+ query: buildFunnelsQuery({+ funnelsFilter: { goalLines: [{ label: 'Target', value: 30, displayIfCrossed: true }] },+ }),+ featureFlags: HOG_CHARTS_FUNNEL_FLAG,+ })++ await screen.findByRole('img', { name: /chart with/i })+ const lines = getHogChart().referenceLines()+ // value→pixel isn't recoverable from the DOM; assert the line is labelled,+ // drawn horizontally (across the value axis), and actually positioned.+ expect(lines).toEqual([+ expect.objectContaining({ label: 'Target', orientation: 'horizontal', position: expect.any(Number) }),+ ])+ })+ })++ describe('trend lines overlay', () => {+ it('adds a trend-line overlay when showTrendLines is enabled', async () => {+ renderInsight({+ query: buildFunnelsQuery({ funnelsFilter: { showTrendLines: true, showValuesOnSeries: true } }),+ featureFlags: HOG_CHARTS_FUNNEL_FLAG,+ })++ // main series + trend-line series = 2 rendered series+ await waitFor(() => {+ expect(getHogChart().seriesCount).toBe(2)+ })++ // the trend line is an overlay — excluded from value labels, so the 5 data+ // points yield 5 labels, not 10 (a regular 2nd series would double them)+ await waitFor(() => {+ expect(getHogChart().valueLabels()).toHaveLength(5)+ })+ })+ })++ describe('annotations', () => {+ it.each([+ { inSharedMode: false, expectsBadges: true },+ { inSharedMode: true, expectsBadges: false },+ ])(+ 'renders annotation badges only when inSharedMode is false (inSharedMode=$inSharedMode)',+ async ({ inSharedMode, expectsBadges }) => {+ renderInsight({+ query: buildFunnelsQuery(),+ featureFlags: HOG_CHARTS_FUNNEL_FLAG,+ inSharedMode,+ mocks: {+ annotations: [+ buildAnnotation({+ scope: AnnotationScope.Project,+ content: 'Hedgehog spotted',+ date_marker: '2024-06-12T12:00:00Z',+ }),+ ],+ },+ })++ if (expectsBadges) {+ await waitFor(() => {+ expect(document.querySelectorAll('.AnnotationsBadge').length).toBeGreaterThan(0)+ })+ } else {+ await screen.findByRole('img', { name: /chart with/i })+ expect(document.querySelectorAll('.AnnotationsBadge')).toHaveLength(0)+ }+ }+ )+ })+})diff --git a/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.tsx b/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.tsxnew file mode 100644index 000000000000..e1840e64d922--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-line-chart/FunnelLineChart.tsx@@ -0,0 +1,183 @@+import { useValues } from 'kea'+import posthog from 'posthog-js'+import { useMemo, type ErrorInfo } from 'react'++import { buildTheme } from 'lib/charts/utils/theme'+import { TimeSeriesLineChart } from 'lib/hog-charts'+import type { PointClickData, TimeSeriesLineChartConfig, TooltipConfig, TooltipContext } from 'lib/hog-charts'+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 { AnnotationsLayer } from 'scenes/trends/viz/shared/AnnotationsLayer'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { cohortsModel } from '~/models/cohortsModel'+import type { Noun } from '~/models/groupsModel'+import { groupsModel } from '~/models/groupsModel'+import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'+import { isFunnelsQuery } from '~/queries/utils'+import { ChartParams, type FunnelStepWithConversionMetrics } from '~/types'++import { funnelDataLogic } from '../../funnelDataLogic'+import { funnelPersonsModalLogic } from '../../funnelPersonsModalLogic'+import type { FunnelSeriesMeta } from '../shared/funnelSeriesMeta'+import { buildFunnelLineSeries, buildFunnelLineTimeSeriesConfig, type IndexedFunnelStep } from './funnelChartTransforms'+import { FunnelLineTooltip } from './FunnelLineTooltip'+import { type FunnelLineChartClickDeps, handleFunnelLineChartClick } from './handleFunnelLineChartClick'++const TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'top' }+const EMPTY_STRINGS: string[] = []++const handleChartError = (error: Error, info: ErrorInfo): void => {+ posthog.captureException(error, {+ feature: 'funnels-line-chart',+ componentStack: info.componentStack ?? undefined,+ })+}++function resolveGroupTypeLabel(+ labelGroupType: 'people' | 'none' | number,+ aggregationLabel: (groupTypeIndex: number) => Noun+): string {+ if (labelGroupType === 'people') {+ return 'people'+ }+ if (labelGroupType === 'none') {+ return ''+ }+ return aggregationLabel(labelGroupType).plural+}++export function FunnelLineChart({+ inSharedMode,+ showPersonsModal: showPersonsModalProp = true,+}: Omit<ChartParams, 'filters'>): JSX.Element | null {+ const { isDarkModeOn } = useValues(themeLogic)+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])+ const { insightProps, insight } = useValues(insightLogic)++ const {+ indexedSteps,+ goalLines,+ aggregationTargetLabel,+ incompletenessOffsetFromEnd,+ querySource,+ interval,+ insightData,+ showValuesOnSeries,+ funnelsFilter,+ breakdownFilter,+ labelGroupType,+ getFunnelsColor,+ } = useValues(funnelDataLogic(insightProps))+ const { canOpenPersonModal } = useValues(funnelPersonsModalLogic(insightProps))+ const { timezone, weekStartDay } = useValues(teamLogic)+ const { allCohorts } = useValues(cohortsModel)+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const { aggregationLabel } = useValues(groupsModel)++ const showPersonsModal = canOpenPersonModal && showPersonsModalProp+ const steps = useMemo(() => (indexedSteps ?? []) as IndexedFunnelStep[], [indexedSteps])++ const series = useMemo(+ () =>+ buildFunnelLineSeries(steps, {+ incompletenessOffsetFromEnd,+ // getFunnelsColor is typed for the steps-viz datasets; for the trends viz it+ // only reads `breakdown_value`, which IndexedFunnelStep carries.+ getColor: (step) => getFunnelsColor(step as unknown as FunnelStepWithConversionMetrics),+ }),+ [steps, incompletenessOffsetFromEnd, getFunnelsColor]+ )++ const chartConfig: TimeSeriesLineChartConfig = useMemo(+ () =>+ buildFunnelLineTimeSeriesConfig({+ indexedSteps: steps,+ interval,+ timezone,+ allDays: steps[0]?.days ?? [],+ goalLines,+ incompletenessOffsetFromEnd,+ showTrendLines: funnelsFilter?.showTrendLines ?? false,+ valueLabels: showValuesOnSeries ? { formatter: (value) => `${value}%` } : false,+ showCrosshair: true,+ tooltip: TOOLTIP_CONFIG,+ }),+ [+ steps,+ interval,+ timezone,+ goalLines,+ incompletenessOffsetFromEnd,+ funnelsFilter?.showTrendLines,+ showValuesOnSeries,+ ]+ )++ if (!isFunnelsQuery(querySource)) {+ return null+ }++ const resolvedGroupTypeLabel = resolveGroupTypeLabel(labelGroupType, aggregationLabel)+ const labels = steps[0]?.labels ?? EMPTY_STRINGS+ const annotationDates = steps[0]?.days ?? EMPTY_STRINGS++ const clickDeps: FunnelLineChartClickDeps = {+ hasPersonsModal: showPersonsModal,+ querySource,+ interval,+ timezone,+ weekStartDay,+ resolvedDateRange: insightData?.resolved_date_range ?? null,+ breakdownFilter,+ aggregationTargetLabel,+ cohorts: allCohorts.results,+ formatPropertyValueForDisplay,+ openPersonsModal,+ }++ const onPointClick = (clickData: PointClickData<FunnelSeriesMeta>): void => {+ if (clickData.series.meta) {+ handleFunnelLineChartClick(clickData.series.meta, clickData.dataIndex, clickDeps)+ }+ }++ const renderTooltip = (ctx: TooltipContext<FunnelSeriesMeta>): JSX.Element => (+ <FunnelLineTooltip+ context={ctx}+ timezone={timezone}+ interval={interval ?? undefined}+ breakdownFilter={breakdownFilter ?? undefined}+ dateRange={insightData?.resolved_date_range ?? undefined}+ groupTypeLabel={resolvedGroupTypeLabel}+ onRowClick={+ showPersonsModal+ ? (datum: SeriesDatum) => {+ const meta = ctx.seriesData[datum.datasetIndex]?.series.meta+ if (meta) {+ handleFunnelLineChartClick(meta, datum.dataIndex, clickDeps)+ }+ }+ : undefined+ }+ />+ )++ return (+ <TimeSeriesLineChart<FunnelSeriesMeta>+ series={series}+ labels={labels}+ theme={theme}+ config={chartConfig}+ tooltip={renderTooltip}+ onPointClick={showPersonsModal ? onPointClick : undefined}+ className="LineGraph"+ dataAttr="trend-line-graph-funnel"+ onError={handleChartError}+ >+ {!inSharedMode && <AnnotationsLayer insightNumericId={insight.id || 'new'} dates={annotationDates} />}+ </TimeSeriesLineChart>+ )+}