{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "heatmap-table",
  "title": "Heatmap Table",
  "description": "A cohort retention table coloured like a heatmap: one row per signup month, one column per month after, cells shaded by how many users stayed, a percent / users switch, a weighted average row and a crosshair that compares any cell with the average.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/heatmap-table/heatmap-table.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type TableTheme = \"dark\" | \"light\";\n\nexport interface HeatmapCohort {\n  label: string;\n  /** Starting size of the cohort. */\n  size: number;\n  /** Users still active in each period, starting with period 0 (usually the full size). */\n  retained: number[];\n}\n\nexport interface HeatmapTableProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: TableTheme;\n  title?: string;\n  subtitle?: string;\n  cohorts?: HeatmapCohort[];\n  /** Header prefix for the periods, e.g. \"Month\" → \"Month 0\", \"Month 1\"… */\n  periodLabel?: string;\n  /** Show percentages or user counts in the cells. */\n  mode?: \"percent\" | \"count\";\n  /** Colour of the strongest cells. */\n  color?: string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    faint: \"rgba(255,255,255,0.38)\",\n    head: \"#131315\",\n    empty: \"#141417\",\n    chip: \"rgba(255,255,255,0.06)\",\n    base: \"#16171C\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    accent: \"#6E9BFF\",\n    hi: \"rgba(255,255,255,0.05)\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.08)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    faint: \"rgba(17,19,23,0.4)\",\n    head: \"#F7F7F5\",\n    empty: \"#F7F7F5\",\n    chip: \"rgba(17,19,23,0.05)\",\n    base: \"#F1F3F8\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    accent: \"#2F6FE4\",\n    hi: \"rgba(17,19,23,0.04)\",\n  },\n};\n\n// Deterministic sample: monthly signup cohorts with a retention curve that slowly improves.\nfunction sampleCohorts(): HeatmapCohort[] {\n  let seed = 9;\n  const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;\n  const months = [\n    \"Jan\",\n    \"Feb\",\n    \"Mar\",\n    \"Apr\",\n    \"May\",\n    \"Jun\",\n    \"Jul\",\n    \"Aug\",\n    \"Sep\",\n    \"Oct\",\n  ];\n  return months.map((m, i) => {\n    const size = Math.round(1800 + rnd() * 1400 + i * 120);\n    const periods = months.length - i;\n    const lift = i * 0.012;\n    const retained = Array.from({ length: periods }, (_, k) => {\n      if (k === 0) return size;\n      const rate =\n        0.18 + lift + 0.42 * Math.exp(-k / 2.2) + (rnd() - 0.5) * 0.04;\n      return Math.round(size * Math.min(0.95, rate));\n    });\n    return { label: `${m} 2025`, size, retained };\n  });\n}\n\nconst DEFAULT_COHORTS = sampleCohorts();\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** 0 → 1 once the element scrolls into view. */\nfunction useReveal(\n  ref: React.RefObject<HTMLElement | null>,\n  reduce: boolean,\n  duration = 1100,\n) {\n  const [t, setT] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || reduce) return;\n    let raf = 0;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        const start = performance.now();\n        const tick = (now: number) => {\n          const k = Math.min(1, (now - start) / duration);\n          setT(k);\n          if (k < 1) raf = requestAnimationFrame(tick);\n        };\n        raf = requestAnimationFrame(tick);\n      },\n      { threshold: 0.2 },\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, reduce, duration]);\n  return reduce ? 1 : t;\n}\n\nfunction mix(a: string, b: string, t: number) {\n  const p = (h: string) => {\n    const s = h.replace(\"#\", \"\");\n    const f =\n      s.length === 3\n        ? s\n            .split(\"\")\n            .map((c) => c + c)\n            .join(\"\")\n        : s;\n    return [0, 2, 4].map((i) => parseInt(f.slice(i, i + 2), 16));\n  };\n  const [x, y] = [p(a), p(b)];\n  return `rgb(${x.map((v, i) => Math.round(v + (y[i] - v) * t)).join(\",\")})`;\n}\n\nconst luminance = (rgb: string) => {\n  const [r, g, b] = rgb.match(/\\d+/g)!.map(Number);\n  return (0.299 * r + 0.587 * g + 0.114 * b) / 255;\n};\n\nexport function HeatmapTable({\n  theme = \"dark\",\n  title = \"Retention by signup cohort\",\n  subtitle = \"Share of each month's signups still active in later months\",\n  cohorts = DEFAULT_COHORTS,\n  periodLabel = \"Month\",\n  mode: initialMode = \"percent\",\n  color,\n  className,\n  style,\n  ...props\n}: HeatmapTableProps) {\n  const pal = PALETTES[theme];\n  const accent = color ?? pal.accent;\n  const reduce = useReducedMotion();\n  const tableRef = React.useRef<HTMLDivElement>(null);\n  const reveal = useReveal(tableRef, reduce);\n  const [mode, setMode] = React.useState(initialMode);\n  const [active, setActive] = React.useState<{ r: number; c: number } | null>(\n    null,\n  );\n\n  const periods = Math.max(...cohorts.map((c) => c.retained.length));\n  const pct = (c: HeatmapCohort, k: number) =>\n    c.size ? c.retained[k] / c.size : 0;\n  // Weighted average per period across the cohorts that have reached it.\n  const avg = Array.from({ length: periods }, (_, k) => {\n    const have = cohorts.filter((c) => c.retained[k] !== undefined);\n    const size = have.reduce((s, c) => s + c.size, 0);\n    return {\n      rate: size ? have.reduce((s, c) => s + c.retained[k], 0) / size : 0,\n      // Average users per cohort for that period, to match the Average label.\n      users: Math.round(have.reduce((s, c) => s + c.retained[k], 0) / Math.max(1, have.length)),\n    };\n  });\n  // Scale colours to the range after period 0 so the interesting cells aren't all pale.\n  const maxRate = Math.max(\n    ...cohorts.flatMap((c) => c.retained.slice(1).map((_, k) => pct(c, k + 1))),\n    0.01,\n  );\n  const fill = (rate: number, k: number) =>\n    k === 0\n      ? mix(pal.base, accent, 1)\n      : mix(\n          pal.base,\n          accent,\n          Math.pow(Math.min(1, rate / maxRate), 0.85) * 0.92,\n        );\n  const cell = (rate: number, users: number) =>\n    mode === \"percent\"\n      ? `${(rate * 100).toFixed(rate >= 0.995 ? 0 : 1)}%`\n      : users.toLocaleString(\"en-US\");\n\n  const onKey = (e: React.KeyboardEvent) => {\n    const moves: Record<string, [number, number]> = {\n      ArrowUp: [-1, 0],\n      ArrowDown: [1, 0],\n      ArrowLeft: [0, -1],\n      ArrowRight: [0, 1],\n    };\n    if (e.key === \"Escape\") return setActive(null);\n    const mv = moves[e.key];\n    if (!mv) return;\n    e.preventDefault();\n    setActive((a) => {\n      if (!a) return { r: 0, c: 0 };\n      const r = Math.max(0, Math.min(cohorts.length - 1, a.r + mv[0]));\n      const maxC = cohorts[r].retained.length - 1;\n      return { r, c: Math.max(0, Math.min(maxC, a.c + mv[1])) };\n    });\n  };\n  const ac = active ? cohorts[active.r] : null;\n\n  return (\n    <div\n      className={cn(\"w-full overflow-hidden rounded-[20px]\", className)}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-4 px-5 pt-5 pb-4 sm:px-6\">\n        <div className=\"min-w-0\">\n          <p className=\"text-[15px] font-semibold tracking-[-0.01em]\">\n            {title}\n          </p>\n          {subtitle && (\n            <p className=\"mt-1 text-[12.5px]\" style={{ color: pal.sub }}>\n              {subtitle}\n            </p>\n          )}\n        </div>\n        <div className=\"flex items-center gap-4\">\n          <div className=\"text-right\">\n            <p className=\"text-[20px] leading-tight font-semibold tracking-[-0.02em] tabular-nums\">\n              {((avg[3]?.rate ?? avg[avg.length - 1].rate) * 100).toFixed(1)}%\n            </p>\n            <p className=\"mt-0.5 text-[11.5px]\" style={{ color: pal.sub }}>\n              avg {periodLabel.toLowerCase()} {avg[3] ? 3 : avg.length - 1}{\" \"}\n              retention\n            </p>\n          </div>\n          <div\n            role=\"radiogroup\"\n            aria-label=\"Cell values\"\n            className=\"flex rounded-full p-0.5 text-[11.5px] font-medium\"\n            style={{ background: pal.chip }}\n          >\n            {([\"percent\", \"count\"] as const).map((m) => (\n              <button\n                key={m}\n                type=\"button\"\n                role=\"radio\"\n                aria-checked={mode === m}\n                onClick={() => setMode(m)}\n                className=\"cursor-pointer rounded-full px-2.5 py-1 transition-colors\"\n                style={{\n                  background: mode === m ? pal.card : \"transparent\",\n                  color: mode === m ? pal.text : pal.sub,\n                  boxShadow: mode === m ? \"0 1px 2px rgba(0,0,0,.2)\" : \"none\",\n                }}\n              >\n                {m === \"percent\" ? \"%\" : \"Users\"}\n              </button>\n            ))}\n          </div>\n        </div>\n      </div>\n\n      <div\n        ref={tableRef}\n        className=\"relative overflow-x-auto border-t overscroll-x-contain\"\n        style={{ borderColor: pal.border }}\n      >\n        <table\n          tabIndex={0}\n          onKeyDown={onKey}\n          onBlur={() => setActive(null)}\n          onMouseLeave={() => setActive(null)}\n          aria-label={title}\n          className=\"w-full border-separate border-spacing-[3px] px-3 py-3 text-[12px] outline-none focus-visible:ring-2 focus-visible:ring-inset sm:px-4\"\n          style={{ minWidth: 150 + periods * 64 }}\n        >\n          <thead>\n            <tr>\n              <th\n                scope=\"col\"\n                className=\"sticky left-0 z-20 px-2 py-1.5 text-left text-[11px] font-medium\"\n                style={{ background: pal.card, color: pal.faint }}\n              >\n                Cohort\n              </th>\n              <th\n                scope=\"col\"\n                className=\"px-2 py-1.5 text-right text-[11px] font-medium\"\n                style={{ color: pal.faint }}\n              >\n                Users\n              </th>\n              {Array.from({ length: periods }, (_, k) => (\n                <th\n                  key={k}\n                  scope=\"col\"\n                  className=\"rounded-md px-1 py-1.5 text-center text-[11px] font-medium whitespace-nowrap transition-colors\"\n                  style={{\n                    color: active?.c === k ? pal.text : pal.faint,\n                    background: active?.c === k ? pal.hi : \"transparent\",\n                  }}\n                >\n                  {k === 0\n                    ? periodLabel.slice(0, 1) + \"0\"\n                    : `${periodLabel.slice(0, 1)}${k}`}\n                </th>\n              ))}\n            </tr>\n          </thead>\n          <tbody>\n            {cohorts.map((c, r) => (\n              <tr key={c.label}>\n                <th\n                  scope=\"row\"\n                  className=\"sticky left-0 z-10 rounded-md px-2 py-1.5 text-left font-medium whitespace-nowrap transition-colors\"\n                  style={{\n                    background:\n                      active?.r === r ? mix(pal.card, accent, 0.1) : pal.card,\n                  }}\n                >\n                  {c.label}\n                </th>\n                <td\n                  className=\"px-2 py-1.5 text-right tabular-nums\"\n                  style={{ color: pal.sub }}\n                >\n                  {c.size.toLocaleString(\"en-US\")}\n                </td>\n                {Array.from({ length: periods }, (_, k) => {\n                  if (c.retained[k] === undefined)\n                    return (\n                      <td\n                        key={k}\n                        aria-hidden=\"true\"\n                        className=\"rounded-md\"\n                        style={{ background: pal.empty, opacity: 0.5 }}\n                      />\n                    );\n                  const rate = pct(c, k);\n                  const bg = fill(rate, k);\n                  const isActive = active?.r === r && active?.c === k;\n                  // Cells appear along the diagonal, oldest first.\n                  const t = Math.min(\n                    1,\n                    Math.max(\n                      0,\n                      reveal * 1.8 -\n                        ((r + k) / (cohorts.length + periods)) * 0.8,\n                    ),\n                  );\n                  return (\n                    <td\n                      key={k}\n                      onMouseEnter={() => setActive({ r, c: k })}\n                      onPointerDown={() => setActive({ r, c: k })}\n                      className=\"h-9 min-w-[56px] rounded-md px-1 text-center font-medium tabular-nums\"\n                      style={{\n                        background: bg,\n                        color: luminance(bg) > 0.55 ? \"#0E1220\" : \"#FFFFFF\",\n                        opacity:\n                          t *\n                          (active &&\n                          !isActive &&\n                          active.r !== r &&\n                          active.c !== k\n                            ? 0.55\n                            : 1),\n                        transform: `scale(${0.9 + 0.1 * t})`,\n                        boxShadow: isActive\n                          ? `0 0 0 2px ${pal.text}`\n                          : undefined,\n                        transition: \"opacity 140ms\",\n                      }}\n                    >\n                      {cell(rate, c.retained[k])}\n                    </td>\n                  );\n                })}\n              </tr>\n            ))}\n            <tr>\n              <th\n                scope=\"row\"\n                className=\"sticky left-0 z-10 px-2 pt-3 pb-1.5 text-left font-semibold whitespace-nowrap\"\n                style={{ background: pal.card }}\n              >\n                Average\n              </th>\n              <td\n                className=\"px-2 pt-3 pb-1.5 text-right tabular-nums\"\n                style={{ color: pal.sub }}\n              >\n                {Math.round(\n                  cohorts.reduce((s, c) => s + c.size, 0) /\n                    Math.max(1, cohorts.length),\n                ).toLocaleString(\"en-US\")}\n              </td>\n              {avg.map((a, k) => (\n                <td\n                  key={k}\n                  className=\"px-1 pt-3 pb-1.5 text-center font-semibold tabular-nums\"\n                  style={{ color: active?.c === k ? pal.text : pal.sub }}\n                >\n                  {cell(a.rate, a.users)}\n                </td>\n              ))}\n            </tr>\n          </tbody>\n        </table>\n      </div>\n\n      <div\n        className=\"flex flex-wrap items-center justify-between gap-3 border-t px-5 py-3 text-[11.5px] sm:px-6\"\n        style={{ borderColor: pal.border, color: pal.sub }}\n      >\n        <span aria-live=\"polite\" className=\"tabular-nums\">\n          {ac && active ? (\n            <>\n              <b style={{ color: pal.text }}>{ac.label}</b> · {periodLabel}{\" \"}\n              {active.c}: {((ac.retained[active.c] / ac.size) * 100).toFixed(1)}\n              % ({ac.retained[active.c].toLocaleString(\"en-US\")} of{\" \"}\n              {ac.size.toLocaleString(\"en-US\")})\n              {active.c > 0 && (\n                <span\n                  style={{\n                    color:\n                      pct(ac, active.c) >= avg[active.c].rate\n                        ? theme === \"dark\"\n                          ? \"#87FFE3\"\n                          : \"#0E9F80\"\n                        : theme === \"dark\"\n                          ? \"#FF8F82\"\n                          : \"#D93848\",\n                  }}\n                >\n                  {\" \"}\n                  {pct(ac, active.c) >= avg[active.c].rate ? \"▲\" : \"▼\"}{\" \"}\n                  {Math.abs(\n                    (pct(ac, active.c) - avg[active.c].rate) * 100,\n                  ).toFixed(1)}{\" \"}\n                  pts vs average\n                </span>\n              )}\n            </>\n          ) : (\n            <>\n              Hover a cell to compare it with the average for that{\" \"}\n              {periodLabel.toLowerCase()}.\n            </>\n          )}\n        </span>\n        <span className=\"flex items-center gap-2\">\n          0%\n          <span\n            className=\"h-2 w-28 rounded-full\"\n            style={{\n              background: `linear-gradient(90deg, ${pal.base}, ${accent})`,\n            }}\n          />\n          {(maxRate * 100).toFixed(0)}%+\n        </span>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}