UNPKG

@hypothesis/frontend-shared

Version:

Shared components, styles and utilities for Hypothesis projects

76 lines (75 loc) 2.85 kB
import type { RefObject } from 'preact'; export type UseArrowKeyNavigationOptions = { /** * Whether to focus the first element in the set of matching elements when * the component is mounted */ autofocus?: boolean; /** * Whether focus should loop back to the first element once the end of the * list is reached. Defaults to `true`. */ loop?: boolean; /** Enable navigating elements using left/right arrow keys */ horizontal?: boolean; /** Enable navigating elements using up/down arrow keys */ vertical?: boolean; /** * CSS selector which specifies the elements that navigation moves between */ selector?: string; /** * Indicates if the container element is currently visible. * This information is used to focus the current element when the container * transitions from hidden to visible. * * Defaults to `true`. */ containerVisible?: boolean; /** * Callback that can be used to customize what happens when this hook wants * to focus an element. * * The default implementation just calls {@link HTMLElement.focus}. * * @param {el} The element within the container to focus * @param {event} The key event which triggered this focus change. May be * unset if the focus update is not happening due to an arrow key press * within the container. For example if tabbing into the container. */ focusElement?: (el: HTMLElement, event?: KeyboardEvent) => void; }; /** * Enable arrow key navigation between interactive descendants of a * container element. * * In addition to moving focus between elements when arrow keys are pressed, * this also implements the "roving tabindex" pattern [1] which sets the * `tabindex` attribute of elements to control which element gets focus when the * user tabs into the container. * * See [2] for a reference of how keyboard navigation should work in web * applications and how it applies to various common widgets. * * @example * function MyToolbar() { * const container = useRef(); * * // Enable arrow key navigation between interactive elements in the * // toolbar container. * useArrowKeyNavigation(container); * * return ( * <div ref={container} role="toolbar"> * <button>Bold</bold> * <button>Italic</bold> * <a href="https://example.com/help">Help</a> * </div> * ) * } * * [1] https://www.w3.org/TR/wai-aria-practices/#kbd_roving_tabindex * [2] https://www.w3.org/TR/wai-aria-practices/#keyboard * */ export declare function useArrowKeyNavigation(containerRef: RefObject<HTMLElement | undefined>, { autofocus, loop, horizontal, vertical, selector, containerVisible, focusElement: focusElement_, }?: UseArrowKeyNavigationOptions): void;