Skip to contentVibraUI
Charts

Funnel chart

Steps one population passes through, as columns joined by the band of people who went on, with the rate on each band.

Server-compatible: no hooks, no client boundary, no recharts. Each step is a column as tall as its share of the largest, its figure on top and its label and share of the first beneath; between two columns a band in a 10% fill runs from the top of one to the top of the next, the people who went on, and carries the step-to-step rate in a pill. Down the card (orientation="vertical") the same drawing turns on its side: bars from the start edge, the bands between them. A step with any value at all keeps a sliver, and an empty one draws nothing. The columns take the height they are given, from --funnel-plot (8rem) up. The steps are ordered, so their colour is ordinal rather than categorical — one hue at rising strength, palest at the largest step and strongest on the step that matters. A funnel is the wrong chart when the steps are not a sequence one population passes through: unrelated counts sorted by size are a bar chart, and a step that can be reached without the one above it is not a funnel step at all. Both readings are shown, because they answer different questions — the share of the first step under each column, and the step-to-step rate on the band, which says "continue" to a screen reader so it cannot be read as its own opposite. Hovering a step quiets the others. Every value is on the page as text, so there is no hidden list to keep in sync.

Install

npx shadcn@latest add @vibra/funnel-chart

Needs the @vibra registry in your components.json — set it up once.

Examples

Down the card

Props

PropTypeDefaultDescription
steps{ label: string; value: number; color?: ChartToken | string }[]one hue at rising strengthThe steps in order. A colour is a chart token or any CSS colour.
valueFormatter(n: number) => stringwhole number with separatorsFormats every value the chart prints.
showConversionbooleantrueShows each step's share of the first, and the rate that went on from the step before.
orientation"horizontal" | "vertical""horizontal"Columns across the card, or bars down it with the labels beside them.

Dependencies

Source

components/ui/funnel-chart.tsx
import * as React from "react"

import { cn } from "@/lib/utils"
import { formatNumber } from "@/lib/format"
import { isChartToken, type ChartToken } from "@/components/ui/percentage-bar"

/**
 * Every step as a percentage of the first, rounded to a tenth. A funnel that
 * starts at nothing has nothing to convert, so the whole run reads zero rather
 * than dividing by it.
 */
export function conversionRates(steps: { value: number }[]): number[] {
  const first = steps[0]?.value ?? 0
  if (first <= 0) return steps.map(() => 0)
  return steps.map((step) => Math.round((step.value / first) * 1000) / 10)
}

export type FunnelOrientation = "horizontal" | "vertical"

/** Two decimals: short paths, and the same string from the server and the browser. */
const round = (n: number) => Math.round(n * 100) / 100

/**
 * The band that carries one step into the next — the people who went on — as
 * a path in a 100 × 100 box its gap stretches to. `from` and `to` are the two
 * steps' sizes as shares of the largest, out of 100. Across the card the band
 * runs from the top of one column to the top of the next and down to the
 * baseline; down the card, from the end of one bar to the end of the next and
 * back to the start edge.
 */
export function funnelFlow(from: number, to: number, orientation: FunnelOrientation = "horizontal"): string {
  return orientation === "horizontal"
    ? `M0 ${round(100 - from)} L100 ${round(100 - to)} L100 100 L0 100 Z`
    : `M0 0 L${round(from)} 0 L${round(to)} 100 L0 100 Z`
}

// Funnel stages are ordered, so their colour is ordinal rather than
// categorical: one hue at rising strength, ending on the step that matters.
// The largest step is the palest — a saturated block that size shouts, and
// the converted step is small enough to need the chroma. Bars paint with
// `bg-current` and bands with `currentColor`, so a colour is a text utility.
const STEP_FILL = [
  "text-chart-1/45",
  "text-chart-1/55",
  "text-chart-1/65",
  "text-chart-1/78",
  "text-chart-1/88",
  "text-chart-1",
]

// Spelled out rather than built from `text-${token}`, because Tailwind scans
// for whole class names in the source and would find nothing to generate.
const CHART_TEXT: Record<ChartToken, string> = {
  "chart-1": "text-chart-1",
  "chart-2": "text-chart-2",
  "chart-3": "text-chart-3",
  "chart-4": "text-chart-4",
  "chart-5": "text-chart-5",
  "chart-6": "text-chart-6",
  "chart-7": "text-chart-7",
  "chart-8": "text-chart-8",
}

type Paint = { className?: string; style?: React.CSSProperties }

/** A step's bar, and the band into it: the band in the hue at full strength, which its 10% fill then quiets. */
function stepPaint(color: ChartToken | string | undefined, index: number, count: number): { bar: Paint; flow: Paint } {
  if (color === undefined) {
    const step = count < 2 ? STEP_FILL.length - 1 : Math.round((index / (count - 1)) * (STEP_FILL.length - 1))
    return { bar: { className: STEP_FILL[step] }, flow: { className: "text-chart-1" } }
  }
  const paint = isChartToken(color) ? { className: CHART_TEXT[color] } : { style: { color } }
  return { bar: paint, flow: paint }
}

/** The share of the largest a step with any value at all keeps, so a sliver of a step still draws. */
const MIN_SHARE = 1

const DEFAULT_FORMAT = (value: number) => formatNumber(value, { maximumFractionDigits: 0 })

/** Rates print to a tenth so a run of steps lines up, e.g. "42.0%", never "42%". */
const rate = (percent: number) => `${percent.toFixed(1)}%`

/**
 * The grid each orientation lays its steps on; the tracks that repeat per step
 * are written inline. Across the card the plot takes the height it is given,
 * from `--funnel-plot` (8rem) up, with room above the tallest column for its
 * figure. Down the card each bar is 1.5rem and the bands between take the
 * rest, from 1rem.
 */
const GRID = {
  horizontal: "grid-rows-[minmax(var(--funnel-plot,8rem),1fr)_auto_auto] gap-y-1.5",
  vertical: "grid-cols-[minmax(0,1fr)_minmax(0,2fr)_auto] gap-x-3",
}

/** Hovering a step quiets the others, so its bar, its figures and its label read as one. */
const HOVER = "[&:has([data-slot=funnel-chart-step]:hover)_[data-slot=funnel-chart-step]:not(:hover)]:opacity-45"

/**
 * The step-to-step rate, on the band it describes. It is absolute with no
 * inline offset of its own across the card, so its band's flex centring
 * places it in either direction of text; the other axis is set where it is
 * drawn.
 */
const RATE_PILL =
  "absolute z-10 rounded-full bg-card px-1.5 py-0.5 text-xs whitespace-nowrap text-muted-foreground tabular-nums ring-1 ring-border"

export type FunnelStep = {
  label: string
  value: number
  /** A chart token, or any CSS colour. Defaults to the ordinal ramp. */
  color?: ChartToken | string
}

export type FunnelChartProps = React.ComponentProps<"div"> & {
  steps: FunnelStep[]
  valueFormatter?: (n: number) => string
  /** Shows each step's share of the first, and the rate that went on from the step before. */
  showConversion?: boolean
  orientation?: FunnelOrientation
}

function FunnelChart({
  className,
  style,
  steps,
  valueFormatter = DEFAULT_FORMAT,
  showConversion = true,
  orientation = "horizontal",
  "aria-label": ariaLabel,
  ...props
}: FunnelChartProps) {
  const across = orientation === "horizontal"
  const cumulative = conversionRates(steps)
  const largest = steps.reduce((most, step) => Math.max(most, step.value), 0)

  const rows = steps.map((step, i) => {
    const previous = steps[i - 1]?.value ?? 0
    const value = Math.max(0, step.value)
    return {
      ...step,
      reading: valueFormatter(step.value),
      size: largest > 0 && value > 0 ? Math.max(MIN_SHARE, (value / largest) * 100) : 0,
      cumulative: cumulative[i],
      // The step-to-step rate, which is the number a funnel is read for: not
      // the share of the top of the funnel but how many of the people who got
      // this far went on. Named for what it counts — the ones who continued —
      // because "42% drop-off" and "42% continue" are opposite readings.
      continued: i === 0 ? null : previous > 0 ? (step.value / previous) * 100 : 0,
      paint: stepPaint(step.color, i, steps.length),
    }
  })

  const summary =
    ariaLabel ??
    (rows.length === 0
      ? "Funnel with no steps."
      : `Funnel of ${rows.length} steps, ${rows[0].reading} down to ${rows[rows.length - 1].reading}, ${rate(cumulative[cumulative.length - 1])} converted.`)

  // Steps and the bands between them take turns in one grid. Across the card
  // a step is a column and a band the gap after it, about half as wide; down
  // the card a step is a row its label, bar and figures share through a
  // subgrid, and a band the row between two bars.
  const tracks = rows
    .map((_, i) => (i === 0 ? "" : across ? "minmax(0,0.55fr) " : "minmax(1rem,1fr) ") + (across ? "minmax(0,1fr)" : "1.5rem"))
    .join(" ")

  return (
    <div
      data-slot="funnel-chart"
      data-orientation={orientation}
      data-conversion={showConversion || undefined}
      role="group"
      aria-label={summary}
      className={cn("flex h-full w-full flex-col", className)}
      style={style}
      {...props}
    >
      <div
        data-slot="funnel-chart-grid"
        className={cn("grid h-full", GRID[orientation], HOVER)}
        style={across ? { gridTemplateColumns: tracks } : { gridTemplateRows: tracks }}
      >
        {rows.map((row, i) => (
          <React.Fragment key={`${row.label}-${i}`}>
            {i > 0 ? (
              <div className={across ? "row-start-1 pt-6" : "col-start-2"} style={across ? { gridColumn: 2 * i } : undefined}>
                <div
                  data-slot="funnel-chart-flow"
                  className={cn("relative flex h-full", across ? "justify-center" : "items-center", row.paint.flow.className)}
                  style={row.paint.flow.style}
                >
                  <svg
                    viewBox="0 0 100 100"
                    preserveAspectRatio="none"
                    aria-hidden="true"
                    focusable="false"
                    className={cn("absolute inset-0 size-full", !across && "rtl:-scale-x-100")}
                  >
                    <path d={funnelFlow(rows[i - 1].size, row.size, orientation)} fill="currentColor" fillOpacity={0.1} />
                  </svg>
                  {showConversion ? (
                    <span
                      data-slot="funnel-chart-step-rate"
                      className={cn(RATE_PILL, across ? "translate-y-1/2" : "-translate-x-1/2 rtl:translate-x-1/2")}
                      // Halfway up the next column, and never under the baseline into its label.
                      style={across ? { bottom: `max(${round(row.size / 2)}%, 0.75rem)` } : { insetInlineStart: `${round(row.size / 2)}%` }}
                    >
                      {rate(row.continued ?? 0)}
                      <span className="sr-only"> continue</span>
                    </span>
                  ) : null}
                </div>
              </div>
            ) : null}

            <div
              data-slot="funnel-chart-step"
              className={cn(
                "grid transition-opacity duration-(--duration-base)",
                across ? "row-span-3 min-w-0 grid-rows-subgrid text-center" : "col-span-full grid-cols-subgrid items-center text-sm"
              )}
              style={across ? { gridColumn: 2 * i + 1 } : undefined}
            >
              {across ? (
                // A column is narrow in a narrow card. Its label wraps between
                // words, never inside one: a word wider than the column hangs
                // over it evenly both sides, as a flex item centred in a box
                // too small for it does, rather than being cut — and the box
                // is contained, so the word cannot widen its column instead.
                <span className="row-start-2 flex justify-center [contain:inline-size]">
                  <span className="text-xs text-muted-foreground">{row.label}</span>
                </span>
              ) : (
                <span className="line-clamp-2 text-muted-foreground">{row.label}</span>
              )}

              <div className={across ? "row-start-1 pt-6" : "h-full"}>
                <div
                  data-slot="funnel-chart-track"
                  className={cn("relative h-full", row.paint.bar.className)}
                  style={row.paint.bar.style}
                >
                  <div
                    data-slot="funnel-chart-bar"
                    aria-hidden="true"
                    className={cn("absolute bg-current", across ? "inset-x-0 bottom-0 rounded-t-sm" : "inset-y-0 start-0 rounded-e-sm")}
                    style={across ? { height: `${round(row.size)}%` } : { width: `${round(row.size)}%` }}
                  />
                  {across ? (
                    <span
                      className="absolute inset-x-0 flex justify-center text-xs font-medium whitespace-nowrap text-foreground tabular-nums"
                      style={{ bottom: `calc(${round(row.size)}% + 0.25rem)` }}
                    >
                      {row.reading}
                    </span>
                  ) : null}
                </div>
              </div>

              {across ? (
                showConversion ? (
                  <span className="row-start-3 text-xs text-muted-foreground tabular-nums">{rate(row.cumulative)}</span>
                ) : null
              ) : (
                <span className="flex items-baseline justify-end gap-2 tabular-nums">
                  <span className="font-medium">{row.reading}</span>
                  {showConversion ? <span className="text-muted-foreground">{rate(row.cumulative)}</span> : null}
                </span>
              )}
            </div>
          </React.Fragment>
        ))}
      </div>
    </div>
  )
}

export { FunnelChart }