{"spec_id":"donut-nested","library":"muix","language":"javascript","code":"// anyplot.ai\n// donut-nested: Nested Donut Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\nimport { PieChart } from \"@mui/x-charts/PieChart\";\nimport { useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TINT_FIRST = 0.12; // share of white mixed into a parent's first child\nconst TINT_LAST = 0.6; // share of white mixed into its last child, still clear of the page in both themes\nconst DARK_INK = \"#1A1A17\"; // fixed label inks: segment colours do not change with the theme\nconst LIGHT_INK = \"#FAF8F1\";\nconst INK_SPLIT = 0.194; // relative luminance at which both inks reach the same WCAG contrast\nconst OUTER_LABEL_MIN_ANGLE = 22; // degrees; narrower outer segments are named in the legend only\nconst TITLE = \"donut-nested · javascript · muix · anyplot.ai\";\nconst TITLE_H = 72;\nconst LEGEND_H = 124; // two legend rows plus the 28 px bottom padding of the page\n\n// Columns: set these to your data's column names\nconst BUSINESS_UNIT = \"Business unit\"; // role: level_1\nconst CUSTOMER_SEGMENT = \"Customer segment\"; // role: level_2\nconst REVENUE = \"Revenue (million USD)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Annual revenue of a technology company by business unit and customer segment\nconst data = [\n  { [BUSINESS_UNIT]: \"Software\", [CUSTOMER_SEGMENT]: \"Enterprise SaaS\", [REVENUE]: 380 },\n  { [BUSINESS_UNIT]: \"Software\", [CUSTOMER_SEGMENT]: \"SMB Subscriptions\", [REVENUE]: 210 },\n  { [BUSINESS_UNIT]: \"Software\", [CUSTOMER_SEGMENT]: \"Developer Tools\", [REVENUE]: 120 },\n  { [BUSINESS_UNIT]: \"Hardware\", [CUSTOMER_SEGMENT]: \"Enterprise Devices\", [REVENUE]: 260 },\n  { [BUSINESS_UNIT]: \"Hardware\", [CUSTOMER_SEGMENT]: \"Consumer Devices\", [REVENUE]: 180 },\n  { [BUSINESS_UNIT]: \"Services\", [CUSTOMER_SEGMENT]: \"Managed Support\", [REVENUE]: 150 },\n  { [BUSINESS_UNIT]: \"Services\", [CUSTOMER_SEGMENT]: \"Professional Services\", [REVENUE]: 130 },\n  { [BUSINESS_UNIT]: \"Services\", [CUSTOMER_SEGMENT]: \"Training\", [REVENUE]: 70 },\n  { [BUSINESS_UNIT]: \"Consulting\", [CUSTOMER_SEGMENT]: \"Strategy Advisory\", [REVENUE]: 140 },\n  { [BUSINESS_UNIT]: \"Consulting\", [CUSTOMER_SEGMENT]: \"Implementation\", [REVENUE]: 100 },\n];\n\n// Plot: reads only data and the constants above\nconst units = [...new Set(data.map((d) => d[BUSINESS_UNIT]))];\nconst total = data.reduce((sum, d) => sum + d[REVENUE], 0);\nconst revenueUnit = REVENUE.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\n\n// Inner ring: one segment per business unit, its value aggregated from its children\nconst inner = units.map((unit, i) => ({\n  id: `unit-${i}`,\n  // Units carry their own arc label, so the legend lists only the customer segments\n  label: (location) => (location === \"legend\" ? undefined : unit),\n  value: data.filter((d) => d[BUSINESS_UNIT] === unit).reduce((sum, d) => sum + d[REVENUE], 0),\n  color: t.palette[i],\n}));\n\n// Outer ring: children grouped under their unit in the inner ring's order, so every child\n// sits inside its parent's arc; children mix the parent's hue with white, lighter in order\nconst outer = units.flatMap((unit, i) => {\n  const children = data.filter((d) => d[BUSINESS_UNIT] === unit);\n  const rgb = [1, 3, 5].map((k) => parseInt(t.palette[i].slice(k, k + 2), 16));\n  return children.map((d, j) => {\n    const tint = TINT_FIRST + ((TINT_LAST - TINT_FIRST) * j) / Math.max(1, children.length - 1);\n    const mixed = rgb.map((c) => Math.round(c + (255 - c) * tint));\n    return {\n      id: `segment-${i}-${j}`,\n      label: d[CUSTOMER_SEGMENT],\n      value: d[REVENUE],\n      color: `rgb(${mixed.join(\", \")})`,\n      rgb: mixed,\n    };\n  });\n});\n\n// Label ink on each segment from its colour's WCAG relative luminance\nconst inkRules = Object.fromEntries(\n  [\n    ...inner.map((s, i) => [\"units\", i, [1, 3, 5].map((k) => parseInt(s.color.slice(k, k + 2), 16))]),\n    ...outer.map((s, i) => [\"segments\", i, s.rgb]),\n  ].map(([series, i, rgb]) => {\n    const [r, g, b] = rgb.map((c) => (c / 255 <= 0.03928 ? c / 255 / 12.92 : ((c / 255 + 0.055) / 1.055) ** 2.4));\n    const ink = 0.2126 * r + 0.7152 * g + 0.0722 * b > INK_SPLIT ? DARK_INK : LIGHT_INK;\n    return [`& .MuiPieChart-seriesLabels[data-series=\"${series}\"] .MuiPieChart-arcLabel:nth-of-type(${i + 1})`, { fill: ink }];\n  }),\n);\n\nfunction CenterTotal() {\n  const { left, top, width, height } = useDrawingArea();\n  const cx = left + width / 2;\n  const cy = top + height / 2;\n  return (\n    <g textAnchor=\"middle\">\n      <text x={cx} y={cy - 34} fontSize={15} fontWeight={600} letterSpacing=\"0.12em\" fill={t.inkSoft}>\n        TOTAL\n      </text>\n      <text x={cx} y={cy + 14} fontSize={42} fontWeight={700} fill={t.ink}>\n        {total.toLocaleString(\"en-US\")}\n      </text>\n      <text x={cx} y={cy + 40} fontSize={15} fill={t.inkSoft}>\n        {revenueUnit}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\", paddingBottom: 28, boxSizing: \"border-box\" }}>\n      <div style={{ height: TITLE_H, paddingTop: 26, boxSizing: \"border-box\", textAlign: \"center\" }}>\n        <span style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</span>\n      </div>\n      <PieChart\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        skipAnimation\n        margin={{ top: 8, right: 40, bottom: 16, left: 40 }}\n        series={[\n          {\n            id: \"units\",\n            data: inner,\n            innerRadius: \"22%\",\n            outerRadius: \"50%\",\n            cornerRadius: 3,\n            arcLabel: \"label\",\n            valueFormatter: (item) => `${item.value.toLocaleString(\"en-US\")} ${revenueUnit}`,\n          },\n          {\n            id: \"segments\",\n            data: outer,\n            innerRadius: \"54%\",\n            outerRadius: \"100%\",\n            cornerRadius: 3,\n            arcLabel: \"label\",\n            arcLabelMinAngle: OUTER_LABEL_MIN_ANGLE,\n            valueFormatter: (item) => `${item.value.toLocaleString(\"en-US\")} ${revenueUnit}`,\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 16, color: t.ink, columnGap: 3, rowGap: 1.5, px: 6, justifyContent: \"center\" },\n          },\n        }}\n        sx={{\n          \"& .MuiPieChart-arc\": { stroke: t.pageBg, strokeWidth: 3 },\n          '& .MuiPieChart-seriesLabels[data-series=\"units\"] .MuiPieChart-arcLabel': { fontSize: 18, fontWeight: 700 },\n          '& .MuiPieChart-seriesLabels[data-series=\"segments\"] .MuiPieChart-arcLabel': { fontSize: 15, fontWeight: 600 },\n          ...inkRules,\n        }}\n      >\n        <CenterTotal />\n      </PieChart>\n    </div>\n  );\n}\n"}