# Treemap

> Size hierarchy tiles by leaf totals using squarified layout, drill into branches and return with a breadcrumb.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/treemap`
- File: `src/components/haze/ui/treemap.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/treemap

## Use when
- Many positive parts make a small set of large contributors important.
- Readers need to drill through an area-based hierarchy.

## Avoid when
- Relative angle within a hierarchy is more useful than rectangular area. Use sunburst.

## Alternatives
- [sunburst](https://hazeui.com/ui/sunburst.md)
- [bar-chart](https://hazeui.com/ui/bar-chart.md)
- [waffle-chart](https://hazeui.com/ui/waffle-chart.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` | Repository footprint | no | Caption and hierarchy navigation name. |
| data | `{ label: string; value?: number; children?: TreeNode[] }` |  | no | Root tree. Branch values are computed from positive finite leaf values; nesting is bounded to 13 levels. |
| class | `string` |  | no | Additional classes on the chart figure. |

## Accessibility
- Tiles are native buttons named with their path and value; focus announces their parent share and branch action.
- The breadcrumb marks its current level; a complete path table retains leaves too small for visible tile labels.
- Key Enter / Space: Open a branch or return through the breadcrumb.
- Key Tab / Shift+Tab: Visit tiles and breadcrumb controls with native focus.

## Agent prompts

### Install and use

Install the Haze UI component "Treemap" with `npx shadcn@latest add @haze/treemap`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Treemap from "@/components/haze/ui/treemap.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/treemap.md

### Customize with real content

Adapt the Haze treemap ui for our product. Replace the demo values of these props with our real content: label, data, class. Keep the layout, the heading level rules and these accessibility details: Tiles are native buttons named with their path and value; focus announces their parent share and branch action. The breadcrumb marks its current level; a complete path table retains leaves too small for visible tile labels. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using treemap, check it fits: use it when many positive parts make a small set of large contributors important.; readers need to drill through an area-based hierarchy.. Avoid it when relative angle within a hierarchy is more useful than rectangular area. use sunburst.. Alternatives: @haze/sunburst, @haze/bar-chart, @haze/waffle-chart.

## Example requests that should lead here
- Show repository size as a squarified treemap with branch drill-down, path breadcrumbs and exact parent shares.

## Source

```astro
---
import { ArrowUpRight, ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface TreeNode{label:string;value?:number;children?:TreeNode[]}
interface Props{label?:string;data?:TreeNode;class?:string}
const{label="Repository footprint",data={label:"All files",children:[{label:"Source",children:[{label:"Components",value:68},{label:"Pages",value:42},{label:"Utilities",value:18}]},{label:"Assets",children:[{label:"Fonts",value:46},{label:"Icons",value:22}]},{label:"Tests",value:35},{label:"Documentation",value:24}]},class:className}=Astro.props;
interface Node{label:string;path:string;parent:number;children:number[];value:number;weight:number;total:string}
const nodes:Node[]=[],seen=new WeakSet<object>();
const visit=(item:TreeNode,parent:number,path:string,depth:number):number=>{const index=nodes.length;nodes.push({label:item.label,path:path?path+" / "+item.label:item.label,parent,children:[],value:0,weight:0,total:"0"});if(depth>12||seen.has(item))return index;seen.add(item);if(item.children?.length)nodes[index].children=item.children.map(child=>visit(child,index,nodes[index].path,depth+1));else nodes[index].value=Number.isFinite(item.value)&&item.value!>0?item.value!:0;return index;};
visit(data,-1,"",0);const largest=Math.max(0,...nodes.map(node=>node.value));
for(let i=nodes.length-1;i>=0;i--){const node=nodes[i];node.weight=node.children.length?node.children.reduce((sum,key)=>sum+nodes[key].weight,0):largest?node.value/largest:0;const total=node.weight*largest;node.total=Number.isFinite(total)?total.toLocaleString("en",{maximumFractionDigits:2}):"Above numeric range";}
const squarify=(parent:number)=>{
 let x=0,y=0,w=300,h=200;const children=nodes[parent].children.filter(key=>nodes[key].weight>0).sort((a,b)=>nodes[b].weight-nodes[a].weight),total=nodes[parent].weight;
 const remaining=children.map(key=>({key,area:nodes[key].weight/total*60000})),tiles:{key:number;x:number;y:number;w:number;h:number}[]=[];
 const worst=(row:typeof remaining,side:number)=>{const sum=row.reduce((s,item)=>s+item.area,0),areas=row.map(item=>item.area);return row.length?Math.max(side*side*Math.max(...areas)/(sum*sum),sum*sum/(side*side*Math.min(...areas))):Infinity;};
 const place=(row:typeof remaining)=>{const sum=row.reduce((s,item)=>s+item.area,0);if(w>=h){const width=sum/h;let top=y;for(const item of row){const height=item.area/width;tiles.push({key:item.key,x,y:top,w:width,h:height});top+=height;}x+=width;w=Math.max(0,w-width);}else{const height=sum/w;let left=x;for(const item of row){const width=item.area/height;tiles.push({key:item.key,x:left,y,w:width,h:height});left+=width;}y+=height;h=Math.max(0,h-height);}};
 let row:typeof remaining=[];while(remaining.length){const item=remaining[0];if(!row.length||worst([...row,item],Math.min(w,h))<=worst(row,Math.min(w,h))){row.push(item);remaining.shift();}else{place(row);row=[];}}if(row.length)place(row);return tiles;
};
const layouts=nodes.map((_,index)=>squarify(index)),colors=["bg-brand/14","bg-success/14","bg-warning/14","bg-foreground/8","bg-destructive/14"];
const first=layouts[0],style=(tile:typeof first[number])=>"left:"+tile.x/3+"%;top:"+tile.y/2+"%;width:"+tile.w/3+"%;height:"+tile.h/2+"%;";
---
<figure data-haze-treemap data-nodes={JSON.stringify(nodes)} data-layouts={JSON.stringify(layouts)} class={cn("grid min-w-0 gap-3 rounded-xl border border-border bg-card p-4.5 text-card-foreground",className)}>
 <figcaption class="text-[0.9375rem]/5 font-medium tracking-[-0.01em] wrap-anywhere">{label}</figcaption>
 <nav aria-label={label+" hierarchy"} data-treemap-breadcrumb class="flex min-w-0 flex-wrap gap-1 text-xs/5 text-muted-foreground"><span aria-current="page" class="wrap-anywhere">{nodes[0].label}</span></nav>
 {first.length?<div data-treemap-plot class="relative aspect-[3/2] min-w-0 overflow-hidden rounded-lg bg-background/40">{first.map((tile,index)=><button data-treemap-node={tile.key} type="button" disabled title={nodes[tile.key].path+": "+nodes[tile.key].total} style={style(tile)} class={cn("absolute overflow-hidden rounded-md border-2 border-card p-2 text-left text-xs/5 transition-[opacity,scale] duration-200 ease-snappy enabled:hover:scale-[0.98] focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",colors[index%colors.length])}><span class={cn("block truncate",tile.w<55||tile.h<35?"sr-only":"")}>{nodes[tile.key].label}{" "}</span><span class={cn("inline-flex items-center gap-0.5 text-xs/4 text-muted-foreground tabular-nums",tile.w<65||tile.h<55?"sr-only":"")}><span>{nodes[tile.key].total}</span>{nodes[tile.key].children.length>0&&<ArrowUpRight aria-hidden="true" class="size-3 shrink-0" />}</span></button>)}</div>:<p class="text-[0.8125rem]/5 text-muted-foreground">No positive child values in this hierarchy.</p>}
 <p data-treemap-readout role="status" aria-live="polite" class="min-h-10 text-xs/5 text-muted-foreground">Tile area shows each part's share. Choose a branch to explore its children.</p>
 <details class="group min-w-0 border-t border-border pt-3"><summary class="flex min-h-7 cursor-pointer list-none items-center justify-between gap-2 rounded-sm text-[0.8125rem]/5 font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">Complete hierarchy and values<ChevronDown aria-hidden="true" class="size-3.5 shrink-0 transition-[rotate] duration-200 ease-snappy group-open:rotate-180" /></summary><table class="mt-3 w-full table-fixed text-left text-xs/5"><caption class="sr-only">{label}</caption><thead><tr><th scope="col" class="p-1">Path</th><th scope="col" class="p-1 text-right">Value / parent share</th></tr></thead><tbody>{nodes.map(node=><tr class="border-t border-border"><th scope="row" class="p-1 font-normal wrap-anywhere">{node.path}</th><td class="p-1 text-right tabular-nums wrap-anywhere">{node.total} / {node.parent>=0&&nodes[node.parent].weight?(node.weight/nodes[node.parent].weight*100).toFixed(1)+"%":"Root"}</td></tr>)}</tbody></table></details>
</figure>
<script>
function initTreemap(){document.querySelectorAll<HTMLElement>("[data-haze-treemap]:not([data-enhanced])").forEach(root=>{
 root.dataset.enhanced="";const nodes:{label:string;path:string;parent:number;children:number[];weight:number;total:string}[]=JSON.parse(root.dataset.nodes||"[]"),layouts:{key:number;x:number;y:number;w:number;h:number}[][]=JSON.parse(root.dataset.layouts||"[]"),plot=root.querySelector<HTMLElement>("[data-treemap-plot]"),nav=root.querySelector<HTMLElement>("[data-treemap-breadcrumb]"),readout=root.querySelector<HTMLElement>("[data-treemap-readout]")!;if(!plot||!nav)return;
 const colors=["bg-brand/14","bg-success/14","bg-warning/14","bg-foreground/8","bg-destructive/14"];
 const read=(key:number)=>{const node=nodes[key],parent=nodes[node.parent];readout.textContent=node.path+": "+node.total+", "+(parent?.weight?(node.weight/parent.weight*100).toFixed(1)+"% of "+parent.label:"root")+(node.children.length?". Opens "+node.children.length+" children.":". Leaf.");};
 const draw=(key:number,animate=true)=>{const tiles=layouts[key];plot.replaceChildren();tiles.forEach((tile,index)=>{const node=nodes[tile.key],button=document.createElement("button");button.type="button";button.dataset.treemapNode=String(tile.key);button.className="absolute overflow-hidden rounded-md border-2 border-card p-2 text-left text-xs/5 transition-[opacity,scale] duration-200 ease-snappy hover:scale-[0.98] focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring "+colors[index%colors.length];button.style.cssText="left:"+tile.x/3+"%;top:"+tile.y/2+"%;width:"+tile.w/3+"%;height:"+tile.h/2+"%;";button.title=node.path+": "+node.total;button.setAttribute("aria-label",node.label+" "+node.total+(node.children.length?", open branch":""));const name=document.createElement("span");name.className=tile.w<55||tile.h<35?"sr-only":"block truncate";name.textContent=node.label+" ";button.append(name);if(tile.w>=65&&tile.h>=55){const value=document.createElement("span");value.className="inline-flex items-center gap-0.5 text-xs/4 text-muted-foreground tabular-nums";value.textContent=node.total;if(node.children.length){const ico=root.querySelector("details summary svg")?.cloneNode(true) as SVGElement|undefined;if(ico){ico.setAttribute("class","size-3 shrink-0 -rotate-135");value.append(ico);}}button.append(value);}button.addEventListener("focus",()=>read(tile.key));button.addEventListener("pointerenter",()=>read(tile.key));button.addEventListener("click",()=>{read(tile.key);if(node.children.length&&layouts[tile.key].length){draw(tile.key);nav.querySelector<HTMLButtonElement>("button")?.focus();}});plot.append(button);});
 nav.replaceChildren();const chain:number[]=[];let current=key;while(current>=0){chain.unshift(current);current=nodes[current].parent;}chain.forEach((nodeKey,index)=>{if(index){const divider=document.createElement("span");divider.textContent="/";divider.setAttribute("aria-hidden","true");nav.append(divider);}if(nodeKey===key){const span=document.createElement("span");span.setAttribute("aria-current","page");span.className="wrap-anywhere";span.textContent=nodes[nodeKey].label;nav.append(span);}else{const button=document.createElement("button");button.type="button";button.className="min-h-6 rounded-md px-1 hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";button.textContent=nodes[nodeKey].label;button.addEventListener("click",()=>{draw(nodeKey);plot.querySelector<HTMLButtonElement>("button")?.focus();});nav.append(button);}});read(key);if(animate&&!matchMedia("(prefers-reduced-motion: reduce)").matches)plot.animate([{opacity:.9},{opacity:1}],{duration:200});};draw(0,false);
});}
initTreemap();if(!document.documentElement.hasAttribute("data-haze-treemap-listener")){document.documentElement.setAttribute("data-haze-treemap-listener","");document.addEventListener("astro:page-load",initTreemap);}
</script>
```
