# Profile dropdown

> Spacious account card trigger with status-dot initials avatar opening a width-matched popover with workspace badge and icon links.

- Kind: ui · Category: Navigation · Interactivity: script
- Install: `npx shadcn@latest add @haze/profile-dropdown`
- File: `src/components/haze/ui/profile-dropdown.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/profile-dropdown

## Use when
- An application header or sidebar needs an account card showing avatar, name, email and plan badge
- Account navigation should open anchored to the trigger card with clean keyboard and no-JS fallback

## Avoid when
- A generic action menu without user identity details is needed; use dropdown-menu
- A minimal name-and-links trigger without plan tier or grouped sections is sufficient; use account-menu

## Alternatives
- [account-menu](https://hazeui.com/ui/account-menu.md)
- [dropdown-menu](https://hazeui.com/ui/dropdown-menu.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique ID linking the trigger popovertarget, CSS anchor name and menu panel. |
| name | `string` | "Maya Lin" | no | User display name shown in the trigger card and used to derive initials. |
| email | `string` | "maya@bramble.studio" | no | Email address rendered beneath the name on the trigger card and inside the menu header. |
| workspace | `string` | "Bramble Studio" | no | Workspace or organization name shown beside the plan badge at the top of the popover. |
| avatarSrc | `string` |  | no | Optional avatar photo URL; high-contrast initials render when omitted. |
| status | `"online" \| "away"` | "online" | no | Presence indicator dot offset cleanly at the bottom-right rim of the avatar. |
| plan | `string` | "Pro" | no | Subscription or tier label shown as a badge inside the popover header. |
| groups | `{ heading?: string; items: { label: string; href: string; hint?: string; icon?: string }[] }[]` | 4 account links | no | Grouped icon-prefixed account links with optional section headings and keyboard hints. |
| signOutLabel | `string` | "Sign out" | no | Text label for the destructive sign-out link in the menu footer. |
| signOutHref | `string` | "#sign-out" | no | Destination URL for the sign-out link. |
| align | `"start" \| "end"` | "end" | no | Horizontal edge of the trigger card to align the popover against. |
| side | `"bottom" \| "top"` | "bottom" | no | Preferred vertical side relative to the trigger before anchor flipping. |
| compact | `boolean` | false | no | Show only the avatar and chevrons icon on the trigger button. |
| class | `string` |  | no | Additional classes on the outer wrapper. |

## Accessibility
- Uses native popover and popovertarget so opening, light-dismiss and Escape work without scripts.
- Enhances keyboard navigation with ArrowDown, ArrowUp, Home, End and character typeahead across all menu items and Sign out.
- Syncs aria-expanded on the trigger button and respects prefers-reduced-motion for panel transitions.
- Key Enter / Space: Open or close the profile popover from the account trigger card
- Key ArrowDown / ArrowUp: Open the menu or move focus across icon links and Sign out
- Key Home / End: Jump focus to the first or last account menu item
- Key Escape: Close the popover and return focus to the account trigger

## Agent prompts

### Install and use

Install the Haze UI component "Profile dropdown" with `npx shadcn@latest add @haze/profile-dropdown`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/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 ProfileDropdown from "@/components/haze/ui/profile-dropdown.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: https://hazeui.com/ui/profile-dropdown.md

### Customize with real content

Adapt the Haze profile-dropdown ui for our product. Replace the demo values of these props with our real content: id, name, email, workspace, avatarSrc, status, plan, groups, signOutLabel, signOutHref, align, side, compact, class. Keep the layout, the heading level rules and these accessibility details: Uses native popover and popovertarget so opening, light-dismiss and Escape work without scripts. Enhances keyboard navigation with ArrowDown, ArrowUp, Home, End and character typeahead across all menu items and Sign out. Syncs aria-expanded on the trigger button and respects prefers-reduced-motion for panel transitions. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using profile-dropdown, check it fits: use it when an application header or sidebar needs an account card showing avatar, name, email and plan badge; account navigation should open anchored to the trigger card with clean keyboard and no-js fallback. Avoid it when a generic action menu without user identity details is needed; use dropdown-menu; a minimal name-and-links trigger without plan tier or grouped sections is sufficient; use account-menu. Alternatives: @haze/account-menu, @haze/dropdown-menu.

## Example requests that should lead here
- Add a spacious profile dropdown card showing circular initials avatar, online dot, email, workspace badge and icon menu items
- Place an account switcher dropdown using native popover with arrow-key navigation and destructive sign-out

## Source

```astro
---
import {
  Bell,
  BookOpen,
  ChevronDown,
  CreditCard,
  Keyboard,
  LogOut,
  Settings,
  Shield,
  Sparkles,
  User,
  Users,
} from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

type ProfileIcon =
  | "user"
  | "credit-card"
  | "settings"
  | "keyboard"
  | "users"
  | "book"
  | "sparkles"
  | "shield"
  | "bell";

interface ProfileLink {
  label: string;
  href: string;
  hint?: string;
  icon?: ProfileIcon;
}

interface ProfileGroup {
  heading?: string;
  items: ProfileLink[];
}

interface Props {
  /** Unique on the page. Connects the trigger popovertarget and CSS anchor to the menu panel. */
  id: string;
  name?: string;
  email?: string;
  workspace?: string;
  avatarSrc?: string;
  status?: "online" | "away";
  plan?: string;
  groups?: ProfileGroup[];
  signOutLabel?: string;
  signOutHref?: string;
  align?: "start" | "end";
  side?: "bottom" | "top";
  /** Hide name and email next to the avatar on the trigger button. */
  compact?: boolean;
  class?: string;
}

const iconMap = {
  user: User,
  "credit-card": CreditCard,
  settings: Settings,
  keyboard: Keyboard,
  users: Users,
  book: BookOpen,
  sparkles: Sparkles,
  shield: Shield,
  bell: Bell,
} as const;

const defaultGroups: ProfileGroup[] = [
  {
    items: [
      { label: "Profile", href: "#profile", icon: "user", hint: "G P" },
      { label: "Billing", href: "#billing", icon: "credit-card" },
      { label: "Workspace settings", href: "#settings", icon: "settings" },
      { label: "Keyboard shortcuts", href: "#shortcuts", icon: "keyboard", hint: "?" },
    ],
  },
];

const {
  id,
  name = "Maya Lin",
  email = "maya@bramble.studio",
  workspace = "Bramble Studio",
  avatarSrc,
  status = "online",
  plan = "Pro",
  groups = defaultGroups,
  signOutLabel = "Sign out",
  signOutHref = "#sign-out",
  align = "end",
  side = "bottom",
  compact = false,
  class: className,
} = Astro.props;

const initials = name
  .split(/\s+/)
  .map((part) => part[0] ?? "")
  .join("")
  .slice(0, 2)
  .toUpperCase();

const statusDot = {
  online: "bg-success",
  away: "bg-muted-foreground",
};

const placement = {
  "bottom-start": "origin-top-left -translate-y-1.5 starting:open:-translate-y-1.5 supports-[position-area:block-end]:me-2 supports-[position-area:block-end]:[position-area:block-end_span-inline-end]",
  "bottom-end": "origin-top-right -translate-y-1.5 starting:open:-translate-y-1.5 supports-[position-area:block-end]:ms-2 supports-[position-area:block-end]:[position-area:block-end_span-inline-start]",
  "top-start": "origin-bottom-left translate-y-1.5 starting:open:translate-y-1.5 supports-[position-area:block-end]:me-2 supports-[position-area:block-end]:[position-area:block-start_span-inline-end]",
  "top-end": "origin-bottom-right translate-y-1.5 starting:open:translate-y-1.5 supports-[position-area:block-end]:ms-2 supports-[position-area:block-end]:[position-area:block-start_span-inline-start]",
};
---

<div class={cn("inline-block max-w-full", className)}>
  <button
    type="button"
    popovertarget={id}
    aria-haspopup="menu"
    aria-controls={id}
    aria-expanded="false"
    aria-label={compact ? `${name}, account menu` : undefined}
    data-pd-trigger
    style={`anchor-name: --${id}`}
    class={cn(
      "group flex max-w-full cursor-pointer items-center gap-3 rounded-xl border border-border bg-field px-3 py-2 text-left text-foreground shadow-key transition-[background-color,border-color] duration-150 ease-snappy hover:bg-accent/50 data-[open]:bg-accent motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
      compact ? "px-2 py-1.5 gap-2" : "min-w-[240px]",
    )}
  >
    <span class="relative inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-primary text-xs/none font-semibold text-primary-foreground select-none" aria-hidden="true">
      {
        avatarSrc ? (
          <img src={avatarSrc} alt="" width="36" height="36" loading="lazy" class="size-full rounded-full object-cover" />
        ) : (
          <span>{initials}</span>
        )
      }
      {
        status && (
          <span
            class={cn(
              "absolute -right-0.5 -bottom-0.5 size-2.5 rounded-full ring-2 ring-card forced-colors:border forced-colors:border-current",
              statusDot[status],
            )}
          />
        )
      }
    </span>

    {
      !compact && (
        <span class="grid min-w-0 flex-1 gap-0.5">
          <span class="truncate text-sm/5 font-medium text-foreground">{name}</span>
          <span class="truncate text-xs/4 text-muted-foreground">{email}</span>
        </span>
      )
    }

    <ChevronDown
      aria-hidden="true"
      class="ml-auto size-4 shrink-0 text-muted-foreground transition-[rotate,color] duration-200 ease-snappy group-data-[open]:rotate-180 group-data-[open]:text-foreground motion-reduce:transition-none"
    />
  </button>

  <div
    popover
    id={id}
    role="menu"
    aria-label={`${name} account menu`}
    data-haze-profile-dropdown
    style={`position-anchor: --${id}`}
    class={cn(
      "m-auto max-h-[min(28rem,calc(100dvh-2rem))] min-w-[240px] w-64 max-w-[calc(100vw-1rem)] overflow-y-auto rounded-xl border border-border bg-popover p-1.5 text-[0.8125rem]/5 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 open:translate-y-0 open:scale-100 open:opacity-100 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]:max-h-[calc(100%-0.75rem)] supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-try-order:most-block-size] supports-[position-area:block-end]:[position-try-fallbacks:flip-block]",
      placement[`${side}-${align}`],
    )}
  >
    <div class="mb-1 flex min-w-0 items-center justify-between gap-2 border-b border-border px-2.5 py-2">
      <div class="grid min-w-0 gap-0.5">
        <p class="truncate text-xs/4 font-medium text-foreground">{workspace}</p>
        <p class="truncate text-[0.6875rem]/4 text-muted-foreground">{email}</p>
      </div>
      {
        plan && (
          <span class="inline-flex shrink-0 items-center rounded-md border border-border px-2 py-0.5 text-[0.6875rem]/4 font-medium text-muted-foreground">
            {plan}
          </span>
        )
      }
    </div>

    <div class="grid gap-1">
      {
        groups.map((group, groupIndex) => (
          <div class={cn(groupIndex > 0 && "border-t border-border pt-1")}>
            {group.heading && (
              <p class="px-2.5 pt-1.5 pb-1 text-[0.6875rem]/4 font-medium tracking-wider text-muted-foreground uppercase">
                {group.heading}
              </p>
            )}
            <ul role="list" class="grid gap-0.5">
              {group.items.map((item) => {
                const Icon = item.icon ? iconMap[item.icon] : undefined;
                return (
                  <li>
                    <a
                      href={item.href}
                      role="menuitem"
                      data-pd-item
                      class="flex min-h-9 items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-popover-foreground transition-colors duration-100 ease-snappy hover:bg-accent focus-visible:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
                    >
                      {Icon && <Icon class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />}
                      <span class="min-w-0 flex-1 truncate">{item.label}</span>
                      {item.hint && <span class="font-mono text-[0.6875rem]/4 text-muted-foreground">{item.hint}</span>}
                    </a>
                  </li>
                );
              })}
            </ul>
          </div>
        ))
      }
    </div>

    <div class="mt-1 border-t border-border pt-1">
      <slot name="footer" />
      <a
        href={signOutHref}
        role="menuitem"
        data-pd-item
        class="flex min-h-9 items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-popover-foreground transition-colors duration-100 ease-snappy hover:bg-accent focus-visible:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
      >
        <LogOut class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
        <span class="min-w-0 flex-1 truncate">{signOutLabel}</span>
      </a>
    </div>
  </div>
</div>

<script>
  function enhanceProfileDropdown(panel: HTMLElement) {
    if (panel.hasAttribute("data-enhanced")) return;
    const trigger = document.querySelector<HTMLButtonElement>(`[popovertarget="${CSS.escape(panel.id)}"]`);
    if (!trigger) return;

    const getItems = () =>
      Array.from(panel.querySelectorAll<HTMLElement>("[data-pd-item]")).filter(
        (el) => !el.hidden && el.getAttribute("aria-disabled") !== "true",
      );

    trigger.addEventListener("keydown", (event) => {
      if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
      event.preventDefault();
      if (!panel.matches(":popover-open")) panel.showPopover();
      const items = getItems();
      const target = event.key === "ArrowUp" ? items.at(-1) : items[0];
      target?.focus();
    });

    let buffer = "";
    let lastKey = 0;

    panel.addEventListener("keydown", (event) => {
      if (event.altKey || event.ctrlKey || event.metaKey || event.key === "Tab") return;
      const items = getItems();
      if (!items.length) return;
      const current = items.indexOf(document.activeElement as HTMLElement);
      let next: HTMLElement | undefined;

      if (event.key === "ArrowDown") {
        next = items[(current + 1) % items.length];
      } else if (event.key === "ArrowUp") {
        next = items[current <= 0 ? items.length - 1 : current - 1];
      } else if (event.key === "Home") {
        next = items[0];
      } else if (event.key === "End") {
        next = items.at(-1);
      } else if (event.key.length === 1 && event.key !== " ") {
        const now = performance.now();
        buffer = now - lastKey > 650 ? event.key : buffer + event.key;
        lastKey = now;
        const query = buffer.toLocaleLowerCase();
        next = [...items.slice(current + 1), ...items.slice(0, current + 1)].find((item) =>
          item.textContent?.trim().toLocaleLowerCase().startsWith(query),
        );
      }

      if (next) {
        event.preventDefault();
        next.focus();
      }
    });

    panel.addEventListener("toggle", () => {
      const open = panel.matches(":popover-open");
      trigger.setAttribute("aria-expanded", String(open));
      trigger.toggleAttribute("data-open", open);
      if (!open) buffer = "";
    });

    panel.addEventListener("click", (event) => {
      if ((event.target as Element).closest("[data-pd-item]")) {
        panel.hidePopover();
      }
    });

    const isOpen = panel.matches(":popover-open");
    trigger.setAttribute("aria-expanded", String(isOpen));
    trigger.toggleAttribute("data-open", isOpen);
    panel.setAttribute("data-enhanced", "");
  }

  const initProfileDropdowns = () => {
    document.querySelectorAll<HTMLElement>("[data-haze-profile-dropdown]").forEach(enhanceProfileDropdown);
  };
  initProfileDropdowns();
  if (!document.documentElement.hasAttribute("data-haze-profile-dropdown-listener")) {
    document.documentElement.setAttribute("data-haze-profile-dropdown-listener", "");
    document.addEventListener("astro:page-load", initProfileDropdowns);
  }
</script>
```
