{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ridgeline-density-chart",
  "title": "Ridgeline Density Chart",
  "description": "Layered Gaussian density estimates on a shared scale, with adjustable smoothing, region inspection, sample counts and median/90th-percentile readouts.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/ridgeline-density-chart/ridgeline-density-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 RidgelineSeries {\n  label: string;\n  values: number[];\n}\nexport interface RidgelineDensityChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  series?: RidgelineSeries[];\n  /** Gaussian kernel bandwidth in data units. Defaults to a per-series Silverman estimate. */\n  bandwidth?: number;\n  /** Optional visible x-domain. The automatic domain includes three kernel widths of padding. */\n  domain?: [number, number];\n  rowHeight?: number;\n  formatValue?: (value: number) => string;\n}\nconst SERIES: RidgelineSeries[] = (() => {\n  let state = 29;\n  const random = () => {\n    state = (state * 9301 + 49297) % 233280;\n    return state / 233280;\n  };\n  return [\n    [\"US East\", 340, 65],\n    [\"Europe\", 440, 95],\n    [\"Asia Pacific\", 570, 135],\n    [\"Edge\", 260, 42],\n  ].map(([label, center, spread]) => ({\n    label: String(label),\n    values: Array.from({ length: 64 }, (_, i) =>\n      Math.round(\n        Number(center) +\n          Number(spread) *\n            (random() +\n              random() +\n              random() +\n              random() +\n              random() +\n              random() -\n              3) +\n          (i % 9 === 0 ? Number(spread) * 1.7 : 0),\n      ),\n    ),\n  }));\n})();\nconst FORMAT = (value: number) =>\n  `${Math.round(value).toLocaleString(\"en-US\")} ms`;\nfunction quantile(values: number[], p: number) {\n  const at = (values.length - 1) * p,\n    lo = Math.floor(at);\n  return values.length\n    ? values[lo] +\n        (values[Math.min(lo + 1, values.length - 1)] - values[lo]) * (at - lo)\n    : 0;\n}\nfunction densityAt(values: number[], x: number, h: number) {\n  return (\n    (values.reduce(\n      (sum, value) => sum + Math.exp(-0.5 * ((x - value) / h) ** 2),\n      0,\n    ) *\n      0.3989422804014327) /\n    (values.length * h)\n  );\n}\nfunction estimateBandwidth(values: number[], span: number) {\n  const mean = values.reduce((sum, v) => sum + v / values.length, 0);\n  const sd = Math.sqrt(\n    values.reduce((sum, v) => sum + (v - mean) ** 2, 0) /\n      Math.max(1, values.length - 1),\n  );\n  const iqr = (quantile(values, 0.75) - quantile(values, 0.25)) / 1.34;\n  const scale = Math.min(sd || Infinity, iqr || Infinity);\n  return Math.max(\n    span * 0.015,\n    Number.isFinite(scale) ? 0.9 * scale * values.length ** -0.2 : span * 0.04,\n    0.000001,\n  );\n}\nexport function RidgelineDensityChart({\n  theme = \"dark\",\n  title = \"Latency, in layers\",\n  subtitle = \"Regional response times. One scale, distinct distributions.\",\n  series: suppliedSeries = SERIES,\n  bandwidth,\n  domain,\n  rowHeight = 58,\n  formatValue = FORMAT,\n  className,\n  style,\n  ...props\n}: RidgelineDensityChartProps) {\n  const pal = PALETTES[theme];\n  const id = React.useId().replace(/:/g, \"\");\n  const [smoothing, setSmoothing] = React.useState(1);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [cursor, setCursor] = React.useState<number | null>(null);\n  const refs = React.useRef<(SVGGElement | null)[]>([]);\n  const rows = React.useMemo(\n    () =>\n      suppliedSeries\n        .map((s) => ({\n          ...s,\n          values: s.values.filter(Number.isFinite).sort((a, b) => a - b),\n        }))\n        .filter(\n          (s, i, all) =>\n            s.values.length > 0 &&\n            all.findIndex((other) => other.label === s.label) === i,\n        ),\n    [suppliedSeries],\n  );\n  const values = rows.flatMap((s) => s.values);\n  const low = values.length ? Math.min(...values) : 0,\n    high = values.length ? Math.max(...values) : 1;\n  const span = high - low || Math.max(1, Math.abs(low) * 0.2);\n  const widths = rows.map(\n    (s) =>\n      (Number.isFinite(bandwidth) && bandwidth! > 0\n        ? bandwidth!\n        : estimateBandwidth(s.values, span)) * [0.6, 1, 1.6][smoothing],\n  );\n  const pad = Math.max(span * 0.05, ...widths.map((v) => v * 3));\n  const bounds: [number, number] =\n    domain && domain.every(Number.isFinite) && domain[1] > domain[0]\n      ? domain\n      : [low - pad, high + pad];\n  const samples = rows.map((s, i) =>\n    Array.from({ length: 121 }, (_, j) => {\n      const x = bounds[0] + ((bounds[1] - bounds[0]) * j) / 120;\n      return { x, y: densityAt(s.values, x, widths[i]) };\n    }),\n  );\n  const peak = Math.max(0.000001, ...samples.flatMap((s) => s.map((p) => p.y)));\n  const h = Number.isFinite(rowHeight)\n    ? Math.max(36, Math.min(100, rowHeight))\n    : 58;\n  const stride = h + 20,\n    plotHeight = 28 + stride * rows.length + 18;\n  const x = (value: number) =>\n    106 + ((value - bounds[0]) / (bounds[1] - bounds[0])) * 580;\n  const base = (row: number) => 14 + h + row * stride;\n  const y = (value: number, row: number) => base(row) - (value / peak) * h;\n  const selected =\n    active !== null ? rows[Math.min(active, rows.length - 1)] : null;\n  const median = values.length\n    ? quantile(\n        [...values].sort((a, b) => a - b),\n        0.5,\n      )\n    : null;\n  const inspect = (event: React.PointerEvent<SVGSVGElement>) => {\n    const r = event.currentTarget.getBoundingClientRect();\n    const px = ((event.clientX - r.left) / r.width) * 760;\n    const py = ((event.clientY - r.top) / r.height) * plotHeight;\n    setActive(\n      Math.max(0, Math.min(rows.length - 1, Math.floor((py - 14) / stride))),\n    );\n    setCursor(\n      Math.max(\n        bounds[0],\n        Math.min(\n          bounds[1],\n          bounds[0] + ((px - 106) / 580) * (bounds[1] - bounds[0]),\n        ),\n      ),\n    );\n  };\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 value={String(values.length)} label=\"Samples\" pal={pal} />\n          <Stat value={String(rows.length)} label=\"Regions\" pal={pal} />\n          <Stat\n            value={median === null ? \"—\" : formatValue(median)}\n            label=\"Overall median\"\n            pal={pal}\n          />\n        </div>\n      </div>\n      {!rows.length ? (\n        <p className=\"py-16 text-center text-sm\" style={{ color: pal.sub }}>\n          No distribution data available.\n        </p>\n      ) : (\n        <div className=\"mt-5 overflow-x-auto\">\n          <svg\n            viewBox={`0 0 760 ${plotHeight}`}\n            className=\"block w-full min-w-[560px]\"\n            role=\"group\"\n            aria-label=\"Response-time distributions. Focus a region; arrow keys inspect regions and values.\"\n            onPointerMove={inspect}\n            onPointerLeave={() => {\n              setActive(null);\n              setCursor(null);\n            }}\n          >\n            <defs>\n              <linearGradient id={`${id}-fill`} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n                <stop stopColor={pal.accent} stopOpacity=\"0.35\" />\n                <stop offset=\"1\" stopColor={pal.accent} stopOpacity=\"0.025\" />\n              </linearGradient>\n            </defs>\n            {Array.from({ length: 6 }, (_, i) => {\n              const value = bounds[0] + ((bounds[1] - bounds[0]) * i) / 5;\n              return (\n                <g key={i}>\n                  <line\n                    x1={x(value)}\n                    x2={x(value)}\n                    y1=\"8\"\n                    y2={plotHeight - 30}\n                    stroke={pal.grid}\n                    strokeDasharray=\"2 5\"\n                  />\n                  <text\n                    x={x(value)}\n                    y={plotHeight - 7}\n                    textAnchor=\"middle\"\n                    fill={pal.sub}\n                    fontSize=\"10\"\n                  >\n                    {formatValue(value)}\n                  </text>\n                </g>\n              );\n            })}\n            {rows.map((s, row) => {\n              const line = samples[row]\n                .map(\n                  (p, j) =>\n                    `${j ? \"L\" : \"M\"}${x(p.x).toFixed(2)},${y(p.y, row).toFixed(2)}`,\n                )\n                .join(\"\");\n              const area = `${line}L686,${base(row)}L106,${base(row)}Z`;\n              const mid = quantile(s.values, 0.5),\n                p90 = quantile(s.values, 0.9);\n              const on = active === row;\n              return (\n                <g\n                  key={s.label}\n                  ref={(element) => {\n                    refs.current[row] = element;\n                  }}\n                  tabIndex={0}\n                  role=\"button\"\n                  aria-label={`${s.label}: ${s.values.length} samples, median ${formatValue(mid)}, 90th percentile ${formatValue(p90)}`}\n                  onFocus={() => setActive(row)}\n                  onBlur={() => {\n                    setActive(null);\n                    setCursor(null);\n                  }}\n                  onClick={() => setActive(row)}\n                  onKeyDown={(event) => {\n                    if (event.key === \"Escape\") {\n                      setActive(null);\n                      setCursor(null);\n                      return;\n                    }\n                    if (\n                      ![\n                        \"ArrowUp\",\n                        \"ArrowDown\",\n                        \"ArrowLeft\",\n                        \"ArrowRight\",\n                        \"Home\",\n                        \"End\",\n                        \"Enter\",\n                        \" \",\n                      ].includes(event.key)\n                    )\n                      return;\n                    event.preventDefault();\n                    if (event.key === \"ArrowUp\" || event.key === \"ArrowDown\")\n                      refs.current[\n                        Math.max(\n                          0,\n                          Math.min(\n                            rows.length - 1,\n                            row + (event.key === \"ArrowDown\" ? 1 : -1),\n                          ),\n                        )\n                      ]?.focus();\n                    else if (event.key === \"Home\" || event.key === \"End\")\n                      setCursor(bounds[event.key === \"Home\" ? 0 : 1]);\n                    else if (\n                      event.key === \"ArrowLeft\" ||\n                      event.key === \"ArrowRight\"\n                    )\n                      setCursor((value) =>\n                        Math.max(\n                          bounds[0],\n                          Math.min(\n                            bounds[1],\n                            (value ?? mid) +\n                              ((event.key === \"ArrowRight\" ? 1 : -1) *\n                                (bounds[1] - bounds[0])) /\n                                50,\n                          ),\n                        ),\n                      );\n                    else setActive(row);\n                  }}\n                  className=\"cursor-pointer outline-offset-2 focus-visible:outline-2 motion-safe:transition-opacity motion-safe:duration-150\"\n                  style={{ opacity: active !== null && !on ? 0.38 : 1 }}\n                >\n                  <text\n                    x=\"0\"\n                    y={base(row) - 16}\n                    fontSize=\"11\"\n                    fill={on ? pal.text : pal.soft}\n                  >\n                    {s.label}\n                  </text>\n                  <text x=\"0\" y={base(row)} fontSize=\"10\" fill={pal.faint}>\n                    n = {s.values.length}\n                  </text>\n                  <line\n                    x1=\"106\"\n                    x2=\"686\"\n                    y1={base(row)}\n                    y2={base(row)}\n                    stroke={pal.border}\n                  />\n                  <path d={area} fill={`url(#${id}-fill)`} />\n                  <path\n                    d={line}\n                    fill=\"none\"\n                    stroke={on ? pal.soft : pal.accent}\n                    strokeWidth={on ? 1.8 : 1.4}\n                  />\n                  {mid >= bounds[0] && mid <= bounds[1] && (\n                    <line\n                      x1={x(mid)}\n                      x2={x(mid)}\n                      y1={base(row)}\n                      y2={y(densityAt(s.values, mid, widths[row]), row)}\n                      stroke={pal.soft}\n                      strokeOpacity=\"0.6\"\n                      strokeDasharray=\"2 3\"\n                    />\n                  )}\n                  <text\n                    x=\"756\"\n                    y={base(row) - 4}\n                    textAnchor=\"end\"\n                    fontSize=\"10\"\n                    fill={pal.sub}\n                  >\n                    {formatValue(mid)}\n                  </text>\n                  {cursor !== null && (\n                    <circle\n                      cx={x(cursor)}\n                      cy={y(densityAt(s.values, cursor, widths[row]), row)}\n                      r={on ? 3.5 : 2}\n                      fill={on ? pal.text : pal.accent}\n                    />\n                  )}\n                </g>\n              );\n            })}\n            {cursor !== null && (\n              <line\n                x1={x(cursor)}\n                x2={x(cursor)}\n                y1=\"8\"\n                y2={plotHeight - 30}\n                stroke={pal.sub}\n                strokeDasharray=\"3 4\"\n                opacity=\"0.5\"\n              />\n            )}\n          </svg>\n        </div>\n      )}\n      <div\n        className=\"mt-3 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 ? (\n            <>\n              <span style={{ color: pal.text }}>{selected.label}</span> · median{\" \"}\n              {formatValue(quantile(selected.values, 0.5))} · p90{\" \"}\n              {formatValue(quantile(selected.values, 0.9))}\n              {cursor !== null ? ` · inspecting ${formatValue(cursor)}` : \"\"}\n            </>\n          ) : (\n            \"Focus or hover a region to inspect its distribution\"\n          )}\n        </p>\n        <span>Dashed marker: median</span>\n      </div>\n      <div className=\"mt-3 flex flex-wrap items-center justify-between gap-3\">\n        <Pills\n          label=\"Smoothing\"\n          options={[\"Sharp\", \"Balanced\", \"Smooth\"]}\n          value={smoothing}\n          onChange={setSmoothing}\n          pal={pal}\n        />\n        <span className=\"text-[10px]\" style={{ color: pal.faint }}>\n          Gaussian KDE · shared density scale\n        </span>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}