{"version":3,"file":"useVirtualizedListboxKeyboardNavigation.mjs","names":[],"sources":["../../../../src/a11y/hooks/useVirtualizedListboxKeyboardNavigation.ts"],"sourcesContent":["import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from 'react';\nimport { useCallback, useRef } from 'react';\n\nimport { getNextRovingFocusIndex } from '../a11yUtils';\n\nconst DEFAULT_OPTION_SELECTOR = '[role=\"option\"]';\n// A virtual list's \"rendered\" callback can fire a frame before the row paints, so focusing after a\n// scroll retries across a few animation frames.\nconst MAX_FOCUS_ATTEMPTS_AFTER_SCROLL = 5;\n\n// Escapes a value for a quoted attribute selector (`[attr=\"value\"]`).\nconst escapeAttributeValue = (value: string) => value.replace(/([\"\\\\])/g, '\\\\$1');\n\nexport type VirtualizedListboxKeyboardNavigationParams<T> = {\n  /** Stable ID of an item; must equal the value its option carries in `itemIdAttribute`. */\n  getItemId: (item: T) => string;\n  /** Attribute every option carries its ID in, to find the active item and the target option. */\n  itemIdAttribute: string;\n  /** The full, unvirtualized list, not just the rendered window. */\n  items: T[];\n  /** Selector for the focusable option elements. Defaults to `[role=\"option\"]`. */\n  optionSelector?: string;\n  /**\n   * Brings the item at `index` into the rendered window and calls `onRendered` once it should be in\n   * the DOM. A non-virtualized list can call `onRendered()` directly.\n   */\n  scrollIndexIntoView: (index: number, onRendered: () => void) => void;\n  /** Ref to the scrollable listbox container whose subtree holds the rendered options. */\n  scrollerRef: RefObject<HTMLElement | null>;\n};\n\n/**\n * Roving-focus navigation (ArrowUp/Down/Home/End) for a virtualized listbox, where only a window of\n * `role=\"option\"` rows is in the DOM. It indexes into the full `items` array, focuses the target\n * row if it is rendered, and otherwise calls `scrollIndexIntoView` and focuses it once painted.\n *\n * Returns `onKeyDown` to spread onto the scroll container, which `scrollerRef` must also point to.\n * The active item is read from the closest element at or above `document.activeElement` that\n * carries `itemIdAttribute`.\n */\nexport const useVirtualizedListboxKeyboardNavigation = <T>({\n  getItemId,\n  itemIdAttribute,\n  items,\n  optionSelector = DEFAULT_OPTION_SELECTOR,\n  scrollerRef,\n  scrollIndexIntoView,\n}: VirtualizedListboxKeyboardNavigationParams<T>) => {\n  // Bumped on every roving key press. A deferred post-scroll focus chain bails once a newer press\n  // supersedes it, so a slow older scroll cannot steal focus back to an outdated row.\n  const latestFocusRequestRef = useRef(0);\n\n  // Focuses the option for `items[index]` if it is in the DOM; returns whether it was.\n  const focusOptionAt = useCallback(\n    (index: number) => {\n      const item = items[index];\n      if (!item) return false;\n      const option = scrollerRef.current?.querySelector<HTMLElement>(\n        `${optionSelector}[${itemIdAttribute}=\"${escapeAttributeValue(getItemId(item))}\"]`,\n      );\n      if (!option) return false;\n      option.focus();\n      return true;\n    },\n    [getItemId, itemIdAttribute, items, optionSelector, scrollerRef],\n  );\n\n  const focusOptionAfterRender = useCallback(\n    (\n      index: number,\n      requestId: number,\n      attemptsLeft = MAX_FOCUS_ATTEMPTS_AFTER_SCROLL,\n    ) => {\n      // A newer key press superseded this chain.\n      if (requestId !== latestFocusRequestRef.current) return;\n      if (focusOptionAt(index) || attemptsLeft <= 0) return;\n      requestAnimationFrame(() =>\n        focusOptionAfterRender(index, requestId, attemptsLeft - 1),\n      );\n    },\n    [focusOptionAt],\n  );\n\n  const onKeyDown = useCallback(\n    (event: ReactKeyboardEvent<HTMLElement>) => {\n      const active = document.activeElement;\n      const activeId =\n        active instanceof HTMLElement\n          ? (active\n              .closest<HTMLElement>(`[${itemIdAttribute}]`)\n              ?.getAttribute(itemIdAttribute) ?? undefined)\n          : undefined;\n      const activeIndex =\n        activeId != null ? items.findIndex((item) => getItemId(item) === activeId) : -1;\n      const nextIndex = getNextRovingFocusIndex({\n        activeIndex,\n        itemCount: items.length,\n        key: event.key,\n      });\n      if (nextIndex === null) return; // Not a roving key.\n\n      event.preventDefault();\n      event.stopPropagation();\n      // Supersedes any pending off-window focus chain from an earlier key press.\n      const requestId = ++latestFocusRequestRef.current;\n      // A rendered row is focused right away (native focus scrolls it fully into view); otherwise\n      // scroll it into existence and focus it once the list has painted it.\n      if (focusOptionAt(nextIndex)) return;\n      scrollIndexIntoView(nextIndex, () => focusOptionAfterRender(nextIndex, requestId));\n    },\n    [\n      focusOptionAfterRender,\n      focusOptionAt,\n      getItemId,\n      itemIdAttribute,\n      items,\n      scrollIndexIntoView,\n    ],\n  );\n\n  return { onKeyDown };\n};\n"],"mappings":";;;AAKA,IAAM,0BAA0B;AAGhC,IAAM,kCAAkC;AAGxC,IAAM,wBAAwB,UAAkB,MAAM,QAAQ,YAAY,MAAM;;;;;;;;;;AA6BhF,IAAa,2CAA8C,EACzD,WACA,iBACA,OACA,iBAAiB,yBACjB,aACA,0BACmD;CAGnD,MAAM,wBAAwB,OAAO,CAAC;CAGtC,MAAM,gBAAgB,aACnB,UAAkB;EACjB,MAAM,OAAO,MAAM;EACnB,IAAI,CAAC,MAAM,OAAO;EAClB,MAAM,SAAS,YAAY,SAAS,cAClC,GAAG,eAAe,GAAG,gBAAgB,IAAI,qBAAqB,UAAU,IAAI,CAAC,EAAE,GACjF;EACA,IAAI,CAAC,QAAQ,OAAO;EACpB,OAAO,MAAM;EACb,OAAO;CACT,GACA;EAAC;EAAW;EAAiB;EAAO;EAAgB;CAAW,CACjE;CAEA,MAAM,yBAAyB,aAE3B,OACA,WACA,eAAe,oCACZ;EAEH,IAAI,cAAc,sBAAsB,SAAS;EACjD,IAAI,cAAc,KAAK,KAAK,gBAAgB,GAAG;EAC/C,4BACE,uBAAuB,OAAO,WAAW,eAAe,CAAC,CAC3D;CACF,GACA,CAAC,aAAa,CAChB;CAuCA,OAAO,EAAE,WArCS,aACf,UAA2C;EAC1C,MAAM,SAAS,SAAS;EACxB,MAAM,WACJ,kBAAkB,cACb,OACE,QAAqB,IAAI,gBAAgB,EAAE,CAAC,EAC3C,aAAa,eAAe,KAAK,KAAA,IACrC,KAAA;EAGN,MAAM,YAAY,wBAAwB;GACxC,aAFA,YAAY,OAAO,MAAM,WAAW,SAAS,UAAU,IAAI,MAAM,QAAQ,IAAI;GAG7E,WAAW,MAAM;GACjB,KAAK,MAAM;EACb,CAAC;EACD,IAAI,cAAc,MAAM;EAExB,MAAM,eAAe;EACrB,MAAM,gBAAgB;EAEtB,MAAM,YAAY,EAAE,sBAAsB;EAG1C,IAAI,cAAc,SAAS,GAAG;EAC9B,oBAAoB,iBAAiB,uBAAuB,WAAW,SAAS,CAAC;CACnF,GACA;EACE;EACA;EACA;EACA;EACA;EACA;CACF,CAGO,EAAU;AACrB"}