| 1 |
"use strict"; |
| 2 |
Object.defineProperty(exports, "__esModule", { value: true }); |
| 3 |
exports.FocusTrap = void 0; |
| 4 |
const tslib_1 = require("tslib"); |
| 5 |
const jsx_runtime_1 = require("react/jsx-runtime"); |
| 6 |
const focus_trap_1 = require("focus-trap"); |
| 7 |
const react_1 = require("react"); |
| 8 |
const useUnmountEffect_1 = require("../useUnmountEffect"); |
| 9 |
exports.FocusTrap = (0, react_1.forwardRef)(function FocusTrap(_a, forwardedRef) { |
| 10 |
var { active = true, paused = false, focusTrapOptions = {}, preventScrollOnDeactivate = false } = _a, props = tslib_1.__rest(_a, ["active", "paused", "focusTrapOptions", "preventScrollOnDeactivate"]); |
| 11 |
// Fall back to internal ref if no forwarded ref is provided. |
| 12 |
const ref = (0, react_1.useRef)(null); |
| 13 |
(0, react_1.useImperativeHandle)(forwardedRef, () => ref.current); |
| 14 |
// Create focus trap instance after rendering DOM. |
| 15 |
const focusTrapRef = (0, react_1.useRef)(null); |
| 16 |
(0, react_1.useEffect)(() => { |
| 17 |
const focusTrap = (0, focus_trap_1.createFocusTrap)(ref.current, Object.assign(Object.assign({}, focusTrapOptions), { returnFocusOnDeactivate: false })); |
| 18 |
focusTrapRef.current = focusTrap; |
| 19 |
// Deactivate focus trap on cleanup. |
| 20 |
return () => { |
| 21 |
focusTrap.deactivate(); |
| 22 |
}; |
| 23 |
}, []); |
| 24 |
// Handle activation status based on 'active' prop. |
| 25 |
(0, react_1.useEffect)(() => { |
| 26 |
const focusTrap = focusTrapRef.current; |
| 27 |
active ? focusTrap === null || focusTrap === void 0 ? void 0 : focusTrap.activate() : focusTrap === null || focusTrap === void 0 ? void 0 : focusTrap.deactivate(); |
| 28 |
}, [active]); |
| 29 |
// Handle pause status based on 'pause' prop. |
| 30 |
(0, react_1.useEffect)(() => { |
| 31 |
const focusTrap = focusTrapRef.current; |
| 32 |
paused ? focusTrap === null || focusTrap === void 0 ? void 0 : focusTrap.pause() : focusTrap === null || focusTrap === void 0 ? void 0 : focusTrap.unpause(); |
| 33 |
}, [paused]); |
| 34 |
// Store the currently active element to restore focus to later. |
| 35 |
const previousElementRef = (0, react_1.useRef)(typeof document !== 'undefined' ? document.activeElement : null); |
| 36 |
// Restore focus to the previously active element on unmount. |
| 37 |
(0, useUnmountEffect_1.useUnmountEffect)(() => { |
| 38 |
if (focusTrapOptions.returnFocusOnDeactivate !== false && previousElementRef.current instanceof HTMLElement) { |
| 39 |
previousElementRef.current.focus({ |
| 40 |
preventScroll: preventScrollOnDeactivate |
| 41 |
}); |
| 42 |
} |
| 43 |
}); |
| 44 |
return (0, jsx_runtime_1.jsx)("div", Object.assign({ ref: ref }, props)); |
| 45 |
}); |
| 46 |
exports.FocusTrap.displayName = 'FocusTrap'; |
| 47 |
//# sourceMappingURL=FocusTrap.js.map |