UNPKG

@workday/canvas-kit-react

Version:

The parent module that contains all Workday Canvas Kit React components

39 lines (38 loc) 1.74 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFocusTrap = void 0; const react_1 = __importDefault(require("react")); const focus_trap_js_1 = require("./focus-trap-js"); const common_1 = require("@workday/canvas-kit-react/common"); const usePopupModel_1 = require("./usePopupModel"); /** * "Trap" or "loop" focus within a provided `stackRef` element. This is required for accessibility * on modals. If a keyboard users hits the Tab or Shift + Tab, this will force "looping" of focus. * It effectively "hides" outside content from keyboard users. Use an overlay to hide content from * mouse users and `useAssistiveHideSiblings` to hide content from assistive technology users. Works * well with `useInitialFocus` and `useReturnFocus`. * * This should be used on popup elements that need to hide content (i.e. Modals). */ exports.useFocusTrap = (0, common_1.createElemPropsHook)(usePopupModel_1.usePopupModel)(model => { const onKeyDown = react_1.default.useCallback((event) => { if (model.state.stackRef.current) { (0, focus_trap_js_1.tabTrappingKey)(event, model.state.stackRef.current); } }, [model.state.stackRef]); const visible = model.state.visibility !== 'hidden'; // `useLayoutEffect` for automation react_1.default.useLayoutEffect(() => { if (!visible) { return; } document.addEventListener('keydown', onKeyDown); return () => { document.removeEventListener('keydown', onKeyDown); }; }, [visible, onKeyDown]); return {}; });