{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "emoji-picker",
  "title": "EmojiPicker",
  "description": "An emoji picker for reactions and for putting emoji into text.",
  "registryDependencies": [
    "@ouro/button",
    "@ouro/emoji",
    "@ouro/lib-announce",
    "@ouro/lib-class-name-check",
    "@ouro/lib-cn",
    "@ouro/lib-env",
    "@ouro/lib-open-mode",
    "@ouro/lib-refs",
    "@ouro/lib-server-element",
    "@ouro/lib-use-dev-messages",
    "@ouro/lib-use-sheet-presentation",
    "@ouro/popover",
    "@ouro/text-field"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/emoji-picker/emoji-picker-styles.ts",
      "content": "import { emojiSkinTones, matchWords, type EmojiSkinTone } from \"@/registry/ouro/components/ouro/emoji/emoji-styles\";\n\nexport {\n  barButtonClass,\n  barClass,\n  bodyClass,\n  cellClass,\n  COLUMNS,\n  FIRST_CELLS,\n  emojiSkinTones,\n  fillCount,\n  gridClass,\n  headingClass,\n  matchEmoji,\n  panelClass,\n  previewClass,\n  previewGlyphClass,\n  quickClass,\n  scrollerClass,\n  skinToneNames,\n  stepInRow,\n  toned,\n  toneOptionClass,\n};\nexport type { EmojiSkinTone, ToneableEmoji };\n\n// Class strings, value lists and helpers for EmojiPicker, apart from the component so its file\n// exports only components (React Fast Refresh). Class strings are literal so the app's Tailwind\n// finds them. The skin tones come from Emoji, which draws a catalogue's images.\n\n/**\n * What screen readers hear for each skin tone, unless the app passes its own words. @internal\n *\n * @claim \"hear for each skin tone\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker skin tones > opens the tones as a radio group on the checked tone, and changes the tone live with the arrow keys)\n * @claim \"hear for each skin tone\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker labels > takes every word it shows or speaks from its props, for other languages)\n */\nconst skinToneNames: Readonly<Record<EmojiSkinTone, string>> = {\n  default: \"Default\",\n  light: \"Light\",\n  \"medium-light\": \"Medium-light\",\n  medium: \"Medium\",\n  \"medium-dark\": \"Medium-dark\",\n  dark: \"Dark\",\n};\n\n/** Emoji per row in the grid. @internal */\nconst COLUMNS = 8;\n\n/** The grid's cells fetched first, at high priority: about what the picker shows as it opens. @internal */\nconst FIRST_CELLS = 8 * COLUMNS;\n\n/** The part of an emoji the tone and the search read. @internal */\ninterface ToneableEmoji {\n  emoji: string;\n  name: string;\n  keywords?: readonly string[] | undefined;\n  skinTones?: boolean | readonly string[] | undefined;\n  /** A catalogue emoji's shortcodes, which the search matches whole or by their words. */\n  shortcodes?: readonly string[] | undefined;\n  /** A catalogue emoji's text, which a search for that text finds. */\n  text?: string | undefined;\n}\n\n/**\n * The emoji in a skin tone: the toned form the app listed, or Unicode's modifier after the\n * first character (dropping the variation selector that follows it, as the toned form has\n * none). An emoji without skin tones, or the default tone, keeps its own form. @internal\n *\n * @claim \"the toned form the app listed\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker skin tones > puts the tone into what it chooses, by Unicode's modifier or the toned forms the app listed)\n * @claim \"the toned form the app listed\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker skin tones > keeps a toned form the app left out as the emoji itself)\n */\nfunction toned(item: Pick<ToneableEmoji, \"emoji\" | \"skinTones\">, tone: EmojiSkinTone): string {\n  const index = emojiSkinTones.indexOf(tone);\n  if (!item.skinTones || index <= 0) return item.emoji;\n  if (item.skinTones !== true) return item.skinTones[index - 1] ?? item.emoji;\n  const [first, ...rest] = Array.from(item.emoji);\n  const tail = rest[0] === \"\\uFE0F\" ? rest.slice(1) : rest;\n  return `${first}${String.fromCodePoint(0x1f3fa + index)}${tail.join(\"\")}`;\n}\n\n/**\n * Whether an emoji matches the search: every word typed starts a word of its name, keywords or\n * shortcodes (or a whole shortcode), ignoring case and accents and colons around a shortcode, or\n * the search is the emoji itself or its text. @internal\n *\n * @claim \"every word typed starts\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker search > matches the start of any word in the name or keywords, ignoring case and accents, and hides the categories)\n * @claim \"every word typed starts\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker search > finds an emoji pasted into the search, and lists one found twice only once)\n * @claim \"or a whole shortcode\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > searches by shortcode, with or without colons, by keyword and by the emoji's text)\n */\nfunction matchEmoji(item: ToneableEmoji, query: string): boolean {\n  const typed = query.trim();\n  if (typed === item.emoji || (item.text !== undefined && typed.replace(/\\uFE0F/g, \"\") === item.text.replace(/\\uFE0F/g, \"\"))) return true;\n  return matchWords([item.name, ...(item.keywords ?? []), ...(item.shortcodes ?? [])], typed);\n}\n\n/**\n * Where a key moves focus in a row of `count` buttons from `at`: the arrows step (the other\n * way in a right-to-left page) and stop at the ends, Home and End go to the ends. Any other\n * key is not the row's. @internal\n */\nfunction stepInRow(key: string, at: number, count: number, rtl: boolean): number | undefined {\n  const forward = rtl ? \"ArrowLeft\" : \"ArrowRight\";\n  const back = rtl ? \"ArrowRight\" : \"ArrowLeft\";\n  if (key === forward) return Math.min(at + 1, count - 1);\n  if (key === back) return Math.max(at - 1, 0);\n  if (key === \"Home\") return 0;\n  if (key === \"End\") return count - 1;\n  return undefined;\n}\n\n/**\n * Puts a count into a label: \"{count} emoji\" with 3 is \"3 emoji\". @internal\n *\n * @claim \"Puts a count into\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker labels > takes every word it shows or speaks from its props, for other languages)\n * @claim \"Puts a count into\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker search > matches the start of any word in the name or keywords, ignoring case and accents, and hides the categories)\n */\nfunction fillCount(template: string, count: number): string {\n  return template.replaceAll(\"{count}\", String(count));\n}\n\n/** The panel inside the popover or the sheet. @internal */\nconst panelClass = \"box-border flex w-full min-w-0 flex-col gap-2 p-1\";\n\n/** The category bar: its buttons spread across the panel, or scrolling sideways when they do not fit, over a rule. @internal */\nconst barClass =\n  \"flex min-w-0 shrink-0 items-center justify-between gap-0.5 overflow-x-auto [scrollbar-width:none] \" +\n  \"border-0 border-b border-solid border-border pb-1\";\n\n/**\n * The quick row: on the grid's eight columns, so its emoji line up with the grid's, over a rule. @internal\n *\n * @claim \"on the grid's eight columns\" registry/ouro/components/ouro/emoji-picker/emoji-picker-styles.ts verify:fileLine(registry/ouro/components/ouro/emoji-picker/emoji-picker-styles.ts, /\"grid shrink-0 grid-cols-\\[repeat\\(8,minmax\\(0,1fr\\)\\)\\]/)\n */\nconst quickClass =\n  \"grid shrink-0 grid-cols-[repeat(8,minmax(0,1fr))] justify-items-center border-0 border-b border-solid border-border pb-1\";\n\n/**\n * An emoji: a 40px square, 44px on touch screens, with the native glyph at 24px. Hover tints\n * under a mouse only, and the press scale stops with reduced motion. Focus scrolls it clear of\n * its category's sticky heading. @internal\n *\n * @claim \"a 40px square, 44px\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker on the page > lines its eight columns up across the panel's width)\n * @claim \"a 40px square, 44px\" registry/ouro/components/ouro/emoji-picker/emoji-picker.touch.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.touch.test.tsx::EmojiPicker on a phone > is a bottom sheet whose emoji, categories and tones are 44px touch targets, and a tap chooses)\n * @claim \"a 40px square, 44px\" registry/ouro/components/ouro/emoji-picker/emoji-picker-styles.ts verify:fileLine(registry/ouro/components/ouro/emoji-picker/emoji-picker-styles.ts, /size-10 shrink-0.*pointer-coarse:size-11 rounded-ouro-md border-0 bg-transparent text-2xl/)\n */\nconst cellClass =\n  \"press relative box-border flex size-10 shrink-0 cursor-pointer items-center justify-center m-0 p-0 \" +\n  \"pointer-coarse:size-11 rounded-ouro-md border-0 bg-transparent text-2xl leading-none [-webkit-tap-highlight-color:transparent] \" +\n  \"pointer-fine:hover:bg-accent motion-safe:active:scale-(--ouro-press-scale) scroll-mt-6 scroll-mb-1 \" +\n  \"outline-ring -outline-offset-2 focus-visible:outline-2 focus-visible:outline-solid\";\n\n/**\n * A category button: a square whose icon is grey and faint until it is the category in view,\n * or under a mouse. @internal\n */\nconst barButtonClass =\n  \"press relative box-border flex size-8 shrink-0 cursor-pointer items-center justify-center m-0 p-0 \" +\n  \"pointer-coarse:size-11 rounded-ouro-md border-0 bg-transparent text-lg leading-none text-muted-foreground [-webkit-tap-highlight-color:transparent] \" +\n  \"[&_svg]:size-4 pointer-fine:hover:bg-accent pointer-fine:hover:text-accent-foreground motion-safe:active:scale-(--ouro-press-scale) \" +\n  \"aria-current:bg-accent aria-current:text-accent-foreground \" +\n  \"[&:not([aria-current])>*]:grayscale [&:not([aria-current])>*]:opacity-70 pointer-fine:hover:[&>*]:grayscale-0 pointer-fine:hover:[&>*]:opacity-100 \" +\n  \"[&>*]:transition-opacity [&>*]:duration-(--ouro-duration-fast) [&>*]:ease-(--ouro-ease-out) \" +\n  \"forced-colors:aria-current:bg-[Highlight] forced-colors:aria-current:text-[HighlightText] \" +\n  \"outline-ring -outline-offset-2 focus-visible:outline-2 focus-visible:outline-solid\";\n\n/** A skin tone choice: the emoji in that tone, ringed while it is the chosen one. @internal */\nconst toneOptionClass =\n  \"press relative box-border flex size-9 shrink-0 cursor-pointer items-center justify-center m-0 p-0 \" +\n  \"pointer-coarse:size-11 rounded-full border-2 border-solid border-transparent bg-transparent text-xl leading-none [-webkit-tap-highlight-color:transparent] \" +\n  \"pointer-fine:hover:bg-accent motion-safe:active:scale-(--ouro-press-scale) \" +\n  \"aria-checked:border-primary forced-colors:aria-checked:border-[Highlight] \" +\n  \"outline-ring outline-offset-1 focus-visible:outline-2 focus-visible:outline-solid\";\n\n/**\n * The category bar over the grid, in rows of a fixed height together: while there is a search the grid lies over the\n * bar's row too, which keeps its height unseen, so the panel keeps its size and the search field stays put. @internal\n */\nconst bodyClass = \"relative grid min-h-0 grid-cols-[minmax(0,1fr)] gap-2\";\n\n/** The grid's scrolling area, as tall as its rows. @internal */\nconst scrollerClass = \"relative box-border h-full min-h-0 overflow-y-auto overscroll-contain [scrollbar-gutter:stable]\";\n\n/** A category's heading, which stays at the top while its emoji scroll under it. @internal */\nconst headingClass = \"sticky top-0 z-1 m-0 bg-popover px-1 py-1 text-xs leading-4 font-medium text-muted-foreground\";\n\n/**\n * A category's emoji, eight to a row. @internal\n *\n * @claim \"eight to a row\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker on the page > lines its eight columns up across the panel's width)\n */\nconst gridClass = \"grid grid-cols-[repeat(8,minmax(0,1fr))] justify-items-center\";\n\n/** The name of the emoji in focus, under the grid. @internal */\nconst previewClass =\n  \"flex min-h-10 min-w-0 shrink-0 items-center gap-2 border-0 border-t border-solid border-border pt-2 text-sm leading-5 text-muted-foreground\";\n\n/** The emoji in focus, drawn large beside its name. @internal */\nconst previewGlyphClass = \"text-2xl leading-none\";\n",
      "type": "registry:ui",
      "target": "@components/ouro/emoji-picker/emoji-picker-styles.ts"
    },
    {
      "path": "registry/ouro/components/ouro/emoji-picker/emoji-picker.tsx",
      "content": "\"use client\";\n\nimport {\n  cloneElement,\n  memo,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type JSX,\n  type KeyboardEvent,\n  type MouseEvent,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n} from \"react\";\nimport { announce } from \"@/registry/ouro/lib/ouro/announce\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { checkOpenMode, type TriggerOrOpen } from \"@/registry/ouro/lib/ouro/open-mode\";\nimport { useMergedRef } from \"@/registry/ouro/lib/ouro/refs\";\nimport { serverElement } from \"@/registry/ouro/lib/ouro/server-element\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { useSheetPresentation } from \"@/registry/ouro/lib/ouro/use-sheet-presentation\";\nimport { Button } from \"@/registry/ouro/components/ouro/button/button\";\nimport { Popover, type PopoverAlign, type PopoverPresentation, type PopoverSide } from \"@/registry/ouro/components/ouro/popover/popover\";\nimport { TextField } from \"@/registry/ouro/components/ouro/text-field/text-field\";\nimport { Emoji, type EmojiCatalogue, type EmojiItem } from \"@/registry/ouro/components/ouro/emoji/emoji\";\nimport { catalogueIndex, emojiToken } from \"@/registry/ouro/components/ouro/emoji/emoji-styles\";\nimport {\n  barButtonClass,\n  barClass,\n  bodyClass,\n  cellClass,\n  COLUMNS,\n  emojiSkinTones,\n  FIRST_CELLS,\n  fillCount,\n  gridClass,\n  headingClass,\n  matchEmoji,\n  panelClass,\n  previewClass,\n  previewGlyphClass,\n  quickClass,\n  scrollerClass,\n  skinToneNames as defaultSkinToneNames,\n  stepInRow,\n  toned,\n  toneOptionClass,\n  type EmojiSkinTone,\n} from \"@/registry/ouro/components/ouro/emoji-picker/emoji-picker-styles\";\n\nexport type { EmojiSkinTone } from \"@/registry/ouro/components/ouro/emoji-picker/emoji-picker-styles\";\n\n/** One emoji the picker offers: the character, its name and the words that find it. */\nexport interface EmojiPickerEmoji {\n  /** The emoji as text, drawn with the platform's own emoji font: `\"👍\"`. */\n  emoji: string;\n  /** Its name, which screen readers hear and the search matches: `\"thumbs up\"`. */\n  name: string;\n  /** More words the search matches: `[\"like\", \"yes\", \"approve\"]`. */\n  keywords?: readonly string[] | undefined;\n  /**\n   * It comes in skin tones. `true` puts Unicode's tone modifier after its first character\n   * (right for one person or hand, such as 👍 or 🧑‍💻); for an emoji where that is not\n   * right, such as two people holding hands, list its five toned forms, light to dark.\n   *\n  \n * @claim \"list its five toned forms\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker skin tones > puts the tone into what it chooses, by Unicode's modifier or the toned forms the app listed)\n   */\n  skinTones?: boolean | readonly string[] | undefined;\n}\n\n/** Draws an emoji in the given skin tone: `renderEmoji`. */\nexport type EmojiRender = (item: EmojiPickerEmoji, skinTone: EmojiSkinTone) => ReactNode;\n\n/** A category of emoji: its name, the icon its button shows, and its emoji in order. */\nexport interface EmojiPickerCategory {\n  /** The category's name, shown as its heading and read for its button: `\"Smileys\"`. Unique within the picker. */\n  label: string;\n  /** What its button in the category bar shows: an icon element or image. Defaults to its first emoji, drawn by `renderEmoji` when given. */\n  icon?: ReactNode;\n  /** The category's emoji, in the order they show. */\n  emoji: readonly EmojiPickerEmoji[];\n}\n\n/** What `onSelect` receives: the emoji chosen, in the skin tone it was chosen in. */\nexport interface EmojiPickerSelection {\n  /** The emoji as text, in the chosen skin tone when it has tones: `\"👍🏽\"`. */\n  emoji: string;\n  /** Its name: `\"thumbs up\"`. */\n  name: string;\n  /** The skin tone it was chosen in; `\"default\"` for an emoji without tones. */\n  skinTone: EmojiSkinTone;\n  /** The entry from `categories`, `frequent` or `quick` that was chosen, as the app passed it. */\n  item: EmojiPickerEmoji;\n}\n\n/** What `onSelect` receives from a picker with a `catalogue`: the emoji chosen, in the skin tone it was chosen in. */\nexport interface EmojiPickerCatalogueSelection {\n  /** The emoji's id, or its tone's id when it was chosen in a skin tone: `\"thumbs-up-tone3\"`. Keep it to react with, or among the person's frequently used emoji. */\n  id: string;\n  /** Its name: `\"Thumbs up\"`. */\n  name: string;\n  /**\n   * The text to put into a message for it, `:shortcode:` (its first shortcode, else its id, and\n   * in a tone the tone's id), which `EmojiText` draws as the image: `\":party:\"`.\n   *\n  \n * @claim \"which `EmojiText` draws as the image\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > chooses an emoji: onSelect gets its id, name, token, tone and catalogue item, and the token draws as its image)\n   */\n  token: string;\n  /** The skin tone it was chosen in; `\"default\"` for an emoji without tones. */\n  skinTone: EmojiSkinTone;\n  /** The catalogue's emoji, as the app passed it. */\n  item: EmojiItem;\n}\n\n/** The props an EmojiPicker takes whichever emoji it offers and however it opens. */\nexport interface EmojiPickerBaseProps {\n  /** What the picker is for, which names it for screen readers: `\"Add a reaction\"`, `\"Insert emoji\"`. Required. */\n  label: string;\n  /**\n   * The skin tone the emoji show in, when you keep it (in the person's settings, say). Pair it\n   * with `onSkinToneChange`. Without it, the picker remembers the tone while it is mounted.\n   */\n  skinTone?: EmojiSkinTone | (string & { 'Use \"default\", \"light\", \"medium-light\", \"medium\", \"medium-dark\" or \"dark\"': never }) | undefined;\n  /** Called with the new skin tone when the person picks one, so the app can keep it. */\n  onSkinToneChange?: ((skinTone: EmojiSkinTone) => void) | undefined;\n  /**\n   * `auto`, the default, is a popover from 640px up and a bottom sheet below. `popover` stays\n   * beside the trigger at every width; `sheet` is always a bottom sheet.\n   * @default \"auto\"\n  \n * @claim \"a popover from 640px up\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker opening and closing > is a bottom sheet below 640px, filling its width, and a popover from 640px up)\n  \n * @claim \"beside the trigger at every width\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker opening and closing > stays a popover on a phone with presentation popover, and falls back to it for an unknown presentation)\n  \n * @claim \"is always a bottom sheet\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker opening and closing > is a sheet at every width with presentation sheet)\n   */\n  presentation?: PopoverPresentation | (string & { 'Use \"auto\", \"popover\" or \"sheet\"': never }) | undefined;\n  /**\n   * The side of the trigger the popover sits on; it flips when there is no room. @default \"bottom\"\n   *\n  \n * @claim \"it flips when there is no room\" https://base-ui.com/react/components/popover verify:urlOk(https://base-ui.com/react/components/popover)\n   */\n  side?: PopoverSide | (string & { 'Use \"top\", \"bottom\", \"left\" or \"right\"': never }) | undefined;\n  /** How the popover lines up with the trigger along that side. @default \"center\" */\n  align?: PopoverAlign | (string & { 'Use \"start\", \"center\" or \"end\": left is \"start\", right is \"end\"': never }) | undefined;\n  /** The search field's label and placeholder. @default \"Search emoji\" */\n  searchLabel?: string | undefined;\n  /** The heading of the frequently used emoji. @default \"Frequently used\" */\n  frequentLabel?: string | undefined;\n  /** What screen readers hear for the `quick` row. @default \"Quick reactions\" */\n  quickLabel?: string | undefined;\n  /** What screen readers hear for the category bar. @default \"Categories\" */\n  categoriesLabel?: string | undefined;\n  /** The name of the skin tone button and its choices. @default \"Skin tone\" */\n  skinToneLabel?: string | undefined;\n  /**\n   * The name of each skin tone, for other languages.\n   * @default { default: \"Default\", light: \"Light\", \"medium-light\": \"Medium-light\", medium: \"Medium\", \"medium-dark\": \"Medium-dark\", dark: \"Dark\" }\n  \n * @claim \"name of each skin tone\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker labels > takes every word it shows or speaks from its props, for other languages)\n   */\n  skinToneNames?: Readonly<Record<EmojiSkinTone, string>> | undefined;\n  /** The heading of the search results, also announced as they change; `{count}` is the number found. @default \"{count} emoji\" */\n  resultsLabel?: string | undefined;\n  /** What shows, and is announced, when nothing matches the search. @default \"No emoji found\" */\n  noResultsLabel?: string | undefined;\n  /** The label of the popover's close button, which only screen-reader and keyboard users see. @default \"Close\" */\n  closeLabel?: string | undefined;\n  /** Layout only, applied to the panel inside the popover: width (`w-96`). Appearance classes warn in development. */\n  className?: string | undefined;\n\n  /** Not a prop. A chosen emoji calls `onSelect`: `<EmojiPicker onSelect={(selection) => insert(selection.emoji)}>`. */\n  onEmojiSelect?: { 'Use onSelect={(selection) => insert(selection.emoji)}': never };\n  /** Not a prop. A chosen emoji calls `onSelect`: `<EmojiPicker onSelect={(selection) => insert(selection.emoji)}>`. */\n  onEmojiClick?: { 'Use onSelect={(selection) => insert(selection.emoji)}': never };\n  /** Not a prop. The emoji come by category in `categories`: `<EmojiPicker categories={[{ label, emoji }]}>`. */\n  data?: { 'Use categories={[{ label: \"Smileys\", emoji: [{ emoji, name }] }]}': never };\n  /** Not a prop. Ouro UI uses `open` with `onOpenChange`: `<EmojiPicker open={open} onOpenChange={setOpen} anchor={buttonRef}>`. */\n  isOpen?: { 'Use <EmojiPicker open={open} onOpenChange={setOpen} anchor={buttonRef}>': never };\n  /** Not a prop. `onOpenChange(false)` fires on close: `<EmojiPicker open={open} onOpenChange={setOpen} anchor={buttonRef}>`. */\n  onClose?: { 'Use <EmojiPicker open={open} onOpenChange={setOpen} anchor={buttonRef}>': never };\n}\n\n/** An EmojiPicker of the platform's own emoji: the app passes them by category as text. */\nexport type EmojiPickerUnicodeProps = {\n  /**\n   * Every emoji the picker offers, by category, in order. The app supplies them, so it picks the set, the names and the language.\n   *\n  \n * @claim \"Every emoji the picker offers\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker content > shows the quick row, the frequently used emoji and every category, each emoji named for screen readers)\n   */\n  categories: readonly EmojiPickerCategory[];\n  /** The person's frequently used emoji, which the app keeps. Shown first, under `frequentLabel`, with its own button in the category bar. */\n  frequent?: readonly EmojiPickerEmoji[] | undefined;\n  /** A row of emoji above the categories for a single press, such as the quick reactions on a message. */\n  quick?: readonly EmojiPickerEmoji[] | undefined;\n  /**\n   * Draws an emoji in the grid, the quick row, the preview, the category buttons (each\n   * category's first emoji) and the skin tone choice (the first emoji with tones), for an app with its own emoji art:\n   * return an image 1em square, so it takes the size of the text, with an empty `alt` (the button\n   * already has the emoji's name). Pass a function that stays the same between renders, so moving\n   * focus redraws only the emoji it leaves and reaches. Without it, the picker shows the\n   * platform's own glyphs, in the skin tone in use.\n   *\n  \n * @claim \"the category buttons (each\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > draws the platform's emoji categories' icons and skin tones with renderEmoji, kept still)\n  \n * @claim \"Draws an emoji in the grid, the quick row\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker content > draws each emoji with renderEmoji in the skin tone in use, keeping its name for screen readers)\n   */\n  renderEmoji?: EmojiRender | undefined;\n  /**\n   * Called with the chosen emoji when the person presses one, or presses Enter in the search\n   * for its first result; the picker then closes. The event comes second, so the app can check\n   * `event.isTrusted` before it acts.\n   */\n  onSelect: (selection: EmojiPickerSelection, event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>) => void;\n  /** Not with `categories`. Remove `categories`, `frequent` and `quick` to offer an image catalogue's emoji instead. */\n  catalogue?: never;\n  /** Not with `categories`. A placeholder stands in for a catalogue's pictures; `renderEmoji` draws your own art. */\n  placeholder?: never;\n};\n\n/**\n * An EmojiPicker of an image catalogue's emoji, the app's own set: it draws only the\n * catalogue's images, never the platform's emoji font, and takes frequently used and quick\n * emoji by id.\n *\n * @claim \"it draws only the\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > draws only the catalogue's images, each named by its emoji's name, with the custom category labelled by the app)\n */\nexport type EmojiPickerCatalogueProps = {\n  /**\n   * The emoji the picker offers, as images, by category, in order: a standard set, and an\n   * organization's custom emoji in a category of their own. The search matches their names,\n   * shortcodes and keywords.\n   *\n  \n * @claim \"The search matches their names\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > searches by shortcode, with or without colons, by keyword and by the emoji's text)\n   */\n  catalogue: EmojiCatalogue;\n  /**\n   * The ids of the person's frequently used or recent emoji, which the app keeps (a tone's id\n   * shows its emoji). Shown first, under `frequentLabel`. An id the catalogue no longer has is\n   * left out.\n   *\n  \n * @claim \"An id the catalogue no longer has is\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > shows frequently used and quick emoji by id, leaving out ids the catalogue lacks)\n   */\n  frequent?: readonly string[] | undefined;\n  /** The ids of a row of emoji above the categories for a single press, such as the quick reactions on a message. */\n  quick?: readonly string[] | undefined;\n  /**\n   * Shows in each emoji's place until its picture has loaded and decoded, as `Emoji`'s\n   * `placeholder`: an image's address, or an element. The picker passes it to every emoji it\n   * draws: the grid, the quick row, the preview, the category buttons and the skin tones. Pass\n   * a value that stays the same between renders (an address, or an element made once), so the\n   * grid is not redrawn while the app renders.\n   *\n  \n * @claim \"Shows in each emoji's place until\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > passes its placeholder to every emoji it draws, each picture keeping its emoji's name, until each picture has decoded)\n  \n * @claim \"The picker passes it to every\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > passes its placeholder to every emoji it draws, each picture keeping its emoji's name, until each picture has decoded)\n   */\n  placeholder?: string | ReactElement | undefined;\n  /**\n   * Called with the chosen emoji when the person presses one, or presses Enter in the search\n   * for its first result; the picker then closes. The event comes second, so the app can check\n   * `event.isTrusted` before it acts.\n   */\n  onSelect: (selection: EmojiPickerCatalogueSelection, event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>) => void;\n  /** Not with `catalogue`. The emoji come from the catalogue: remove `categories`. */\n  categories?: never;\n  /** Not with `catalogue`. The picker draws the catalogue's images. */\n  renderEmoji?: never;\n};\n\n/** How an uncontrolled EmojiPicker opens: `trigger` opens and closes it. */\nexport type EmojiPickerTriggerOpening = {\n  /** The element that opens and closes the picker, usually an icon Button: `trigger={<Button aria-label=\"Add a reaction\">…</Button>}`. */\n  trigger: ReactElement;\n  /** Not with `trigger`. Remove `trigger` to control the picker with `open`, `onOpenChange` and `anchor`. */\n  open?: TriggerOrOpen;\n  /** Not with `trigger`. Remove `trigger` to control the picker with `open`, `onOpenChange` and `anchor`. */\n  onOpenChange?: never;\n  /** Not with `trigger`. The picker sits beside its trigger. */\n  anchor?: never;\n};\n\n/** How a controlled EmojiPicker opens: you own `open`, update it in `onOpenChange`, and say what it points at with `anchor`. */\nexport type EmojiPickerControlledOpening = {\n  /** Whether the picker is open. */\n  open: boolean;\n  /** Called with `false` when the person dismisses the picker (Escape, an outside press, the close button) or chooses an emoji. */\n  onOpenChange: (open: boolean) => void;\n  /** The element the picker points at, usually the button that toggles it: `anchor={buttonRef}`. */\n  anchor: RefObject<HTMLElement | null>;\n  /** Not with `open`. Remove `open`, `onOpenChange` and `anchor` to let a trigger open the picker. */\n  trigger?: never;\n};\n\n/** An uncontrolled EmojiPicker of the platform's emoji: `trigger` opens and closes it. */\nexport type EmojiPickerWithTriggerProps = EmojiPickerBaseProps & EmojiPickerUnicodeProps & EmojiPickerTriggerOpening;\n\n/** A controlled EmojiPicker of the platform's emoji: you own `open`, update it in `onOpenChange`, and say what it points at with `anchor`. */\nexport type EmojiPickerControlledProps = EmojiPickerBaseProps & EmojiPickerUnicodeProps & EmojiPickerControlledOpening;\n\n/** An uncontrolled EmojiPicker of an image catalogue's emoji: `trigger` opens and closes it. */\nexport type EmojiPickerCatalogueWithTriggerProps = EmojiPickerBaseProps & EmojiPickerCatalogueProps & EmojiPickerTriggerOpening;\n\n/** A controlled EmojiPicker of an image catalogue's emoji: you own `open`, update it in `onOpenChange`, and say what it points at with `anchor`. */\nexport type EmojiPickerCatalogueControlledProps = EmojiPickerBaseProps & EmojiPickerCatalogueProps & EmojiPickerControlledOpening;\n\n/**\n * Props for {@link EmojiPicker}: the emoji, by `categories` or an image `catalogue`, and either\n * `trigger`, or `open` with `onOpenChange` and `anchor`.\n */\nexport type EmojiPickerProps = EmojiPickerWithTriggerProps | EmojiPickerControlledProps | EmojiPickerCatalogueWithTriggerProps | EmojiPickerCatalogueControlledProps;\n\ntype TriggerProps = {\n  ref?: Ref<HTMLElement> | undefined;\n  onClick?: ((event: MouseEvent<HTMLElement>) => void) | undefined;\n};\n\nconst categoriesFix = '<EmojiPicker label=\"Add a reaction\" categories={[{ label: \"Smileys\", emoji: [{ emoji: \"😀\", name: \"grinning face\" }] }]} onSelect={react}>';\nconst catalogueFix = '<EmojiPicker label=\"Add a reaction\" catalogue={{ categories: [{ id: \"smileys\", label: \"Smileys\", items }] }} onSelect={react}>';\nconst selectFix = \"<EmojiPicker onSelect={(selection) => insert(selection.emoji)}>\";\nconst controlFix = \"<EmojiPicker open={open} onOpenChange={setOpen} anchor={buttonRef}>\";\n\n/**\n * An emoji picker for reactions and for putting emoji into text. It has a search field, a bar\n * of categories, an optional row of quick reactions, a skin tone choice and a grid of the\n * platform's own emoji, in a `Popover` that is a bottom sheet on phones. The app passes the\n * emoji by category, with names and keywords in its own language, and the person's\n * frequently used ones. With `catalogue` it offers an image catalogue's emoji instead (a\n * standard set and an organization's custom emoji), drawn only as the catalogue's images, an\n * animated one playing while it is in focus or under the mouse, and gives `onSelect` the\n * emoji's id and the `:shortcode:` token to put into text. A catalogue's images are all fetched\n * as the picker opens, the quick row and the grid's first eight rows first; while the browser asks\n * to save data, the rest of the grid's wait until they near the screen.\n *\n * The search matches the start of any word in an emoji's name, keywords or shortcodes, ignoring\n * case and accents, and announces how many it found. The grid is one Tab stop: the arrow keys move\n * through it, Home and End go to the ends of a row (with Ctrl, of the grid), Page Down and\n * Page Up go to the next and previous category, and Enter chooses. Every emoji is named for\n * screen readers, and the one in focus shows large with its name under the grid. Choosing one\n * calls `onSelect` and closes the picker; Escape closes it too.\n *\n * A closed picker makes nothing from its emoji, so one in each conversation's reply box costs\n * next to nothing to mount; the first to open makes what it shows from a catalogue, once for every\n * picker given that catalogue.\n *\n * Use `ReactionBar` instead to show a message's reactions and its few quick ones, with an\n * EmojiPicker beside it for the rest. Use `Command` instead for a searchable list of actions.\n *\n * @claim \"A closed picker makes nothing from its\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > reads none of its catalogue while closed, and builds what it shows once per catalogue as pickers open)\n * @group Chat\n * @see https://ui.ouroboros.bot/docs/emoji-picker\n *\n * @example\n * <EmojiPicker\n *   label=\"Add a reaction\"\n *   trigger={<Button variant=\"plain\" aria-label=\"Add a reaction\"><SmileIcon /></Button>}\n *   categories={categories}\n *   frequent={frequent}\n *   quick={quickReactions}\n *   skinTone={tone}\n *   onSkinToneChange={setTone}\n *   onSelect={(selection) => react(message.id, selection.emoji)}\n * />\n * <EmojiPicker\n *   label=\"Add a reaction\"\n *   trigger={<Button variant=\"plain\" aria-label=\"Add a reaction\"><SmileIcon /></Button>}\n *   catalogue={catalogue}\n *   frequent={recentIds}\n *   quick={[\"like\", \"heart\", \"laugh\"]}\n *   placeholder=\"/emoji/waiting.svg\"\n *   onSelect={(selection) => react(message.id, selection.id)}\n * />\n * @claim \"while the browser asks to save data, the rest\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > fetches the grid past its first eight rows only as it nears the screen while the browser asks to save data)\n * @claim \"A catalogue's images are all fetched\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > fetches every image as it opens, the quick row and the grid's first eight rows first, then the rest in order)\n * @claim \"drawn only as the catalogue's images\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > draws only the catalogue's images, each named by its emoji's name, with the custom category labelled by the app)\n * @claim \"an animated one playing while it is in focus\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > plays an animated emoji while it is in focus or under the mouse, and the preview with it)\n * @claim \"Every emoji is named for\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker content > shows the quick row, the frequently used emoji and every category, each emoji named for screen readers)\n * @claim \"the one in focus shows large\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker content > shows the name of the emoji in focus, or under the mouse, large beside its glyph)\n * @claim \"announces how many it found\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker search > announces how many it found as the count changes, once each, and when nothing matches)\n * @claim \"The grid is one Tab stop\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker keyboard > is one Tab stop that follows focus)\n * @claim \"Page Up go to the next\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker keyboard > goes to the next and previous category with Page Down and Page Up, keeping the column)\n * @claim \"Home and End go to the\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker keyboard > goes to the ends of a row with Home and End, and of the grid with Ctrl)\n * @claim \"calls `onSelect` and closes the picker\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker content > chooses an emoji with a press: onSelect gets it, its name, its tone and the event, and the picker closes)\n */\nexport function EmojiPicker(props: EmojiPickerProps): JSX.Element {\n  const {\n    label,\n    categories,\n    catalogue,\n    frequent,\n    quick,\n    renderEmoji,\n    placeholder,\n    onSelect,\n    skinTone: skinToneProp,\n    onSkinToneChange,\n    presentation = \"auto\",\n    side,\n    align,\n    searchLabel = \"Search emoji\",\n    frequentLabel = \"Frequently used\",\n    quickLabel = \"Quick reactions\",\n    categoriesLabel = \"Categories\",\n    skinToneLabel = \"Skin tone\",\n    skinToneNames = defaultSkinToneNames,\n    resultsLabel = \"{count} emoji\",\n    noResultsLabel = \"No emoji found\",\n    closeLabel = \"Close\",\n    className,\n    trigger,\n    open,\n    onOpenChange,\n    anchor,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    onEmojiSelect,\n    onEmojiClick,\n    data,\n    isOpen,\n    onClose,\n  } = props as EmojiPickerBaseProps & {\n    categories?: readonly EmojiPickerCategory[];\n    catalogue?: EmojiCatalogue;\n    frequent?: readonly EmojiPickerEmoji[] | readonly string[];\n    quick?: readonly EmojiPickerEmoji[] | readonly string[];\n    renderEmoji?: EmojiRender;\n    placeholder?: string | ReactElement;\n    onSelect: (selection: EmojiPickerSelection & EmojiPickerCatalogueSelection, event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>) => void;\n    trigger?: ReactElement;\n    open?: boolean;\n    onOpenChange?: (open: boolean) => void;\n    anchor?: RefObject<HTMLElement | null>;\n  };\n\n  checkOpenMode(\"EmojiPicker\", \"emoji picker\", trigger !== undefined, open, onOpenChange);\n\n  const knownTone = skinToneProp === undefined || emojiSkinTones.includes(skinToneProp as EmojiSkinTone);\n  useAppearanceClassNameCheck(\n    \"EmojiPicker\",\n    className,\n    process.env.NODE_ENV !== \"production\"\n      ? (token: string) => `remove \"${token}\"; EmojiPicker 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    \"EmojiPicker\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [\n          !label && [\"label is required; it names the picker for screen readers\", '<EmojiPicker label=\"Add a reaction\">'],\n          !(catalogue?.categories ?? categories)?.length &&\n            (catalogue ? [\"catalogue has no categories; pass the emoji to offer\", catalogueFix] : [\"categories is empty; pass the emoji to offer\", categoriesFix]),\n          !knownTone && [\n            `skinTone=\"${String(skinToneProp)}\" is not a skin tone; use ${emojiSkinTones.map((tone) => `\"${tone}\"`).join(\", \")}`,\n            '<EmojiPicker skinTone=\"medium\">',\n          ],\n          onEmojiSelect !== undefined && [\"onEmojiSelect is not a prop\", selectFix],\n          onEmojiClick !== undefined && [\"onEmojiClick is not a prop\", selectFix],\n          data !== undefined && [\"data is not a prop; the emoji come by category in categories\", categoriesFix],\n          isOpen !== undefined && [\"isOpen is not a prop\", controlFix],\n          onClose !== undefined && [\"onClose is not a prop\", controlFix],\n        ]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n\n  // The picker owns the open state even with a trigger, so choosing an emoji can close it.\n  const [ownOpen, setOwnOpen] = useState(false);\n  const controlled = open !== undefined;\n  const isOpenNow = controlled ? open : ownOpen;\n  const setOpen = controlled ? onOpenChange! : setOwnOpen;\n\n  const [ownTone, setOwnTone] = useState<EmojiSkinTone>(\"default\");\n  const tone: EmojiSkinTone = skinToneProp === undefined ? ownTone : knownTone ? (skinToneProp as EmojiSkinTone) : \"default\";\n  const setTone = (next: EmojiSkinTone) => {\n    setOwnTone(next);\n    onSkinToneChange?.(next);\n  };\n\n\n  // A presentation that is not one of Popover's is a popover there, and is no sheet here either.\n  const asSheet = useSheetPresentation(presentation);\n\n  const triggerRef = useRef<HTMLElement>(null);\n  // A Server Component's trigger can arrive as a lazy wrapper; resolve it before cloning.\n  const triggerElement = serverElement(trigger);\n  const triggerProps = (triggerElement?.props ?? {}) as TriggerProps;\n  const mergedTriggerRef = useMergedRef(triggerProps.ref, triggerRef);\n  const triggerNode =\n    triggerElement !== undefined &&\n    cloneElement(triggerElement as ReactElement<TriggerProps & { \"aria-haspopup\"?: string; \"aria-expanded\"?: boolean }>, {\n      ref: mergedTriggerRef,\n      onClick: (event: MouseEvent<HTMLElement>) => {\n        triggerProps.onClick?.(event);\n        if (!event.defaultPrevented) setOwnOpen(!ownOpen);\n      },\n      \"aria-haspopup\": \"dialog\",\n      \"aria-expanded\": isOpenNow,\n    });\n\n  return (\n    <>\n      {triggerNode}\n      <Popover\n        // Without a label (a development message names the fix), the dialog still has a name.\n        title={label || \"Emoji\"}\n        hideTitle\n        closeLabel={closeLabel}\n        presentation={presentation}\n        side={side}\n        align={align}\n        className=\"w-auto p-1\"\n        open={isOpenNow}\n        onOpenChange={setOpen}\n        anchor={controlled ? anchor! : triggerRef}\n      >\n        <PickerPanel\n          source={{ catalogue, categories, frequent, quick, renderEmoji, placeholder }}\n          tone={tone}\n          setTone={setTone}\n          asSheet={asSheet}\n          labels={{ searchLabel, frequentLabel, quickLabel, categoriesLabel, skinToneLabel, skinToneNames, resultsLabel, noResultsLabel }}\n          className={className}\n          onChoose={(item, event) => {\n            const skinTone = item.skinTones ? tone : \"default\";\n            const image = (item as CatalogueEntry).image;\n            onSelect(\n              image\n                ? ({ id: toned(item, tone), name: item.name, token: emojiToken(image, skinTone), skinTone, item: image } as EmojiPickerSelection & EmojiPickerCatalogueSelection)\n                : ({ emoji: toned(item, tone), name: item.name, skinTone, item } as EmojiPickerSelection & EmojiPickerCatalogueSelection),\n              event,\n            );\n            setOpen(false);\n          }}\n        />\n      </Popover>\n    </>\n  );\n}\n\n/** Draws an emoji in a skin tone, and plays it (`true`), keeps it still (`false`) or lets it play for its button (`undefined`). */\n/**\n * How soon an emoji's image is fetched: `high` for what shows as the picker opens, `low` for the\n * rest, in order, and `saved` for the rest while the browser asks to save data, fetched only as it\n * nears the screen.\n */\ntype GlyphPriority = \"high\" | \"low\" | \"saved\";\n\n/** Whether the browser asks to save data (Save-Data). */\nconst savingData = () => Boolean((navigator as Navigator & { connection?: { saveData?: boolean } }).connection?.saveData);\ntype GlyphRender = (item: EmojiPickerEmoji, skinTone: EmojiSkinTone, play?: boolean, priority?: GlyphPriority) => ReactNode;\n\n/** A catalogue's emoji as the panel holds it: its id as `emoji`, its tones' ids as its toned forms, and the item to draw. */\ninterface CatalogueEntry extends EmojiPickerEmoji {\n  shortcodes: EmojiItem[\"shortcodes\"];\n  text: EmojiItem[\"text\"];\n  image: EmojiItem;\n}\n\n/** The raised hand the skin tone button and its choices show. */\nconst hand = { emoji: \"✋\", skinTones: true };\n\n/** A catalogue item's entry, made once per item, so the cells it fills keep their memo while the app re-renders. */\nconst entries = new WeakMap<EmojiItem, CatalogueEntry>();\nfunction entryOf(item: EmojiItem): CatalogueEntry {\n  let entry = entries.get(item);\n  if (entry === undefined) {\n    entry = {\n      emoji: item.id,\n      name: item.name,\n      keywords: item.keywords,\n      shortcodes: item.shortcodes,\n      text: item.text,\n      skinTones: item.skinTones?.length ? item.skinTones.map((form) => form.id) : undefined,\n      image: item,\n    };\n    entries.set(item, entry);\n  }\n  return entry;\n}\n\n/**\n * A catalogue's categories as the panel shows them, and the first of their emoji with tones: made once per catalogue, so a\n * picker that mounts closed (one in each conversation's reply box, say) costs next to nothing after the first.\n * @claim \"A catalogue's categories as the panel\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > reads none of its catalogue while closed, and builds what it shows once per catalogue as pickers open)\n */\nfunction buildCatalogueContent(catalogue: EmojiCatalogue) {\n  const list = catalogue.categories.map((category) => ({ label: category.label, icon: category.icon, emoji: category.items.map(entryOf) }));\n  return { list, toned: list.flatMap((category) => category.emoji).find((entry) => entry.skinTones) };\n}\nconst catalogueContents = new WeakMap<EmojiCatalogue, ReturnType<typeof buildCatalogueContent>>();\nfunction catalogueContent(catalogue: EmojiCatalogue) {\n  let made = catalogueContents.get(catalogue);\n  if (made === undefined) catalogueContents.set(catalogue, (made = buildCatalogueContent(catalogue)));\n  return made;\n}\n\n/** The emoji a picker offers, as its props give them, for the panel to make into what it shows. */\ninterface PickerSource {\n  catalogue: EmojiCatalogue | undefined;\n  categories: readonly EmojiPickerCategory[] | undefined;\n  frequent: readonly EmojiPickerEmoji[] | readonly string[] | undefined;\n  quick: readonly EmojiPickerEmoji[] | readonly string[] | undefined;\n  renderEmoji: EmojiRender | undefined;\n  placeholder: string | ReactElement | undefined;\n}\n\n/**\n * The panel, with what it shows made from the picker's emoji. Inside the popover, which renders it only while open, so a\n * picker that mounts closed (one in each conversation's reply box, say) makes nothing.\n * @claim \"Inside the popover, which renders it\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > reads none of its catalogue while closed, and builds what it shows once per catalogue as pickers open)\n */\nfunction PickerPanel({ source, ...rest }: { source: PickerSource } & Omit<Parameters<typeof Panel>[0], \"categories\" | \"frequent\" | \"quick\" | \"render\" | \"toneGlyph\">): JSX.Element {\n  const content = usePickerContent(source.catalogue, source.categories, source.frequent, source.quick, source.renderEmoji, source.placeholder);\n  return <Panel categories={content.categories} frequent={content.frequent} quick={content.quick} render={content.render} toneGlyph={content.toneGlyph} {...rest} />;\n}\n\n/** What the panel shows: the app's categories as they are, or a catalogue's as entries, with the frequent and quick ids found in it. */\nfunction usePickerContent(\n  catalogue: EmojiCatalogue | undefined,\n  categories: readonly EmojiPickerCategory[] | undefined,\n  frequent: readonly EmojiPickerEmoji[] | readonly string[] | undefined,\n  quick: readonly EmojiPickerEmoji[] | readonly string[] | undefined,\n  renderEmoji: EmojiRender | undefined,\n  placeholder: string | ReactElement | undefined,\n) {\n  // A catalogue's ids stand in as their text, so a new array of the same ids keeps the content.\n  const frequentKey = catalogue ? (frequent as readonly string[] | undefined)?.join(\"\\n\") : frequent;\n  const quickKey = catalogue ? (quick as readonly string[] | undefined)?.join(\"\\n\") : quick;\n  return useMemo(() => {\n    if (!catalogue) {\n      const given = { categories: categories ?? [], frequent: frequentKey as readonly EmojiPickerEmoji[] | undefined, quick: quickKey as readonly EmojiPickerEmoji[] | undefined };\n      // With the app's own art, the tones show on its first emoji with tones, drawn by it; else on a raised hand.\n      const sample = renderEmoji && [...(given.quick ?? []), ...(given.frequent ?? []), ...given.categories.flatMap((category) => category.emoji)].find((item) => item.skinTones);\n      return {\n        ...given,\n        render: renderEmoji as GlyphRender | undefined,\n        toneGlyph: (tone: EmojiSkinTone): ReactNode => (sample ? renderEmoji!(sample, tone) : toned(hand, tone)),\n      };\n    }\n    const { byId } = catalogueIndex(catalogue);\n    const byIds = (ids: string | undefined) => ids?.split(\"\\n\").flatMap((id) => (byId.has(id) ? [entryOf(byId.get(id)!.item)] : []));\n    const { list, toned: firstToned } = catalogueContent(catalogue);\n    const found = { frequent: byIds(frequentKey as string | undefined), quick: byIds(quickKey as string | undefined) };\n    const withTones = <T extends { skinTones?: unknown }>(list: readonly T[] | undefined) => list?.find((entry) => entry.skinTones);\n    const sample = withTones(found.quick) ?? withTones(found.frequent) ?? firstToned;\n    // Draws a catalogue's emoji: its image, in the tone, playing for its button unless told otherwise.\n    const drawCatalogue: GlyphRender = (item, skinTone, play, priority) => (\n      <Emoji\n        item={(item as CatalogueEntry).image}\n        skinTone={skinTone}\n        play={play}\n        placeholder={placeholder}\n        fetchPriority={priority === \"saved\" ? \"low\" : priority}\n        // The one place Ouro waits for an image to near the screen: the person asked to save data.\n        loading={priority === \"saved\" ? \"lazy\" : undefined}\n      />\n    );\n    return {\n      categories: list,\n      ...found,\n      render: drawCatalogue,\n      // Shown only when some emoji has tones, so there is a sample.\n      toneGlyph: (tone: EmojiSkinTone): ReactNode => drawCatalogue(sample!, tone, false),\n    };\n  }, [catalogue, categories, frequentKey, quickKey, renderEmoji, placeholder]);\n}\n\n/** A run of grid cells: one category, or the search results. */\ninterface Section {\n  label: string;\n  icon: ReactNode;\n  items: readonly EmojiPickerEmoji[];\n  /** Where its first emoji is among the grid's cells. */\n  start: number;\n}\n\n/** One row of the grid: the section it is in and the cells it holds. */\ninterface Row {\n  section: number;\n  start: number;\n  length: number;\n}\n\ninterface PanelLabels {\n  searchLabel: string;\n  frequentLabel: string;\n  quickLabel: string;\n  categoriesLabel: string;\n  skinToneLabel: string;\n  skinToneNames: Readonly<Record<EmojiSkinTone, string>>;\n  resultsLabel: string;\n  noResultsLabel: string;\n}\n\ninterface PanelProps {\n  categories: readonly EmojiPickerCategory[];\n  frequent: readonly EmojiPickerEmoji[] | undefined;\n  quick: readonly EmojiPickerEmoji[] | undefined;\n  render: GlyphRender | undefined;\n  toneGlyph: (tone: EmojiSkinTone) => ReactNode;\n  tone: EmojiSkinTone;\n  setTone: (tone: EmojiSkinTone) => void;\n  asSheet: boolean;\n  labels: PanelLabels;\n  className: string | undefined;\n  onChoose: (item: EmojiPickerEmoji, event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>) => void;\n}\n\nconst isRtl = (element: Element) => getComputedStyle(element).direction === \"rtl\";\nconst offersTones = (items: readonly EmojiPickerEmoji[] | undefined) => items?.some((item) => Boolean(item.skinTones)) ?? false;\n\n/** A clock, the frequently used category's icon. */\nfunction ClockIcon(): JSX.Element {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\">\n      <circle cx=\"8\" cy=\"8\" r=\"6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path d=\"M8 4.5V8l2.5 1.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\n/** A magnifier, the search field's icon. */\nfunction SearchIcon(): JSX.Element {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\">\n      <circle cx=\"7\" cy=\"7\" r=\"4.75\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path d=\"m10.5 10.5 3 3\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\n/** An emoji as the app or the catalogue draws it, else its platform glyph in the tone. */\nconst glyphOf = (item: EmojiPickerEmoji, tone: EmojiSkinTone, render: GlyphRender | undefined, play?: boolean, priority?: GlyphPriority) =>\n  render ? render(item, tone, play, priority) : toned(item, tone);\n\n/** One emoji button. Memoized, so moving focus re-renders only the cells it leaves and reaches. */\nconst Cell = memo(function Cell({ item, tone, render, index, active, quick, priority }: { item: EmojiPickerEmoji; tone: EmojiSkinTone; render: GlyphRender | undefined; index: number; active: boolean; quick: boolean; priority: GlyphPriority }) {\n  return (\n    <button\n      type=\"button\"\n      tabIndex={active ? 0 : -1}\n      aria-label={item.name}\n      data-cell={index}\n      data-ouro-control=\"emoji-picker\"\n      data-ouro-part={quick ? \"quick\" : \"emoji\"}\n      className={cellClass}\n    >\n      <span aria-hidden=\"true\">{glyphOf(item, tone, render, undefined, priority)}</span>\n    </button>\n  );\n});\n\n/**\n * The emoji a search finds, the frequently used first, each once.\n *\n * @claim \"frequently used first, each once\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker search > finds an emoji pasted into the search, and lists one found twice only once)\n */\nfunction found(categories: readonly EmojiPickerCategory[], frequent: readonly EmojiPickerEmoji[] | undefined, query: string): EmojiPickerEmoji[] {\n  const seen = new Set<string>();\n  // Stryker disable next-line ArrayDeclaration: a stand-in with no emoji or name matches no search, so it changes no result.\n  return [...(frequent ?? []), ...categories.flatMap((category) => category.emoji)].filter((item) => {\n    if (seen.has(item.emoji) || !matchEmoji(item, query)) return false;\n    seen.add(item.emoji);\n    return true;\n  });\n}\n\n/** The grid's sections and rows: the search's results while there is a search, else the frequently used emoji and the categories. */\nfunction useSections(categories: readonly EmojiPickerCategory[], frequent: readonly EmojiPickerEmoji[] | undefined, query: string, labels: PanelLabels, render: GlyphRender | undefined) {\n  const searching = query.trim() !== \"\";\n  const { resultsLabel, frequentLabel } = labels;\n  const sections = useMemo(() => {\n    const results = (items: EmojiPickerEmoji[]) => ({ label: fillCount(resultsLabel, items.length), icon: null, items });\n    const list: Omit<Section, \"start\">[] = searching\n      ? [results(found(categories, frequent, query))]\n      : [\n          ...(frequent?.length ? [{ label: frequentLabel, icon: <ClockIcon />, items: frequent }] : []),\n          ...categories\n            .filter((category) => category.emoji.length)\n            .map((category) => ({ label: category.label, icon: category.icon ?? glyphOf(category.emoji[0]!, \"default\", render, false), items: category.emoji })),\n        ];\n    let start = 0;\n    return list.map((section) => {\n      const placed = { ...section, start };\n      start += section.items.length;\n      return placed;\n    });\n  }, [searching, query, frequent, categories, resultsLabel, frequentLabel, render]);\n  const rows = useMemo(() => {\n    const list: Row[] = [];\n    sections.forEach((section, index) => {\n      for (let offset = 0; offset < section.items.length; offset += COLUMNS) {\n        list.push({ section: index, start: section.start + offset, length: Math.min(COLUMNS, section.items.length - offset) });\n      }\n    });\n    return list;\n  }, [sections]);\n  const total = rows.length ? rows.at(-1)!.start + rows.at(-1)!.length : 0;\n  return { searching, sections, rows, total };\n}\n\n/** Speaks a message politely when it changes, and nothing when it is empty. */\nfunction useAnnouncement(message: string): void {\n  useEffect(() => {\n    if (message) announce(message);\n  }, [message]);\n}\n\n/** Where a key takes focus in the grid. */\ninterface GridStep {\n  /**\n   * The cell focus moves to, or -1 for the search field.\n   *\n  \n * @claim \"or -1 for the search\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker keyboard > moves from the search into the grid with Down, and back up from the first row with Up)\n   */\n  next: number;\n  /** The column an Up, Down or page key keeps, for the next one. */\n  column?: number;\n}\n\n/**\n * Where a key moves focus in the grid from cell `at`: the arrows (Left and Right swapped in a\n * right-to-left page), Up from the first row to the search, Home and End to the ends of the row\n * (with Ctrl or Command, of the grid), Page Down and Page Up by category. Up, Down and the page\n * keys keep `column` across shorter rows. Any other key is not the grid's.\n */\nfunction gridStep(key: string, ctrl: boolean, at: number, column: number, rows: readonly Row[], sectionCount: number, rtl: boolean): GridStep | undefined {\n  const rowIndex = rows.findLastIndex((row) => row.start <= at);\n  const row = rows[rowIndex]!;\n  const total = rows.at(-1)!.start + rows.at(-1)!.length;\n  const inRow = (other: Row | undefined) => (other ? other.start + Math.min(column, other.length - 1) : undefined);\n  const firstRowOf = (section: number) => rows.find((entry) => entry.section === section)!;\n  const vertical = (next: number | undefined) => (next === undefined ? undefined : { next, column });\n  if (key === \"ArrowDown\") return vertical(inRow(rows[rowIndex + 1]));\n  if (key === \"ArrowUp\") return vertical(rowIndex === 0 ? -1 : inRow(rows[rowIndex - 1]));\n  if (key === \"PageDown\") return vertical(inRow(row.section + 1 < sectionCount ? firstRowOf(row.section + 1) : rows.at(-1)));\n  if (key === \"PageUp\") return vertical(inRow(firstRowOf(firstRowOf(row.section) === row ? Math.max(row.section - 1, 0) : row.section)));\n  if (key === \"Home\") return { next: ctrl ? 0 : row.start };\n  if (key === \"End\") return { next: ctrl ? total - 1 : row.start + row.length - 1 };\n  if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return undefined;\n  const forward = (key === \"ArrowRight\") !== rtl;\n  return { next: Math.min(Math.max(at + (forward ? 1 : -1), 0), total - 1) };\n}\n\n/** The skin tones as a radio group, in place of the search while the person chooses. */\nfunction ToneChoice({ tone, setTone, label, names, glyph, onDone }: { tone: EmojiSkinTone; setTone: (tone: EmojiSkinTone) => void; label: string; names: Readonly<Record<EmojiSkinTone, string>>; glyph: (tone: EmojiSkinTone) => ReactNode; onDone: (returnFocus: boolean) => void }) {\n  const group = useRef<HTMLDivElement>(null);\n  // Stryker disable next-line ArrayDeclaration: a list that never changes runs the effect once, as an empty one does.\n  useEffect(() => group.current!.querySelector<HTMLElement>('[aria-checked=\"true\"]')!.focus(), []);\n  return (\n    <div\n      ref={group}\n      role=\"radiogroup\"\n      aria-label={label}\n      className=\"flex min-h-9 min-w-0 flex-1 items-center justify-between gap-1 pointer-coarse:min-h-11\"\n      // Keeps focus on the checked tone while another is pressed: Safari does not focus a\n      // pressed button, and the row would close on the blur before the press lands.\n      onMouseDown={(event) => event.preventDefault()}\n      onKeyDown={(event) => {\n        if (event.key === \"Escape\") {\n          event.preventDefault();\n          // Stryker disable next-line CallExpression: the popover and the sheet already keep a handled Escape from the page; this keeps it so if they change.\n          event.stopPropagation();\n          onDone(true);\n          return;\n        }\n        const arrows: Record<string, string> = { ArrowDown: \"ArrowRight\", ArrowUp: \"ArrowLeft\" };\n        const key = arrows[event.key] ?? event.key;\n        const next = stepInRow(key, emojiSkinTones.indexOf(tone), emojiSkinTones.length, key === event.key && isRtl(event.currentTarget));\n        if (next === undefined) return;\n        event.preventDefault();\n        setTone(emojiSkinTones[next]!);\n        event.currentTarget.querySelectorAll<HTMLElement>('[role=\"radio\"]')[next]!.focus();\n      }}\n      onBlur={(event) => {\n        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) onDone(false);\n      }}\n    >\n      {emojiSkinTones.map((option) => (\n        <button\n          key={option}\n          type=\"button\"\n          role=\"radio\"\n          aria-checked={option === tone}\n          aria-label={names[option]}\n          tabIndex={option === tone ? 0 : -1}\n          data-ouro-control=\"emoji-picker\"\n          data-ouro-part=\"tone\"\n          className={toneOptionClass}\n          onClick={() => {\n            setTone(option);\n            onDone(true);\n          }}\n        >\n          <span aria-hidden=\"true\">{glyph(option)}</span>\n        </button>\n      ))}\n    </div>\n  );\n}\n\n/**\n * The categories' or results' grids, each labelled by its heading, which stays at the top as its emoji scroll.\n * Every image is fetched as the picker opens: the first eight rows' (about what shows first) at high priority, the rest at low, in order.\n * While the browser asks to save data, the rest wait until they near the screen.\n *\n * @claim \"While the browser asks to save data\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > fetches the grid past its first eight rows only as it nears the screen while the browser asks to save data)\n * @claim \"Every image is fetched as the picker\" registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.catalogue.test.tsx::EmojiPicker with a catalogue > fetches every image as it opens, the quick row and the grid's first eight rows first, then the rest in order)\n * @claim \"each labelled by its heading\" registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx verify:testExists(registry/ouro/components/ouro/emoji-picker/emoji-picker.test.tsx::EmojiPicker content > shows the quick row, the frequently used emoji and every category, each emoji named for screen readers)\n */\nfunction Grids({ id, sections, rows, tone, render, active, sectionRefs, saving }: { id: string; sections: readonly Section[]; rows: readonly Row[]; tone: EmojiSkinTone; render: GlyphRender | undefined; active: number; sectionRefs: RefObject<(HTMLElement | null)[]>; saving: boolean }) {\n  return sections.map((section, index) => (\n    <div\n      key={index}\n      ref={(element) => {\n        sectionRefs.current[index] = element;\n      }}\n    >\n      <div id={`${id}-s${index}`} className={headingClass}>\n        {section.label}\n      </div>\n      <div role=\"grid\" aria-labelledby={`${id}-s${index}`} className=\"grid\">\n        {rows\n          .filter((row) => row.section === index)\n          .map((row) => (\n            <div role=\"row\" key={row.start} className={gridClass}>\n              {section.items.slice(row.start - section.start, row.start - section.start + row.length).map((item, offset) => (\n                <div role=\"gridcell\" key={offset} className=\"flex justify-center\">\n                  <Cell item={item} tone={tone} render={render} index={row.start + offset} active={row.start + offset === active} quick={false} priority={row.start + offset < FIRST_CELLS ? \"high\" : saving ? \"saved\" : \"low\"} />\n                </div>\n              ))}\n            </div>\n          ))}\n      </div>\n    </div>\n  ));\n}\n\n/** The cell an event came from, if any. */\nconst cellOf = (event: { target: EventTarget }) => (event.target as Element).closest<HTMLElement>(\"[data-cell]\");\n\n/** Moves along a row of buttons (the quick row, the category bar) on its arrow, Home and End keys. */\nfunction onRowKey(event: KeyboardEvent<HTMLDivElement>, count: number, at: number, move: (index: number) => void) {\n  const next = stepInRow(event.key, at, count, isRtl(event.currentTarget));\n  if (next === undefined) return;\n  event.preventDefault();\n  move(next);\n  event.currentTarget.querySelectorAll<HTMLElement>(\"button\")[next]!.focus();\n}\n\n/** Whether the skin tones are showing, and their closing, which can put focus back on the button that opened them. */\nfunction useToneChoice() {\n  const [choosingTone, setChoosingTone] = useState(false);\n  const toneReturn = useRef(false);\n  const toneButtonRef = useRef<HTMLButtonElement>(null);\n  useEffect(() => {\n    if (!choosingTone && toneReturn.current) toneButtonRef.current!.focus();\n  }, [choosingTone]);\n  const doneChoosingTone = (returnFocus: boolean) => {\n    toneReturn.current = returnFocus;\n    setChoosingTone(false);\n  };\n  return { choosingTone, openTones: () => setChoosingTone(true), doneChoosingTone, toneButtonRef };\n}\n\n/** The category in view as the grid scrolls, and a category button's jump to its category. */\nfunction useCategoryScroll(scrollerRef: RefObject<HTMLDivElement | null>, sectionRefs: RefObject<(HTMLElement | null)[]>, focusFirst: (section: number) => void) {\n  const [categoryActive, setCategoryActive] = useState(0);\n  const [inView, setInView] = useState(0);\n  // Where a category button scrolled the grid, so that scroll does not mark another category.\n  const jumpedTo = useRef<number | null>(null);\n  const onScroll = () => {\n    const { scrollTop } = scrollerRef.current!;\n    if (scrollTop === jumpedTo.current) return;\n    jumpedTo.current = null;\n    // The first section starts at the top, so one always qualifies.\n    setInView(sectionRefs.current.findLastIndex((section) => section !== null && section.offsetTop <= scrollTop + 1));\n  };\n  const jumpTo = (index: number) => {\n    setCategoryActive(index);\n    setInView(index);\n    scrollerRef.current!.scrollTop = sectionRefs.current[index]!.offsetTop;\n    jumpedTo.current = scrollerRef.current!.scrollTop;\n    // The cell sits just under its sticky heading, which its scroll margin clears, so focus does not scroll.\n    focusFirst(index);\n  };\n  return { categoryActive, setCategoryActive, inView, onScroll, jumpTo };\n}\n\n/** The grid's key handler: moves focus by `gridStep`, and from the first row up to the search. */\nfunction useGridKeys(rows: readonly Row[], sectionCount: number, toSearch: () => void, focusCell: (index: number) => void) {\n  // The column Up and Down keep while they cross shorter rows, for the cell they last moved to.\n  const sticky = useRef<{ at: number; column: number } | null>(null);\n  return (event: KeyboardEvent<HTMLDivElement>) => {\n    const cell = cellOf(event);\n    if (!cell) return;\n    const at = Number(cell.dataset.cell);\n    const column = sticky.current?.at === at ? sticky.current.column : at - rows[rows.findLastIndex((row) => row.start <= at)]!.start;\n    const step = gridStep(event.key, event.ctrlKey || event.metaKey, at, column, rows, sectionCount, isRtl(event.currentTarget));\n    if (!step) return;\n    event.preventDefault();\n    sticky.current = step.column === undefined ? null : { at: step.next, column: step.column };\n    if (step.next < 0) toSearch();\n    else focusCell(step.next);\n  };\n}\n\n/** The skin tone button: the hand in the tone in use, named by it. */\nfunction ToneButton({ tone, labels, glyph, buttonRef, onOpen }: { tone: EmojiSkinTone; labels: PanelLabels; glyph: (tone: EmojiSkinTone) => ReactNode; buttonRef: RefObject<HTMLButtonElement | null>; onOpen: () => void }) {\n  return (\n    <Button\n      ref={buttonRef}\n      variant=\"plain\"\n      tone=\"secondary\"\n      aria-label={`${labels.skinToneLabel}: ${labels.skinToneNames[tone]}`}\n      aria-expanded={false}\n      data-ouro-control=\"emoji-picker\"\n      data-ouro-part=\"skin-tone\"\n      className=\"aspect-square shrink-0 px-0\"\n      onClick={onOpen}\n    >\n      <span aria-hidden=\"true\" className=\"text-xl leading-none\">\n        {glyph(tone)}\n      </span>\n    </Button>\n  );\n}\n\n/** The quick row: a toolbar of emoji for a reaction, one Tab stop. */\nfunction QuickRow({ quick, tone, render, label, onChoose }: { quick: readonly EmojiPickerEmoji[]; tone: EmojiSkinTone; render: GlyphRender | undefined; label: string; onChoose: PanelProps[\"onChoose\"] }) {\n  const [quickActive, setQuickActive] = useState(0);\n  return (\n    <div\n      role=\"toolbar\"\n      aria-label={label}\n      className={quickClass}\n      onKeyDown={(event) => onRowKey(event, quick.length, quickActive, setQuickActive)}\n      onClick={(event) => {\n        const cell = cellOf(event);\n        if (cell) onChoose(quick[Number(cell.dataset.cell)]!, event);\n      }}\n    >\n      {quick.map((item, index) => (\n        <Cell key={index} item={item} tone={tone} render={render} index={index} active={index === quickActive} quick priority=\"high\" />\n      ))}\n    </div>\n  );\n}\n\n/** The category bar: a toolbar with a button per category, one Tab stop, marking the one in view. */\nfunction CategoryBar({ sections, label, active, inView, setActive, onJump }: { sections: readonly Section[]; label: string; active: number; inView: number; setActive: (index: number) => void; onJump: (index: number) => void }) {\n  return (\n    <div role=\"toolbar\" aria-label={label} className={barClass} onKeyDown={(event) => onRowKey(event, sections.length, active, setActive)}>\n      {sections.map((section, index) => (\n        <button\n          key={index}\n          type=\"button\"\n          aria-label={section.label}\n          aria-current={index === inView ? \"true\" : undefined}\n          tabIndex={index === active ? 0 : -1}\n          data-ouro-control=\"emoji-picker\"\n          data-ouro-part=\"category\"\n          className={barButtonClass}\n          onClick={() => onJump(index)}\n        >\n          <span aria-hidden=\"true\" className=\"flex items-center justify-center\">\n            {section.icon}\n          </span>\n        </button>\n      ))}\n    </div>\n  );\n}\n\n/** The name of the emoji under the mouse or in focus, beside its glyph. */\nfunction Preview({ item, tone, render, play }: { item: EmojiPickerEmoji | undefined; tone: EmojiSkinTone; render: GlyphRender | undefined; play: boolean }) {\n  return (\n    <div aria-hidden=\"true\" className={previewClass}>\n      {item && (\n        <>\n          <span className={previewGlyphClass}>{glyphOf(item, tone, render, play)}</span>\n          <span className=\"min-w-0 truncate\">{item.name}</span>\n        </>\n      )}\n    </div>\n  );\n}\n\nfunction Panel({ categories, frequent, quick, render, toneGlyph, tone, setTone, asSheet, labels, className, onChoose }: PanelProps): JSX.Element {\n  const id = useId();\n  const [query, setQuery] = useState(\"\");\n  const [activeCell, setActive] = useState(0);\n  const [hovered, setHovered] = useState<EmojiPickerEmoji | undefined>(undefined);\n  // Focus is on an emoji in the grid, so the preview of the one in focus plays.\n  const [gridFocus, setGridFocus] = useState(false);\n  const { choosingTone, openTones, doneChoosingTone, toneButtonRef } = useToneChoice();\n\n  const searchRef = useRef<HTMLInputElement>(null);\n  const scrollerRef = useRef<HTMLDivElement>(null);\n  // Stryker disable next-line ArrayDeclaration: each section's ref callback fills its own entry before anything reads it.\n  const sectionRefs = useRef<(HTMLElement | null)[]>([]);\n\n  const { searching, sections, rows, total } = useSections(categories, frequent, query, labels, render);\n  // Read as the panel mounts: it mounts only in the browser, as the picker opens, never on the server.\n  const [saving] = useState(savingData);\n  // The app can take emoji away while the picker is open; the Tab stop stays on the last one.\n  const active = Math.min(activeCell, total - 1);\n  const itemAt = (index: number) => {\n    const section = sections.findLast((entry) => entry.start <= index)!;\n    return section.items[index - section.start]!;\n  };\n\n  useAnnouncement(searching ? (total ? fillCount(labels.resultsLabel, total) : labels.noResultsLabel) : \"\");\n\n  const tonesShown = offersTones(frequent) || offersTones(quick) || categories.some((category) => offersTones(category.emoji));\n  // Whether there is a category bar, searching or not: while there is a search its row stays, unseen, and the results\n  // take it, so the panel keeps its height and the search field stays where it is (a sheet is held at its foot, and lost\n  // the bar's height on the first letter typed: ourostack/ouro-ui#696).\n  const barShown = (frequent?.length ? 1 : 0) + categories.filter((category) => category.emoji.length).length > 1;\n\n  // The grid's focus handler makes the cell that gains focus the Tab stop.\n  const focusCell = (index: number) => scrollerRef.current!.querySelector<HTMLElement>(`[data-cell=\"${index}\"]`)!.focus();\n  const onGridKey = useGridKeys(rows, sections.length, () => searchRef.current!.focus(), focusCell);\n  const { categoryActive, setCategoryActive, inView, onScroll, jumpTo } = useCategoryScroll(scrollerRef, sectionRefs, (index) => focusCell(sections[index]!.start));\n\n  const preview = hovered ?? (total ? itemAt(active) : undefined);\n\n  return (\n    <div data-ouro=\"emoji-picker\" className={cn(panelClass, asSheet ? \"w-full\" : \"w-[21rem] max-w-full\", className)}>\n      <div className=\"flex min-w-0 shrink-0 items-center gap-1\">\n        {choosingTone ? (\n          <ToneChoice tone={tone} setTone={setTone} label={labels.skinToneLabel} names={labels.skinToneNames} glyph={toneGlyph} onDone={doneChoosingTone} />\n        ) : (\n          <>\n            <TextField\n              ref={searchRef}\n              type=\"search\"\n              label={labels.searchLabel}\n              hideLabel\n              placeholder={labels.searchLabel}\n              clearable\n              startAdornment={<SearchIcon />}\n              value={query}\n              className=\"min-w-0 flex-1\"\n              onChange={(event) => {\n                setQuery(event.currentTarget.value);\n                setActive(0);\n                setHovered(undefined);\n                scrollerRef.current!.scrollTop = 0;\n              }}\n              onKeyDown={(event) => {\n                if (event.key === \"ArrowDown\" && total) {\n                  event.preventDefault();\n                  focusCell(active);\n                } else if (event.key === \"Enter\" && searching && total) {\n                  event.preventDefault();\n                  onChoose(itemAt(0), event);\n                }\n              }}\n            />\n            {tonesShown && <ToneButton tone={tone} labels={labels} glyph={toneGlyph} buttonRef={toneButtonRef} onOpen={openTones} />}\n          </>\n        )}\n      </div>\n      {quick?.length ? <QuickRow quick={quick} tone={tone} render={render} label={labels.quickLabel} onChoose={onChoose} /> : null}\n      <div className={cn(bodyClass, barShown ? \"grid-rows-[auto_18rem]\" : \"grid-rows-[18rem]\")}>\n        {barShown &&\n          (searching ? (\n            <div aria-hidden=\"true\" inert className={cn(barClass, \"invisible\")}>\n              <span className={barButtonClass} />\n            </div>\n          ) : (\n            <CategoryBar sections={sections} label={labels.categoriesLabel} active={categoryActive} inView={inView} setActive={setCategoryActive} onJump={jumpTo} />\n          ))}\n        <div\n          ref={scrollerRef}\n          className={cn(scrollerClass, searching && barShown && \"absolute inset-0\")}\n          onScroll={onScroll}\n          onKeyDown={onGridKey}\n          onClick={(event) => {\n            const cell = cellOf(event);\n            if (cell) onChoose(itemAt(Number(cell.dataset.cell)), event);\n          }}\n          onPointerOver={(event) => {\n            const cell = cellOf(event);\n            if (cell && event.pointerType === \"mouse\") setHovered(itemAt(Number(cell.dataset.cell)));\n          }}\n          onPointerLeave={() => setHovered(undefined)}\n          onFocus={(event) => {\n            const cell = cellOf(event);\n            if (cell) setActive(Number(cell.dataset.cell));\n            setGridFocus(Boolean(cell));\n          }}\n          // Focus moving on to another emoji is this blur and its focus in one render, so the preview never stops between them.\n          onBlur={() => setGridFocus(false)}\n        >\n          {total === 0 ? (\n            <p className=\"m-0 px-1 py-6 text-sm leading-5 text-muted-foreground\">{searching ? labels.noResultsLabel : null}</p>\n          ) : (\n            <Grids id={id} sections={sections} rows={rows} tone={tone} render={render} active={active} sectionRefs={sectionRefs} saving={saving} />\n          )}\n        </div>\n      </div>\n      <Preview item={preview} tone={tone} render={render} play={hovered !== undefined || gridFocus} />\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/emoji-picker/emoji-picker.tsx"
    }
  ],
  "docs": "An emoji picker for reactions and for putting emoji into text. Import: import { EmojiPicker } from \"@/components/ouro/emoji-picker/emoji-picker\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: button, emoji, field, popover, sheet, text-field, 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/emoji-picker.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}