Debian Codegraph @

node/@patternfly/react-core/dist/esm/helpers/FocusTrap/FocusTrap.js

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