{"version":3,"file":"useListboxKeyboardNavigation.mjs","names":[],"sources":["../../../../src/a11y/hooks/useListboxKeyboardNavigation.ts"],"sourcesContent":["import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from 'react';\n\nimport { getNextRovingFocusIndex } from '../a11yUtils';\n\nconst DEFAULT_OPTION_SELECTOR = '[role=\"option\"]';\nconst VERTICAL_KEYS = ['ArrowUp', 'ArrowDown', 'Home', 'End'];\n\n/** State handed to a {@link ListboxKeyHandler} when its key is pressed inside the container. */\nexport type ListboxNavigationContext = {\n  /** The focused element, always inside the container. */\n  active: HTMLElement;\n  /** The listbox container element. */\n  container: HTMLElement;\n  /** Queries the current option elements on each call. */\n  getOptions: () => HTMLElement[];\n  /** Whether {@link ListboxNavigationContext.active} is itself an option. */\n  onOption: boolean;\n};\n\n/**\n * Handler for a non-roving key. Returning `true` marks the key as handled and the hook calls\n * `preventDefault()` and `stopPropagation()`; any other return lets the key fall through.\n */\nexport type ListboxKeyHandler = (context: ListboxNavigationContext) => boolean | void;\n\nexport type ListboxKeyboardNavigationConfig = {\n  /**\n   * Where the roving (Up/Down/Home/End) keys are active. Defaults to `'option'`.\n   * - `'option'`: only while focus is on an option.\n   * - `'container'`: anywhere inside the container, so focus can enter the list from a preceding\n   *   control. Off an option, Down and Home focus the first option, Up and End the last.\n   */\n  enterScope?: 'container' | 'option';\n  /**\n   * Extra handlers by `event.key`; {@link createRowActionKeyHandlers} builds a ready-made set.\n   * Up, Down, Home and End are reserved for roving and never reach a handler.\n   */\n  keyHandlers?: Record<string, ListboxKeyHandler>;\n  /** Selector for the navigable options. Defaults to `[role=\"option\"]`. */\n  optionSelector?: string;\n  /**\n   * Maps the focused element to the option that roving moves relative to, for focus on something\n   * inside an option's row. Use with `enterScope: 'container'`. Returning `null` treats no option\n   * as active, so Down lands on the first option and Up on the last.\n   */\n  resolveActiveOption?: (active: HTMLElement) => HTMLElement | null;\n};\n\n/**\n * Keyboard navigation for a listbox. Returns `onKeyDown` to spread onto the container and\n * `getOptions` to query the current options.\n *\n * ArrowUp/ArrowDown/Home/End rove the options (see `enterScope`); other keys go to `keyHandlers`.\n * Handled keys call `preventDefault()` and `stopPropagation()`, so neither an ancestor handler nor\n * a browser default can move focus to a non-option. Options are read from the DOM on each key.\n */\nexport const useListboxKeyboardNavigation = (\n  containerRef: RefObject<HTMLElement | null>,\n  {\n    enterScope = 'option',\n    keyHandlers,\n    optionSelector = DEFAULT_OPTION_SELECTOR,\n    resolveActiveOption,\n  }: ListboxKeyboardNavigationConfig = {},\n) => {\n  const getOptions = () =>\n    Array.from(containerRef.current?.querySelectorAll<HTMLElement>(optionSelector) ?? []);\n\n  const onKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {\n    const container = containerRef.current;\n    const active = document.activeElement;\n    if (!container || !(active instanceof HTMLElement) || !container.contains(active)) {\n      return;\n    }\n\n    const onOption = active.matches(optionSelector);\n\n    if (VERTICAL_KEYS.includes(event.key)) {\n      if (enterScope === 'option' && !onOption) return;\n      const options = getOptions();\n      // Move relative to the focused option, or to the one `resolveActiveOption` maps the focus to.\n      const current = onOption ? active : (resolveActiveOption?.(active) ?? null);\n      const nextIndex = getNextRovingFocusIndex({\n        activeIndex: current ? options.indexOf(current) : -1,\n        itemCount: options.length,\n        key: event.key,\n      });\n      if (nextIndex === null) return;\n      event.preventDefault();\n      event.stopPropagation();\n      options[nextIndex]?.focus();\n      return;\n    }\n\n    const handled = keyHandlers?.[event.key]?.({\n      active,\n      container,\n      getOptions,\n      onOption,\n    });\n    if (handled) {\n      event.preventDefault();\n      event.stopPropagation();\n    }\n  };\n\n  return { getOptions, onKeyDown };\n};\n\n/**\n * ArrowLeft/ArrowRight {@link ListboxKeyHandler}s for an option that sits in a row next to action\n * targets. The option and its actions form one cyclic group in DOM order, so the actions need not\n * be in the Tab order. A row with a lone option leaves the keys unhandled. Pass the result as (part\n * of) `keyHandlers`.\n */\nexport const createRowActionKeyHandlers = ({\n  actionSelector,\n  optionSelector = DEFAULT_OPTION_SELECTOR,\n  rowSelector,\n}: {\n  actionSelector: string;\n  optionSelector?: string;\n  rowSelector: string;\n}): Record<string, ListboxKeyHandler> => {\n  const rove =\n    (step: -1 | 1): ListboxKeyHandler =>\n    ({ active }) => {\n      const row = active.closest(rowSelector);\n      if (!row) return;\n      // The option and its action targets in DOM order, as one cyclic group.\n      const items = Array.from(\n        row.querySelectorAll<HTMLElement>(`${optionSelector}, ${actionSelector}`),\n      );\n      if (items.length < 2) return; // A lone option has nothing to move between.\n      const index = items.indexOf(active);\n      if (index === -1) return;\n      items[(index + step + items.length) % items.length].focus();\n      return true;\n    };\n\n  return { ArrowLeft: rove(-1), ArrowRight: rove(1) };\n};\n"],"mappings":";;AAIA,IAAM,0BAA0B;AAChC,IAAM,gBAAgB;CAAC;CAAW;CAAa;CAAQ;AAAK;;;;;;;;;AAmD5D,IAAa,gCACX,cACA,EACE,aAAa,UACb,aACA,iBAAiB,yBACjB,wBACmC,CAAC,MACnC;CACH,MAAM,mBACJ,MAAM,KAAK,aAAa,SAAS,iBAA8B,cAAc,KAAK,CAAC,CAAC;CAEtF,MAAM,aAAa,UAA2C;EAC5D,MAAM,YAAY,aAAa;EAC/B,MAAM,SAAS,SAAS;EACxB,IAAI,CAAC,aAAa,EAAE,kBAAkB,gBAAgB,CAAC,UAAU,SAAS,MAAM,GAC9E;EAGF,MAAM,WAAW,OAAO,QAAQ,cAAc;EAE9C,IAAI,cAAc,SAAS,MAAM,GAAG,GAAG;GACrC,IAAI,eAAe,YAAY,CAAC,UAAU;GAC1C,MAAM,UAAU,WAAW;GAE3B,MAAM,UAAU,WAAW,SAAU,sBAAsB,MAAM,KAAK;GACtE,MAAM,YAAY,wBAAwB;IACxC,aAAa,UAAU,QAAQ,QAAQ,OAAO,IAAI;IAClD,WAAW,QAAQ;IACnB,KAAK,MAAM;GACb,CAAC;GACD,IAAI,cAAc,MAAM;GACxB,MAAM,eAAe;GACrB,MAAM,gBAAgB;GACtB,QAAQ,UAAU,EAAE,MAAM;G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