Allows user to hit enter to create label, fixes console errors.

This commit is contained in:
Alex Corey 2019-08-16 09:45:07 -04:00 committed by Jake McDermott
parent 534c4e776a
commit fbe6abfb53
4 changed files with 33 additions and 17 deletions

View File

@ -86,7 +86,7 @@ class MultiSelect extends Component {
this.handleSelection(e, option);
}
} else {
this.setState({ isExpanded: false });
this.setState({ input: '', isExpanded: false });
}
}
@ -105,17 +105,30 @@ class MultiSelect extends Component {
handleAddItem(event) {
const { input, chipItems } = this.state;
const { onAddNewItem } = this.props;
const newChip = { name: input, id: Math.random() };
if (event.key !== 'Tab') {
const isIncluded = chipItems.some(chipItem => chipItem.name === input);
if (!input) {
return;
}
this.setState({
chipItems: chipItems.concat(newChip),
isExpanded: false,
input: '',
});
onAddNewItem(input);
if (isIncluded) {
// This event.preventDefault prevents the form from submitting
// if the user tries to create 2 chips of the same name
event.preventDefault();
this.setState({ input: '', isExpanded: false });
return;
}
if (event.key === 'Enter') {
event.preventDefault();
this.setState({
chipItems: chipItems.concat({ name: input, id: input }),
isExpanded: false,
input: '',
});
onAddNewItem(input);
} else if (event.key === 'Tab') {
this.setState({ input: '' });
}
}
handleInputChange(e) {

View File

@ -40,10 +40,10 @@ describe('<MultiSelect />', () => {
const component = wrapper.find('MultiSelect');
component
.find('input[aria-label="labels"]')
.simulate('keydown', { key: 'Tab' });
.simulate('keydown', { key: 'Enter' });
component.update();
await sleep(1);
expect(component.state().chipItems.length).toBe(3);
expect(component.state().chipItems.length).toBe(2);
});
test('handleAddItem adds a chip only when Tab is pressed', () => {
const onAddNewItem = jest.fn();
@ -57,7 +57,7 @@ describe('<MultiSelect />', () => {
);
const event = {
preventDefault: () => {},
key: 'Tab',
key: 'Enter',
};
const component = wrapper.find('MultiSelect');

View File

@ -19,10 +19,13 @@ function JobTemplateAdd({ history, i18n }) {
const handleSubmit = async values => {
setError(null);
try {
const { data } = await JobTemplatesAPI.create(values);
history.push(`/templates/${data.type}/${data.id}/details`);
} catch (err) {
setError(err);
const {
data: { id, type },
} = await JobTemplatesAPI.create(values);
await Promise.all([submitLabels(id, newLabels, removedLabels)]);
history.push(`/templates/${type}/${id}/details`);
} catch (error) {
setFormSubmitError(error);
}
};

View File

@ -158,7 +158,7 @@ describe('<JobTemplateForm />', () => {
_JobTemplateForm.prototype,
'handleNewLabel'
);
const event = { key: 'Tab' };
const event = { key: 'Enter', preventDefault: () => {} };
const wrapper = mountWithContexts(
<JobTemplateForm
template={mockData}