hightable
Version:
A dynamic windowed scrolling table component for react
40 lines (39 loc) • 1.65 kB
TypeScript
import { RefObject } from 'react';
/**
* A hook that manages focus behavior for interactive UI components like menus or modals.
*
* This hook handles focus management by storing the previously focused element when
* a component opens, focusing the first focusable element within the component,
* and restoring focus to the original element when the component closes. This is
* essential for accessibility and keyboard navigation.
*
* @param isOpen - Boolean indicating whether the component is open.
* When true, captures current focus and moves focus to the first
* focusable element in the menu. When false, restores focus to
* the previously focused element.
* @param menuRef - React ref object pointing to the container element that
* contains the focusable elements to manage.
*
* @returns An object containing:
* - getFocusableElements: Function that returns all focusable elements
* within the menu container using the standard focusable selector.
*
* @example
* ```tsx
* function DropdownMenu({ isOpen }: { isOpen: boolean }) {
* const menuRef = useRef<HTMLDivElement | null>(null)
* const { getFocusableElements } = useFocusManagement(isOpen, menuRef)
*
* return (
* <div ref={menuRef}>
* <button>Option 1</button>
* <button>Option 2</button>
* </div>
* )
* }
* ```
*/
export declare function useFocusManagement(isOpen: boolean, menuRef: RefObject<HTMLDivElement | null>): {
getFocusableElements: () => HTMLElement[];
navigateFocus: (direction: "next" | "previous" | "first" | "last") => void;
};