UNPKG

2.58 kBJavaScriptView Raw
1import { __rest } from "tslib";
2import * as React from 'react';
3import { createFocusTrap } from 'focus-trap';
4export class FocusTrap extends React.Component {
5 constructor(props) {
6 super(props);
7 this.divRef = React.createRef();
8 if (typeof document !== 'undefined') {
9 this.previouslyFocusedElement = document.activeElement;
10 }
11 }
12 componentDidMount() {
13 // We need to hijack the returnFocusOnDeactivate option,
14 // because React can move focus into the element before we arrived at
15 // this lifecycle hook (e.g. with autoFocus inputs). So the component
16 // captures the previouslyFocusedElement in componentWillMount,
17 // then (optionally) returns focus to it in componentWillUnmount.
18 this.focusTrap = createFocusTrap(this.divRef.current, Object.assign(Object.assign({}, this.props.focusTrapOptions), { returnFocusOnDeactivate: false }));
19 if (this.props.active) {
20 this.focusTrap.activate();
21 }
22 if (this.props.paused) {
23 this.focusTrap.pause();
24 }
25 }
26 componentDidUpdate(prevProps) {
27 if (prevProps.active && !this.props.active) {
28 this.focusTrap.deactivate();
29 }
30 else if (!prevProps.active && this.props.active) {
31 this.focusTrap.activate();
32 }
33 if (prevProps.paused && !this.props.paused) {
34 this.focusTrap.unpause();
35 }
36 else if (!prevProps.paused && this.props.paused) {
37 this.focusTrap.pause();
38 }
39 }
40 componentWillUnmount() {
41 this.focusTrap.deactivate();
42 if (this.props.focusTrapOptions.returnFocusOnDeactivate !== false &&
43 this.previouslyFocusedElement &&
44 this.previouslyFocusedElement.focus) {
45 this.previouslyFocusedElement.focus({ preventScroll: this.props.preventScrollOnDeactivate });
46 }
47 }
48 render() {
49 // eslint-disable-next-line @typescript-eslint/no-unused-vars
50 const _a = this.props, { children, className, focusTrapOptions, active, paused, preventScrollOnDeactivate } = _a, rest = __rest(_a, ["children", "className", "focusTrapOptions", "active", "paused", "preventScrollOnDeactivate"]);
51 return (React.createElement("div", Object.assign({ ref: this.divRef, className: className }, rest), children));
52 }
53}
54FocusTrap.displayName = 'FocusTrap';
55FocusTrap.defaultProps = {
56 active: true,
57 paused: false,
58 focusTrapOptions: {},
59 preventScrollOnDeactivate: false
60};
61//# sourceMappingURL=FocusTrap.js.map
\No newline at end of file