"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _Dock = _interopRequireDefault(require("../../../styles/cspace-ui/Dock.css"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

/* global window */
const propTypes = {
  children: _propTypes.default.element,
  dockTop: _propTypes.default.number,
  isSidebarOpen: _propTypes.default.bool
};
const defaultProps = {
  isSidebarOpen: true
};

class Dock extends _react.Component {
  constructor(props) {
    super(props);
    this.setDomNode = this.setDomNode.bind(this);
    this.handleScroll = this.handleScroll.bind(this);
    this.state = {
      docked: false
    };
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll, false);
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll, false);
  }

  setDomNode(ref) {
    this.domNode = ref;
  }

  handleScroll() {
    const node = this.domNode;
    if (!node) return;
    const {
      dockTop
    } = this.props;

    if (this.state.docked) {
      if (window.scrollY + dockTop < node.offsetTop) {
        this.setState({
          docked: false
        });
      }
    } else if (window.scrollY + dockTop >= node.offsetTop) {
      this.setState({
        docked: true
      });
    }
  }

  render() {
    const {
      children,
      dockTop,
      isSidebarOpen
    } = this.props;
    const {
      docked
    } = this.state;
    const className = (0, _classnames.default)(isSidebarOpen ? _Dock.default.normal : _Dock.default.full, {
      [_Dock.default.docked]: docked
    });
    const inlineStyle = docked ? {
      height: this.domNode.offsetHeight
    } : {};
    const innerInlineStyle = docked ? {
      top: dockTop || 0
    } : {};
    return _react.default.createElement("header", {
      className: className,
      style: inlineStyle,
      ref: this.setDomNode
    }, _react.default.createElement("div", {
      style: innerInlineStyle
    }, children));
  }

}

exports.default = Dock;
Dock.propTypes = propTypes;
Dock.defaultProps = defaultProps;