{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "retention",
  "title": "Retention",
  "description": "Primitives for retention: rates per cohort, a size-weighted average curve, where the curve levels off, the growth accounting quick ratio, a shaded cohort table with a hover tooltip, a bar and a change in percentage points.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/change-amount.json",
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/heatmap.json",
    "https://www.dashboardblocks.com/r/radix/use-reveal.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/retention.tsx",
      "content": "'use client'\n\nimport {\n  BlockStateText,\n  useBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport { ChangeAmount } from '@/registry/components/dashboardblocks/change-amount'\nimport {\n  ChartFloatingTooltip,\n  chartHatchFill,\n  ChartTooltipItem,\n} from '@/registry/components/dashboardblocks/chart'\nimport { getHeatColor } from '@/registry/components/dashboardblocks/heatmap'\nimport { useReveal } from '@/registry/hooks/use-reveal'\nimport {\n  formatNumber,\n  formatPercent,\n  formatPoints,\n} from '@/registry/lib/dashboardblocks/format'\nimport {\n  type FocusEvent,\n  Fragment,\n  type PointerEvent,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\ninterface RetentionCohort {\n  label: string\n  size: number\n  /** How many were still active in each period since joining, starting with period 0. */\n  retained: number[]\n  /** A swatch before the label, tying the row to its line in a chart. */\n  color?: string\n  /** Shown before the label, after the swatch, such as a country's flag. */\n  icon?: ReactNode\n  /**\n   * How many were old enough to reach each period, starting with period 0. A row that groups\n   * cohorts (one per source, say) needs it: its later periods count only its older cohorts.\n   * @default `size` for every period\n   */\n  eligible?: number[]\n  /** `true` when the last period hasn't ended, so its count can still grow: it's striped and left out of the average. */\n  filling?: boolean\n}\n\nfunction getEligible(cohort: RetentionCohort, period: number) {\n  return cohort.eligible?.[period] ?? cohort.size\n}\n\nfunction getRetentionRates(cohort: RetentionCohort) {\n  return cohort.retained.map((count, period) => {\n    const eligible = getEligible(cohort, period)\n    return eligible > 0 ? count / eligible : 0\n  })\n}\n\nfunction getAverageRetention(cohorts: RetentionCohort[]) {\n  const periods = Math.max(0, ...cohorts.map((cohort) => cohort.retained.length))\n  return Array.from({ length: periods }, (_, period) => {\n    let retained = 0\n    let size = 0\n    for (const cohort of cohorts) {\n      const complete = cohort.filling\n        ? cohort.retained.length - 1\n        : cohort.retained.length\n      if (period >= Math.max(complete, 1)) continue\n      retained += cohort.retained[period]\n      size += getEligible(cohort, period)\n    }\n    return size > 0 ? retained / size : null\n  })\n}\n\n/**\n * The first period after which retention holds: the next period drops by less than `threshold` of\n * the rate, and no later one falls more than twice that below it. `null` when it never does.\n */\nfunction getPlateau(rates: (number | null)[], threshold = 0.05) {\n  for (let period = 1; period < rates.length - 1; period++) {\n    const rate = rates[period]\n    const next = rates[period + 1]\n    if (rate === null || next === null) return null\n    if (rate - next >= rate * threshold) continue\n    const later = rates.slice(period + 1).filter((value) => value !== null)\n    if (Math.min(...later) >= rate * (1 - 2 * threshold)) return { period, rate }\n  }\n  return null\n}\n\ninterface GrowthAccountingInput {\n  churned: number\n  new: number\n  resurrected: number\n}\n\nfunction getQuickRatio({ churned, new: added, resurrected }: GrowthAccountingInput) {\n  const gained = added + resurrected\n  return churned > 0 ? gained / churned : gained > 0 ? Infinity : 0\n}\n\ninterface RetentionChangeProps {\n  className?: string\n  /** The difference between two 0–1 shares, e.g. */\n  difference: number\n  /** Ends the sentence, such as `from 56.1% in July`. */\n  versus?: string\n}\n\nfunction RetentionChange({ className, difference, versus }: RetentionChangeProps) {\n  const state = useBlockState()\n  const points = Math.round(difference * 1000) / 10\n  if (state === 'loading') {\n    return <BlockStateText className={cn('text-sm', className)} />\n  }\n  if (state) return null\n\n  return (\n    <span className={cn('text-muted-foreground text-sm', className)}>\n      <ChangeAmount\n        change={points}\n        className={cn(\n          'font-medium tabular-nums',\n          points > 0 && 'text-emerald-700 dark:text-emerald-400',\n          points < 0 && 'text-red-700 dark:text-red-400',\n        )}\n      >\n        {formatPoints(Math.abs(points))}\n      </ChangeAmount>\n      {versus && <> {versus}</>}\n    </span>\n  )\n}\n\ninterface CohortCell {\n  period: number\n  row: number | 'average'\n}\n\n/** A cohort's cell: `row` is the cohort's index in `cohorts`, `period` counts from 0. */\ninterface CohortCellPosition {\n  period: number\n  row: number\n}\n\ninterface HoveredCell extends CohortCell {\n  flip: boolean\n  x: number\n  y: number\n}\n\ninterface CohortTableProps {\n  /** A note under the table, such as a summary. */\n  children?: ReactNode\n  average?: boolean\n  /** @default 'Average' */\n  averageLabel?: string\n  /** The count beside the average row. @default the mean cohort size */\n  averageSize?: number\n  caption: string\n  className?: string\n  /** @default 'Cohort' */\n  cohortHeader?: string\n  cohorts: RetentionCohort[]\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  describeCell?: (cell: {\n    cohort: RetentionCohort | null\n    period: number\n    rate: number\n  }) => string\n  formatCount?: (value: number) => string\n  footer?: ReactNode\n  label?: string\n  /** Keeps cells legible in narrow cards: below this width the table scrolls sideways. */\n  minWidth?: string\n  mode?: 'percent' | 'count'\n  /**\n   * Makes each cohort's cells after period 0 buttons. Called with the cell clicked, or `null` when\n   * the selected cell is clicked again.\n   */\n  onCellSelect?: (cell: CohortCellPosition | null) => void\n  /** Called with the cohort row under the pointer, or `null` when it leaves the table. */\n  onRowHover?: (row: number | null) => void\n  periodName?: string\n  scaleMax?: number\n  /** The share that gets the faintest colour, for tables whose shares sit in a narrow band, such as revenue around 100%. */\n  scaleMin?: number\n  /** The open cell, drawn in `color` while the rest fade. */\n  selected?: CohortCellPosition | null\n  /** Shown across the table under the open cell's row, such as the people in it. It stays in view while the cells scroll sideways. */\n  selectedDetail?: ReactNode\n  /** @default 'Users' */\n  sizeHeader?: string\n}\n\nfunction CohortTable({\n  average = true,\n  averageLabel = 'Average',\n  averageSize: averageSizeProp,\n  caption,\n  children,\n  className,\n  cohortHeader = 'Cohort',\n  cohorts,\n  color,\n  describeCell,\n  footer,\n  formatCount = (value) => formatNumber(value),\n  label = caption,\n  minWidth,\n  mode = 'percent',\n  onCellSelect,\n  onRowHover,\n  periodName = 'Period',\n  scaleMax: scaleMaxProp,\n  scaleMin: scaleMinProp = 0,\n  selected = null,\n  selectedDetail,\n  sizeHeader = 'Users',\n}: CohortTableProps) {\n  const frame = useRef<HTMLDivElement>(null)\n  const view = useRef<HTMLDivElement>(null)\n  const [viewWidth, setViewWidth] = useState<number>()\n  const [hovered, setHovered] = useState<HoveredCell | null>(null)\n  const [open, setOpen] = useState(false)\n\n  const averages = getAverageRetention(cohorts)\n  const periods = averages.length\n  const total = cohorts.reduce((sum, cohort) => sum + cohort.size, 0)\n  const averageSize =\n    averageSizeProp ?? (cohorts.length > 0 ? Math.round(total / cohorts.length) : 0)\n  const later = cohorts.flatMap((cohort) => getRetentionRates(cohort).slice(1))\n  const scaleMax = scaleMaxProp ?? (later.length > 0 ? Math.max(...later) : 1)\n  const scaleMin = scaleMinProp < scaleMax ? scaleMinProp : 0\n  const scaleRange = scaleMax - scaleMin\n  const unit = periodName.toLowerCase()\n  const shortName = periodName.charAt(0).toUpperCase()\n\n  const rateOf = ({ period, row }: CohortCell) =>\n    row === 'average'\n      ? (averages[period] ?? 0)\n      : (getRetentionRates(cohorts[row])[period] ?? 0)\n\n  const heatOf = (rate: number) =>\n    getHeatColor(scaleRange > 0 ? (rate - scaleMin) / scaleRange : 0, color)\n\n  const cellName = ({ period, row }: CohortCell) =>\n    `${row === 'average' ? averageLabel : cohorts[row].label}, ${unit} ${period}`\n\n  const describe = (cell: CohortCell) => {\n    const cohort = cell.row === 'average' ? null : cohorts[cell.row]\n    const rate = rateOf(cell)\n    if (describeCell) return describeCell({ cohort, period: cell.period, rate })\n    if (!cohort) return `${cellName(cell)}: ${formatPercent(rate)} retained`\n    return `${cellName(cell)}: ${formatCount(cohort.retained[cell.period])} of ${formatCount(getEligible(cohort, cell.period))} (${formatPercent(rate)})`\n  }\n\n  const buttonName = (cell: CohortCell, label: string) => {\n    const cohort = cell.row === 'average' ? null : cohorts[cell.row]\n    if (describeCell || !cohort) return `${label}, ${describe(cell)}`\n    return `${label}, ${cellName(cell)}: ${formatCount(cohort.retained[cell.period])} of ${formatCount(getEligible(cohort, cell.period))}`\n  }\n\n  const tooltipValue = (cell: CohortCell) => {\n    const text = describe(cell)\n    const prefix = `${cellName(cell)}: `\n    return text.startsWith(prefix) ? text.slice(prefix.length) : text\n  }\n\n  const showTooltip = (cell: CohortCell, target: HTMLElement) => {\n    const origin = frame.current?.getBoundingClientRect()\n    if (!origin) return\n    const box = target.getBoundingClientRect()\n    const x = box.left - origin.left + box.width / 2\n    setHovered({\n      ...cell,\n      flip: x > origin.width / 2,\n      x,\n      y: box.top - origin.top + box.height / 2,\n    })\n    setOpen(true)\n  }\n\n  const renderCell = (\n    row: CohortCell['row'],\n    period: number,\n    rate: number,\n    label: string,\n    filling = false,\n  ) => {\n    const cell = { period, row }\n    const isSelected = selected?.row === row && selected.period === period\n    const selectable = onCellSelect && row !== 'average' && period > 0\n    const hover = (event: PointerEvent<HTMLElement> | FocusEvent<HTMLElement>) =>\n      showTooltip(cell, event.currentTarget)\n    const base = color ?? 'var(--color-chart-2)'\n    const faded = selected !== null && !isSelected\n    const fade = (fill: string) =>\n      faded\n        ? `color-mix(in oklab, ${fill} var(--cohort-fade), var(--color-background))`\n        : fill\n    const style = {\n      backgroundColor: isSelected\n        ? `color-mix(in oklab, ${base} 80%, var(--color-foreground))`\n        : fade(heatOf(rate)),\n      backgroundImage: filling && !isSelected ? chartHatchFill(fade(base)) : undefined,\n    }\n    const tile = cn(\n      'h-8 min-w-11 rounded-[3px] px-1 text-center font-medium whitespace-nowrap transition-colors duration-200',\n      row === 'average' && 'font-semibold',\n      isSelected && 'text-background',\n    )\n    if (selectable) {\n      return (\n        // Not a data table: a tile of the cohort heatmap.\n        <td key={period} className='p-0'>\n          <button\n            type='button'\n            aria-label={buttonName(cell, label)}\n            aria-pressed={isSelected}\n            onPointerEnter={hover}\n            onFocus={hover}\n            onBlur={() => setOpen(false)}\n            onClick={() => {\n              setOpen(false)\n              onCellSelect(isSelected ? null : { period, row })\n            }}\n            className={cn(\n              tile,\n              'focus-visible:ring-ring/50 w-full cursor-pointer outline-none focus-visible:ring-3',\n            )}\n            style={style}\n          >\n            {label}\n          </button>\n        </td>\n      )\n    }\n    return (\n      // Not a data table: a tile of the cohort heatmap.\n      <td\n        key={period}\n        onPointerEnter={hover}\n        onPointerDown={hover}\n        className={tile}\n        style={style}\n      >\n        {label}\n      </td>\n    )\n  }\n\n  const hasDetail = Boolean(selectedDetail) && selected !== null\n  useEffect(() => {\n    const node = view.current\n    if (!node || !minWidth || !hasDetail) return\n    const observer = new ResizeObserver(() => setViewWidth(node.clientWidth))\n    observer.observe(node)\n    return () => observer.disconnect()\n  }, [hasDetail, minWidth])\n\n  const emptyCell = (period: number) => (\n    // Not a data table: a tile of the cohort heatmap.\n    <td key={period}>\n      <span className='sr-only'>Not reached yet</span>\n    </td>\n  )\n\n  const labelCell = cn(\n    'pr-2 text-left whitespace-nowrap',\n    minWidth && 'bg-background in-data-[slot=card]:bg-card sticky left-0 z-10',\n  )\n\n  return (\n    <div className={cn('flex flex-col gap-3', className)}>\n      <div\n        ref={frame}\n        className='relative'\n        onPointerLeave={() => {\n          setOpen(false)\n          onRowHover?.(null)\n        }}\n      >\n        <div\n          ref={view}\n          role={minWidth ? 'region' : undefined}\n          aria-label={minWidth ? label : undefined}\n          tabIndex={minWidth ? 0 : undefined}\n          className={cn(\n            minWidth &&\n              'focus-visible:ring-ring/50 relative -my-1 overflow-x-auto rounded-sm py-1 outline-none [scrollbar-width:thin] focus-visible:ring-3',\n          )}\n        >\n          {/* Not a data table: a heatmap chart, each cell a coloured tile with its own tooltip. */}\n          <table\n            className='w-full border-separate border-spacing-(--cohort-gap) text-xs tabular-nums [--cohort-fade:25%] [--cohort-gap:3px] dark:[--cohort-fade:55%]'\n            style={{ minWidth }}\n          >\n            <caption className='sr-only'>{caption}</caption>\n            <thead>\n              <tr className='text-muted-foreground'>\n                <th scope='col' className={cn(labelCell, 'font-normal')}>\n                  {cohortHeader}\n                </th>\n                <th scope='col' className='pr-2 text-right font-normal whitespace-nowrap'>\n                  {sizeHeader}\n                </th>\n                {averages.map((_, period) => (\n                  <th key={period} scope='col' className='font-normal whitespace-nowrap'>\n                    <span aria-hidden>\n                      {shortName}\n                      {period}\n                    </span>\n                    <span className='sr-only'>\n                      {periodName} {period}\n                    </span>\n                  </th>\n                ))}\n              </tr>\n            </thead>\n            <tbody>\n              {cohorts.map((cohort, row) => (\n                <Fragment key={cohort.label}>\n                  <tr onPointerEnter={onRowHover && (() => onRowHover(row))}>\n                    <th\n                      scope='row'\n                      className={cn(\n                        labelCell,\n                        'font-normal transition-colors',\n                        selected?.row === row\n                          ? 'text-foreground font-medium'\n                          : 'text-muted-foreground',\n                      )}\n                    >\n                      {cohort.color || cohort.icon ? (\n                        <span className='flex items-center gap-2'>\n                          {cohort.color && (\n                            <span\n                              aria-hidden\n                              className='size-2 shrink-0 rounded-xs'\n                              style={{ background: cohort.color }}\n                            />\n                          )}\n                          {cohort.icon}\n                          {cohort.label}\n                        </span>\n                      ) : (\n                        cohort.label\n                      )}\n                    </th>\n                    <td className='text-muted-foreground pr-2 text-right whitespace-nowrap'>\n                      {formatCount(cohort.size)}\n                    </td>\n                    {Array.from({ length: periods }, (_, period) => {\n                      if (period >= cohort.retained.length) return emptyCell(period)\n                      const count = cohort.retained[period]\n                      const eligible = getEligible(cohort, period)\n                      const rate = eligible > 0 ? count / eligible : 0\n                      const label =\n                        mode === 'percent'\n                          ? formatPercent(rate, { maximumFractionDigits: 0 })\n                          : formatCount(count)\n                      const filling =\n                        cohort.filling &&\n                        period > 0 &&\n                        period === cohort.retained.length - 1\n                      return renderCell(row, period, rate, label, filling)\n                    })}\n                  </tr>\n                  {hasDetail && selected?.row === row && (\n                    <tr\n                      onPointerEnter={() => {\n                        setOpen(false)\n                        onRowHover?.(null)\n                      }}\n                    >\n                      <td colSpan={periods + 2} className='p-0'>\n                        <div\n                          className='sticky left-0 text-sm'\n                          style={{\n                            width:\n                              minWidth && viewWidth !== undefined\n                                ? `calc(${viewWidth}px - 2 * var(--cohort-gap))`\n                                : undefined,\n                          }}\n                        >\n                          {selectedDetail}\n                        </div>\n                      </td>\n                    </tr>\n                  )}\n                </Fragment>\n              ))}\n            </tbody>\n            {average && (\n              <tfoot>\n                <tr>\n                  <th scope='row' className={cn(labelCell, 'font-medium')}>\n                    {averageLabel}\n                  </th>\n                  <td className='pr-2 text-right font-medium whitespace-nowrap'>\n                    {formatCount(averageSize)}\n                  </td>\n                  {averages.map((rate, period) =>\n                    rate === null\n                      ? emptyCell(period)\n                      : renderCell(\n                          'average',\n                          period,\n                          rate,\n                          formatPercent(rate, { maximumFractionDigits: 0 }),\n                        ),\n                  )}\n                </tr>\n              </tfoot>\n            )}\n          </table>\n        </div>\n        {hovered && (\n          <ChartFloatingTooltip\n            active={open}\n            flip={hovered.flip}\n            x={hovered.x}\n            y={hovered.y}\n          >\n            <span className='font-medium'>{cellName(hovered)}</span>\n            <ChartTooltipItem\n              color={heatOf(rateOf(hovered))}\n              value={tooltipValue(hovered)}\n            />\n          </ChartFloatingTooltip>\n        )}\n      </div>\n      {(children || footer) && (\n        <div className='flex flex-wrap items-center justify-between gap-x-6 gap-y-2'>\n          {children && <p className='text-muted-foreground text-sm'>{children}</p>}\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n\ninterface RetentionBarProps {\n  animated?: boolean\n  className?: string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  /** 0–1. */\n  value: number\n}\n\nfunction RetentionBar({\n  animated = true,\n  className,\n  color = 'var(--color-chart-2)',\n  value,\n}: RetentionBarProps) {\n  const { ref, revealed } = useReveal(animated)\n  const state = useBlockState()\n\n  return (\n    <div\n      ref={ref}\n      aria-hidden\n      className={cn(\n        'bg-muted h-2 w-full overflow-hidden rounded-full',\n        state === 'loading' && 'animate-pulse motion-reduce:animate-none',\n        className,\n      )}\n    >\n      <div\n        className='h-full rounded-full transition-[width] duration-1000 ease-[cubic-bezier(0.33,1,0.68,1)] motion-reduce:transition-none'\n        style={{\n          backgroundColor: color,\n          width: `${(revealed && !state ? Math.min(1, Math.max(0, value)) : 0) * 100}%`,\n        }}\n      />\n    </div>\n  )\n}\n\nconst growthColors = {\n  churned: 'color-mix(in oklab, var(--color-destructive) 75%, var(--color-background))',\n  new: 'var(--color-chart-3)',\n  resurrected: 'var(--color-chart-4)',\n} as const\n\nexport {\n  CohortTable,\n  RetentionBar,\n  RetentionChange,\n  getAverageRetention,\n  getEligible,\n  getPlateau,\n  getQuickRatio,\n  getRetentionRates,\n  growthColors,\n}\n\nexport type {\n  CohortCellPosition,\n  CohortTableProps,\n  GrowthAccountingInput,\n  RetentionBarProps,\n  RetentionChangeProps,\n  RetentionCohort,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/retention.tsx"
    }
  ],
  "type": "registry:component"
}
