{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "correlation-matrix-chart",
  "title": "Correlation Matrix Chart",
  "description": "An interactive Pearson correlation matrix with pairwise missing-data handling, a diverging color scale, strong-link emphasis and keyboard cell inspection.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/correlation-matrix-chart/correlation-matrix-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nconst PALETTES = {\n  dark: {\n    bg: \"#08090A\",\n    surface: \"#0F1011\",\n    text: \"#F7F8F8\",\n    soft: \"#D0D6E0\",\n    sub: \"#8A8F98\",\n    faint: \"#62666D\",\n    border: \"rgba(255,255,255,0.08)\",\n    grid: \"rgba(255,255,255,0.05)\",\n    chip: \"rgba(255,255,255,0.05)\",\n    chipOn: \"rgba(255,255,255,0.1)\",\n    accent: \"#6B76DE\",\n    positive: \"#79AEA0\",\n    negative: \"#C18686\",\n  },\n  light: {\n    bg: \"#FFFFFF\",\n    surface: \"#F7F8F8\",\n    text: \"#08090A\",\n    soft: \"#3C3F44\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    border: \"rgba(8,9,10,0.08)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    chip: \"rgba(8,9,10,0.04)\",\n    chipOn: \"rgba(8,9,10,0.08)\",\n    accent: \"#5864C6\",\n    positive: \"#377D69\",\n    negative: \"#A35454\",\n  },\n};\ntype Palette = typeof PALETTES.dark;\nconst FONT =\n  '\"Inter Variable\", Inter, -apple-system, BlinkMacSystemFont, sans-serif';\nfunction Stat({\n  value,\n  label,\n  pal,\n}: {\n  value: string;\n  label: string;\n  pal: Palette;\n}) {\n  return (\n    <div>\n      <p className=\"m-0 text-[18px] leading-tight font-[510] tracking-[-0.018em] tabular-nums\">\n        {value}\n      </p>\n      <p className=\"m-0 mt-1 text-[11px]\" style={{ color: pal.sub }}>\n        {label}\n      </p>\n    </div>\n  );\n}\nfunction Pills({\n  label,\n  options,\n  value,\n  onChange,\n  pal,\n}: {\n  label: string;\n  options: string[];\n  value: number;\n  onChange: (value: number) => void;\n  pal: Palette;\n}) {\n  return (\n    <div\n      role=\"radiogroup\"\n      aria-label={label}\n      className=\"flex w-fit max-w-full flex-wrap rounded-full p-0.5\"\n      style={{ background: pal.chip }}\n    >\n      {options.map((option, i) => (\n        <button\n          key={`${option}-${i}`}\n          type=\"button\"\n          role=\"radio\"\n          aria-checked={i === value}\n          tabIndex={i === value ? 0 : -1}\n          onClick={() => onChange(i)}\n          onKeyDown={(event) => {\n            if (![\"ArrowLeft\", \"ArrowRight\", \"Home\", \"End\"].includes(event.key))\n              return;\n            event.preventDefault();\n            const next =\n              event.key === \"Home\"\n                ? 0\n                : event.key === \"End\"\n                  ? options.length - 1\n                  : (i +\n                      (event.key === \"ArrowRight\" ? 1 : -1) +\n                      options.length) %\n                    options.length;\n            onChange(next);\n            event.currentTarget.parentElement\n              ?.querySelectorAll<HTMLButtonElement>(\"button\")\n              [next]?.focus();\n          }}\n          className=\"cursor-pointer rounded-full px-3 py-1.5 text-[12px] font-[510] tracking-[-0.011em] outline-offset-2 focus-visible:outline-2\"\n          style={{\n            background: i === value ? pal.chipOn : \"transparent\",\n            color: i === value ? pal.text : pal.sub,\n          }}\n        >\n          {option}\n        </button>\n      ))}\n    </div>\n  );\n}\n\nexport interface CorrelationMetric {\n  key: string;\n  label: string;\n}\nexport type CorrelationObservation = Record<string, number | null | undefined>;\nexport interface CorrelationMatrixChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  metrics?: CorrelationMetric[];\n  /** Each row is one observation. Missing/nonfinite pairs are excluded pairwise. */\n  observations?: CorrelationObservation[];\n  /** Minimum absolute coefficient to emphasize in Strong links mode. */\n  threshold?: number;\n}\nconst METRICS: CorrelationMetric[] = [\n  { key: \"activation\", label: \"Activation\" },\n  { key: \"retention\", label: \"Retention\" },\n  { key: \"revenue\", label: \"Revenue\" },\n  { key: \"churn\", label: \"Churn\" },\n  { key: \"support\", label: \"Support\" },\n  { key: \"latency\", label: \"Latency\" },\n];\nconst OBSERVATIONS: CorrelationObservation[] = (() => {\n  let state = 81;\n  const next = () => {\n    state = (state * 9301 + 49297) % 233280;\n    return state / 233280;\n  };\n  return Array.from({ length: 48 }, () => {\n    const health = Math.round(next() * 100),\n      churn = Math.round(100 - health + next() * 35);\n    return {\n      activation: health,\n      retention: Math.round(health * 0.8 + next() * 30),\n      revenue: Math.round(health * 4 + next() * 160),\n      churn,\n      support: Math.round(churn * 0.5 + next() * 60),\n      latency: Math.round(next() * 100 + churn * 0.25),\n    };\n  });\n})();\n\n/** Stable Pearson correlation with pairwise deletion and a centered second pass. */\nfunction correlate(rows: CorrelationObservation[], a: string, b: string) {\n  const pairs = rows.flatMap((row) =>\n    typeof row[a] === \"number\" &&\n    Number.isFinite(row[a]) &&\n    typeof row[b] === \"number\" &&\n    Number.isFinite(row[b])\n      ? [[row[a] as number, row[b] as number]]\n      : [],\n  );\n  const n = pairs.length;\n  if (n < 2) return { r: null, n };\n  const mx = pairs.reduce((s, p) => s + p[0] / n, 0),\n    my = pairs.reduce((s, p) => s + p[1] / n, 0);\n  let xx = 0,\n    yy = 0,\n    xy = 0;\n  pairs.forEach(([x, y]) => {\n    const dx = x - mx,\n      dy = y - my;\n    xx += dx * dx;\n    yy += dy * dy;\n    xy += dx * dy;\n  });\n  const denominator = Math.sqrt(xx) * Math.sqrt(yy);\n  const r =\n    denominator > 0 ? Math.max(-1, Math.min(1, xy / denominator)) : null;\n  return { r: r !== null && Number.isFinite(r) ? r : null, n };\n}\nconst coefficient = (r: number | null) =>\n  r === null\n    ? \"—\"\n    : `${r > 0 ? \"+\" : \"\"}${Math.abs(r) < 0.005 ? \"0.00\" : r.toFixed(2)}`;\n\nexport function CorrelationMatrixChart({\n  theme = \"dark\",\n  title = \"What moves together\",\n  subtitle = \"Relationships across the metrics that shape your product.\",\n  metrics: suppliedMetrics = METRICS,\n  observations = OBSERVATIONS,\n  threshold = 0.6,\n  className,\n  style,\n  ...props\n}: CorrelationMatrixChartProps) {\n  const pal = PALETTES[theme];\n  const [mode, setMode] = React.useState(0);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [focused, setFocused] = React.useState(0);\n  const refs = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const metrics = React.useMemo(\n    () =>\n      suppliedMetrics.filter(\n        (m, i) =>\n          suppliedMetrics.findIndex((other) => other.key === m.key) === i,\n      ),\n    [suppliedMetrics],\n  );\n  const matrix = React.useMemo(\n    () =>\n      metrics.map((a) =>\n        metrics.map((b) => correlate(observations, a.key, b.key)),\n      ),\n    [metrics, observations],\n  );\n  const count = metrics.length;\n  const limit = Number.isFinite(threshold)\n    ? Math.max(0, Math.min(1, threshold))\n    : 0.6;\n  let strongest: { row: number; col: number; r: number } | null = null;\n  matrix.forEach((row, i) =>\n    row.forEach((cell, j) => {\n      if (\n        j > i &&\n        cell.r !== null &&\n        (!strongest || Math.abs(cell.r) > Math.abs(strongest.r))\n      )\n        strongest = { row: i, col: j, r: cell.r };\n    }),\n  );\n  const strongestPair = strongest as {\n    row: number;\n    col: number;\n    r: number;\n  } | null;\n  const index =\n    active === null ? null : Math.max(0, Math.min(count * count - 1, active));\n  const row = index === null ? null : Math.floor(index / Math.max(1, count));\n  const col = index === null ? null : index % Math.max(1, count);\n  const selected = row !== null && col !== null ? matrix[row]?.[col] : null;\n  return (\n    <section\n      className={`w-full rounded-2xl p-5 sm:p-6 ${className ?? \"\"}`}\n      style={{\n        background: pal.bg,\n        boxShadow: `inset 0 0 0 1px ${pal.border}`,\n        color: pal.text,\n        fontFamily: FONT,\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-x-8 gap-y-4\">\n        <div>\n          <h3 className=\"m-0 text-[17px] font-[590] tracking-[-0.012em]\">\n            {title}\n          </h3>\n          <p className=\"m-0 mt-1 text-[13px]\" style={{ color: pal.sub }}>\n            {subtitle}\n          </p>\n        </div>\n        <div className=\"flex flex-wrap gap-x-7 gap-y-3\">\n          <Stat\n            value={String(observations.length)}\n            label=\"Observations\"\n            pal={pal}\n          />\n          <Stat value={String(count)} label=\"Metrics\" pal={pal} />\n          <Stat\n            value={coefficient(strongestPair?.r ?? null)}\n            label=\"Strongest relationship\"\n            pal={pal}\n          />\n        </div>\n      </div>\n      {!count || !observations.length ? (\n        <p className=\"py-16 text-center text-sm\" style={{ color: pal.sub }}>\n          No observations available.\n        </p>\n      ) : (\n        <div className=\"mt-5 overflow-x-auto\">\n          <table className=\"w-full min-w-[480px] table-fixed border-separate border-spacing-1\">\n            <caption className=\"sr-only\">\n              Pearson correlation coefficients. Indigo is positive, rose is\n              negative. Arrow keys inspect cells. A dash means insufficient or\n              constant data.\n            </caption>\n            <thead>\n              <tr>\n                <th className=\"w-[92px]\" scope=\"col\">\n                  <span className=\"sr-only\">Metric</span>\n                </th>\n                {metrics.map((m, j) => (\n                  <th\n                    key={m.key}\n                    scope=\"col\"\n                    className=\"pb-2 text-center text-[10px] font-normal\"\n                    style={{ color: col === j ? pal.text : pal.sub }}\n                  >\n                    {m.label}\n                  </th>\n                ))}\n              </tr>\n            </thead>\n            <tbody>\n              {metrics.map((m, i) => (\n                <tr key={m.key}>\n                  <th\n                    scope=\"row\"\n                    className=\"pr-2 text-left text-[11px] font-medium\"\n                    style={{ color: row === i ? pal.text : pal.sub }}\n                  >\n                    {m.label}\n                  </th>\n                  {matrix[i].map((cell, j) => {\n                    const at = i * count + j,\n                      diagonal = i === j,\n                      chosen = index === at;\n                    const dim =\n                      mode === 1 &&\n                      !diagonal &&\n                      (cell.r === null || Math.abs(cell.r) < limit);\n                    return (\n                      <td key={metrics[j].key} className=\"p-0\">\n                        <button\n                          ref={(el) => {\n                            refs.current[at] = el;\n                          }}\n                          type=\"button\"\n                          tabIndex={\n                            at === Math.min(focused, count * count - 1) ? 0 : -1\n                          }\n                          aria-label={`${m.label} and ${metrics[j].label}: ${cell.r === null ? \"undefined correlation\" : `correlation ${coefficient(cell.r)}`}, ${cell.n} paired observations`}\n                          onFocus={() => {\n                            setFocused(at);\n                            setActive(at);\n                          }}\n                          onBlur={() => setActive(null)}\n                          onPointerEnter={() => setActive(at)}\n                          onPointerLeave={() => setActive(null)}\n                          onClick={() => setActive(at)}\n                          onKeyDown={(event) => {\n                            const moves: Record<string, number> = {\n                              ArrowLeft: -1,\n                              ArrowRight: 1,\n                              ArrowUp: -count,\n                              ArrowDown: count,\n                            };\n                            if (event.key === \"Escape\") {\n                              setActive(null);\n                              return;\n                            }\n                            if (\n                              !(event.key in moves) &&\n                              event.key !== \"Home\" &&\n                              event.key !== \"End\"\n                            )\n                              return;\n                            event.preventDefault();\n                            const next =\n                              event.key === \"Home\"\n                                ? 0\n                                : event.key === \"End\"\n                                  ? count * count - 1\n                                  : Math.max(\n                                      0,\n                                      Math.min(\n                                        count * count - 1,\n                                        at + moves[event.key],\n                                      ),\n                                    );\n                            refs.current[next]?.focus();\n                          }}\n                          className=\"relative flex h-11 w-full cursor-pointer items-center justify-center overflow-hidden rounded-[4px] text-[11px] tabular-nums outline-offset-2 focus-visible:outline-2 motion-safe:transition-opacity motion-safe:duration-150\"\n                          style={{\n                            background: pal.surface,\n                            outline: chosen\n                              ? `1px solid ${pal.soft}`\n                              : undefined,\n                            opacity: dim ? 0.22 : 1,\n                          }}\n                        >\n                          <span\n                            className=\"absolute inset-0\"\n                            style={{\n                              background:\n                                diagonal || cell.r === null\n                                  ? pal.sub\n                                  : cell.r < 0\n                                    ? pal.negative\n                                    : pal.accent,\n                              opacity: diagonal\n                                ? 0.08\n                                : cell.r === null\n                                  ? 0.025\n                                  : 0.05 +\n                                    Math.abs(cell.r) *\n                                      (theme === \"dark\" ? 0.65 : 0.3),\n                            }}\n                          />\n                          <span\n                            className=\"relative\"\n                            style={{ color: diagonal ? pal.faint : pal.text }}\n                          >\n                            {coefficient(cell.r)}\n                          </span>\n                        </button>\n                      </td>\n                    );\n                  })}\n                </tr>\n              ))}\n            </tbody>\n          </table>\n        </div>\n      )}\n      <div\n        className=\"mt-4 flex min-h-10 flex-wrap items-center justify-between gap-3 border-t pt-3 text-[11px]\"\n        style={{ borderColor: pal.border, color: pal.sub }}\n      >\n        <p className=\"m-0\" aria-live=\"polite\">\n          {selected && row !== null && col !== null ? (\n            <>\n              <span style={{ color: pal.text }}>\n                {metrics[row].label} × {metrics[col].label}\n              </span>{\" \"}\n              ·{\" \"}\n              {selected.r === null\n                ? \"Not enough variation to calculate r\"\n                : `r = ${coefficient(selected.r)}`}{\" \"}\n              · n = {selected.n}\n            </>\n          ) : strongestPair ? (\n            <>\n              Strongest pair:{\" \"}\n              <span style={{ color: pal.soft }}>\n                {metrics[strongestPair.row].label} ×{\" \"}\n                {metrics[strongestPair.col].label}\n              </span>\n            </>\n          ) : (\n            \"Hover or focus a cell to inspect a pair\"\n          )}\n        </p>\n        <span className=\"flex items-center gap-1.5\">\n          <span>−1</span>\n          <span\n            className=\"h-1.5 w-24 rounded-full\"\n            style={{\n              background: `linear-gradient(90deg, ${pal.negative}, ${pal.surface}, ${pal.accent})`,\n            }}\n          />\n          <span>+1</span>\n        </span>\n      </div>\n      <div className=\"mt-3 flex flex-wrap items-center justify-between gap-3\">\n        <Pills\n          label=\"Relationship filter\"\n          options={[\"All pairs\", \"Strong links\"]}\n          value={mode}\n          onChange={setMode}\n          pal={pal}\n        />\n        <span className=\"text-[10px]\" style={{ color: pal.faint }}>\n          Pearson r · pairwise complete observations\n        </span>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}