{"spec_id":"treemap-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// treemap-basic: Basic Treemap\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"treemap-basic · javascript · muix · anyplot.ai\";\nconst TITLE_H = 80;\nconst MARGIN = { top: 8, right: 32, bottom: 24, left: 32 };\nconst GUTTER = 3; // px between main categories\nconst HEADER_H = 30; // px band that names a main category above its tiles\nconst MIN_NESTED_H = 40; // px a category needs below its header to show its subcategories\nconst TILE_TINT = 0.3; // share mixed toward white for the subcategory level\nconst LABEL_FONT = 15;\nconst CHAR_W = 0.56; // average glyph width as a share of the font size\n\n// Columns: set these to your data's column names\nconst CATEGORY = \"Department\"; // role: category\nconst SUBCATEGORY = \"Cost center\"; // role: subcategory\nconst VALUE = \"Budget (USD thousand)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Company expense breakdown: six departments, 20 cost centers.\nconst data = [\n  { [CATEGORY]: \"Engineering\", [SUBCATEGORY]: \"Platform Infra\", [VALUE]: 820 },\n  { [CATEGORY]: \"Engineering\", [SUBCATEGORY]: \"Mobile Apps\", [VALUE]: 540 },\n  { [CATEGORY]: \"Engineering\", [SUBCATEGORY]: \"DevOps\", [VALUE]: 310 },\n  { [CATEGORY]: \"Engineering\", [SUBCATEGORY]: \"QA & Testing\", [VALUE]: 210 },\n  { [CATEGORY]: \"Sales\", [SUBCATEGORY]: \"Enterprise\", [VALUE]: 610 },\n  { [CATEGORY]: \"Sales\", [SUBCATEGORY]: \"SMB\", [VALUE]: 380 },\n  { [CATEGORY]: \"Sales\", [SUBCATEGORY]: \"Partnerships\", [VALUE]: 190 },\n  { [CATEGORY]: \"Marketing\", [SUBCATEGORY]: \"Digital Ads\", [VALUE]: 430 },\n  { [CATEGORY]: \"Marketing\", [SUBCATEGORY]: \"Content\", [VALUE]: 260 },\n  { [CATEGORY]: \"Marketing\", [SUBCATEGORY]: \"Events\", [VALUE]: 150 },\n  { [CATEGORY]: \"Marketing\", [SUBCATEGORY]: \"Brand\", [VALUE]: 120 },\n  { [CATEGORY]: \"R&D\", [SUBCATEGORY]: \"Applied Research\", [VALUE]: 480 },\n  { [CATEGORY]: \"R&D\", [SUBCATEGORY]: \"Prototyping\", [VALUE]: 260 },\n  { [CATEGORY]: \"R&D\", [SUBCATEGORY]: \"Patents & Compliance\", [VALUE]: 140 },\n  { [CATEGORY]: \"Operations\", [SUBCATEGORY]: \"Facilities\", [VALUE]: 340 },\n  { [CATEGORY]: \"Operations\", [SUBCATEGORY]: \"IT Support\", [VALUE]: 220 },\n  { [CATEGORY]: \"Operations\", [SUBCATEGORY]: \"Logistics\", [VALUE]: 180 },\n  { [CATEGORY]: \"Customer Success\", [SUBCATEGORY]: \"Support\", [VALUE]: 300 },\n  { [CATEGORY]: \"Customer Success\", [SUBCATEGORY]: \"Onboarding\", [VALUE]: 180 },\n  { [CATEGORY]: \"Customer Success\", [SUBCATEGORY]: \"Training\", [VALUE]: 110 },\n];\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[VALUE] != null && d[VALUE] > 0);\nconst categories = [...new Set(rows.map((d) => d[CATEGORY]))];\nconst categoryTotals = categories.map((c) => ({\n  name: c,\n  value: rows.filter((d) => d[CATEGORY] === c).reduce((sum, d) => sum + d[VALUE], 0),\n}));\nconst grandTotal = categoryTotals.reduce((sum, c) => sum + c.value, 0);\n\n// Colors: one Imprint hue per main category in order of appearance; the\n// subcategory tiles take a lighter shade of it, so shading tells the levels\n// apart. Text ink follows each fill's luminance, not the theme. Slot 5\n// (matte red) is the semantic bad/loss anchor, so ordinary categories skip it.\nconst categoryPalette = t.palette.filter((_, i) => i !== 4);\nconst shades = new Map(\n  categories.map((c, i) => {\n    const head = categoryPalette[i % categoryPalette.length];\n    const base = [16, 8, 0].map((s) => (parseInt(head.slice(1), 16) >> s) & 255);\n    const tile = base.map((v) => Math.round(v + (255 - v) * TILE_TINT));\n    const [headInk, tileInk] = [base, tile].map((rgb) => {\n      const [r, g, b] = rgb.map((v) => v / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));\n      return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.2 ? \"#1A1A17\" : \"#FAF8F1\";\n    });\n    return [c, { head, tile: `rgb(${tile.join(\",\")})`, headInk, tileInk }];\n  }),\n);\n\n// Squarified layout (Bruls, Huizing & van Wijk) in px of the drawing area, one\n// task per container: the main categories over the whole area first, then the\n// subcategories of each category inside its rectangle below the header band.\nconst PLOT_W = window.ANYPLOT_SIZE.width - MARGIN.left - MARGIN.right;\nconst PLOT_H = window.ANYPLOT_SIZE.height - TITLE_H - MARGIN.top - MARGIN.bottom;\nconst tiles = [];\nconst tasks = [{ level: 0, category: null, items: categoryTotals, rect: { x: 0, y: 0, w: PLOT_W, h: PLOT_H } }];\nwhile (tasks.length > 0) {\n  const { level, category, items, rect } = tasks.shift();\n  const total = items.reduce((sum, d) => sum + d.value, 0);\n  const rest = items\n    .map((d) => ({ ...d, area: (d.value / total) * rect.w * rect.h }))\n    .sort((a, b) => b.area - a.area);\n  let free = { ...rect };\n  let row = [];\n  while (rest.length > 0 || row.length > 0) {\n    // Grow the current strip while that keeps its worst aspect ratio from rising\n    const side = Math.min(free.w, free.h);\n    let grow = rest.length > 0 && row.length === 0;\n    if (rest.length > 0 && row.length > 0) {\n      const [current, next] = [row, [...row, rest[0]]].map((r) => {\n        const s = r.reduce((sum, d) => sum + d.area, 0);\n        const areas = r.map((d) => d.area);\n        return Math.max((side * side * Math.max(...areas)) / (s * s), (s * s) / (side * side * Math.min(...areas)));\n      });\n      grow = next <= current;\n    }\n    if (grow) {\n      row.push(rest.shift());\n      continue;\n    }\n    // Lay the strip along the shorter side of the free space\n    const stripArea = row.reduce((sum, d) => sum + d.area, 0);\n    const vertical = free.w >= free.h;\n    const thickness = stripArea / (vertical ? free.h : free.w);\n    let offset = vertical ? free.y : free.x;\n    row.forEach((d) => {\n      const span = d.area / thickness;\n      const box = vertical\n        ? { x: free.x, y: offset, w: thickness, h: span }\n        : { x: offset, y: free.y, w: span, h: thickness };\n      offset += span;\n      if (level === 0) {\n        const outer = { x: box.x + GUTTER, y: box.y + GUTTER, w: Math.max(0, box.w - 2 * GUTTER), h: Math.max(0, box.h - 2 * GUTTER) };\n        const nested = outer.h >= HEADER_H + MIN_NESTED_H;\n        tiles.push({ level, category: d.name, name: d.name, value: d.value, ...outer, nested });\n        if (nested) {\n          tasks.push({\n            level: 1,\n            category: d.name,\n            items: rows.filter((r) => r[CATEGORY] === d.name).map((r) => ({ name: r[SUBCATEGORY], value: r[VALUE] })),\n            rect: { x: outer.x, y: outer.y + HEADER_H, w: outer.w, h: outer.h - HEADER_H },\n          });\n        }\n      } else {\n        tiles.push({ level, category, name: d.name, value: d.value, ...box });\n      }\n    });\n    free = vertical\n      ? { x: free.x + thickness, y: free.y, w: free.w - thickness, h: free.h }\n      : { x: free.x, y: free.y + thickness, w: free.w, h: free.h - thickness };\n    row = [];\n  }\n}\n\nconst fmt = new Intl.NumberFormat(\"en-US\");\nconst SUBTITLE = `${rows.length} ${SUBCATEGORY.toLowerCase()} tiles in ${categories.length} ${CATEGORY.toLowerCase()} blocks · area ∝ ${VALUE}, ${fmt.format(grandTotal)} in total`;\n\n// The community package has no treemap: a custom layer draws the tiles through\n// the container's px-unit scales, labels only where the text fits its tile.\nfunction Treemap() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n\n  return (\n    <g>\n      {tiles.map((tile) => {\n        const shade = shades.get(tile.category);\n        const x = xScale(tile.x);\n        const y = yScale(tile.y);\n        const w = xScale(tile.x + tile.w) - x;\n        const h = yScale(tile.y + tile.h) - y;\n        const pct = ((tile.value / grandTotal) * 100).toFixed(1);\n\n        if (tile.level === 0) {\n          const header = `${tile.name} · ${fmt.format(tile.value)}`;\n          const headerFits = w - 16 >= header.length * LABEL_FONT * CHAR_W;\n          const nameFits = w - 16 >= tile.name.length * LABEL_FONT * CHAR_W && h >= LABEL_FONT + 10;\n          return (\n            <g key={`cat-${tile.name}`}>\n              <rect x={x} y={y} width={w} height={tile.nested ? HEADER_H : h} fill={shade.head}>\n                <title>{`${tile.name}: ${fmt.format(tile.value)} (${pct}%)`}</title>\n              </rect>\n              {(tile.nested ? headerFits : nameFits) && (\n                <text x={x + 8} y={y + HEADER_H / 2 + 5} fontSize={LABEL_FONT} fontWeight={700} fill={shade.headInk}>\n                  {tile.nested ? header : tile.name}\n                </text>\n              )}\n              <rect x={x} y={y} width={w} height={h} fill=\"none\" stroke={t.pageBg} strokeWidth={GUTTER} />\n            </g>\n          );\n        }\n\n        const nameFits = w - 16 >= tile.name.length * LABEL_FONT * CHAR_W && h >= LABEL_FONT + 12;\n        const valueFits = nameFits && h >= LABEL_FONT * 2 + 18;\n        return (\n          <g key={`sub-${tile.category}-${tile.name}`}>\n            <rect x={x} y={y} width={w} height={h} fill={shade.tile} stroke={t.pageBg} strokeWidth={2}>\n              <title>{`${tile.category} / ${tile.name}: ${fmt.format(tile.value)} (${pct}%)`}</title>\n            </rect>\n            {nameFits && (\n              <text x={x + 8} y={y + LABEL_FONT + 7} fontSize={LABEL_FONT} fontWeight={500} fill={shade.tileInk}>\n                {tile.name}\n              </text>\n            )}\n            {valueFits && (\n              <text x={x + 8} y={y + LABEL_FONT * 2 + 12} fontSize={LABEL_FONT - 1} fill={shade.tileInk}>\n                {fmt.format(tile.value)}\n              </text>\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, padding: \"18px 36px 0\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.2, marginTop: 8 }}>{SUBTITLE}</div>\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H}\n        series={[]}\n        skipAnimation\n        margin={MARGIN}\n        xAxis={[{ id: \"px-x\", scaleType: \"linear\", min: 0, max: PLOT_W, position: \"none\" }]}\n        yAxis={[{ id: \"px-y\", scaleType: \"linear\", min: 0, max: PLOT_H, reverse: true, position: \"none\" }]}\n      >\n        <Treemap />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}