{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gravity-bubble-chart",
  "title": "Gravity Bubble Chart",
  "description": "A force-based bubble chart with pointer attraction, collision separation, together/team layouts and keyboard-accessible project values.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/gravity-bubble-chart/gravity-bubble-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface GravityItem {\n  label: string;\n  value: number;\n  /** Index into groups. */\n  group: number;\n}\n\nexport interface GravityBubbleChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  items?: GravityItem[];\n  groups?: string[];\n  /** How strongly the pointer pulls on the bubbles. 0 turns it off. */\n  pull?: number;\n  /** Height of the plot, in px. */\n  height?: number;\n  /** Word after the value in the readout. */\n  unit?: string;\n  formatValue?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#08090A\",\n    surface: \"#0F1011\",\n    border: \"rgba(255,255,255,0.08)\",\n    grid: \"rgba(255,255,255,0.05)\",\n    text: \"#F7F8F8\",\n    soft: \"#D0D6E0\",\n    sub: \"#8A8F98\",\n    faint: \"#62666D\",\n    tip: \"#161718\",\n    tipShadow: \"0 4px 24px rgba(0,0,0,0.4)\",\n    chip: \"rgba(255,255,255,0.05)\",\n    chipOn: \"rgba(255,255,255,0.1)\",\n    accent: \"#5E6AD2\",\n    blue: \"#4EA7FC\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    surface: \"#F7F8F8\",\n    border: \"rgba(8,9,10,0.08)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    text: \"#08090A\",\n    soft: \"#3C3F44\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    tip: \"#FFFFFF\",\n    tipShadow: \"0 3px 12px rgba(8,9,10,0.09)\",\n    chip: \"rgba(8,9,10,0.04)\",\n    chipOn: \"#FFFFFF\",\n    accent: \"#5E6AD2\",\n    blue: \"#4EA7FC\",\n  },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nconst CARD_FONT =\n  '\"Inter Variable\", Inter, \"SF Pro Display\", -apple-system, BlinkMacSystemFont, sans-serif';\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/** The chart is drawn at its real width, so its text stays the same size on a phone. */\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(700);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(Math.max(240, Math.round(entry.contentRect.width))),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction Stat({\n  value,\n  label,\n  pal,\n}: {\n  value: string;\n  label: string;\n  pal: Palette;\n}) {\n  return (\n    <div className=\"text-left sm:text-right\">\n      <p className=\"m-0 text-[18px] leading-[1.2] font-[510] tracking-[-0.018em] tabular-nums\">\n        {value}\n      </p>\n      <p\n        className=\"m-0 mt-0.5 text-[12px] tracking-[-0.011em]\"\n        style={{ color: pal.sub }}\n      >\n        {label}\n      </p>\n    </div>\n  );\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: (index: number) => void;\n  pal: Palette;\n}) {\n  return (\n    <div\n      className=\"flex rounded-full p-0.5\"\n      style={{ background: pal.chip }}\n      role=\"radiogroup\"\n      aria-label={label}\n    >\n      {options.map((option, i) => (\n        <button\n          key={option}\n          type=\"button\"\n          role=\"radio\"\n          aria-checked={i === value}\n          tabIndex={i === value ? 0 : -1}\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          onClick={() => onChange(i)}\n          className=\"h-7 cursor-pointer rounded-full px-3 text-[13px] font-[510] tracking-[-0.011em] transition-colors outline-none focus-visible:ring-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\nfunction Tip({\n  x,\n  y,\n  width,\n  pal,\n  children,\n}: {\n  x: number;\n  y: number;\n  width: number;\n  pal: Palette;\n  children: React.ReactNode;\n}) {\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute z-10 -translate-x-1/2 rounded-lg px-2.5 py-1.5 text-[12px] tracking-[-0.011em] whitespace-nowrap\"\n      style={{\n        left: Math.max(110, Math.min(width - 110, x)),\n        top: Math.max(0, y - 42),\n        background: pal.tip,\n        color: pal.sub,\n        boxShadow: `inset 0 0 0 1px ${pal.border}, ${pal.tipShadow}`,\n      }}\n    >\n      {children}\n    </div>\n  );\n}\n\nconst GROUPS = [\"Engineering\", \"Design\", \"Support\"];\n\nconst ITEMS: GravityItem[] = [\n  { label: \"Search\", value: 420, group: 0 },\n  { label: \"Billing\", value: 310, group: 0 },\n  { label: \"Sync\", value: 268, group: 0 },\n  { label: \"API\", value: 232, group: 0 },\n  { label: \"Auth\", value: 174, group: 0 },\n  { label: \"Exports\", value: 118, group: 0 },\n  { label: \"Alerts\", value: 92, group: 0 },\n  { label: \"Cache\", value: 64, group: 0 },\n  { label: \"Brand\", value: 286, group: 1 },\n  { label: \"Mobile\", value: 244, group: 1 },\n  { label: \"Icons\", value: 136, group: 1 },\n  { label: \"Motion\", value: 108, group: 1 },\n  { label: \"Research\", value: 196, group: 1 },\n  { label: \"Forms\", value: 72, group: 1 },\n  { label: \"Tickets\", value: 348, group: 2 },\n  { label: \"Docs\", value: 212, group: 2 },\n  { label: \"Calls\", value: 158, group: 2 },\n  { label: \"Macros\", value: 84, group: 2 },\n  { label: \"Forum\", value: 66, group: 2 },\n];\n\nconst FORMAT = (n: number) => Math.round(n).toLocaleString(\"en-US\");\nconst MODES = [\"Together\", \"By team\"];\nconst PAD = 3;\n\ninterface Spot {\n  x: number;\n  y: number;\n}\n\n/** Bubble sizes that fill a fixed share of the plot, so they scale with the space they get. */\nfunction sizes(items: GravityItem[], width: number, height: number) {\n  const max = Math.max(1, ...items.map((i) => i.value));\n  const area = items.reduce((n, i) => n + i.value / max, 0) * Math.PI;\n  const scale = Math.min(\n    height * 0.21,\n    Math.sqrt((width * height * 0.36) / Math.max(1, area)),\n  );\n  return items.map((i) => Math.max(7, scale * Math.sqrt(i.value / max)));\n}\n\n/**\n * Where each bubble comes to rest. Only arithmetic and square roots, which every engine\n * computes the same, so the server and the browser start from identical positions.\n */\nfunction settle(\n  radii: number[],\n  targets: Spot[],\n  width: number,\n  height: number,\n) {\n  let state = 17;\n  const jitter = () => {\n    state = (state * 9301 + 49297) % 233280;\n    return (state / 233280 - 0.5) * 90;\n  };\n  const spots = targets.map((t) => ({ x: t.x + jitter(), y: t.y + jitter() }));\n  for (let step = 0; step < 400; step++) {\n    spots.forEach((s, i) => {\n      if (step < 320) {\n        s.x += (targets[i].x - s.x) * 0.05;\n        s.y += (targets[i].y - s.y) * 0.05;\n      }\n    });\n    for (let i = 0; i < spots.length; i++) {\n      for (let j = i + 1; j < spots.length; j++) {\n        const dx = spots[j].x - spots[i].x;\n        const dy = spots[j].y - spots[i].y;\n        const distance = Math.sqrt(dx * dx + dy * dy) || 1;\n        const gap = radii[i] + radii[j] + PAD;\n        if (distance < gap) {\n          const push = (gap - distance) / distance / 2;\n          spots[i].x -= dx * push;\n          spots[i].y -= dy * push;\n          spots[j].x += dx * push;\n          spots[j].y += dy * push;\n        }\n      }\n    }\n    spots.forEach((s, i) => {\n      const r = radii[i] + 1;\n      s.x = Math.min(width - r, Math.max(r, s.x));\n      s.y = Math.min(height - r, Math.max(r, s.y));\n    });\n  }\n  return spots.map((s) => ({\n    x: Math.round(s.x * 100) / 100,\n    y: Math.round(s.y * 100) / 100,\n  }));\n}\n\nexport function GravityBubbleChart({\n  theme = \"dark\",\n  title = \"Where the hours went\",\n  subtitle = \"Every bubble is a project. Move the pointer to pull them around.\",\n  items: suppliedItems = ITEMS,\n  groups = GROUPS,\n  pull = 1,\n  height: requestedHeight = 300,\n  unit = \"hours\",\n  formatValue = FORMAT,\n  className,\n  style,\n  ...props\n}: GravityBubbleChartProps) {\n  const pal = PALETTES[theme];\n  const height = Number.isFinite(requestedHeight)\n    ? Math.max(180, Math.min(600, requestedHeight))\n    : 300;\n  const items = React.useMemo(\n    () =>\n      suppliedItems.filter(\n        (item, index) =>\n          Number.isFinite(item.value) &&\n          item.value > 0 &&\n          Number.isInteger(item.group) &&\n          item.group >= 0 &&\n          item.group < groups.length &&\n          suppliedItems.findIndex((other) => other.label === item.label) ===\n            index,\n      ),\n    [suppliedItems, groups.length],\n  );\n\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const nodeRefs = React.useRef<(SVGGElement | null)[]>([]);\n  const start = React.useRef<() => void>(() => {});\n  const pointer = React.useRef<Spot | null>(null);\n  const [mode, setMode] = React.useState(0);\n  const [active, setActive] = React.useState<number | null>(null);\n\n  const radii = React.useMemo(\n    () => sizes(items, width, height),\n    [items, width, height],\n  );\n  const homes = React.useMemo(() => {\n    const together = items.map(() => ({ x: width / 2, y: height / 2 }));\n    const apart = items.map((item) => ({\n      x: ((item.group + 0.5) / Math.max(1, groups.length)) * width,\n      y: height / 2 + 8,\n    }));\n    return [\n      settle(radii, together, width, height),\n      settle(radii, apart, width, height),\n    ];\n  }, [items, groups.length, radii, width, height]);\n  const home = homes[mode];\n\n  const motion = React.useRef(\n    home.map((h) => ({ x: h.x, y: h.y, vx: 0, vy: 0 })),\n  );\n\n  // Bubbles spring to their resting spots, shoulder each other out of the way, and lean toward the pointer.\n  React.useEffect(() => {\n    let raf = 0;\n    let prev = 0;\n    const place = () =>\n      motion.current.forEach((m, i) => {\n        nodeRefs.current[i]?.setAttribute(\n          \"transform\",\n          `translate(${m.x.toFixed(2)} ${m.y.toFixed(2)})`,\n        );\n      });\n    const frame = (now: number) => {\n      const dt = Math.min(0.033, prev ? (now - prev) / 1000 : 1 / 60);\n      prev = now;\n      const list = motion.current;\n      const target = pointer.current;\n      let busy = target !== null;\n      list.forEach((m, i) => {\n        const h = home[i];\n        let ax = (h.x - m.x) * 26 - m.vx * 8;\n        let ay = (h.y - m.y) * 26 - m.vy * 8;\n        if (target) {\n          const dx = target.x - m.x;\n          const dy = target.y - m.y;\n          const distance = Math.sqrt(dx * dx + dy * dy) || 1;\n          if (distance < 240) {\n            const force = (1 - distance / 240) * 1500 * pull;\n            ax += (dx / distance) * force;\n            ay += (dy / distance) * force;\n          }\n        }\n        m.vx += ax * dt;\n        m.vy += ay * dt;\n        m.x += m.vx * dt;\n        m.y += m.vy * dt;\n      });\n      for (let pass = 0; pass < 4; pass++) {\n        for (let i = 0; i < list.length; i++) {\n          for (let j = i + 1; j < list.length; j++) {\n            const dx = list[j].x - list[i].x;\n            const dy = list[j].y - list[i].y;\n            const distance = Math.sqrt(dx * dx + dy * dy) || 1;\n            const gap = radii[i] + radii[j] + PAD;\n            if (distance < gap) {\n              const push = ((gap - distance) / distance) * 0.5;\n              list[i].x -= dx * push;\n              list[i].y -= dy * push;\n              list[j].x += dx * push;\n              list[j].y += dy * push;\n            }\n          }\n        }\n      }\n      list.forEach((m, i) => {\n        const h = home[i];\n        const r = radii[i] + 1;\n        m.x = Math.min(width - r, Math.max(r, m.x));\n        m.y = Math.min(height - r, Math.max(r, m.y));\n        const still =\n          Math.abs(h.x - m.x) < 0.25 &&\n          Math.abs(h.y - m.y) < 0.25 &&\n          Math.abs(m.vx) < 2 &&\n          Math.abs(m.vy) < 2;\n        if (!still) busy = true;\n      });\n      if (!busy) {\n        // Every bubble is home, so land it exactly and let the loop rest.\n        list.forEach((m, i) => {\n          m.x = home[i].x;\n          m.y = home[i].y;\n          m.vx = 0;\n          m.vy = 0;\n        });\n      }\n      place();\n      if (busy && !document.hidden) raf = requestAnimationFrame(frame);\n      else {\n        raf = 0;\n        prev = 0;\n      }\n    };\n    start.current = () => {\n      if (reduce) {\n        motion.current = home.map((h) => ({ ...h, vx: 0, vy: 0 }));\n        place();\n      } else if (!raf) raf = requestAnimationFrame(frame);\n    };\n    if (motion.current.length !== home.length) {\n      motion.current = home.map((h) => ({ ...h, vx: 0, vy: 0 }));\n    }\n    const resume = () => {\n      if (!document.hidden) start.current();\n    };\n    document.addEventListener(\"visibilitychange\", resume);\n    start.current();\n    return () => {\n      document.removeEventListener(\"visibilitychange\", resume);\n      cancelAnimationFrame(raf);\n      raf = 0;\n    };\n  }, [home, radii, width, height, pull, reduce]);\n\n  const fills = [pal.accent, pal.blue, pal.sub];\n  const total = items.reduce((n, i) => n + i.value, 0);\n  const largest = items.reduce(\n    (best, i) => (i.value > best.value ? i : best),\n    items[0] ?? { label: \"—\", value: 0, group: 0 },\n  );\n  const sums = groups.map((_, g) =>\n    items.filter((i) => i.group === g).reduce((n, i) => n + i.value, 0),\n  );\n  const topGroup = sums.indexOf(Math.max(0, ...sums));\n  const item = active === null ? null : items[active];\n\n  return (\n    <section\n      className={`w-full rounded-2xl p-5 sm:p-6 ${className ?? \"\"}`}\n      style={{\n        background: pal.card,\n        boxShadow: `inset 0 0 0 1px ${pal.border}`,\n        color: pal.text,\n        fontFamily: CARD_FONT,\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-x-8 gap-y-3\">\n        <div>\n          <h3 className=\"m-0 text-[17px] leading-[1.33] font-[590] tracking-[-0.012em]\">\n            {title}\n          </h3>\n          <p\n            className=\"m-0 mt-0.5 text-[13px] tracking-[-0.011em]\"\n            style={{ color: pal.sub }}\n          >\n            {subtitle}\n          </p>\n        </div>\n        <div className=\"flex flex-wrap gap-x-7 gap-y-3\">\n          <Stat value={formatValue(total)} label={`Total ${unit}`} pal={pal} />\n          <Stat value={largest.label} label=\"Biggest project\" pal={pal} />\n          <Stat\n            value={total > 0 ? (groups[topGroup] ?? \"—\") : \"—\"}\n            label=\"Busiest team\"\n            pal={pal}\n          />\n        </div>\n      </div>\n\n      {!items.length ? (\n        <p className=\"py-16 text-center text-sm\" style={{ color: pal.sub }}>\n          No data available.\n        </p>\n      ) : (\n        <div\n          ref={boxRef}\n          className=\"relative mt-4 touch-pan-y\"\n          onPointerMove={(e) => {\n            if (e.pointerType !== \"mouse\" || !pull) return;\n            const r = e.currentTarget.getBoundingClientRect();\n            pointer.current = { x: e.clientX - r.left, y: e.clientY - r.top };\n            start.current();\n          }}\n          onPointerLeave={() => {\n            pointer.current = null;\n            setActive(null);\n            start.current();\n          }}\n        >\n          <svg\n            viewBox={`0 0 ${width} ${height}`}\n            className=\"block w-full\"\n            style={{ height }}\n            role=\"group\"\n            aria-label={`${formatValue(total)} ${unit}. Largest: ${largest.label}, ${formatValue(largest.value)}.`}\n          >\n            {groups.map((g, i) => (\n              <text\n                key={g}\n                x={((i + 0.5) / groups.length) * width}\n                y=\"11\"\n                textAnchor=\"middle\"\n                fontSize=\"12\"\n                fontWeight=\"510\"\n                fill={pal.sub}\n                className=\"motion-safe:transition-opacity motion-safe:duration-300\"\n                style={{ opacity: mode === 1 ? 1 : 0 }}\n              >\n                {g}\n              </text>\n            ))}\n            {items.map((b, i) => {\n              const r = radii[i];\n              const on = active === i;\n              return (\n                <g\n                  key={b.label}\n                  role=\"button\"\n                  tabIndex={0}\n                  aria-label={`${b.label}, ${groups[b.group]}, ${formatValue(b.value)} ${unit}`}\n                  onFocus={() => setActive(i)}\n                  onBlur={() => setActive(null)}\n                  onClick={() => setActive(i)}\n                  onKeyDown={(event) => {\n                    if (event.key === \"Escape\") {\n                      setActive(null);\n                      return;\n                    }\n                    if ([\"Enter\", \" \"].includes(event.key)) {\n                      event.preventDefault();\n                      setActive(i);\n                      return;\n                    }\n                    if (\n                      ![\"ArrowLeft\", \"ArrowRight\", \"Home\", \"End\"].includes(\n                        event.key,\n                      )\n                    )\n                      return;\n                    event.preventDefault();\n                    const next =\n                      event.key === \"Home\"\n                        ? 0\n                        : event.key === \"End\"\n                          ? items.length - 1\n                          : (i +\n                              (event.key === \"ArrowRight\" ? 1 : -1) +\n                              items.length) %\n                            items.length;\n                    nodeRefs.current[next]?.focus();\n                  }}\n                  ref={(el) => {\n                    nodeRefs.current[i] = el;\n                  }}\n                  transform={`translate(${home[i].x} ${home[i].y})`}\n                  onPointerEnter={() => setActive(i)}\n                  onPointerLeave={() => setActive(null)}\n                >\n                  <circle\n                    r={r}\n                    fill={fills[b.group % fills.length]}\n                    fillOpacity={active !== null && !on ? 0.45 : 0.9}\n                    stroke={on ? pal.text : \"none\"}\n                    className=\"motion-safe:transition-[fill-opacity] motion-safe:duration-150\"\n                  />\n                  {r > b.label.length * 3.3 + 3 && (\n                    <text\n                      y=\"4\"\n                      textAnchor=\"middle\"\n                      fontSize=\"11\"\n                      fontWeight=\"510\"\n                      fill=\"#FFFFFF\"\n                      pointerEvents=\"none\"\n                    >\n                      {b.label}\n                    </text>\n                  )}\n                </g>\n              );\n            })}\n          </svg>\n\n          {item && active !== null && (\n            <Tip x={width / 2} y={42} width={width} pal={pal}>\n              <span className=\"font-[510]\" style={{ color: pal.text }}>\n                {formatValue(item.value)} {unit}\n              </span>{\" \"}\n              on {item.label}, {groups[item.group]}\n            </Tip>\n          )}\n        </div>\n      )}\n\n      <div className=\"mt-3 flex flex-wrap items-center justify-between gap-2\">\n        <Pills\n          label=\"Layout\"\n          options={MODES}\n          value={mode}\n          onChange={setMode}\n          pal={pal}\n        />\n        <div\n          className=\"flex items-center gap-3 text-[12px]\"\n          style={{ color: pal.sub }}\n        >\n          {groups.map((g, i) => (\n            <span key={g} className=\"flex items-center gap-1.5\">\n              <span\n                className=\"size-2 rounded-full\"\n                style={{ background: fills[i % fills.length] }}\n              />\n              {g}\n            </span>\n          ))}\n        </div>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}