"use strict";

exports.__esModule = true;
exports.default = exports.ListControlButton = exports.List = exports.REMOVE_ROW = void 0;

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

var _styledComponents = _interopRequireWildcard(require("styled-components"));

var _utils = require("../../utils");

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

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

var _Form = require("./Form");

var _FieldElements = _interopRequireDefault(require("./FieldElements"));

var _Field = _interopRequireWildcard(require("./Field"));

var _excluded = ["fields", "label"],
    _excluded2 = ["fields", "proportions"],
    _excluded3 = ["name", "staticValues", "getUpdater", "rowField", "rowCount", "tallRows"];

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 () {
  var enterModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined;
  enterModule && enterModule(module);
})();

(function () {
  var enterModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined;
  enterModule && enterModule(module);
})();

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

var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) {
  return a;
};

var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) {
  return a;
};

var REMOVE_ROW = "__form_list_remove_row";
exports.REMOVE_ROW = REMOVE_ROW;

var generateId = function () {
  var counter = 0;
  return (
    /* istanbul ignore next */
    function () {
      return counter += 1;
    }
  );
}();

var stripLabelFromTree = function stripLabelFromTree(_ref) {
  var fields = _ref.fields,
      label = _ref.label,
      remainder = _objectWithoutProperties(_ref, _excluded);

  var tree = _objectSpread({}, remainder);

  if (fields && Array.isArray(fields)) {
    tree.fields = fields.map(stripLabelFromTree);
  }

  return tree;
};

var List = _styledComponents.default.div.withConfig({
  displayName: "FieldList__List",
  componentId: "sc-1v84f9-0"
})(["display:flex;flex-direction:column;", ""], (0, _utils.ifFlag)("tallRows", (0, _styledComponents.css)(["& > ", "{margin:0;padding:20px 0;border-bottom:1px solid ", ";}& > ", ":first-child{margin-top:15px;}& > ", ":last-child{border-bottom:0 none transparent;}"], _Field.FieldBox, (0, _utils.getThemeProp)(["colors", "borderLight"], "#cccccc"), _Field.FieldBox, _Field.FieldBox), (0, _styledComponents.css)(["margin-top:20px;& > ", "{margin-top:0;}& > ", " + ", "{margin-top:10px;}"], _Field.FieldBox, _Field.FieldBox, _Field.FieldBox)));

exports.List = List;
var ListControlButton = (0, _styledComponents.default)(_Button.default).attrs(function () {
  return {
    primary: true
  };
}).withConfig({
  displayName: "FieldList__ListControlButton",
  componentId: "sc-1v84f9-1"
})(["align-self:flex-start;min-width:100px;"]);
exports.ListControlButton = ListControlButton;

var decorateField = function decorateField(field, remove) {
  if (remove === void 0) {
    remove = "[remove]";
  }

  if (field.type === "Combination") {
    // Add the closer to the tail end of the combo

    /* istanbul ignore next */
    var _field$fields = field.fields,
        fields = _field$fields === void 0 ? [] : _field$fields,
        _field$proportions = field.proportions,
        proportions = _field$proportions === void 0 ? [] : _field$proportions,
        remainder = _objectWithoutProperties(field, _excluded2);

    var decoratedProportions = [].concat(proportions);
    decoratedProportions[fields.length] = "30px"; // Set this way to ensure index match

    var decoratedFields = fields.concat([{
      type: "SmallButton",
      name: REMOVE_ROW,
      primary: true,
      icon: "cross",
      altText: remove
    }]);
    return _objectSpread(_objectSpread({}, remainder), {}, {
      proportions: decoratedProportions,
      fields: decoratedFields
    });
  } // Wrap field in a combo with the closer


  return {
    type: "Combination",
    name: "rowField",
    // Set field base size to fit in field set
    proportions: [100, "30px"],
    fields: [field, {
      type: "SmallButton",
      name: REMOVE_ROW,
      primary: true,
      icon: "cross",
      altText: remove
    }]
  };
};

var createRowGetter = function createRowGetter(valueList, rowCount) {
  if (valueList === void 0) {
    valueList = [];
  }

  var rows = [];

  if (rowCount === undefined) {
    rows.push.apply(rows, valueList);
  } else {
    var _loop = function _loop(i) {
      var row = _objectSpread({}, valueList[i]);

      if (!row.id) {
        row.id = generateId();
        valueList.forEach(function (valRow) {
          /* istanbul ignore else */
          if (valRow.id) {
            while (valRow.id >= row.id) {
              row.id = generateId();
            }
          }
        });
      }

      rows.push(row);
    };

    for (var i = 0; i < rowCount; i += 1) {
      _loop(i);
    }
  }

  return function () {
    return rows;
  };
};

var getListFieldUpdater = function getListFieldUpdater(updateAll, getRows) {
  return (0, _utils.memoize)(function (index) {
    if (index < 0) {
      return function () {
        var rows = getRows();
        var id = generateId();
        rows.forEach(function (row) {
          /* istanbul ignore else */
          if (row.id) {
            while (row.id >= id) {
              id = generateId();
            }
          }
        });
        rows.push({
          id: id
        });
        updateAll(rows);
      };
    }

    return (0, _utils.memoize)(function (name) {
      if (name === REMOVE_ROW) {
        return function () {
          return setTimeout(function () {
            var rows = getRows();
            rows.splice(index, 1);
            updateAll(rows);
          }, 0);
        };
      }

      return function (value) {
        var rows = getRows();
        rows[index][name] = value;
        updateAll(rows);
      };
    });
  });
};

var FieldList = function FieldList(_ref2) {
  var name = _ref2.name,
      _ref2$staticValues = _ref2.staticValues,
      staticValues = _ref2$staticValues === void 0 ? [] : _ref2$staticValues,
      getUpdater = _ref2.getUpdater,
      rowField = _ref2.rowField,
      rowCount = _ref2.rowCount,
      tallRows = _ref2.tallRows,
      props = _objectWithoutProperties(_ref2, _excluded3);

  var _useContext = (0, _react.useContext)(_Form.FormContext),
      values = _useContext.values,
      listIndex = _useContext.listIndex; // eslint-disable-next-line react-hooks/exhaustive-deps


  var getRows = (0, _react.useCallback)(createRowGetter(values[name], rowCount), [values, name, rowCount]); // eslint-disable-next-line react-hooks/exhaustive-deps

  var listUpdater = (0, _react.useCallback)(getListFieldUpdater(getUpdater(name), getRows), [getUpdater, name, getRows]);

  if (listIndex !== undefined) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "Cannot render list inside list");
  }

  var renderField = rowCount === undefined ? decorateField(rowField, props.remove) : rowField;
  return /*#__PURE__*/_react.default.createElement(List, {
    tallRows: tallRows
  }, tallRows ? null : /*#__PURE__*/_react.default.createElement(_FieldElements.default, {
    fields: [renderField],
    labelOnly: true
  }), getRows().map(function (row, index) {
    return /*#__PURE__*/_react.default.createElement(_Form.FormContext.Provider, {
      key: row.id,
      value: {
        values: _objectSpread(_objectSpread({}, row), staticValues[index]),
        listIndex: index
      }
    }, /*#__PURE__*/_react.default.createElement(_FieldElements.default, {
      fields: [tallRows ? renderField : stripLabelFromTree(renderField)],
      listIndex: index,
      getUpdater: listUpdater(index)
    }));
  }), rowCount === undefined ? /*#__PURE__*/_react.default.createElement(_Field.default, null, /*#__PURE__*/_react.default.createElement(ListControlButton, {
    onClick: listUpdater(-1)
  }, /*#__PURE__*/_react.default.createElement(_Text.default, {
    message: props.add || "[add]"
  }))) : null);
};

__signature__(FieldList, "useContext{{ values, listIndex }}\nuseCallback{getRows}\nuseCallback{listUpdater}");

__signature__(FieldList, "useContext{{ values, listIndex }}\nuseCallback{getRows}\nuseCallback{listUpdater}");

var _default = FieldList;
var _default2 = _default;
var _default3 = _default2;
exports.default = _default3;
;

(function () {
  var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined;

  if (!reactHotLoader) {
    return;
  }

  reactHotLoader.register(REMOVE_ROW, "REMOVE_ROW", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(generateId, "generateId", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(stripLabelFromTree, "stripLabelFromTree", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(List, "List", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(ListControlButton, "ListControlButton", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(decorateField, "decorateField", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(createRowGetter, "createRowGetter", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(getListFieldUpdater, "getListFieldUpdater", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(FieldList, "FieldList", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(_default, "default", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
})();

;

(function () {
  var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined;
  leaveModule && leaveModule(module);
})();

;

(function () {
  var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined;

  if (!reactHotLoader) {
    return;
  }

  reactHotLoader.register(REMOVE_ROW, "REMOVE_ROW", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(generateId, "generateId", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(stripLabelFromTree, "stripLabelFromTree", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(List, "List", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(ListControlButton, "ListControlButton", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(decorateField, "decorateField", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(createRowGetter, "createRowGetter", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(getListFieldUpdater, "getListFieldUpdater", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(FieldList, "FieldList", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
  reactHotLoader.register(_default2, "default", "/home/vsts/work/1/s/src/components/Form/FieldList.js");
})();

;

(function () {
  var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined;
  leaveModule && leaveModule(module);
})();