Skip to content

: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.

fix(funnels): flow horizontal funnel rows to fit step text (#60843)

Sam Pennington8cb9c242e1ab
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7838fb27a731..826cd62aa277 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1997,13 +1997,17 @@ snapshots:
home-recordingrow--default--light:
hash: v1.k794b7964.329d31ae48aa77fb3985b7b04d9dd7442300f121a5216295ae62403ee2822c73.4UlskD-jaI7b0oEHZVJSnt34xEIL6IBubmZlb3edfvE
insights-funnelbarhorizontalchart--breakdown--dark:
- hash: v1.k794b7964.2399c3aaefe28872b98a766828373dfa2a2af07e570e51c3916a5e6441e56c99.Jwv9SlihbIqbaNbNtPtMNGdYFZpcBQffhH939az6JlU
+ hash: v1.k794b7964.dbd3815a2ce70313c4c756db00ac6833f615b2fd792346d1bf4eab96c5172b24.egLwOZA7evFp0IrboQABx_rpY3KiRH_TGWQOis1NPc8
insights-funnelbarhorizontalchart--breakdown--light:
- hash: v1.k794b7964.eb99a41493e9ab9534721b2c768aba6804be2a11c8d0d0b6bba635a95f60bbe1.Pvd4_u21_pG3USKvQqwfTEu66VQltyBQ6rXeLvbR5vE
+ hash: v1.k794b7964.c2b5e38ee6ab82db0be7edf94e2574feae2acb2506e8e140291afb05f10c8550.-Ef2fKN3l1IwbDeqKRTqwrKXwX5QaTwYR4TLNRVT_vk
insights-funnelbarhorizontalchart--default--dark:
- hash: v1.k794b7964.43302c9174c7cd7a3ea66450b3c50d69c219a1ddb770a6211f035460e4af6370.zHS6Xm-tU3FD8tmRHll7kATc3ei-klj3jYBVFVcEz1o
+ hash: v1.k794b7964.05d512588c6069b2105c4684b44857fd48cbc8a6f19cd0e757a9a805dc014a6d.UQhkOqMBpA2JbXYSH14xWkhxYp2jQ_mece8zogMNIHE
insights-funnelbarhorizontalchart--default--light:
- hash: v1.k794b7964.766e219b80c8d0bd5ef7d3e70c55e3ccac4149e5bbf0df28700ec80823b83752.SbbGf02Ugrx7Nm6nR8gxDe_HZrhFoPNSNzVGhzU-kYU
+ hash: v1.k794b7964.77e3cbda393cc66a977556211a04080b22b97c3f46f255a7baa65e4772e7a37b.JrqpYmAk2loyRWkOQIGyoHXM8tPQZkq09dsXX9UTaBc
+ insights-funnelbarhorizontalchart--default-narrow--dark:
+ hash: v1.k794b7964.ed8dcfd0398a52a184600b34416183c0e4f7db42860db1fed3e3631b31819a9c.VemuVUNUEgJsYOIWX8UgRIlBSIs9GeBXCSJsTV8nzAg
+ insights-funnelbarhorizontalchart--default-narrow--light:
+ hash: v1.k794b7964.b6543758ca04b2e970af5d54a370ba18ced44e9ae8fc75814f19392942db7abc.y9qjx5SS8j1iMTyUqdHLGqjEZuGfzS23ao2GcioBRUc
insights-funnelcorrelationtable--default--dark:
hash: v1.k794b7964.85a7028e6729988dedf767a52640b16c94aa48baf0ab9c89b1085c38d4e8cc8e.wDERvaZQvyEVwZsoj2q7nTwZSDswGOq-6dnRNcvuRpw
insights-funnelcorrelationtable--default--light:
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
index 913e98575ae2..3033457486ce 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -136,6 +136,7 @@ function BarChartInner<Meta = unknown>({
maxBandRange,
bandPadding,
minBandSize,
+ valueDomain,
} = config?.bars ?? {}
const isHorizontal = axisOrientation === 'horizontal'
@@ -221,6 +222,7 @@ function BarChartInner<Meta = unknown>({
stackedSeries,
maxBandRange,
bandPadding,
+ valueDomain,
})
const tickAxisLength = isHorizontal ? dimensions.plotWidth : dimensions.plotHeight
@@ -270,7 +272,17 @@ function BarChartInner<Meta = unknown>({
_private: barChartPrivate,
}
},
- [yScaleType, barLayout, axisOrientation, stackedData, isHorizontal, divergingStack, maxBandRange, bandPadding]
+ [
+ yScaleType,
+ barLayout,
+ axisOrientation,
+ stackedData,
+ isHorizontal,
+ divergingStack,
+ maxBandRange,
+ bandPadding,
+ valueDomain,
+ ]
)
const drawStatic = useCallback(
diff --git a/frontend/src/lib/hog-charts/core/scales.ts b/frontend/src/lib/hog-charts/core/scales.ts
index 2d3743d799b9..1e3fae4dea6c 100644
--- a/frontend/src/lib/hog-charts/core/scales.ts
+++ b/frontend/src/lib/hog-charts/core/scales.ts
@@ -324,6 +324,8 @@ export function createBarScales(
stackedSeries?: Series[]
/** Cap on the band-axis range in px — clusters bars at the start of the plot when set. */
maxBandRange?: number
+ /** Fixed value-axis domain — bypasses data-derived range + `nice()`. */
+ valueDomain?: [number, number]
} = {}
): BarScaleSet {
const {
@@ -334,6 +336,7 @@ export function createBarScales(
groupPadding = 0.1,
stackedSeries,
maxBandRange,
+ valueDomain,
} = options
const isHorizontal = axisOrientation === 'horizontal'
@@ -361,7 +364,7 @@ export function createBarScales(
return {
band,
- value: buildBarValueScale(series, valueRange, tickCount, barLayout, scaleType, stackedSeries),
+ value: buildBarValueScale(series, valueRange, tickCount, barLayout, scaleType, stackedSeries, valueDomain),
group,
}
}
@@ -372,8 +375,12 @@ function buildBarValueScale(
tickCount: number,
barLayout: 'stacked' | 'grouped' | 'percent',
scaleType: 'linear' | 'log',
- stackedSeries: Series[] | undefined
+ stackedSeries: Series[] | undefined,
+ valueDomain: [number, number] | undefined
): D3YScale {
+ if (valueDomain) {
+ return d3.scaleLinear().domain(valueDomain).range(valueRange)
+ }
if (barLayout === 'percent') {
return d3.scaleLinear().domain([0, 1]).nice(tickCount).range(valueRange)
}
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index e1d44557e0ec..f2f7063056e9 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -232,6 +232,9 @@ export interface BarsConfig {
* an unreadable strip, the chart expands its container height so each row has at least this
* much vertical space (label height + breathing room). Defaults to `24`. Pass `0` to opt out. */
minBandSize?: number
+ /** Fix the value-axis domain (no data-derived range, no `d3.nice()`) so independent charts
+ * sharing a logical scale stay comparable. Takes precedence over `barLayout: 'percent'`. */
+ valueDomain?: [number, number]
}
export interface BarChartConfig extends ChartConfig {
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.stories.tsx b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.stories.tsx
index 37839f0ff2ed..e75365683d0a 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.stories.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.stories.tsx
@@ -29,14 +29,12 @@ 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: 480, width: 720, display: 'flex', flexDirection: 'column' }}>{children}</div>
- )
+function Stage({ children, width }: { children: React.ReactNode; width: number }): JSX.Element {
+ // eslint-disable-next-line react/forbid-dom-props
+ return <div style={{ width }}>{children}</div>
}
-function StoryRender({ insightFixture }: { insightFixture: any }): JSX.Element {
+function StoryRender({ insightFixture, width }: { insightFixture: any; width: number }): JSX.Element {
const [dashboardItemId] = useState(() => `FunnelBarHorizontalChartStory.${uniqueNode++}` as InsightShortId)
const source = insightFixture.query.source
const cachedInsight = { ...insightFixture, short_id: dashboardItemId }
@@ -52,7 +50,7 @@ function StoryRender({ insightFixture }: { insightFixture: any }): JSX.Element {
return (
<BindLogic logic={insightLogic} props={insightProps}>
<BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>
- <Stage>
+ <Stage width={width}>
<FunnelBarHorizontalChart />
</Stage>
</BindLogic>
@@ -61,9 +59,14 @@ function StoryRender({ insightFixture }: { insightFixture: any }): JSX.Element {
}
export const Default: Story = {
- render: () => <StoryRender insightFixture={funnelTopToBottomFixture} />,
+ render: () => <StoryRender insightFixture={funnelTopToBottomFixture} width={720} />,
}
export const Breakdown: Story = {
- render: () => <StoryRender insightFixture={funnelTopToBottomBreakdownFixture} />,
+ render: () => <StoryRender insightFixture={funnelTopToBottomBreakdownFixture} width={720} />,
+}
+
+// A narrow width forces footers to wrap — each row should grow to fit its text, not overlap the next.
+export const DefaultNarrow: Story = {
+ render: () => <StoryRender insightFixture={funnelTopToBottomFixture} width={320} />,
}
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.tsx
index 7c2424f08306..1b26f3ad037e 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalChart.tsx
@@ -1,24 +1,23 @@
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
-import { useMemo, type ErrorInfo } from 'react'
+import { type ErrorInfo, useMemo } from 'react'
import { buildTheme } from 'lib/charts/utils/theme'
-import { BarChart, type BarChartConfig, type PointClickData, type TooltipContext } from 'lib/hog-charts'
+import { type ChartTheme, type TooltipContext } from 'lib/hog-charts'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { funnelPersonsModalLogic } from 'scenes/funnels/funnelPersonsModalLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { groupsModel } from '~/models/groupsModel'
-import { type ChartParams, FunnelStepReference } from '~/types'
+import { type ChartParams, FunnelStepReference, StepOrderValue } from '~/types'
import { FunnelBarHorizontalTooltip } from './FunnelBarHorizontalTooltip'
import { buildFunnelBarHorizontalData, type FunnelBarHorizontalSegmentMeta } from './funnelBarHorizontalTransforms'
-import { StepDecorations } from './StepDecorations'
-
-const ROW_HEIGHT_PX = 76
-const BAR_PADDING = 0.6
-const GLYPH_COLUMN_WIDTH_PX = 24
+import { GlyphColumn } from './GlyphColumn'
+import { SingleStepBar } from './SingleStepBar'
+import { StepFooter } from './StepFooter'
+import { StepHeader } from './StepHeader'
function getFillerColor(): string {
if (typeof document === 'undefined') {
@@ -39,7 +38,7 @@ export function FunnelBarHorizontalChart({
inCardView,
}: ChartParams): JSX.Element | null {
const { isDarkModeOn } = useValues(themeLogic)
- const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+ const theme = useMemo<ChartTheme>(() => buildTheme(), [isDarkModeOn])
const fillerColor = useMemo(() => getFillerColor(), [isDarkModeOn])
const { insightProps } = useValues(insightLogic)
@@ -60,10 +59,11 @@ export function FunnelBarHorizontalChart({
const stepReference = funnelsFilter?.funnelStepReference || FunnelStepReference.total
const showPersonsModal = canOpenPersonModal && showPersonsModalProp
const interactive = showPersonsModal && !inCardView
+ const isUnordered = funnelsFilter?.funnelOrderType === StepOrderValue.UNORDERED
const hasOptionalSteps = steps.some((_, stepIndex) => isStepOptional(stepIndex + 1))
const groupTypeLabel = aggregationLabel(querySource?.aggregation_group_type_index).plural
- const { series, labels } = useMemo(
+ const stepsData = useMemo(
() =>
buildFunnelBarHorizontalData(steps, {
stepReference,
@@ -75,80 +75,83 @@ export function FunnelBarHorizontalChart({
[steps, stepReference, breakdownFilter, getFunnelsColor, fillerColor]
)
- const chartConfig = useMemo<BarChartConfig>(
- () => ({
- barLayout: 'stacked',
- bars: { cornerRadius: 4, bandPadding: BAR_PADDING },
- axisOrientation: 'horizontal',
- hideXAxis: true,
- hideYAxis: true,
- showGrid: false,
- animateHover: true,
- margins: { top: 0, right: 0, bottom: 0, left: GLYPH_COLUMN_WIDTH_PX },
- tooltip: { placement: 'top' },
- }),
- []
- )
-
- const onPointClick = (clickData: PointClickData<FunnelBarHorizontalSegmentMeta>): void => {
- const meta = clickData.series.meta
- const step = steps[clickData.dataIndex]
- if (!step || !meta) {
- return
- }
- if (meta.isDropOff) {
- openPersonsModalForStep({ step, converted: false })
- return
- }
- if (meta.breakdownIndex != null && step.nested_breakdown?.[meta.breakdownIndex]) {
- openPersonsModalForSeries({
- step,
- series: step.nested_breakdown[meta.breakdownIndex],
- converted: true,
- })
- return
- }
- openPersonsModalForStep({ step, converted: true })
- }
-
- const renderTooltip = (ctx: TooltipContext<FunnelBarHorizontalSegmentMeta>): JSX.Element | null => (
- <FunnelBarHorizontalTooltip
- context={ctx}
- steps={steps}
- breakdownFilter={breakdownFilter}
- groupTypeLabel={groupTypeLabel}
- showPersonsModal={showPersonsModal}
- />
- )
-
if (steps.length === 0) {
return null
}
return (
<div data-attr="funnel-bar-horizontal" className="w-full p-4">
- {/* eslint-disable-next-line react/forbid-dom-props */}
- <div className="relative flex w-full" style={{ height: steps.length * ROW_HEIGHT_PX }}>
- <BarChart<FunnelBarHorizontalSegmentMeta>
- series={series}
- labels={labels}
- theme={theme}
- config={chartConfig}
- tooltip={renderTooltip}
- onPointClick={interactive ? onPointClick : undefined}
- onError={handleChartError}
- >
- <StepDecorations
- steps={steps}
- funnelsFilter={funnelsFilter}
- aggregationTargetLabel={aggregationTargetLabel}
- isStepOptional={isStepOptional}
- hasOptionalSteps={hasOptionalSteps}
- showPersonsModal={showPersonsModal}
- openPersonsModalForStep={openPersonsModalForStep}
- gapFraction={BAR_PADDING / 2}
- />
- </BarChart>
+ <div className="flex flex-col">
+ {steps.map((step, stepIndex) => {
+ const isOptional = isStepOptional(stepIndex + 1)
+
+ const onSegmentClick = (meta: FunnelBarHorizontalSegmentMeta): void => {
+ if (meta.isDropOff) {
+ openPersonsModalForStep({ step, converted: false })
+ return
+ }
+ if (meta.breakdownIndex != null && step.nested_breakdown?.[meta.breakdownIndex]) {
+ openPersonsModalForSeries({
+ step,
+ series: step.nested_breakdown[meta.breakdownIndex],
+ converted: true,
+ })
+ return
+ }
+ openPersonsModalForStep({ step, converted: true })
+ }
+
+ const renderTooltip = (ctx: TooltipContext<FunnelBarHorizontalSegmentMeta>): JSX.Element | null => (
+ <FunnelBarHorizontalTooltip
+ context={ctx}
+ step={step}
+ stepIndex={stepIndex}
+ breakdownFilter={breakdownFilter}
+ groupTypeLabel={groupTypeLabel}
+ showPersonsModal={showPersonsModal}
+ />
+ )
+
+ return (
+ <div className="flex" key={step.order}>
+ <GlyphColumn
+ index={stepIndex}
+ stepCount={steps.length}
+ glyphNumber={step.order + 1}
+ isUnordered={isUnordered}
+ isOptional={isOptional}
+ hasOptionalSteps={hasOptionalSteps}
+ />
+ <div className="flex-1 min-w-0 pb-3 pl-2">
+ <StepHeader
+ step={step}
+ stepIndex={stepIndex}
+ previousStep={steps[stepIndex - 1]}
+ isUnordered={isUnordered}
+ isOptional={isOptional}
+ />
+ <SingleStepBar
+ stepData={stepsData[stepIndex]}
+ theme={theme}
+ interactive={interactive}
+ onSegmentClick={onSegmentClick}
+ renderTooltip={renderTooltip}
+ onError={handleChartError}
+ />
+ <StepFooter
+ step={step}
+ stepIndex={stepIndex}
+ funnelsFilter={funnelsFilter}
+ aggregationTargetLabel={aggregationTargetLabel}
+ isOptional={isOptional}
+ showPersonsModal={showPersonsModal}
+ onOpenConverted={() => openPersonsModalForStep({ step, converted: true })}
+ onOpenDroppedOff={() => openPersonsModalForStep({ step, converted: false })}
+ />
+ </div>
+ </div>
+ )
+ })}
</div>
</div>
)
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalTooltip.tsx b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalTooltip.tsx
index 942d68f1b38f..eb749538f2e0 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalTooltip.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/FunnelBarHorizontalTooltip.tsx
@@ -8,7 +8,8 @@ import type { FunnelBarHorizontalSegmentMeta } from './funnelBarHorizontalTransf
interface FunnelBarHorizontalTooltipProps {
context: TooltipContext<FunnelBarHorizontalSegmentMeta>
- steps: FunnelStepWithConversionMetrics[]
+ step: FunnelStepWithConversionMetrics
+ stepIndex: number
breakdownFilter: BreakdownFilter | null | undefined
groupTypeLabel: string
showPersonsModal: boolean
@@ -16,15 +17,14 @@ interface FunnelBarHorizontalTooltipProps {
export function FunnelBarHorizontalTooltip({
context,
- steps,
+ step,
+ stepIndex,
breakdownFilter,
groupTypeLabel,
showPersonsModal,
}: FunnelBarHorizontalTooltipProps): JSX.Element | null {
- const stepIndex = context.dataIndex
- const step = steps[stepIndex]
const entry = context.seriesData[0]
- if (!step || !entry) {
+ if (!entry) {
return null
}
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/SingleStepBar.tsx b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/SingleStepBar.tsx
new file mode 100644
index 000000000000..64f5b74751da
--- /dev/null
+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/SingleStepBar.tsx
@@ -0,0 +1,73 @@
+import { type ErrorInfo } from 'react'
+
+import {
+ BarChart,
+ type BarChartConfig,
+ type ChartTheme,
+ type PointClickData,
+ type TooltipContext,
+} from 'lib/hog-charts'
+
+import {
+ FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN,
+ type FunnelBarHorizontalSegmentMeta,
+ type FunnelBarHorizontalStepData,
+} from './funnelBarHorizontalTransforms'
+
+interface SingleStepBarProps {
+ stepData: FunnelBarHorizontalStepData
+ theme: ChartTheme
+ interactive: boolean
+ onSegmentClick: (meta: FunnelBarHorizontalSegmentMeta) => void
+ renderTooltip: (ctx: TooltipContext<FunnelBarHorizontalSegmentMeta>) => JSX.Element | null
+ onError: (error: Error, info: ErrorInfo) => void
+}
+
+const CHART_CONFIG: BarChartConfig = {
+ barLayout: 'stacked',
+ axisOrientation: 'horizontal',
+ hideXAxis: true,
+ hideYAxis: true,
+ showGrid: false,
+ animateHover: true,
+ margins: { top: 0, right: 0, bottom: 0, left: 0 },
+ tooltip: { placement: 'top' },
+ bars: {
+ cornerRadius: 4,
+ bandPadding: 0,
+ minBandSize: 0,
+ valueDomain: FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN,
+ },
+}
+
+export function SingleStepBar({
+ stepData,
+ theme,
+ interactive,
+ onSegmentClick,
+ renderTooltip,
+ onError,
+}: SingleStepBarProps): JSX.Element {
+ const onPointClick = interactive
+ ? (clickData: PointClickData<FunnelBarHorizontalSegmentMeta>): void => {
+ const meta = clickData.series.meta
+ if (meta) {
+ onSegmentClick(meta)
+ }
+ }
+ : undefined
+
+ return (
+ <div className="flex flex-col h-8 my-1">
+ <BarChart<FunnelBarHorizontalSegmentMeta>
+ series={stepData.series}
+ labels={[stepData.label]}
+ theme={theme}
+ config={CHART_CONFIG}
+ tooltip={renderTooltip}
+ onPointClick={onPointClick}
+ onError={onError}
+ />
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.test.ts b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.test.ts
index 020136b32369..2c3cb5dee9a1 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.test.ts
@@ -2,6 +2,7 @@ import { EntityTypes, FunnelStepReference, type FunnelStepWithConversionMetrics
import {
buildFunnelBarHorizontalData,
+ type FunnelBarHorizontalStepData,
FUNNEL_BAR_HORIZONTAL_FILLER_KEY,
FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX,
} from './funnelBarHorizontalTransforms'
@@ -45,19 +46,25 @@ const options = {
fillerColor: '#eef0f3',
}
+/** Collects one series' value across every step, for asserting against the old per-step arrays. */
+function dataAcross(steps: FunnelBarHorizontalStepData[], seriesIndex: number): number[] {
+ return steps.map((s) => s.series[seriesIndex].data[0])
+}
+
describe('buildFunnelBarHorizontalData', () => {
- it('returns empty series + labels when given no steps', () => {
- expect(buildFunnelBarHorizontalData([], options)).toEqual({ series: [], labels: [] })
+ it('returns no steps when given no steps', () => {
+ expect(buildFunnelBarHorizontalData([], options)).toEqual([])
})
- it('emits one label per step', () => {
+ it('emits one entry per step, each labeled by its index', () => {
const steps = [
makeStep({ count: 100, fromBasisStep: 1, name: 'Viewed' }),
makeStep({ count: 50, fromBasisStep: 0.5, name: 'Signed up' }),
makeStep({ count: 20, fromBasisStep: 0.2, name: 'Purchased' }),
]
- const { labels } = buildFunnelBarHorizontalData(steps, options)
- expect(labels).toHaveLength(3)
+ const result = buildFunnelBarHorizontalData(steps, options)
+ expect(result).toHaveLength(3)
+ expect(result.map((s) => s.label)).toEqual(['0', '1', '2'])
})
describe('non-breakdown funnel', () => {
@@ -67,32 +74,33 @@ describe('buildFunnelBarHorizontalData', () => {
makeStep({ count: 20, fromBasisStep: 0.2, name: 'Purchased' }),
]
- it('emits one segment series + one filler series, each with one value per step', () => {
- const { series } = buildFunnelBarHorizontalData(noBreakdownSteps, options)
+ it('gives each step one segment series + one filler series, each holding a single value', () => {
+ const result = buildFunnelBarHorizontalData(noBreakdownSteps, options)
- expect(series).toHaveLength(2)
- expect(series[0].data).toEqual([100, 50, 20])
- expect(series[1].data).toEqual([0, 50, 80])
+ expect(result.every((s) => s.series.length === 2)).toBe(true)
+ expect(result.every((s) => s.series.every((entry) => entry.data.length === 1))).toBe(true)
+ expect(dataAcross(result, 0)).toEqual([100, 50, 20])
+ expect(dataAcross(result, 1)).toEqual([0, 50, 80])
})
it('tags each series with its drop-off / breakdown role for click + tooltip routing', () => {
- const { series } = buildFunnelBarHorizontalData(noBreakdownSteps, options)
+ const [first] = buildFunnelBarHorizontalData(noBreakdownSteps, options)
- expect(series[0].meta).toEqual({ isDropOff: false, breakdownIndex: null })
- expect(series[1].meta).toEqual({ isDropOff: true, breakdownIndex: null })
+ expect(first.series[0].meta).toEqual({ isDropOff: false, breakdownIndex: null })
+ expect(first.series[1].meta).toEqual({ isDropOff: true, breakdownIndex: null })
})
it('hides the filler from the tooltip so it doesn’t double up with FunnelTooltip’s drop-off section', () => {
- const { series } = buildFunnelBarHorizontalData(noBreakdownSteps, options)
- expect(series[1].visibility?.tooltip).toBe(false)
+ const [first] = buildFunnelBarHorizontalData(noBreakdownSteps, options)
+ expect(first.series[1].visibility?.tooltip).toBe(false)
})
- it('colors the segment from the representative step and the filler from options.fillerColor', () => {
+ it('colors the segment from the step and the filler from options.fillerColor', () => {
const getColor = jest.fn(() => '#abcabc')
- const { series } = buildFunnelBarHorizontalData(noBreakdownSteps, { ...options, getColor })
+ const [first] = buildFunnelBarHorizontalData(noBreakdownSteps, { ...options, getColor })
- expect(series[0].color).toBe('#abcabc')
- expect(series[1].color).toBe(options.fillerColor)
+ expect(first.series[0].color).toBe('#abcabc')
+ expect(first.series[1].color).toBe(options.fillerColor)
expect(getColor).toHaveBeenCalledWith(noBreakdownSteps[0])
})
})
@@ -117,24 +125,24 @@ describe('buildFunnelBarHorizontalData', () => {
}),
]
- it('emits one series per variant plus the trailing filler', () => {
- const { series } = buildFunnelBarHorizontalData(breakdownSteps, options)
+ it('gives each step one series per variant plus the trailing filler', () => {
+ const result = buildFunnelBarHorizontalData(breakdownSteps, options)
- expect(series).toHaveLength(3)
- expect(series.map((s) => s.label)).toEqual(['mobile', 'desktop', 'Drop-off'])
+ expect(result.every((s) => s.series.length === 3)).toBe(true)
+ expect(result[0].series.map((s) => s.label)).toEqual(['mobile', 'desktop', 'Drop-off'])
})
it('builds per-step fractions per variant against the configured basis step', () => {
- const { series } = buildFunnelBarHorizontalData(breakdownSteps, options)
- expect(series[0].data).toEqual([60, 30])
- expect(series[1].data).toEqual([40, 10])
- expect(series[2].data).toEqual([0, 60])
+ const result = buildFunnelBarHorizontalData(breakdownSteps, options)
+ expect(dataAcross(result, 0)).toEqual([60, 30])
+ expect(dataAcross(result, 1)).toEqual([40, 10])
+ expect(dataAcross(result, 2)).toEqual([0, 60])
})
it('tags each segment with its source breakdownIndex', () => {
- const { series } = buildFunnelBarHorizontalData(breakdownSteps, options)
- expect(series[0].meta).toEqual({ isDropOff: false, breakdownIndex: 0 })
- expect(series[1].meta).toEqual({ isDropOff: false, breakdownIndex: 1 })
+ const [first] = buildFunnelBarHorizontalData(breakdownSteps, options)
+ expect(first.series[0].meta).toEqual({ isDropOff: false, breakdownIndex: 0 })
+ expect(first.series[1].meta).toEqual({ isDropOff: false, breakdownIndex: 1 })
})
it('zeros a missing variant at a later step rather than rolling its count into another bar', () => {
@@ -154,11 +162,11 @@ describe('buildFunnelBarHorizontalData', () => {
}),
]
- const { series } = buildFunnelBarHorizontalData(skewed, options)
- expect(series).toHaveLength(3)
- expect(series[0].data).toEqual([60, 50]) // mobile
- expect(series[1].data).toEqual([40, 0]) // desktop — missing in step 1
- expect(series[2].data).toEqual([0, 50]) // filler
+ const result = buildFunnelBarHorizontalData(skewed, options)
+ expect(result.every((s) => s.series.length === 3)).toBe(true)
+ expect(dataAcross(result, 0)).toEqual([60, 50]) // mobile
+ expect(dataAcross(result, 1)).toEqual([40, 0]) // desktop — missing in step 1
+ expect(dataAcross(result, 2)).toEqual([0, 50]) // filler
})
})
@@ -178,20 +186,20 @@ describe('buildFunnelBarHorizontalData', () => {
const breakdownFilter = { breakdown: '$browser' }
it('collapses to one segment + filler, sourced from the single visible variant', () => {
- const { series } = buildFunnelBarHorizontalData(collapsedSteps, { ...options, breakdownFilter })
+ const result = buildFunnelBarHorizontalData(collapsedSteps, { ...options, breakdownFilter })
- expect(series).toHaveLength(2)
- expect(series[0].label).toBe('mobile')
- expect(series[0].data).toEqual([100, 50])
- expect(series[0].meta?.breakdownIndex).toBe(0)
- expect(series[1].data).toEqual([0, 50])
+ expect(result.every((s) => s.series.length === 2)).toBe(true)
+ expect(result[0].series[0].label).toBe('mobile')
+ expect(dataAcross(result, 0)).toEqual([100, 50])
+ expect(result[0].series[0].meta?.breakdownIndex).toBe(0)
+ expect(dataAcross(result, 1)).toEqual([0, 50])
})
it('falls back to the parent step’s rate when no breakdownFilter is set', () => {
- const { series } = buildFunnelBarHorizontalData(collapsedSteps, options)
+ const result = buildFunnelBarHorizontalData(collapsedSteps, options)
- expect(series[0].data).toEqual([100, 50])
- expect(series[0].meta?.breakdownIndex).toBeNull()
+ expect(dataAcross(result, 0)).toEqual([100, 50])
+ expect(result[0].series[0].meta?.breakdownIndex).toBeNull()
})
})
@@ -207,8 +215,8 @@ describe('buildFunnelBarHorizontalData', () => {
makeStep({ count: 50, fromBasisStep: 0.5, name: 'Signed up' }),
makeStep({ count: 20, fromBasisStep: 0.2, name: 'Purchased' }),
]
- const { series } = buildFunnelBarHorizontalData(steps, { ...options, stepReference })
- expect(series[0].data).toEqual(expected)
+ const result = buildFunnelBarHorizontalData(steps, { ...options, stepReference })
+ expect(dataAcross(result, 0)).toEqual(expected)
}
)
@@ -226,12 +234,12 @@ describe('buildFunnelBarHorizontalData', () => {
],
}),
]
- const { series } = buildFunnelBarHorizontalData(steps, {
+ const result = buildFunnelBarHorizontalData(steps, {
...options,
stepReference: FunnelStepReference.previous,
})
- // Step 0 has no nested_breakdown, so non-breakdown path is taken regardless of stepReference.
- expect(series[0].data).toEqual([100, 50, 30])
+ // Step 0 has no nested_breakdown, so the non-breakdown path is taken regardless of stepReference.
+ expect(dataAcross(result, 0)).toEqual([100, 50, 30])
})
})
@@ -257,8 +265,8 @@ describe('buildFunnelBarHorizontalData', () => {
],
}),
]
- const { series } = buildFunnelBarHorizontalData(steps, options)
- expect(series.map((s) => s.data)).toEqual([
+ const result = buildFunnelBarHorizontalData(steps, options)
+ expect([dataAcross(result, 0), dataAcross(result, 1), dataAcross(result, 2)]).toEqual([
[0, 0],
[0, 0],
[100, 100],
@@ -286,8 +294,8 @@ describe('buildFunnelBarHorizontalData', () => {
],
}),
]
- const { series } = buildFunnelBarHorizontalData(steps, options)
- expect(series.map((s) => s.key)).toEqual([
+ const [first] = buildFunnelBarHorizontalData(steps, options)
+ expect(first.series.map((s) => s.key)).toEqual([
`${FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX}0`,
`${FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX}1`,
FUNNEL_BAR_HORIZONTAL_FILLER_KEY,
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.ts b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.ts
index 8610d676efe1..163361aea38b 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.ts
+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/funnelBarHorizontalTransforms.ts
@@ -7,6 +7,9 @@ import { FunnelStepReference, type FunnelStepWithConversionMetrics } from '~/typ
export const FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX = 'funnel-bar-horizontal-segment-'
export const FUNNEL_BAR_HORIZONTAL_FILLER_KEY = 'funnel-bar-horizontal-filler'
+/** Shared `bars.valueDomain` so each step's separate chart lines up (basis-step percentages, `0–100`). */
+export const FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN: [number, number] = [0, 100]
+
const RATE_TO_PERCENT = 100
export interface FunnelBarHorizontalSegmentMeta {
@@ -14,9 +17,11 @@ export interface FunnelBarHorizontalSegmentMeta {
breakdownIndex: number | null
}
-export interface FunnelBarHorizontalData {
+/** 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>[]
- labels: string[]
}
interface BuildOptions {
@@ -42,84 +47,72 @@ function variantAtStep(
export function buildFunnelBarHorizontalData(
steps: FunnelStepWithConversionMetrics[],
options: BuildOptions
-): FunnelBarHorizontalData {
+): FunnelBarHorizontalStepData[] {
if (steps.length === 0) {
- return { series: [], labels: [] }
- }
-
- // Band keys must be unique — funnels often repeat the same event, so step names collide and
- // d3.scaleBand would collapse them into one band. The visible step names come from StepDecorations.
- const labels = steps.map((_, stepIndex) => String(stepIndex))
-
- if (isBreakdownLayout(steps)) {
- return { series: buildBreakdownSeries(steps, options), labels }
+ return []
}
- return { series: buildSingleSeries(steps, options), labels }
+ const breakdown = isBreakdownLayout(steps)
+ return steps.map((step, stepIndex) => ({
+ label: String(stepIndex),
+ series: breakdown ? buildBreakdownSegments(steps, stepIndex, options) : buildSingleSegment(step, options),
+ }))
}
-function buildBreakdownSeries(
+function buildBreakdownSegments(
steps: FunnelStepWithConversionMetrics[],
+ stepIndex: number,
options: BuildOptions
): Series<FunnelBarHorizontalSegmentMeta>[] {
+ const step = steps[stepIndex]
+ const basisCount = getReferenceStep(steps, options.stepReference, stepIndex).count
const breakdownCount = steps[0].nested_breakdown!.length
- const series: Series<FunnelBarHorizontalSegmentMeta>[] = []
+ const segments: Series<FunnelBarHorizontalSegmentMeta>[] = []
for (let breakdownIndex = 0; breakdownIndex < breakdownCount; breakdownIndex++) {
- const fractions = steps.map((step, stepIndex) => {
- const variant = variantAtStep(step, breakdownIndex)
- if (!variant) {
- return 0
- }
- const basisCount = getReferenceStep(steps, options.stepReference, stepIndex).count
- return basisCount > 0 ? variant.count / basisCount : 0
- })
+ const variant = variantAtStep(step, breakdownIndex)
+ const fraction = variant && basisCount > 0 ? variant.count / basisCount : 0
+ // Color and label come from step 0's variant so the same breakdown reads consistently
+ // across steps even when a later step is missing that variant.
const representative = variantAtStep(steps[0], breakdownIndex)!
- series.push({
+ segments.push({
key: `${FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX}${breakdownIndex}`,
label: options.getLabel(representative),
- data: fractions.map((f) => f * RATE_TO_PERCENT),
+ data: [fraction * RATE_TO_PERCENT],
color: options.getColor(representative),
meta: { isDropOff: false, breakdownIndex },
})
}
- series.push(buildFiller(steps, series, options.fillerColor))
- return series
+ return [...segments, buildFiller(segments, options.fillerColor)]
}
-function buildSingleSeries(
- steps: FunnelStepWithConversionMetrics[],
+function buildSingleSegment(
+ step: FunnelStepWithConversionMetrics,
options: BuildOptions
): Series<FunnelBarHorizontalSegmentMeta>[] {
- const displaySteps = steps.map((step) => getStepBreakdownSeries(step, options.breakdownFilter) ?? step)
- const fractions = displaySteps.map((s) => s.conversionRates.fromBasisStep)
- const representative = displaySteps[0]
- const isSingleBreakdownCollapse = displaySteps[0] !== steps[0]
+ const displayStep = getStepBreakdownSeries(step, options.breakdownFilter) ?? step
+ const isSingleBreakdownCollapse = displayStep !== step
const segment: Series<FunnelBarHorizontalSegmentMeta> = {
key: `${FUNNEL_BAR_HORIZONTAL_SEGMENT_KEY_PREFIX}0`,
- label: options.getLabel(representative),
- data: fractions.map((f) => f * RATE_TO_PERCENT),
- color: options.getColor(representative),
+ label: options.getLabel(displayStep),
+ data: [displayStep.conversionRates.fromBasisStep * RATE_TO_PERCENT],
+ color: options.getColor(displayStep),
meta: { isDropOff: false, breakdownIndex: isSingleBreakdownCollapse ? 0 : null },
}
- return [segment, buildFiller(steps, [segment], options.fillerColor)]
+ return [segment, buildFiller([segment], options.fillerColor)]
}
function buildFiller(
- steps: FunnelStepWithConversionMetrics[],
segments: Series<FunnelBarHorizontalSegmentMeta>[],
color: string
): Series<FunnelBarHorizontalSegmentMeta> {
- const fillerData = steps.map((_, stepIndex) => {
- const covered = segments.reduce((sum, s) => sum + (s.data[stepIndex] ?? 0), 0)
- return Math.max(0, RATE_TO_PERCENT - covered)
- })
+ const covered = segments.reduce((sum, s) => sum + (s.data[0] ?? 0), 0)
return {
key: FUNNEL_BAR_HORIZONTAL_FILLER_KEY,
label: 'Drop-off',
- data: fillerData,
+ data: [Math.max(0, RATE_TO_PERCENT - covered)],
color,
visibility: { tooltip: false },
meta: { isDropOff: true, breakdownIndex: null },