Files
SCM-Manager/scm-ui/ui-components/src/Autocomplete.tsx

105 lines
2.8 KiB
TypeScript
Raw Normal View History

import React from "react";
import { Async, AsyncCreatable } from "react-select";
import { SelectValue } from "@scm-manager/ui-types";
import LabelWithHelpIcon from "./forms/LabelWithHelpIcon";
import { ActionMeta, ValueType } from "react-select/lib/types";
2018-11-14 13:40:14 +01:00
type Props = {
loadSuggestions: (p: string) => Promise<SelectValue[]>;
valueSelected: (p: SelectValue) => void;
label: string;
helpText?: string;
value?: SelectValue;
placeholder: string;
loadingMessage: string;
noOptionsMessage: string;
creatable?: boolean;
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> {
static defaultProps = {
placeholder: "Type here",
loadingMessage: "Loading...",
noOptionsMessage: "No suggestion available"
2018-11-22 10:55:21 +01:00
};
handleInputChange = (
newValue: ValueType<SelectValue>,
action: ActionMeta
) => {
this.selectValue(newValue as SelectValue);
};
selectValue = (value: SelectValue) => {
this.props.valueSelected(value);
};
// We overwrite this to avoid running into a bug (https://github.com/JedWatson/react-select/issues/2944)
2019-06-12 09:47:13 +02:00
isValidNewOption = (
inputValue: string,
selectValue: ValueType<SelectValue>,
selectOptions: readonly SelectValue[]
): boolean => {
const isNotDuplicated = !selectOptions
.map(option => option.label)
.includes(inputValue);
const isNotEmpty = inputValue !== "";
return isNotEmpty && isNotDuplicated;
2018-11-14 13:40:14 +01:00
};
render() {
2019-06-12 09:47:13 +02:00
const {
label,
helpText,
value,
placeholder,
loadingMessage,
noOptionsMessage,
loadSuggestions,
creatable
2019-06-12 09:47:13 +02:00
} = this.props;
2018-11-14 13:40:14 +01:00
return (
<div className="field">
<LabelWithHelpIcon label={label} helpText={helpText} />
<div className="control">
2019-06-12 09:47:13 +02:00
{creatable ? (
<AsyncCreatable
cacheOptions
loadOptions={loadSuggestions}
onChange={this.handleInputChange}
value={value}
placeholder={placeholder}
loadingMessage={() => loadingMessage}
noOptionsMessage={() => noOptionsMessage}
isValidNewOption={this.isValidNewOption}
onCreateOption={value => {
this.selectValue({
label: value,
value: {
id: value,
displayName: value
}
});
}}
/>
2019-06-12 09:47:13 +02:00
) : (
<Async
cacheOptions
loadOptions={loadSuggestions}
onChange={this.handleInputChange}
value={value}
placeholder={placeholder}
loadingMessage={() => loadingMessage}
noOptionsMessage={() => noOptionsMessage}
/>
2019-06-12 09:47:13 +02:00
)}
</div>
</div>
2018-11-14 13:40:14 +01:00
);
}
}
2018-11-19 10:31:01 +01:00
export default Autocomplete;