{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "conversation-list",
  "title": "ConversationList",
  "description": "A list of conversations to choose from: each row shows the avatar, the title, when the latest message arrived and a line of it, and marks unread conversations with a bold title and a dot.",
  "registryDependencies": [
    "@ouro/avatar",
    "@ouro/lib-class-name-check",
    "@ouro/lib-cn",
    "@ouro/lib-env",
    "@ouro/lib-use-dev-messages",
    "@ouro/menu",
    "@ouro/unread-dot"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/conversation-list/conversation-list.tsx",
      "content": "\"use client\";\n\nimport {\n  memo,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type HTMLAttributes,\n  type JSX,\n  type KeyboardEvent,\n  type MouseEvent,\n  type PointerEvent,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { Avatar } from \"@/registry/ouro/components/ouro/avatar/avatar\";\nimport type { MenuAnchor, MenuEntry } from \"@/registry/ouro/components/ouro/menu/menu\";\nimport { UnreadDot } from \"@/registry/ouro/components/ouro/unread-dot/unread-dot\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\n\ntype MenuModule = typeof import(\"@/registry/ouro/components/ouro/menu/menu\");\n\n// Menu's code, loaded once, as the first row with a menu renders, so a press opens the menu at once.\nlet menuModule: Promise<MenuModule> | undefined;\nlet menuLoaded: MenuModule | undefined;\nconst loadMenu = () => (menuModule ??= import(\"@/registry/ouro/components/ouro/menu/menu\").then((module) => (menuLoaded = module)));\n\n// How long a finger rests on a row, in ms, before its menu opens, as a long press does on a phone.\nconst LONG_PRESS = 500;\n// How far a finger may drift, in px, and still be pressing rather than scrolling.\nconst PRESS_SLOP = 10;\n\nconst hasMenu = (item: ConversationListItem) => item.menu !== undefined && item.menu.length > 0;\n\n/** An element's box as it is now, for a menu that stays where it opened after the row goes. */\nfunction frozen(element: Element): MenuAnchor {\n  const box = element.getBoundingClientRect();\n  return { getBoundingClientRect: () => box };\n}\n\n/** What a {@link ConversationList} row shows of a conversation, whichever way its title comes. */\nexport interface ConversationListItemFields {\n  /** Identifies the conversation; `onSelect` receives it. */\n  id: string;\n  /**\n   * A quiet tag right after the title, such as \"AI agent\" for an agent or \"Guest\": small and muted, not a badge, and\n   * read after the title (\"Halden, AI agent\"). In a narrow row the title shortens and the tag stays whole.\n   * @claim \"In a narrow row the title\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > shows a quiet name tag after the title, read after it, and shortens the title first)\n   * @claim \"A quiet tag right after the\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > shows a quiet name tag after the title, read after it, and shortens the title first)\n   */\n  nameTag?: string | undefined;\n  /**\n   * A muted name after the title, on its line, such as the team a channel belongs to: \"Design\n   * reviews · Launch team\". Text, or content such as `<EmojiText>` to draw its emoji as pictures.\n   * It shows whole or not at all: when the row has no room for it, the title keeps the room and the\n   * where is hidden, never cut to a fragment; screen readers still read it. Leave it out where a\n   * section's title already names it.\n   * @claim \"It shows whole or not at all\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > shows the where whole or not at all, never cut, and gives it up before the title)\n   */\n  where?: ReactNode;\n  /** A second line under the title, such as the group a topic belongs to. */\n  subtitle?: string | undefined;\n  /**\n   * A line between the title and the preview that says what happened and where, as an activity\n   * feed shows it: the title names the person, this line \"mentioned you in Design reviews\", and\n   * the preview the message. Text, or content such as `<EmojiText>`. It keeps to `density=\"compact\"`.\n   *\n   * @claim \"A line between the title and the preview\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > shows a context line between the title and the preview, which the mark ends when there is no preview)\n   */\n  context?: ReactNode;\n  /** The latest message, cut to one line. `density=\"compact\"` hides it. */\n  preview?: ReactNode;\n  /**\n   * The first words of a message the person started here and has not sent. They show in place\n   * of the preview after `draftLabel` (\"Draft:\"), in the destructive tone as chat apps mark a\n   * draft, so a half-written reply is visible from the list. `density=\"compact\"` hides it with\n   * the preview.\n   *\n   * @claim \"They show in place of the preview\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > shows a draft in place of the preview, after its label in the destructive tone, and hides it when compact)\n   */\n  draft?: ReactNode;\n  /** When the latest message arrived, already formatted (\"9:41\", `<RelativeTime>`). */\n  time?: ReactNode;\n  /** There are messages the person has not read: the title is bold and a dot shows. */\n  unread?: boolean | undefined;\n  /** A small icon before the title, in the muted color, such as a pin or a muted bell. Give it a name (`role=\"img\"` and `aria-label`) when it means something. */\n  icon?: ReactNode;\n  /** Small marks after the title, such as a `<Badge>`. */\n  badges?: ReactNode;\n  /**\n   * The row's mark, at the end of its last line under the time: a mention `<Badge>`, \"in 10 min\" before a meeting.\n   * It takes the unread dot's place; screen readers still hear `unreadLabel`. Words show small and muted, like the\n   * time. It keeps to the line's height, so the row stays the height of the others.\n   */\n  mark?: ReactNode;\n  /**\n   * The avatar: a picture's URL, or an element to show instead, such as an `<Avatar>` with the person's presence or an\n   * `<AvatarGroup>`. Without it the avatar shows the title's initials; `false` hides the avatar.\n   */\n  avatar?: string | ReactElement | false | undefined;\n  /** The `id` of the section in `sections` the row shows under. Rows without a section come first, before the headers. */\n  section?: string | undefined;\n  /**\n   * The row's own menu, as `Menu` entries: what a right-click, a long press, Shift+F10 or the Menu key on the row opens, such\n   * as Mark as read, Pin and Mute. It opens at the pointer, or beside the row from the keyboard, and focus goes back to the\n   * row when it closes. A row the list stops drawing while its menu is open (scrolled far away) keeps the menu where it\n   * opened. A row without one keeps the browser's own menu.\n   */\n  menu?: readonly MenuEntry[] | undefined;\n}\n\n/** A conversation whose title is text. */\nexport interface ConversationListTextTitle {\n  /** The conversation's name: a person, a group or a topic. The avatar's initials come from it. */\n  title: string;\n  /** The name screen readers hear in place of `title`, and the avatar's initials come from. @default the title */\n  name?: string | undefined;\n}\n\n/**\n * A conversation whose title is content, such as its name with emoji drawn as pictures\n * (`<EmojiText text={chat.name} catalogue={catalogue} />`), with its name as text beside it.\n */\nexport interface ConversationListContentTitle {\n  /** What the row shows as the conversation's name. */\n  title: ReactNode;\n  /**\n   * The conversation's name as text: what screen readers hear in place of the title, and the\n   * avatar's initials come from it.\n   *\n   * @claim \"what screen readers hear in place of the title\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > shows a title and where given as content, with the name screen readers hear and the avatar's initials come from)\n   */\n  name: string;\n}\n\n/** One conversation in a {@link ConversationList}: its title as text, or as content with a `name`. */\nexport type ConversationListItem = ConversationListItemFields & (ConversationListTextTitle | ConversationListContentTitle);\n\n/** A group of rows in a {@link ConversationList}, under a header that opens and closes it. */\nexport interface ConversationListSection {\n  /** Identifies the section; rows name it in their `section`, and `onSectionOpenChange` receives it. */\n  id: string;\n  /** The header's words: \"Pinned\", \"Recent\". They also name the section's list for screen readers. */\n  title: string;\n  /** Muted words after the title on the header, such as \"your folder\". */\n  note?: ReactNode;\n  /** Whether the section starts open, when the list keeps its state. @default true */\n  defaultOpen?: boolean | undefined;\n  /** Whether the section is open, when the app keeps the state with `onSectionOpenChange`. */\n  open?: boolean | undefined;\n}\n\n/** The density of the rows. */\nexport type ConversationListDensity = \"comfortable\" | \"compact\";\n\n/** The props ConversationList adds to the `<div>` attributes it passes through. */\nexport interface ConversationListOwnProps {\n  /** What the list is, for screen readers (\"Conversations\"). Required, so the list has a name. */\n  label: string;\n  /** The conversations, in the order they show. */\n  items: readonly ConversationListItem[];\n  /** The headers the rows group under, in order. A row names its header in `section`, and a section without rows is left out. */\n  sections?: readonly ConversationListSection[] | undefined;\n  /** Called with a section's `id` and whether it is now open, when its header is pressed. */\n  onSectionOpenChange?: ((id: string, open: boolean) => void) | undefined;\n  /** The `id` of the open conversation. Its row is highlighted and marked `aria-current`. */\n  selectedId?: string | null | undefined;\n  /**\n   * Called with a row's `id` when it is chosen by a click, a tap, Enter or Space. A handler that takes a second\n   * parameter also gets the click, so the app can check `event.isTrusted` or `event.metaKey`; a one-parameter\n   * handler or a server action gets the `id` alone.\n   */\n  onSelect: (id: string, event: MouseEvent<HTMLButtonElement>) => void;\n  /** What shows when `items` is empty. @default \"Nothing here yet\" */\n  empty?: ReactNode;\n  /** `compact` drops the preview line and uses a smaller avatar. @default \"comfortable\" */\n  density?: ConversationListDensity | (string & { 'Use \"comfortable\" or \"compact\"': never }) | undefined;\n  /** What screen readers hear for an unread row's dot, and a closed section's, for other languages. @default \"Unread\" */\n  unreadLabel?: string | undefined;\n  /** The words before a row's `draft`, for other languages. @default \"Draft:\" */\n  draftLabel?: string | undefined;\n  /** Layout only: width, margins, grid placement (`w-80`). Appearance classes warn in development. */\n  className?: string | undefined;\n  ref?: Ref<HTMLDivElement> | undefined;\n\n  /** Not a prop. The open conversation is `selectedId`: `<ConversationList selectedId={openId}>`. */\n  value?: { 'Use selectedId={openId}': never };\n  /** Not a prop. The open conversation is `selectedId`: `<ConversationList selectedId={openId}>`. */\n  selected?: { 'Use selectedId={openId}': never };\n  /** Not a prop. A chosen row calls `onSelect`: `<ConversationList onSelect={(id) => open(id)}>`. */\n  onValueChange?: { 'Use onSelect={(id) => open(id)}': never };\n  /** Not a prop. The rows are `items`: `<ConversationList items={conversations}>`. */\n  conversations?: { 'Use items={conversations}': never };\n  /** Not a prop. Headers are `sections`, and a row names its own in `section`: `<ConversationList sections={sections} items={rows}>`. */\n  groups?: { 'Use sections={sections}, and section on each item': never };\n}\n\n/** Props for {@link ConversationList}: its own props and the `<div>` attributes it passes through. */\nexport type ConversationListProps = Omit<HTMLAttributes<HTMLDivElement>, keyof ConversationListOwnProps> & ConversationListOwnProps;\n\nconst densities = [\"comfortable\", \"compact\"] as const;\nconst quiet = \"text-[color-mix(in_oklab,var(--muted-foreground)_80%,var(--foreground))]\";\n\n// A row highlights while pressed instead of scaling, as Item's linked row does, and is a\n// full touch target on a coarse pointer. The focus outline sits inside the row, so a list\n// in a scrolling pane never clips it.\nconst controlClass =\n  \"press relative box-border flex w-full min-w-0 cursor-pointer items-center rounded-ouro-md border-0 forced-colors:border forced-colors:border-solid bg-transparent px-3 \" +\n  \"text-start text-foreground select-none touch-manipulation [-webkit-tap-highlight-color:transparent] \" +\n  \"outline-ring -outline-offset-2 focus-visible:outline-2 focus-visible:outline-solid pointer-coarse:min-h-11 pointer-fine:hover:bg-muted active:bg-muted\";\n// A row opens and closes at once (`press` eases no colour): the open row is drawn in its accent on the first frame after\n// it becomes current, and the row that closes drops it on that frame.\nconst rowClass = \"gap-3 aria-[current=true]:bg-accent aria-[current=true]:text-accent-foreground forced-colors:aria-[current=true]:border-2\";\n// The open row keeps its highlight under the pointer and while pressed: the plain rows' muted\n// hover would make it look closed. These replace controlClass's hover and press colours.\nconst currentClass = \"pointer-fine:hover:bg-accent active:bg-accent\";\nconst headerClass = \"gap-1.5 py-1.5 text-sm\";\nconst listClass = \"m-0 flex list-none flex-col gap-0.5 p-0\";\n\nconst moves: Readonly<Record<string, (index: number, last: number) => number>> = {\n  ArrowDown: (index, last) => Math.min(index + 1, last),\n  ArrowUp: (index) => Math.max(index - 1, 0),\n  Home: () => 0,\n  End: (_index, last) => last,\n};\n\nconst shown = (node: ReactNode): boolean => node !== undefined && node !== null && node !== false;\n\n// Above this many conversations the list renders only the rows near the view, so a long list costs what a screenful does.\nconst windowAbove = 20;\n// How far past the view's top and bottom edges rows still render, in pixels, so a scroll shows rows already drawn.\nconst overscan = 320;\n// How much of the list renders before the view is known, as in server HTML, in pixels.\nconst firstView = 1000;\n// A row's height before any is measured, with the gap before it, by density; a header's too, until one is measured.\nconst estimates: Readonly<Record<ConversationListDensity, number>> = { comfortable: 58, compact: 34 };\n// The shortest a row is assumed to be on the first frame, in pixels: rows shorter than the estimates still fill the view, so the window never grows once measured.\nconst shortest = 40;\nconst noHeights: ReadonlyMap<string, number> = new Map();\n// The default for sections: one array, so the rows are put in order again only when they or their sections change.\nconst noSections: readonly ConversationListSection[] = [];\n\n// What a windowed list's last render laid out, for the scroll, resize and measuring that follow it.\ninterface Laid {\n  keys: readonly string[];\n  offsets: readonly number[];\n  total: number;\n  range: readonly [number, number];\n  heights: ReadonlyMap<string, number>;\n}\nconst kindOf = (key: string) => (key.startsWith(\"section:\") ? \"section\" : \"row\");\n\n// Where each control's slot starts in a windowed list, and the list's height. A slot not measured yet takes the average\n// height of the measured slots of its kind, leaving out the first slot, which has no gap before it; before any is\n// measured, it takes the estimate.\nfunction place(keys: readonly string[], heights: ReadonlyMap<string, number>, estimate: number) {\n  const known = { row: { sum: 0, count: 0 }, section: { sum: 0, count: 0 } };\n  keys.forEach((key, index) => {\n    const height = heights.get(key);\n    if (height === undefined || index === 0) return;\n    known[kindOf(key)].sum += height;\n    known[kindOf(key)].count++;\n  });\n  const offsets: number[] = [];\n  let total = 0;\n  for (const key of keys) {\n    offsets.push(total);\n    const { sum, count } = known[kindOf(key)];\n    total += heights.get(key) ?? (count ? sum / count : estimate);\n  }\n  return { offsets, total };\n}\n\n// Whether a section shows its rows: as the app says, else as the person left it, else as it starts.\nfunction openOf(section: ConversationListSection, opened: Readonly<Record<string, boolean>>): boolean {\n  return section.open ?? opened[section.id] ?? section.defaultOpen ?? true;\n}\n\n// Scrolls a control into view: as little as it takes, or to the middle of the view.\nfunction reveal(controls: ReadonlyMap<string, HTMLElement>, key: string, block: \"nearest\" | \"center\") {\n  // Stryker disable next-line OptionalChaining: the rows revealed are kept rendered (the open row, the row with focus, the row the keyboard reached); this only guards a crash.\n  controls.get(key)?.scrollIntoView({ block });\n}\n\n/** A chevron that points at the rows when the section is open, and along the header when it is closed. */\nfunction Chevron({ open }: { open: boolean }): JSX.Element {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" className={cn(\"size-4 shrink-0\", quiet, !open && \"rtl:-scale-x-100\")}>\n      <path d={open ? \"M4 6l4 4 4-4\" : \"M6 4l4 4-4 4\"} />\n    </svg>\n  );\n}\n\ntype RowProps = {\n  item: ConversationListItem;\n  rowKey: string;\n  density: ConversationListDensity;\n  unreadLabel: string;\n  draftLabel: string;\n  selected: boolean;\n  tabStop: boolean;\n  windowed: boolean;\n  top: number | undefined;\n  slotClass?: string | undefined;\n  position: number;\n  count: number;\n  register: (key: string, node: HTMLButtonElement | null) => void;\n  onPick: (id: string, event: MouseEvent<HTMLButtonElement>) => void;\n  onKey: (event: KeyboardEvent<HTMLButtonElement>, key: string) => void;\n  onActive: (key: string) => void;\n};\n\n// A row renders again only when its own conversation, place or state changes, so opening another conversation renders\n// the row that closes and the row that opens, not the list.\nconst Row = memo(function Row({ item, rowKey: key, density, unreadLabel, draftLabel, selected, tabStop, windowed, top, slotClass, position, count, register, onPick, onKey, onActive }: RowProps): JSX.Element {\n  const drafted = shown(item.draft);\n  const withPreview = density === \"comfortable\" && (drafted || shown(item.preview));\n  // The mark and the unread dot end the last line: the preview's, else the context's, else the subtitle's, else the title's.\n  const withContext = shown(item.context);\n  const endsTitle = !withPreview && !withContext && !item.subtitle;\n  const endsSubtitle = !withPreview && !withContext && !!item.subtitle;\n  const hasMark = shown(item.mark);\n  const end = (\n    <>\n      {hasMark && (\n        // As tall as the line, so a badge that is a little taller leaves the row the height of the others.\n        <span data-ouro-conversation-mark=\"\" className={cn(\"flex h-5 shrink-0 items-center text-xs\", quiet)}>\n          {item.mark}\n        </span>\n      )}\n      {item.unread && <UnreadDot data-ouro-conversation-unread=\"\" label={unreadLabel} dot={!hasMark} />}\n    </>\n  );\n  return (\n    <li\n      {...(windowed && { style: { top }, \"aria-posinset\": position, \"aria-setsize\": count })}\n      className={cn(\"m-0 p-0\", windowed && slotClass)}\n    >\n      <button\n        ref={(node) => register(key, node)}\n        type=\"button\"\n        data-ouro-control=\"conversation-list\"\n        data-ouro-part=\"row\"\n        tabIndex={tabStop ? 0 : -1}\n        aria-current={selected ? \"true\" : undefined}\n        onClick={(event) => onPick(item.id, event)}\n        onKeyDown={(event) => onKey(event, key)}\n        onFocus={() => onActive(key)}\n        // A row with a menu opens it on a long press, in place of the phone's own callout.\n        className={cn(controlClass, rowClass, selected && currentClass, density === \"compact\" ? \"py-1.5\" : \"py-2\", hasMenu(item) && \"[-webkit-touch-callout:none]\")}\n      >\n        {item.avatar === false ? null : typeof item.avatar === \"object\" ? (\n          <span data-ouro-conversation-avatar=\"\" className=\"flex shrink-0\">\n            {item.avatar}\n          </span>\n        ) : (\n          <Avatar name={item.name ?? (item.title as string)} src={item.avatar} alt=\"\" size={density === \"compact\" ? \"xs\" : \"sm\"} />\n        )}\n        <span className=\"flex min-w-0 flex-1 flex-col\">\n          <span className=\"flex min-w-0 items-center gap-2\">\n            <span className=\"flex min-w-0 flex-1 items-center gap-1.5\">\n              {shown(item.icon) && (\n                <span data-ouro-conversation-icon=\"\" className={cn(\"flex shrink-0 items-center [&_svg]:size-4\", quiet)}>\n                  {item.icon}\n                </span>\n              )}\n              <span data-ouro-conversation-title=\"\" className={cn(\"min-w-0 truncate text-base pointer-fine:text-sm\", item.unread ? \"font-semibold\" : \"font-normal\")}>\n                {item.name === undefined ? (\n                  item.title\n                ) : (\n                  <>\n                    <span aria-hidden=\"true\">{item.title}</span>\n                    <span className=\"sr-only\">{item.name}</span>\n                  </>\n                )}\n              </span>\n              {item.nameTag && (\n                <span data-ouro-conversation-name-tag=\"\" className={cn(\"shrink-0 text-sm pointer-fine:text-xs\", quiet)}>\n                  <span className=\"sr-only\">, </span>\n                  {item.nameTag}\n                </span>\n              )}\n              {shown(item.where) && (\n                // One line tall: the where wraps past the empty first item when it does not fit, and the wrapped line is clipped.\n                <span data-ouro-conversation-where=\"\" className={cn(\"flex h-lh min-w-0 max-w-max flex-[1_1_0%] flex-wrap overflow-hidden text-sm pointer-fine:text-xs\", quiet)}>\n                  <span className=\"h-lh w-0\" />\n                  <span className=\"whitespace-nowrap\">\n                    <span aria-hidden=\"true\">· </span>\n                    {item.where}\n                  </span>\n                </span>\n              )}\n              {item.badges}\n            </span>\n            {shown(item.time) && (\n              <span data-ouro-conversation-time=\"\" className={cn(\"shrink-0 text-xs tabular-nums\", quiet)}>\n                {item.time}\n              </span>\n            )}\n            {endsTitle && end}\n          </span>\n          {item.subtitle && (\n            <span className=\"flex min-w-0 items-center gap-2\">\n              <span data-ouro-conversation-subtitle=\"\" className={cn(\"min-w-0 flex-1 truncate text-xs\", quiet)}>\n                {item.subtitle}\n              </span>\n              {endsSubtitle && end}\n            </span>\n          )}\n          {withContext && (\n            <span className=\"flex min-w-0 items-center gap-2\">\n              <span data-ouro-conversation-context=\"\" className=\"min-w-0 flex-1 truncate text-sm text-foreground\">\n                {item.context}\n              </span>\n              {!withPreview && end}\n            </span>\n          )}\n          {withPreview && (\n            <span className=\"flex min-w-0 items-center gap-2\">\n              <span data-ouro-conversation-preview=\"\" className={cn(\"min-w-0 flex-1 truncate text-sm\", item.unread ? \"text-foreground\" : quiet)}>\n                {drafted ? (\n                  <>\n                    <span data-ouro-conversation-draft=\"\" className=\"font-medium text-[color-mix(in_oklab,var(--destructive)_80%,var(--foreground))]\">\n                      {draftLabel}\n                    </span>{\" \"}\n                    {item.draft}\n                  </>\n                ) : (\n                  item.preview\n                )}\n              </span>\n              {end}\n            </span>\n          )}\n        </span>\n      </button>\n    </li>\n  );\n});\n\n/**\n * A list of conversations to choose from: each row shows the avatar, the title, when the\n * latest message arrived and a line of it, and marks unread conversations with a bold title\n * and a dot. The open conversation's row is highlighted, under the pointer too, and marked\n * `aria-current`. The list\n * is a single stop for the Tab key, which lands on the open conversation; Up and Down arrows\n * move between rows, Home and End jump to the first and last, and Enter, Space or a click\n * calls `onSelect`. Rows can group under `sections`, whose headers open and close them.\n * A list of more than 20 conversations renders only the rows near the view, and the Tab stop and the open row,\n * each placed where it would be in the whole list and measured as it renders, so a long list costs about what a\n * screenful does. The arrow keys, Home and End still reach every row, and the open conversation's row scrolls\n * into view. A long list's other rows are not in the page, so code that reads the rows from the page, and the\n * browser's find in page, see only the rows rendered: read `items` instead.\n *\n * Use `ItemGroup` instead for a static list with nothing open, and `Tabs` for a handful of\n * views that switch in place.\n *\n * @group Chat\n * @see https://ui.ouroboros.bot/docs/conversation-list\n *\n * @example\n * <ConversationList label=\"Conversations\" items={conversations} selectedId={openId} onSelect={setOpenId} />\n * <ConversationList label=\"Chats\" sections={[{ id: \"pinned\", title: \"Pinned\" }]} items={[{ id: \"ana\", title: \"Ana Lind\", section: \"pinned\" }]} onSelect={open} />\n * @claim \"A list of conversations to choose\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > is a named list of buttons, one per conversation, in order)\n * @claim \"A list of conversations to choose\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > shows unread conversations with a bold title, a dot and a spoken label)\n * @claim \"The open conversation's row is\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > marks the open conversation current and highlights it)\n * @claim \"The open conversation's row is\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > keeps the open conversation highlighted under the pointer)\n * @claim \"is a single stop for the\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > is one Tab stop, which lands on the open conversation)\n * @claim \"is a single stop for the\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList > moves focus with the arrow keys, Home and End)\n * @claim \"A list of more than 20\" registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx::ConversationList windowing > keeps a list of 20 conversations whole, as a short list always was)\n * @claim \"A list of more than 20\" registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx::ConversationList windowing > renders only the rows near the view of a long list, in a list as tall as all of them)\n * @claim \"A list of more than 20\" registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx::ConversationList windowing > renders the rows a scroll reaches, in order, and drops the rows it leaves)\n * @claim \"The arrow keys, Home and End still reach every row\" registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx::ConversationList windowing > moves focus to the last row with End and back with Home, rendering and showing the row it reaches)\n * @claim \"The arrow keys, Home and End still reach every row\" registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx::ConversationList windowing > walks down past the rows first rendered with the Down arrow, scrolling only as far as the row with focus needs)\n * @claim \"A long list's other rows are not in the page\" registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx::ConversationList windowing > renders only the rows near the view of a long list, in a list as tall as all of them)\n * @claim \"the open conversation's row scrolls\" registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.windowing.test.tsx::ConversationList windowing > renders the open conversation far down the list and scrolls it into view, and again when another opens)\n * @claim \"Rows can group under\" registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx verify:testExists(registry/ouro/components/ouro/conversation-list/conversation-list.test.tsx::ConversationList sections > groups rows under headers that open and close them)\n */\nexport function ConversationList(props: ConversationListProps): JSX.Element {\n  const {\n    label,\n    items,\n    sections = noSections,\n    onSectionOpenChange,\n    selectedId,\n    onSelect,\n    empty = \"Nothing here yet\",\n    density: densityProp = \"comfortable\",\n    unreadLabel = \"Unread\",\n    draftLabel = \"Draft:\",\n    className,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    value,\n    selected,\n    onValueChange,\n    conversations,\n    groups,\n    ...rest\n  } = props;\n  const density: ConversationListDensity = (densities as readonly string[]).includes(densityProp) ? (densityProp as ConversationListDensity) : \"comfortable\";\n  const listRef = useRef<HTMLUListElement>(null);\n  const baseId = useId();\n  // The control that has focus, while focus is in the list: it keeps the list's one Tab stop.\n  // Stryker disable next-line StringLiteral: no control's key is this string, which is all \"nothing has focus\" needs.\n  const [active, setActive] = useState(\"\");\n  const [opened, setOpened] = useState<Readonly<Record<string, boolean>>>({});\n  // A long list renders only the rows near the view, and those it must keep: the Tab stop, the open row and the row\n  // the keyboard is moving to. Each sits at its place in a list as tall as all of them, measured as they render.\n  const windowed = items.length > windowAbove;\n  const [measured, setMeasured] = useState<{ density: ConversationListDensity; heights: ReadonlyMap<string, number> } | null>(null);\n  const [range, setRange] = useState<readonly [number, number] | null>(null);\n  const [reach, setReach] = useState<string | null>(null);\n  const controls = useRef(new Map<string, HTMLButtonElement>());\n  const latest = useRef<Laid | null>(null);\n  const clips = useRef<HTMLElement[] | null>(null);\n  const scroller = useRef<Element | null>(null);\n  // Whether the list has been scrolled since it mounted.\n  const scrolled = useRef(false);\n  const seenTop = useRef(0);\n  const viewSize = useRef(\"\");\n  const selectionFrame = useRef(0);\n  // What every render, scroll and resize runs, from the latest render; set before any scroll or resize can call it.\n  const sync = useRef<(() => void) | null>(null);\n  // Stryker disable next-line ArrowFunction,ArrayDeclaration,CallExpression: the cleanup only stops a late frame reading a gone list; no test can observe it.\n  useLayoutEffect(() => () => cancelAnimationFrame(selectionFrame.current), []);\n  // What the last sync ran for, and the observer that reports a row's change of size once the page is laid out.\n  const synced = useRef<{ inputs: string; places: string; heights: ReadonlyMap<string, number> } | null>(null);\n  const rows = useRef<ResizeObserver | null>(null);\n  const revealed = useRef<string | null>(null);\n  // Whether the open row changed since the last sync, which then checks it is in view.\n  const opening = useRef(false);\n  const focusNext = useRef<string | null>(null);\n  // The row to keep in view while the heights around it settle, and where in the view.\n  const keepInView = useRef<{ key: string; block: \"nearest\" | \"center\" } | null>(null);\n  const known = useMemo(() => new Set<string | undefined>(sections.map((section) => section.id)), [sections]);\n  const stray = items.find((item) => item.section !== undefined && !known.has(item.section));\n  useAppearanceClassNameCheck(\n    \"ConversationList\",\n    className,\n    process.env.NODE_ENV !== \"production\"\n      ? (token: string) => `remove \"${token}\"; ConversationList takes its colors from the theme`\n      : // Stryker disable next-line StringLiteral: production only; the check never runs there.\n        /* istanbul ignore next @preserve -- production only */ \"\",\n  );\n  useDevWarnings(\n    \"ConversationList\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [\n          label === undefined && [\"label is missing, so screen readers cannot name the list\", '<ConversationList label=\"Conversations\" items={conversations} onSelect={open}>'],\n          density !== densityProp && [`density=\"${String(densityProp)}\" is not a density; use \"comfortable\" or \"compact\"`, '<ConversationList density=\"compact\">'],\n          (value !== undefined || selected !== undefined) && [`${value !== undefined ? \"value\" : \"selected\"} is not a prop`, \"<ConversationList selectedId={openId}>\"],\n          onValueChange !== undefined && [\"onValueChange is not a prop\", \"<ConversationList onSelect={(id) => open(id)}>\"],\n          conversations !== undefined && [\"conversations is not a prop\", \"<ConversationList items={conversations}>\"],\n          groups !== undefined && [\"groups is not a prop\", '<ConversationList sections={[{ id: \"pinned\", title: \"Pinned\" }]} items={[{ ...row, section: \"pinned\" }]}>'],\n          stray !== undefined && [\n            `the row \"${stray.id}\" names section \"${String(stray.section)}\", which is not in sections, so it shows first`,\n            `<ConversationList sections={[{ id: \"${String(stray.section)}\", title: \"Pinned\" }]}>`,\n          ],\n          sections.some((section) => section.open !== undefined) &&\n            onSectionOpenChange === undefined && [\"a section's open is set without onSectionOpenChange, so its header cannot open or close it\", \"<ConversationList onSectionOpenChange={(id, open) => setOpen(id, open)}>\"],\n        ]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n\n  const isOpen = (section: ConversationListSection) => openOf(section, opened);\n  const toggle = (section: ConversationListSection, next: boolean) => {\n    setOpened({ ...opened, [section.id]: next });\n    onSectionOpenChange?.(section.id, next);\n  };\n\n  // The rows in the order they show: those with no section first, then each section's under its header. Worked out\n  // once per change to the rows, the sections or what is open, not on every scroll's render of a long list.\n  const { loose, groupsShown, keys } = useMemo(() => {\n    const loose = items.filter((item) => !known.has(item.section));\n    const groupsShown = sections.map((section) => ({ section, rows: items.filter((item) => item.section === section.id) })).filter((group) => group.rows.length > 0);\n    const keys = [\n      ...loose.map((item) => `row:${item.id}`),\n      ...groupsShown.flatMap(({ section, rows }) => [`section:${section.id}`, ...(openOf(section, opened) ? rows : []).map((item) => `row:${item.id}`)]),\n    ];\n    return { loose, groupsShown, keys };\n  }, [items, sections, known, opened]);\n  const current = `row:${String(selectedId)}`;\n  const tabStop = keys.includes(active) ? active : keys.includes(current) ? current : keys[0];\n\n  const heights = measured?.density === density ? measured.heights : noHeights;\n  const { offsets, total } = useMemo(() => place(keys, heights, estimates[density]), [keys, heights, density]);\n  // The first frame counts its rows from the estimates alone: counting from measured heights would grow the window after the first measurement.\n  const guessed = place(keys, noHeights, Math.min(estimates[density], shortest)).offsets;\n  // Stryker disable next-line EqualityOperator: a slot that starts exactly where the first view ends may render or not, and the first layout corrects it.\n  const firstRows = guessed.filter((offset) => offset < firstView).length;\n  const [start, end] = range ?? [0, firstRows];\n  const indexes = useMemo(() => new Map(keys.map((key, index) => [key, index])), [keys]);\n  const kept = useMemo(() => new Set([tabStop, current, reach]), [tabStop, current, reach]);\n  const rendered = (key: string) => {\n    const index = indexes.get(key)!;\n    if (!windowed) return true;\n    return (index >= start && index < end) || kept.has(key);\n  };\n  // In a windowed list a control's slot is placed where it would be, with the gap before it as padding, and says\n  // where it is in its list, since screen readers cannot count the rows that are not there.\n  // Until the first measurement, and while the view has not moved, the slots of the first window sit in normal flow, so\n  // their places are the ones the measured heights give: nothing estimated lies above a row in view.\n  const flow = windowed && start === 0;\n  const slot = (key: string) => {\n    const index = indexes.get(key)!;\n    const gap = index > 0 && (kindOf(key) === \"section\" ? \"pt-2.5\" : \"pt-0.5\");\n    // Stryker disable next-line EqualityOperator: a kept row at index end follows the last flowed row, so flow and its absolute place agree.\n    if (flow && index < end) return { className: cn(gap), style: undefined };\n    return { className: cn(\"absolute inset-x-0\", gap), style: { top: offsets[index] } };\n  };\n  const register = useCallback((key: string, node: HTMLButtonElement | null) => {\n    if (node) controls.current.set(key, node);\n    else controls.current.delete(key);\n  },\n  // Stryker disable next-line ArrayDeclaration: the callback reads only a ref, so any constant list keeps it stable.\n  []);\n  const controlRef = (key: string) => (node: HTMLButtonElement | null) => register(key, node);\n\n  // The list's view, from its top: the part no scrolling box around it, or the window, clips.\n  const view = () => {\n    const box = listRef.current!.getBoundingClientRect();\n    let top = 0;\n    let bottom = innerHeight;\n    for (const clip of clips.current!) {\n      const edges = clip.getBoundingClientRect();\n      top = Math.max(top, edges.top);\n      bottom = Math.min(bottom, edges.bottom);\n    }\n    return { top: top - box.top, bottom: bottom - box.top };\n  };\n  // Renders the slots the view and its overscan reach.\n  const update = () => {\n    const { offsets: at, total: height, range: was } = latest.current!;\n    const { top, bottom } = view();\n    // A scroll that moved the view without a scroll event reaching the list, as a focus scroll can, counts too.\n    // Stryker disable next-line ConditionalExpression: the scroll event, the key path and a size change also set it.\n    if (scroller.current!.scrollTop !== seenTop.current) scrolled.current = true;\n    seenTop.current = scroller.current!.scrollTop;\n    let first = at.length;\n    let last = 0;\n    at.forEach((offset, index) => {\n      if ((at[index + 1] ?? height) > top - overscan && offset < bottom + overscan) {\n        first = Math.min(first, index);\n        last = index + 1;\n      }\n    });\n    // Until the first scroll, rows rendered on the first frame stay: measuring narrows the window, and a row or section\n    // that unmounts after the first paint would make the first frame differ from the finished screen.\n    // Stryker disable next-line EqualityOperator: an empty window (nothing reaches the view) keeps the last one either way.\n    // Stryker disable next-line ConditionalExpression: with an empty range the unions below leave the window as it was.\n    if (!scrolled.current && last > 0) {\n      // Stryker disable next-line MethodExpression: the first frame's window starts at the top, so min and max agree until a scroll.\n      first = Math.min(first, was[0]);\n      last = Math.max(last, was[1]);\n      // A first window that already covers the view does not grow once measured rows are shorter than the estimates.\n      // Stryker disable next-line ConditionalExpression: a window ending exactly at the view's bottom covers it either way.\n      // Stryker disable next-line EqualityOperator: a window ending exactly at the view's bottom covers it either way.\n      if ((at[was[1]] as number) >= bottom) last = was[1];\n    }\n    if (was[0] !== first || was[1] !== last) setRange([first, last]);\n  };\n  // Measures the rendered slots; says whether a height changed.\n  const measure = () => {\n    const { keys: order, offsets: at, total: height, heights: had } = latest.current!;\n    let next: Map<string, number> | undefined;\n    for (const [key, control] of controls.current) {\n      const size = control.parentElement!.offsetHeight;\n      if (size && had.get(key) !== size) (next ??= new Map(had)).set(key, size);\n    }\n    if (!next) return false;\n    // The first slot measured before (which the person has seen) that ends below the view's top stays where it\n    // shows, so the rows measured above it never push the rows in view.\n    const { top } = view();\n    // Stryker disable next-line EqualityOperator: a slot that ends exactly at the view's top keeps the next one where it is too.\n    const anchor = order.findIndex((key, index) => had.has(key) && (at[index + 1] ?? height) > top);\n    scroller.current!.scrollTop += (place(order, next, estimates[density]).offsets[anchor] ?? 0) - (at[anchor] ?? 0);\n    setMeasured({ density, heights: next });\n    return true;\n  };\n  const focusKey = (key: string) => {\n    const control = controls.current.get(key);\n    if (!control) {\n      focusNext.current = key;\n      setReach(key);\n    } else if (windowed) {\n      // A rendered row has been measured, so it shows now and stays where it shows; a key that leaves focus where it\n      // is (Home on the first row) brings no render to wait for.\n      control.focus({ preventScroll: true });\n      reveal(controls.current, key, \"nearest\");\n      // The scroll's own event may land late, so the window follows the key's scroll from the next frame.\n      // Stryker disable next-line BooleanLiteral: the frame's own scrollTop check sets it too.\n      scrolled.current = true;\n      // Stryker disable next-line CallExpression: cancelling a frame that already ran is a no-op.\n      cancelAnimationFrame(selectionFrame.current);\n      // Stryker disable next-line ArrowFunction: the observer's next callback makes the same sync.\n      selectionFrame.current = requestAnimationFrame(() => sync.current!());\n    } else control.focus();\n  };\n\n  // The boxes that clip the list, which scroll it and whose size sets its view, and the box that scrolls it.\n  // Nothing is read while the list mounts: the first rows render in flow at their estimates, and the observer's first\n  // callback, which comes with the page already laid out, finds the boxes, measures the rows and sets the window.\n  useLayoutEffect(() => {\n    if (!windowed) return;\n    const list = listRef.current!;\n    let found: HTMLElement[] = [];\n    let frame = 0;\n    const onScroll = (event: Event) => {\n      // Stryker disable next-line ConditionalExpression: a scroll elsewhere would only read a view that has not changed.\n      if (event.target === document || found.includes(event.target as HTMLElement)) {\n        scrolled.current = true;\n        sync.current!();\n      }\n    };\n    const onResize = () => {\n      // Stryker disable next-line ConditionalExpression: finding the clips again would find the same boxes, which `found` already holds\n      if (!clips.current) {\n        let scrolls: HTMLElement | undefined;\n        for (let node = list.parentElement; node; node = node.parentElement) {\n          const { overflowY } = getComputedStyle(node);\n          if (overflowY === \"visible\") continue;\n          found.push(node);\n          // Stryker disable next-line LogicalOperator: the window reads the list's rectangle against each clip, so which scroller is kept changes only where scroll events are filtered\n          // Stryker disable next-line ConditionalExpression: same reason, the kept scroller does not change what the window shows\n          if (!scrolls && /auto|scroll/.test(overflowY)) scrolls = node;\n        }\n        clips.current = found;\n        scroller.current = scrolls ?? document.scrollingElement;\n        document.addEventListener(\"scroll\", onScroll, { capture: true });\n        addEventListener(\"resize\", onResize);\n        // Boxes above the list are observed after this frame, or the observer reports their first sizes as a loop.\n        frame = requestAnimationFrame(() => {\n          for (const clip of found) resizes.observe(clip);\n        });\n      }\n      // A change in the view's size, as opposed to the rows', lets the window narrow again.\n      const size = `${innerHeight}:${clips.current.map((clip) => clip.clientHeight).join()}`;\n      if (viewSize.current && viewSize.current !== size) scrolled.current = true;\n      viewSize.current = size;\n      sync.current!();\n    };\n    const resizes = new ResizeObserver(onResize);\n    // Stryker disable next-line CallExpression: the rows observed on the first sync also deliver the first callback; observing the list only adds its own later resizes\n    resizes.observe(list);\n    rows.current = resizes;\n    return () => {\n      rows.current = null;\n      synced.current = null;\n      clips.current = null;\n      // Stryker disable next-line ArrayDeclaration: the effect re-runs with a fresh array; cleanup only drops references\n      found = [];\n      // Stryker disable next-line CallExpression: a frame cancelled late observes boxes of a disconnected observer, which does nothing\n      cancelAnimationFrame(frame);\n      document.removeEventListener(\"scroll\", onScroll, { capture: true });\n      removeEventListener(\"resize\", onResize);\n      resizes.disconnect();\n    };\n  }, [windowed]);\n  useLayoutEffect(() => {\n    latest.current = { keys, offsets, total, range: [start, end], heights };\n    // The open row is tracked in a short list too, so a list that grows long, or long again, sees no row newly opened.\n    const opened = revealed.current;\n    revealed.current = current;\n    if (!windowed) return;\n    // The open conversation's row comes to the middle of the view when it opens out of view, as it may not have\n    // rendered yet; one that opens in view stays where it is.\n    if (opened !== current) opening.current = true;\n    // Measures what rendered, moves focus to the row the keyboard reached once it has, keeps a row that must show in\n    // view while the heights around it settle, and renders the slots in view; on every render, scroll and resize.\n    sync.current = () => {\n      if (opening.current) {\n        opening.current = false;\n        const row = controls.current.get(current)?.getBoundingClientRect();\n        const listTop = listRef.current!.getBoundingClientRect().top;\n        const { top, bottom } = view();\n        if (row && (row.top - listTop < top || row.bottom - listTop > bottom)) {\n          keepInView.current = { key: current, block: \"center\" };\n        }\n      }\n      const changed = measure();\n      const reached = focusNext.current && controls.current.get(focusNext.current);\n      if (reached) {\n        keepInView.current = { key: focusNext.current!, block: \"nearest\" };\n        focusNext.current = null;\n        reached.focus({ preventScroll: true });\n      }\n      if (keepInView.current) reveal(controls.current, keepInView.current.key, keepInView.current.block);\n      // A row to keep in view stays so until nothing new is measured, since rows measured around it may move it.\n      if (!changed) keepInView.current = null;\n      update();\n    };\n    // A sync reads layout, which inside a commit lays the page out at once, so a render runs it only when what it\n    // places changed: the rows, the window, the heights, the open, reached or focusable row. A row that changes size otherwise\n    // (new text) is reported by the observer, once the page is laid out, where reads are free.\n    const places = JSON.stringify([keys, start, end, density, reach]);\n    const inputs = JSON.stringify([places, current, tabStop]);\n    for (const control of controls.current.values()) rows.current!.observe(control.parentElement!);\n    if (synced.current?.inputs === inputs && synced.current.heights === heights) return;\n    // Stryker disable next-line ConditionalExpression: a changed place with equal heights also gets its sync from the observer and the scroll listener, so skipping it in the commit shows in no test.\n    const selectionOnly = !focusNext.current && synced.current?.places === places && synced.current.heights === heights;\n    synced.current = { inputs, places, heights };\n    // Switching the open row moves nothing: its reveal, if it needs one, reads after the commit instead of in it.\n    if (selectionOnly) {\n      // Stryker disable next-line CallExpression: cancelling a frame that already ran is a no-op; it matters only when a newer switch arrives first.\n      cancelAnimationFrame(selectionFrame.current);\n      // Stryker disable next-line ConditionalExpression,LogicalOperator,ArrowFunction,EqualityOperator: the frame only repeats a reveal the observer's next callback also makes, so tests cannot tell the two apart.\n      if ((opening.current || keepInView.current) && clips.current) selectionFrame.current = requestAnimationFrame(() => sync.current!());\n      return;\n    }\n    // Until the observer's first callback has found the boxes around the list, nothing is read. Nor is it while the window's\n    // slots sit in normal flow, where no row's place waits on a measurement: the rows that rendered are observed, and their\n    // first sizes come to the observer once the page is laid out, as a mounting list's do. A row the keyboard reached still\n    // takes focus in the commit.\n    if (clips.current && (!flow || focusNext.current)) sync.current();\n  });\n\n  // The row menu that opened, with Menu's code, and the row it belongs to: by its key, as the row may stop being drawn.\n  const [menu, setMenu] = useState<{ M: MenuModule; key: string; name: string; entries: readonly MenuEntry[]; anchor: MenuAnchor; open: boolean } | null>(null);\n  const itemOf = (key: string | undefined) => items.find((item) => `row:${item.id}` === key);\n  // The key of the row an event came from: the button around it, as the list registered it.\n  const rowAt = (target: EventTarget) => {\n    const button = (target as Element).closest(\"button\");\n    for (const [key, control] of controls.current) if (control === button) return key;\n    return undefined;\n  };\n  const openMenu = (item: ConversationListItem, key: string, anchor: MenuAnchor) => {\n    const open = (M: MenuModule) => setMenu({ M, key, name: item.name ?? (item.title as string), entries: item.menu!, anchor, open: true });\n    // Loaded already (the first row with a menu loads it), it opens within the event, before the next frame.\n    if (menuLoaded) flushSync(() => open(menuLoaded!));\n    else void loadMenu().then(open);\n  };\n  // Where focus went outside the open menu: a chosen item that moved it to a field. Menu puts it back there as it closes.\n  // Base UI's focus guards beside the menu are the menu's own, as Menu counts them: focus that meets one has not moved away,\n  // and counting it left focus on the page's body when Escape closed the menu before the guard had gone.\n  const movedAway = useRef<Element | null>(null);\n  const menuOpen = menu?.open === true;\n  useEffect(() => {\n    if (!menuOpen) return;\n    movedAway.current = null;\n    const away = (event: FocusEvent) => {\n      const target = event.target as Element;\n      if (target.closest('[data-ouro=\"menu-positioner\"], [data-base-ui-focus-guard]') === null) movedAway.current = target;\n    };\n    document.addEventListener(\"focusin\", away);\n    // Stryker disable next-line ArrowFunction,StringLiteral: a listener left from an earlier opening records only what the next opening clears as it starts; removing it frees memory only.\n    return () => document.removeEventListener(\"focusin\", away);\n  }, [menuOpen]);\n  const closeMenu = () => {\n    const key = menu!.key;\n    setMenu((previous) => previous && { ...previous, open: false });\n    // Back to the row once Menu has finished closing, unless the chosen item moved focus elsewhere; drawn again first if it\n    // was scrolled out of the window.\n    setTimeout(() => {\n      if (movedAway.current?.isConnected) return;\n      const active = document.activeElement as Element;\n      if (active === document.body || active.closest('[data-ouro=\"menu-positioner\"]') !== null) focusKey(key);\n    });\n  };\n  // A finger resting on a row: where, and the timer that opens its menu. The click that ends a press that opened one is the menu's.\n  const press = useRef<{ x: number; y: number; timer: ReturnType<typeof setTimeout> } | null>(null);\n  const pressed = useRef(false);\n  const endPress = () => {\n    if (press.current) clearTimeout(press.current.timer);\n    press.current = null;\n  };\n  const onPointerDown = (event: PointerEvent<HTMLUListElement>) => {\n    endPress();\n    pressed.current = false;\n    if (event.pointerType === \"mouse\") return;\n    const key = rowAt(event.target);\n    const item = itemOf(key);\n    if (item === undefined || !hasMenu(item)) return;\n    const { clientX: x, clientY: y } = event;\n    press.current = {\n      x,\n      y,\n      timer: setTimeout(() => {\n        press.current = null;\n        pressed.current = true;\n        openMenu(item, key!, { x, y });\n      }, LONG_PRESS),\n    };\n  };\n  const onPointerMove = (event: PointerEvent<HTMLUListElement>) => {\n    if (press.current && Math.hypot(event.clientX - press.current.x, event.clientY - press.current.y) > PRESS_SLOP) endPress();\n  };\n  const onContextMenu = (event: MouseEvent<HTMLUListElement>) => {\n    const key = rowAt(event.target);\n    const item = itemOf(key);\n    if (item === undefined || !hasMenu(item)) return;\n    event.preventDefault();\n    openMenu(item, key!, { x: event.clientX, y: event.clientY });\n  };\n  const onClickCapture = (event: MouseEvent<HTMLUListElement>) => {\n    if (!pressed.current) return;\n    pressed.current = false;\n    event.preventDefault();\n    event.stopPropagation();\n  };\n  // Stryker disable next-line MethodExpression: Menu's code, once loaded by any list, stays loaded, so no test can tell when this one asked for it.\n  const withMenus = items.some(hasMenu);\n  // Stryker disable next-line CallExpression,ArrowFunction,BlockStatement,ConditionalExpression,ArrayDeclaration: Menu's code, once loaded by any list, stays loaded, so no test can tell when this one asked for it.\n  useLayoutEffect(() => {\n    // Stryker disable next-line ConditionalExpression: Menu's code, once loaded by any list, stays loaded, so no test can tell when this one asked for it.\n    if (withMenus) void loadMenu();\n  },\n  // Stryker disable next-line ArrayDeclaration: Menu's code, once loaded by any list, stays loaded, so no test can tell when this one asked for it.\n  [withMenus]);\n\n  const move = (event: KeyboardEvent<HTMLButtonElement>, key: string) => {\n    // Shift+F10 and the Menu key open a row's menu beside it, as a right-click does at the pointer.\n    if ((event.key === \"F10\" && event.shiftKey) || event.key === \"ContextMenu\") {\n      // A row's own key names an item drawn from the items now.\n      const item = itemOf(key)!;\n      if (!hasMenu(item)) return;\n      event.preventDefault();\n      return openMenu(item, key, frozen(event.currentTarget));\n    }\n    const to = moves[event.key];\n    if (!to) return;\n    event.preventDefault();\n    focusKey(keys[to(keys.indexOf(key), keys.length - 1)]!);\n  };\n  // The rows are memoised, so they call the latest handlers through these stable ones.\n  // Stryker disable next-line ObjectLiteral: the layout effect below sets the handlers before any row can call them.\n  const handlers = useRef({ onSelect, move });\n  useLayoutEffect(() => {\n    handlers.current = { onSelect, move };\n  });\n  const onPick = useCallback((id: string, event: MouseEvent<HTMLButtonElement>) => {\n    const { onSelect: select } = handlers.current;\n    if (select.length > 1) select(id, event);\n    else (select as (id: string) => void)(id);\n  },\n  // Stryker disable next-line ArrayDeclaration: the callback reads only a ref, so any constant list keeps it stable.\n  []);\n  // Stryker disable next-line ArrayDeclaration: the callback reads only a ref, so any constant list keeps it stable.\n  const onKey = useCallback((event: KeyboardEvent<HTMLButtonElement>, key: string) => handlers.current.move(event, key), []);\n\n  const rowFor = (item: ConversationListItem, position: number, count: number) => {\n    const key = `row:${item.id}`;\n    return (\n      <Row\n        key={item.id}\n        item={item}\n        rowKey={key}\n        density={density}\n        unreadLabel={unreadLabel}\n        draftLabel={draftLabel}\n        selected={item.id === selectedId}\n        tabStop={key === tabStop}\n        windowed={windowed}\n        top={windowed ? slot(key).style?.top : 0}\n        slotClass={windowed ? slot(key).className : undefined}\n        position={position}\n        count={count}\n        register={register}\n        onPick={onPick}\n        onKey={onKey}\n        onActive={setActive}\n      />\n    );\n  };\n\n  const outer = loose.length + groupsShown.length;\n  return (\n    <div {...rest} data-ouro=\"conversation-list\" data-density={density} className={cn(\"box-border min-w-0\", className)}>\n      {items.length === 0 ? (\n        <p className={cn(\"m-0 px-3 py-2 text-sm\", quiet)}>{empty}</p>\n      ) : (\n        // Focus moving to another control sets it again; leaving the list hands the stop back to the open conversation.\n        // The window losing focus blurs the row too, but focus stays on it, and so do the stop and the row.\n        <ul\n          ref={listRef}\n          aria-label={label}\n          onBlur={() => {\n            // Stryker disable next-line StringLiteral: no control's key is this string, which is all \"nothing has focus\" needs.\n            if (!listRef.current!.contains(document.activeElement)) setActive(\"\");\n          }}\n          onContextMenu={onContextMenu}\n          onPointerDown={onPointerDown}\n          onPointerMove={onPointerMove}\n          onPointerUp={endPress}\n          onPointerCancel={endPress}\n          onClickCapture={onClickCapture}\n          className={cn(listClass, windowed && \"relative block\")}\n          style={windowed ? { height: total } : undefined}\n        >\n          {loose.map((item, index) => rendered(`row:${item.id}`) && rowFor(item, index + 1, outer))}\n          {groupsShown.map(({ section, rows }, index) => {\n            const key = `section:${section.id}`;\n            const open = isOpen(section);\n            const groupId = `${baseId}-section-${index}`;\n            const shownRows = open ? rows.flatMap((item, at) => (rendered(`row:${item.id}`) ? [rowFor(item, at + 1, rows.length)] : [])) : [];\n            if (windowed && !rendered(key) && shownRows.length === 0) return null;\n            const header = (\n              <button\n                ref={controlRef(key)}\n                type=\"button\"\n                data-ouro-control=\"conversation-list\"\n                data-ouro-part=\"section\"\n                aria-expanded={open}\n                aria-controls={open ? groupId : undefined}\n                tabIndex={key === tabStop ? 0 : -1}\n                onClick={() => toggle(section, !open)}\n                onKeyDown={(event) => {\n                  if ((event.key === \"ArrowRight\" && !open) || (event.key === \"ArrowLeft\" && open)) {\n                    event.preventDefault();\n                    toggle(section, !open);\n                  } else move(event, key);\n                }}\n                onFocus={() => setActive(key)}\n                className={cn(controlClass, headerClass)}\n              >\n                <Chevron open={open} />\n                <span data-ouro-conversation-section-title=\"\" className=\"min-w-0 truncate font-semibold\">\n                  {section.title}\n                </span>\n                {shown(section.note) && (\n                  <span data-ouro-conversation-section-note=\"\" className={cn(\"min-w-0 max-w-max flex-[1_1_0%] truncate text-xs\", quiet)}>\n                    {section.note}\n                  </span>\n                )}\n                {!open && rows.some((item) => item.unread) && (\n                  <span className=\"ms-auto flex shrink-0 items-center\">\n                    <UnreadDot data-ouro-conversation-unread=\"\" label={unreadLabel} />\n                  </span>\n                )}\n              </button>\n            );\n            return (\n              <li\n                key={key}\n                data-ouro-conversation-section={section.id}\n                aria-posinset={windowed ? loose.length + index + 1 : undefined}\n                aria-setsize={windowed ? outer : undefined}\n                className={windowed ? \"m-0 p-0\" : \"m-0 p-0 not-first:mt-2\"}\n              >\n                {!windowed ? header : rendered(key) && <div {...slot(key)}>{header}</div>}\n                {open &&\n                  // Stryker disable next-line ConditionalExpression,EqualityOperator: an empty <div> and an empty <ul> differ only for assistive tech, which the accessibility-tree test covers for open sections with rows outside the window\n                  (shownRows.length > 0 ? (\n                    <ul id={groupId} aria-label={section.title} className={windowed ? \"m-0 list-none p-0\" : cn(listClass, \"mt-0.5\")}>\n                      {shownRows}\n                    </ul>\n                  ) : (\n                    // The section's rows are all outside the window: no list, so none reads as empty, but the header's aria-controls still finds this.\n                    <div id={groupId} />\n                  ))}\n              </li>\n            );\n          })}\n        </ul>\n      )}\n      {menu !== null && <menu.M.Menu anchor={menu.anchor} open={menu.open} onOpenChange={(open) => !open && closeMenu()} aria-label={menu.name} items={menu.entries} />}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/conversation-list/conversation-list.tsx"
    }
  ],
  "docs": "A list of conversations to choose from: each row shows the avatar, the title, when the latest message arrived and a line of it, and marks unread conversations with a bold title and a dot. Import: import { ConversationList } from \"@/components/ouro/conversation-list/conversation-list\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: avatar, kbd, menu, skeleton, unread-dot, the helpers they import in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/conversation-list.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}