Sunburst
Partition a hierarchy into proportional rings, explore named branches and return through a center control or breadcrumb.
pnpm dlx shadcn@latest add @haze/sunburst---
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="Workspace allocation",data={label:"All work",children:[{label:"Product",children:[{label:"Research",value:28},{label:"Delivery",value:52},{label:"Quality",value:20}]},{label:"Operations",children:[{label:"Support",value:31},{label:"Infrastructure",value:24}]},{label:"Community",children:[{label:"Documentation",value:26},{label:"Events",value:19}]}]},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 key=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 key;seen.add(item);if(item.children?.length)nodes[key].children=item.children.map(child=>visit(child,key,nodes[key].path,depth+1));else nodes[key].value=Number.isFinite(item.value)&&item.value!>0?item.value!:0;return key;};visit(data,-1,"",0);
const max=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((s,key)=>s+nodes[key].weight,0):max?node.value/max:0;const total=node.weight*max;node.total=Number.isFinite(total)?total.toLocaleString("en",{maximumFractionDigits:2}):"Above numeric range";}
const layouts=nodes.map((_,root)=>{
const depth=(key:number):number=>nodes[key].children.length?1+Math.max(...nodes[key].children.map(depth)):0,levels=Math.max(1,depth(root)),step=100/levels,arcs:{key:number;start:number;end:number;inner:number;outer:number;group:number}[]=[];
const descend=(key:number,start:number,end:number,level:number,group:number)=>{let angle=start;nodes[key].children.filter(child=>nodes[child].weight>0).forEach((child,index)=>{const next=angle+(end-start)*nodes[child].weight/nodes[key].weight,rootGroup=level===0?index:group;arcs.push({key:child,start:angle,end:next,inner:35+level*step,outer:35+(level+1)*step,group:rootGroup});descend(child,angle,next,level+1,rootGroup);angle=next;});};descend(root,0,Math.PI*2,0,0);return arcs;
});
const arc=(part:typeof layouts[number][number])=>{const a=part.start,b=Math.min(part.end,a+Math.PI*2-.000001),point=(r:number,t:number)=>[150+Math.sin(t)*r,150-Math.cos(t)*r].join(" ");return"M"+point(part.outer,a)+"A"+part.outer+" "+part.outer+" 0 "+(b-a>Math.PI?1:0)+" 1 "+point(part.outer,b)+"L"+point(part.inner,b)+"A"+part.inner+" "+part.inner+" 0 "+(b-a>Math.PI?1:0)+" 0 "+point(part.inner,a)+"Z";};
const colors=["fill-brand","fill-success","fill-warning","fill-muted-foreground","fill-destructive"];
---
<figure data-haze-sunburst 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 data-sunburst-nav aria-label={label+" path"} 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>
{layouts[0].length?<div class="relative mx-auto aspect-square w-full max-w-80"><svg data-sunburst-plot aria-hidden="true" viewBox="0 0 300 300" class="size-full">{layouts[0].map(part=><path data-sunburst-arc={part.key} d={arc(part)} stroke-width="2" class={cn("stroke-card transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-20",colors[part.group%colors.length])}/>)}</svg><button data-sunburst-back type="button" disabled aria-label={nodes[0].total+" Total; root of the hierarchy"} class="absolute start-1/2 top-1/2 grid size-[20%] -translate-x-1/2 -translate-y-1/2 place-content-center rounded-full text-center text-xs/4 text-muted-foreground enabled:hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"><span data-sunburst-total class="font-medium tabular-nums">{nodes[0].total}{" "}</span><span data-sunburst-back-label>Total</span></button></div>:<p class="text-[0.8125rem]/5 text-muted-foreground">No positive descendants to display.</p>}
<div data-sunburst-options class="grid min-w-0 gap-1">{nodes[0].children.map(key=><button type="button" data-sunburst-node={key} disabled class="inline-flex min-h-9 items-center gap-1 rounded-lg px-2 py-1 text-start text-xs/5 transition-colors duration-150 ease-snappy enabled:hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"><span>{nodes[key].label} · {nodes[key].total}</span>{nodes[key].children.length>0&&<ArrowUpRight aria-hidden="true" class="size-3.5 shrink-0 text-muted-foreground" />}</button>)}</div>
<p data-sunburst-readout role="status" aria-live="polite" class="min-h-10 text-xs/5 text-muted-foreground">Angle encodes share of the parent. Use a named branch below the chart to drill into 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">Hierarchy shares<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">Full 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 initSunburst(){document.querySelectorAll<HTMLElement>("[data-haze-sunburst]: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;start:number;end:number;inner:number;outer:number;group:number}[][]=JSON.parse(root.dataset.layouts||"[]"),plot=root.querySelector<SVGSVGElement>("[data-sunburst-plot]"),options=root.querySelector<HTMLElement>("[data-sunburst-options]"),nav=root.querySelector<HTMLElement>("[data-sunburst-nav]"),back=root.querySelector<HTMLButtonElement>("[data-sunburst-back]");if(!plot||!options||!nav||!back)return;let current=0;const colors=["fill-brand","fill-success","fill-warning","fill-muted-foreground","fill-destructive"];
const arc=(part:typeof layouts[number][number])=>{const a=part.start,b=Math.min(part.end,a+Math.PI*2-.000001),point=(r:number,t:number)=>[150+Math.sin(t)*r,150-Math.cos(t)*r].join(" ");return"M"+point(part.outer,a)+"A"+part.outer+" "+part.outer+" 0 "+(b-a>Math.PI?1:0)+" 1 "+point(part.outer,b)+"L"+point(part.inner,b)+"A"+part.inner+" "+part.inner+" 0 "+(b-a>Math.PI?1:0)+" 0 "+point(part.inner,a)+"Z";};
const read=(key:number)=>{const node=nodes[key],parent=nodes[node.parent];root.querySelector("[data-sunburst-readout]")!.textContent=node.path+": "+node.total+(parent?.weight?", "+(node.weight/parent.weight*100).toFixed(1)+"% of "+parent.label:"")+(node.children.length?". Open to explore this branch.":". Leaf.");plot.querySelectorAll<SVGPathElement>("[data-sunburst-arc]").forEach(path=>path.toggleAttribute("data-dimmed",Number(path.dataset.sunburstArc)!==key));};
const draw=(key:number,animate=true)=>{current=key;plot.replaceChildren();layouts[key].forEach(part=>{const path=document.createElementNS("http://www.w3.org/2000/svg","path");path.setAttribute("d",arc(part));path.setAttribute("data-sunburst-arc",String(part.key));path.setAttribute("class","stroke-card transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-20 "+colors[part.group%colors.length]);path.style.strokeWidth="2";path.addEventListener("pointerenter",()=>read(part.key));path.addEventListener("click",()=>{if(nodes[part.key].children.length){draw(part.key);back.focus();}else read(part.key);});plot.append(path);});
options.replaceChildren();nodes[key].children.filter(child=>nodes[child].weight>0).forEach(child=>{const button=document.createElement("button");button.type="button";button.className="inline-flex min-h-9 items-center gap-1 rounded-lg px-2 py-1 text-start text-xs/5 transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";button.textContent=nodes[child].label+" · "+nodes[child].total+" · "+(nodes[child].weight/nodes[key].weight*100).toFixed(1)+"%";if(nodes[child].children.length){const ico=root.querySelector("details summary svg")?.cloneNode(true) as SVGElement|undefined;if(ico){ico.setAttribute("class","size-3.5 shrink-0 -rotate-135 text-muted-foreground");button.append(ico);}}button.addEventListener("focus",()=>read(child));button.addEventListener("click",()=>{read(child);if(nodes[child].children.length){draw(child);back.focus();}});options.append(button);});
nav.replaceChildren();const chain:number[]=[];let ancestor=key;while(ancestor>=0){chain.unshift(ancestor);ancestor=nodes[ancestor].parent;}chain.forEach(nodeKey=>{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.textContent=nodes[nodeKey].label+" /";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.addEventListener("click",()=>{draw(nodeKey);back.focus();});nav.append(button);}});back.disabled=nodes[key].parent<0;back.setAttribute("aria-label",nodes[key].total+(back.disabled?" Total; root of the hierarchy":" Back to "+nodes[nodes[key].parent].label));root.querySelector("[data-sunburst-total]")!.textContent=nodes[key].total+" ";root.querySelector("[data-sunburst-back-label]")!.textContent=back.disabled?"Total":"Back";root.querySelector("[data-sunburst-readout]")!.textContent=nodes[key].path+": "+nodes[key].total;if(animate&&!matchMedia("(prefers-reduced-motion: reduce)").matches)plot.animate([{opacity:.4,transform:"rotate(-8deg)"},{opacity:1,transform:"rotate(0)"}],{duration:200});};back.addEventListener("click",()=>{if(nodes[current].parent>=0)draw(nodes[current].parent);});draw(0,false);
});}
initSunburst();if(!document.documentElement.hasAttribute("data-haze-sunburst-listener")){document.documentElement.setAttribute("data-haze-sunburst-listener","");document.addEventListener("astro:page-load",initSunburst);}
</script>When to use
- A compact hierarchy needs shares within each parent and within the whole.
- A dashboard benefits from drilling through successive hierarchy levels.
When not to use
- Area comparisons across many uneven parts are the priority. Use treemap.
Installation
Add the Haze registry to components.json once, then install Sunburst with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/sunburstnpx shadcn@latest add @haze/sunburstyarn dlx shadcn@latest add @haze/sunburstbunx --bun shadcn@latest add @haze/sunburstFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | Workspace allocation | Chart caption and breadcrumb navigation name. |
| data | { label: string; value?: number; children?: TreeNode[] } | – | Root hierarchy with totals derived from finite positive leaves; zero descendants leave an empty chart. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- EnterSpace
- Drill into a named branch or return to a parent.
- TabShiftTab
- Move among branch controls, center navigation and breadcrumbs.
Accessibility
- All drill actions are native named legend or breadcrumb buttons; SVG arcs duplicate data and remain hidden from assistive technology.
- The center button names its parent destination, and a disclosure lists every path, total and parent share.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Sunburst" with `npx shadcn@latest add @haze/sunburst`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/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 Sunburst from "@/components/haze/ui/sunburst.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: http://localhost:4329/ui/sunburst.md
Customize with real content
Adapt the Haze sunburst 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: All drill actions are native named legend or breadcrumb buttons; SVG arcs duplicate data and remain hidden from assistive technology. The center button names its parent destination, and a disclosure lists every path, total and parent share. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using sunburst, check it fits: use it when a compact hierarchy needs shares within each parent and within the whole.; a dashboard benefits from drilling through successive hierarchy levels.. Avoid it when area comparisons across many uneven parts are the priority. use treemap.. Alternatives: @haze/treemap, @haze/donut-chart, @haze/sankey-flow.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.