UNPKG

@workday/canvas-kit-react

Version:

The parent module that contains all Workday Canvas Kit React components

30 lines (29 loc) 1.53 kB
import React from 'react'; import { changeFocus, assert, getFirstFocusableElement, createElemPropsHook, } from '@workday/canvas-kit-react/common'; import { usePopupModel } from './usePopupModel'; /** * Moves focus within the popup when the popup becomes visible. This is useful for keyboard and * screen reader users alike. This should be used with {@link useFocusRedirect} or * {@link useFocusTrap} for a complete focus management solution. * * This should be used for popups that have focusable elements inside, like Modals, non-modal * dialogs, menus, etc. */ export const useInitialFocus = createElemPropsHook(usePopupModel)(model => { const visible = model.state.visibility !== 'hidden'; // Using `useEffect` instead of `useLayoutEffect` so that focus doesn't change _before_ PopperJS // has positioned the Popup. If we change focus before positioning, the browser will scroll to the // top of the page. React.useEffect(() => { var _a; if (visible && model.state.stackRef.current) { const element = ((_a = model.state.initialFocusRef) === null || _a === void 0 ? void 0 : _a.current) || getFirstFocusableElement(model.state.stackRef.current); assert(element, 'No focusable element was found. Please ensure popup has at least one focusable element'); requestAnimationFrame(() => { changeFocus(element); }); } }, [model.state.initialFocusRef, model.state.stackRef, visible]); return {}; });