import { createFocusTrap } from "focus-trap";
import React from "react";
import { keys } from "./../ts-utils/keys.js";
const checkedProps = ["active", "paused", "tag", "focusTrapOptions", "_createFocusTrap"];
class FocusTrap extends React.Component {
  constructor() {
    super(...arguments);
    this.setNode = (el) => this.node = el;
  }
  componentDidMount() {
    const options = this.getOptionsWithScopedInitialFocus();
    this.focusTrap = this.props._createFocusTrap(this.node, options);
    if (!this.node.firstElementChild?.hasAttribute("nofocus")) {
      if (this.props.active) {
        this.focusTrap.activate();
      }
      if (this.props.paused) {
        this.focusTrap.pause();
      }
    }
  }
  getOptionsWithScopedInitialFocus() {
    const options = this.props.focusTrapOptions;
    if (!options?.initialFocus) {
      return {
        ...options,
        initialFocus: () => {
          const autofocusElement = this.node.querySelector("[data-autofocus]");
          return autofocusElement || void 0;
        }
      };
    }
    return options;
  }
  componentDidUpdate(prevProps) {
    if (prevProps.active && !this.props.active) {
      this.focusTrap.deactivate();
    } else if (!prevProps.active && this.props.active) {
      this.focusTrap.activate();
    }
    if (prevProps.paused && !this.props.paused) {
      this.focusTrap.unpause();
    } else if (!prevProps.paused && this.props.paused) {
      this.focusTrap.pause();
    }
  }
  componentWillUnmount() {
    this.focusTrap.deactivate();
  }
  render() {
    const elementProps = keys(this.props).filter(
      (prop) => Object.prototype.hasOwnProperty.call(this.props, prop) && !checkedProps.includes(prop)
    ).reduce(
      (resultProps, prop) => ({
        ...resultProps,
        [prop]: this.props[prop]
      }),
      {
        ref: this.setNode
      }
    );
    return React.createElement(this.props.tag, elementProps, this.props.children);
  }
}
FocusTrap.defaultProps = {
  active: true,
  tag: "div",
  paused: false,
  focusTrapOptions: {},
  _createFocusTrap: createFocusTrap
};
export {
  FocusTrap
};
//# sourceMappingURL=focus-trap-react.js.map
