-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAsyncTypeaheadInput.tsx
More file actions
163 lines (153 loc) · 5.57 KB
/
AsyncTypeaheadInput.tsx
File metadata and controls
163 lines (153 loc) · 5.57 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { useRef, useState } from "react";
import { AsyncTypeahead, UseAsyncProps } from "react-bootstrap-typeahead";
import { Controller, FieldError, FieldValues, get } from "react-hook-form";
import { useSafeNameId } from "src/lib/hooks/useSafeNameId";
import { FormGroupLayout } from "./FormGroupLayout";
import { convertTypeaheadOptionsToStringArray, renderMenu } from "./helpers/typeahead";
import { CommonTypeaheadProps, TypeaheadOptions } from "./types/Typeahead";
import { useMarkOnFocusHandler } from "./hooks/useMarkOnFocusHandler";
import { useFormContext } from "./context/FormContext";
import TypeheadRef from "react-bootstrap-typeahead/types/core/Typeahead";
import { LabelValueOption } from "./types/LabelValueOption";
type AsyncTypeaheadProps<T extends FieldValues> = CommonTypeaheadProps<T> & {
queryFn: (query: string) => Promise<TypeaheadOptions>;
reactBootstrapTypeaheadProps?: Partial<UseAsyncProps>;
}
const AsyncTypeaheadInput = <T extends FieldValues>(props: AsyncTypeaheadProps<T>) => {
const {
disabled,
label,
helpText,
labelToolTip,
defaultSelected,
reactBootstrapTypeaheadProps,
onChange,
onInputChange,
markAllOnFocus,
addonLeft,
addonRight,
className = "",
style,
emptyLabel,
placeholder,
multiple,
invalidErrorMessage,
hideValidationMessage = false,
inputRef,
useGroupBy = false,
} = props;
const { name, id } = useSafeNameId(props?.name ?? "", props.id);
const ref = useRef<TypeheadRef | null>(null);
const {
control,
disabled: formDisabled,
formState: { errors },
setError,
clearErrors,
getValues,
getFieldState,
} = useFormContext();
const fieldError = get(errors, name) as FieldError | undefined;
const hasError = !!fieldError;
const [isLoading, setIsLoading] = useState(false);
const [options, setOptions] = useState<TypeaheadOptions>([]);
const focusHandler = useMarkOnFocusHandler(markAllOnFocus);
const isDisabled = formDisabled || disabled;
return (
<Controller
control={control}
name={name}
rules={{
validate: {
required: () => getFieldState(name)?.error?.message,
},
}}
render={({ field, fieldState: { error } }) => (
<FormGroupLayout
helpText={helpText}
name={name}
id={id}
label={label}
labelToolTip={labelToolTip}
addonLeft={addonLeft}
addonRight={addonRight}
addonProps={{
isDisabled,
}}
inputGroupStyle={props.inputGroupStyle}
hideValidationMessage={hideValidationMessage}
>
<AsyncTypeahead
{...field}
id={id}
ref={(elem) => {
ref.current = elem;
if (inputRef) {
inputRef.current = elem;
}
}}
multiple={multiple}
defaultSelected={defaultSelected}
isInvalid={hasError}
onChange={(e) => {
const values = convertTypeaheadOptionsToStringArray(e);
const finalValue = multiple ? values : values[0];
clearErrors(name);
if (onChange) {
onChange(finalValue);
}
field.onChange(finalValue);
// if not multiple, clear options to prevent the dropdown from showing multiple again when activating
if (!multiple) setOptions([]);
}}
onInputChange={onInputChange}
className={`${className} ${error ? "is-invalid" : ""}`}
inputProps={{ id }}
isLoading={isLoading}
options={options}
filterBy={() => true}
onSearch={(query) => {
void (async () => {
setIsLoading(true);
const results = await props.queryFn(query);
setOptions(results);
setIsLoading(false);
})();
}}
onBlur={() => {
if (options.length === 1 && ref.current?.state.text.length) {
ref.current?.setState({
selected: [...(ref.current?.state.selected ?? []), ...options],
text: "",
showMenu: false,
});
const newValue = typeof options[0] == "string" ? options[0] : options[0].value;
if (multiple) {
field.onChange([...((getValues(name) as [] | undefined) ?? []), newValue]);
} else {
field.onChange(newValue);
}
clearErrors(name);
} else if (ref.current?.state.text.length && (!!multiple || !ref.current?.state.selected.length)) {
// only set error if the text is not empty and the typeahead is multiple or the selected array is empty (for single select, if the selected array is not empty, it means the user has already selected an option)
setError(name, { message: invalidErrorMessage ?? "Invalid Input" });
} else {
clearErrors(name);
}
}}
disabled={isDisabled}
onFocus={(event) => {
focusHandler?.(event);
}}
{...reactBootstrapTypeaheadProps}
style={style}
emptyLabel={emptyLabel}
placeholder={placeholder}
renderMenu={useGroupBy ? (results, menuProps) => renderMenu(results as LabelValueOption[], menuProps) : undefined}
/>
</FormGroupLayout>
)}
/>
);
};
export { AsyncTypeaheadInput, AsyncTypeaheadProps };