Slope chart
Connect before and after values on a shared scale, isolate each item, and read competition ranks and exact changes.
pnpm dlx shadcn@latest add @haze/slope-chart---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Datum{label:string;before:number;after:number}
interface Props{label?:string;beforeLabel?:string;afterLabel?:string;data?:Datum[];unit?:string;class?:string}
const{label="Retention by cohort",beforeLabel="Previous quarter",afterLabel="Current quarter",unit="%",data=[{label:"Independent",before:62,after:78},{label:"Small teams",before:81,after:75},{label:"Studio",before:73,after:84},{label:"Enterprise",before:88,after:91}],class:className}=Astro.props;
const rows=data.filter(item=>Number.isFinite(item.before)&&Number.isFinite(item.after)),values=rows.flatMap(item=>[item.before,item.after]),lo=values.length?Math.min(...values):0,hi=values.length?Math.max(...values):1,magnitude=Math.max(Math.abs(lo),Math.abs(hi),1);
const y=(value:number)=>hi===lo?100:175-(value/magnitude-lo/magnitude)/(hi/magnitude-lo/magnitude)*150,rank=(value:number,key:"before"|"after")=>1+rows.filter(item=>item[key]>value).length;
const colors=["stroke-brand bg-brand","stroke-success bg-success","stroke-warning bg-warning","stroke-muted-foreground bg-muted-foreground","stroke-destructive bg-destructive"],text=(value:number)=>new Intl.NumberFormat("en",{maximumFractionDigits:2}).format(value)+unit;
const lineRows=rows.map((row,index)=>({...row,index,start:y(row.before),end:y(row.after),fromRank:rank(row.before,"before"),toRank:rank(row.after,"after")}));
---
<figure data-haze-slope-chart data-items={JSON.stringify(lineRows)} data-unit={unit} 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><div class="grid grid-cols-2 gap-2 text-xs/5 text-muted-foreground"><span class="wrap-anywhere">{beforeLabel}</span><span class="text-end wrap-anywhere">{afterLabel}</span></div>
{rows.length?<div class="relative h-48 w-full"><svg aria-hidden="true" viewBox="0 0 300 200" preserveAspectRatio="none" class="absolute inset-0 size-full"><path d="M70 15V185M230 15V185" fill="none" vector-effect="non-scaling-stroke" class="stroke-border"/>{lineRows.map(row=><path data-slope-line={row.index} d={"M70 "+row.start+" L230 "+row.end} fill="none" stroke-width="2" vector-effect="non-scaling-stroke" class={cn("transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-15",colors[row.index%colors.length])}/>)}</svg>{lineRows.map(row=><div data-slope-line={row.index} aria-hidden="true" class="transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-15"><span style={`left:23.333%;top:${row.start/2}%`} class={cn("absolute size-2 -translate-1/2 rounded-full",colors[row.index%colors.length])}></span><span style={`left:76.667%;top:${row.end/2}%`} class={cn("absolute size-2 -translate-1/2 rounded-full",colors[row.index%colors.length])}></span><span style={`right:calc(76.667% + 0.625rem);top:${row.start/2}%`} class="absolute -translate-y-1/2 text-xs/4 text-muted-foreground tabular-nums">{text(row.before)}</span><span style={`left:calc(76.667% + 0.625rem);top:${row.end/2}%`} class="absolute -translate-y-1/2 text-xs/4 text-muted-foreground tabular-nums">{text(row.after)}</span></div>)}</div>:<p class="text-[0.8125rem]/5 text-muted-foreground">No complete before and after measurements.</p>}
<div class="flex min-w-0 flex-wrap gap-1">{lineRows.map(row=><button type="button" data-slope-option={row.index} aria-pressed="false" disabled class="flex min-h-8 max-w-full items-center gap-2 rounded-lg px-2 text-xs/5 transition-colors duration-150 ease-snappy enabled:hover:bg-accent aria-pressed:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"><span aria-hidden="true" class={cn("size-2 shrink-0 rounded-full",colors[row.index%colors.length])}></span><span class="wrap-anywhere">{row.label}</span></button>)}</div>
<p data-slope-readout role="status" aria-live="polite" class="min-h-10 text-xs/5 text-muted-foreground">Select a cohort to inspect both measurements and its rank movement.</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">Before, after and rank<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">Item</th><th scope="col" class="p-1">Measurements</th><th scope="col" class="p-1">Rank</th></tr></thead><tbody>{[...lineRows].sort((a,b)=>b.after-a.after).map(row=><tr class="border-t border-border"><th scope="row" class="p-1 font-normal wrap-anywhere">{row.label}</th><td class="p-1 tabular-nums wrap-anywhere">{text(row.before)} → {text(row.after)}</td><td class="p-1 tabular-nums">{row.fromRank} → {row.toRank}</td></tr>)}</tbody></table></details>
</figure>
<script>
function initSlope(){document.querySelectorAll<HTMLElement>("[data-haze-slope-chart]:not([data-enhanced])").forEach(root=>{
root.dataset.enhanced="";const rows:{label:string;before:number;after:number;fromRank:number;toRank:number}[]=JSON.parse(root.dataset.items||"[]"),buttons=Array.from(root.querySelectorAll<HTMLButtonElement>("[data-slope-option]")),lines=root.querySelectorAll<SVGElement|HTMLElement>("[data-slope-line]");
const select=(index:number)=>{buttons.forEach((button,i)=>button.setAttribute("aria-pressed",String(i===index)));lines.forEach(line=>line.toggleAttribute("data-dimmed",index>=0&&index!==Number(line.dataset.slopeLine)));const row=rows[index],unit=root.dataset.unit||"";root.querySelector("[data-slope-readout]")!.textContent=row?row.label+": "+row.before+unit+" to "+row.after+unit+", change "+(row.after-row.before>0?"+":"")+(row.after-row.before).toLocaleString("en",{maximumFractionDigits:2})+unit+". Rank "+row.fromRank+" to "+row.toRank+".":"All before and after slopes shown.";};
buttons.forEach((button,i)=>{button.disabled=false;button.addEventListener("click",()=>select(button.getAttribute("aria-pressed")==="true"?-1:i));button.addEventListener("keydown",event=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(event.key))return;event.preventDefault();const rtl=getComputedStyle(root).direction==="rtl",forward=(event.key==="ArrowRight")!==rtl;buttons[event.key==="Home"?0:event.key==="End"?buttons.length-1:(i+(forward?1:-1)+buttons.length)%buttons.length].focus();});});
});}
initSlope();if(!document.documentElement.hasAttribute("data-haze-slope-chart-listener")){document.documentElement.setAttribute("data-haze-slope-chart-listener","");document.addEventListener("astro:page-load",initSlope);}
</script>When to use
- The direction of change between two periods is the main comparison.
- Readers need to see both value change and rank movement.
When not to use
- More than two ordered measurements form a trend. Use line-chart.
Installation
Add the Haze registry to components.json once, then install Slope chart with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/slope-chartnpx shadcn@latest add @haze/slope-chartyarn dlx shadcn@latest add @haze/slope-chartbunx --bun shadcn@latest add @haze/slope-chartFirst 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 | Retention by cohort | Caption describing the paired measurement. |
| beforeLabel | string | Previous quarter | Name of the left period. |
| afterLabel | string | Current quarter | Name of the right period. |
| data | { label: string; before: number; after: number }[] | – | Complete finite pairs, including negative and constant values. |
| unit | string | % | Measurement suffix. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- Arrow LeftArrow RightHomeEnd
- Move focus among named items; the order follows the reading direction.
- EnterSpace
- Isolate or clear the focused slope.
Accessibility
- Named cohort buttons reveal the before and after reading and both competition ranks in a polite status message.
- Incomplete pairs are omitted; the disclosure lists complete pairs in descending final-value order.
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 "Slope chart" with `npx shadcn@latest add @haze/slope-chart`. 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 SlopeChart from "@/components/haze/ui/slope-chart.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/slope-chart.md
Customize with real content
Adapt the Haze slope-chart ui for our product. Replace the demo values of these props with our real content: label, beforeLabel, afterLabel, data, unit, class. Keep the layout, the heading level rules and these accessibility details: Named cohort buttons reveal the before and after reading and both competition ranks in a polite status message. Incomplete pairs are omitted; the disclosure lists complete pairs in descending final-value order. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using slope-chart, check it fits: use it when the direction of change between two periods is the main comparison.; readers need to see both value change and rank movement.. Avoid it when more than two ordered measurements form a trend. use line-chart.. Alternatives: @haze/line-chart, @haze/bar-chart, @haze/radar-chart.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.