@shopify/react-form-state
Version:
Manage react forms tersely and type-safe with no magic.
58 lines (57 loc) • 2.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var react_1 = tslib_1.__importDefault(require("react"));
var utilities_1 = require("../utilities");
var List = /** @class */ (function (_super) {
tslib_1.__extends(List, _super);
function List() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.changeHandlers = new Map();
_this.handleChange = function (_a) {
var index = _a.index, key = _a.key;
var hashKey = index + ":" + key;
if (_this.changeHandlers.has(hashKey)) {
return _this.changeHandlers.get(hashKey);
}
var handler = function (newValue) {
var onChange = _this.props.field.onChange;
onChange(function (value) {
var _a;
var existingItem = value[index];
var newItem = tslib_1.__assign({}, existingItem, (_a = {}, _a[key] = typeof newValue === 'function'
? newValue(value[index][key])
: newValue, _a));
return utilities_1.replace(value, index, newItem);
});
};
_this.changeHandlers.set(hashKey, handler);
return handler;
};
return _this;
}
List.prototype.render = function () {
var _this = this;
var _a = this.props, _b = _a.field, value = _b.value, initialValue = _b.initialValue, error = _b.error, name = _b.name, onBlur = _b.onBlur, getChildKey = _a.getChildKey, children = _a.children;
return value.map(function (fieldValues, index) {
var innerFields = utilities_1.mapObject(fieldValues, function (value, fieldPath) {
var initialFieldValue = initialValue &&
initialValue[index] &&
initialValue[index][fieldPath];
return {
value: value,
onBlur: onBlur,
name: name + "." + index + "." + fieldPath,
initialValue: initialFieldValue,
dirty: value !== initialFieldValue,
error: error && error[index] && error[index][fieldPath],
onChange: _this.handleChange({ index: index, key: fieldPath }),
};
});
var key = getChildKey ? getChildKey(fieldValues) : index;
return (react_1.default.createElement(react_1.default.Fragment, { key: key }, children(innerFields, index)));
});
};
return List;
}(react_1.default.PureComponent));
exports.default = List;