{"slug":"combobox","name":"Combobox","description":"Searchable combobox with a morphing portal, grouped filtering, keyboard navigation, and controlled or uncontrolled state.","category":"motion","source_url":"https://beui.dev/r/combobox/raw","detail_url":"https://beui.dev/r/combobox","raw_url":"https://beui.dev/r/combobox/raw","page_url":"https://beui.dev/components/motion/combobox","markdown_url":"https://beui.dev/components/motion/combobox.md","published_at":"2026-08-11","updated_at":"2026-11-28","dependencies":["clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["./combobox/content","./combobox/context","./combobox/list","./combobox/messages","./combobox/trigger","./context","./engine","./listbox-panel","./messages","./use-active-option","./use-filtered-options","@/components/motion/combobox","@/components/motion/popover-position","@/lib/audio-context","@/lib/ease","@/lib/hooks/use-dismiss","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/sound","@/lib/sounds/close","@/lib/sounds/engine","@/lib/sounds/open","@/lib/sounds/select","@/lib/utils"],"install_slugs":["combobox"],"requires_theme":true,"props":[{"displayName":"ComboboxContent","props":[{"name":"side","type":"\"top\" | \"bottom\"","required":false,"defaultValue":"bottom","description":"Preferred side of the field to open on. Default: \"bottom\""},{"name":"align","type":"\"start\" | \"center\" | \"end\"","required":false,"defaultValue":"start","description":"Horizontal alignment against the field. Default: \"start\""},{"name":"sideOffset","type":"number","required":false,"defaultValue":"6","description":"Gap between the field and the panel, in px. Default: 6"},{"name":"avoidCollisions","type":"boolean","required":false,"defaultValue":"true","description":"Flip to the other side when there is more room there. Default: true"},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the panel element."}]},{"displayName":"Combobox","props":[{"name":"value","type":"string","required":false,"defaultValue":null,"description":"The selected value, for controlled use."},{"name":"defaultValue","type":"string","required":false,"defaultValue":null,"description":"The initial value when uncontrolled."},{"name":"onValueChange","type":"((value: string) => void)","required":false,"defaultValue":null,"description":"Called with the option value when the user picks an option."},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the list is open, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"false","description":"Whether the list starts open when uncontrolled. Default: false"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the next open state when the list opens or closes."},{"name":"query","type":"string","required":false,"defaultValue":null,"description":"The search text, for controlled use."},{"name":"defaultQuery","type":"string","required":false,"defaultValue":"","description":"The initial search text when uncontrolled. Default: \"\""},{"name":"onQueryChange","type":"((query: string) => void)","required":false,"defaultValue":null,"description":"Called with the new text when the query changes. It clears on close."},{"name":"filter","type":"OptionFilter","required":false,"defaultValue":"(value, query, keywords) => {\n  const needle = query.trim().toLocaleLowerCase();\n  if (!needle) return true;\n\n  const haystack = [value, ...keywords].join(\" \").toLocaleLowerCase();\n  let queryIndex = 0;\n  for (const character of haystack) {\n    if (character === needle[queryIndex]) queryIndex += 1;\n    if (queryIndex === needle.length) return true;\n  }\n  return false;\n}","description":"Return true to show an option for the query. Default: fuzzy match on value and keywords"},{"name":"disabled","type":"boolean","required":false,"defaultValue":"false","description":"Disables the input and blocks opening the list. Default: false"},{"name":"sound","type":"boolean","required":false,"defaultValue":"false","description":"Play open and close swishes and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"labels","type":"Partial<{ valuePlaceholder: string; inputLabel: string; inputPlaceholder: string; listLabel: string; empty: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]},{"displayName":"ComboboxEmpty","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the empty message."}]},{"displayName":"ComboboxGroup","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the group element."}]},{"displayName":"ComboboxItem","props":[{"name":"value","type":"string","required":true,"defaultValue":null,"description":"Unique value set on the combobox when this item is picked."},{"name":"textValue","type":"string","required":false,"defaultValue":null,"description":"Text used for search and the selected label. Default: string children, else `value`"},{"name":"keywords","type":"string[]","required":false,"defaultValue":"[]","description":"Extra search terms that match this item."},{"name":"disabled","type":"boolean","required":false,"defaultValue":"false","description":"Dims the item and stops it from being picked. Default: false"},{"name":"onSelect","type":"((value: string) => void)","required":false,"defaultValue":null,"description":"Called with the item's value when it is picked."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the item button."}]},{"displayName":"ComboboxLabel","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the label element."}]},{"displayName":"ComboboxList","props":[{"name":"ariaLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the list. Default: \"Options\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the scrolling list element."}]},{"displayName":"ComboboxSeparator","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the separator line."}]},{"displayName":"ComboboxInput","props":[{"name":"ref","type":"Ref<HTMLInputElement>","required":false,"defaultValue":null,"description":"Ref to the underlying input element."},{"name":"wrapperClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the wrapper around the search icon and input."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"ComboboxTrigger","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the trigger field."}]},{"displayName":"ComboboxValue","props":[{"name":"placeholder","type":"ReactNode","required":false,"defaultValue":null,"description":"Shown while nothing is selected. Default: \"Select an option\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the value text."}]}],"types":[],"files":[{"path":"components/motion/combobox.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/combobox\n\nexport {\n  ComboboxContent,\n  type ComboboxContentProps,\n} from \"./combobox/content\";\nexport {\n  Combobox,\n  type ComboboxFilter,\n  type ComboboxProps,\n} from \"./combobox/context\";\nexport {\n  ComboboxEmpty,\n  type ComboboxEmptyProps,\n  ComboboxGroup,\n  type ComboboxGroupProps,\n  ComboboxItem,\n  type ComboboxItemProps,\n  ComboboxLabel,\n  type ComboboxLabelProps,\n  ComboboxList,\n  type ComboboxListProps,\n  ComboboxSeparator,\n  type ComboboxSeparatorProps,\n} from \"./combobox/list\";\nexport {\n  type ComboboxMessages,\n  comboboxMessages,\n} from \"./combobox/messages\";\nexport {\n  ComboboxInput,\n  type ComboboxInputProps,\n  ComboboxTrigger,\n  type ComboboxTriggerProps,\n  ComboboxValue,\n  type ComboboxValueProps,\n} from \"./combobox/trigger\";\n"},{"path":"components/motion/combobox/content.tsx","type":"util","content":"\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { useComboboxContext } from \"./context\";\nimport { ListboxPanel, type ListboxPanelPlacement } from \"./listbox-panel\";\n\nexport interface ComboboxContentProps extends ListboxPanelPlacement {\n  children: ReactNode;\n}\n\nexport function ComboboxContent({\n  children,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n  avoidCollisions = true,\n  className,\n}: ComboboxContentProps) {\n  const context = useComboboxContext(\"ComboboxContent\");\n  return (\n    <ListboxPanel\n      name=\"combobox\"\n      open={context.open}\n      reduce={context.reduce}\n      triggerRef={context.triggerRef}\n      contentRef={context.contentRef}\n      side={side}\n      align={align}\n      sideOffset={sideOffset}\n      avoidCollisions={avoidCollisions}\n      className={className}\n    >\n      {children}\n    </ListboxPanel>\n  );\n}\n"},{"path":"components/motion/combobox/context.tsx","type":"util","content":"\"use client\";\n\nimport { useReducedMotion } from \"motion/react\";\nimport {\n  createContext,\n  type MutableRefObject,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { useSound } from \"@/lib/sound\";\nimport { closeSound } from \"@/lib/sounds/close\";\nimport { openSound } from \"@/lib/sounds/open\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  type ComboboxMessages,\n  type ComboboxTranslate,\n  comboboxMessages,\n} from \"./messages\";\nimport {\n  defaultOptionFilter,\n  type OptionFilter,\n  type RegisteredItem,\n  useFilteredOptions,\n} from \"./use-filtered-options\";\n\nexport type { RegisteredItem };\n\nexport type ComboboxFilter = OptionFilter;\n\nexport type ComboboxContextValue = {\n  open: boolean;\n  setOpen: (open: boolean, restoreFocus?: boolean) => void;\n  value: string | undefined;\n  select: (value: string) => void;\n  query: string;\n  setQuery: (query: string) => void;\n  /** The option the list is currently pointing at, resolved during render. */\n  activeValue: string | null;\n  /**\n   * Records where the pointer or keyboard moved to. The recorded value is\n   * dropped when the query or the result set changes, so it does not always\n   * survive to the next `activeValue`.\n   */\n  setActiveValue: (value: string | null) => void;\n  moveActive: (direction: 1 | -1 | \"first\" | \"last\") => void;\n  selectActive: () => void;\n  registerItem: (item: RegisteredItem) => void;\n  unregisterItem: (value: string) => void;\n  labelFor: (value: string | undefined) => string | undefined;\n  isVisible: (value: string) => boolean;\n  hasVisibleItems: (groupId: string) => boolean;\n  visibleCount: number;\n  activeItemId: string | undefined;\n  triggerId: string;\n  listId: string;\n  inputId: string;\n  disabled: boolean;\n  reduce: boolean;\n  triggerRef: MutableRefObject<HTMLDivElement | null>;\n  contentRef: MutableRefObject<HTMLDivElement | null>;\n  inputRef: MutableRefObject<HTMLInputElement | null>;\n  activeLayoutId: string;\n  t: ComboboxTranslate;\n};\n\nexport const ComboboxContext = createContext<ComboboxContextValue | null>(null);\nexport const ComboboxGroupContext = createContext<string | null>(null);\n\nexport function useComboboxContext(component: string) {\n  const context = useContext(ComboboxContext);\n  if (!context) throw new Error(`${component} must be used within <Combobox>`);\n  return context;\n}\n\nexport interface ComboboxProps {\n  children: ReactNode;\n  /** The selected value, for controlled use. */\n  value?: string;\n  /** The initial value when uncontrolled. */\n  defaultValue?: string;\n  /** Called with the option value when the user picks an option. */\n  onValueChange?: (value: string) => void;\n  /** Whether the list is open, for controlled use. */\n  open?: boolean;\n  /** Whether the list starts open when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the next open state when the list opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** The search text, for controlled use. */\n  query?: string;\n  /** The initial search text when uncontrolled. Default: \"\" */\n  defaultQuery?: string;\n  /** Called with the new text when the query changes. It clears on close. */\n  onQueryChange?: (query: string) => void;\n  /** Return true to show an option for the query. Default: fuzzy match on value and keywords */\n  filter?: ComboboxFilter;\n  /** Disables the input and blocks opening the list. Default: false */\n  disabled?: boolean;\n  /** Play open and close swishes and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<ComboboxMessages>;\n}\n\nexport function Combobox({\n  children,\n  value: controlledValue,\n  defaultValue,\n  onValueChange,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  query: controlledQuery,\n  defaultQuery = \"\",\n  onQueryChange,\n  filter = defaultOptionFilter,\n  disabled = false,\n  sound = false,\n  className,\n  labels,\n}: ComboboxProps) {\n  const t = useMessages(\"combobox\", comboboxMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const triggerRef = useRef<HTMLDivElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const [internalValue, setInternalValue] = useState(defaultValue);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [internalQuery, setInternalQuery] = useState(defaultQuery);\n\n  const valueControlled = controlledValue !== undefined;\n  const openControlled = controlledOpen !== undefined;\n  const queryControlled = controlledQuery !== undefined;\n  const value = valueControlled ? controlledValue : internalValue;\n  const open = openControlled ? controlledOpen : internalOpen;\n  const query = queryControlled ? controlledQuery : internalQuery;\n\n  const updateQuery = useCallback(\n    (next: string) => {\n      if (!queryControlled) setInternalQuery(next);\n      onQueryChange?.(next);\n    },\n    [onQueryChange, queryControlled],\n  );\n\n  const playOpen = useSound(openSound, { enabled: sound });\n  const playClose = useSound(closeSound, { enabled: sound });\n  const playSelect = useSound(selectSound, { enabled: sound });\n\n  // `quiet` skips the close sweep when a pick already made its own sound.\n  const updateOpen = useCallback(\n    (next: boolean, restoreFocus = false, quiet = false) => {\n      if (disabled && next) return;\n      if (next !== open) {\n        if (!quiet) {\n          if (next) playOpen();\n          else playClose();\n        }\n        if (!openControlled) setInternalOpen(next);\n        onOpenChange?.(next);\n      }\n      if (!next) updateQuery(\"\");\n      if (restoreFocus)\n        requestAnimationFrame(() =>\n          inputRef.current?.focus({ preventScroll: true }),\n        );\n    },\n    [disabled, onOpenChange, open, openControlled, updateQuery, playOpen, playClose],\n  );\n\n  const {\n    items,\n    registerItem,\n    unregisterItem,\n    listQuery,\n    visibleValues,\n    visibleGroupIds,\n    visibleCount,\n    activeValue,\n    setActiveValue,\n    moveActive,\n    activeItemId,\n  } = useFilteredOptions({ open, query, value, filter });\n\n  const select = useCallback(\n    (next: string) => {\n      if (items.get(next)?.disabled) return;\n      playSelect();\n      if (!valueControlled) setInternalValue(next);\n      onValueChange?.(next);\n      updateOpen(false, true, true);\n    },\n    [items, onValueChange, updateOpen, valueControlled, playSelect],\n  );\n\n  const selectActive = useCallback(() => {\n    if (activeValue) select(activeValue);\n  }, [activeValue, select]);\n\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() =>\n      inputRef.current?.focus({ preventScroll: true }),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const insideContent = useCallback(\n    (target: Element) => Boolean(contentRef.current?.contains(target)),\n    [],\n  );\n  const dismiss = useCallback(\n    (reason: DismissReason) => updateOpen(false, reason === \"escape\"),\n    [updateOpen],\n  );\n  useDismiss(open, dismiss, rootRef, { focusOutside: true, ignore: insideContent });\n\n  const context = useMemo<ComboboxContextValue>(\n    () => ({\n      open,\n      setOpen: updateOpen,\n      value,\n      select,\n      query,\n      setQuery: updateQuery,\n      activeValue,\n      setActiveValue,\n      moveActive,\n      selectActive,\n      registerItem,\n      unregisterItem,\n      labelFor: (itemValue) =>\n        itemValue === undefined ? undefined : items.get(itemValue)?.label,\n      isVisible: (itemValue) => !listQuery.trim() || visibleValues.has(itemValue),\n      hasVisibleItems: (groupId) => visibleGroupIds.has(groupId),\n      visibleCount,\n      activeItemId,\n      triggerId: `${baseId}-trigger`,\n      listId: `${baseId}-list`,\n      inputId: `${baseId}-input`,\n      disabled,\n      reduce,\n      triggerRef,\n      contentRef,\n      inputRef,\n      activeLayoutId: `${baseId}-active`,\n      t,\n    }),\n    [\n      activeItemId,\n      activeValue,\n      baseId,\n      disabled,\n      items,\n      listQuery,\n      moveActive,\n      open,\n      query,\n      reduce,\n      registerItem,\n      select,\n      selectActive,\n      setActiveValue,\n      t,\n      unregisterItem,\n      updateOpen,\n      updateQuery,\n      value,\n      visibleCount,\n      visibleGroupIds,\n      visibleValues,\n    ],\n  );\n\n  return (\n    <ComboboxContext.Provider value={context}>\n      <div ref={rootRef} className={cn(\"relative w-full\", className)}>\n        {children}\n      </div>\n    </ComboboxContext.Provider>\n  );\n}\n"},{"path":"components/motion/combobox/list.tsx","type":"util","content":"\"use client\";\n\nimport { Check } from \"lucide-react\";\nimport { motion } from \"motion/react\";\nimport {\n  type ReactNode,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport { EASE_OUT, SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { ComboboxGroupContext, useComboboxContext } from \"./context\";\n\nexport interface ComboboxListProps {\n  children: ReactNode;\n  /** Accessible name for the list. Default: \"Options\" */\n  ariaLabel?: string;\n  /** Classes merged onto the scrolling list element. */\n  className?: string;\n}\n\nexport function ComboboxList({\n  children,\n  ariaLabel,\n  className,\n}: ComboboxListProps) {\n  const context = useComboboxContext(\"ComboboxList\");\n  return (\n    <div\n      id={context.listId}\n      role=\"listbox\"\n      aria-label={ariaLabel ?? context.t(\"listLabel\")}\n      className={cn(\n        \"relative isolate max-h-64 overflow-y-auto overscroll-contain p-2 [-ms-overflow-style:none] scrollbar-none [&::-webkit-scrollbar]:hidden\",\n        className,\n      )}>\n      {children}\n    </div>\n  );\n}\n\nexport interface ComboboxGroupProps {\n  children: ReactNode;\n  /** Classes merged onto the group element. */\n  className?: string;\n}\n\nexport function ComboboxGroup({ children, className }: ComboboxGroupProps) {\n  const context = useComboboxContext(\"ComboboxGroup\");\n  const groupId = useId();\n  return (\n    <ComboboxGroupContext.Provider value={groupId}>\n      <fieldset\n        hidden={!context.hasVisibleItems(groupId)}\n        className={cn(\"m-0 min-w-0 border-0 p-0 py-0.5\", className)}>\n        {children}\n      </fieldset>\n    </ComboboxGroupContext.Provider>\n  );\n}\n\nexport interface ComboboxLabelProps {\n  children: ReactNode;\n  /** Classes merged onto the label element. */\n  className?: string;\n}\n\nexport function ComboboxLabel({ children, className }: ComboboxLabelProps) {\n  const groupId = useContext(ComboboxGroupContext);\n  const labelClassName = cn(\n    \"w-full px-3 py-1.5 text-[11px] font-medium uppercase tracking-[0.12em] text-muted-foreground\",\n    className,\n  );\n  return groupId ? (\n    <legend className={labelClassName}>{children}</legend>\n  ) : (\n    <div className={labelClassName}>{children}</div>\n  );\n}\n\nexport interface ComboboxItemProps {\n  /** Unique value set on the combobox when this item is picked. */\n  value: string;\n  children: ReactNode;\n  /** Text used for search and the selected label. Default: string children, else `value` */\n  textValue?: string;\n  /** Extra search terms that match this item. */\n  keywords?: string[];\n  /** Dims the item and stops it from being picked. Default: false */\n  disabled?: boolean;\n  /** Called with the item's value when it is picked. */\n  onSelect?: (value: string) => void;\n  /** Classes merged onto the item button. */\n  className?: string;\n}\n\nexport function ComboboxItem({\n  value,\n  children,\n  textValue,\n  keywords = [],\n  disabled = false,\n  onSelect,\n  className,\n}: ComboboxItemProps) {\n  const context = useComboboxContext(\"ComboboxItem\");\n  const groupId = useContext(ComboboxGroupContext);\n  const id = useId();\n  const itemRef = useRef<HTMLButtonElement>(null);\n  const label = textValue ?? (typeof children === \"string\" ? children : value);\n  const visible = context.isVisible(value);\n  const active = context.activeValue === value;\n  const selected = context.value === value;\n  const keywordKey = keywords.join(\"\\u0000\");\n  const normalizedKeywords = useMemo(\n    () => (keywordKey ? keywordKey.split(\"\\u0000\") : []),\n    [keywordKey],\n  );\n  const { registerItem, unregisterItem } = context;\n\n  useLayoutEffect(() => {\n    registerItem({\n      value,\n      label,\n      keywords: normalizedKeywords,\n      disabled,\n      groupId,\n      id,\n      ref: itemRef,\n    });\n    return () => unregisterItem(value);\n  }, [\n    disabled,\n    groupId,\n    id,\n    label,\n    normalizedKeywords,\n    registerItem,\n    unregisterItem,\n    value,\n  ]);\n\n  if (!visible) return null;\n\n  return (\n    <button\n      ref={itemRef}\n      id={id}\n      type=\"button\"\n      role=\"option\"\n      aria-selected={selected}\n      disabled={disabled}\n      tabIndex={-1}\n      data-combobox-item=\"\"\n      data-active={active || undefined}\n      data-selected={selected || undefined}\n      onPointerMove={() => {\n        if (!disabled) context.setActiveValue(value);\n      }}\n      onPointerDown={(event) => event.preventDefault()}\n      onClick={() => {\n        if (disabled) return;\n        onSelect?.(value);\n        context.select(value);\n      }}\n      className={cn(\n        \"relative flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-left text-sm outline-none transition-colors duration-150\",\n        active ? \"text-foreground\" : \"text-muted-foreground\",\n        \"disabled:pointer-events-none disabled:opacity-45\",\n        className,\n      )}>\n      {active ? (\n        <motion.span\n          aria-hidden\n          layoutId={context.activeLayoutId}\n          className=\"absolute inset-0 -z-10 rounded-lg bg-muted\"\n          transition={context.reduce ? { duration: 0 } : SPRING_LAYOUT}\n        />\n      ) : null}\n      <span className=\"min-w-0 flex-1\">{children}</span>\n      <motion.span\n        aria-hidden\n        initial={false}\n        animate={{\n          opacity: selected ? 1 : 0,\n          transform: selected ? \"scale(1)\" : \"scale(0.82)\",\n        }}\n        transition={\n          context.reduce ? { duration: 0 } : { duration: 0.14, ease: EASE_OUT }\n        }\n        className=\"grid size-5 shrink-0 place-items-center text-foreground\">\n        <Check className=\"size-4\" />\n      </motion.span>\n    </button>\n  );\n}\n\nexport interface ComboboxEmptyProps {\n  children?: ReactNode;\n  /** Classes merged onto the empty message. */\n  className?: string;\n}\n\nexport function ComboboxEmpty({\n  children,\n  className,\n}: ComboboxEmptyProps) {\n  const context = useComboboxContext(\"ComboboxEmpty\");\n  if (context.visibleCount > 0) return null;\n  return (\n    <div\n      role=\"status\"\n      className={cn(\n        \"px-3 py-8 text-center text-sm text-muted-foreground\",\n        className,\n      )}>\n      {children ?? context.t(\"empty\")}\n    </div>\n  );\n}\n\nexport interface ComboboxSeparatorProps {\n  /** Classes merged onto the separator line. */\n  className?: string;\n}\n\nexport function ComboboxSeparator({ className }: ComboboxSeparatorProps) {\n  return (\n    <div aria-hidden className={cn(\"-mx-1 my-1 h-px bg-border\", className)} />\n  );\n}\n"},{"path":"components/motion/combobox/messages.ts","type":"util","content":"import type { useMessages } from \"@/lib/i18n\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const comboboxMessages = {\n  valuePlaceholder: \"Select an option\",\n  inputLabel: \"Search options\",\n  inputPlaceholder: \"Search…\",\n  listLabel: \"Options\",\n  empty: \"No options found.\",\n};\n\nexport type ComboboxMessages = typeof comboboxMessages;\n\n/** The resolved translator the root hands to its parts. */\nexport type ComboboxTranslate = ReturnType<typeof useMessages<ComboboxMessages>>;\n"},{"path":"components/motion/combobox/trigger.tsx","type":"util","content":"\"use client\";\n\nimport { ChevronsUpDown, Search } from \"lucide-react\";\nimport type {\n  InputHTMLAttributes,\n  KeyboardEvent as ReactKeyboardEvent,\n  ReactNode,\n  Ref,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { mergeRefs } from \"@/lib/merge-refs\";\nimport { useComboboxContext } from \"./context\";\n\nexport interface ComboboxTriggerProps {\n  children: ReactNode;\n  /** Classes merged onto the trigger field. */\n  className?: string;\n}\n\nexport function ComboboxTrigger({ children, className }: ComboboxTriggerProps) {\n  const context = useComboboxContext(\"ComboboxTrigger\");\n\n  return (\n    <div\n      ref={context.triggerRef}\n      id={context.triggerId}\n      data-state={context.open ? \"open\" : \"closed\"}\n      onPointerDown={(event) => {\n        if (context.disabled || event.target === context.inputRef.current) return;\n        event.preventDefault();\n        context.inputRef.current?.focus({ preventScroll: true });\n        context.setOpen(true);\n      }}\n      className={cn(\n        \"relative z-20 flex h-10 w-full min-w-52 cursor-text items-center justify-between gap-3 rounded-full border border-border bg-transparent px-4 text-sm text-foreground transition-[border-color] hover:border-(--color-border-strong)\",\n        \"focus-within:ring-2 focus-within:ring-foreground/20\",\n        context.disabled && \"pointer-events-none opacity-50\",\n        className,\n      )}\n    >\n      <span className=\"min-w-0 flex-1 text-left\">{children}</span>\n      <span aria-hidden className=\"shrink-0 text-muted-foreground\">\n        <ChevronsUpDown className=\"size-4\" />\n      </span>\n    </div>\n  );\n}\n\nexport interface ComboboxValueProps {\n  /** Shown while nothing is selected. Default: \"Select an option\" */\n  placeholder?: ReactNode;\n  children?:\n    | ReactNode\n    | ((value: string | undefined, label: string | undefined) => ReactNode);\n  /** Classes merged onto the value text. */\n  className?: string;\n}\n\nexport function ComboboxValue({\n  placeholder,\n  children,\n  className,\n}: ComboboxValueProps) {\n  const context = useComboboxContext(\"ComboboxValue\");\n  const label = context.labelFor(context.value);\n  const content =\n    typeof children === \"function\"\n      ? children(context.value, label)\n      : children ?? label ?? placeholder ?? context.t(\"valuePlaceholder\");\n\n  return (\n    <span\n      className={cn(\n        \"block truncate\",\n        context.value === undefined\n          ? \"text-muted-foreground\"\n          : \"text-foreground\",\n        className,\n      )}\n    >\n      {content}\n    </span>\n  );\n}\n\nexport interface ComboboxInputProps\n  extends Omit<\n    InputHTMLAttributes<HTMLInputElement>,\n    \"defaultValue\" | \"value\"\n  > {\n  /** Ref to the underlying input element. */\n  ref?: Ref<HTMLInputElement>;\n  /** Classes merged onto the wrapper around the search icon and input. */\n  wrapperClassName?: string;\n}\n\nexport function ComboboxInput({\n  ref,\n  className,\n  wrapperClassName,\n  \"aria-label\": ariaLabel,\n  onChange,\n  onClick,\n  onFocus,\n  onKeyDown,\n  onPointerDown,\n  placeholder,\n  ...props\n}: ComboboxInputProps) {\n  const context = useComboboxContext(\"ComboboxInput\");\n  const selectedLabel = context.labelFor(context.value);\n\n  const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      // Opening is the whole action. While closed the list is still filtering\n      // by the query the last session left, so a step taken here would be\n      // measured against rows the next render replaces - and stamped with a\n      // query it no longer has, which discards it. Open onto the selection,\n      // and let the next key step through the list the user can see.\n      if (!context.open) {\n        context.setOpen(true);\n        return;\n      }\n      context.moveActive(event.key === \"ArrowDown\" ? 1 : -1);\n    } else if (event.key === \"Home\" && context.open) {\n      event.preventDefault();\n      context.moveActive(\"first\");\n    } else if (event.key === \"End\" && context.open) {\n      event.preventDefault();\n      context.moveActive(\"last\");\n    } else if (event.key === \"Enter\") {\n      if (event.nativeEvent.isComposing || event.keyCode === 229) return;\n      event.preventDefault();\n      if (context.open) context.selectActive();\n      else context.setOpen(true);\n    } else if (event.key === \"Escape\" && context.open) {\n      event.preventDefault();\n      context.setOpen(false, true);\n    }\n  };\n\n  return (\n    <div\n      className={cn(\n        \"flex min-w-0 flex-1 items-center gap-2\",\n        wrapperClassName,\n      )}\n    >\n      <Search aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n      <input\n        {...props}\n        ref={mergeRefs(ref, context.inputRef)}\n        id={context.inputId}\n        role=\"combobox\"\n        aria-label={ariaLabel ?? context.t(\"inputLabel\")}\n        aria-autocomplete=\"list\"\n        aria-expanded={context.open}\n        aria-controls={context.listId}\n        aria-activedescendant={\n          context.open ? context.activeItemId : undefined\n        }\n        autoComplete=\"off\"\n        disabled={context.disabled}\n        value={context.open ? context.query : (selectedLabel ?? \"\")}\n        placeholder={placeholder ?? context.t(\"inputPlaceholder\")}\n        onPointerDown={(event) => {\n          onPointerDown?.(event);\n          if (event.defaultPrevented || context.open) return;\n          event.preventDefault();\n          context.inputRef.current?.focus({ preventScroll: true });\n          context.setOpen(true);\n        }}\n        onFocus={(event) => {\n          context.setOpen(true);\n          onFocus?.(event);\n        }}\n        onClick={(event) => {\n          context.setOpen(true);\n          onClick?.(event);\n        }}\n        onChange={(event) => {\n          context.setOpen(true);\n          context.setQuery(event.target.value);\n          onChange?.(event);\n        }}\n        onKeyDown={handleKeyDown}\n        className={cn(\n          \"h-10 min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\",\n          className,\n        )}\n      />\n    </div>\n  );\n}\n"},{"path":"components/motion/combobox/listbox-panel.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport {\n  type CSSProperties,\n  type ReactNode,\n  type RefObject,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { SPRING_MORPH } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ListboxPanelSide = \"top\" | \"bottom\";\nexport type ListboxPanelAlign = \"start\" | \"center\" | \"end\";\n\nconst VIEWPORT_PADDING = 8;\n\nexport interface ListboxPanelPlacement {\n  /** Preferred side of the field to open on. Default: \"bottom\" */\n  side?: ListboxPanelSide;\n  /** Horizontal alignment against the field. Default: \"start\" */\n  align?: ListboxPanelAlign;\n  /** Gap between the field and the panel, in px. Default: 6 */\n  sideOffset?: number;\n  /** Flip to the other side when there is more room there. Default: true */\n  avoidCollisions?: boolean;\n  /** Classes merged onto the panel element. */\n  className?: string;\n}\n\n/**\n * The portaled panel Combobox and Multi Select open into: anchored to the\n * field, flipped to the side with room, and revealed from the field's edge on\n * one spring. Each component passes its own open state and refs, and `name` keeps\n * its `data-<name>-content` attribute and `--<name>-trigger-width` variable.\n */\nexport function ListboxPanel({\n  name,\n  open,\n  reduce,\n  triggerRef,\n  contentRef,\n  children,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n  avoidCollisions = true,\n  className,\n}: ListboxPanelPlacement & {\n  name: \"combobox\" | \"multi-select\";\n  open: boolean;\n  reduce: boolean;\n  triggerRef: RefObject<HTMLDivElement | null>;\n  contentRef: RefObject<HTMLDivElement | null>;\n  children: ReactNode;\n}) {\n  const measureRef = useRef<HTMLDivElement>(null);\n  const [portalReady, setPortalReady] = useState(false);\n  const [actualSide, setActualSide] = useState<ListboxPanelSide>(side);\n  const [morphReady, setMorphReady] = useState(false);\n  // Fully closed: the close animation has finished, or nothing has opened yet.\n  const [settledClosed, setSettledClosed] = useState(!open);\n  if (open && settledClosed) setSettledClosed(false);\n  const layout = usePopoverPortalPosition(triggerRef, measureRef, portalReady);\n\n  useEffect(() => setPortalReady(true), []);\n  useLayoutEffect(() => {\n    if (!portalReady) return;\n    const readyFrame = requestAnimationFrame(() => setMorphReady(true));\n    return () => cancelAnimationFrame(readyFrame);\n  }, [portalReady]);\n\n  useLayoutEffect(() => {\n    // Preserve the resolved side during exit, so top panels close upward. Once\n    // closed it follows the field again, so the next reveal starts from the\n    // edge the panel will open on.\n    if (!layout || (!open && !settledClosed)) return;\n    if (!avoidCollisions) {\n      setActualSide(side);\n      return;\n    }\n    const below = window.innerHeight - (layout.trigger.top + layout.trigger.height);\n    const above = layout.trigger.top;\n    if (side === \"bottom\" && below < layout.content.height + sideOffset && above > below)\n      setActualSide(\"top\");\n    else if (side === \"top\" && above < layout.content.height + sideOffset && below > above)\n      setActualSide(\"bottom\");\n    else setActualSide(side);\n  }, [avoidCollisions, open, settledClosed, layout, side, sideOffset]);\n\n  if (!portalReady) return null;\n\n  const triggerLeft = layout?.trigger.left ?? 0;\n  const triggerWidth = layout?.trigger.width ?? 0;\n  const contentWidth = layout?.content.width ?? triggerWidth;\n  const desiredLeft =\n    align === \"end\"\n      ? triggerLeft + triggerWidth - contentWidth\n      : align === \"center\"\n        ? triggerLeft + (triggerWidth - contentWidth) / 2\n        : triggerLeft;\n  const maxLeft = Math.max(VIEWPORT_PADDING, window.innerWidth - contentWidth - VIEWPORT_PADDING);\n  const left = Math.min(Math.max(desiredLeft, VIEWPORT_PADDING), maxLeft);\n  const transition = reduce || !morphReady ? { duration: 0 } : SPRING_MORPH;\n  // Revealed from the field's edge by a clip, so the panel keeps its size and\n  // nothing reflows while it opens. Percentages throughout, so motion can\n  // interpolate every edge.\n  const clipClosed =\n    actualSide === \"bottom\" ? \"inset(0% 0% 100% 0% round 16px)\" : \"inset(100% 0% 0% 0% round 16px)\";\n  const clipOpen = \"inset(0% 0% 0% 0% round 16px)\";\n\n  return createPortal(\n    <motion.div\n      ref={contentRef}\n      {...{ [`data-${name}-content`]: \"\" }}\n      data-side={actualSide}\n      aria-hidden={!open}\n      inert={!open}\n      initial={false}\n      animate={{\n        clipPath: open ? clipOpen : clipClosed,\n        opacity: open ? 1 : 0,\n        y: open ? (actualSide === \"bottom\" ? sideOffset : -sideOffset) : 0,\n      }}\n      transition={transition}\n      onAnimationComplete={() => {\n        if (!open) setSettledClosed(true);\n      }}\n      style={\n        {\n          left,\n          top:\n            actualSide === \"bottom\" && layout ? layout.trigger.top + layout.trigger.height : undefined,\n          bottom: actualSide === \"top\" && layout ? window.innerHeight - layout.trigger.top : undefined,\n          minWidth: triggerWidth,\n          pointerEvents: open ? \"auto\" : \"none\",\n          transformOrigin: actualSide === \"bottom\" ? \"top\" : \"bottom\",\n          visibility: layout ? \"visible\" : \"hidden\",\n          \"--listbox-trigger-width\": `${triggerWidth}px`,\n          [`--${name}-trigger-width`]: `${triggerWidth}px`,\n        } as CSSProperties\n      }\n      className={cn(\n        \"fixed z-[9999] w-(--listbox-trigger-width) overflow-hidden rounded-2xl border border-border bg-background text-popover-foreground outline-none will-change-[clip-path,transform]\",\n        className,\n      )}\n    >\n      <motion.div ref={measureRef} initial={false} animate={{ opacity: open ? 1 : 0 }} transition={transition}>\n        {children}\n      </motion.div>\n    </motion.div>,\n    document.body,\n  );\n}\n"},{"path":"components/motion/combobox/use-filtered-options.ts","type":"util","content":"\"use client\";\n\nimport { type MutableRefObject, useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useActiveOption } from \"./use-active-option\";\n\n/** An option as it registers with its list. */\nexport type RegisteredItem = {\n  value: string;\n  label: string;\n  keywords: string[];\n  disabled: boolean;\n  groupId: string | null;\n  id: string;\n  ref: MutableRefObject<HTMLButtonElement | null>;\n};\n\nexport type OptionFilter = (value: string, query: string, keywords: string[]) => boolean;\n\n/** Fuzzy match: the query's characters appear in order in the value or a keyword. */\nexport const defaultOptionFilter: OptionFilter = (value, query, keywords) => {\n  const needle = query.trim().toLocaleLowerCase();\n  if (!needle) return true;\n\n  const haystack = [value, ...keywords].join(\" \").toLocaleLowerCase();\n  let queryIndex = 0;\n  for (const character of haystack) {\n    if (character === needle[queryIndex]) queryIndex += 1;\n    if (queryIndex === needle.length) return true;\n  }\n  return false;\n};\n\n/**\n * The options a searchable list registers, filtered by its query, with the\n * active option resolved during render and kept scrolled into view. Shared by\n * Combobox and Multi Select, which differ only in what a pick does.\n */\nexport function useFilteredOptions({\n  open,\n  query,\n  value,\n  filter,\n}: {\n  open: boolean;\n  query: string;\n  /** The selected value the cursor starts on when the list opens. */\n  value: string | undefined;\n  filter: OptionFilter;\n}) {\n  const [items, setItems] = useState<Map<string, RegisteredItem>>(new Map());\n\n  const registerItem = useCallback((item: RegisteredItem) => {\n    setItems((current) => {\n      const existing = current.get(item.value);\n      if (\n        existing?.label === item.label &&\n        existing.disabled === item.disabled &&\n        existing.id === item.id &&\n        existing.ref === item.ref &&\n        existing.groupId === item.groupId &&\n        existing.keywords.join(\"\\u0000\") === item.keywords.join(\"\\u0000\")\n      ) {\n        return current;\n      }\n      const next = new Map(current);\n      next.set(item.value, item);\n      return next;\n    });\n  }, []);\n\n  const unregisterItem = useCallback((itemValue: string) => {\n    setItems((current) => {\n      if (!current.has(itemValue)) return current;\n      const next = new Map(current);\n      next.delete(itemValue);\n      return next;\n    });\n  }, []);\n\n  // The query the list filters by. Closing clears `query`, but the panel is\n  // still on screen for its exit, so it keeps filtering by the query it was\n  // open with rather than repopulating mid-collapse. The input already reads\n  // `query` only while open, so nothing the user can see reads the other one.\n  const [openQuery, setOpenQuery] = useState(query);\n  if (open && openQuery !== query) setOpenQuery(query);\n  const listQuery = open ? query : openQuery;\n\n  const visibleItems = useMemo(\n    () =>\n      Array.from(items.values()).filter((item) =>\n        filter(item.value, listQuery, [item.label, ...item.keywords]),\n      ),\n    [filter, items, listQuery],\n  );\n  const enabledVisibleItems = useMemo(\n    () => visibleItems.filter((item) => !item.disabled),\n    [visibleItems],\n  );\n  const visibleValues = useMemo(\n    () => new Set(visibleItems.map((item) => item.value)),\n    [visibleItems],\n  );\n  const visibleGroupIds = useMemo(\n    () => new Set(visibleItems.map((item) => item.groupId)),\n    [visibleItems],\n  );\n\n  const { activeValue, setActiveValue, moveActive } = useActiveOption({\n    open,\n    query: listQuery,\n    value,\n    enabledItems: enabledVisibleItems,\n  });\n\n  useEffect(() => {\n    if (!activeValue || !open) return;\n    const item = items.get(activeValue)?.ref.current;\n    const list = item?.closest<HTMLElement>(\"[role='listbox']\");\n    if (!item || !list) return;\n    const itemRect = item.getBoundingClientRect();\n    const listRect = list.getBoundingClientRect();\n    if (itemRect.top < listRect.top) list.scrollTop -= listRect.top - itemRect.top;\n    else if (itemRect.bottom > listRect.bottom) list.scrollTop += itemRect.bottom - listRect.bottom;\n  }, [activeValue, items, open]);\n\n  return {\n    items,\n    registerItem,\n    unregisterItem,\n    listQuery,\n    visibleValues,\n    visibleGroupIds,\n    visibleCount: visibleItems.length,\n    activeValue,\n    setActiveValue,\n    moveActive,\n    activeItemId: activeValue ? items.get(activeValue)?.id : undefined,\n  };\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident - the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it - the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/sound.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/close.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */\nexport const closeSound = defineSound({\n  name: \"Close\",\n  duration: 0.16,\n  room: 0.18,\n  build: (v) => {\n    v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });\n    v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });\n    v.strike({ freq: 260, material: \"wood\", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });\n  },\n});\n"},{"path":"lib/sounds/open.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */\nexport const openSound = defineSound({\n  name: \"Open\",\n  duration: 0.2,\n  room: 0.2,\n  build: (v) => {\n    v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });\n    v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });\n    v.strike({ freq: 1320, material: \"glass\", at: 0.05, decay: 0.07, gain: 0.12 });\n  },\n});\n"},{"path":"lib/sounds/select.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/merge-refs.ts","type":"util","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"components/motion/popover-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"components/motion/combobox/use-active-option.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * Where the keyboard or the pointer last moved to, stamped with the query it\n * was placed under. Which option is *active* is resolved from this during\n * render, never in an effect: a passive effect runs after the commit, so a list\n * would briefly have none of its options active, and a key arriving in that\n * window would move from nowhere onto the row it was already about to\n * highlight.\n */\ntype ActiveCursor = { value: string; query: string };\n\ntype Options = {\n  query: string;\n  value: string | undefined;\n  /** The enabled, visible options in list order - all this hook reads of them. */\n  enabledItems: readonly { value: string }[];\n};\n\nconst isEnabled = (\n  enabledItems: Options[\"enabledItems\"],\n  candidate: string | undefined,\n): candidate is string =>\n  candidate !== undefined && enabledItems.some((i) => i.value === candidate);\n\n/**\n * The cursor's option, or null once the query or the result set it was placed\n * in has changed. A cursor that outlived either would steal Enter from the row\n * the user is aiming at. The result-set half costs something: a live search\n * that blanks its rows while fetching and returns the same ones loses the moved\n * highlight. That is deliberate - a highlight visibly back at the top beats one\n * silently in the wrong place.\n *\n * It is stamped with the query rather than with the identity of the visible\n * list because callers routinely pass an inline `filter`, which makes that list\n * a fresh array on every render.\n */\nfunction liveCursorValue(cursor: ActiveCursor | null, options: Options) {\n  if (cursor === null || cursor.query !== options.query) return null;\n  return isEnabled(options.enabledItems, cursor.value) ? cursor.value : null;\n}\n\n/**\n * Where the highlight sits with no live cursor: the selection if it can be\n * selected, otherwise the first option that can. Only enabled options qualify -\n * an active disabled option would point `aria-activedescendant` at a row Enter\n * then refuses to select.\n */\nfunction fallbackActive({ value, enabledItems }: Options) {\n  return isEnabled(enabledItems, value) ? value : (enabledItems[0]?.value ?? null);\n}\n\n/** The active option, from a cursor that may or may not still be live. */\nconst resolveActive = (cursor: ActiveCursor | null, options: Options) =>\n  liveCursorValue(cursor, options) ?? fallbackActive(options);\n\nexport function useActiveOption({ open, ...options }: Options & { open: boolean }) {\n  const { query, value, enabledItems } = options;\n  const [cursor, setCursor] = useState<ActiveCursor | null>(null);\n\n  const live = liveCursorValue(cursor, options);\n  // Cleared rather than ignored: React re-runs this render with the cursor\n  // gone, so a value that reappears later cannot revive it.\n  if (cursor !== null && live === null) setCursor(null);\n  const derived = live ?? fallbackActive(options);\n\n  // Nothing is active until the list has been opened once. After that the\n  // resolution above is already stable across a close - the list keeps\n  // filtering by the query it was open with - so the highlight holds its row\n  // through the exit without being frozen separately.\n  const [opened, setOpened] = useState(open);\n  if (open && !opened) setOpened(true);\n  const activeValue = opened ? derived : null;\n\n  // Both callbacks keep one identity for the life of the component, and read\n  // the list through a ref to do it. A caller will put them in a `useMemo` or\n  // an effect's dependencies - the exhaustive-deps rule makes it - and\n  // `enabledItems` is a fresh array on every render for any consumer passing an\n  // inline `filter`, so a callback keyed to it would be rebuilt every render.\n  // Written after commit rather than during render: a render React discards\n  // still runs the component body, and a handler reading this in that window\n  // would step against a list the committed tree does not have.\n  const latest = useRef({ open, query, value, enabledItems });\n  useLayoutEffect(() => {\n    latest.current = { open, query, value, enabledItems };\n  });\n\n  const setActiveValue = useCallback((next: string | null) => {\n    setCursor(\n      next === null ? null : { value: next, query: latest.current.query },\n    );\n  }, []);\n\n  // Steps from the option the cursor really resolves to, inside the update, so\n  // that two keys landing in one batch move two rows rather than one.\n  const moveActive = useCallback(\n    (direction: 1 | -1 | \"first\" | \"last\") => {\n      const options = latest.current;\n      // While closed the list is still filtering by the query it was open\n      // with, so a step taken now would be measured against rows the next\n      // render replaces. Opening is the caller's job; stepping waits for it.\n      if (!options.open) return;\n      const rows = options.enabledItems;\n      const last = rows.length - 1;\n      if (last < 0) {\n        setCursor(null);\n        return;\n      }\n      setCursor((current) => {\n        // `resolveActive` always lands on a member of `enabledItems` once the\n        // list is non-empty, which the early return above guarantees, so there\n        // is always a row to step from.\n        const from = resolveActive(current, options);\n        const at = rows.findIndex((item) => item.value === from);\n        const index =\n          direction === \"first\"\n            ? 0\n            : direction === \"last\"\n              ? last\n              : (at + direction + rows.length) % rows.length;\n        return { value: rows[index].value, query: options.query };\n      });\n    },\n    [],\n  );\n\n  return { activeValue, setActiveValue, moveActive };\n}\n"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"lib/audio-context.ts","type":"util","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"util","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"},{"path":"components/previews/motion/combobox.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { Blocks, Box, Component, Layers3 } from \"lucide-react\";\nimport { useState } from \"react\";\nimport {\n  Combobox,\n  ComboboxContent,\n  ComboboxEmpty,\n  ComboboxGroup,\n  ComboboxInput,\n  ComboboxItem,\n  ComboboxLabel,\n  ComboboxList,\n  ComboboxSeparator,\n  ComboboxTrigger,\n} from \"@/components/motion/combobox\";\n\nconst WORKSPACES = [\n  {\n    value: \"studio\",\n    label: \"Design studio\",\n    detail: \"12 projects\",\n    group: \"Recent\",\n    icon: Component,\n    color: \"bg-amber-400/20 text-amber-700 dark:text-amber-300\",\n  },\n  {\n    value: \"product\",\n    label: \"Product team\",\n    detail: \"8 projects\",\n    group: \"Recent\",\n    icon: Layers3,\n    color: \"bg-sky-400/20 text-sky-700 dark:text-sky-300\",\n  },\n  {\n    value: \"playground\",\n    label: \"Playground\",\n    detail: \"24 experiments\",\n    group: \"Workspaces\",\n    icon: Blocks,\n    color: \"bg-emerald-400/20 text-emerald-700 dark:text-emerald-300\",\n  },\n  {\n    value: \"archive\",\n    label: \"Component archive\",\n    detail: \"41 components\",\n    group: \"Workspaces\",\n    icon: Box,\n    color: \"bg-rose-400/20 text-rose-700 dark:text-rose-300\",\n  },\n] as const;\n\nfunction WorkspaceMark({ value }: { value: string }) {\n  const workspace = WORKSPACES.find((item) => item.value === value);\n  if (!workspace) return null;\n  const Icon = workspace.icon;\n  return (\n    <span\n      className={`grid size-7 shrink-0 place-items-center rounded-full ${workspace.color}`}\n    >\n      <Icon className=\"size-3.5\" />\n    </span>\n  );\n}\n\nexport function ComboboxPreview() {\n  const [value, setValue] = useState(\"studio\");\n\n  return (\n    <div className=\"w-full max-w-72\">\n      <p className=\"mb-2 text-xs font-medium text-muted-foreground\">\n        Workspace\n      </p>\n      <Combobox sound value={value} onValueChange={setValue}>\n        <ComboboxTrigger className=\"h-12 px-2.5\">\n          <ComboboxInput\n            aria-label=\"Search workspaces\"\n            placeholder=\"Search workspaces…\"\n          />\n        </ComboboxTrigger>\n\n        <ComboboxContent className=\"w-72\">\n          <ComboboxList ariaLabel=\"Workspaces\" className=\"p-2\">\n            <ComboboxEmpty>No workspaces found.</ComboboxEmpty>\n            {([\"Recent\", \"Workspaces\"] as const).map((group, groupIndex) => (\n              <ComboboxGroup key={group}>\n                {groupIndex > 0 ? <ComboboxSeparator /> : null}\n                <ComboboxLabel>{group}</ComboboxLabel>\n                {WORKSPACES.filter((item) => item.group === group).map(\n                  (workspace) => (\n                    <ComboboxItem\n                      key={workspace.value}\n                      value={workspace.value}\n                      textValue={workspace.label}\n                      keywords={[workspace.detail, workspace.group]}\n                      className=\"py-2\"\n                    >\n                      <span className=\"flex min-w-0 items-center gap-2.5\">\n                        <WorkspaceMark value={workspace.value} />\n                        <span className=\"min-w-0\">\n                          <span className=\"block truncate font-medium text-foreground\">\n                            {workspace.label}\n                          </span>\n                          <span className=\"block truncate text-xs text-muted-foreground\">\n                            {workspace.detail}\n                          </span>\n                        </span>\n                      </span>\n                    </ComboboxItem>\n                  ),\n                )}\n              </ComboboxGroup>\n            ))}\n          </ComboboxList>\n        </ComboboxContent>\n      </Combobox>\n    </div>\n  );\n}\n"}]}