import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Components, registerComponent } from 'meteor/vulcan:core';
// Replaceable layout
const FormNestedArrayLayout = ({ hasErrors, label, content }) => (
);
FormNestedArrayLayout.propTypes = {
hasErrors: PropTypes.bool,
label: PropTypes.node,
content: PropTypes.node
};
registerComponent({
name: 'FormNestedArrayLayout',
component: FormNestedArrayLayout
});
class FormNestedArray extends PureComponent {
getCurrentValue() {
return this.props.value || [];
}
addItem = () => {
const value = this.getCurrentValue();
this.props.updateCurrentValues(
{ [`${this.props.path}.${value.length}`]: {} },
{ mode: 'merge' }
);
};
removeItem = index => {
this.props.updateCurrentValues({ [`${this.props.path}.${index}`]: null });
};
/*
Go through this.context.deletedValues and see if any value matches both the current field
and the given index (ex: if we want to know if the second address is deleted, we
look for the presence of 'addresses.1')
*/
isDeleted = index => {
return this.props.deletedValues.includes(`${this.props.path}.${index}`);
};
render() {
const value = this.getCurrentValue();
// do not pass FormNested's own value, input and inputProperties props down
const properties = _.omit(
this.props,
'value',
'input',
'inputProperties',
'nestedInput'
);
const { errors, path, label, formComponents, minCount, maxCount } = this.props;
const FormComponents = formComponents;
//filter out null values to calculate array length
let arrayLength = value.filter(singleValue => {
return !!singleValue;
}).length;
// only keep errors specific to the nested array (and not its subfields)
const nestedArrayErrors = errors.filter(
error => error.path && error.path === path
);
const hasErrors = nestedArrayErrors && nestedArrayErrors.length;
return (
!this.isDeleted(i) && (
{
this.removeItem(i);
}}
hideRemove={minCount && arrayLength <= minCount}
/>
)
),
(!maxCount || arrayLength < maxCount) && (
),
hasErrors ? (
) : null
]}
/>
);
}
}
FormNestedArray.propTypes = {
currentValues: PropTypes.object,
path: PropTypes.string,
label: PropTypes.string,
errors: PropTypes.array.isRequired,
deletedValues: PropTypes.array.isRequired,
formComponents: PropTypes.object.isRequired
};
module.exports = FormNestedArray;
registerComponent('FormNestedArray', FormNestedArray);
const IconAdd = ({ width = 24, height = 24 }) => (
);
registerComponent('IconAdd', IconAdd);
const IconRemove = ({ width = 24, height = 24 }) => (
);
registerComponent('IconRemove', IconRemove);