Drop-off funnel

A conversion funnel of horizontal stages whose widths shrink with their value, joined by curved bridges so it reads as one flowing shape filled with a gradient from the theme's chart colours. Each stage shows its label, count and share of the first stage, and a chip between stages shows the loss. The largest drop is found automatically and marked in the destructive tone. An optional earlier period draws as a dashed ghost shape with up or down deltas per stage. Stages grow in when scrolled into view, it can lay out horizontally on wide containers, labels move above the bars on phones, and every number is available as text for screen readers.

DashboardsComponentTailwind v4

Source

"use client";

import * as React from "react";
import { ArrowDownRight, ArrowUpRight, TrendingDown } from "lucide-react";
import { cn } from "@/lib/utils";

export type FunnelStage = { label: string; value: number };

export type DropOffFunnelProps = {
  stages: FunnelStage[];
  /** The same stages for an earlier period, drawn as an outlined ghost with per-stage deltas. */
  compare?: FunnelStage[];
  compareLabel?: string;
  format?: (value: number) => string;
  /** "auto" goes horizontal when the container is at least 960px wide. */
  orientation?: "auto" | "vertical" | "horizontal";
  highlightLargestDrop?: boolean;
  onStageClick?: (stage: FunnelStage, index: number) => void;
  /** Accessible name for the funnel. */
  title?: string;
  className?: string;
};

const number = new Intl.NumberFormat("en");
const pct = (share: number) => `${share >= 0.1 || share === 0 ? Math.round(share * 100) : (share * 100).toFixed(1)}%`;
const signed = (share: number) => `${share > 0 ? "+" : share < 0 ? "−" : ""}${Math.abs(share * 100).toFixed(1)}%`;
const MIN_SHARE = 0.06;
const BAR = 46;
const BRIDGE = 40;

const stageColor = (index: number, count: number) => {
  const t = count > 1 ? index / (count - 1) : 0;
  return `color-mix(in oklch, var(--chart-1) ${Math.round((1 - t) * 100)}%, var(--chart-2))`;
};
const DANGER = "color-mix(in oklab, var(--destructive) 70%, var(--card))";

/** Outline of the curved bridge between two stage extents (0–1 shares of the full width), in a 100 × 100 box. */
function bridgePath(a: number, b: number, horizontal: boolean) {
  const a0 = 50 - a * 50;
  const a1 = 50 + a * 50;
  const b0 = 50 - b * 50;
  const b1 = 50 + b * 50;
  if (!horizontal) return `M ${a0} 0 C ${a0} 55, ${b0} 45, ${b0} 100 L ${b1} 100 C ${b1} 45, ${a1} 55, ${a1} 0 Z`;
  return `M 0 ${a0} C 55 ${a0}, 45 ${b0}, 100 ${b0} L 100 ${b1} C 45 ${b1}, 55 ${a1}, 0 ${a1} Z`;
}
function bridgeSides(a: number, b: number, horizontal: boolean) {
  const a0 = 50 - a * 50;
  const a1 = 50 + a * 50;
  const b0 = 50 - b * 50;
  const b1 = 50 + b * 50;
  if (!horizontal) return [`M ${a0} 0 C ${a0} 55, ${b0} 45, ${b0} 100`, `M ${a1} 0 C ${a1} 55, ${b1} 45, ${b1} 100`];
  return [`M 0 ${a0} C 55 ${a0}, 45 ${b0}, 100 ${b0}`, `M 0 ${a1} C 55 ${a1}, 45 ${b1}, 100 ${b1}`];
}

function useInView<T extends Element>() {
  const ref = React.useRef<T>(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    const node = ref.current;
    if (!node || typeof IntersectionObserver === "undefined") return setSeen(true);
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setSeen(true);
        observer.disconnect();
      }
    }, { threshold: 0.2 });
    observer.observe(node);
    return () => observer.disconnect();
  }, []);
  return [ref, seen] as const;
}

/** 0 → 1 over a short ease-out once `start` is true; 1 straight away when motion is reduced. Timer-backed so it also
    finishes in pages that are not painting. */
function useReveal(start: boolean, ms = 750) {
  const [progress, setProgress] = React.useState(0);
  React.useEffect(() => {
    if (!start) return;
    if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return setProgress(1);
    const began = performance.now();
    let frame = 0;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const tick = () => {
      cancelAnimationFrame(frame);
      clearTimeout(timer);
      const t = Math.min(1, (performance.now() - began) / ms);
      setProgress(1 - (1 - t) ** 3);
      if (t < 1) {
        frame = requestAnimationFrame(tick);
        timer = setTimeout(tick, 34);
      }
    };
    tick();
    return () => {
      cancelAnimationFrame(frame);
      clearTimeout(timer);
    };
  }, [start, ms]);
  return progress;
}

function useWidth<T extends Element>(ref: React.RefObject<T | null>) {
  const [width, setWidth] = React.useState(0);
  React.useLayoutEffect(() => {
    const node = ref.current;
    if (!node) return;
    const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
    observer.observe(node);
    return () => observer.disconnect();
  }, [ref]);
  return width;
}

export function DropOffFunnel({
  stages,
  compare,
  compareLabel = "previous period",
  format = (value) => number.format(value),
  orientation = "auto",
  highlightLargestDrop = true,
  onStageClick,
  title = "Conversion funnel",
  className,
}: DropOffFunnelProps) {
  const [ref, seen] = useInView<HTMLDivElement>();
  const width = useWidth(ref);
  const horizontal = orientation === "horizontal" || (orientation === "auto" && width >= 960);
  const uid = React.useId();

  const first = Math.max(stages[0]?.value ?? 0, 1e-9);
  const compareFirst = compare?.[0]?.value || 0;
  const scaleBase = Math.max(first, compareFirst);
  const share = (value: number) => Math.max(MIN_SHARE, Math.min(1, value / scaleBase));

  const drops = stages.slice(1).map((stage, index) => {
    const before = stages[index].value;
    const lost = Math.max(0, before - stage.value);
    return { lost, rate: before > 0 ? lost / before : 0 };
  });
  const largest = highlightLargestDrop && drops.length
    ? drops.reduce((best, drop, index) => (drop.rate > drops[best].rate ? index : best), 0)
    : -1;

  const description = largest >= 0
    ? `Largest drop is between ${stages[largest].label} and ${stages[largest + 1].label}: ${pct(drops[largest].rate)}, ${format(drops[largest].lost)} lost.`
    : undefined;

  const reveal = useReveal(seen);
  const grow = "origin-center";
  const growStyle: React.CSSProperties = { transform: reveal >= 1 ? "none" : horizontal ? `scaleY(${reveal})` : `scaleX(${reveal})` };

  const delta = (index: number) => {
    const before = compare?.[index]?.value;
    if (before == null || before === 0) return null;
    const change = (stages[index].value - before) / before;
    const up = change >= 0;
    const Icon = up ? ArrowUpRight : ArrowDownRight;
    return (
      <span
        className={cn(
          "inline-flex items-center gap-0.5 rounded px-1 text-[11px] font-medium tabular-nums",
          up ? "bg-emerald-500/12 text-emerald-700 dark:text-emerald-300" : "bg-destructive/10 text-destructive",
        )}
      >
        <Icon aria-hidden="true" className="size-3" />
        {signed(change)}
        <span className="sr-only"> versus {compareLabel}</span>
      </span>
    );
  };

  const chip = (index: number, stacked = false) => {
    const drop = drops[index];
    const worst = index === largest;
    return (
      <span
        className={cn(
          "pointer-events-none inline-flex items-center gap-1 whitespace-nowrap rounded-full border px-2 py-0.5 text-[11px] font-medium tabular-nums shadow-sm",
          worst ? "border-destructive/40 bg-card text-destructive" : "border-border bg-card text-muted-foreground",
          stacked && "flex-col gap-0 rounded-lg px-1.5 py-1 leading-tight",
        )}
      >
        {worst && <TrendingDown aria-hidden="true" className={cn("size-3", stacked && "hidden")} />}
        <span>−{pct(drop.rate)}</span>
        <span className={stacked ? "font-normal" : "font-normal before:mr-1 before:content-['/']"}>{format(drop.lost)} lost</span>
      </span>
    );
  };

  const label = (stage: FunnelStage, index: number) => (
    <>
      <span className="block truncate text-sm font-medium text-foreground">{stage.label}</span>
      <span className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1">
        <span className="text-sm font-semibold tabular-nums text-foreground">{format(stage.value)}</span>
        <span className="text-xs tabular-nums text-muted-foreground">{pct(stage.value / first)}</span>
        {delta(index)}
      </span>
    </>
  );

  const srText = (stage: FunnelStage, index: number) =>
    `${stage.label}: ${format(stage.value)}, ${pct(stage.value / first)} of ${stages[0].label}` +
    (index > 0 ? `, ${pct(drops[index - 1].rate)} drop from previous step, ${format(drops[index - 1].lost)} lost` : "") +
    (index - 1 === largest ? " (largest drop)" : "") +
    (compare?.[index] ? `, ${format(compare[index].value)} in ${compareLabel}` : "");

  const stageWrap = (index: number, children: React.ReactNode) => {
    const stage = stages[index];
    if (!onStageClick) return children;
    return (
      <button
        type="button"
        onClick={() => onStageClick(stage, index)}
        className="group/stage block w-full rounded-lg text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
      >
        {children}
      </button>
    );
  };

  /* ---------------- horizontal ---------------- */
  if (horizontal) {
    return (
      <div ref={ref} className={cn("min-w-0", className)}>
        <ol role="list" aria-label={title} aria-description={description} className="flex items-stretch">
          {stages.map((stage, index) => {
            const s = share(stage.value);
            const ghost = compare?.[index] ? share(compare[index].value) : null;
            const color = stageColor(index, stages.length);
            const next = stages[index + 1];
            return (
              <React.Fragment key={stage.label}>
                <li role="listitem" className="min-w-0 flex-1">
                  {stageWrap(index, <>
                    <span className="sr-only">{srText(stage, index)}</span>
                    <span aria-hidden="true" className="block h-16 px-1">{label(stage, index)}</span>
                    <span aria-hidden="true" className="relative block h-56">
                      <span
                        className={cn("absolute inset-x-0 top-1/2 -translate-y-1/2 block", grow, index === 0 && "rounded-l-lg", !next && "rounded-r-lg")}
                        style={{ height: `${s * 100}%`, background: color, ...growStyle }}
                      />
                      {ghost != null && (
                        <span
                          className={cn("absolute inset-x-0 top-1/2 block -translate-y-1/2 border-y border-dashed border-foreground/45", index === 0 && "border-l rounded-l-lg", !next && "border-r rounded-r-lg")}
                          style={{ height: `${ghost * 100}%` }}
                        />
                      )}
                    </span>
                  </>)}
                </li>
                {next && (
                  <li role="presentation" aria-hidden="true" className="relative w-[72px] shrink-0 pt-16">
                    <span className="relative block h-56">
                      <BridgeSvg
                        a={s}
                        b={share(next.value)}
                        ghostA={ghost}
                        ghostB={compare?.[index + 1] ? share(compare[index + 1].value) : null}
                        from={color}
                        to={stageColor(index + 1, stages.length)}
                        danger={index === largest}
                        horizontal
                        id={`${uid}-${index}`}
                        className={grow}
                        style={growStyle}
                      />
                      <span className="absolute left-1/2 top-1/2 z-10 -translate-x-1/2 -translate-y-1/2">{chip(index, true)}</span>
                    </span>
                    {index === largest && (
                      <span className="absolute inset-x-0 bottom-[-1.75rem] text-center text-[11px] font-medium text-destructive">Largest drop</span>
                    )}
                  </li>
                )}
              </React.Fragment>
            );
          })}
        </ol>
        {compare && <Legend compareLabel={compareLabel} className="mt-10" />}
      </div>
    );
  }

  /* ---------------- vertical ---------------- */
  return (
    <div ref={ref} className={cn("@container min-w-0", className)}>
      <ol role="list" aria-label={title} aria-description={description} className="grid">
        {stages.map((stage, index) => {
          const s = share(stage.value);
          const ghost = compare?.[index] ? share(compare[index].value) : null;
          const color = stageColor(index, stages.length);
          const next = stages[index + 1];
          return (
            <li role="listitem" key={stage.label} className="min-w-0">
              {stageWrap(index, <>
                <span className="sr-only">{srText(stage, index)}</span>
                <span aria-hidden="true" className="grid items-center gap-x-6 gap-y-1.5 @xl:grid-cols-[13rem_minmax(0,1fr)]">
                  <span className="block min-w-0 pt-2 @xl:pt-0">{label(stage, index)}</span>
                  <span className="relative block" style={{ height: BAR }}>
                    <span
                      className={cn(
                        "absolute inset-y-0 left-1/2 block -translate-x-1/2 motion-safe:group-hover/stage:brightness-110",
                        grow,
                        "rounded-md @xl:rounded-none",
                        index === 0 && "@xl:rounded-t-lg",
                        !next && "@xl:rounded-b-lg",
                      )}
                      style={{ width: `${s * 100}%`, background: color, ...growStyle }}
                    />
                    {ghost != null && (
                      <span
                        className={cn(
                          "absolute inset-y-0 left-1/2 block -translate-x-1/2 rounded-md border border-dashed border-foreground/45",
                          "@xl:rounded-none @xl:border-y-0",
                          index === 0 && "@xl:rounded-t-lg @xl:border-t",
                          !next && "@xl:rounded-b-lg @xl:border-b",
                        )}
                        style={{ width: `${ghost * 100}%` }}
                      />
                    )}
                  </span>
                </span>
              </>)}
              {next && (
                <span aria-hidden="true" className="grid gap-x-6 @xl:grid-cols-[13rem_minmax(0,1fr)]">
                  <span className="hidden @xl:block" />
                  <span className="relative block" style={{ height: BRIDGE }}>
                    <BridgeSvg
                      a={s}
                      b={share(next.value)}
                      ghostA={ghost}
                      ghostB={compare?.[index + 1] ? share(compare[index + 1].value) : null}
                      from={color}
                      to={stageColor(index + 1, stages.length)}
                      danger={index === largest}
                      id={`${uid}-${index}`}
                      className={grow}
                      style={growStyle}
                    />
                    <span className="absolute left-1/2 top-1/2 z-10 flex -translate-x-1/2 -translate-y-1/2 items-center gap-2">
                      {chip(index)}
                    </span>
                    {index === largest && (
                      <span className="absolute right-0 top-1/2 hidden -translate-y-1/2 items-center gap-1 text-[11px] font-medium text-destructive @lg:flex">
                        <span className="h-px w-5 bg-destructive/50" />
                        Largest drop
                      </span>
                    )}
                  </span>
                </span>
              )}
            </li>
          );
        })}
      </ol>
      {compare && <Legend compareLabel={compareLabel} className="mt-5" />}
    </div>
  );
}

function Legend({ compareLabel, className }: { compareLabel: string; className?: string }) {
  return (
    <div aria-hidden="true" className={cn("flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground", className)}>
      <span className="inline-flex items-center gap-1.5">
        <span className="h-2.5 w-4 rounded-sm" style={{ background: "linear-gradient(90deg, var(--chart-1), var(--chart-2))" }} />
        This period
      </span>
      <span className="inline-flex items-center gap-1.5">
        <span className="h-2.5 w-4 rounded-sm border border-dashed border-foreground/50" />
        {compareLabel[0].toUpperCase() + compareLabel.slice(1)}
      </span>
    </div>
  );
}

function BridgeSvg({
  a, b, ghostA, ghostB, from, to, danger, horizontal = false, id, className, style,
}: {
  a: number; b: number; ghostA: number | null; ghostB: number | null; from: string; to: string; danger: boolean;
  horizontal?: boolean; id: string; className?: string; style?: React.CSSProperties;
}) {
  const gradient = `${id.replace(/[^a-zA-Z0-9-]/g, "")}-g`;
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" className={cn("absolute inset-0 size-full overflow-visible", horizontal ? "block" : "hidden @xl:block")}>
      <defs>
        <linearGradient id={gradient} x1="0" y1="0" x2={horizontal ? "1" : "0"} y2={horizontal ? "0" : "1"}>
          <stop offset="0%" style={{ stopColor: from }} />
          <stop offset="50%" style={{ stopColor: danger ? DANGER : from }} />
          <stop offset="100%" style={{ stopColor: to }} />
        </linearGradient>
      </defs>
      <g className={className} style={{ ...style, transformBox: "fill-box" }}>
        <path d={bridgePath(a, b, horizontal)} fill={`url(#${gradient})`} />
      </g>
      {ghostA != null && ghostB != null &&
        bridgeSides(ghostA, ghostB, horizontal).map((d) => (
          <path key={d} d={d} fill="none" stroke="currentColor" strokeWidth="1" strokeDasharray="3 3" vectorEffect="non-scaling-stroke" className="text-foreground/45" />
        ))}
    </svg>
  );
}