Split bar
Divide a single bar into proportional shares; toggle categories to reflow the visible total and inspect exact values.
pnpm dlx shadcn@latest add @haze/split-bar---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Segment{label:string;value:number}
interface Props{label?:string;segments?:Segment[];unit?:string;class?:string}
const{label="Acquisition mix",unit="visits",segments=[{label:"Search",value:416},{label:"Direct",value:248},{label:"Referral",value:207},{label:"Campaigns",value:129}],class:className}=Astro.props;
const items=segments.filter(item=>Number.isFinite(item.value)&&item.value>=0),colors=["fill-brand bg-brand","fill-success bg-success","fill-warning bg-warning","fill-muted-foreground bg-muted-foreground","fill-destructive bg-destructive"],max=Math.max(0,...items.map(item=>item.value)),total=max?items.reduce((sum,item)=>sum+item.value/max,0):0;
let start=0;
const bars=items.map((item,index)=>{const share=total?item.value/max/total*100:0,result={...item,index,share,start};start+=share;return result;});
const format=(value:number)=>new Intl.NumberFormat("en",{maximumFractionDigits:2}).format(value);
const pct=(value:number)=>new Intl.NumberFormat("en",{minimumFractionDigits:1,maximumFractionDigits:1}).format(value);
---
<figure data-haze-split-bar data-items={JSON.stringify(items)} data-unit={unit} class={cn("grid min-w-0 gap-4 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>
<p data-split-readout role="status" aria-live="polite" class="min-h-5 text-xs/5 text-muted-foreground tabular-nums">All categories · {max?format(total*max):"0"} {unit}</p>
{max?<svg aria-hidden="true" viewBox="0 0 100 14" preserveAspectRatio="none" class="h-14 w-full overflow-hidden rounded-lg">{bars.map(item=><rect data-split-part={item.index} x={item.start} y="0" width={item.share} height="14" class={cn("transition-opacity duration-150 ease-snappy data-[dimmed]:opacity-30",item.index===0||item.index===bars.length-1?"stroke-transparent":"stroke-card",colors[item.index%colors.length])} stroke-width=".6"/>)}</svg>:<p class="text-[0.8125rem]/5 text-muted-foreground">No positive values to divide.</p>}
<ul role="list" class="grid min-w-0 gap-1">{bars.map(item=><li><button data-split-toggle={item.index} type="button" aria-pressed="true" disabled class="group flex min-h-9 w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1 text-start text-xs/5 transition-colors duration-150 ease-snappy enabled:hover:bg-accent active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"><span aria-hidden="true" class={cn("size-2 shrink-0 rounded-xs group-aria-[pressed=false]:bg-transparent",colors[item.index%colors.length])}></span><span class="min-w-0 flex-1 wrap-anywhere group-aria-[pressed=false]:line-through">{item.label}</span><span data-split-share class="shrink-0 tabular-nums text-muted-foreground">{pct(item.share)}%</span></button></li>)}</ul>
<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">All category 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">Category</th><th scope="col" class="p-1 text-right">Value ({unit})</th></tr></thead><tbody>{items.map(item=><tr class="border-t border-border"><th scope="row" class="p-1 font-normal wrap-anywhere">{item.label}</th><td class="p-1 text-right tabular-nums wrap-anywhere">{format(item.value)}</td></tr>)}</tbody></table></details>
</figure>
<script>
function initSplit(){document.querySelectorAll<HTMLElement>("[data-haze-split-bar]:not([data-enhanced])").forEach(root=>{
root.dataset.enhanced="";const items:{label:string;value:number}[]=JSON.parse(root.dataset.items||"[]"),buttons=Array.from(root.querySelectorAll<HTMLButtonElement>("[data-split-toggle]")),parts=Array.from(root.querySelectorAll<SVGRectElement>("[data-split-part]")),shown=items.map(()=>true),readout=root.querySelector<HTMLElement>("[data-split-readout]")!;
let previous=parts.map(rect=>[Number(rect.getAttribute("x")),Number(rect.getAttribute("width"))]),raf=0;const format=(n:number)=>new Intl.NumberFormat("en",{maximumFractionDigits:2}).format(n),pct=(n:number)=>new Intl.NumberFormat("en",{minimumFractionDigits:1,maximumFractionDigits:1}).format(n);
const draw=(active=-1)=>{const max=Math.max(0,...items.filter((_,i)=>shown[i]).map(item=>item.value)),total=max?items.reduce((sum,item,i)=>sum+(shown[i]?item.value/max:0),0):0;let start=0;const target=items.map((item,i)=>{const width=shown[i]&&total?item.value/max/total*100:0,pos=[start,width];start+=width;return pos;});
buttons.forEach((button,i)=>{button.setAttribute("aria-pressed",String(shown[i]));button.setAttribute("aria-disabled",String(shown[i]&&shown.filter(Boolean).length===1));button.querySelector("[data-split-share]")!.textContent=shown[i]?pct(target[i][1])+"%":"Off";});parts.forEach((rect,i)=>rect.toggleAttribute("data-dimmed",active>=0&&active!==i));readout.textContent=active>=0?items[active].label+" · "+format(items[active].value)+" "+(root.dataset.unit||"")+" · "+format(target[active][1])+"% of visible total":"Visible total · "+format(total*max)+" "+(root.dataset.unit||"");
cancelAnimationFrame(raf);const from=previous.map(p=>[...p]),began=performance.now();const frame=(now:number)=>{const t=matchMedia("(prefers-reduced-motion: reduce)").matches?1:Math.min(1,(now-began)/200);previous=target.map((p,i)=>p.map((v,j)=>from[i][j]+(v-from[i][j])*t));parts.forEach((rect,i)=>{rect.setAttribute("x",String(previous[i][0]));rect.setAttribute("width",String(previous[i][1]));});if(t<1)raf=requestAnimationFrame(frame);};raf=requestAnimationFrame(frame);};
buttons.forEach((button,i)=>{button.disabled=false;button.addEventListener("click",()=>{if(shown[i]&&shown.filter(Boolean).length===1){readout.textContent="Keep at least one category visible.";return;}shown[i]=!shown[i];draw();});button.addEventListener("focus",()=>draw(i));button.addEventListener("pointerenter",()=>draw(i));button.addEventListener("pointerleave",()=>draw());button.addEventListener("blur",()=>draw());});
});}
initSplit();if(!document.documentElement.hasAttribute("data-haze-split-bar-listener")){document.documentElement.setAttribute("data-haze-split-bar-listener","");document.addEventListener("astro:page-load",initSplit);}
</script>When to use
- A compact composition needs to fit into a dashboard row.
- Readers need to exclude categories and compare the remaining mix.
When not to use
- Individual category magnitudes matter more than composition. Use bar-chart.
Installation
Add the Haze registry to components.json once, then install Split bar with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/split-barnpx shadcn@latest add @haze/split-baryarn dlx shadcn@latest add @haze/split-barbunx --bun shadcn@latest add @haze/split-barFirst 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 | Acquisition mix | Figure caption. |
| segments | { label: string; value: number }[] | – | Nonnegative finite quantities; negative and nonfinite entries are excluded. |
| unit | string | visits | Unit printed with values and the table. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- EnterSpace
- Toggle the focused category while retaining at least one visible category.
Accessibility
- Every share has a named toggle, a percentage and an underlying value in the disclosure table.
- The final category stays enabled and a status message explains a refused removal. Reflow interpolates without motion under reduced motion.
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 "Split bar" with `npx shadcn@latest add @haze/split-bar`. 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 SplitBar from "@/components/haze/ui/split-bar.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/split-bar.md
Customize with real content
Adapt the Haze split-bar ui for our product. Replace the demo values of these props with our real content: label, segments, unit, class. Keep the layout, the heading level rules and these accessibility details: Every share has a named toggle, a percentage and an underlying value in the disclosure table. The final category stays enabled and a status message explains a refused removal. Reflow interpolates without motion under reduced motion. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using split-bar, check it fits: use it when a compact composition needs to fit into a dashboard row.; readers need to exclude categories and compare the remaining mix.. Avoid it when individual category magnitudes matter more than composition. use bar-chart.. Alternatives: @haze/donut-chart, @haze/waffle-chart, @haze/bar-chart.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.