{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bubble-chart",
  "title": "Bubble Chart",
  "description": "A bubble chart for three measures at once: x, y and bubble size, coloured by group, split into four labelled quadrants like a portfolio matrix, with bubbles that pop in largest first, names inside the big ones and a tooltip that says which quadrant an item sits in.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/bubble-chart/bubble-chart.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 ChartTheme = \"dark\" | \"light\";\n\nexport interface BubbleGroup {\n  label: string;\n  color?: string;\n}\n\nexport interface Bubble {\n  label: string;\n  x: number;\n  y: number;\n  /** Bubble area follows this value. */\n  size: number;\n  /** Index into `groups`. */\n  group: number;\n}\n\nexport interface BubbleQuadrants {\n  /** Where the dividing lines sit, in data units. Defaults to the middle of each axis. */\n  x?: number;\n  y?: number;\n  /** Labels for top-left, top-right, bottom-left and bottom-right. */\n  labels: [string, string, string, string];\n}\n\nexport interface BubbleChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  title?: string;\n  subtitle?: string;\n  groups?: BubbleGroup[];\n  bubbles?: Bubble[];\n  xLabel?: string;\n  yLabel?: string;\n  sizeLabel?: string;\n  /** Split the plot into four labelled quadrants; false for none. */\n  quadrants?: BubbleQuadrants | false;\n  /** Radius of the largest bubble, in px (scaled down on narrow screens). */\n  maxRadius?: number;\n  /** Height of the plot area, in px. */\n  height?: number;\n  formatX?: (value: number) => string;\n  formatY?: (value: number) => string;\n  formatSize?: (value: number) => 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    grid: \"rgba(255,255,255,0.07)\",\n    axis: \"rgba(255,255,255,0.45)\",\n    divider: \"rgba(255,255,255,0.22)\",\n    quad: \"rgba(255,255,255,0.28)\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    series: [\"#87FFE3\", \"#8FB8FF\", \"#B69CFF\", \"#F2A841\", \"#FF7A6B\"],\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.07)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    grid: \"rgba(17,19,23,0.08)\",\n    axis: \"rgba(17,19,23,0.5)\",\n    divider: \"rgba(17,19,23,0.25)\",\n    quad: \"rgba(17,19,23,0.32)\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    series: [\"#0E9F80\", \"#3B6FD8\", \"#7B5CE0\", \"#D9822B\", \"#E5484D\"],\n  },\n};\n\nconst DEFAULT_GROUPS: BubbleGroup[] = [\n  { label: \"Software\" },\n  { label: \"Hardware\" },\n  { label: \"Services\" },\n];\nconst DEFAULT_BUBBLES: Bubble[] = [\n  { label: \"Analytics\", x: 38, y: 72, size: 48, group: 0 },\n  { label: \"Payments\", x: 24, y: 64, size: 86, group: 0 },\n  { label: \"CRM\", x: 9, y: 58, size: 120, group: 0 },\n  { label: \"AI Copilot\", x: 61, y: 41, size: 22, group: 0 },\n  { label: \"Security\", x: 31, y: 69, size: 34, group: 0 },\n  { label: \"Sensors\", x: 18, y: 33, size: 41, group: 1 },\n  { label: \"Terminals\", x: 4, y: 27, size: 76, group: 1 },\n  { label: \"Wearables\", x: 44, y: 22, size: 18, group: 1 },\n  { label: \"Gateways\", x: -3, y: 19, size: 29, group: 1 },\n  { label: \"Onboarding\", x: 27, y: 38, size: 25, group: 2 },\n  { label: \"Support\", x: 6, y: 44, size: 58, group: 2 },\n  { label: \"Training\", x: 15, y: 51, size: 16, group: 2 },\n  { label: \"Consulting\", x: -6, y: 36, size: 39, group: 2 },\n];\nconst DEFAULT_QUADRANTS: BubbleQuadrants = {\n  x: 20,\n  y: 45,\n  labels: [\"Profitable, slow\", \"Stars\", \"Watch list\", \"Bets\"],\n};\n\nconst money = new Intl.NumberFormat(\"en-US\", {\n  style: \"currency\",\n  currency: \"USD\",\n  maximumFractionDigits: 0,\n});\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\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\n/** 0 → 1 (linear) once the element scrolls into view; 1 straight away with reduced motion. */\nfunction useReveal(\n  ref: React.RefObject<HTMLElement | null>,\n  reduce: boolean,\n  duration = 1500,\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 niceScale(min: number, max: number, count = 5) {\n  const span = Math.max(1e-9, max - min);\n  const raw = span / count;\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n  const step =\n    [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;\n  const lo = Math.floor(min / step) * step;\n  const hi = Math.ceil(max / step) * step;\n  return {\n    min: lo,\n    max: hi,\n    ticks: Array.from(\n      { length: Math.round((hi - lo) / step) + 1 },\n      (_, i) => lo + i * step,\n    ),\n  };\n}\n\nconst clamp01 = (t: number) => Math.min(1, Math.max(0, t));\nconst easeOutBack = (t: number) =>\n  1 + 2.4 * Math.pow(t - 1, 3) + 1.4 * Math.pow(t - 1, 2);\n\nconst M = { top: 14, right: 16, bottom: 44, left: 48 };\n\nexport function BubbleChart({\n  theme = \"dark\",\n  title = \"Product portfolio\",\n  subtitle = \"Revenue growth vs operating margin, bubble size is annual revenue\",\n  groups = DEFAULT_GROUPS,\n  bubbles = DEFAULT_BUBBLES,\n  xLabel = \"Revenue growth\",\n  yLabel = \"Operating margin\",\n  sizeLabel = \"Revenue\",\n  quadrants = DEFAULT_QUADRANTS,\n  maxRadius = 46,\n  height = 340,\n  formatX = (v) => `${v > 0 ? \"+\" : \"\"}${v}%`,\n  formatY = (v) => `${v}%`,\n  formatSize = (v) => `${money.format(v)}M`,\n  className,\n  style,\n  ...props\n}: BubbleChartProps) {\n  const pal = PALETTES[theme];\n  const reduce = useReducedMotion();\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(plotRef);\n  const reveal = useReveal(plotRef, reduce);\n  const [hidden, setHidden] = React.useState<boolean[]>(() =>\n    groups.map(() => false),\n  );\n  const [active, setActive] = React.useState<number | null>(null);\n  const colors = groups.map(\n    (g, i) => g.color ?? pal.series[i % pal.series.length],\n  );\n\n  const plotW = Math.max(0, width - M.left - M.right);\n  const rMax = Math.max(16, Math.min(maxRadius, plotW / 12));\n  const sMax = Math.max(1, ...bubbles.map((b) => b.size));\n  const radius = (s: number) => Math.max(4, Math.sqrt(s / sMax) * rMax);\n  const xs = niceScale(\n    Math.min(...bubbles.map((b) => b.x)) - 4,\n    Math.max(...bubbles.map((b) => b.x)) + 4,\n    Math.max(3, Math.min(6, Math.floor(plotW / 100))),\n  );\n  const ys = niceScale(\n    Math.min(...bubbles.map((b) => b.y)) - 6,\n    Math.max(...bubbles.map((b) => b.y)) + 6,\n    5,\n  );\n  // Keep bubbles inside the plot: pad the scales by the largest radius.\n  const xAt = (v: number) =>\n    M.left +\n    rMax * 0.6 +\n    ((v - xs.min) / (xs.max - xs.min)) * (plotW - rMax * 1.2);\n  const yAt = (v: number) =>\n    M.top +\n    rMax * 0.6 +\n    (height - rMax * 1.2) -\n    ((v - ys.min) / (ys.max - ys.min)) * (height - rMax * 1.2);\n\n  // Largest first so small bubbles sit on top and stay hoverable.\n  const order = React.useMemo(\n    () => bubbles.map((b, i) => ({ b, i })).sort((a, b) => b.b.size - a.b.size),\n    [bubbles],\n  );\n  const visible = order.filter(({ b }) => !hidden[b.group]);\n  const qx = quadrants ? (quadrants.x ?? (xs.min + xs.max) / 2) : 0;\n  const qy = quadrants ? (quadrants.y ?? (ys.min + ys.max) / 2) : 0;\n\n  const hit = (clientX: number, clientY: number) => {\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!r) return;\n    const px = clientX - r.left;\n    const py = clientY - r.top;\n    // Topmost (smallest) bubble under the pointer wins.\n    let found: number | null = null;\n    for (const { b, i } of visible)\n      if (\n        (xAt(b.x) - px) ** 2 + (yAt(b.y) - py) ** 2 <=\n        (radius(b.size) + 2) ** 2\n      )\n        found = i;\n    setActive(found);\n  };\n  const onKey = (event: React.KeyboardEvent) => {\n    if (!visible.length) return;\n    const at = visible.findIndex(({ i }) => i === active);\n    let next = at;\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowDown\")\n      next = at < 0 ? 0 : (at + 1) % visible.length;\n    else if (event.key === \"ArrowLeft\" || event.key === \"ArrowUp\")\n      next =\n        at < 0\n          ? visible.length - 1\n          : (at - 1 + visible.length) % visible.length;\n    else if (event.key === \"Escape\") return setActive(null);\n    else return;\n    event.preventDefault();\n    setActive(visible[next].i);\n  };\n\n  const ab = active !== null ? bubbles[active] : null;\n  const tipX = ab ? xAt(ab.x) : 0;\n  const tipY = ab ? yAt(ab.y) : 0;\n  const tipR = ab ? radius(ab.size) : 0;\n  const tipFlip = tipX > width - 220;\n  const totalSize = bubbles\n    .filter((b) => !hidden[b.group])\n    .reduce((s, b) => s + b.size, 0);\n  const summary = `${title}. ${bubbles.map((b) => `${b.label}: ${xLabel} ${formatX(b.x)}, ${yLabel} ${formatY(b.y)}, ${sizeLabel} ${formatSize(b.size)}`).join(\"; \")}.`;\n\n  return (\n    <div\n      className={cn(\n        \"w-full overflow-hidden rounded-[20px] p-5 sm:p-7\",\n        className,\n      )}\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\">\n        <div className=\"min-w-0 max-w-[460px]\">\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-end gap-4\">\n          <div className=\"text-right\">\n            <p className=\"text-[20px] leading-tight font-semibold tracking-[-0.02em] tabular-nums\">\n              {formatSize(totalSize)}\n            </p>\n            <p className=\"mt-0.5 text-[11.5px]\" style={{ color: pal.sub }}>\n              Total {sizeLabel.toLowerCase()}\n            </p>\n          </div>\n        </div>\n      </div>\n\n      <div className=\"mt-4 flex flex-wrap gap-x-4 gap-y-2\">\n        {groups.map((g, i) => (\n          <button\n            key={g.label}\n            type=\"button\"\n            aria-pressed={!hidden[i]}\n            onClick={() => {\n              setActive(null);\n              setHidden((h) =>\n                h.filter((x) => !x).length === 1 && !h[i]\n                  ? h\n                  : h.map((x, j) => (j === i ? !x : x)),\n              );\n            }}\n            className=\"flex cursor-pointer items-center gap-1.5 text-[12px] font-medium transition-opacity\"\n            style={{ opacity: hidden[i] ? 0.4 : 1 }}\n          >\n            <span\n              className=\"size-2.5 rounded-full\"\n              style={{\n                background: hidden[i] ? \"transparent\" : colors[i],\n                boxShadow: `inset 0 0 0 1.5px ${colors[i]}`,\n              }}\n            />\n            {g.label}\n          </button>\n        ))}\n      </div>\n\n      <div\n        ref={plotRef}\n        role=\"img\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKey}\n        onPointerMove={(e) => hit(e.clientX, e.clientY)}\n        onPointerDown={(e) => hit(e.clientX, e.clientY)}\n        onPointerLeave={(e) => e.pointerType === \"mouse\" && setActive(null)}\n        onBlur={() => setActive(null)}\n        className=\"relative mt-3 w-full rounded-lg outline-none focus-visible:ring-2\"\n        style={{ height: height + M.top + M.bottom }}\n      >\n        {width > 0 && (\n          <svg\n            width={width}\n            height={height + M.top + M.bottom}\n            className=\"block overflow-visible\"\n            aria-hidden=\"true\"\n          >\n            {ys.ticks.map((t) => (\n              <g key={`y${t}`}>\n                <line\n                  x1={M.left}\n                  x2={M.left + plotW}\n                  y1={yAt(t)}\n                  y2={yAt(t)}\n                  stroke={pal.grid}\n                  strokeDasharray=\"3 4\"\n                />\n                <text\n                  x={M.left - 10}\n                  y={yAt(t) + 4}\n                  textAnchor=\"end\"\n                  fontSize={11}\n                  fill={pal.axis}\n                  className=\"tabular-nums\"\n                >\n                  {formatY(t)}\n                </text>\n              </g>\n            ))}\n            {xs.ticks.map((t) => (\n              <text\n                key={`x${t}`}\n                x={xAt(t)}\n                y={M.top + height + 18}\n                textAnchor=\"middle\"\n                fontSize={11}\n                fill={pal.axis}\n                className=\"tabular-nums\"\n              >\n                {formatX(t)}\n              </text>\n            ))}\n            <line\n              x1={M.left}\n              x2={M.left + plotW}\n              y1={M.top + height}\n              y2={M.top + height}\n              stroke={pal.grid}\n            />\n            <text\n              x={M.left + plotW}\n              y={M.top + height + 38}\n              textAnchor=\"end\"\n              fontSize={11}\n              fontWeight={500}\n              fill={pal.sub}\n            >\n              {xLabel} →\n            </text>\n            <text\n              x={M.left + 8}\n              y={M.top + 12}\n              fontSize={11}\n              fontWeight={500}\n              fill={pal.sub}\n            >\n              ↑ {yLabel}\n            </text>\n\n            {quadrants && (\n              <g style={{ opacity: clamp01(reveal * 3) }}>\n                <line\n                  x1={xAt(qx)}\n                  x2={xAt(qx)}\n                  y1={M.top}\n                  y2={M.top + height}\n                  stroke={pal.divider}\n                  strokeDasharray=\"4 4\"\n                />\n                <line\n                  x1={M.left}\n                  x2={M.left + plotW}\n                  y1={yAt(qy)}\n                  y2={yAt(qy)}\n                  stroke={pal.divider}\n                  strokeDasharray=\"4 4\"\n                />\n                <g\n                  fontSize={10.5}\n                  fontWeight={600}\n                  fill={pal.quad}\n                  letterSpacing=\"0.08em\"\n                >\n                  <text x={xAt(qx) - 10} y={M.top + 30} textAnchor=\"end\">\n                    {quadrants.labels[0].toUpperCase()}\n                  </text>\n                  <text x={M.left + plotW - 8} y={M.top + 30} textAnchor=\"end\">\n                    {quadrants.labels[1].toUpperCase()}\n                  </text>\n                  <text\n                    x={xAt(qx) - 10}\n                    y={M.top + height - 10}\n                    textAnchor=\"end\"\n                  >\n                    {quadrants.labels[2].toUpperCase()}\n                  </text>\n                  <text\n                    x={M.left + plotW - 8}\n                    y={M.top + height - 10}\n                    textAnchor=\"end\"\n                  >\n                    {quadrants.labels[3].toUpperCase()}\n                  </text>\n                </g>\n              </g>\n            )}\n\n            {order.map(({ b, i }, k) => {\n              const s = easeOutBack(\n                clamp01(reveal * 1.7 - (k / order.length) * 0.7),\n              );\n              const r = radius(b.size) * (hidden[b.group] ? 0 : Math.max(0, s));\n              const dim = active !== null && active !== i;\n              const c = colors[b.group];\n              return (\n                <g\n                  key={i}\n                  style={{ transition: \"opacity 160ms\" }}\n                  opacity={dim ? 0.3 : 1}\n                >\n                  <circle\n                    cx={xAt(b.x)}\n                    cy={yAt(b.y)}\n                    r={r}\n                    fill={c}\n                    fillOpacity={theme === \"dark\" ? 0.22 : 0.18}\n                    stroke={c}\n                    strokeWidth={active === i ? 2.4 : 1.4}\n                  />\n                  {r > 27 && (\n                    <text\n                      x={xAt(b.x)}\n                      y={yAt(b.y) + 4}\n                      textAnchor=\"middle\"\n                      fontSize={Math.max(10, Math.min(12, r / 3.2))}\n                      fontWeight={600}\n                      fill={pal.text}\n                      style={{ pointerEvents: \"none\" }}\n                    >\n                      {b.label.length *\n                        Math.max(10, Math.min(12, r / 3.2)) *\n                        0.58 >\n                      r * 1.8\n                        ? `${b.label.slice(0, Math.max(3, Math.floor((r * 1.8) / (Math.max(10, Math.min(12, r / 3.2)) * 0.58)) - 1))}…`\n                        : b.label}\n                    </text>\n                  )}\n                </g>\n              );\n            })}\n          </svg>\n        )}\n        {ab && width > 0 && (\n          <div\n            className=\"pointer-events-none absolute z-10 min-w-[180px] rounded-xl px-3 py-2.5 text-[12px] shadow-xl\"\n            style={{\n              left: tipFlip ? undefined : tipX + tipR + 10,\n              right: tipFlip ? width - tipX + tipR + 10 : undefined,\n              top: Math.max(0, tipY - 50),\n              background: pal.tip,\n              border: `1px solid ${pal.tipBorder}`,\n              backdropFilter: \"blur(8px)\",\n            }}\n          >\n            <p className=\"flex items-center gap-1.5 font-semibold\">\n              <span\n                className=\"size-2 rounded-full\"\n                style={{ background: colors[ab.group] }}\n              />\n              {ab.label}\n              <span className=\"font-normal\" style={{ color: pal.sub }}>\n                · {groups[ab.group]?.label}\n              </span>\n            </p>\n            {[\n              [sizeLabel, formatSize(ab.size)],\n              [xLabel, formatX(ab.x)],\n              [yLabel, formatY(ab.y)],\n            ].map(([k, v]) => (\n              <div key={k} className=\"mt-1.5 flex justify-between gap-4\">\n                <span style={{ color: pal.sub }}>{k}</span>\n                <span className=\"font-semibold tabular-nums\">{v}</span>\n              </div>\n            ))}\n            {quadrants && (\n              <p\n                className=\"mt-2 border-t pt-1.5 text-[11px] font-semibold tracking-[0.06em] uppercase\"\n                style={{ borderColor: pal.tipBorder, color: colors[ab.group] }}\n              >\n                {quadrants.labels[(ab.y >= qy ? 0 : 2) + (ab.x >= qx ? 1 : 0)]}\n              </p>\n            )}\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}