Workspace switcher
Multi-tenant organization and workspace switcher trigger opening a filterable listbox popover with a create link.
pnpm dlx shadcn@latest add @haze/workspace-switcher---
import { Building, Check, ChevronDown, Plus, Search } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Workspace {
id: string;
name: string;
plan: string;
members?: number;
}
interface Props {
id: string;
workspaces?: Workspace[];
activeId?: string;
createLabel?: string;
createHref?: string;
class?: string;
}
const {
id,
workspaces = [
{ id: "tidewell", name: "Tidewell Studio", plan: "Scale", members: 10 },
{ id: "fieldnote", name: "Fieldnote Labs", plan: "Growth", members: 15 },
{ id: "ostro", name: "Ostro Coffee", plan: "Starter", members: 4 },
],
activeId = "tidewell",
createLabel = "Create workspace",
createHref = "#create-workspace",
class: className,
} = Astro.props;
const active = workspaces.find((w) => w.id === activeId) ?? workspaces[0];
---
<div id={id} data-haze-workspace-switcher class={cn("relative inline-block min-w-0", className)}>
<button
type="button"
data-ws-trigger
popovertarget={`${id}-menu`}
aria-haspopup="listbox"
aria-expanded="false"
style={`anchor-name: --${id}-ws`}
class="group flex h-10 w-60 max-w-full cursor-pointer items-center justify-between gap-2.5 rounded-lg border border-frame bg-field px-2.5 text-left transition-[border-color,background-color] duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
>
<span class="flex min-w-0 items-center gap-2">
<span class="grid size-6 shrink-0 place-items-center rounded-md border border-frame bg-muted text-foreground">
<Building class="size-3.5" aria-hidden="true" />
</span>
<span class="min-w-0">
<span data-ws-active-name class="block truncate text-[0.8125rem]/4 font-semibold text-foreground">{active?.name}</span>
<span data-ws-active-plan class="block truncate text-[0.6875rem]/3.5 text-muted-foreground">{active?.plan} plan</span>
</span>
</span>
<ChevronDown class="size-3.5 shrink-0 text-muted-foreground transition-[rotate] duration-200 ease-snappy motion-reduce:transition-none group-aria-expanded:rotate-180" aria-hidden="true" />
</button>
<div
id={`${id}-menu`}
data-ws-panel
popover
style={`position-anchor: --${id}-ws`}
class="m-auto w-60 max-w-[calc(100vw-1rem)] overflow-hidden open:grid open:grid-rows-[auto_minmax(0,1fr)_auto] rounded-xl border border-border bg-popover p-1 text-popover-foreground shadow-float backdrop:bg-background/60 scale-[0.97] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-200 ease-snappy motion-reduce:transition-none -translate-y-1.5 open:translate-y-0 open:scale-100 open:opacity-100 starting:open:-translate-y-1.5 starting:open:scale-[0.97] starting:open:opacity-0 supports-[position-area:block-end]:m-0 supports-[position-area:block-end]:my-1.5 supports-[position-area:block-end]:max-h-[calc(100%-0.75rem)] supports-[position-area:block-end]:w-[anchor-size(width)] supports-[position-area:block-end]:min-w-48 supports-[position-area:block-end]:[position-try-order:most-block-size] supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block]"
>
<label class="flex h-8 items-center gap-2 border-b border-border px-2 text-xs text-muted-foreground">
<Search class="size-3.5 shrink-0" aria-hidden="true" />
<input
type="search"
data-ws-search
aria-label="Filter workspaces"
placeholder="Switch workspace…"
class="h-full min-w-0 flex-1 bg-transparent text-xs text-foreground outline-hidden placeholder:text-muted-foreground"
/>
</label>
<ul role="listbox" aria-label="Workspaces" class="max-h-56 min-h-0 overflow-y-auto py-1">
{
workspaces.map((ws) => (
<li role="presentation" data-ws-row data-search={ws.name.toLowerCase()}>
<button
type="button"
role="option"
aria-selected={ws.id === active?.id ? "true" : "false"}
data-ws-option={ws.id}
data-ws-name={ws.name}
data-ws-plan={ws.plan}
class="flex w-full cursor-pointer items-center justify-between gap-2 rounded-sm px-2 py-2 text-left text-[0.8125rem]/5 text-foreground transition-colors duration-75 hover:bg-accent aria-selected:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
>
<span class="min-w-0">
<span class="block truncate font-medium text-foreground">{ws.name}</span>
<span class="block text-[0.6875rem] text-muted-foreground">
{ws.plan} {ws.members ? `· ${ws.members} members` : ""}
</span>
</span>
<Check
data-ws-check
class={cn("size-3.5 shrink-0 text-foreground", ws.id === active?.id ? "opacity-100" : "opacity-0")}
aria-hidden="true"
/>
</button>
</li>
))
}
</ul>
<div class="border-t border-border pt-1">
<a
href={createHref}
class="flex h-8 items-center gap-2 rounded-sm px-2 text-xs font-medium text-foreground transition-colors duration-75 hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
>
<Plus class="size-3.5 text-muted-foreground" aria-hidden="true" />
<span>{createLabel}</span>
</a>
</div>
</div>
</div>
<script>
function initWorkspaceSwitchers() {
document.querySelectorAll<HTMLElement>("[data-haze-workspace-switcher]:not([data-enhanced])").forEach((root) => {
root.setAttribute("data-enhanced", "");
const trigger = root.querySelector<HTMLButtonElement>("[data-ws-trigger]");
const panel = root.querySelector<HTMLElement>("[data-ws-panel]");
const searchIn = root.querySelector<HTMLInputElement>("[data-ws-search]");
const activeName = root.querySelector<HTMLElement>("[data-ws-active-name]");
const activePlan = root.querySelector<HTMLElement>("[data-ws-active-plan]");
const options = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-ws-option]"));
const rows = Array.from(root.querySelectorAll<HTMLElement>("[data-ws-row]"));
if (!trigger || !panel) return;
panel.addEventListener("toggle", (ev) => {
const open = (ev as ToggleEvent).newState === "open";
trigger.setAttribute("aria-expanded", String(open));
if (open) {
if (searchIn) {
searchIn.value = "";
rows.forEach((r) => (r.hidden = false));
searchIn.focus();
}
}
});
const visible = () => options.filter((o) => !o.closest<HTMLElement>("[data-ws-row]")?.hidden);
searchIn?.addEventListener("keydown", (event) => {
if (event.key === "ArrowDown" || (event.key === "Enter" && searchIn.value.trim())) {
const first = visible()[0];
if (first) { event.preventDefault(); event.stopPropagation(); if (event.key === "ArrowDown") first.focus(); else first.click(); }
}
});
panel.addEventListener("keydown", (event) => {
const list = visible();
const at = list.indexOf(document.activeElement as HTMLButtonElement);
if (at < 0) return;
const next = event.key === "ArrowDown" ? list[Math.min(at + 1, list.length - 1)] : event.key === "Home" ? list[0] : event.key === "End" ? list[list.length - 1] : null;
if (next) { event.preventDefault(); next.focus(); }
else if (event.key === "ArrowUp") { event.preventDefault(); if (at > 0) list[at - 1].focus(); else searchIn?.focus(); }
});
searchIn?.addEventListener("input", () => {
const q = searchIn.value.trim().toLowerCase();
rows.forEach((r) => {
r.hidden = !!q && !(r.dataset.search ?? "").includes(q);
});
});
options.forEach((opt) => {
opt.addEventListener("click", () => {
const nextName = opt.dataset.wsName ?? "";
const nextPlan = opt.dataset.wsPlan ?? "";
if (activeName) activeName.textContent = nextName;
if (activePlan) activePlan.textContent = `${nextPlan} plan`;
options.forEach((o) => {
const on = o === opt;
o.setAttribute("aria-selected", String(on));
o.querySelector("[data-ws-check]")?.classList.toggle("opacity-100", on);
o.querySelector("[data-ws-check]")?.classList.toggle("opacity-0", !on);
});
panel.hidePopover?.();
trigger.focus();
root.dispatchEvent(new CustomEvent("haze:workspace-change", { bubbles: true, detail: { id: opt.dataset.wsOption, name: nextName } }));
});
});
});
}
initWorkspaceSwitchers();
if (!document.documentElement.hasAttribute("data-haze-ws-listener")) {
document.documentElement.setAttribute("data-haze-ws-listener", "");
document.addEventListener("astro:page-load", initWorkspaceSwitchers);
}
</script>When to use
- Top-left sidebar or header navigation in multi-workspace SaaS applications
- Switching between billing accounts, teams, or environments
When not to use
- Single-selection form inputs belong in select or combobox
- Signed-in user profile actions belong in account-menu
Installation
Add the Haze registry to components.json once, then install Workspace switcher with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/workspace-switchernpx shadcn@latest add @haze/workspace-switcheryarn dlx shadcn@latest add @haze/workspace-switcherbunx --bun shadcn@latest add @haze/workspace-switcherFirst 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 | – | Unique DOM id for the switcher and anchored popover. |
| workspaces | Workspace[] | – | Organizations with id, name, plan, and optional member count. |
| activeId | string | "tidewell" | Initially active workspace id. |
| createLabel | string | "Create workspace" | Footer action text. |
Keyboard interactions
- Escape
- Closes the switcher popover and returns focus to the trigger button.
Accessibility
- Anchored popover opens natively via popovertarget and closes with Escape or click-outside.
- Active selection is signaled by aria-selected alongside a Lucide Check icon.
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 "Workspace switcher" with `npx shadcn@latest add @haze/workspace-switcher`. 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 WorkspaceSwitcher from "@/components/haze/ui/workspace-switcher.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/workspace-switcher.md
Customize with real content
Adapt the Haze workspace-switcher ui for our product. Replace the demo values of these props with our real content: id, workspaces, activeId, createLabel. Keep the layout, the heading level rules and these accessibility details: Anchored popover opens natively via popovertarget and closes with Escape or click-outside. Active selection is signaled by aria-selected alongside a Lucide Check icon. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using workspace-switcher, check it fits: use it when top-left sidebar or header navigation in multi-workspace saas applications; switching between billing accounts, teams, or environments. Avoid it when single-selection form inputs belong in select or combobox; signed-in user profile actions belong in account-menu. Alternatives: @haze/account-menu, @haze/combobox, @haze/sidebar.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.