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.

feat(funnels): show step conversion and counts on the steps bar chart (#118334)

Sam Pennington8aa2e29a6125
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1ae5891799b7..60487a4e5793 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3852,14 +3852,18 @@ snapshots:
hash: v1.k794b7964.78fb6437968de10ad57843fbf5878102a73d60befd9fb4cad75d798df9890019.sRau17NRwFfT6JEJzu_sn1c8TkoQ8eyg_BsqpejRrwk
insights-funnelpropertycorrelationtable--default--light:
hash: v1.k794b7964.d92e6f81c63dc330f512b926f058c176125ac0413296275f5a3f416ae2fab10d.WgPOHv1rLmkFI1GCi8XasA5UoHRyk-wIzuiTFfgHX4I
+ insights-funnelstepsbarchart--bar-labels--dark:
+ hash: v1.k794b7964.5de2ee4fdd7ba021e1af1363b1e7977b10a245ce3ae6486008b83552cc41296d.tMGnyCUxbncHrGz42VrPrOAdXqsv6oqpZP2N6hjMW48
+ insights-funnelstepsbarchart--bar-labels--light:
+ hash: v1.k794b7964.e83a257faa00b86d54af31d9036282287980fb3364f113e8a0d2aecebb45ab67.abnZOn1eB9PVmogPAEiACEwtoKJtInL232ouk55ZBeU
insights-funnelstepsbarchart--bar-labels-breakdown--dark:
- hash: v1.k794b7964.1b81a37668d87d9e22111138a41b64ba2a35df1e2ade467aaee188f2c8d04f3c.UKeyJfLXVsNRZ8KxhlOZvv62ThvYUL_o399r-hVnvO0
+ hash: v1.k794b7964.d3675eb469f32b3a3767a993ebae285cf78dadaeece9b92bd9fc5e91080b6068.Lsx3bzPCJAlujEQn8J9l7O77jhh10eNRXSiDPoVe7r4
insights-funnelstepsbarchart--bar-labels-breakdown--light:
- hash: v1.k794b7964.c0c82357191864f94bcaff7b5b10b488167a0b280e703373d0148325cfc2355e.AdRk7JPu1Ee4wOEJR3vBS_e7YpIBee-ZV_lscrfYQlk
+ hash: v1.k794b7964.2c3c0f0066ab4d0d241134e6de2ddd48c34ec5996e06067e8097a20a62922cf8.K2qM77LHmP27bs4qp40o8hdxMSEsznlBDv8V2F_BMR4
insights-funnelstepsbarchart--bar-labels-many-steps--dark:
- hash: v1.k794b7964.10eb1afc21f49174149c7679c740deeb02d6483d9535e1083b8cef2d6ffb7f26.jQR-MrvgFYeHiqHWGcaOkLNHXfwz0aC-2Hl_ERddPNQ
+ hash: v1.k794b7964.f8f7ee9285db3cd93dad1945ba60c8a785dd4884bddda6a2615fef74cef6aa74.vo-lKwvxnbnPRqLX1vuqTnFa7-t_z3l4bmsYSdq5GXM
insights-funnelstepsbarchart--bar-labels-many-steps--light:
- hash: v1.k794b7964.8c792f8d561d28f5468edd450b1495b5e475b2507f126d3d17534856e8e26f15.mG7etoFQtpXzqFLbq5bJ3psNR5r7RjklLaexltXIrpw
+ hash: v1.k794b7964.446c2439434ebc7c2548104754e305d55996c802f4bbba92400abe26cf131f87.J8KJa21D37xtnfweXJdk9CSYFCKkUQyv7n0RvofA1gM
insights-funnelstepsbarchart--breakdown--dark:
hash: v1.k794b7964.790ff5760fabe3a875385fc7f09cd89d8096abf331d4b36a59abee7f0a35bc23.3uG4AjVvDhojZ8UlnAa4vzwgAdjl3zsbKVnN6ysAHls
insights-funnelstepsbarchart--breakdown--light:
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.stories.tsx b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.stories.tsx
index ef0cf10cdd73..72261771ccf7 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.stories.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.stories.tsx
@@ -98,6 +98,12 @@ const manyStepsFixture = {
},
}
+// One bar per step, so the step to step conversion chips sit in the gaps between steps.
+export const BarLabels: Story = {
+ render: () => <StoryRender insightFixture={funnelTopToBottomFixture} />,
+ parameters: { featureFlags: [FEATURE_FLAGS.FUNNEL_STEPS_BAR_LABELS] },
+}
+
// Steps shrink to fit the width instead of scrolling, with the rate on each bar.
export const BarLabelsManySteps: Story = {
render: () => <StoryRender insightFixture={manyStepsFixture} width={1520} />,
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.tsx
index 875263adf38b..4775c2440786 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/FunnelStepsBarChart.tsx
@@ -13,18 +13,20 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { groupsModel } from '~/models/groupsModel'
-import { ChartParams } from '~/types'
+import { ChartParams, FunnelStepReference } from '~/types'
import { funnelDataLogic } from '../funnelDataLogic'
import { funnelPersonsModalLogic } from '../funnelPersonsModalLogic'
import { FunnelStepsBarTooltip } from './FunnelStepsBarTooltip'
import {
+ buildFunnelStepBarLabelFormatter,
buildFunnelStepsBarData,
- formatFunnelStepBarLabel,
FUNNEL_STEPS_BAR_TOOLTIP_CONFIG,
+ getConversionChipStepIndexes,
resolveFunnelStepClick,
type FunnelStepsBarSeriesMeta,
} from './funnelStepsBarTransforms'
+import { StepConversionChips } from './StepConversionChips'
import { StepLegend } from './StepLegend'
import { StepNameLabel } from './StepNameLabel'
@@ -57,9 +59,16 @@ export function FunnelStepsBarChart({
const { featureFlags } = useValues(featureFlagLogic)
const hasBarLabels = !!featureFlags[FEATURE_FLAGS.FUNNEL_STEPS_BAR_LABELS]
const { insightProps } = useValues(insightLogic)
- const { visibleStepsWithConversionMetrics, getFunnelsColor, breakdownFilter, querySource, insightData } = useValues(
- funnelDataLogic(insightProps)
- )
+ const {
+ stepsWithConversionMetrics,
+ visibleStepsWithConversionMetrics,
+ getFunnelsColor,
+ breakdownFilter,
+ querySource,
+ insightData,
+ funnelsFilter,
+ isStepOptional,
+ } = useValues(funnelDataLogic(insightProps))
const { canOpenPersonModal } = useValues(funnelPersonsModalLogic(insightProps))
const { openPersonsModalForSeries } = useActions(funnelPersonsModalLogic(insightProps))
const { aggregationLabel } = useValues(groupsModel)
@@ -75,6 +84,7 @@ export function FunnelStepsBarChart({
}),
[steps, getFunnelsColor]
)
+ const formatBarLabel = useMemo(() => buildFunnelStepBarLabelFormatter(series), [series])
// Feeds the tooltip header only; the visible labels come from the StepLegend footer.
const stepLabels = useMemo(() => steps.map((step) => String(step.custom_name ?? step.name ?? '')), [steps])
@@ -83,6 +93,18 @@ export function FunnelStepsBarChart({
const showTime = steps.some((step) => step.average_conversion_time != null)
const breakdownCount = series.length
+ const conversionChipStepIndexes = useMemo(
+ () =>
+ hasBarLabels
+ ? getConversionChipStepIndexes(steps, {
+ // The visible steps always carry nested_breakdown, so check the steps before hidden values are filtered out.
+ hasBreakdownOrCompare: stepsWithConversionMetrics[0]?.nested_breakdown != null,
+ stepReference: funnelsFilter?.funnelStepReference ?? FunnelStepReference.total,
+ isStepOptional,
+ })
+ : [],
+ [hasBarLabels, steps, stepsWithConversionMetrics, funnelsFilter?.funnelStepReference, isStepOptional]
+ )
const chartWidth = (stepWidthPx: number): number =>
DEFAULT_MARGINS.left +
steps.length * Math.max(stepWidthPx, breakdownCount * PER_BAR_WIDTH_PX) +
@@ -121,7 +143,7 @@ export function FunnelStepsBarChart({
return null
}
return hasBarLabels ? (
- <StepNameLabel step={step} stepIndex={stepIndex} />
+ <StepNameLabel step={step} stepIndex={stepIndex} showPersonsModal={showPersonsModal} />
) : (
<StepLegend
step={step}
@@ -162,7 +184,10 @@ export function FunnelStepsBarChart({
dataAttr="funnel-steps-bar-chart-canvas"
onError={handleChartError}
>
- {hasBarLabels && <ValueLabels valueFormatter={formatFunnelStepBarLabel} offset={4} />}
+ {hasBarLabels && <ValueLabels valueFormatter={formatBarLabel} offset={4} />}
+ {conversionChipStepIndexes.length > 0 && (
+ <StepConversionChips steps={steps} stepIndexes={conversionChipStepIndexes} />
+ )}
</FunnelChart>
</div>
</ScrollableShadows>
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/StepConversionChips.tsx b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/StepConversionChips.tsx
new file mode 100644
index 000000000000..0247b5283c73
--- /dev/null
+++ b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/StepConversionChips.tsx
@@ -0,0 +1,81 @@
+/* eslint-disable react/forbid-dom-props -- positions come from the chart scales */
+import { useMemo } from 'react'
+
+import { IconArrowRight } from '@posthog/icons'
+import { RATE_TO_PERCENT, useChartLayout } from '@posthog/quill-charts'
+
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import type { FunnelStepWithConversionMetrics } from '~/types'
+
+import { formatFunnelStepRate, placeStepConversionChips, type StepBandBox } from './funnelStepsBarTransforms'
+
+const CHIP_ROW_HEIGHT_PX = 16
+const CHIP_CHROME_PX = 6
+const CHIP_EDGE_INSET_PX = 4
+
+interface StepConversionChipsProps {
+ steps: FunnelStepWithConversionMetrics[]
+ stepIndexes: number[]
+}
+
+export function StepConversionChips({ steps, stepIndexes }: StepConversionChipsProps): JSX.Element | null {
+ const { scales, dimensions, labels } = useChartLayout()
+
+ const placements = useMemo(() => {
+ const bands: StepBandBox[] = labels.map((label) => {
+ const center = scales.x(label) ?? 0
+ const width = scales.extent?.(label) ?? 0
+ return { left: center - width / 2, width }
+ })
+ return placeStepConversionChips(bands.slice(0, steps.length)).filter(({ stepIndex }) =>
+ stepIndexes.includes(stepIndex)
+ )
+ }, [scales, labels, steps.length, stepIndexes])
+
+ if (placements.length === 0) {
+ return null
+ }
+
+ const plotBottom = dimensions.plotTop + dimensions.plotHeight
+
+ return (
+ <>
+ {placements.map(({ stepIndex, centerX }) => {
+ const step = steps[stepIndex]
+ const previousStep = steps[stepIndex - 1]
+ if (!step || !previousStep) {
+ return null
+ }
+ const hasDropOff = step.droppedOffFromPrevious > 0
+ const chipHeight = (hasDropOff ? 2 : 1) * CHIP_ROW_HEIGHT_PX + CHIP_CHROME_PX
+ // Centers the rate row on the previous bar's top, so chips line up whether or not they show a drop-off.
+ const previousBarTop = scales.y(previousStep.conversionRates.fromBasisStep * RATE_TO_PERCENT)
+ const top = Math.min(
+ plotBottom - chipHeight - CHIP_EDGE_INSET_PX,
+ Math.max(
+ dimensions.plotTop + CHIP_EDGE_INSET_PX,
+ previousBarTop - (CHIP_ROW_HEIGHT_PX + CHIP_CHROME_PX) / 2
+ )
+ )
+ return (
+ <div
+ key={stepIndex}
+ className="pointer-events-none absolute flex -translate-x-1/2 flex-col items-center rounded-md border border-primary bg-surface-primary px-1 py-0.5 text-xs leading-4 tabular-nums shadow-sm"
+ style={{ left: centerX, top }}
+ data-attr="funnel-step-conversion-chip"
+ translate="no"
+ >
+ <span className="flex items-center gap-0.5 font-semibold">
+ <IconArrowRight className="size-3 shrink-0 text-secondary" />
+ {formatFunnelStepRate(step.conversionRates.fromPrevious)}
+ </span>
+ {hasDropOff && (
+ <span className="text-danger">{`−${humanFriendlyLargeNumber(step.droppedOffFromPrevious)}`}</span>
+ )}
+ </div>
+ )
+ })}
+ </>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/StepNameLabel.tsx b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/StepNameLabel.tsx
index 166fdda2d217..427885da933d 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/StepNameLabel.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/StepNameLabel.tsx
@@ -1,26 +1,34 @@
import './FunnelBarVertical.scss'
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { userLogic } from 'scenes/userLogic'
import { AvailableFeature, FunnelStepWithConversionMetrics } from '~/types'
import { funnelDataLogic } from '../funnelDataLogic'
+import { funnelPersonsModalLogic } from '../funnelPersonsModalLogic'
import { FunnelStepPathLinks } from '../shared/FunnelStepPathLinks'
import { getActionFilterFromFunnelStep } from '../shared/funnelStepTableUtils'
+import { ValueInspectorButton } from '../shared/ValueInspectorButton'
type StepNameLabelProps = {
step: FunnelStepWithConversionMetrics
stepIndex: number
+ showPersonsModal: boolean
}
-export function StepNameLabel({ step, stepIndex }: StepNameLabelProps): JSX.Element {
+export function StepNameLabel({ step, stepIndex, showPersonsModal }: StepNameLabelProps): JSX.Element {
const { insightProps } = useValues(insightLogic)
- const { isStepOptional, querySource } = useValues(funnelDataLogic(insightProps))
+ const { isStepOptional, querySource, aggregationTargetLabel } = useValues(funnelDataLogic(insightProps))
+ const { isInExperimentContext } = useValues(funnelPersonsModalLogic(insightProps))
+ const { openPersonsModalForStep } = useActions(funnelPersonsModalLogic(insightProps))
const { hasAvailableFeature } = useValues(userLogic)
const isOptionalStep = isStepOptional(stepIndex + 1)
@@ -35,9 +43,19 @@ export function StepNameLabel({ step, stepIndex }: StepNameLabelProps): JSX.Elem
</span>
)
+ const count = step.count ?? 0
+ const countLabel = (
+ <span className="tabular-nums">
+ <span translate="no">{humanFriendlyNumber(count)}</span>
+ <span className="hidden @min-[11rem]:inline">
+ {` ${pluralize(count, aggregationTargetLabel.singular, aggregationTargetLabel.plural, false)}`}
+ </span>
+ </span>
+ )
+
return (
<div
- className="StepNameLabel flex items-start justify-center px-1 text-center text-sm"
+ className="StepNameLabel flex flex-col items-center px-1 text-center text-sm"
data-attr="funnel-step-legend"
style={{ opacity: isOptionalStep ? 0.6 : 1 }}
>
@@ -55,6 +73,19 @@ export function StepNameLabel({ step, stepIndex }: StepNameLabelProps): JSX.Elem
) : (
<div className="max-w-full px-1">{name}</div>
)}
+ <Tooltip title={`${capitalizeFirstLetter(aggregationTargetLabel.plural)} who completed this step`}>
+ {showPersonsModal && !isInExperimentContext ? (
+ <ValueInspectorButton
+ onClick={() => openPersonsModalForStep({ step, stepIndex, converted: true })}
+ // pinned: shared with the legacy step legend, so autocapture insights keep counting clicks
+ data-attr="funnel-inspect-converted"
+ >
+ {countLabel}
+ </ValueInspectorButton>
+ ) : (
+ <span className="text-secondary">{countLabel}</span>
+ )}
+ </Tooltip>
</div>
)
}
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.test.ts b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.test.ts
index d0b415a8df29..8e2d5ed54f0a 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.test.ts
@@ -1,10 +1,13 @@
import type { PointClickData, Series } from '@posthog/quill-charts'
-import { EntityTypes, type FunnelStepWithConversionMetrics } from '~/types'
+import { EntityTypes, FunnelStepReference, type FunnelStepWithConversionMetrics } from '~/types'
import {
buildFunnelStepsBarData,
+ formatFunnelStepRates,
FUNNEL_STEPS_SERIES_KEY_PREFIX,
+ getConversionChipStepIndexes,
+ placeStepConversionChips,
resolveFunnelStepClick,
type FunnelStepsBarSeriesMeta,
} from './funnelStepsBarTransforms'
@@ -245,3 +248,100 @@ describe('resolveFunnelStepClick', () => {
expect(resolveFunnelStepClick(noBreakdownSteps, makeClick({ dataIndex: 99 }))).toBeNull()
})
})
+
+describe('placeStepConversionChips', () => {
+ test.each([
+ {
+ name: 'centers a chip in each gap, keyed to the step it converts into',
+ bands: [
+ { left: 40, width: 100 },
+ { left: 240, width: 100 },
+ { left: 440, width: 100 },
+ ],
+ expected: [
+ { stepIndex: 1, centerX: 190 },
+ { stepIndex: 2, centerX: 390 },
+ ],
+ },
+ { name: 'places nothing for a single step', bands: [{ left: 40, width: 100 }], expected: [] },
+ ])('$name', ({ bands, expected }) => {
+ expect(placeStepConversionChips(bands)).toEqual(expected)
+ })
+})
+
+describe('formatFunnelStepRates', () => {
+ test.each([
+ { name: 'keeps far-apart rates whole', rates: [1, 0.8, 0.201], expected: ['100%', '80%', '20%'] },
+ { name: 'never shows a drop-off as 100%', rates: [1, 24861 / 24873], expected: ['100%', '99.9%'] },
+ {
+ name: 'never shows a small rate as 0%',
+ rates: [1, 77 / 24873, 3 / 24873],
+ expected: ['100%', '0.3%', '<0.1%'],
+ },
+ {
+ name: 'adds a decimal to neighbors that round the same',
+ rates: [0.454, 0.451, 0.2],
+ expected: ['45.4%', '45.1%', '20%'],
+ },
+ { name: 'keeps equal neighbors whole', rates: [2071 / 24873, 2071 / 24873], expected: ['8%', '8%'] },
+ ])('$name', ({ rates, expected }) => {
+ expect(formatFunnelStepRates(rates)).toEqual(expected)
+ })
+})
+
+describe('getConversionChipStepIndexes', () => {
+ const stepsWithCounts = (counts: number[]): FunnelStepWithConversionMetrics[] =>
+ counts.map((count) => makeStep({ fromBasisStep: count / counts[0], count }))
+
+ test.each([
+ {
+ name: 'gives every gap a chip without a breakdown',
+ counts: [1000, 600, 300],
+ hasBreakdownOrCompare: false,
+ stepReference: FunnelStepReference.total,
+ optionalStepNumbers: [],
+ expected: [1, 2],
+ },
+ {
+ name: 'gives no chips to a breakdown or compare',
+ counts: [1000, 600, 300],
+ hasBreakdownOrCompare: true,
+ stepReference: FunnelStepReference.total,
+ optionalStepNumbers: [],
+ expected: [],
+ },
+ {
+ name: 'gives no chips when bars are relative to the previous step',
+ counts: [1000, 600, 300],
+ hasBreakdownOrCompare: false,
+ stepReference: FunnelStepReference.previous,
+ optionalStepNumbers: [],
+ expected: [],
+ },
+ {
+ name: 'skips the gap after an optional step',
+ counts: [1000, 100, 600],
+ hasBreakdownOrCompare: false,
+ stepReference: FunnelStepReference.total,
+ optionalStepNumbers: [2],
+ expected: [1],
+ },
+ {
+ name: 'skips the gap after an empty step',
+ counts: [1000, 0, 0],
+ hasBreakdownOrCompare: false,
+ stepReference: FunnelStepReference.total,
+ optionalStepNumbers: [],
+ expected: [1],
+ },
+ ])('$name', ({ counts, hasBreakdownOrCompare, stepReference, optionalStepNumbers, expected }) => {
+ const isStepOptional = (stepNumber: number): boolean => optionalStepNumbers.includes(stepNumber)
+ expect(
+ getConversionChipStepIndexes(stepsWithCounts(counts), {
+ hasBreakdownOrCompare,
+ stepReference,
+ isStepOptional,
+ })
+ ).toEqual(expected)
+ })
+})
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.ts b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.ts
index 5f28cd7f93bf..7b4040453a4e 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.ts
+++ b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.ts
@@ -1,8 +1,8 @@
-import type { PointClickData, TooltipConfig } from '@posthog/quill-charts'
+import type { PointClickData, Series, TooltipConfig, ValueLabelFormatter } from '@posthog/quill-charts'
import { percentage } from 'lib/utils/numbers'
-import type { BreakdownKeyType, FunnelStepWithConversionMetrics } from '~/types'
+import { type BreakdownKeyType, FunnelStepReference, type FunnelStepWithConversionMetrics } from '~/types'
import { INSIGHT_TOOLTIP_CONFIG } from '../../shared/tooltipConfig'
import { getVisibilityKey } from '../funnelUtils'
@@ -150,6 +150,83 @@ export function resolveFunnelStepClick(
return { step, series: variant, converted: !clickData.inTrackArea }
}
-export function formatFunnelStepBarLabel(ratePercent: number): string {
- return percentage(ratePercent / RATE_TO_PERCENT, 0)
+const SMALLEST_SHOWN_RATE = 0.001
+const LARGEST_SHOWN_RATE = 0.999
+
+function formatPreciseRate(rate: number): string {
+ if (rate > 0 && rate < SMALLEST_SHOWN_RATE) {
+ return `<${percentage(SMALLEST_SHOWN_RATE, 1)}`
+ }
+ if (rate < 1 && rate > LARGEST_SHOWN_RATE) {
+ return percentage(LARGEST_SHOWN_RATE, 1)
+ }
+ return percentage(rate, 1)
+}
+
+// Adds a decimal only where a whole percentage would hide a difference, from 0%, 100% or a neighboring step.
+export function formatFunnelStepRates(rates: number[]): string[] {
+ const wholes = rates.map((rate) => percentage(rate, 0))
+ return rates.map((rate, index) => {
+ const whole = wholes[index]
+ const hidesDifference =
+ (whole === '0%' && rate > 0) ||
+ (whole === '100%' && rate < 1) ||
+ [index - 1, index + 1].some(
+ (neighbor) => neighbor in rates && rates[neighbor] !== rate && wholes[neighbor] === whole
+ )
+ return hidesDifference ? formatPreciseRate(rate) : whole
+ })
+}
+
+export function formatFunnelStepRate(rate: number): string {
+ return formatFunnelStepRates([rate])[0]
+}
+
+export function buildFunnelStepBarLabelFormatter(series: Pick<Series, 'data'>[]): ValueLabelFormatter {
+ const labels = series.map((s) => formatFunnelStepRates(s.data.map((value) => value / RATE_TO_PERCENT)))
+ return (value, seriesIndex, dataIndex) =>
+ labels[seriesIndex]?.[dataIndex] ?? formatFunnelStepRate(value / RATE_TO_PERCENT)
+}
+
+export function getConversionChipStepIndexes(
+ steps: FunnelStepWithConversionMetrics[],
+ {
+ hasBreakdownOrCompare,
+ stepReference,
+ isStepOptional,
+ }: {
+ hasBreakdownOrCompare: boolean
+ stepReference: FunnelStepReference
+ isStepOptional: (stepNumber: number) => boolean
+ }
+): number[] {
+ // With bars relative to the previous step, the bar labels already show step to step conversion.
+ // A breakdown or compare puts several bars in each step, and one chip cannot describe all of them.
+ if (hasBreakdownOrCompare || stepReference !== FunnelStepReference.total) {
+ return []
+ }
+ // A step after an optional step converts from an earlier step, so a chip in that gap would misread.
+ return steps.flatMap((_, index) =>
+ index > 0 && steps[index - 1].count > 0 && !isStepOptional(index) ? [index] : []
+ )
+}
+
+export interface StepBandBox {
+ left: number
+ width: number
+}
+
+export interface StepConversionChipPlacement {
+ /** The step the chip converts into. The chip sits in the gap before this step's bars. */
+ stepIndex: number
+ centerX: number
+}
+
+export function placeStepConversionChips(bands: StepBandBox[]): StepConversionChipPlacement[] {
+ const placements: StepConversionChipPlacement[] = []
+ for (let stepIndex = 1; stepIndex < bands.length; stepIndex++) {
+ const previousRight = bands[stepIndex - 1].left + bands[stepIndex - 1].width
+ placements.push({ stepIndex, centerX: (previousRight + bands[stepIndex].left) / 2 })
+ }
+ return placements
}