AI model selector
Expandable model pill with four AI models and an adaptive detent effort track that reshapes stops while preserving effort preference.
pnpm dlx shadcn@latest add @haze/ai-model-selector---
import { Check, ChevronUp } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface ModelSpec {
id: string;
name: string;
context?: string;
latency?: string;
summary: string;
stops: string[];
badge?: string;
}
interface Props {
id?: string;
heading?: string;
models?: ModelSpec[];
initialModel?: string;
initialEffort?: string;
class?: string;
}
const {
id = "haze-ai-model-selector",
heading = "AI model selector",
models = [
{
id: "opus",
name: "Opus 5.5",
context: "200k",
latency: "Deep",
summary: "Most capable, for complex work",
stops: ["Low", "Medium", "High", "Max"],
},
{
id: "sonnet",
name: "Sonnet 5.5",
context: "200k",
latency: "Balanced",
summary: "Fast and capable for everyday tasks",
stops: ["Low", "Medium", "High"],
},
{
id: "haiku",
name: "Haiku 5.5",
context: "200k",
latency: "Instant",
summary: "Fastest, for quick answers",
stops: ["Fast", "Balanced"],
},
{
id: "codex",
name: "Codex 5.6",
context: "128k",
latency: "Agentic",
summary: "Strong at agentic coding",
stops: ["Medium", "High", "Max"],
badge: "C",
},
],
initialModel = "opus",
initialEffort = "High",
class: className,
} = Astro.props;
const activeModel = models.find((m) => m.id === initialModel) ?? models[0];
const activeStopIdx = Math.max(
0,
activeModel.stops.findIndex((s) => s.toLowerCase() === initialEffort.toLowerCase())
);
const activeStop = activeModel.stops[activeStopIdx] ?? activeModel.stops[0];
const initialThumbWidth = 100 / activeModel.stops.length;
const initialThumbTranslate = activeStopIdx * 100;
const effortRank = (stop: string) => {
const lower = stop.toLowerCase();
if (lower === "fast" || lower === "low") return 1;
if (lower === "balanced" || lower === "medium") return 2;
if (lower === "high") return 3;
return 4;
};
const effortCopy = (stop: string) => {
const lower = stop.toLowerCase();
if (lower === "fast" || lower === "low") return "Quickest responses for straightforward questions. Lowest latency.";
if (lower === "balanced" || lower === "medium") return "Balanced reasoning depth and speed for everyday tasks.";
if (lower === "max") return "Maximum reasoning budget for deep audits and complex architecture.";
return "Thinks longer on hard problems. Slower, uses more tokens.";
};
const initialBars = effortRank(activeStop);
---
<section
aria-labelledby={`${id}-title`}
data-haze-ai-model-selector
data-models={JSON.stringify(models)}
data-initial-model={activeModel.id}
data-initial-effort={activeStop}
class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
<h2 id={`${id}-title`} class="sr-only">{heading}</h2>
<div class="mx-auto flex w-full max-w-xs flex-col gap-3">
<div
id={`${id}-panel`}
data-ams-panel
class="rounded-2xl border border-border bg-card p-3 shadow-float"
>
<div role="radiogroup" aria-label="AI model" class="space-y-0.5">
{
models.map((m) => {
const selected = m.id === activeModel.id;
return (
<button
type="button"
role="radio"
aria-checked={selected ? "true" : "false"}
data-ams-model={m.id}
class="flex w-full cursor-pointer items-center justify-between gap-3 rounded-xl px-3 py-2.5 text-left transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
>
<span class="flex min-w-0 items-start gap-3">
{m.badge ? (
<span
aria-hidden="true"
class="mt-0.5 grid size-4 shrink-0 place-items-center rounded-full bg-foreground text-[0.625rem] font-bold text-background"
>
{m.badge}
</span>
) : (
<svg
viewBox="0 0 20 20"
fill="none"
class="mt-0.5 size-4 shrink-0 text-foreground"
aria-hidden="true"
>
<path
d="M10 2v16M2 10h16M4.34 4.34l11.32 11.32M15.66 4.34L4.34 15.66"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
/>
</svg>
)}
<span class="min-w-0">
<span class="block truncate text-[0.9375rem]/5 font-medium text-foreground">
{m.name}
</span>
<span class="mt-0.5 block truncate text-xs/4 text-muted-foreground">
{m.summary}
</span>
</span>
</span>
<Check
data-ams-check
aria-hidden="true"
class={cn(
"size-4 shrink-0 text-foreground transition-opacity duration-150 ease-snappy",
!selected && "opacity-0"
)}
/>
</button>
);
})
}
</div>
<div class="mt-3 border-t border-border px-1 pt-3 pb-1">
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="text-sm/5 font-medium text-foreground">Effort</span>
<span class="text-xs/4 text-muted-foreground">← → to adjust</span>
</div>
<div class="mt-2.5 rounded-full bg-muted/60 p-1">
<div class="relative">
<div
data-ams-thumb
aria-hidden="true"
style={`width: ${initialThumbWidth}%; translate: ${initialThumbTranslate}% 0;`}
class="pointer-events-none absolute inset-y-0 left-0 rounded-full border border-frame-strong bg-card shadow-key transition-[translate,width] duration-200 ease-snappy"
></div>
<div
data-ams-stops
role="radiogroup"
aria-label="Reasoning effort level"
style={`grid-template-columns: repeat(${activeModel.stops.length}, minmax(0, 1fr));`}
class="relative z-10 grid"
>
{
activeModel.stops.map((stop, idx) => (
<button
type="button"
role="radio"
aria-checked={idx === activeStopIdx ? "true" : "false"}
data-ams-stop={stop}
class={cn(
"min-h-8 cursor-pointer truncate rounded-full px-2 py-1 text-center text-xs font-medium transition-colors duration-150 ease-snappy focus-visible:outline-2 focus-visible:outline-ring",
idx === activeStopIdx ? "text-foreground" : "text-muted-foreground hover:text-foreground"
)}
>
{stop}
</button>
))
}
</div>
</div>
</div>
<p data-ams-effort-desc class="mt-2.5 text-xs/5 text-muted-foreground">
{effortCopy(activeStop)}
</p>
</div>
</div>
<div class="rounded-full border border-frame bg-card p-1.5 shadow-key">
<button
type="button"
data-ams-trigger
aria-expanded="true"
aria-controls={`${id}-panel`}
class="inline-flex min-h-9 max-w-full cursor-pointer items-center gap-2 rounded-full bg-muted/60 px-3.5 py-1.5 text-sm font-medium text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.98] active:duration-75"
>
<svg
data-ams-pill-star
viewBox="0 0 20 20"
fill="none"
class={cn("size-4 shrink-0 text-foreground", Boolean(activeModel.badge) && "hidden")}
aria-hidden="true"
>
<path
d="M10 2v16M2 10h16M4.34 4.34l11.32 11.32M15.66 4.34L4.34 15.66"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
/>
</svg>
<span
data-ams-pill-badge
aria-hidden="true"
class={cn(
"grid size-4 shrink-0 place-items-center rounded-full bg-foreground text-[0.625rem] font-bold text-background",
!activeModel.badge && "hidden"
)}
>
{activeModel.badge ?? "C"}
</span>
<span data-ams-pill-model class="truncate">{activeModel.name}</span>
<svg
viewBox="0 0 16 14"
fill="none"
class="size-3.5 shrink-0"
aria-hidden="true"
>
<rect
data-ams-sig-bar="1"
x="1"
y="9"
width="2.5"
height="4"
rx="1"
class={initialBars >= 1 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
/>
<rect
data-ams-sig-bar="2"
x="5"
y="6.5"
width="2.5"
height="6.5"
rx="1"
class={initialBars >= 2 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
/>
<rect
data-ams-sig-bar="3"
x="9"
y="4"
width="2.5"
height="9"
rx="1"
class={initialBars >= 3 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
/>
<rect
data-ams-sig-bar="4"
x="13"
y="1.5"
width="2.5"
height="11.5"
rx="1"
class={initialBars >= 4 ? "fill-current text-foreground" : "fill-current text-muted-foreground/30"}
/>
</svg>
<span data-ams-pill-effort class="font-normal text-muted-foreground">{activeStop}</span>
<ChevronUp
data-ams-chevron
class="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-snappy"
aria-hidden="true"
/>
</button>
</div>
<p data-ams-status role="status" class="sr-only"></p>
</div>
</section>
<script>
interface ModelItem {
id: string;
name: string;
summary: string;
stops: string[];
badge?: string;
}
function initAiModelSelectors() {
const rankOf = (stop: string): number => {
const lower = stop.toLowerCase();
if (lower === "fast" || lower === "low") return 0;
if (lower === "balanced" || lower === "medium") return 1;
if (lower === "high") return 2;
if (lower === "max") return 3;
return 1;
};
const describeStop = (stop: string): string => {
const lower = stop.toLowerCase();
if (lower === "fast" || lower === "low") {
return "Quickest responses for straightforward questions. Lowest latency.";
}
if (lower === "balanced" || lower === "medium") {
return "Balanced reasoning depth and speed for everyday tasks.";
}
if (lower === "max") {
return "Maximum reasoning budget for deep audits and complex architecture.";
}
return "Thinks longer on hard problems. Slower, uses more tokens.";
};
document.querySelectorAll<HTMLElement>("[data-haze-ai-model-selector]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const trigger = root.querySelector<HTMLButtonElement>("[data-ams-trigger]");
const chevron = root.querySelector<HTMLElement>("[data-ams-chevron]");
const pillStar = root.querySelector<HTMLElement>("[data-ams-pill-star]");
const pillBadge = root.querySelector<HTMLElement>("[data-ams-pill-badge]");
const pillModel = root.querySelector<HTMLElement>("[data-ams-pill-model]");
const pillEffort = root.querySelector<HTMLElement>("[data-ams-pill-effort]");
const sigBars = Array.from(root.querySelectorAll<SVGElement>("[data-ams-sig-bar]"));
const panel = root.querySelector<HTMLElement>("[data-ams-panel]");
const stopsGrid = root.querySelector<HTMLElement>("[data-ams-stops]");
const thumb = root.querySelector<HTMLElement>("[data-ams-thumb]");
const effortDesc = root.querySelector<HTMLElement>("[data-ams-effort-desc]");
const status = root.querySelector<HTMLElement>("[data-ams-status]");
let models: ModelItem[] = [];
try {
models = JSON.parse(root.dataset.models ?? "[]") as ModelItem[];
} catch {
models = [];
}
if (!models.length) return;
let currentModel = models.find((m) => m.id === root.dataset.initialModel) ?? models[0];
let currentStop =
currentModel.stops.find((s) => s.toLowerCase() === (root.dataset.initialEffort ?? "").toLowerCase()) ??
currentModel.stops[0];
let preferredRank = rankOf(currentStop);
const announce = (msg: string) => {
if (status) status.textContent = msg;
};
const findClosestStop = (stops: string[], targetRank: number): { stop: string; clamped: boolean } => {
let best = stops[0];
let bestDiff = Math.abs(rankOf(best) - targetRank);
for (const s of stops) {
const diff = Math.abs(rankOf(s) - targetRank);
if (diff < bestDiff) {
best = s;
bestDiff = diff;
}
}
return { stop: best, clamped: bestDiff > 0 };
};
const paintSignal = (stop: string) => {
const activeCount = rankOf(stop) + 1;
sigBars.forEach((bar, i) => {
const lit = i < activeCount;
bar.classList.toggle("text-foreground", lit);
bar.classList.toggle("text-muted-foreground/30", !lit);
});
};
const syncPill = () => {
if (pillModel) pillModel.textContent = currentModel.name;
if (pillEffort) pillEffort.textContent = currentStop;
if (effortDesc) effortDesc.textContent = describeStop(currentStop);
if (pillStar && pillBadge) {
const hasBadge = Boolean(currentModel.badge);
pillStar.classList.toggle("hidden", hasBadge);
pillBadge.classList.toggle("hidden", !hasBadge);
if (hasBadge && currentModel.badge) pillBadge.textContent = currentModel.badge;
}
paintSignal(currentStop);
};
const positionThumb = (idx: number, total: number) => {
if (!thumb || total <= 0) return;
thumb.style.width = `${100 / total}%`;
thumb.style.translate = `${idx * 100}% 0`;
};
const renderStops = () => {
if (!stopsGrid) return;
const stops = currentModel.stops;
stopsGrid.style.gridTemplateColumns = `repeat(${stops.length}, minmax(0, 1fr))`;
const buttons: HTMLButtonElement[] = stops.map((stop, idx) => {
const active = stop === currentStop;
const btn = document.createElement("button");
btn.type = "button";
btn.setAttribute("role", "radio");
btn.setAttribute("aria-checked", String(active));
btn.dataset.amsStop = stop;
btn.className = active
? "min-h-8 cursor-pointer truncate rounded-full px-2 py-1 text-center text-xs font-medium text-foreground transition-colors duration-150 ease-snappy focus-visible:outline-2 focus-visible:outline-ring"
: "min-h-8 cursor-pointer truncate rounded-full px-2 py-1 text-center text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring";
btn.textContent = stop;
btn.addEventListener("click", () => {
currentStop = stop;
preferredRank = rankOf(stop);
renderStops();
announce(`Effort set to ${stop} for ${currentModel.name}.`);
});
btn.addEventListener("keydown", (ev) => {
if (ev.key !== "ArrowRight" && ev.key !== "ArrowLeft") return;
ev.preventDefault();
const dir = ev.key === "ArrowRight" ? 1 : -1;
const nextIdx = (idx + dir + stops.length) % stops.length;
const nextStop = stops[nextIdx];
if (!nextStop) return;
currentStop = nextStop;
preferredRank = rankOf(nextStop);
renderStops();
const focusTarget = stopsGrid.querySelector<HTMLButtonElement>(`[data-ams-stop="${nextStop}"]`);
focusTarget?.focus();
announce(`Effort set to ${nextStop} for ${currentModel.name}.`);
});
return btn;
});
stopsGrid.replaceChildren(...buttons);
const activeIdx = Math.max(0, stops.indexOf(currentStop));
positionThumb(activeIdx, stops.length);
syncPill();
};
const syncModelCards = () => {
root.querySelectorAll<HTMLButtonElement>("[data-ams-model]").forEach((card) => {
const selected = card.dataset.amsModel === currentModel.id;
card.setAttribute("aria-checked", String(selected));
const check = card.querySelector<HTMLElement>("[data-ams-check]");
check?.classList.toggle("opacity-0", !selected);
});
};
trigger?.addEventListener("click", () => {
if (!panel) return;
const willOpen = Boolean(panel.hidden);
panel.hidden = !willOpen;
trigger.setAttribute("aria-expanded", String(willOpen));
chevron?.classList.toggle("rotate-180", !willOpen);
});
root.querySelectorAll<HTMLButtonElement>("[data-ams-model]").forEach((card) => {
card.addEventListener("click", () => {
const id = card.dataset.amsModel;
const next = models.find((m) => m.id === id);
if (!next) return;
currentModel = next;
const resolved = findClosestStop(next.stops, preferredRank);
currentStop = resolved.stop;
syncModelCards();
renderStops();
announce(
resolved.clamped
? `Switched to ${next.name}; effort adjusted to nearest stop (${currentStop}).`
: `Switched to ${next.name} at ${currentStop} effort.`
);
});
});
renderStops();
});
}
initAiModelSelectors();
document.addEventListener("astro:page-load", initAiModelSelectors);
</script>When to use
- Pairing model selection with model-specific reasoning effort stops inside an AI toolbar
- Showing context window and latency metadata alongside an adaptive segmented effort control
- Preserving a user's preferred effort rank while smoothly clamping to the nearest valid stop
When not to use
- Every model shares identical static options without dynamic stop reshaping; use model-picker or segmented-control instead
Installation
Add the Haze registry to components.json once, then install AI model selector with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-model-selectornpx shadcn@latest add @haze/ai-model-selectoryarn dlx shadcn@latest add @haze/ai-model-selectorbunx --bun shadcn@latest add @haze/ai-model-selectorFirst 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 |
|---|---|---|---|
| id | string | "haze-ai-model-selector" | Unique prefix for heading and panel aria-controls. |
| heading | string | "AI model selector" | Screen-reader section heading for the model selector. |
| models | { id: string; name: string; summary: string; stops: string[]; badge?: string }[] | 4 demo models | Model definitions including summary copy and adaptive effort stops. |
| initialModel | string | "opus" | ID of the initially active model. |
| initialEffort | string | "High" | Initial effort stop selected on load. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- EnterSpace
- Expand or collapse the selector panel and select a model or effort stop
- ArrowLeftArrowRight
- Step across the active model's effort stops on the detent track
Accessibility
- The pill trigger uses aria-expanded and aria-controls, while both the model list and effort track expose radiogroup and radio semantics.
- Model switches and effort stop clamping announce cleanly through a polite role="status" live region.
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 block "AI model selector" with `npx shadcn@latest add @haze/ai-model-selector`. 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 AiModelSelector from "@/components/haze/blocks/ai-model-selector.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/blocks/ai-model-selector.md
Customize with real content
Adapt the Haze ai-model-selector block for our product. Replace the demo values of these props with our real content: id, heading, models, initialModel, initialEffort, class. Keep the layout, the heading level rules and these accessibility details: The pill trigger uses aria-expanded and aria-controls, while both the model list and effort track expose radiogroup and radio semantics. Model switches and effort stop clamping announce cleanly through a polite role="status" live region. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-model-selector, check it fits: use it when pairing model selection with model-specific reasoning effort stops inside an ai toolbar; showing context window and latency metadata alongside an adaptive segmented effort control; preserving a user's preferred effort rank while smoothly clamping to the nearest valid stop. Avoid it when every model shares identical static options without dynamic stop reshaping; use model-picker or segmented-control instead. Alternatives: @haze/model-picker, @haze/ai-prompt, @haze/segmented-control.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.