1 | import { __rest } from "tslib";
|
2 | import * as React from 'react';
|
3 | import { createFocusTrap } from 'focus-trap';
|
4 | export 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 |
|
14 |
|
15 |
|
16 |
|
17 |
|
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 |
|
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 | }
|
54 | FocusTrap.displayName = 'FocusTrap';
|
55 | FocusTrap.defaultProps = {
|
56 | active: true,
|
57 | paused: false,
|
58 | focusTrapOptions: {},
|
59 | preventScrollOnDeactivate: false
|
60 | };
|
61 |
|
\ | No newline at end of file |