: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): extract neutral funnel bar primitives into shared module (#62410)
Sam Pennington05caea99cf31
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/SingleStepBar.tsx b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/SingleStepBar.tsxindex 043065d00d76..624524783b16 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/SingleStepBar.tsx+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/SingleStepBar.tsx@@ -12,7 +12,7 @@ import {FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN,type FunnelBarHorizontalSegmentMeta,type FunnelBarHorizontalStepData,-} from './funnelBarHorizontalTransforms'+} from '../shared/funnelBarHorizontalShared'const BAR_CORNER_RADIUS = 4diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.ts b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.tsindex 3cc97534217a..f9c9a46cf9db 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.ts+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.ts@@ -5,27 +5,23 @@ import { getReferenceStep, getStepBreakdownSeries } from 'scenes/funnels/funnelUimport type { BreakdownFilter } from '~/queries/schema/schema-general'import { FunnelStepReference, type FunnelStepWithConversionMetrics } from '~/types'-export const FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX = 'funnel-bar-horizontal-segment-'-export const FUNNEL_BAR_HORIZONTAL_FILLER_KEY = 'funnel-bar-horizontal-filler'--/** Every step's bar is its own single-band chart, so they only line up if they share this- * value domain (passed to BarChart as `bars.valueDomain`). Segment data are basis-step- * percentages, so the axis is `0–100`. */-export const FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN: [number, number] = [0, 100]--const RATE_TO_PERCENT = 100--export interface FunnelBarHorizontalSegmentMeta {- isDropOff: boolean- breakdownIndex: number | null-}--/** Series for one step's single-band bar. Each series' `data` has exactly one value. */-export interface FunnelBarHorizontalStepData {- /** Band label — a single per-chart slot, so just the step index as a string. */- label: string- series: Series<FunnelBarHorizontalSegmentMeta>[]-}+import {+ buildFunnelBarHorizontalFiller,+ FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX,+ RATE_TO_PERCENT,+ type FunnelBarHorizontalSegmentMeta,+ type FunnelBarHorizontalStepData,+} from '../shared/funnelBarHorizontalShared'++// Re-exported so existing importers (the chart component, tests) keep a single entry point even+// though the neutral primitives now live in the shared module for the MCP bundle to reuse.+export {+ FUNNEL_BAR_HORIZONTAL_FILLER_KEY,+ FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX,+ FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN,+ type FunnelBarHorizontalSegmentMeta,+ type FunnelBarHorizontalStepData,+} from '../shared/funnelBarHorizontalShared'interface BuildOptions {stepReference: FunnelStepReference@@ -86,7 +82,7 @@ function buildBreakdownSegments(})}- return [...segments, buildFiller(segments, options.fillerColor)]+ return [...segments, buildFunnelBarHorizontalFiller(segments, options.fillerColor)]}function buildSingleSegment(@@ -104,20 +100,5 @@ function buildSingleSegment(meta: { isDropOff: false, breakdownIndex: isSingleBreakdownCollapse ? 0 : null },}- return [segment, buildFiller([segment], options.fillerColor)]-}--function buildFiller(- segments: Series<FunnelBarHorizontalSegmentMeta>[],- color: string-): Series<FunnelBarHorizontalSegmentMeta> {- const covered = segments.reduce((sum, s) => sum + (s.data[0] ?? 0), 0)- return {- key: FUNNEL_BAR_HORIZONTAL_FILLER_KEY,- label: 'Drop-off',- data: [Math.max(0, RATE_TO_PERCENT - covered)],- color,- visibility: { tooltip: false },- meta: { isDropOff: true, breakdownIndex: null },- }+ return [segment, buildFunnelBarHorizontalFiller([segment], options.fillerColor)]}diff --git a/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.test.ts b/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.test.tsnew file mode 100644index 000000000000..e120e351d626--- /dev/null+++ b/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.test.ts@@ -0,0 +1,118 @@+import {+ buildFunnelBarHorizontalFiller,+ buildFunnelBars,+ buildFunnelConversionStep,+ FUNNEL_BAR_HORIZONTAL_FILLER_KEY,+ FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX,+ funnelConversionRate,+} from './funnelBarHorizontalShared'++const segment = (value: number): Parameters<typeof buildFunnelBarHorizontalFiller>[0][number] => ({+ key: `${FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX}0`,+ label: 'a',+ data: [value],+ meta: { isDropOff: false, breakdownIndex: null },+})++describe('funnelBarHorizontalShared', () => {+ describe('funnelConversionRate', () => {+ it.each([+ { count: 50, basisCount: 100, expected: 0.5, description: 'partial conversion' },+ { count: 100, basisCount: 100, expected: 1, description: 'full conversion' },+ { count: 0, basisCount: 100, expected: 0, description: 'zero count' },+ { count: 5, basisCount: 0, expected: 0, description: 'zero basis guards divide-by-zero' },+ ])('$description', ({ count, basisCount, expected }) => {+ expect(funnelConversionRate(count, basisCount)).toBe(expected)+ })+ })++ describe('buildFunnelBarHorizontalFiller', () => {+ it.each([+ { segmentValues: [30], expectedFiller: 70, description: 'fills the remaining percentage up to 100' },+ { segmentValues: [30, 50], expectedFiller: 20, description: 'sums multiple segments before filling' },+ { segmentValues: [120], expectedFiller: 0, description: 'clamps to 0 when segments exceed 100' },+ ])('$description', ({ segmentValues, expectedFiller }) => {+ const filler = buildFunnelBarHorizontalFiller(segmentValues.map(segment), '#ccc')+ expect(filler.key).toBe(FUNNEL_BAR_HORIZONTAL_FILLER_KEY)+ expect(filler.data).toEqual([expectedFiller])+ expect(filler.meta).toEqual({ isDropOff: true, breakdownIndex: null })+ expect(filler.visibility).toEqual({ tooltip: false })+ })+ })++ describe('buildFunnelConversionStep', () => {+ it('builds a converted segment carrying the label, color, and meta', () => {+ const stepData = buildFunnelConversionStep({+ stepIndex: 1,+ label: 'Signed up',+ fractionOfBasis: 0.42,+ color: '#1d4aff',+ fillerColor: '#eee',+ })+ expect(stepData.label).toBe('1')+ expect(stepData.series).toHaveLength(2)++ const [segment, filler] = stepData.series+ expect(segment.label).toBe('Signed up')+ expect(segment.color).toBe('#1d4aff')+ expect(segment.meta).toEqual({ isDropOff: false, breakdownIndex: null })+ expect(filler.key).toBe(FUNNEL_BAR_HORIZONTAL_FILLER_KEY)+ })++ it.each([+ { fractionOfBasis: 0, expectedSegment: 0, expectedFiller: 100, description: 'fully dropped step' },+ { fractionOfBasis: 0.42, expectedSegment: 42, expectedFiller: 58, description: 'partial conversion' },+ { fractionOfBasis: 1, expectedSegment: 100, expectedFiller: 0, description: 'full basis step' },+ ])('$description: segment + filler sum to 100', ({ fractionOfBasis, expectedSegment, expectedFiller }) => {+ const stepData = buildFunnelConversionStep({+ stepIndex: 0,+ label: 'Pageview',+ fractionOfBasis,+ color: '#1d4aff',+ fillerColor: '#eee',+ })+ expect(stepData.series[0].data).toEqual([expectedSegment])+ expect(stepData.series[1].data).toEqual([expectedFiller])+ })+ })++ describe('buildFunnelBars', () => {+ const COLORS = { color: '#1d4aff', fillerColor: '#eee' }+ const steps = [+ { name: 'Pageview', count: 1000 },+ { name: 'Signed up', count: 400 },+ { name: 'Activated', count: 100 },+ ]++ it('computes per-step conversion vs the first step and vs the previous step', () => {+ const { rows } = buildFunnelBars(steps, COLORS)++ expect(rows.map((r) => r.fractionOfBasis)).toEqual([1, 0.4, 0.1])+ // step 0 has no previous step (value unused by the view); steps 1/2 are vs the prior count.+ expect(rows.map((r) => r.fromPrevious)).toEqual([0, 0.4, 0.25])+ expect(rows.map((r) => r.name)).toEqual(['Pageview', 'Signed up', 'Activated'])+ expect(rows[0].stepData.series).toHaveLength(2)+ })++ it('reports overall conversion as last/first', () => {+ expect(buildFunnelBars(steps, COLORS).overall).toEqual({ rate: 0.1, firstCount: 1000, lastCount: 100 })+ })++ it('guards divide-by-zero when the first step has no entries', () => {+ const { rows, overall } = buildFunnelBars(+ [+ { name: 'A', count: 0 },+ { name: 'B', count: 0 },+ ],+ COLORS+ )++ expect(rows.map((r) => r.fractionOfBasis)).toEqual([0, 0])+ expect(overall.rate).toBe(0)+ })++ it('returns no rows for an empty funnel', () => {+ expect(buildFunnelBars([], COLORS).rows).toEqual([])+ })+ })+})diff --git a/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.ts b/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.tsnew file mode 100644index 000000000000..0d04a4ffe3af--- /dev/null+++ b/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.ts@@ -0,0 +1,119 @@+import type { Series } from '@posthog/quill-charts'++// Dependency-neutral primitives for the horizontal funnel bars, shared by the web container+// (funnelBarHorizontalTransforms.ts) and the MCP UI app. Deliberately free of `~/`, `lib/`, and+// `scenes/` imports so they compile in the MCP Vite bundle, which only resolves `products/*` and+// `@posthog/*`.++export const FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX = 'funnel-bar-horizontal-segment-'+export const FUNNEL_BAR_HORIZONTAL_FILLER_KEY = 'funnel-bar-horizontal-filler'++/** Every step's bar is its own single-band chart, so they only line up if they share this+ * value domain (passed to BarChart as `bars.valueDomain`). Segment data are basis-step+ * percentages, so the axis is `0–100`. */+export const FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN: [number, number] = [0, 100]++export const RATE_TO_PERCENT = 100++/** Conversion of a step's count against a basis count, as a 0..1 rate. A zero or absent basis+ * yields 0 (rather than dividing by zero) so the bar collapses instead of rendering NaN. */+export function funnelConversionRate(count: number, basisCount: number): number {+ return basisCount > 0 ? count / basisCount : 0+}++export interface FunnelBarHorizontalSegmentMeta {+ isDropOff: boolean+ breakdownIndex: number | null+}++/** Series for one step's single-band bar. Each series' `data` has exactly one value. */+export interface FunnelBarHorizontalStepData {+ /** Band label — a single per-chart slot, so just the step index as a string. */+ label: string+ series: Series<FunnelBarHorizontalSegmentMeta>[]+}++/** Trailing grey band that fills the bar up to 100% so every step reads against the same axis. */+export function buildFunnelBarHorizontalFiller(+ segments: Series<FunnelBarHorizontalSegmentMeta>[],+ color: string+): Series<FunnelBarHorizontalSegmentMeta> {+ const covered = segments.reduce((sum, s) => sum + (s.data[0] ?? 0), 0)+ return {+ key: FUNNEL_BAR_HORIZONTAL_FILLER_KEY,+ label: 'Drop-off',+ data: [Math.max(0, RATE_TO_PERCENT - covered)],+ color,+ visibility: { tooltip: false },+ meta: { isDropOff: true, breakdownIndex: null },+ }+}++/** Everything the MCP funnel view needs to render one step — all conversion math precomputed so the+ * view stays presentational. */+export interface FunnelBarRow {+ stepIndex: number+ name: string+ count: number+ /** Conversion relative to the first step (0..1) — drives bar length and the per-step label. */+ fractionOfBasis: number+ /** Conversion relative to the previous step (0..1); 0 for the first step (not displayed). */+ fromPrevious: number+ stepData: FunnelBarHorizontalStepData+}++export interface FunnelBarsModel {+ rows: FunnelBarRow[]+ overall: { rate: number; firstCount: number; lastCount: number }+}++/** Precomputes the per-step conversion rows + overall conversion for the (non-breakdown) MCP funnel,+ * so the visualizer is pure rendering and the rate/divide-by-zero math is unit-tested here. */+export function buildFunnelBars(+ steps: { name: string; count: number }[],+ opts: { color: string; fillerColor: string }+): FunnelBarsModel {+ const firstCount = steps[0]?.count ?? 0+ const lastCount = steps[steps.length - 1]?.count ?? 0+ const rows = steps.map((step, stepIndex) => {+ const fractionOfBasis = funnelConversionRate(step.count, firstCount)+ return {+ stepIndex,+ name: step.name,+ count: step.count,+ fractionOfBasis,+ fromPrevious: funnelConversionRate(step.count, steps[stepIndex - 1]?.count ?? 0),+ stepData: buildFunnelConversionStep({+ stepIndex,+ label: step.name,+ fractionOfBasis,+ color: opts.color,+ fillerColor: opts.fillerColor,+ }),+ }+ })+ return { rows, overall: { rate: funnelConversionRate(lastCount, firstCount), firstCount, lastCount } }+}++/** Build a single-segment step bar (no breakdown) plus its drop-off filler. `fractionOfBasis` is a+ * 0..1 conversion rate relative to the basis step. Shared by the web single-segment path and the+ * simpler MCP funnel, which has no breakdown variants. */+export function buildFunnelConversionStep(opts: {+ stepIndex: number+ label: string+ fractionOfBasis: number+ color: string+ fillerColor: string+}): FunnelBarHorizontalStepData {+ const segment: Series<FunnelBarHorizontalSegmentMeta> = {+ key: `${FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX}0`,+ label: opts.label,+ data: [opts.fractionOfBasis * RATE_TO_PERCENT],+ color: opts.color,+ meta: { isDropOff: false, breakdownIndex: null },+ }+ return {+ label: String(opts.stepIndex),+ series: [segment, buildFunnelBarHorizontalFiller([segment], opts.fillerColor)],+ }+}