Files
SCM-Manager/scm-ui/src/containers/Autocomplete.js

69 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-11-14 13:40:14 +01:00
// @flow
import React from "react";
2018-11-19 10:31:01 +01:00
import { LabelWithHelpIcon } from "@scm-manager/ui-components";
import { AsyncCreatable } from "react-select";
2018-11-14 13:40:14 +01:00
2018-11-19 10:31:01 +01:00
export type AutocompleteObject = {
2018-11-14 13:40:14 +01:00
id: string,
displayName: string
};
export type SelectValue = {
2018-11-19 10:31:01 +01:00
value: AutocompleteObject,
2018-11-14 13:40:14 +01:00
label: string
};
type Props = {
2018-11-19 10:31:01 +01:00
loadSuggestions: string => Promise<AutocompleteObject>,
valueSelected: SelectValue => void,
label: string,
helpText?: string,
value?: SelectValue
2018-11-14 13:40:14 +01:00
};
type State = {};
2018-11-14 13:40:14 +01:00
2018-11-19 10:31:01 +01:00
class Autocomplete extends React.Component<Props, State> {
2018-11-14 13:40:14 +01:00
handleInputChange = (newValue: SelectValue) => {
this.props.valueSelected(newValue);
};
isValidNewOption = (inputValue, selectValue, selectOptions) => {
//TODO: types
const isNotDuplicated = !selectOptions
.map(option => option.label)
.includes(inputValue);
const isNotEmpty = inputValue !== "";
return isNotEmpty && isNotDuplicated;
2018-11-14 13:40:14 +01:00
};
render() {
const { label, helpText, value } = this.props;
2018-11-14 13:40:14 +01:00
return (
<div className="field">
<LabelWithHelpIcon label={label} helpText={helpText} />
<div className="control">
<AsyncCreatable
cacheOptions
loadOptions={this.props.loadSuggestions}
onChange={this.handleInputChange}
value={value}
placeholder="Start typing..." // TODO: i18n
loadingMessage={() => <>Loading...</>} // TODO: i18n
noOptionsMessage={() => <>No suggestion available</>} // TODO: i18n
isValidNewOption={this.isValidNewOption}
onCreateOption={value => {
this.handleInputChange({
label: value,
value: { id: value, displayName: value }
});
}}
/>
</div>
</div>
2018-11-14 13:40:14 +01:00
);
}
}
2018-11-19 10:31:01 +01:00
export default Autocomplete;