@shopify/react-form-state
Version:
Manage React forms tersely and type-safely with no magic
88 lines (73 loc) • 2.44 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var _rollupPluginBabelHelpers = require('../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var utilities = require('../utilities.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
class List extends React__default['default'].PureComponent {
constructor(...args) {
super(...args);
this.changeHandlers = new Map();
this.handleChange = ({
index,
key
}) => {
const hashKey = `${index}:${key}`;
if (this.changeHandlers.has(hashKey)) {
return this.changeHandlers.get(hashKey);
}
const handler = newValue => {
const {
field: {
onChange
}
} = this.props;
onChange(value => {
const existingItem = value[index];
const newItem = _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, existingItem), {}, {
[key]: typeof newValue === 'function' ? newValue(value[index][key]) : newValue
});
return utilities.replace(value, index, newItem);
});
};
this.changeHandlers.set(hashKey, handler);
return handler;
};
}
render() {
const {
field: {
value,
initialValue,
error,
name,
onBlur
},
getChildKey,
children
} = this.props;
return value.map((fieldValues, index) => {
const innerFields = utilities.mapObject(fieldValues, (value, fieldPath) => {
const initialFieldValue = initialValue && initialValue[index] && initialValue[index][fieldPath];
return {
value,
onBlur,
name: `${name}.${index}.${fieldPath}`,
initialValue: initialFieldValue,
dirty: value !== initialFieldValue,
error: error && error[index] && error[index][fieldPath],
onChange: this.handleChange({
index,
key: fieldPath
})
};
});
const key = getChildKey ? getChildKey(fieldValues) : index;
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, {
key: key
}, children(innerFields, index));
});
}
}
exports.default = List;