{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "retention-02",
  "description": "Every cohort's retention curve, with one highlighted against the average and where the average levels off.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "card",
    "button",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/chart-panel.json",
    "https://www.dashboardblocks.com/r/radix/kpi.json",
    "https://www.dashboardblocks.com/r/radix/link.json",
    "https://www.dashboardblocks.com/r/radix/retention.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/retention/retention-02.tsx",
      "content": "'use client'\n\nimport {\n  BlockStateProvider,\n  type BlockStateProps,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartPlaceholder,\n  ChartTooltipContent,\n  chartActiveDot,\n  chartAxisProps,\n  chartFadedColor,\n  chartGridProps,\n  chartLineCursor,\n  chartReferenceLabel,\n  chartReferenceProps,\n  chartValueAxisWidth,\n  useChartId,\n} from '@/registry/components/dashboardblocks/chart'\nimport {\n  ChartPanelFigure,\n  ChartPanelLegend,\n  ChartPanelTable,\n} from '@/registry/components/dashboardblocks/chart-panel'\nimport { KPIValue } from '@/registry/components/dashboardblocks/kpi'\nimport { Link } from '@/registry/components/dashboardblocks/link'\nimport {\n  RetentionChange,\n  type RetentionCohort,\n  getAverageRetention,\n  getPlateau,\n  getRetentionRates,\n} from '@/registry/components/dashboardblocks/retention'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { formatPercent } from '@/registry/lib/dashboardblocks/format'\nimport {\n  Area,\n  CartesianGrid,\n  ComposedChart,\n  Line,\n  ReferenceLine,\n  ResponsiveContainer,\n  Tooltip,\n  XAxis,\n  YAxis,\n} from 'recharts'\n\nimport { buttonVariants } from '@/components/ui/button'\nimport { Card, CardContent } from '@/components/ui/card'\n\nimport { cn } from '@/lib/utils'\n\ninterface Retention2Props extends BlockStateProps {\n  /** Oldest first. Leave out, or pass none, to show the empty state. */\n  cohorts?: RetentionCohort[]\n  description: string\n  highlight?: number\n  /** Where the chart opens in full, such as the explorer it was saved from. */\n  link?: { href: string; label: string }\n  /** @default 'Month' */\n  periodName?: string\n  title: string\n}\n\nconst COHORT_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']\nconst COHORT_SIZES = [1_184, 1_246, 1_402, 1_318, 1_527, 1_611, 1_489, 1_702]\n\nconst exampleProps: Retention2Props = {\n  cohorts: COHORT_NAMES.map((name, index) => {\n    const size = COHORT_SIZES[index]\n    const floor = index < 4 ? 0.2 + index * 0.006 : 0.27 + (index - 4) * 0.015\n    return {\n      label: `${name} 2026`,\n      retained: Array.from({ length: COHORT_NAMES.length + 1 - index }, (_, month) => {\n        if (month === 0) return size\n        const rate = floor + (0.6 - floor) * Math.exp(-(month - 1) / 1.3)\n        return Math.round(size * (rate + Math.sin(index * 1.9 + month) * 0.01))\n      }),\n      size,\n    }\n  }),\n  description:\n    'Share of each monthly signup cohort still active, by months since signup.',\n  highlight: 4,\n  link: { href: '/dashboard/retention', label: 'Open in Retention' },\n  periodName: 'Month',\n  title: 'Retention curves',\n}\n\nconst Retention2 = (props: Retention2Props) => {\n  const {\n    cohorts = [],\n    description,\n    periodName = 'Month',\n    errorMessage,\n    link,\n    status,\n    title,\n  } = props\n  const state = getBlockState(status, cohorts)\n  let fallback = cohorts.length - 1\n  while (fallback > 0 && cohorts[fallback].retained.length < 2) fallback--\n  const highlight = props.highlight ?? Math.max(0, fallback)\n  const selected = cohorts[highlight]\n  const averages = getAverageRetention(cohorts)\n  const unit = periodName.toLowerCase()\n\n  const rates = cohorts.map(getRetentionRates)\n  const rows = averages.map((average, period) => {\n    const row: Record<string, number | null> = { average, period }\n    rates.forEach((cohortRates, index) => {\n      row[`c${index}`] = cohortRates[period] ?? null\n    })\n    return row\n  })\n\n  const latest = Math.max(0, (selected?.retained.length ?? 1) - 1)\n  const selectedRate = rates[highlight]?.[latest] ?? 0\n  const averageRate = averages[latest] ?? 0\n  const plateau = getPlateau(averages)\n  const format = (value: number) => formatPercent(value, { maximumFractionDigits: 0 })\n  const gradientId = useChartId()\n  const otherCohortColor = chartFadedColor('var(--color-muted-foreground)')\n\n  return (\n    <BlockStateProvider errorMessage={errorMessage} state={state}>\n      <Card>\n        <CardContent>\n          <section className='@container flex flex-col gap-4'>\n            <header className='flex items-start justify-between gap-3'>\n              <div className='flex min-w-0 flex-col gap-0.5'>\n                <h2 className='font-semibold tracking-tight'>{title}</h2>\n                <p className='text-muted-foreground text-sm'>{description}</p>\n              </div>\n              {link && (\n                <Link\n                  href={link.href}\n                  className={cn(\n                    buttonVariants({ size: 'xs', variant: 'outline' }),\n                    'group/open shrink-0',\n                  )}\n                >\n                  {link.label}\n                  <IconPlaceholder\n                    lucide='ArrowRightIcon'\n                    tabler='IconArrowRight'\n                    hugeicons='ArrowRight01Icon'\n                    phosphor='ArrowRightIcon'\n                    remixicon='RiArrowRightLine'\n                    className='transition-transform group-hover/open:translate-x-0.5 motion-reduce:transition-none'\n                    data-icon='inline-end'\n                    aria-hidden\n                  />\n                </Link>\n              )}\n            </header>\n            <dl className='grid grid-cols-2 gap-x-6 gap-y-4 border-t pt-4 @lg:grid-cols-3 @lg:items-start'>\n              <div className='col-span-2 flex flex-col gap-1 @lg:col-span-1'>\n                <dt className='text-muted-foreground text-sm'>\n                  {selected && !state\n                    ? `${selected.label}, ${unit} ${latest}`\n                    : 'Latest cohort'}\n                </dt>\n                <dd>\n                  <KPIValue value={selected ? selectedRate : undefined} format={format} />\n                </dd>\n                <dd>\n                  <RetentionChange\n                    difference={selectedRate - averageRate}\n                    versus='against the average'\n                  />\n                </dd>\n              </div>\n              {state === 'loading' && (\n                <>\n                  <div className='flex flex-col gap-1'>\n                    <dt className='text-muted-foreground text-sm'>Average</dt>\n                    <dd>\n                      <KPIValue className='text-2xl' value={undefined} />\n                    </dd>\n                  </div>\n                  <div className='flex flex-col gap-1'>\n                    <dt className='text-muted-foreground text-sm'>Levels off</dt>\n                    <dd>\n                      <KPIValue className='text-2xl' value={undefined} />\n                    </dd>\n                  </div>\n                </>\n              )}\n              {!state && (\n                <>\n                  <div className='flex flex-col gap-1'>\n                    <dt className='text-muted-foreground text-sm'>\n                      Average, {unit} {latest}\n                    </dt>\n                    <dd className='text-2xl font-light tracking-tight tabular-nums'>\n                      {format(averageRate)}\n                    </dd>\n                  </div>\n                  <div className='flex flex-col gap-1'>\n                    <dt className='text-muted-foreground text-sm'>Levels off</dt>\n                    <dd className='text-2xl font-light tracking-tight tabular-nums'>\n                      {plateau ? `${periodName} ${plateau.period}` : 'Not yet'}\n                    </dd>\n                    {plateau && (\n                      <dd className='text-muted-foreground text-xs'>\n                        at about {format(plateau.rate)} retained\n                      </dd>\n                    )}\n                  </div>\n                </>\n              )}\n            </dl>\n            {(!state || state === 'loading') && (\n              <ChartPanelLegend\n                items={[\n                  {\n                    color: 'var(--color-chart-2)',\n                    label: selected?.label ?? '',\n                    shape: 'line',\n                  },\n                  { color: 'var(--color-foreground)', label: 'Average', shape: 'line' },\n                  {\n                    color: otherCohortColor,\n                    label: 'Other cohorts',\n                    shape: 'line',\n                  },\n                ]}\n              />\n            )}\n            {state ? (\n              <ChartPlaceholder height={240} />\n            ) : (\n              <>\n                <ChartPanelFigure className='h-60'>\n                  <ResponsiveContainer width='100%' height='100%'>\n                    <ComposedChart\n                      aria-label={title}\n                      data={rows}\n                      margin={{ top: 8, right: 12, bottom: 0, left: 0 }}\n                    >\n                      <defs>\n                        <linearGradient id={gradientId} x1='0' y1='0' x2='0' y2='1'>\n                          <stop\n                            offset='0%'\n                            stopColor='var(--color-chart-2)'\n                            stopOpacity={0.3}\n                          />\n                          <stop\n                            offset='100%'\n                            stopColor='var(--color-chart-2)'\n                            stopOpacity={0}\n                          />\n                        </linearGradient>\n                      </defs>\n                      <CartesianGrid {...chartGridProps} />\n                      <XAxis\n                        {...chartAxisProps}\n                        dataKey='period'\n                        tickFormatter={(value: number) =>\n                          `${periodName.charAt(0).toUpperCase()}${value}`\n                        }\n                      />\n                      <YAxis\n                        {...chartAxisProps}\n                        domain={[0, 1]}\n                        tickFormatter={format}\n                        ticks={[0, 0.25, 0.5, 0.75, 1]}\n                        width={chartValueAxisWidth}\n                      />\n                      {plateau && (\n                        <ReferenceLine\n                          {...chartReferenceProps}\n                          x={plateau.period}\n                          label={{\n                            ...chartReferenceLabel,\n                            position: 'insideTopRight',\n                            value: 'Levels off',\n                          }}\n                        />\n                      )}\n                      <Tooltip\n                        content={({ active, label, payload }) => (\n                          <ChartTooltipContent\n                            active={active}\n                            formatLabel={(value) => `${periodName} ${value}`}\n                            label={label}\n                            payload={payload?.filter(\n                              (item) =>\n                                item.dataKey === 'average' ||\n                                item.dataKey === `c${highlight}`,\n                            )}\n                            valueFormatter={(value) => formatPercent(value)}\n                          />\n                        )}\n                        cursor={chartLineCursor}\n                      />\n                      {cohorts.map((cohort, index) =>\n                        index === highlight ? null : (\n                          <Line\n                            key={cohort.label}\n                            activeDot={false}\n                            dataKey={`c${index}`}\n                            dot={false}\n                            name={cohort.label}\n                            stroke={otherCohortColor}\n                            strokeWidth={1}\n                            type='monotone'\n                          />\n                        ),\n                      )}\n                      <Line\n                        activeDot={chartActiveDot}\n                        dataKey='average'\n                        dot={false}\n                        name='Average'\n                        stroke='var(--color-foreground)'\n                        strokeDasharray='4 3'\n                        strokeWidth={2}\n                        type='monotone'\n                      />\n                      <Area\n                        activeDot={chartActiveDot}\n                        dataKey={`c${highlight}`}\n                        dot={{ fill: 'var(--color-chart-2)', r: 2.5, strokeWidth: 0 }}\n                        fill={`url(#${gradientId})`}\n                        fillOpacity={1}\n                        name={selected?.label}\n                        stroke='var(--color-chart-2)'\n                        strokeLinecap='round'\n                        strokeWidth={2.5}\n                        type='monotone'\n                      />\n                    </ComposedChart>\n                  </ResponsiveContainer>\n                </ChartPanelFigure>\n                <ChartPanelTable\n                  caption={`${title}: ${description} The average is weighted by cohort size.`}\n                  columns={[\n                    { key: 'label', label: periodName },\n                    { format, key: 'average', label: 'Average' },\n                    ...cohorts.map((cohort, index) => ({\n                      format,\n                      key: `c${index}`,\n                      label: cohort.label,\n                    })),\n                  ]}\n                  rows={rows.map((row) => {\n                    const cells: Record<string, number | string> = {\n                      label: `${periodName} ${row.period}`,\n                    }\n                    for (const [key, value] of Object.entries(row)) {\n                      if (key !== 'period') cells[key] = value ?? '—'\n                    }\n                    return cells\n                  })}\n                />\n              </>\n            )}\n          </section>\n        </CardContent>\n      </Card>\n    </BlockStateProvider>\n  )\n}\n\nexport { Retention2, exampleProps as retention2ExampleProps, type Retention2Props }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/retention/retention-02.tsx"
    }
  ],
  "meta": {
    "shows": "Every cohort's retention curve, with one highlighted against the average and where the average levels off.",
    "size": "full",
    "usedWith": [
      "retention-01",
      "retention-04"
    ],
    "component": "Retention2",
    "props": "{ cohorts?: { label: string; size: number; retained: number[]; color?: string; icon?: ReactNode; eligible?: number[]; filling?: boolean }[]; description: string; highlight?: number; link?: { href: string; label: string }; periodName?: string; title: string; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
