{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "account-menu",
  "type": "registry:ui",
  "title": "Account Menu",
  "description": "The account control at the right end of a `Topbar`'s `actions` slot, for any sign-in service. It has the three states every app with accounts has:",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "navigation",
    "pattern"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/avatar.json",
    "https://ds.interlace.tools/r/button-variants.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/dropdown-menu.json",
    "https://ds.interlace.tools/r/visually-hidden.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/account-menu.tsx",
      "target": "components/ui/patterns/account-menu.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/account-menu v1.0.2 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/account-menu\n// What changed since: https://ds.interlace.tools/c/account-menu#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — AccountMenu\n *\n * The account control at the right end of a `Topbar`'s `actions` slot, for any sign-in service.\n * It has the three states every app with accounts has:\n *\n * 1. **Unknown.** The browser has not read the session yet. The control keeps exactly the room\n *    the answer will take, shows nothing, says nothing and cannot be focused.\n * 2. **Signed out.** A \"Sign in\" link that carries the page the person is on (`?next=`), and\n *    does not when they are already on the sign-in page.\n * 3. **Signed in.** Their photo, or their initials when there is none, as a menu button named\n *    \"Account menu for Dana\". The menu opens on a header (name and email), then the app's links,\n *    then \"Sign out\", which may take a moment and may fail.\n *\n * The component is a function of its props: it takes `state`. `useAccount(adapter)` builds that\n * state from the app's own service (Supabase, Auth.js, Clerk, a cookie), and the kit never reads\n * or writes a session. The pure helpers beside it (`accountDisplayName`, `accountInitials`,\n * `signInHref`, `safeReturnPath`) are in `account-menu-model`.\n *\n * ## The bar does not move\n *\n * Every state sits in one grid cell beside an invisible copy of the Sign in button at its own\n * label, and aligns to the end. So the root is as wide as Sign in in every state, in any font and\n * any language, the neighbour to its left sits in the same place in all three, and the avatar\n * (narrower) lands where Sign in's right edge was. `--account-menu-room` is only a floor. There\n * is no fade between the states: a control in the first viewport that fades in is a layout and\n * paint cost for nothing.\n *\n * ## Flow\n *\n * A flow (docs/philosophies/FLOW_PHILOSOPHY.md) with one part: the app drives every phase through\n * `state` (usually from `useAccount`), so there is nothing to compose.\n *\n * | Phase       | Part                                         | Leaves by                                        |\n * | ----------- | -------------------------------------------- | ------------------------------------------------ |\n * | unknown     | AccountMenu, an inert placeholder            | the adapter answers → signed-out or signed-in    |\n * | signed-out  | AccountMenu, the Sign in link                | the person signs in (the app's page) → signed-in |\n * | signed-in   | AccountMenu, the avatar and its menu         | Sign out → signing-out                           |\n * | signing-out | AccountMenu, Sign out disabled, \"Signing out…\" | the promise settles → signed-out, or failed   |\n * | failed      | AccountMenu, a polite live region, `onError` | the person tries again → signing-out             |\n *\n * ## Anatomy\n *\n *   AccountMenu                    (div — data-slot=\"account-menu\", data-state, one grid cell, min inline size = --account-menu-room)\n *     ├─ span                      (every state: data-slot=\"account-menu-room\", the Sign in label, aria-hidden, inert, invisible)\n *     ├─ span                      (unknown: data-slot=\"account-menu-placeholder\", aria-hidden, inert, invisible)\n *     ├─ a                         (signed-out: data-slot=\"account-menu-sign-in\", buttonVariants outline sm)\n *     └─ DropdownMenu              (signed-in)\n *         ├─ Trigger               (data-slot=\"account-menu-trigger\", aria-label = labels.menu(name), round)\n *         │   └─ Avatar            (image alt=\"\", no-referrer, or initials aria-hidden)\n *         ├─ Content               (align end)\n *         │   ├─ Label             (name and email: a heading, not an item)\n *         │   ├─ Separator\n *         │   ├─ Item × links      (data-slot=\"account-menu-link\", through `renderLink`)\n *         │   └─ Item              (data-slot=\"account-menu-sign-out\")\n *         └─ span role=status      (data-slot=\"account-menu-live\", visually hidden, polite)\n *\n * ## States\n *\n * Unknown, signed out, signed in (closed, open), image failed (initials show), no name and no\n * email (the fallback name, `?`), signing out, sign-out failed, long name or email (truncated,\n * full text in `title`), 320 px, RTL. Without JavaScript the server renders the unknown\n * placeholder: the session is read in the browser. A page that wants a Sign in link without\n * JavaScript renders its own `<noscript>` link beside this.\n *\n * ## Source of the API\n *\n * The slot and the three states are what apps with accounts write at the end of a header; the\n * adapter's `{ read, subscribe }` is the smallest shape that both a `getSession` plus\n * `onAuthStateChange` pair and an Auth.js `getSession` plus session event fit. It diverges from\n * those libraries on purpose: it names none of them.\n *\n * | Rule | Concept                  | Where                                                      |\n * | ---- | ------------------------ | ---------------------------------------------------------- |\n * | R6   | data-slot per part       | every part above                                           |\n * | R14  | declares a min viewport  | `MIN_VIEWPORT` on the root (`data-min-viewport`)           |\n * | R19  | tokens only              | `text-muted-foreground`, `ring-ring`, `size-control`       |\n * | R25  | client component         | the menu primitive and the live region need the browser    |\n * | R26  | A11y                     | named trigger, header is not an item, polite live region   |\n */\n\nimport { cn } from '@/lib/utils';\nimport { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';\nimport { buttonVariants } from '@/components/ui/button-variants';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuLabel,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from '@/components/ui/dropdown-menu';\nimport { VisuallyHidden } from '@/components/ui/visually-hidden';\nimport {\n  accountDisplayName,\n  accountInitials,\n  DEFAULT_FALLBACK_NAME,\n  signInHref as buildSignInHref,\n  type Account,\n  type AccountState,\n} from '@/components/ui/patterns/account-menu-model';\n\nexport { useAccount, type AccountAdapter } from '@/components/ui/patterns/use-account';\nexport type { Account, AccountState };\n\nexport const MIN_VIEWPORT = 320 as const;\n\n/**\n * A floor for the root's width, under the invisible Sign in copy that sets it. It is 0 because\n * that copy already makes the root as wide as Sign in at its own label; a floor above it only\n * widened the bar (72px for a 61px button was 11px a phone could not spare). An app that wants\n * more room sets `--account-menu-room` on the control or above it.\n */\nconst DEFAULT_ROOM = '0px';\n\nexport interface AccountMenuLink {\n  label: string;\n  href: string;\n  icon?: React.ReactNode;\n}\n\nexport interface AccountMenuLabels {\n  signIn: string;\n  signOut: string;\n  signingOut: string;\n  signOutFailed: string;\n  /** The trigger's accessible name, given the display name. */\n  menu: (name: string) => string;\n  /** What to call a person with no name and no email. */\n  fallbackName: string;\n}\n\nexport interface AccountMenuLinkRenderProps {\n  href: string;\n  className?: string;\n  /** Put this on the element you return, so the part keeps its `data-slot`. */\n  'data-slot'?: string;\n  children: React.ReactNode;\n}\n\nexport interface AccountMenuProps extends Omit<React.ComponentProps<'div'>, 'children'> {\n  state: AccountState;\n  /** The sign-in page. The current page is added as `?next=` unless `here` is the sign-in page. */\n  signInHref: string;\n  /** The page the person is on, a path. Used to build `?next=`. Read from your router, not here. */\n  here?: string;\n  /** Links between the header and Sign out. */\n  links?: readonly AccountMenuLink[];\n  /** May return a promise. A rejection is shown (a polite message) and passed to `onError`. */\n  onSignOut: () => void | Promise<void>;\n  onError?: (error: unknown) => void;\n  /** The same seam as `Topbar`: a router's Link. Defaults to a plain `<a>`. */\n  renderLink?: (props: AccountMenuLinkRenderProps) => React.ReactElement;\n  labels?: Partial<AccountMenuLabels>;\n}\n\nexport const DEFAULT_LABELS: AccountMenuLabels = {\n  signIn: 'Sign in',\n  signOut: 'Sign out',\n  signingOut: 'Signing out…',\n  signOutFailed: 'We could not sign you out. Try again.',\n  menu: (name) => `Account menu for ${name}`,\n  fallbackName: DEFAULT_FALLBACK_NAME,\n};\n\nconst defaultRenderLink: NonNullable<AccountMenuProps['renderLink']> = ({ href, className, children, ...rest }) => (\n  <a href={href} className={className} {...rest}>\n    {children}\n  </a>\n);\n\nconst SIGN_IN_CLASS = buttonVariants({ variant: 'outline', size: 'sm' });\n\nfunction AccountMenu({\n  state,\n  signInHref,\n  here,\n  links = [],\n  onSignOut,\n  onError,\n  renderLink = defaultRenderLink,\n  labels: labelOverrides,\n  className,\n  style,\n  ...props\n}: AccountMenuProps) {\n  const labels = { ...DEFAULT_LABELS, ...labelOverrides };\n  const [open, setOpen] = React.useState(false);\n  const [pending, setPending] = React.useState(false);\n  const [failed, setFailed] = React.useState(false);\n  const busy = React.useRef(false);\n  const trigger = React.useRef<HTMLButtonElement>(null);\n\n  async function signOut() {\n    if (busy.current) return;\n    busy.current = true;\n    setPending(true);\n    setFailed(false);\n    try {\n      await onSignOut();\n      setOpen(false);\n    } catch (error) {\n      setOpen(false);\n      setFailed(true);\n      onError?.(error);\n      trigger.current?.focus();\n    } finally {\n      busy.current = false;\n      setPending(false);\n    }\n  }\n\n  return (\n    <div\n      data-slot=\"account-menu\"\n      data-state={state.status}\n      data-account-id={state.status === 'signed-in' ? state.account.id : undefined}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid min-h-control items-center justify-items-end *:[grid-area:1/1]', className)}\n      style={{ minInlineSize: `var(--account-menu-room, ${DEFAULT_ROOM})`, ...style }}\n      {...props}\n    >\n      {/* The room: the Sign in button at its own label, invisible in every state, so the root is\n          as wide as the widest state in any font and any language. */}\n      <span data-slot=\"account-menu-room\" aria-hidden=\"true\" inert className={cn(SIGN_IN_CLASS, 'invisible')}>\n        {labels.signIn}\n      </span>\n      {state.status === 'unknown' ? (\n        <span\n          data-slot=\"account-menu-placeholder\"\n          aria-hidden=\"true\"\n          inert\n          className=\"invisible block h-control-sm min-w-full\"\n        />\n      ) : null}\n      {state.status === 'signed-out'\n        ? renderLink({\n            href: buildSignInHref(signInHref, here),\n            className: SIGN_IN_CLASS,\n            'data-slot': 'account-menu-sign-in',\n            children: labels.signIn,\n          })\n        : null}\n      {state.status === 'signed-in' ? (\n        <SignedIn\n          account={state.account}\n          labels={labels}\n          links={links}\n          renderLink={renderLink}\n          open={open}\n          onOpenChange={(next) => {\n            setOpen(next);\n            if (next) setFailed(false);\n          }}\n          pending={pending}\n          failed={failed}\n          onSignOut={signOut}\n          triggerRef={trigger}\n        />\n      ) : null}\n    </div>\n  );\n}\nAccountMenu.displayName = 'AccountMenu';\n\ninterface SignedInProps {\n  account: Account;\n  labels: AccountMenuLabels;\n  links: readonly AccountMenuLink[];\n  renderLink: NonNullable<AccountMenuProps['renderLink']>;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  pending: boolean;\n  failed: boolean;\n  onSignOut: () => void;\n  triggerRef: React.Ref<HTMLButtonElement>;\n}\n\nfunction SignedIn({\n  account,\n  labels,\n  links,\n  renderLink,\n  open,\n  onOpenChange,\n  pending,\n  failed,\n  onSignOut,\n  triggerRef,\n}: SignedInProps) {\n  const name = accountDisplayName(account, labels.fallbackName);\n  const email = account.email?.trim();\n  return (\n    <>\n      <DropdownMenu open={open} onOpenChange={onOpenChange}>\n        <DropdownMenuTrigger\n          ref={triggerRef}\n          data-slot=\"account-menu-trigger\"\n          aria-label={labels.menu(name)}\n          className=\"relative rounded-full focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background after:absolute after:-inset-1 after:rounded-full after:content-['']\"\n        >\n          <Avatar className=\"size-control\">\n            {account.imageUrl ? <AvatarImage src={account.imageUrl} alt=\"\" referrerPolicy=\"no-referrer\" /> : null}\n            <AvatarFallback aria-hidden=\"true\">{accountInitials(account)}</AvatarFallback>\n          </Avatar>\n        </DropdownMenuTrigger>\n        <DropdownMenuContent align=\"end\" className=\"max-w-[calc(100vw-2rem)] min-w-56\">\n          <DropdownMenuLabel data-slot=\"account-menu-header\">\n            <span dir=\"auto\" title={name} className=\"block truncate font-medium\">\n              {name}\n            </span>\n            {email ? (\n              <span dir=\"auto\" title={email} className=\"block truncate text-xs font-normal text-muted-foreground\">\n                {email}\n              </span>\n            ) : null}\n          </DropdownMenuLabel>\n          <DropdownMenuSeparator />\n          {links.map((link) => (\n            <MenuLink key={link.href} link={link} renderLink={renderLink} />\n          ))}\n          <DropdownMenuItem\n            data-slot=\"account-menu-sign-out\"\n            closeOnClick={false}\n            disabled={pending}\n            onClick={onSignOut}\n          >\n            {pending ? labels.signingOut : labels.signOut}\n          </DropdownMenuItem>\n        </DropdownMenuContent>\n      </DropdownMenu>\n      <VisuallyHidden role=\"status\" aria-live=\"polite\" data-slot=\"account-menu-live\">\n        {failed ? labels.signOutFailed : ''}\n      </VisuallyHidden>\n    </>\n  );\n}\n\nfunction MenuLink({ link, renderLink }: { link: AccountMenuLink; renderLink: NonNullable<AccountMenuProps['renderLink']> }) {\n  const content = (\n    <>\n      {link.icon}\n      {link.label}\n    </>\n  );\n  return (\n    <DropdownMenuItem data-slot=\"account-menu-link\" render={renderLink({ href: link.href, children: content })}>\n      {content}\n    </DropdownMenuItem>\n  );\n}\n\nexport { AccountMenu };\n"
    },
    {
      "path": "registry/interlace-ui/patterns/account-menu-model.ts",
      "target": "components/ui/patterns/account-menu-model.ts",
      "type": "registry:ui",
      "content": "export interface Account {\n  /** Opaque to the kit. Used as a React key and as `data-account-id`. */\n  id: string;\n  firstName?: string | null;\n  lastName?: string | null;\n  email?: string | null;\n  imageUrl?: string | null;\n}\n\nexport type AccountState =\n  | { status: 'unknown' }\n  | { status: 'signed-out' }\n  | { status: 'signed-in'; account: Account };\n\nexport type AccountEvent =\n  | { type: 'read'; account: Account | null }\n  | { type: 'change'; account: Account | null }\n  | { type: 'reset' };\n\nexport const DEFAULT_FALLBACK_NAME = 'Your account';\n\n/** The fake origin a path is resolved against. `.invalid` never resolves to a real host. */\nconst FAKE_ORIGIN = 'http://return.invalid';\nconst MAX_PATH = 2048;\n\n/** A path: `/`, then not `/` or `\\`, then no whitespace, no control character, no backslash. */\nconst SAFE_PATH = /^\\/(?![/\\\\])[^\\s\\\\\\x00-\\x1f\\x7f]*$/;\n\n/**\n * Only a path on this site comes back out; anything else is `fallback` (the app's own\n * constant, never checked). Never throws.\n */\nexport function safeReturnPath(next: unknown, fallback = '/'): string {\n  return typeof next === 'string' &&\n    next.length <= MAX_PATH &&\n    SAFE_PATH.test(next) &&\n    new URL(next, FAKE_ORIGIN).origin === FAKE_ORIGIN\n    ? next\n    : fallback;\n}\n\nconst present = (value: string | null | undefined): string => (value ?? '').trim();\n\n/** First name, else the start of the email, else `fallback`. Never an empty string. */\nexport function accountDisplayName(\n  account: Pick<Account, 'firstName' | 'email'> | null,\n  fallback: string = DEFAULT_FALLBACK_NAME,\n): string {\n  const first = present(account?.firstName);\n  if (first) return first;\n  const email = present(account?.email);\n  const at = email.indexOf('@');\n  const local = at < 0 ? email : email.slice(0, at);\n  return local.trim() || fallback;\n}\n\nfunction graphemes(text: string): string[] {\n  if (typeof Intl.Segmenter === 'function') {\n    return Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), (s) => s.segment);\n  }\n  return Array.from(text);\n}\n\nconst firstGrapheme = (text: string): string => graphemes(text)[0] ?? '';\n\n/**\n * Up to two letters, upper-cased: the first of the first name and the first of the last name; if\n * there is neither, the first of the email; if there is nothing, `?`. Scripts with no case\n * (Hebrew, Arabic, Han) come out unchanged.\n */\nexport function accountInitials(\n  account: Pick<Account, 'firstName' | 'lastName' | 'email'> | null,\n): string {\n  const names = [firstGrapheme(present(account?.firstName)), firstGrapheme(present(account?.lastName))].join('');\n  const letters = names || firstGrapheme(present(account?.email));\n  return letters ? letters.toLocaleUpperCase() : '?';\n}\n\n/** The path of an address: no query, no fragment, no trailing slash (the root becomes empty). */\nconst pagePath = (address: string): string => address.split(/[?#]/, 1)[0]!.replace(/\\/+$/, '');\n\n/**\n * The sign-in address with a safe `?next=`. `signIn` comes back unchanged when `here` is absent,\n * empty, the sign-in page itself (`/sign-in` and `/sign-in/` are one page) or not a path on this\n * site (it is left out, never encoded). `signIn` may already have a query; it must have no fragment.\n */\nexport function signInHref(signIn: string, here?: string | null): string {\n  if (!here || pagePath(here) === pagePath(signIn)) return signIn;\n  const next = safeReturnPath(here, '');\n  if (!next) return signIn;\n  return `${signIn}${signIn.includes('?') ? '&' : '?'}next=${encodeURIComponent(next)}`;\n}\n\nexport const UNKNOWN: AccountState = { status: 'unknown' };\nconst SIGNED_OUT: AccountState = { status: 'signed-out' };\n\nconst sameAccount = (a: Account, b: Account): boolean =>\n  a.id === b.id &&\n  a.firstName === b.firstName &&\n  a.lastName === b.lastName &&\n  a.email === b.email &&\n  a.imageUrl === b.imageUrl;\n\nconst settle = (state: AccountState, account: Account | null): AccountState => {\n  if (!account) return state.status === 'signed-out' ? state : SIGNED_OUT;\n  if (state.status === 'signed-in' && sameAccount(state.account, account)) return state;\n  return { status: 'signed-in', account };\n};\n\n/**\n * The state under `useAccount`. `read` is the first answer and counts only while nothing is\n * known: a late `read` never overwrites a newer `change`. `change` always counts. An equal\n * account returns the same object, so nothing re-renders. `reset` goes back to `unknown` (the\n * adapter was swapped for another).\n */\nexport function reduceAccount(state: AccountState, event: AccountEvent): AccountState {\n  if (event.type === 'reset') return UNKNOWN;\n  if (event.type === 'read' && state.status !== 'unknown') return state;\n  return settle(state, event.account);\n}\n\n/**\n * @interlace/ui — patterns/account-menu-model\n *\n * The pure half of `AccountMenu`: what to call a person, what to put in an avatar with no photo,\n * the sign-in address that carries the page they were on, the one check that decides whether an\n * address they come back to is on this site, and the reducer under `useAccount`. No DOM, no\n * `window`, no storage, no network: a server, a test and an agent can all use it.\n *\n * ## `safeReturnPath`\n *\n * A \"return to\" address (`?next=`) is the classic open redirect: the sign-in page sends the\n * person wherever the link says. Only a path on this site may come back out, for any input,\n * including the ones a browser rewrites. A browser deletes tabs and newlines from an address\n * before it reads it, so `/\\t/evil.com` is a path to a prefix check and `//evil.com` to the\n * browser. So the rule refuses what a browser would rewrite, and then asks the parser:\n *\n *   1. It is a string, 1 to 2048 characters.\n *   2. It starts with `/`, and the next character is not `/` or `\\`.\n *   3. No whitespace (any Unicode space, line separator or paragraph separator), no control\n *      character (C0 and DEL) and no backslash appears anywhere in it.\n *   4. Parsed with `new URL` against a fixed fake origin, it still has that origin.\n *\n * Anything else is the fallback. The function never throws.\n *\n * **An encoded slash is allowed.** `/%2F%2Fevil.com` is a path on this site: a browser does not\n * decode `%2F` before it resolves an address, so it can never become `//`. It is kept as given.\n * Whoever reads the path out of the address and decodes it again owns that second step, and must\n * run `safeReturnPath` on the decoded value too (\"use it on the reading side, not only when you\n * build the link\").\n *\n * The same rule as the hand-written `safeNext` a first consumer shipped and tested with 22 cases,\n * with one addition: the 2048 limit.\n * Step 4 cannot fail after steps 1 to 3 (it is defence in depth), so a mutation of it is an\n * equivalent mutant.\n *\n * ## Names\n *\n * `accountDisplayName` is what to greet someone by: first name, else the start of the email, else\n * a plain label. `accountInitials` is up to two letters for an avatar with no photo, counted in\n * grapheme clusters (`Intl.Segmenter` where the runtime has it, `Array.from` otherwise, which\n * can still cut a ZWJ emoji sequence in the middle), so an emoji, a letter with a combining mark\n * or a Hebrew or Han name is not cut in half.\n */\n"
    },
    {
      "path": "registry/interlace-ui/patterns/use-account.ts",
      "target": "components/ui/patterns/use-account.ts",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n/**\n * @interlace/ui — useAccount\n *\n * Turns the app's own sign-in service into the state `AccountMenu` shows: `unknown`, then\n * `signed-out` or `signed-in`. The service is the app's (Supabase, Auth.js, Clerk, a cookie);\n * nothing here names one. The app writes an adapter in about ten lines:\n *\n *   const adapter: AccountAdapter = {\n *     read: async () => toAccount(await service.getSession()),\n *     subscribe: (onChange) => service.onChange((session) => onChange(toAccount(session))),\n *   };\n *\n * `read` is called once on mount (it may return a promise); `subscribe`, when present, reports\n * later changes (a sign-in, a sign-out, a better profile) and returns the unsubscribe. The hook\n * holds the state and nothing else: it never reads or writes a session, a cookie or a storage key.\n *\n * - The first render is `unknown`, on the server and in the browser alike, so the markup matches\n *   and nothing flashes the wrong state.\n * - A `read` that fails is `signed-out`. An app that wants the failure reported wraps its adapter.\n * - Unmounting unsubscribes, and an answer that arrives after it is ignored.\n * - A later `read` never overwrites a newer change (see `reduceAccount`).\n * - Keep the adapter's identity stable (module scope or `useMemo`): a new one means a new\n *   subscription and a fresh `unknown`.\n * - `useAccount(null)` stays `unknown`, for an app whose accounts are switched off.\n */\n\nimport { reduceAccount, UNKNOWN, type Account, type AccountState } from '@/components/ui/patterns/account-menu-model';\n\nexport interface AccountAdapter {\n  /** The current account or null. Called once on mount. */\n  read(): Account | null | Promise<Account | null>;\n  /** Later changes. Returns the unsubscribe. */\n  subscribe?(onChange: (account: Account | null) => void): () => void;\n}\n\nexport function useAccount(adapter: AccountAdapter | null): AccountState {\n  const [state, dispatch] = React.useReducer(reduceAccount, UNKNOWN);\n\n  React.useEffect(() => {\n    dispatch({ type: 'reset' });\n    if (!adapter) return undefined;\n    let live = true;\n    const unsubscribe = adapter.subscribe?.((account) => {\n      if (live) dispatch({ type: 'change', account });\n    });\n    new Promise<Account | null>((resolve) => resolve(adapter.read())).then(\n      (account) => {\n        if (live) dispatch({ type: 'read', account });\n      },\n      () => {\n        if (live) dispatch({ type: 'read', account: null });\n      },\n    );\n    return () => {\n      live = false;\n      unsubscribe?.();\n    };\n  }, [adapter]);\n\n  return state;\n}\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.2",
    "since": "2.3.0"
  },
  "docs": "## @interlace/account-menu\n\nInstalled to `components/ui/patterns/account-menu.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/account-menu';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/account-menu\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
