react-jsonschema
Version:
React forms with JSONSchema
60 lines (51 loc) • 2.16 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.addValueToState = addValueToState;
exports.deleteIndexFromState = deleteIndexFromState;
var _lodash = require('lodash');
var _types = require('./constants/types');
var _types2 = _interopRequireDefault(_types);
var _utils = require('./utils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
/**
* Takes a current state, and adds a new value in the state array.
*
* @param {Array} state - The current state to modify
* @param {Object} action - The action payload
* @param {String} action.path - The path to the array in the state object
* @param {Object} action.schema - The schema to parse against
* @return {Array} The new state
*/
function addValueToState(state, action) {
var newState = (0, _lodash.cloneDeep)(state);
var newArray = (0, _lodash.result)(newState, action.path);
switch (action.schema.type) {
case _types2.default.ARRAY:
newArray.push((0, _utils.getDefaultState)(action.schema.items));
break;
default:
// do nothing
}
(0, _lodash.set)(newState, action.path, newArray);
return newState;
}
/**
* Takes a current state, and removes a value specified at the given
* index and path to the array in the state object.
*
* @param {Object} state - The current state to modify
* @param {Object} action - The action payload
* @param {Number} action.index - The index of the value to remove
* @param {String} action.path - The path to the array in the state object
* @return {Object} The new state
*/
function deleteIndexFromState(state, action) {
var newState = (0, _lodash.cloneDeep)(state);
var values = (0, _lodash.result)(newState, action.path);
var newArray = [].concat(_toConsumableArray(values.slice(0, action.index)), _toConsumableArray(values.slice(action.index + 1)));
(0, _lodash.set)(newState, action.path, newArray);
return newState;
}
;