forked from ukrbublik/react-awesome-query-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseListValuesAutocomplete.jsx
More file actions
308 lines (273 loc) · 9.3 KB
/
Copy pathuseListValuesAutocomplete.jsx
File metadata and controls
308 lines (273 loc) · 9.3 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import React from "react";
import { Utils } from "react-simple-query-builder/core";
import debounce from "lodash/debounce";
const { mergeListValues, listValueToOption, getListValue } = Utils.Autocomplete;
const { mapListValues, listValuesToArray } = Utils.ListUtils;
const useListValuesAutocomplete = ({
asyncFetch, useLoadMore, useAsyncSearch, forceAsyncSearch,
asyncListValues: selectedAsyncListValues,
listValues: staticListValues, allowCustomValues,
value: selectedValue, setValue, placeholder,
config
}, {
debounceTimeout,
multiple
}) => {
const knownSpecialValues = ["LOAD_MORE", "LOADING_MORE"];
const loadMoreTitle = "Load more...";
const loadingMoreTitle = "Loading more...";
const aPlaceholder = forceAsyncSearch ? "Type to search" : placeholder;
// state
const [open, setOpen] = React.useState(false);
const [asyncFetchMeta, setAsyncFetchMeta] = React.useState(undefined);
const [loadingCnt, setLoadingCnt] = React.useState(0);
const [isLoadingMore, setIsLoadingMore] = React.useState(false);
const [inputValue, setInputValue] = React.useState("");
const [asyncListValues, setAsyncListValues] = React.useState(undefined);
// ref
const asyncFectchCnt = React.useRef(0);
const componentIsMounted = React.useRef(0);
const isSelectedLoadMore = React.useRef(false);
// compute
const nSelectedAsyncListValues = listValuesToArray(selectedAsyncListValues);
const listValues = asyncFetch
? (!allowCustomValues ? mergeListValues(asyncListValues, nSelectedAsyncListValues, true) : asyncListValues)
: staticListValues;
//const isDirtyInitialListValues = asyncListValues == undefined && selectedAsyncListValues && selectedAsyncListValues.length && typeof selectedAsyncListValues[0] != "object";
const isLoading = loadingCnt > 0;
const canInitialLoad = open && asyncFetch
&& asyncListValues === undefined
&& (forceAsyncSearch ? inputValue : true);
const isInitialLoading = canInitialLoad && isLoading;
const canLoadMore = !isInitialLoading && listValues && listValues.length > 0
&& asyncFetchMeta && asyncFetchMeta.hasMore && (asyncFetchMeta.filter || "") === inputValue;
const canShowLoadMore = !isLoading && canLoadMore;
const options = mapListValues(listValues, listValueToOption);
const hasValue = selectedValue != null;
// const selectedListValue = hasValue ? getListValue(selectedValue, listValues) : null;
// const selectedOption = listValueToOption(selectedListValue);
// fetch
const fetchListValues = async (filter = null, isLoadMore = false) => {
// clear obsolete meta
if (!isLoadMore && asyncFetchMeta) {
setAsyncFetchMeta(undefined);
}
const offset = isLoadMore && asyncListValues ? asyncListValues.length : 0;
const meta = isLoadMore && asyncFetchMeta || !useLoadMore && { pageSize: 0 };
const newAsyncFetchCnt = ++asyncFectchCnt.current;
const res = await asyncFetch.call(config?.ctx, filter, offset, meta);
const isFetchCancelled = asyncFectchCnt.current != newAsyncFetchCnt;
if (isFetchCancelled || !componentIsMounted.current) {
return null;
}
const { values, hasMore, meta: newMeta } = res && res.values ? res : { values: res };
const nValues = listValuesToArray(values);
let assumeHasMore;
let newValues;
if (isLoadMore) {
newValues = mergeListValues(asyncListValues, nValues, false);
assumeHasMore = newValues.length > asyncListValues.length;
} else {
newValues = nValues;
if (useLoadMore) {
assumeHasMore = newValues.length > 0;
}
}
// save new meta
const realNewMeta = hasMore != null || newMeta != null || assumeHasMore != null ? {
...(assumeHasMore != null ? { hasMore: assumeHasMore } : {}),
...(hasMore != null ? { hasMore } : {}),
...(newMeta != null ? newMeta : {}),
filter
} : undefined;
if (realNewMeta) {
setAsyncFetchMeta(realNewMeta);
}
return newValues;
};
const loadListValues = async (filter = null, isLoadMore = false) => {
setLoadingCnt(x => (x + 1));
setIsLoadingMore(isLoadMore);
const list = await fetchListValues(filter, isLoadMore);
if (!componentIsMounted.current) {
return;
}
if (list != null) {
// tip: null can be used for reject (eg, if user don't want to filter by input)
setAsyncListValues(list);
}
setLoadingCnt(x => (x - 1));
setIsLoadingMore(false);
};
const loadListValuesDebounced = React.useCallback(debounce(loadListValues, debounceTimeout), []);
React.useEffect(() => {
componentIsMounted.current++;
// Initial loading
if (canInitialLoad && loadingCnt == 0 && asyncFectchCnt.current == 0) {
(async () => {
await loadListValues();
})();
}
// Unmount
return () => {
componentIsMounted.current--;
};
}, [canInitialLoad]);
// Event handlers
const onOpen = () => {
setOpen(true);
};
const onClose = (_e) => {
if (isSelectedLoadMore.current) {
isSelectedLoadMore.current = false;
if (multiple) {
setOpen(false);
}
} else {
setOpen(false);
}
};
const onDropdownVisibleChange = (open) => {
if (open) {
onOpen();
} else {
onClose();
}
};
const isSpecialValue = (option) => {
const specialValue = option?.specialValue || option?.value;
return knownSpecialValues.includes(specialValue);
};
const onChange = async (_e, option) => {
let specialValue = option?.specialValue || option?.value
|| multiple && option.map(opt => opt?.specialValue || opt?.value).find(v => !!v);
if (specialValue == "LOAD_MORE") {
isSelectedLoadMore.current = true;
await loadListValues(inputValue, true);
} else if (specialValue == "LOADING_MORE") {
isSelectedLoadMore.current = true;
} else {
if (multiple) {
const options = option;
let newSelectedListValues = options.map((o, i) => {
const item = o.value != null ? o : getListValue(o, listValues);
// AntDesign puts array of labels in `_e` (`option` is array of objects, but custom option is always `{}`)
// MUI puts array of labels in `option`
const customItem = allowCustomValues && !item ? (Array.isArray(_e) ? _e[i] : o) : null;
return item || customItem;
});
let newSelectedValues = newSelectedListValues
.filter(o => o !== undefined)
.map(o => (o.value !== undefined ? o.value : o));
if (!newSelectedValues.length)
newSelectedValues = undefined; //not allow []
setValue(newSelectedValues, newSelectedListValues);
} else {
const v = option == null ? undefined : option.value;
setValue(v, [option]);
}
}
};
const onInputChange = async (_e, newInputValue) => {
const val = newInputValue;
//const isTypeToSearch = e.type == 'change';
if (val === loadMoreTitle || val === loadingMoreTitle) {
return;
}
setInputValue(val);
if (allowCustomValues) {
if (multiple) {
//todo
} else {
setValue(val, [val]);
}
}
const canSearchAsync = useAsyncSearch && (forceAsyncSearch ? !!val : true);
if (canSearchAsync) {
await loadListValuesDebounced(val);
} else if (useAsyncSearch && forceAsyncSearch) {
setAsyncListValues([]);
}
};
// to keep compatibility with antD
const onSearch = async (newInputValue) => {
if (newInputValue === "" && !open) {
return;
}
await onInputChange(null, newInputValue);
};
// Options
const extendOptions = (options) => {
const filtered = [...options];
if (useLoadMore) {
if (canShowLoadMore) {
filtered.push({
specialValue: "LOAD_MORE",
title: loadMoreTitle,
});
} else if (isLoadingMore) {
filtered.push({
specialValue: "LOADING_MORE",
title: loadingMoreTitle,
disabled: true
});
}
}
return filtered;
};
const getOptionSelected = (option, valueOrOption) => {
if (valueOrOption == null)
return null;
const selectedValue = valueOrOption.value != undefined ? valueOrOption.value : valueOrOption;
return option.value === selectedValue;
};
const getOptionDisabled = (valueOrOption) => {
return valueOrOption && valueOrOption.disabled;
};
const getOptionLabel = (valueOrOption) => {
if (valueOrOption == null)
return null;
const option = valueOrOption.value != undefined ? valueOrOption
: listValueToOption(getListValue(valueOrOption, listValues));
if (!option && valueOrOption.specialValue) {
// special last 'Load more...' item
return valueOrOption.title;
}
if (!option && allowCustomValues) {
// there is just string value, it's not item from list
return valueOrOption;
}
if (!option) {
// weird
return valueOrOption;
}
return option.title;
};
return {
options,
listValues,
hasValue,
open,
onOpen,
onClose,
onDropdownVisibleChange,
onChange,
inputValue,
onInputChange,
onSearch,
canShowLoadMore,
isInitialLoading,
isLoading,
isLoadingMore,
isSpecialValue,
extendOptions,
getOptionSelected,
getOptionDisabled,
getOptionLabel,
// unused
//selectedListValue,
//selectedOption,
aPlaceholder,
};
};
export default useListValuesAutocomplete;