stitch-ui
Version:
83 lines (81 loc) • 2.36 kB
JavaScript
import React from "react";
import PropTypes from "prop-types";
import { enterPressedCaller } from "../../../util";
import { Button } from "../../../core";
import { validateDisallowedChars } from "../validation";
export default class AddFieldForm extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
this.cancelAddField = this.cancelAddField.bind(this);
this.handleChange = this.handleChange.bind(this);
this.addField = this.addField.bind(this);
}
handleChange(x) {
this.props.setNewFieldInput(x.target.value);
}
cancelAddField() {
this.setState({ error: null });
this.props.setNewFieldInput(null);
}
addField() {
const { rootPath, addField, setNewFieldInput, newFieldInput } = this.props;
const field = newFieldInput;
if (field.length === 0) {
this.setState({ error: "Field name must not be blank." });
return;
} else if (!validateDisallowedChars(field, [".", "$", "\x00"])) {
this.setState({ error: "Field name contains illegal characters." });
return;
}
this.setState({ error: null });
addField(rootPath, field);
setNewFieldInput(null);
}
render() {
const { newFieldInput } = this.props;
const { error } = this.state;
return (
<span>
<input
type="text"
className="text-input text-input-for-filter text-input-is-inline-block"
placeholder="Field Name"
value={newFieldInput}
onChange={this.handleChange}
onKeyDown={enterPressedCaller(this.addField, this.cancelAddField)}
/>
{error &&
<span>
<br />
<span className="mongo-schema-newfield-error">
{error}
</span>
</span>}
<Button
small
primary
onClick={e => {
e.stopPropagation();
this.addField();
}}
>
Add
</Button>
<Button small default onClick={() => this.cancelAddField()}>
Cancel
</Button>
</span>
);
}
}
AddFieldForm.propTypes = {
rootPath: PropTypes.string,
setNewFieldInput: PropTypes.func.isRequired,
addField: PropTypes.func.isRequired,
newFieldInput: PropTypes.string
};
AddFieldForm.defaultProps = {
rootPath: null,
newFieldInput: ""
};