Responsive navbar with products menu

A sticky top bar with logo, a Products disclosure menu (two-column panel with icons, descriptions and a footer link), plain links, sign-in and a primary action. The menu opens on click or Arrow Down, moves with arrow keys, and closes on Escape, outside press or when focus leaves. Below the large breakpoint a menu button opens a full-height sheet: a modal dialog that takes focus, keeps Tab inside, closes on Escape or the backdrop, locks page scroll and hands focus back.

NavigationBlockTailwind v4

Source

"use client";

import { useCallback, useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { ArrowRight, ChevronDown, FileText, Inbox, Menu, PanelsTopLeft, Workflow, X, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";

export type NavLink = { label: string; href: string };
export type NavProduct = { label: string; description: string; href: string; icon: LucideIcon };

export type NavbarResponsiveProps = {
  brand?: string;
  logo?: ReactNode;
  homeHref?: string;
  products?: NavProduct[];
  productsLabel?: string;
  /** A link at the foot of the products menu. */
  productsFooter?: NavLink;
  links?: NavLink[];
  signIn?: NavLink;
  cta?: NavLink;
  /** Open the products menu on first render (useful for demos and docs). */
  defaultProductsOpen?: boolean;
  className?: string;
};

const DEFAULT_PRODUCTS: NavProduct[] = [
  { label: "Docs", description: "Specs, notes and wikis with live editing", href: "#docs", icon: FileText },
  { label: "Whiteboards", description: "Sketch flows next to the page they explain", href: "#whiteboards", icon: PanelsTopLeft },
  { label: "Forms", description: "Collect requests straight into a table", href: "#forms", icon: Inbox },
  { label: "Automations", description: "Run checklists when a page changes", href: "#automations", icon: Workflow },
];

const DEFAULT_LINKS: NavLink[] = [
  { label: "Customers", href: "#customers" },
  { label: "Pricing", href: "#pricing" },
  { label: "Changelog", href: "#changelog" },
];

const KEYFRAMES = `@keyframes chm-nav-pop{from{opacity:0;transform:translateY(-4px) scale(.98)}to{opacity:1;transform:none}}
@keyframes chm-nav-sheet{from{transform:translateX(100%)}to{transform:none}}
@keyframes chm-nav-fade{from{opacity:0}to{opacity:1}}`;

const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])';

function DefaultLogo() {
  return (
    <svg viewBox="0 0 24 24" className="size-7" aria-hidden="true">
      <path d="M5 3h9l5 5v13H5V3Z" fill="currentColor" />
      <path d="M14 3v5h5" fill="none" stroke="var(--background)" strokeWidth="1.6" />
      <path d="M8.5 13.5h7M8.5 17h4.5" stroke="var(--background)" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}

export function NavbarResponsive({
  brand = "Paperlark",
  logo = <DefaultLogo />,
  homeHref = "/",
  products = DEFAULT_PRODUCTS,
  productsLabel = "Products",
  productsFooter = { label: "What's new in Paperlark 3", href: "#whats-new" },
  links = DEFAULT_LINKS,
  signIn = { label: "Sign in", href: "#sign-in" },
  cta = { label: "Start free", href: "#start" },
  defaultProductsOpen = false,
  className,
}: NavbarResponsiveProps) {
  const id = useId();
  const [productsOpen, setProductsOpen] = useState(defaultProductsOpen);
  const [sheetOpen, setSheetOpen] = useState(false);
  const productsRef = useRef<HTMLLIElement>(null);
  const productsButton = useRef<HTMLButtonElement>(null);
  const menuButton = useRef<HTMLButtonElement>(null);
  const sheetRef = useRef<HTMLDivElement>(null);
  const closeButton = useRef<HTMLButtonElement>(null);

  // Products menu: close on outside press and on Escape (returning focus to its button).
  useEffect(() => {
    if (!productsOpen) return;
    const onPointer = (event: PointerEvent) => {
      if (!productsRef.current?.contains(event.target as Node)) setProductsOpen(false);
    };
    document.addEventListener("pointerdown", onPointer);
    return () => document.removeEventListener("pointerdown", onPointer);
  }, [productsOpen]);

  const onProductsKey = (event: KeyboardEvent<HTMLLIElement>) => {
    const items = Array.from(productsRef.current?.querySelectorAll<HTMLAnchorElement>("[data-product-item]") ?? []);
    const index = items.indexOf(document.activeElement as HTMLAnchorElement);
    if (event.key === "Escape" && productsOpen) {
      event.preventDefault();
      setProductsOpen(false);
      productsButton.current?.focus();
    } else if (event.key === "ArrowDown") {
      event.preventDefault();
      if (!productsOpen) setProductsOpen(true);
      requestAnimationFrame(() => {
        const list = Array.from(productsRef.current?.querySelectorAll<HTMLAnchorElement>("[data-product-item]") ?? []);
        list[index < 0 ? 0 : Math.min(index + 1, list.length - 1)]?.focus();
      });
    } else if (event.key === "ArrowUp" && index >= 0) {
      event.preventDefault();
      if (index === 0) productsButton.current?.focus();
      else items[index - 1]?.focus();
    }
  };

  // Mobile sheet: a modal dialog. Focus moves in, Tab stays inside, Escape closes, focus returns to the menu button.
  const closeSheet = useCallback(() => {
    setSheetOpen(false);
    menuButton.current?.focus();
  }, []);

  useEffect(() => {
    if (!sheetOpen) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButton.current?.focus();
    const onKey = (event: globalThis.KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeSheet();
        return;
      }
      if (event.key !== "Tab" || !sheetRef.current) return;
      const focusable = Array.from(sheetRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last?.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first?.focus();
      }
    };
    // Widening past the breakpoint closes the sheet, so no hidden dialog keeps the page locked.
    const wide = window.matchMedia("(min-width: 1024px)");
    const onWide = () => wide.matches && setSheetOpen(false);
    document.addEventListener("keydown", onKey);
    wide.addEventListener("change", onWide);
    return () => {
      document.body.style.overflow = previousOverflow;
      document.removeEventListener("keydown", onKey);
      wide.removeEventListener("change", onWide);
    };
  }, [sheetOpen, closeSheet]);

  return (
    <header className={cn("sticky top-0 z-40 bg-background shadow-[0_1px_0_var(--border)]", className)}>
      <style href="chm-navbar-responsive" precedence="default">{KEYFRAMES}</style>
      <nav aria-label="Main" className="mx-auto flex h-16 max-w-6xl items-center gap-6 px-4 sm:px-6 lg:gap-10 lg:px-8">
        <a href={homeHref} className={cn("flex items-center gap-2.5 rounded-md text-lg font-semibold tracking-tight text-foreground", focusRing)}>
          {logo}
          {brand}
        </a>

        <ul className="hidden items-center gap-1 lg:flex">
          {products.length > 0 && (
            <li
              ref={productsRef}
              className="relative"
              onKeyDown={onProductsKey}
              onBlur={(event) => {
                if (!productsRef.current?.contains(event.relatedTarget as Node | null)) setProductsOpen(false);
              }}
            >
              <button
                ref={productsButton}
                type="button"
                aria-expanded={productsOpen}
                aria-controls={`${id}-products`}
                onClick={() => setProductsOpen((value) => !value)}
                className={cn(
                  "inline-flex h-9 items-center gap-1 rounded-md px-3 text-sm font-medium transition-colors hover:bg-accent hover:text-foreground",
                  productsOpen ? "bg-accent text-foreground" : "text-foreground/80",
                  focusRing,
                )}
              >
                {productsLabel}
                <ChevronDown className={cn("size-4 motion-safe:transition-transform", productsOpen && "rotate-180")} aria-hidden="true" />
              </button>
              <div
                id={`${id}-products`}
                hidden={!productsOpen}
                className="absolute left-0 top-full z-50 mt-3 w-[34rem] rounded-xl bg-popover p-2 text-popover-foreground shadow-[0_24px_60px_-20px_rgb(0_0_0/0.35)] ring-1 ring-border motion-safe:animate-[chm-nav-pop_.16s_ease-out]"
              >
                <ul className="grid grid-cols-2 gap-1">
                  {products.map(({ label, description, href, icon: Icon }) => (
                    <li key={label}>
                      <a
                        data-product-item
                        href={href}
                        onClick={() => setProductsOpen(false)}
                        className={cn("flex gap-3 rounded-lg p-3 transition-colors hover:bg-accent", focusRing)}
                      >
                        <span className="grid size-9 shrink-0 place-items-center rounded-md bg-muted text-foreground">
                          <Icon className="size-4" aria-hidden="true" />
                        </span>
                        <span>
                          <span className="block text-sm font-medium text-foreground">{label}</span>
                          <span className="mt-0.5 block text-sm leading-snug text-muted-foreground">{description}</span>
                        </span>
                      </a>
                    </li>
                  ))}
                </ul>
                {productsFooter && (
                  <a
                    data-product-item
                    href={productsFooter.href}
                    className={cn("mt-1 flex items-center justify-between rounded-lg bg-muted/70 px-4 py-3 text-sm font-medium text-foreground transition-colors hover:bg-muted", focusRing)}
                  >
                    {productsFooter.label}
                    <ArrowRight className="size-4" aria-hidden="true" />
                  </a>
                )}
              </div>
            </li>
          )}
          {links.map((link) => (
            <li key={link.label}>
              <a
                href={link.href}
                className={cn("inline-flex h-9 items-center rounded-md px-3 text-sm font-medium text-foreground/80 transition-colors hover:bg-accent hover:text-foreground", focusRing)}
              >
                {link.label}
              </a>
            </li>
          ))}
        </ul>

        <div className="ml-auto flex items-center gap-2">
          <a
            href={signIn.href}
            className={cn("hidden h-9 items-center rounded-md px-3 text-sm font-medium text-foreground/80 transition-colors hover:bg-accent hover:text-foreground sm:inline-flex", focusRing)}
          >
            {signIn.label}
          </a>
          <a
            href={cta.href}
            className={cn("hidden h-9 items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-opacity hover:opacity-90 sm:inline-flex", focusRing)}
          >
            {cta.label}
          </a>
          <button
            ref={menuButton}
            type="button"
            aria-expanded={sheetOpen}
            aria-controls={`${id}-sheet`}
            aria-label="Open menu"
            onClick={() => setSheetOpen(true)}
            className={cn("grid size-10 place-items-center rounded-md text-foreground transition-colors hover:bg-accent lg:hidden", focusRing)}
          >
            <Menu className="size-5" aria-hidden="true" />
          </button>
        </div>
      </nav>

      {sheetOpen && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-foreground/25 motion-safe:animate-[chm-nav-fade_.2s_ease-out]" onClick={closeSheet} aria-hidden="true" />
          <div
            ref={sheetRef}
            id={`${id}-sheet`}
            role="dialog"
            aria-modal="true"
            aria-label="Menu"
            className="absolute inset-y-0 right-0 flex w-full flex-col bg-background sm:max-w-sm shadow-[0_0_60px_-10px_rgb(0_0_0/0.4)] motion-safe:animate-[chm-nav-sheet_.25s_cubic-bezier(.2,.8,.2,1)]"
          >
            <div className="flex h-16 shrink-0 items-center justify-between px-4 sm:px-6">
              <a href={homeHref} onClick={closeSheet} className={cn("flex items-center gap-2.5 rounded-md text-lg font-semibold tracking-tight text-foreground", focusRing)}>
                {logo}
                {brand}
              </a>
              <button
                ref={closeButton}
                type="button"
                aria-label="Close menu"
                onClick={closeSheet}
                className={cn("grid size-10 place-items-center rounded-md text-foreground transition-colors hover:bg-accent", focusRing)}
              >
                <X className="size-5" aria-hidden="true" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto px-4 pb-6 sm:px-6">
              {products.length > 0 && (
                <section aria-labelledby={`${id}-sheet-products`} className="pt-2">
                  <h2 id={`${id}-sheet-products`} className="px-3 text-sm font-medium text-muted-foreground">{productsLabel}</h2>
                  <ul className="mt-2 space-y-1">
                    {products.map(({ label, description, href, icon: Icon }) => (
                      <li key={label}>
                        <a href={href} onClick={closeSheet} className={cn("flex items-center gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-accent", focusRing)}>
                          <span className="grid size-9 shrink-0 place-items-center rounded-md bg-muted text-foreground">
                            <Icon className="size-4" aria-hidden="true" />
                          </span>
                          <span className="min-w-0">
                            <span className="block text-base font-medium text-foreground">{label}</span>
                            <span className="block truncate text-sm text-muted-foreground">{description}</span>
                          </span>
                        </a>
                      </li>
                    ))}
                  </ul>
                </section>
              )}
              <ul className="mt-6 space-y-1 border-t border-border pt-6">
                {links.map((link) => (
                  <li key={link.label}>
                    <a href={link.href} onClick={closeSheet} className={cn("block rounded-lg px-3 py-2.5 text-lg font-medium text-foreground transition-colors hover:bg-accent", focusRing)}>
                      {link.label}
                    </a>
                  </li>
                ))}
              </ul>
            </div>

            <div className="grid shrink-0 gap-2 bg-muted/50 p-4 sm:px-6">
              <a href={cta.href} onClick={closeSheet} className={cn("inline-flex h-11 items-center justify-center rounded-md bg-primary text-sm font-medium text-primary-foreground", focusRing)}>
                {cta.label}
              </a>
              <a href={signIn.href} onClick={closeSheet} className={cn("inline-flex h-11 items-center justify-center rounded-md bg-background text-sm font-medium text-foreground ring-1 ring-border", focusRing)}>
                {signIn.label}
              </a>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}