@workday/canvas-kit-react
Version:
The parent module that contains all Workday Canvas Kit React components
36 lines (35 loc) • 1.83 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useInitialFocus = void 0;
const react_1 = __importDefault(require("react"));
const common_1 = require("@workday/canvas-kit-react/common");
const usePopupModel_1 = require("./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.
*/
exports.useInitialFocus = (0, common_1.createElemPropsHook)(usePopupModel_1.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_1.default.useEffect(() => {
var _a;
if (visible && model.state.stackRef.current) {
const element = ((_a = model.state.initialFocusRef) === null || _a === void 0 ? void 0 : _a.current) ||
(0, common_1.getFirstFocusableElement)(model.state.stackRef.current);
(0, common_1.assert)(element, 'No focusable element was found. Please ensure popup has at least one focusable element');
requestAnimationFrame(() => {
(0, common_1.changeFocus)(element);
});
}
}, [model.state.initialFocusRef, model.state.stackRef, visible]);
return {};
});
;