: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 vertical funnel steps viz to hog-charts BarChart (#59743)
Sam Pennington82caeb48716e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0d8af292509f..40e3c472668d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1892,6 +1892,14 @@ snapshots:hash: v1.k794b7964.49a465be8c619b1b05298a08904f554cb8636e8080dece84b8a37f85e1fefa8f.XYyBv_BrMjUV6Vqt_JHcot038t7pXgyS7FSXNBV7wJsinsights-funnelpropertycorrelationtable--default--light:hash: v1.k794b7964.46127dfa894a9b46a595c1b48b9bd8996a2851ce5ae04e70c4f1ee43d2d818ec.dddj8FIYUsb6XDaYbe4eQ_k4bJ5NY2kvo6m3KFS3Vwg+ insights-funnelstepsbarchart--breakdown--dark:+ hash: v1.k794b7964.4fdfbf1fced53a530a770c9e757892faefb8fb6ba5e2c664d175562441dc33af.4CZffzRTcE99pBKIvo6o7ggKeXPU7bmpzslEM0DFAEM+ insights-funnelstepsbarchart--breakdown--light:+ hash: v1.k794b7964.d57f0a6959ac0bb6a84f2914bce51d44dafabd09b166d39c095263b3ab82e9e5.q_Zv6bRyEI9gx7WVcyh0YoQT4ym68bZJt5Xmy-NvS9Q+ insights-funnelstepsbarchart--default--dark:+ hash: v1.k794b7964.2ae1ba07ab95585978ce1828ce81125d0285e2e8a9c83b70d8040c809fe83005.XZhWCtYy8v4FXcMk-Oxruk9K0AvIy_V8Q1-CicVQHHg+ insights-funnelstepsbarchart--default--light:+ hash: v1.k794b7964.3c1fc6cc15dda94c60eb841cfeaa6496c9adb21171c49ee28c11c456de9a2b57.CMa3pHrAA_2KEuBwIPzWi5moIIiByHasJtnx-LVe0gQinsights-insightstable--aggregation--dark:hash: v1.k794b7964.7ca9378b33815143119b6263ad32770289133ce2faa21251189b505821d7d846.NXyGQGn0JrsrEWfzXtZTntAvvx5CSTKBLXWWdzgkCI8insights-insightstable--aggregation--light:diff --git a/frontend/src/scenes/funnels/Funnel.tsx b/frontend/src/scenes/funnels/Funnel.tsxindex 2645bc14566e..f28beab21adf 100644--- a/frontend/src/scenes/funnels/Funnel.tsx+++ b/frontend/src/scenes/funnels/Funnel.tsx@@ -16,6 +16,7 @@ import { FunnelFlowGraph } from './FunnelFlowGraph/FunnelFlowGraph'import { FunnelHistogram } from './FunnelHistogram'import { FunnelHistogramChart } from './viz/funnel-histogram/FunnelHistogramChart'import { FunnelLineChart } from './viz/funnel-line-chart/FunnelLineChart'+import { FunnelStepsBarChart } from './viz/funnel-steps-bar-chart/FunnelStepsBarChart'export function Funnel(props: ChartParams): JSX.Element {const { insightProps } = useValues(insightLogic)@@ -31,7 +32,7 @@ export function Funnel(props: ChartParams): JSX.Element {} else if (funnelVizType === FunnelVizType.Flow) {viz = <FunnelFlowGraph />} else if ((layout || FunnelLayout.vertical) === FunnelLayout.vertical) {- viz = <FunnelBarVertical {...props} />+ viz = hogChartsFunnelEnabled ? <FunnelStepsBarChart {...props} /> : <FunnelBarVertical {...props} />} else {viz = <FunnelBarHorizontal {...props} />}diff --git a/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarChart.stories.tsx b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarChart.stories.tsxnew file mode 100644index 000000000000..e0b17f6cd20b--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarChart.stories.tsx@@ -0,0 +1,74 @@+import { Meta, StoryObj } from '@storybook/react'+import { BindLogic } from 'kea'+import { useState } from 'react'++import { insightLogic } from 'scenes/insights/insightLogic'++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 { InsightLogicProps, InsightShortId } from '~/types'++import { FunnelStepsBarChart } from './FunnelStepsBarChart'++type Story = StoryObj<{}>++const meta: Meta = {+ title: 'Insights/FunnelStepsBarChart',+ component: FunnelStepsBarChart,+ parameters: {+ layout: 'centered',+ mockDate: '2022-03-12',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+}+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: 420, width: 720, display: 'flex', flexDirection: 'column' }}>{children}</div>+ )+}++function StoryRender({ insightFixture }: { insightFixture: any }): JSX.Element {+ const [dashboardItemId] = useState(() => `FunnelStepsBarChartStory.${uniqueNode++}` as InsightShortId)+ const source = insightFixture.query.source+ const cachedInsight = { ...insightFixture, short_id: dashboardItemId }++ 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>+ <FunnelStepsBarChart />+ </Stage>+ </BindLogic>+ </BindLogic>+ )+}++/* eslint-disable @typescript-eslint/no-var-requires */+const funnelStepsInsight = (): any =>+ require('../../../../mocks/fixtures/api/projects/team_id/insights/funnelTopToBottom.json')+const funnelStepsBreakdownInsight = (): any =>+ require('../../../../mocks/fixtures/api/projects/team_id/insights/funnelTopToBottomBreakdown.json')++export const Default: Story = {+ render: () => <StoryRender insightFixture={funnelStepsInsight()} />,+}++export const Breakdown: Story = {+ render: () => <StoryRender insightFixture={funnelStepsBreakdownInsight()} />,+}+/* eslint-enable @typescript-eslint/no-var-requires */diff --git a/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarChart.tsx b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarChart.tsxnew file mode 100644index 000000000000..fc26e0e5f9e3--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarChart.tsx@@ -0,0 +1,138 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'+import { useCallback, useMemo, type ErrorInfo } from 'react'++import { buildTheme } from 'lib/charts/utils/theme'+import { BarChart } from 'lib/hog-charts'+import type { BarChartConfig, PointClickData, TooltipContext } from 'lib/hog-charts'+import { insightLogic } from 'scenes/insights/insightLogic'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { groupsModel } from '~/models/groupsModel'+import { ChartParams, type FunnelStepWithConversionMetrics } from '~/types'++import { StepLegend } from '../../FunnelBarVertical/StepLegend'+import { funnelDataLogic } from '../../funnelDataLogic'+import { funnelPersonsModalLogic } from '../../funnelPersonsModalLogic'+import { FunnelStepsBarTooltip } from './FunnelStepsBarTooltip'+import { buildFunnelStepsBarData, type FunnelStepsBarSeriesMeta } from './funnelStepsBarTransforms'++// Both axes are hidden: steps are identified by the legend row below, and the per-step+// conversion rate is shown there too. This lets the bars span the full width so the+// legend columns line up with them without measuring the chart's plot area.+const CHART_CONFIG: BarChartConfig = {+ barLayout: 'grouped',+ showGrid: true,+ barCornerRadius: 6,+ barTrack: true,+ hideXAxis: true,+ hideYAxis: true,+ tooltip: { placement: 'top' },+}++// Floor per-step width — below this the legend text overlaps; scroll horizontally instead.+const MIN_STEP_WIDTH_PX = 210++const handleChartError = (error: Error, info: ErrorInfo): void => {+ posthog.captureException(error, {+ feature: 'funnels-steps-bar-chart',+ componentStack: info.componentStack ?? undefined,+ })+}++export function FunnelStepsBarChart({+ showPersonsModal: showPersonsModalProp = true,+ inCardView,+}: ChartParams): JSX.Element | null {+ const { isDarkModeOn } = useValues(themeLogic)+ // buildTheme() reads CSS vars; we re-memo on isDarkModeOn so the theme refreshes+ // when the user toggles dark mode even though the function takes no arguments.+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])+ const { insightProps } = useValues(insightLogic)+ const { visibleStepsWithConversionMetrics, getFunnelsColor, breakdownFilter, querySource } = useValues(+ funnelDataLogic(insightProps)+ )+ const { canOpenPersonModal } = useValues(funnelPersonsModalLogic(insightProps))+ const { openPersonsModalForSeries } = useActions(funnelPersonsModalLogic(insightProps))+ const { aggregationLabel } = useValues(groupsModel)++ const showPersonsModal = canOpenPersonModal && showPersonsModalProp+ const steps = visibleStepsWithConversionMetrics++ const { series, labels } = useMemo(+ () =>+ buildFunnelStepsBarData(steps, {+ getColor: getFunnelsColor,+ getLabel: (variant) => String(variant.breakdown_value ?? variant.name ?? ''),+ }),+ [steps, getFunnelsColor]+ )++ const groupTypeLabel = aggregationLabel(querySource?.aggregation_group_type_index).plural+ const showTime = steps.some((step) => step.average_conversion_time != null)++ const onPointClick = useCallback(+ (clickData: PointClickData<FunnelStepsBarSeriesMeta>): void => {+ const step = steps[clickData.dataIndex]+ if (!step) {+ return+ }+ const breakdownIndex = clickData.series.meta?.breakdownIndex ?? 0+ const variant: FunnelStepWithConversionMetrics = step.nested_breakdown?.[breakdownIndex] ?? step+ openPersonsModalForSeries({ step, series: variant, converted: true })+ },+ [steps, openPersonsModalForSeries]+ )++ const renderTooltip = useCallback(+ (ctx: TooltipContext<FunnelStepsBarSeriesMeta>): JSX.Element => (+ <FunnelStepsBarTooltip+ context={ctx}+ steps={steps}+ breakdownFilter={breakdownFilter}+ groupTypeLabel={groupTypeLabel}+ showPersonsModal={showPersonsModal}+ />+ ),+ [steps, breakdownFilter, groupTypeLabel, showPersonsModal]+ )++ if (steps.length === 0) {+ return null+ }++ return (+ <div className="flex w-full flex-1 flex-col overflow-x-auto" data-attr="funnel-steps-bar-chart">+ <div+ className="flex flex-1 flex-col"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ minWidth: steps.length * MIN_STEP_WIDTH_PX }}+ >+ <div className="flex min-h-[150px] flex-1">+ <BarChart<FunnelStepsBarSeriesMeta>+ series={series}+ labels={labels}+ theme={theme}+ config={CHART_CONFIG}+ tooltip={renderTooltip}+ onPointClick={showPersonsModal ? onPointClick : undefined}+ onError={handleChartError}+ />+ </div>+ <div className="flex">+ {steps.map((step, stepIndex) => (+ <div key={stepIndex} className="min-w-0 flex-1 overflow-hidden">+ <StepLegend+ step={step}+ stepIndex={stepIndex}+ showTime={showTime}+ showPersonsModal={showPersonsModal}+ inCardView={inCardView}+ />+ </div>+ ))}+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarTooltip.tsx b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarTooltip.tsxnew file mode 100644index 000000000000..f63959433526--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/FunnelStepsBarTooltip.tsx@@ -0,0 +1,44 @@+import type { TooltipContext } from 'lib/hog-charts'++import type { BreakdownFilter } from '~/queries/schema/schema-general'+import type { FunnelStepWithConversionMetrics } from '~/types'++import { FunnelTooltip } from '../../FunnelTooltip'+import type { FunnelStepsBarSeriesMeta } from './funnelStepsBarTransforms'++interface FunnelStepsBarTooltipProps {+ context: TooltipContext<FunnelStepsBarSeriesMeta>+ steps: FunnelStepWithConversionMetrics[]+ breakdownFilter: BreakdownFilter | null | undefined+ groupTypeLabel: string+ showPersonsModal: boolean+}++export function FunnelStepsBarTooltip({+ context,+ steps,+ breakdownFilter,+ groupTypeLabel,+ showPersonsModal,+}: FunnelStepsBarTooltipProps): JSX.Element | null {+ const stepIndex = context.dataIndex+ const step = steps[stepIndex]+ const entry = context.seriesData[0]+ if (!step || !entry) {+ return null+ }++ const breakdownIndex = entry.series.meta?.breakdownIndex ?? 0+ const series = step.nested_breakdown?.[breakdownIndex] ?? step++ return (+ <FunnelTooltip+ embedded+ showPersonsModal={showPersonsModal}+ stepIndex={stepIndex}+ series={series}+ groupTypeLabel={groupTypeLabel}+ breakdownFilter={breakdownFilter}+ />+ )+}diff --git a/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/funnelStepsBarTransforms.test.ts b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/funnelStepsBarTransforms.test.tsnew file mode 100644index 000000000000..0d9c4e7ed51d--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/funnelStepsBarTransforms.test.ts@@ -0,0 +1,114 @@+import { EntityTypes, type FunnelStepWithConversionMetrics } from '~/types'++import { buildFunnelStepsBarData, FUNNEL_STEPS_SERIES_KEY_PREFIX } from './funnelStepsBarTransforms'++type StepOverrides = Partial<FunnelStepWithConversionMetrics> & { fromBasisStep: number }++function makeStep({ fromBasisStep, ...overrides }: StepOverrides): FunnelStepWithConversionMetrics {+ return {+ action_id: 'action',+ average_conversion_time: null,+ median_conversion_time: null,+ count: 0,+ name: 'Step',+ order: 0,+ type: EntityTypes.EVENTS,+ converted_people_url: '',+ dropped_people_url: null,+ droppedOffFromPrevious: 0,+ conversionRates: { fromPrevious: fromBasisStep, total: fromBasisStep, fromBasisStep },+ ...overrides,+ }+}++const noBreakdownSteps: FunnelStepWithConversionMetrics[] = [+ makeStep({ fromBasisStep: 1, name: 'Viewed' }),+ makeStep({ fromBasisStep: 0.5, name: 'Signed up' }),+ makeStep({ fromBasisStep: 0.2, name: 'Purchased' }),+]++const breakdownSteps: FunnelStepWithConversionMetrics[] = [+ makeStep({+ fromBasisStep: 1,+ nested_breakdown: [+ makeStep({ fromBasisStep: 1, breakdown_value: 'mobile' }),+ makeStep({ fromBasisStep: 1, breakdown_value: 'desktop' }),+ ],+ }),+ makeStep({+ fromBasisStep: 0.4,+ nested_breakdown: [+ makeStep({ fromBasisStep: 0.6, breakdown_value: 'mobile' }),+ makeStep({ fromBasisStep: 0.3, breakdown_value: 'desktop' }),+ ],+ }),+]++const options = {+ getColor: () => '#1d4aff',+ getLabel: (variant: FunnelStepWithConversionMetrics) => String(variant.breakdown_value ?? variant.name),+}++describe('buildFunnelStepsBarData', () => {+ it('builds a single series valued by conversion rate when there is no breakdown', () => {+ const { series, labels } = buildFunnelStepsBarData(noBreakdownSteps, options)++ expect(series).toHaveLength(1)+ expect(series[0].key).toBe(`${FUNNEL_STEPS_SERIES_KEY_PREFIX}0`)+ expect(series[0].data).toEqual([100, 50, 20])+ expect(labels).toEqual(['1', '2', '3'])+ })++ it('builds one series per breakdown variant', () => {+ const { series } = buildFunnelStepsBarData(breakdownSteps, options)++ expect(series).toHaveLength(2)+ expect(series[0].data).toEqual([100, 60])+ expect(series[1].data).toEqual([100, 30])+ })++ it('tags each series with its breakdown index for click/tooltip mapping', () => {+ const { series } = buildFunnelStepsBarData(breakdownSteps, options)++ expect(series.map((s) => s.meta?.breakdownIndex)).toEqual([0, 1])+ })++ it('labels and colors each series from its representative variant', () => {+ const getColor = jest.fn(() => '#1d4aff')+ const { series } = buildFunnelStepsBarData(breakdownSteps, { ...options, getColor })++ expect(series.map((s) => s.label)).toEqual(['mobile', 'desktop'])+ expect(getColor).toHaveBeenCalledWith(breakdownSteps[0].nested_breakdown?.[0])+ })++ it('zeroes the bar when a step is missing a breakdown variant (not inflating to the parent rate)', () => {+ const skewedSteps: FunnelStepWithConversionMetrics[] = [+ makeStep({+ fromBasisStep: 1,+ nested_breakdown: [+ makeStep({ fromBasisStep: 1, breakdown_value: 'mobile' }),+ makeStep({ fromBasisStep: 1, breakdown_value: 'desktop' }),+ ],+ }),+ makeStep({+ fromBasisStep: 0.5,+ // Only one variant in step 2 — the missing 'desktop' variant must not inherit+ // the parent's 50% aggregate, or the chart misrepresents reality.+ nested_breakdown: [makeStep({ fromBasisStep: 0.7, breakdown_value: 'mobile' })],+ }),+ ]++ const { series } = buildFunnelStepsBarData(skewedSteps, options)++ expect(series).toHaveLength(2)+ expect(series[0].data).toEqual([100, 70])+ expect(series[1].data).toEqual([100, 0])+ })++ it('handles an empty step list', () => {+ const { series, labels } = buildFunnelStepsBarData([], options)++ expect(series).toEqual([])+ expect(labels).toEqual([])+ })+})diff --git a/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/funnelStepsBarTransforms.ts b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/funnelStepsBarTransforms.tsnew file mode 100644index 000000000000..c54384b86689--- /dev/null+++ b/frontend/src/scenes/funnels/viz/funnel-steps-bar-chart/funnelStepsBarTransforms.ts@@ -0,0 +1,71 @@+import type { Series } from 'lib/hog-charts'++import type { FunnelStepWithConversionMetrics } from '~/types'++export const FUNNEL_STEPS_SERIES_KEY_PREFIX = 'funnel-step-series-'++/** `conversionRates.fromBasisStep` is a 0–1 ratio; hog-charts bars are valued in percent. */+const RATE_TO_PERCENT = 100++/** Identifies which breakdown variant a hog-charts series maps back to, so click and+ * tooltip handlers can recover the original `FunnelStepWithConversionMetrics`. */+export interface FunnelStepsBarSeriesMeta {+ breakdownIndex: number+}++interface BuildOptions {+ getColor: (series: FunnelStepWithConversionMetrics) => string+ getLabel: (series: FunnelStepWithConversionMetrics) => string+}++export interface FunnelStepsBarData {+ /** One series per breakdown variant; `data[stepIndex]` is a percent (0–100). */+ series: Series<FunnelStepsBarSeriesMeta>[]+ labels: string[]+}++function variantAtStep(+ step: FunnelStepWithConversionMetrics,+ breakdownIndex: number,+ isBreakdown: boolean+): FunnelStepWithConversionMetrics {+ if (!isBreakdown) {+ return step+ }+ const variant = step.nested_breakdown?.[breakdownIndex]+ if (variant) {+ return variant+ }+ // The breakdown variant is absent for this step — treat as no conversion rather than+ // inflating to the parent step's aggregate rate.+ return { ...step, conversionRates: { ...step.conversionRates, fromBasisStep: 0 } }+}++/** Maps the funnel steps onto grouped hog-charts bar series — one series per breakdown+ * variant, one bar per step, valued by conversion rate from the basis step. */+export function buildFunnelStepsBarData(+ steps: FunnelStepWithConversionMetrics[],+ options: BuildOptions+): FunnelStepsBarData {+ if (steps.length === 0) {+ return { series: [], labels: [] }+ }++ const isBreakdown = steps[0].nested_breakdown != null+ const breakdownCount = isBreakdown ? steps[0].nested_breakdown!.length : 1+ const series: Series<FunnelStepsBarSeriesMeta>[] = []++ for (let breakdownIndex = 0; breakdownIndex < breakdownCount; breakdownIndex++) {+ const variants = steps.map((step) => variantAtStep(step, breakdownIndex, isBreakdown))+ const representative = variants[0]+ series.push({+ key: `${FUNNEL_STEPS_SERIES_KEY_PREFIX}${breakdownIndex}`,+ label: representative ? options.getLabel(representative) : '',+ data: variants.map((variant) => variant.conversionRates.fromBasisStep * RATE_TO_PERCENT),+ color: representative ? options.getColor(representative) : undefined,+ meta: { breakdownIndex },+ })+ }++ return { series, labels: steps.map((_, stepIndex) => `${stepIndex + 1}`) }+}