var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

import classNames from 'classnames';
import css from 'dom-helpers/style';
import React from 'react';
import PropTypes from 'prop-types';
import Transition, { EXITED, ENTERED, ENTERING, EXITING } from 'react-transition-group/Transition';

function capitalize(string) {
  return '' + string.charAt(0).toUpperCase() + string.slice(1);
}

function getDimensionValue(dimension, elem) {
  var MARGINS = {
    height: ['marginTop', 'marginBottom'],
    width: ['marginLeft', 'marginRight']
  };
  var value = elem['offset' + capitalize(dimension)];
  var margins = MARGINS[dimension];

  return value + parseInt(css(elem, margins[0]), 10) + parseInt(css(elem, margins[1]), 10);
}

function triggerBrowserReflow(node) {
  node.offsetHeight; // eslint-disable-line no-unused-expressions
}

/** The following animation component was implemented following the same logic/strucure
 *  as React-Bootstrap's Collapse component.
 *  (https://react-bootstrap.github.io/utilities/transitions/#transitions-collapse)
*/

var Collapse = function (_React$Component) {
  _inherits(Collapse, _React$Component);

  function Collapse(props) {
    _classCallCheck(this, Collapse);

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.handleEnter = _this.handleEnter.bind(_this);
    _this.handleEntering = _this.handleEntering.bind(_this);
    _this.handleEntered = _this.handleEntered.bind(_this);
    _this.handleExit = _this.handleExit.bind(_this);
    _this.handleExiting = _this.handleExiting.bind(_this);
    return _this;
  }

  Collapse.prototype.getDimension = function getDimension() {
    return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension;
  };

  // Expanding


  Collapse.prototype.handleEnter = function handleEnter(elem) {
    var minDimension = this.props.minDimension;

    var dimension = this.getDimension();
    var currentDim = parseInt(css(elem, dimension), 10);
    var setDim = minDimension <= currentDim ? minDimension : currentDim;
    elem.style[dimension] = setDim + 'px'; // eslint-disable-line no-param-reassign
    elem.style['max' + capitalize(dimension)] = 'none'; // eslint-disable-line no-param-reassign
  };

  Collapse.prototype.handleEntering = function handleEntering(elem) {
    var dimension = this.getDimension();
    elem.style[dimension] = elem['scroll' + capitalize(dimension)] + 'px'; // eslint-disable-line no-param-reassign
  };

  Collapse.prototype.handleEntered = function handleEntered(elem) {
    elem.style[this.getDimension()] = null; // eslint-disable-line no-param-reassign
  };

  // Collapsing


  Collapse.prototype.handleExit = function handleExit(elem) {
    var dimension = this.getDimension();
    elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px'; // eslint-disable-line no-param-reassign
    triggerBrowserReflow(elem);
  };

  Collapse.prototype.handleExiting = function handleExiting(elem) {
    var minDimension = this.props.minDimension;

    var dimension = this.getDimension();
    var currentDim = parseInt(css(elem, dimension), 10);
    var setDim = minDimension <= currentDim ? minDimension : currentDim;
    elem.style[dimension] = setDim + 'px'; // eslint-disable-line no-param-reassign
  };

  Collapse.prototype.render = function render() {
    var _collapseStyles;

    var _props = this.props,
        onEnter = _props.onEnter,
        onEntering = _props.onEntering,
        onEntered = _props.onEntered,
        onExit = _props.onExit,
        onExiting = _props.onExiting,
        className = _props.className,
        children = _props.children,
        minDimension = _props.minDimension,
        minDimensionOnMount = _props.minDimensionOnMount,
        props = _objectWithoutProperties(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className', 'children', 'minDimension', 'minDimensionOnMount']);

    var collapseStyles = (_collapseStyles = {}, _collapseStyles[EXITED] = 'collapsed', _collapseStyles[EXITING] = 'collapsing', _collapseStyles[ENTERING] = 'expanding', _collapseStyles[ENTERED] = 'expanded', _collapseStyles);

    var dimension = this.getDimension();

    delete props.dimension;
    delete props.getDimensionValue;
    return React.createElement(
      Transition,
      _extends({}, props, {
        'aria-expanded': props.role ? props.in : null,
        onEnter: this.handleEnter,
        onEntering: this.handleEntering,
        onEntered: this.handleEntered,
        onExit: this.handleExit,
        onExiting: this.handleExiting
      }),
      function (state, innerProps) {
        var _style;

        return React.cloneElement(children, _extends({}, innerProps, {
          style: (_style = {}, _style['max' + capitalize(dimension)] = minDimensionOnMount ? minDimension + 'px' : 'none', _style),
          className: classNames(className, children.props.className, collapseStyles[state], dimension === 'width' && 'width')
        }));
      }
    );
  };

  return Collapse;
}(React.Component);

Collapse.propTypes = process.env.NODE_ENV !== "production" ? {
  /** Show the component; triggers the expand or collapse animation */
  in: PropTypes.bool,
  /** Wait until the first "enter" transition to mount the component (add it to the DOM) */
  mountOnEnter: PropTypes.bool,
  /** Unmount the component (remove it from the DOM) when it is collapsed */
  unmountOnExit: PropTypes.bool,
  /** Run the expand animation when the component mounts, if it is initially shown */
  appear: PropTypes.bool,
  /** Duration of the collapse animation in milliseconds */
  timeout: PropTypes.number,
  /** Callback fired before the component expands */
  onEnter: PropTypes.func,
  /** Callback fired after the component starts to expand */
  onEntering: PropTypes.func,
  /** Callback fired after the component has expanded */
  onEntered: PropTypes.func,
  /** Callback fired before the component collapses */
  onExit: PropTypes.func,
  /** Callback fired after the component starts to collapse */
  onExiting: PropTypes.func,
  /** Callback fired after the component has collapsed */
  onExited: PropTypes.func,
  /** The dimension used when collapsing, or a function that returns the dimension */
  dimension: PropTypes.oneOfType([PropTypes.oneOf(['height', 'width']), PropTypes.func]),
  /** Function that returns the height or width of the animating DOM node Allows for providing some custom
   * logic for how much the Collapse component should animate in its specified dimension. Called with
   * the current dimension prop value and the DOM node. */
  getDimensionValue: PropTypes.func,
  /** ARIA role of collapsible element */
  role: PropTypes.string,
  /** classNames for direct children */
  className: PropTypes.string,
  /** child node */
  children: PropTypes.node,
  /** The minimum dimension, height or width, that you want the animation to collapse to.
   *  This should be in number of pixels (i.e. pass 200 if you want it to collapse to a height of 200px.
      The default value is 0. */
  minDimension: PropTypes.number,
  /** Whether you want to set the minimum height of the child on its initial mount */
  minDimensionOnMount: PropTypes.bool
} : {};

Collapse.defaultProps = {
  in: false,
  timeout: 300,
  mountOnEnter: false,
  unmountOnExit: false,
  appear: true,
  dimension: 'height',
  getDimensionValue: getDimensionValue,
  minDimension: 0,
  minDimensionOnMount: false
};

export default Collapse;