{"spec_id":"bubble-packed","library":"muix","language":"javascript","code":"// anyplot.ai\n// bubble-packed: Basic Packed Bubble Chart\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 85/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst HEADER_H = 118;\nconst MARGIN = 24;\nconst FILL_RATIO = 0.44;\nconst PADDING = 5;\nconst ATTRACTION = 0.032;\nconst ITERATIONS = 420;\nconst ANCHOR_SPREAD = 1.1; // pushes the group anchors outward from the centre of the drawing area\nconst DARK_TEXT = \"#1A1A17\";\nconst LIGHT_TEXT = \"#FAF8F1\";\n\n// Columns: set these to your data's column names\nconst LABEL = \"Product line\"; // role: label\nconst VALUE = \"Annual revenue ($M)\"; // role: value\nconst GROUP = \"Division\"; // role: group\n\n// Data: replace this block with your own records, one object per row\nconst data = [\n  { [LABEL]: \"Smart Speakers\", [GROUP]: \"Consumer Electronics\", [VALUE]: 42 },\n  { [LABEL]: \"Wireless Earbuds\", [GROUP]: \"Consumer Electronics\", [VALUE]: 68 },\n  { [LABEL]: \"4K Televisions\", [GROUP]: \"Consumer Electronics\", [VALUE]: 55 },\n  { [LABEL]: \"Home Routers\", [GROUP]: \"Consumer Electronics\", [VALUE]: 24 },\n  { [LABEL]: \"Streaming Devices\", [GROUP]: \"Consumer Electronics\", [VALUE]: 31 },\n  { [LABEL]: \"Digital Cameras\", [GROUP]: \"Consumer Electronics\", [VALUE]: 18 },\n  { [LABEL]: \"Gaming Consoles\", [GROUP]: \"Consumer Electronics\", [VALUE]: 74 },\n  { [LABEL]: \"Tablets\", [GROUP]: \"Consumer Electronics\", [VALUE]: 47 },\n  { [LABEL]: \"Laptops\", [GROUP]: \"Consumer Electronics\", [VALUE]: 89 },\n  { [LABEL]: \"Cloud Storage\", [GROUP]: \"Software & Cloud\", [VALUE]: 95 },\n  { [LABEL]: \"Productivity Suite\", [GROUP]: \"Software & Cloud\", [VALUE]: 61 },\n  { [LABEL]: \"Video Conferencing\", [GROUP]: \"Software & Cloud\", [VALUE]: 38 },\n  { [LABEL]: \"Cybersecurity Tools\", [GROUP]: \"Software & Cloud\", [VALUE]: 52 },\n  { [LABEL]: \"Analytics Platform\", [GROUP]: \"Software & Cloud\", [VALUE]: 44 },\n  { [LABEL]: \"CRM Software\", [GROUP]: \"Software & Cloud\", [VALUE]: 33 },\n  { [LABEL]: \"Developer Tools\", [GROUP]: \"Software & Cloud\", [VALUE]: 27 },\n  { [LABEL]: \"AI Assistant\", [GROUP]: \"Software & Cloud\", [VALUE]: 58 },\n  { [LABEL]: \"Collaboration Suite\", [GROUP]: \"Software & Cloud\", [VALUE]: 29 },\n  { [LABEL]: \"Robotic Arms\", [GROUP]: \"Industrial Equipment\", [VALUE]: 71 },\n  { [LABEL]: \"CNC Machines\", [GROUP]: \"Industrial Equipment\", [VALUE]: 48 },\n  { [LABEL]: \"Conveyor Systems\", [GROUP]: \"Industrial Equipment\", [VALUE]: 22 },\n  { [LABEL]: \"Industrial Sensors\", [GROUP]: \"Industrial Equipment\", [VALUE]: 36 },\n  { [LABEL]: \"3D Printers\", [GROUP]: \"Industrial Equipment\", [VALUE]: 19 },\n  { [LABEL]: \"Hydraulic Presses\", [GROUP]: \"Industrial Equipment\", [VALUE]: 41 },\n  { [LABEL]: \"Welding Robots\", [GROUP]: \"Industrial Equipment\", [VALUE]: 53 },\n  { [LABEL]: \"Packaging Machines\", [GROUP]: \"Industrial Equipment\", [VALUE]: 26 },\n  { [LABEL]: \"Quality Scanners\", [GROUP]: \"Industrial Equipment\", [VALUE]: 15 },\n  { [LABEL]: \"Fitness Trackers\", [GROUP]: \"Health & Wearables\", [VALUE]: 39 },\n  { [LABEL]: \"Smartwatches\", [GROUP]: \"Health & Wearables\", [VALUE]: 62 },\n  { [LABEL]: \"Blood Pressure Monitors\", [GROUP]: \"Health & Wearables\", [VALUE]: 21 },\n  { [LABEL]: \"Glucose Monitors\", [GROUP]: \"Health & Wearables\", [VALUE]: 34 },\n  { [LABEL]: \"Sleep Trackers\", [GROUP]: \"Health & Wearables\", [VALUE]: 17 },\n  { [LABEL]: \"Posture Sensors\", [GROUP]: \"Health & Wearables\", [VALUE]: 12 },\n  { [LABEL]: \"Hearing Aids\", [GROUP]: \"Health & Wearables\", [VALUE]: 45 },\n  { [LABEL]: \"Smart Scales\", [GROUP]: \"Health & Wearables\", [VALUE]: 14 },\n  { [LABEL]: \"Recovery Devices\", [GROUP]: \"Health & Wearables\", [VALUE]: 23 },\n];\n\n// Plot: reads only data and the constants above\nconst groups = Array.from(new Set(data.map((d) => d[GROUP])));\n\nconst groupMeta = Object.fromEntries(\n  groups.map((g, i) => {\n    const color = t.palette[i];\n    const hexVal = Number.parseInt(color.replace(\"#\", \"\"), 16);\n    const srgb = [(hexVal >> 16) & 255, (hexVal >> 8) & 255, hexVal & 255].map(\n      (v) => {\n        const c = v / 255;\n        return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n      },\n    );\n    const lum = 0.2126 * srgb[0] + 0.7152 * srgb[1] + 0.0722 * srgb[2];\n    const darkContrast = (Math.max(lum, 0.01) + 0.05) / (0.01 + 0.05);\n    const lightContrast = (0.96 + 0.05) / (Math.min(lum, 0.96) + 0.05);\n    const labelInk = darkContrast >= lightContrast ? DARK_TEXT : LIGHT_TEXT;\n    return [g, { index: i, color, labelInk }];\n  }),\n);\n\nconst totalValue = data.reduce((sum, d) => sum + d[VALUE], 0);\nconst TITLE = \"bubble-packed · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${data.length} bubbles (${LABEL}) · ${groups.length} groups (${GROUP}) · Area ∝ ${VALUE}, total ${totalValue.toLocaleString(\"en-US\")}`;\n\nfunction PackedBubblesLayer() {\n  const { left, top, width, height } = useDrawingArea();\n  const radiusScale = Math.sqrt(\n    (FILL_RATIO * width * height) / (Math.PI * (totalValue || 1)),\n  );\n\n  const cols = Math.ceil(Math.sqrt(groups.length));\n  const rows = Math.ceil(groups.length / cols);\n\n  const anchors = Object.fromEntries(\n    groups.map((g, idx) => {\n      const col = idx % cols;\n      const row = Math.floor(idx / cols);\n      const ax = left + width * (0.5 + ((col + 0.5) / cols - 0.5) * ANCHOR_SPREAD);\n      const ay = top + height * (0.5 + ((row + 0.5) / rows - 0.5) * ANCHOR_SPREAD);\n      return [g, { x: ax, y: ay }];\n    }),\n  );\n\n  let seedState = 42;\n  const bubbles = data.map((d) => {\n    const groupName = d[GROUP];\n    const anchor = anchors[groupName];\n    seedState = (seedState * 1664525 + 1013904223) % 4294967296;\n    const rx = seedState / 4294967296 - 0.5;\n    seedState = (seedState * 1664525 + 1013904223) % 4294967296;\n    const ry = seedState / 4294967296 - 0.5;\n    return {\n      label: d[LABEL],\n      group: groupName,\n      value: d[VALUE],\n      r: radiusScale * Math.sqrt(Math.max(0, d[VALUE])),\n      x: anchor.x + rx * 60,\n      y: anchor.y + ry * 60,\n    };\n  });\n\n  const resolveCollisions = () => {\n    let maxOverlap = 0;\n    for (let i = 0; i < bubbles.length; i += 1) {\n      for (let j = i + 1; j < bubbles.length; j += 1) {\n        const a = bubbles[i];\n        const c = bubbles[j];\n        const dx = c.x - a.x;\n        const dy = c.y - a.y;\n        const dist = Math.hypot(dx, dy) || 0.01;\n        const minDist = a.r + c.r + PADDING;\n        if (dist < minDist) {\n          const overlap = (minDist - dist) / 2;\n          maxOverlap = Math.max(maxOverlap, overlap);\n          const ux = dx / dist;\n          const uy = dy / dist;\n          a.x -= ux * overlap;\n          a.y -= uy * overlap;\n          c.x += ux * overlap;\n          c.y += uy * overlap;\n        }\n      }\n    }\n    return maxOverlap;\n  };\n\n  for (let iter = 0; iter < ITERATIONS; iter += 1) {\n    const pull = ATTRACTION * (1 - iter / ITERATIONS);\n    for (const b of bubbles) {\n      const anchor = anchors[b.group];\n      b.x += (anchor.x - b.x) * pull;\n      b.y += (anchor.y - b.y) * pull;\n    }\n    resolveCollisions();\n    for (const b of bubbles) {\n      b.x = Math.min(left + width - b.r, Math.max(left + b.r, b.x));\n      b.y = Math.min(top + height - b.r, Math.max(top + b.r, b.y));\n    }\n  }\n  // Collision-only passes: no attraction or clamp, so no circle ends crossing another\n  let pass = 0;\n  while (pass < 500 && resolveCollisions() > 0.01) pass += 1;\n\n  return (\n    <g>\n      {bubbles.map((b) => {\n        const meta = groupMeta[b.group];\n        const valueStr = b.value.toLocaleString(\"en-US\");\n        const words = b.label.split(\" \");\n        const singleLineFits = b.label.length * 8.4 + 20 <= b.r * 2 && b.r >= 52;\n        const twoLines =\n          !singleLineFits && words.length === 2\n            ? [words[0], words[1]]\n            : !singleLineFits && words.length === 3\n              ? [`${words[0]} ${words[1]}`, words[2]]\n              : [b.label];\n        const longestLineChars = Math.max(...twoLines.map((line) => line.length));\n        const multiLineFits =\n          twoLines.length > 1 &&\n          longestLineChars * 8.2 + 18 <= b.r * 1.82 &&\n          b.r >= 48;\n        const showName = singleLineFits || multiLineFits;\n        const nameLines = singleLineFits ? [b.label] : twoLines;\n        const showValue = b.r >= 30;\n\n        return (\n          <g key={b.label}>\n            <circle\n              cx={b.x}\n              cy={b.y}\n              r={b.r}\n              fill={meta.color}\n              stroke={t.pageBg}\n              strokeWidth={2}\n            >\n              <title>{`${b.label} (${b.group}) · ${VALUE}: ${valueStr}`}</title>\n            </circle>\n            {showName &&\n              nameLines.map((line, idx) => {\n                const baseOffset =\n                  nameLines.length === 1\n                    ? -8\n                    : idx === 0\n                      ? -18\n                      : -1;\n                return (\n                  <text\n                    key={`${b.label}-line-${idx}`}\n                    x={b.x}\n                    y={b.y + baseOffset}\n                    textAnchor=\"middle\"\n                    dominantBaseline=\"central\"\n                    fontSize={14}\n                    fontWeight={600}\n                    fill={meta.labelInk}\n                  >\n                    {line}\n                  </text>\n                );\n              })}\n            {showValue && (\n              <text\n                x={b.x}\n                y={\n                  b.y +\n                  (showName\n                    ? nameLines.length === 1\n                      ? 12\n                      : 18\n                    : 0)\n                }\n                textAnchor=\"middle\"\n                dominantBaseline=\"central\"\n                fontSize={14}\n                fontWeight={showName ? 500 : 600}\n                fill={meta.labelInk}\n              >\n                {valueStr}\n              </text>\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const surfaceHeight = height - HEADER_H;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        background: t.pageBg,\n        fontFamily: \"Inter, system-ui, sans-serif\",\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_H,\n          paddingLeft: MARGIN,\n          paddingRight: MARGIN,\n          display: \"flex\",\n          flexDirection: \"column\",\n          justifyContent: \"center\",\n          gap: 8,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>\n          {TITLE}\n        </div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n        <div\n          style={{\n            display: \"flex\",\n            flexWrap: \"wrap\",\n            gap: 24,\n            alignItems: \"center\",\n            paddingTop: 2,\n          }}\n        >\n          {groups.map((g) => (\n            <div\n              key={g}\n              style={{\n                display: \"flex\",\n                alignItems: \"center\",\n                gap: 8,\n                fontSize: 14,\n                color: t.inkSoft,\n              }}\n            >\n              <span\n                style={{\n                  width: 14,\n                  height: 14,\n                  borderRadius: \"50%\",\n                  background: groupMeta[g].color,\n                  display: \"inline-block\",\n                }}\n              />\n              <span>{g}</span>\n            </div>\n          ))}\n        </div>\n      </div>\n\n      <ChartsContainer\n        width={width}\n        height={surfaceHeight}\n        series={[]}\n        skipAnimation\n        margin={{ top: MARGIN, right: MARGIN, bottom: MARGIN, left: MARGIN }}\n      >\n        <PackedBubblesLayer />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}