import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

function setRef(ref, value) {
  if (typeof ref === 'function') {
    ref(value);
  } else if (ref) {
    ref.current = value;
  }
}
/**
 * 帮助获取ref
 * https://github.com/facebook/react/issues/11401#issuecomment-340543801.
 * 例如：
 * ```jsx
 * import React from 'react';
 * import RootRef from '@material-ui/core/RootRef';
 *
 * class MyComponent extends React.Component {
 *   constructor() {
 *     super();
 *     this.domRef = React.createRef();
 *   }
 *
 *   componentDidMount() {
 *     console.log(this.domRef.current); // DOM node
 *   }
 *
 *   render() {
 *     return (
 *       <RootRef rootRef={this.domRef}>
 *         <SomeChildComponent />
 *       </RootRef>
 *     );
 *   }
 * }
 * ```
 */


var RootRef =
/*#__PURE__*/
function (_React$Component) {
  _inherits(RootRef, _React$Component);

  function RootRef() {
    _classCallCheck(this, RootRef);

    return _possibleConstructorReturn(this, _getPrototypeOf(RootRef).apply(this, arguments));
  }

  _createClass(RootRef, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var rootRef = this.props.rootRef;
      this.ref = ReactDOM.findDOMNode(this);
      setRef(rootRef, this.ref);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var rootRef = this.props.rootRef;
      var ref = ReactDOM.findDOMNode(this);

      if (prevProps.rootRef !== rootRef || this.ref !== ref) {
        if (prevProps.rootRef !== rootRef) {
          setRef(prevProps.rootRef, null);
        }

        this.ref = ref;
        setRef(rootRef, this.ref);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var rootRef = this.props.rootRef;
      this.ref = null;
      setRef(rootRef, null);
    }
  }, {
    key: "render",
    value: function render() {
      var children = this.props.children;
      return children;
    }
  }]);

  return RootRef;
}(React.Component);

RootRef.propTypes = {
  /**
   * The wrapped element.
   */
  children: PropTypes.element.isRequired,

  /**
   * Provide a way to access the DOM node of the wrapped element.
   * You can provide a callback ref or a `React.createRef()` ref.
   */
  rootRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired
};
export default RootRef;