Morphic navbar
Inverted morphic pill bar where inactive links fuse seamlessly and the active destination splits apart with rounded neighbor corners.
pnpm dlx shadcn@latest add @haze/morphic-navbar---
import { Menu, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface NavItem {
label: string;
href: string;
current?: boolean;
}
interface Props {
/** Unique on the page. Links the compact mobile trigger to its menu popover. */
id: string;
items?: NavItem[];
/** Accessible name for the navigation landmark. */
label?: string;
/** Accessible name for the compact mobile menu button. */
menuLabel?: string;
/** Accessible name for the mobile close button. */
closeLabel?: string;
class?: string;
}
const defaultItems: NavItem[] = [
{ label: "Home", href: "#home", current: true },
{ label: "Work", href: "#work" },
{ label: "Journal", href: "#journal" },
{ label: "Specs", href: "#specs" },
{ label: "About", href: "#about" },
];
const {
id,
items = defaultItems,
label = "Primary navigation",
menuLabel = "Open navigation menu",
closeLabel = "Close menu",
class: className,
} = Astro.props;
const activeIndex = Math.max(0, items.findIndex((item) => item.current));
const activeItem = items[activeIndex] ?? items[0];
const menuId = `${id}-menu`;
---
<nav
id={id}
data-haze-morphic-navbar
aria-label={label}
class={cn("@container relative w-full min-w-0", className)}
>
<div class="hidden @sm:flex @sm:justify-center">
<ul role="list" class="inline-flex max-w-full items-center">
{
items.map((item, index) => {
const isCurrent = index === activeIndex;
const isBefore = index === activeIndex - 1;
const isAfter = index === activeIndex + 1;
const edge =
items.length === 1
? "both"
: index === 0
? "start"
: index === items.length - 1
? "end"
: undefined;
return (
<li class="min-w-0">
<a
href={item.href}
data-mn-link
data-mn-index={index}
data-edge={edge}
data-before-active={isBefore ? "" : undefined}
data-after-active={isAfter ? "" : undefined}
aria-current={isCurrent ? "page" : undefined}
class={cn(
"relative inline-flex h-10 max-w-full items-center justify-center rounded-none bg-primary px-4 text-[0.8125rem]/5 font-medium whitespace-nowrap text-primary-foreground/75 transition-[border-radius,margin,background-color,color] duration-200 ease-snappy hover:text-primary-foreground focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring motion-reduce:transition-none",
"data-[edge=start]:rounded-l-xl data-[edge=end]:rounded-r-xl data-[edge=both]:rounded-xl",
"data-[before-active]:rounded-r-xl data-[after-active]:rounded-l-xl",
"aria-[current=page]:mx-1.5 aria-[current=page]:rounded-xl aria-[current=page]:font-semibold aria-[current=page]:text-primary-foreground aria-[current=page]:shadow-key",
"data-[edge=start]:aria-[current=page]:ms-0 data-[edge=end]:aria-[current=page]:me-0 data-[edge=both]:aria-[current=page]:mx-0",
)}
>
<span class="truncate">{item.label}</span>
</a>
</li>
);
})
}
</ul>
</div>
<div class="flex w-full min-w-0 items-center justify-between gap-2 rounded-xl bg-primary py-1.5 ps-4 pe-1.5 text-primary-foreground shadow-key @sm:hidden">
<span data-mn-current class="min-w-0 truncate text-[0.8125rem]/5 font-semibold text-primary-foreground">
{activeItem?.label ?? label}
</span>
<button
type="button"
popovertarget={menuId}
aria-label={menuLabel}
aria-controls={menuId}
aria-expanded="false"
data-mn-toggle
style={`anchor-name: --${menuId}`}
class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-primary-foreground/12 text-primary-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-primary-foreground/20 active:scale-95 motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<Menu class="size-4" aria-hidden="true" />
</button>
</div>
<div
popover
id={menuId}
data-mn-popover
style={`position-anchor: --${menuId}`}
class={cn(
"m-auto max-h-[min(22rem,calc(100dvh-2rem))] w-56 max-w-[calc(100vw-1rem)] overflow-y-auto rounded-2xl border border-border bg-popover p-1.5 text-[0.8125rem]/5 text-popover-foreground shadow-float backdrop:bg-background/60",
"origin-top-right -translate-y-1 scale-[0.97] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-200 ease-snappy motion-reduce:transition-none open:translate-y-0 open:scale-100 open:opacity-100 starting:open:-translate-y-1 starting:open:scale-[0.97] starting:open:opacity-0",
"supports-[position-area:block-end]:mx-0 supports-[position-area:block-end]:my-1.5 supports-[position-area:block-end]:ms-2 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-start] supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline]",
)}
>
<div class="mb-1 flex items-center justify-between gap-2 border-b border-border px-2.5 py-1.5">
<span class="text-xs/4 font-medium text-muted-foreground">{label}</span>
<button
type="button"
popovertarget={menuId}
popovertargetaction="hide"
aria-label={closeLabel}
class="inline-flex size-6 cursor-pointer items-center justify-center rounded-lg text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<X class="size-3.5" aria-hidden="true" />
</button>
</div>
<ul role="list" class="grid gap-0.5">
{
items.map((item, index) => {
const isCurrent = index === activeIndex;
return (
<li>
<a
href={item.href}
data-mn-mobile-link
data-mn-index={index}
aria-current={isCurrent ? "page" : undefined}
class="flex min-h-9 items-center rounded-xl px-3 py-1.5 font-medium text-popover-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-[current=page]:bg-primary aria-[current=page]:font-semibold aria-[current=page]:text-primary-foreground"
>
<span class="truncate">{item.label}</span>
</a>
</li>
);
})
}
</ul>
</div>
</nav>
<script>
function enhanceMorphicNavbar(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const links = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-mn-link]"));
const mobileLinks = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-mn-mobile-link]"));
const currentLabel = root.querySelector<HTMLElement>("[data-mn-current]");
const toggle = root.querySelector<HTMLButtonElement>("[data-mn-toggle]");
const popover = root.querySelector<HTMLElement>("[data-mn-popover]");
if (!links.length) return;
const selectIndex = (index: number) => {
const target = links[index];
if (!target) return;
links.forEach((link, i) => {
if (i === index) link.setAttribute("aria-current", "page");
else link.removeAttribute("aria-current");
link.toggleAttribute("data-before-active", i === index - 1);
link.toggleAttribute("data-after-active", i === index + 1);
});
mobileLinks.forEach((link, i) => {
if (i === index) link.setAttribute("aria-current", "page");
else link.removeAttribute("aria-current");
});
if (currentLabel) currentLabel.textContent = target.textContent?.trim() ?? "";
root.dispatchEvent(
new CustomEvent("haze:morphic-navbar-change", {
detail: { index, href: target.getAttribute("href") ?? "", label: target.textContent?.trim() ?? "" },
bubbles: true,
}),
);
};
const handleClick = (link: HTMLAnchorElement, event: MouseEvent) => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const index = Number(link.dataset.mnIndex);
if (!Number.isFinite(index)) return;
const href = link.getAttribute("href") ?? "";
if (href.startsWith("#")) {
const targetEl = href.length > 1 ? document.getElementById(href.slice(1)) : null;
if (!targetEl) event.preventDefault();
}
selectIndex(index);
if (popover?.matches(":popover-open")) popover.hidePopover();
};
links.forEach((link) => {
link.addEventListener("click", (event) => handleClick(link, event));
link.addEventListener("keydown", (event) => {
const index = links.indexOf(link);
let next: number | undefined;
if (event.key === "ArrowRight") next = (index + 1) % links.length;
else if (event.key === "ArrowLeft") next = (index - 1 + links.length) % links.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = links.length - 1;
if (next === undefined) return;
event.preventDefault();
links[next].focus();
});
});
mobileLinks.forEach((link) => {
link.addEventListener("click", (event) => handleClick(link, event));
});
popover?.addEventListener("toggle", () => {
toggle?.setAttribute("aria-expanded", String(popover.matches(":popover-open")));
});
root.setAttribute("data-enhanced", "");
}
const initMorphicNavbars = () => {
document.querySelectorAll<HTMLElement>("[data-haze-morphic-navbar]").forEach(enhanceMorphicNavbar);
};
initMorphicNavbars();
if (!document.documentElement.hasAttribute("data-haze-morphic-navbar-listener")) {
document.documentElement.setAttribute("data-haze-morphic-navbar-listener", "");
document.addEventListener("astro:page-load", initMorphicNavbars);
}
</script>When to use
- A top-level section bar needs a tactile split-pill silhouette across three to six destinations
- A compact floating header needs automatic collapse into a native popover menu on narrow viewports
- In-page or SPA navigation benefits from crisp corner-morphing continuity when switching routes
When not to use
- Navigation needs multi-column mega menus or nested link groups; use navigation-menu
- Controls toggle local view state rather than page destinations; use segmented-control or tabs
Installation
Add the Haze registry to components.json once, then install Morphic navbar with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/morphic-navbarnpx shadcn@latest add @haze/morphic-navbaryarn dlx shadcn@latest add @haze/morphic-navbarbunx --bun shadcn@latest add @haze/morphic-navbarFirst 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 caller-supplied ID used to connect the mobile menu trigger and popover. |
| items | { label: string; href: string; current?: boolean }[] | 5 sample links | Ordered navigation destinations; mark the active item with current. |
| label | string | "Primary navigation" | Accessible label for the navigation landmark and mobile popover header. |
| menuLabel | string | "Open navigation menu" | Accessible name for the narrow-viewport menu trigger button. |
| closeLabel | string | "Close menu" | Accessible name for the close button inside the mobile popover. |
| class | string | – | Additional classes on the outer nav container. |
Keyboard interactions
- TabShiftTab
- Move focus into the bar or onto the mobile menu button
- ArrowLeftArrowRight
- Move focus between desktop links inside the pill bar
- Enter
- Activate the focused navigation link or toggle the mobile menu
- Escape
- Close the mobile navigation popover
Accessibility
- Marks the active destination with aria-current="page" and computes initial split corners server-side so the morphing geometry renders without JavaScript.
- Uses native popover and popovertarget for the narrow-viewport menu so Escape, light-dismiss and focus restoration work automatically.
- Disables corner and margin transitions when prefers-reduced-motion is active.
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 "Morphic navbar" with `npx shadcn@latest add @haze/morphic-navbar`. 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 MorphicNavbar from "@/components/haze/ui/morphic-navbar.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/morphic-navbar.md
Customize with real content
Adapt the Haze morphic-navbar ui for our product. Replace the demo values of these props with our real content: id, items, label, menuLabel, closeLabel, class. Keep the layout, the heading level rules and these accessibility details: Marks the active destination with aria-current="page" and computes initial split corners server-side so the morphing geometry renders without JavaScript. Uses native popover and popovertarget for the narrow-viewport menu so Escape, light-dismiss and focus restoration work automatically. Disables corner and margin transitions when prefers-reduced-motion is active. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using morphic-navbar, check it fits: use it when a top-level section bar needs a tactile split-pill silhouette across three to six destinations; a compact floating header needs automatic collapse into a native popover menu on narrow viewports; in-page or spa navigation benefits from crisp corner-morphing continuity when switching routes. Avoid it when navigation needs multi-column mega menus or nested link groups; use navigation-menu; controls toggle local view state rather than page destinations; use segmented-control or tabs. Alternatives: @haze/navigation-menu, @haze/segmented-control, @haze/tabs.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.