import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { intlShape } from 'meteor/vulcan:i18n';
import classNames from 'classnames';
import { Components } from 'meteor/vulcan:core';
import { registerComponent } from 'meteor/vulcan:core';
import debounce from 'lodash.debounce';
import get from 'lodash/get';
class FormComponent extends PureComponent {
constructor(props, context) {
super(props);
const value = this.getValue(props, context);
if (props.limit) {
this.state = {
limit: value ? props.limit - value.length : props.limit,
};
}
}
handleChange = (name, value) => {
// if this is a number field, convert value before sending it up to Form
if (this.getType() === 'number') {
value = Number(value);
}
this.context.updateCurrentValues({ [this.props.path]: value });
// for text fields, update character count on change
if (['number', 'url', 'email', 'textarea', 'text'].includes(this.getType())) {
this.updateCharacterCount(value);
}
};
/*
Note: not currently used because when function is debounced
some changes might not register if the user submits form too soon
*/
handleChangeDebounced = debounce(this.handleChange, 500, { leading: true });
updateCharacterCount = (value) => {
if (this.props.limit) {
const characterCount = value ? value.length : 0;
this.setState({
limit: this.props.limit - characterCount,
});
}
};
/*
Get value from Form state through context
*/
getValue = (props, context) => {
const p = props || this.props;
const c = context || this.context;
return get(c.getDocument(), p.path);
};
/*
Get errors from Form state through context
*/
getErrors = () => {
const fieldErrors = this.context.errors.filter(error => error.data.name === this.props.path);
return fieldErrors;
};
/*
Get form control type, either based on control props, or by guessing
based on form field type
*/
getType = () => {
return this.props.control || 'text';
};
renderComponent() {
// see https://facebook.github.io/react/warnings/unknown-prop.html
const {
control,
group,
updateCurrentValues,
document,
beforeComponent,
afterComponent,
limit,
errors,
nestedSchema,
nestedFields,
datatype,
parentFieldName,
itemIndex,
path,
...rest
} = this.props; // eslint-disable-line
const properties = {
...rest,
// onBlur: this.handleChange,
onChange: this.handleChange,
document,
value: this.getValue(),
};
// if control is a React component, use it
if (typeof this.props.control === 'function') {
return