-
Notifications
You must be signed in to change notification settings - Fork 173
/
combobox.tsx
103 lines (88 loc) · 2.82 KB
/
combobox.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import * as React from "react";
import Creatable from "react-select/creatable";
import withTestAttributes from "./input/select-test-attributes";
type ReactSelectItem = {
value: string | null | undefined;
id: any | null | undefined;
label: string;
};
export type ComboboxItem = {
id: any;
text: string;
};
type ComboboxProps = {
id?: string;
name?: string;
options?: Array<ComboboxItem>;
selectedId?: (number | null | undefined) | (string | null | undefined);
onFocus?: () => void;
onSelect: (value: ComboboxItem) => void;
getNewOptionData?: (userInput: string, label: string) => { id: string; value: string; label: string };
placeholder?: string;
/** Id for testing purposes */
"data-testid"?: string;
};
type ComboboxState = {
focused: boolean;
};
export class Combobox extends React.Component<ComboboxProps, ComboboxState> {
onChange = (selectedOption: ReactSelectItem) => {
if (selectedOption.id && selectedOption.value) {
return this.props.onSelect({
id: selectedOption.id,
text: selectedOption.label,
});
}
const sanitizedLabel = selectedOption.label && selectedOption.label.replace(/[',]/g, "");
// It means a new option was created
return this.props.onSelect({
id: selectedOption.id,
text: sanitizedLabel,
});
};
render() {
const colourStyles = {
option: (styles, { data, isDisabled, isFocused, isSelected }) => {
if (isFocused) {
return Object.assign(styles, { backgroundColor: "#052940", color: "#ffffff" });
}
if (isSelected) {
return Object.assign(styles, { backgroundColor: "#063559", color: "#ffffff" });
}
return styles;
},
menu: (styles: {}) => ({
...styles,
zIndex: 3,
}),
menuPortal: (styles: {}) => ({
...styles,
zIndex: 9999,
}),
};
// The react-select is expecting the value to be a string, but let's keep the original id here so we can propagate
// correctly the selected option up.
const options: Array<ReactSelectItem> = (this.props.options || []).map((item) => ({
value: item.id.toString(),
id: item.id,
label: item.text,
}));
const testAttributes = withTestAttributes(this.props["data-testid"], this.props.name);
return (
<Creatable
id={this.props.id}
name={this.props.name}
onFocus={this.props.onFocus}
onChange={this.onChange}
value={options.find((option) => option.id === this.props.selectedId)}
options={options}
styles={colourStyles}
menuPortalTarget={document.body}
formatCreateLabel={(label: string) => t("Create {label}", { label })}
getNewOptionData={this.props.getNewOptionData}
placeholder={this.props.placeholder}
{...testAttributes}
/>
);
}
}