{"spec_id":"circlepacking-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// circlepacking-basic: Circle Packing Chart\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 88/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useDrawingArea } from \"@mui/x-charts/hooks\";\nimport { ChartsText } from \"@mui/x-charts/ChartsText\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"circlepacking-basic · javascript · muix · anyplot.ai\";\nconst MARGIN = { top: 16, right: 24, bottom: 24, left: 24 };\nconst HEADER_HEIGHT = 136;\nconst LEAF_RADIUS_SCALE = 8;\nconst SIBLING_PADDING_RATIO = 0.06;\nconst PARENT_PADDING_RATIO = 0.08;\nconst PACK_ATTRACTION = 0.02;\nconst PACK_ITERATIONS = 400;\nconst SEED_SPREAD = 1.4;\nconst INNER_FILL_OPACITY = 0.14;\nconst LEAF_FILL_OPACITY = 0.92;\n\n// Columns: set these to your data's column names\nconst ID = \"Node ID\"; // role: id\nconst PARENT = \"Parent ID\"; // role: parent\nconst LABEL = \"Asset class / holding\"; // role: label\nconst VALUE = \"Market value ($K)\"; // role: value\n\n// Data: replace this block with your own records\nconst data = [\n  { [ID]: \"portfolio\", [PARENT]: null, [LABEL]: \"Portfolio\", [VALUE]: null },\n  { [ID]: \"equities\", [PARENT]: \"portfolio\", [LABEL]: \"Equities\", [VALUE]: null },\n  { [ID]: \"us-large-cap\", [PARENT]: \"equities\", [LABEL]: \"US Large Cap\", [VALUE]: 420 },\n  { [ID]: \"us-small-cap\", [PARENT]: \"equities\", [LABEL]: \"US Small Cap\", [VALUE]: 140 },\n  { [ID]: \"intl-developed\", [PARENT]: \"equities\", [LABEL]: \"Int'l Developed\", [VALUE]: 210 },\n  { [ID]: \"emerging-markets\", [PARENT]: \"equities\", [LABEL]: \"Emerging Markets\", [VALUE]: 95 },\n  { [ID]: \"fixed-income\", [PARENT]: \"portfolio\", [LABEL]: \"Fixed Income\", [VALUE]: null },\n  { [ID]: \"gov-bonds\", [PARENT]: \"fixed-income\", [LABEL]: \"Government Bonds\", [VALUE]: 260 },\n  { [ID]: \"corp-bonds\", [PARENT]: \"fixed-income\", [LABEL]: \"Corporate Bonds\", [VALUE]: 180 },\n  { [ID]: \"muni-bonds\", [PARENT]: \"fixed-income\", [LABEL]: \"Municipal Bonds\", [VALUE]: 90 },\n  { [ID]: \"real-estate\", [PARENT]: \"portfolio\", [LABEL]: \"Real Estate\", [VALUE]: null },\n  { [ID]: \"reits\", [PARENT]: \"real-estate\", [LABEL]: \"REITs\", [VALUE]: 150 },\n  { [ID]: \"direct-property\", [PARENT]: \"real-estate\", [LABEL]: \"Direct Property\", [VALUE]: 110 },\n  { [ID]: \"alternatives\", [PARENT]: \"portfolio\", [LABEL]: \"Alternatives\", [VALUE]: null },\n  { [ID]: \"private-equity\", [PARENT]: \"alternatives\", [LABEL]: \"Private Equity\", [VALUE]: 130 },\n  { [ID]: \"commodities\", [PARENT]: \"alternatives\", [LABEL]: \"Commodities\", [VALUE]: 70 },\n  { [ID]: \"hedge-funds\", [PARENT]: \"alternatives\", [LABEL]: \"Hedge Funds\", [VALUE]: 85 },\n  { [ID]: \"cash\", [PARENT]: \"portfolio\", [LABEL]: \"Cash & Equivalents\", [VALUE]: null },\n  { [ID]: \"money-market\", [PARENT]: \"cash\", [LABEL]: \"Money Market\", [VALUE]: 60 },\n  { [ID]: \"treasury-bills\", [PARENT]: \"cash\", [LABEL]: \"Treasury Bills\", [VALUE]: 40 },\n];\n\n// Plot: reads only data and the constants above\nconst VALUE_UNIT = VALUE.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst unitSuffix = VALUE_UNIT ? ` ${VALUE_UNIT}` : \"\";\n\nconst nodes = data.map((row) => ({\n  id: String(row[ID]),\n  parent: row[PARENT] == null ? null : String(row[PARENT]),\n  label: String(row[LABEL]),\n  value: Number(row[VALUE] ?? 0),\n  children: [] as any[],\n  depth: 0,\n  x: 0,\n  y: 0,\n  r: 0,\n  cx: 0,\n  cy: 0,\n  color: t.palette[0],\n  ink: \"#1A1A17\",\n  lines: [String(row[LABEL])],\n}));\n\nconst byId = new Map(nodes.map((n) => [n.id, n]));\nlet root = nodes[0];\nfor (const node of nodes) {\n  if (node.parent == null) {\n    root = node;\n  } else {\n    byId.get(node.parent)?.children.push(node);\n  }\n}\n\nconst order = [root];\nfor (let i = 0; i < order.length; i++) {\n  const curr = order[i];\n  for (const child of curr.children) {\n    child.depth = curr.depth + 1;\n    order.push(child);\n  }\n}\n\nroot.children.forEach((branch, i) => {\n  branch.color = t.palette[i];\n});\nfor (const node of order) {\n  if (node.depth > 1 && node.parent != null) {\n    const parentNode = byId.get(node.parent);\n    if (parentNode) node.color = parentNode.color;\n  }\n  const hexNum = parseInt(node.color.slice(1), 16);\n  const rgb = [(hexNum >> 16) & 255, (hexNum >> 8) & 255, hexNum & 255];\n  const lin = rgb.map((v) => {\n    const s = v / 255;\n    return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n  });\n  const lum = 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];\n  node.ink = lum > 0.18 ? \"#1A1A17\" : \"#FAF8F1\";\n\n  const words = node.label.split(\" \");\n  if (words.length <= 1 || node.label.length <= 10) {\n    node.lines = [node.label];\n  } else {\n    let best = [node.label];\n    let bestDiff = Infinity;\n    for (let k = 1; k < words.length; k++) {\n      const l1 = words.slice(0, k).join(\" \");\n      const l2 = words.slice(k).join(\" \");\n      const diff = Math.abs(l1.length - l2.length);\n      if (diff < bestDiff) {\n        bestDiff = diff;\n        best = [l1, l2];\n      }\n    }\n    node.lines = best;\n  }\n}\n\nlet lcgState = 42;\nfor (let idx = order.length - 1; idx >= 0; idx--) {\n  const node = order[idx];\n  if (node.children.length === 0) {\n    node.r = LEAF_RADIUS_SCALE * Math.sqrt(node.value);\n    continue;\n  }\n  node.value = node.children.reduce((sum, c) => sum + c.value, 0);\n  const children = node.children;\n  const sorted = [...children].sort((a, b) => b.r - a.r);\n  const meanChildR = children.reduce((sum, c) => sum + c.r, 0) / children.length;\n  const siblingPad = meanChildR * SIBLING_PADDING_RATIO;\n  const seedRadius = sorted[0].r * SEED_SPREAD;\n\n  sorted.forEach((c, i) => {\n    const angle = (2 * Math.PI * i) / sorted.length;\n    lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n    const jx = (lcgState / 4294967296 - 0.5) * 4;\n    lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n    const jy = (lcgState / 4294967296 - 0.5) * 4;\n    c.x = Math.cos(angle) * seedRadius + jx;\n    c.y = Math.sin(angle) * seedRadius + jy;\n  });\n\n  for (let iter = 0; iter < PACK_ITERATIONS; iter++) {\n    for (const c of children) {\n      c.x -= c.x * PACK_ATTRACTION;\n      c.y -= c.y * PACK_ATTRACTION;\n    }\n    for (let i = 0; i < children.length; i++) {\n      for (let j = i + 1; j < children.length; j++) {\n        const a = children[i];\n        const b = children[j];\n        const dx = b.x - a.x;\n        const dy = b.y - a.y;\n        const dist = Math.hypot(dx, dy) || 0.01;\n        const minDist = a.r + b.r + siblingPad;\n        if (dist < minDist) {\n          const overlap = (minDist - dist) / 2;\n          const ux = dx / dist;\n          const uy = dy / dist;\n          a.x -= ux * overlap;\n          a.y -= uy * overlap;\n          b.x += ux * overlap;\n          b.y += uy * overlap;\n        }\n      }\n    }\n  }\n\n  const minX = Math.min(...children.map((c) => c.x - c.r));\n  const maxX = Math.max(...children.map((c) => c.x + c.r));\n  const minY = Math.min(...children.map((c) => c.y - c.r));\n  const maxY = Math.max(...children.map((c) => c.y + c.r));\n  const shiftX = (minX + maxX) / 2;\n  const shiftY = (minY + maxY) / 2;\n  for (const c of children) {\n    c.x -= shiftX;\n    c.y -= shiftY;\n  }\n\n  let enclosing = 0;\n  for (const c of children) {\n    enclosing = Math.max(enclosing, Math.hypot(c.x, c.y) + c.r);\n  }\n  node.r = enclosing * (1 + PARENT_PADDING_RATIO);\n}\n\nfor (const node of order) {\n  for (const child of node.children) {\n    child.cx = node.cx + child.x;\n    child.cy = node.cy + child.y;\n  }\n}\n\nconst SUBTITLE = `${root.label} · ${root.children.length} groups · total ${root.value.toLocaleString()}${unitSuffix} · circle area ∝ ${VALUE}`;\n\nfunction CirclePacking() {\n  const { left, top, width, height } = useDrawingArea();\n  const availableRadius = Math.min(width, height) / 2 - 4;\n  const scale = availableRadius / root.r;\n  const originX = left + width / 2;\n  const originY = top + height / 2;\n\n  return (\n    <g>\n      {order.map((node) => {\n        const nCx = originX + node.cx * scale;\n        const nCy = originY + node.cy * scale;\n        const nR = node.r * scale;\n        const formattedVal = `${node.value.toLocaleString()}${unitSuffix}`;\n\n        if (node.depth === 0) {\n          return (\n            <circle\n              key={node.id}\n              cx={nCx}\n              cy={nCy}\n              r={nR}\n              fill=\"none\"\n              stroke={t.inkSoft}\n              strokeOpacity={0.35}\n              strokeWidth={1.5}\n            />\n          );\n        }\n\n        if (node.children.length > 0) {\n          return (\n            <circle\n              key={node.id}\n              cx={nCx}\n              cy={nCy}\n              r={nR}\n              fill={node.color}\n              fillOpacity={INNER_FILL_OPACITY}\n              stroke={node.color}\n              strokeOpacity={0.85}\n              strokeWidth={2}\n            >\n              <title>{`${node.label}: ${formattedVal}`}</title>\n            </circle>\n          );\n        }\n\n        const nameSize = Math.max(14, Math.min(17, Math.round(nR * 0.22)));\n        const valueSize = 14;\n        const maxLineChars = Math.max(...node.lines.map((line: string) => line.length));\n        const reqHalfWidth = (maxLineChars * nameSize * 0.56) / 2;\n        const showName = nR >= 32 && reqHalfWidth <= nR * 0.9;\n        const showValue = showName && nR >= 46;\n        const lineHeightEm = 1.18;\n        const nameHalfHeight = (node.lines.length * nameSize * lineHeightEm) / 2;\n        const valueHalfHeight = (valueSize * lineHeightEm) / 2;\n        const gap = nameSize * 0.28;\n        const nameCenterY = showValue ? nCy - valueHalfHeight - gap / 2 : nCy;\n        const valueCenterY = nCy + nameHalfHeight + gap / 2;\n\n        return (\n          <g key={node.id}>\n            <circle\n              cx={nCx}\n              cy={nCy}\n              r={nR}\n              fill={node.color}\n              fillOpacity={LEAF_FILL_OPACITY}\n              stroke={t.pageBg}\n              strokeWidth={2}\n            >\n              <title>{`${node.label}: ${formattedVal}`}</title>\n            </circle>\n            {showName && (\n              <ChartsText\n                text={node.lines.join(\"\\n\")}\n                x={nCx}\n                y={nameCenterY}\n                style={{\n                  fontSize: nameSize,\n                  fontWeight: 600,\n                  fill: node.ink,\n                  textAnchor: \"middle\",\n                  dominantBaseline: \"central\",\n                }}\n              />\n            )}\n            {showValue && (\n              <ChartsText\n                text={formattedVal}\n                x={nCx}\n                y={valueCenterY}\n                opacity={0.92}\n                style={{\n                  fontSize: valueSize,\n                  fill: node.ink,\n                  textAnchor: \"middle\",\n                  dominantBaseline: \"central\",\n                }}\n              />\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartHeight = height - HEADER_HEIGHT;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        backgroundColor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        fontFamily: \"Inter, system-ui, sans-serif\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_HEIGHT,\n          padding: \"18px 28px 0 28px\",\n          boxSizing: \"border-box\",\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.25 }}>\n          {TITLE}\n        </div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 4, lineHeight: 1.3 }}>\n          {SUBTITLE}\n        </div>\n        <div\n          style={{\n            display: \"flex\",\n            flexWrap: \"wrap\",\n            justifyContent: \"center\",\n            gap: \"8px 22px\",\n            marginTop: 12,\n            fontSize: 14,\n            color: t.inkSoft,\n          }}\n        >\n          {root.children.map((branch) => (\n            <div key={branch.id} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n              <span\n                style={{\n                  width: 14,\n                  height: 14,\n                  borderRadius: \"50%\",\n                  backgroundColor: branch.color,\n                  opacity: LEAF_FILL_OPACITY,\n                  display: \"inline-block\",\n                }}\n              />\n              <span>{`${branch.label} (${branch.value.toLocaleString()}${unitSuffix})`}</span>\n            </div>\n          ))}\n        </div>\n      </div>\n      <ChartsContainer\n        width={width}\n        height={chartHeight}\n        series={[]}\n        xAxis={[{ position: \"none\" }]}\n        yAxis={[{ position: \"none\" }]}\n        margin={MARGIN}\n        skipAnimation\n      >\n        <CirclePacking />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}