"use strict";

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

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

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

var _JSONArrow = _interopRequireDefault(require("./JSONArrow"));

var _getCollectionEntries = _interopRequireDefault(require("./getCollectionEntries"));

var _JSONNode = _interopRequireDefault(require("./JSONNode"));

var _ItemRange = _interopRequireDefault(require("./ItemRange"));

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

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

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

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

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

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 _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); }

/**
 * Renders nested values (eg. objects, arrays, lists, etc.)
 */
function renderChildNodes(props, from, to) {
  var nodeType = props.nodeType,
      data = props.data,
      collectionLimit = props.collectionLimit,
      circularCache = props.circularCache,
      keyPath = props.keyPath,
      postprocessValue = props.postprocessValue,
      sortObjectKeys = props.sortObjectKeys;
  var childNodes = [];
  (0, _getCollectionEntries["default"])(nodeType, data, sortObjectKeys, collectionLimit, from, to).forEach(function (entry) {
    if (entry.to) {
      childNodes.push( /*#__PURE__*/_react["default"].createElement(_ItemRange["default"], _extends({}, props, {
        key: "ItemRange--".concat(entry.from, "-").concat(entry.to),
        from: entry.from,
        to: entry.to,
        renderChildNodes: renderChildNodes
      })));
    } else {
      var key = entry.key,
          value = entry.value;
      var isCircular = circularCache.indexOf(value) !== -1;

      var node = /*#__PURE__*/_react["default"].createElement(_JSONNode["default"], _extends({}, props, {
        postprocessValue: postprocessValue,
        collectionLimit: collectionLimit
      }, {
        key: "Node--".concat(key),
        keyPath: [key].concat(_toConsumableArray(keyPath)),
        value: postprocessValue(value),
        circularCache: [].concat(_toConsumableArray(circularCache), [value]),
        isCircular: isCircular,
        hideRoot: false
      }));

      if (node !== false) {
        childNodes.push(node);
      }
    }
  });
  return childNodes;
}

function getStateFromProps(props) {
  // calculate individual node expansion if necessary
  var expanded = props.shouldExpandNode && !props.isCircular ? props.shouldExpandNode(props.keyPath, props.data, props.level) : false;
  return {
    expanded: expanded
  };
}

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

  var _super = _createSuper(JSONNestedNode);

  function JSONNestedNode(props) {
    var _this;

    _classCallCheck(this, JSONNestedNode);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "handleClick", function () {
      if (_this.props.expandable) {
        _this.setState({
          expanded: !_this.state.expanded
        });
      }
    });

    _this.state = getStateFromProps(props);
    return _this;
  }

  _createClass(JSONNestedNode, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      var nextState = getStateFromProps(nextProps);

      if (getStateFromProps(this.props).expanded !== nextState.expanded) {
        this.setState(nextState);
      }
    }
  }, {
    key: "shouldComponentUpdate",
    value: function shouldComponentUpdate(nextProps, nextState) {
      var _this2 = this;

      return !!Object.keys(nextProps).find(function (key) {
        return key !== 'circularCache' && (key === 'keyPath' ? nextProps[key].join('/') !== _this2.props[key].join('/') : nextProps[key] !== _this2.props[key]);
      }) || nextState.expanded !== this.state.expanded;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          getItemString = _this$props.getItemString,
          nodeTypeIndicator = _this$props.nodeTypeIndicator,
          nodeType = _this$props.nodeType,
          data = _this$props.data,
          hideRoot = _this$props.hideRoot,
          createItemString = _this$props.createItemString,
          styling = _this$props.styling,
          collectionLimit = _this$props.collectionLimit,
          keyPath = _this$props.keyPath,
          labelRenderer = _this$props.labelRenderer,
          expandable = _this$props.expandable;
      var expanded = this.state.expanded;
      var renderedChildren = expanded || hideRoot && this.props.level === 0 ? renderChildNodes(_objectSpread(_objectSpread({}, this.props), {}, {
        level: this.props.level + 1
      })) : null;

      var itemType = /*#__PURE__*/_react["default"].createElement("span", styling('nestedNodeItemType', expanded), nodeTypeIndicator);

      var renderedItemString = getItemString(nodeType, data, itemType, createItemString(data, collectionLimit));
      var stylingArgs = [keyPath, nodeType, expanded, expandable];
      return hideRoot ? /*#__PURE__*/_react["default"].createElement("li", styling.apply(void 0, ['rootNode'].concat(stylingArgs)), /*#__PURE__*/_react["default"].createElement("ul", styling.apply(void 0, ['rootNodeChildren'].concat(stylingArgs)), renderedChildren)) : /*#__PURE__*/_react["default"].createElement("li", styling.apply(void 0, ['nestedNode'].concat(stylingArgs)), expandable && /*#__PURE__*/_react["default"].createElement(_JSONArrow["default"], {
        styling: styling,
        nodeType: nodeType,
        expanded: expanded,
        onClick: this.handleClick
      }), /*#__PURE__*/_react["default"].createElement("label", _extends({}, styling.apply(void 0, [['label', 'nestedNodeLabel']].concat(stylingArgs)), {
        onClick: this.handleClick
      }), labelRenderer.apply(void 0, stylingArgs)), /*#__PURE__*/_react["default"].createElement("span", _extends({}, styling.apply(void 0, ['nestedNodeItemString'].concat(stylingArgs)), {
        onClick: this.handleClick
      }), renderedItemString), /*#__PURE__*/_react["default"].createElement("ul", styling.apply(void 0, ['nestedNodeChildren'].concat(stylingArgs)), renderedChildren));
    }
  }]);

  return JSONNestedNode;
}(_react["default"].Component);

exports["default"] = JSONNestedNode;

_defineProperty(JSONNestedNode, "propTypes", {
  getItemString: _propTypes["default"].func.isRequired,
  nodeTypeIndicator: _propTypes["default"].any,
  nodeType: _propTypes["default"].string.isRequired,
  data: _propTypes["default"].any,
  hideRoot: _propTypes["default"].bool.isRequired,
  createItemString: _propTypes["default"].func.isRequired,
  styling: _propTypes["default"].func.isRequired,
  collectionLimit: _propTypes["default"].number,
  keyPath: _propTypes["default"].arrayOf(_propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number])).isRequired,
  labelRenderer: _propTypes["default"].func.isRequired,
  shouldExpandNode: _propTypes["default"].func,
  level: _propTypes["default"].number.isRequired,
  sortObjectKeys: _propTypes["default"].oneOfType([_propTypes["default"].func, _propTypes["default"].bool]),
  isCircular: _propTypes["default"].bool,
  expandable: _propTypes["default"].bool
});

_defineProperty(JSONNestedNode, "defaultProps", {
  data: [],
  circularCache: [],
  level: 0,
  expandable: true
});