"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

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

var _Box = _interopRequireDefault(require("../../box/Box"));

var _Text = _interopRequireDefault(require("../../text/Text"));

var _Button = _interopRequireDefault(require("../../buttons/Button"));

var _Transition = _interopRequireDefault(require("../Transition"));

var _Stage = _interopRequireDefault(require("./common/Stage"));

var _useIsomorphicLayoutEffect = require("../../utils/useIsomorphicLayoutEffect");

var _useTransformationState = require("./common/useTransformationState");

var _excluded = ["color", "expanded", "containerRef", "onExpand", "onCollapse"];

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

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

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var ExpandingDetails = function ExpandingDetails() {
  var containerRef = React.useRef(null);

  var _React$useState = React.useState(null),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      expandedIndex = _React$useState2[0],
      setExpandedIndex = _React$useState2[1];

  return /*#__PURE__*/React.createElement(_Stage.default, {
    ref: containerRef,
    className: "sg-space-y-xs",
    format: "portrait"
  }, exampleData.map(function (dataProps, index) {
    return /*#__PURE__*/React.createElement(ExpandableBox, _extends({
      key: index,
      expanded: index === expandedIndex,
      containerRef: containerRef,
      onExpand: function onExpand() {
        return setExpandedIndex(index);
      },
      onCollapse: function onCollapse() {
        return setExpandedIndex(null);
      }
    }, dataProps));
  }));
};

exports.ExpandingDetails = ExpandingDetails;

var ExpandableBox = function ExpandableBox(_ref) {
  var color = _ref.color,
      expanded = _ref.expanded,
      containerRef = _ref.containerRef,
      onExpand = _ref.onExpand,
      onCollapse = _ref.onCollapse,
      contentProps = _objectWithoutProperties(_ref, _excluded);

  var _React$useState3 = React.useState(false),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      animating = _React$useState4[0],
      setAnimating = _React$useState4[1];

  var _React$useState5 = React.useState({
    expandingBox: null,
    appearingContent: null
  }),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      effects = _React$useState6[0],
      setEffects = _React$useState6[1];

  var elementRef = React.useRef(null);
  var transformation = (0, _useTransformationState.useTransformationState)({
    elementRef: elementRef,
    containerRef: containerRef,
    updateKey: expanded
  });
  var wrapperFixedHeight = React.useRef();

  var handleExpand = function handleExpand() {
    onExpand();

    if (elementRef.current) {
      wrapperFixedHeight.current = elementRef.current.clientHeight;
    }
  };

  var handleTransitionStart = function handleTransitionStart() {
    setAnimating(true);
  };

  var handleTransitionEnd = function handleTransitionEnd() {
    setAnimating(false);

    if (!expanded) {
      wrapperFixedHeight.current = 'auto';
    }
  };

  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
    var _transformation$previ, _transformation$curre;

    if (transformation.diffHeight === 0) {
      return;
    }
    /**
     * https://css-tricks.com/animating-layouts-with-the-flip-technique/
     */


    setEffects({
      expandingBox: {
        initial: {
          transform: {
            translateY: -transformation.diffTop
          },
          height: (_transformation$previ = transformation.previousSnapshot) === null || _transformation$previ === void 0 ? void 0 : _transformation$previ.height
        },
        animate: {
          transform: {
            translateY: 0,
            origin: 'left top'
          },
          height: (_transformation$curre = transformation.currentSnapshot) === null || _transformation$curre === void 0 ? void 0 : _transformation$curre.height,
          duration: 'gentle1'
        }
      },
      appearingContent: {
        initial: {
          opacity: 0
        },
        animate: {
          opacity: 1,
          duration: 'gentle2',
          easing: 'entry'
        }
      }
    });
  }, [transformation]);
  return /*#__PURE__*/React.createElement("div", {
    style: {
      height: wrapperFixedHeight.current
    }
  }, /*#__PURE__*/React.createElement("div", {
    ref: elementRef,
    style: getElementStyle(expanded, animating)
  }, /*#__PURE__*/React.createElement(_Transition.default, {
    active: true,
    effect: effects.expandingBox,
    onTransitionStart: handleTransitionStart,
    onTransitionEnd: handleTransitionEnd
  }, /*#__PURE__*/React.createElement(_Box.default, _extends({}, getBoxStylingProps(color), {
    onClick: expanded ? undefined : handleExpand
  }), /*#__PURE__*/React.createElement(_Transition.default, {
    active: true,
    effect: effects.appearingContent,
    fillMode: "backwards",
    delay: 80
  }, /*#__PURE__*/React.createElement(ExpandableBoxContent, _extends({}, contentProps, {
    expanded: expanded,
    onButtonClick: onCollapse
  })))))));
};

var ExpandableBoxContent = function ExpandableBoxContent(_ref2) {
  var expanded = _ref2.expanded,
      shortContent = _ref2.shortContent,
      fullContent = _ref2.fullContent,
      onButtonClick = _ref2.onButtonClick;

  if (!expanded) {
    return /*#__PURE__*/React.createElement(_Text.default, {
      size: "small"
    }, shortContent);
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Text.default, {
    size: "small",
    className: "sg-space-y-m"
  }, fullContent), /*#__PURE__*/React.createElement(_Button.default, {
    variant: "solid",
    style: {
      position: 'absolute',
      left: 24,
      bottom: 24,
      right: 24
    },
    onClick: onButtonClick
  }, "close"));
};

var exampleData = [{
  color: 'red',
  shortContent: 'A hive of bees contains 27 bees when it is first discovered. After 3 days, there are 36 bees. It is determined that the population of bees increases exponentially.',
  fullContent: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Text.default, {
    weight: "bold",
    inherited: true
  }, "A hive of bees contains 27 bees when it is first discovered. After 3 days, there are 36 bees. It is determined that the population of bees increases exponentially."), /*#__PURE__*/React.createElement(_Text.default, {
    inherited: true
  }, "How many bees are will there be after 30 days? Express your answer as an exact value and rounded to the nearest whole number."), /*#__PURE__*/React.createElement(_Text.default, {
    inherited: true
  }, "360. When the beehive was discovered, there were 27 bees. After 3 days, the numbers of bee increased to 36. Progression Type: Exponential (also knows as geometry). Number of bees after 30 days is unknown."))
}, {
  color: 'yellow',
  shortContent: 'Louis Napoleon Bonaparte was the nephew of Napoleon Bonaparte.',
  fullContent: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Text.default, {
    weight: "bold",
    inherited: true
  }, "Louis Napoleon Bonaparte was the nephew of Napoleon Bonaparte."), /*#__PURE__*/React.createElement(_Text.default, {
    inherited: true
  }, "Napoleon III, the nephew of Napoleon I, was the first elected President of France from 1848 to 1852. Louis Napoleon seized power in 1851 and served as Emperor of the French from 1852 to 1870. He founded the Second French Empire and was its only emperor until the French army was defeated and he was captured by Prussia and its allies in the Franco-Prussian War in 1870."), /*#__PURE__*/React.createElement(_Text.default, {
    inherited: true
  }, "He aimed to modernize the French economy, rebuilt the center of Paris, expanded the overseas empire."))
}, {
  color: 'blue',
  shortContent: 'Biology is a branch of science that studies about life and living organisms. It includes physical and chemical structure, development, and evolution of all living things. It seeks to answer questions about all living things.',
  fullContent: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Text.default, {
    weight: "bold",
    inherited: true
  }, "Biology is a branch of science that studies about life and living organisms. It includes physical and chemical structure, development, and evolution of all living things. It seeks to answer questions about all living things."), /*#__PURE__*/React.createElement(_Text.default, {
    inherited: true
  }, "A biologist may ask about how plants maintain life processes. In Christian biology, biblical knowledge and faith are integrated in learning the evolution of the earth and the living things that consist it. Likewise, it states that God's signature is written in his creation or the living world is a testament of God's actions."))
}];

var getElementStyle = function getElementStyle(expanded, animating) {
  if (expanded) {
    return {
      position: 'absolute',
      zIndex: 1,
      top: 16,
      left: 16,
      right: 16,
      bottom: 16
    };
  }

  if (animating) {
    return {
      height: '100%',
      position: 'relative',
      zIndex: 1
    };
  }

  return {
    cursor: 'pointer'
  };
};

var getBoxStylingProps = function getBoxStylingProps(color) {
  var colorsMap = {
    red: {
      backgroundColor: 'red-30',
      borderColor: 'red-40'
    },
    yellow: {
      backgroundColor: 'yellow-20',
      borderColor: 'yellow-40'
    },
    blue: {
      backgroundColor: 'blue-30',
      borderColor: 'blue-40'
    }
  };
  return {
    style: {
      height: '100%',
      position: 'relative',
      overflow: 'hidden'
    },
    color: colorsMap[color].backgroundColor,
    borderColor: colorsMap[color].borderColor,
    border: true
  };
};

ExpandingDetails.parameters = {
  layout: 'centered'
};