mirror of
https://github.com/hexastack/hexabot
synced 2025-05-12 00:21:05 +00:00
fix: autocomplete entity
This commit is contained in:
parent
d089506579
commit
bd7a850d87
@ -8,13 +8,14 @@
|
|||||||
|
|
||||||
import { ChipTypeMap } from "@mui/material";
|
import { ChipTypeMap } from "@mui/material";
|
||||||
import { AutocompleteProps } from "@mui/material/Autocomplete";
|
import { AutocompleteProps } from "@mui/material/Autocomplete";
|
||||||
import { forwardRef, useEffect, useState } from "react";
|
import { forwardRef, useEffect, useRef } from "react";
|
||||||
|
|
||||||
import { useFind } from "@/hooks/crud/useFind";
|
import { useInfiniteFind } from "@/hooks/crud/useInfiniteFind";
|
||||||
import { useSearch } from "@/hooks/useSearch";
|
import { useSearch } from "@/hooks/useSearch";
|
||||||
import { Format } from "@/services/types";
|
import { Format, QueryType } from "@/services/types";
|
||||||
import { IEntityMapTypes } from "@/types/base.types";
|
import { IEntityMapTypes } from "@/types/base.types";
|
||||||
import { TFilterStringFields } from "@/types/search.types";
|
import { TFilterStringFields } from "@/types/search.types";
|
||||||
|
import { generateId } from "@/utils/generateId";
|
||||||
|
|
||||||
import AutoCompleteSelect from "./AutoCompleteSelect";
|
import AutoCompleteSelect from "./AutoCompleteSelect";
|
||||||
|
|
||||||
@ -62,75 +63,53 @@ const AutoCompleteEntitySelect = <
|
|||||||
helperText,
|
helperText,
|
||||||
preprocess,
|
preprocess,
|
||||||
idKey = "id",
|
idKey = "id",
|
||||||
|
labelKey,
|
||||||
...rest
|
...rest
|
||||||
}: AutoCompleteEntitySelectProps<Value, Label, Multiple>,
|
}: AutoCompleteEntitySelectProps<Value, Label, Multiple>,
|
||||||
ref,
|
ref,
|
||||||
) => {
|
) => {
|
||||||
const { onSearch, searchPayload } = useSearch<Value>({
|
const { onSearch, searchPayload } = useSearch<Value>({
|
||||||
$iLike: searchFields as TFilterStringFields<unknown>,
|
$or: (searchFields as TFilterStringFields<unknown>) || [idKey, labelKey],
|
||||||
});
|
});
|
||||||
const [initialValue] = useState(value);
|
const idRef = useRef(generateId());
|
||||||
const { data: defaultData, isLoading: isDefaultLoading } = useFind(
|
const params = {
|
||||||
{ entity, format },
|
|
||||||
{
|
|
||||||
params: {
|
|
||||||
where: {
|
where: {
|
||||||
...(initialValue && Array.isArray(initialValue)
|
or: [
|
||||||
? initialValue.length > 1
|
...(searchPayload.where.or || []),
|
||||||
? { or: initialValue.map((v) => ({ [idKey]: v })) }
|
...(value
|
||||||
: { [idKey]: initialValue[0] }
|
? Array.isArray(value)
|
||||||
: { [idKey]: initialValue }),
|
? value.map((v) => ({ [idKey]: v }))
|
||||||
|
: [{ [idKey]: value }]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
},
|
},
|
||||||
},
|
};
|
||||||
hasCount: false,
|
const { data, isFetching, fetchNextPage } = useInfiniteFind(
|
||||||
},
|
|
||||||
{
|
|
||||||
keepPreviousData: true,
|
|
||||||
enabled: Array.isArray(initialValue) ? initialValue.length > 0 : !!value,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const { data: newData, isLoading } = useFind(
|
|
||||||
{ entity, format },
|
{ entity, format },
|
||||||
{
|
{
|
||||||
params: {
|
params,
|
||||||
...searchPayload,
|
|
||||||
where: { ...searchPayload.where, skip: 0, limit: 10 },
|
|
||||||
},
|
|
||||||
hasCount: false,
|
hasCount: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
keepPreviousData: true,
|
keepPreviousData: true,
|
||||||
|
queryKey: [QueryType.collection, entity, `autocomplete/${idRef.current}`],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
const data = [...(defaultData || []), ...(newData || [])];
|
// flatten & filter unique
|
||||||
const [accumulatedOptions, setAccumulatedOptions] = useState<
|
const flattenedData = data?.pages
|
||||||
Map<string, Value>
|
?.flat()
|
||||||
>(new Map());
|
.filter(
|
||||||
|
(a, idx, self) => self.findIndex((b) => a[idKey] === b[idKey]) === idx,
|
||||||
|
);
|
||||||
|
const options =
|
||||||
|
preprocess && flattenedData
|
||||||
|
? preprocess((flattenedData || []) as unknown as Value[])
|
||||||
|
: ((flattenedData || []) as Value[]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (data) {
|
fetchNextPage({ pageParam: params });
|
||||||
const newOptions =
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
preprocess && data
|
}, [JSON.stringify(searchPayload)]);
|
||||||
? preprocess((data || []) as Value[])
|
|
||||||
: ((data || []) as Value[]);
|
|
||||||
|
|
||||||
setAccumulatedOptions((prevMap) => {
|
|
||||||
const newMap = new Map(prevMap);
|
|
||||||
|
|
||||||
newOptions.forEach((option) => {
|
|
||||||
const id = option[idKey];
|
|
||||||
|
|
||||||
if (!newMap.has(id)) {
|
|
||||||
newMap.set(id, option);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return newMap;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [JSON.stringify(newData), idKey]);
|
|
||||||
|
|
||||||
const options = Array.from(accumulatedOptions.values());
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AutoCompleteSelect<Value, Label, Multiple>
|
<AutoCompleteSelect<Value, Label, Multiple>
|
||||||
@ -140,11 +119,12 @@ const AutoCompleteEntitySelect = <
|
|||||||
multiple={multiple}
|
multiple={multiple}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
idKey={idKey}
|
idKey={idKey}
|
||||||
|
labelKey={labelKey}
|
||||||
options={options || []}
|
options={options || []}
|
||||||
onSearch={onSearch}
|
onSearch={onSearch}
|
||||||
error={error}
|
error={error}
|
||||||
helperText={helperText}
|
helperText={helperText}
|
||||||
loading={isLoading || isDefaultLoading}
|
loading={isFetching}
|
||||||
{...rest}
|
{...rest}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
@ -6,7 +6,7 @@
|
|||||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Box, Chip, ChipTypeMap } from "@mui/material";
|
import { Box, Chip, ChipTypeMap, CircularProgress } from "@mui/material";
|
||||||
import Autocomplete, {
|
import Autocomplete, {
|
||||||
AutocompleteProps,
|
AutocompleteProps,
|
||||||
AutocompleteValue,
|
AutocompleteValue,
|
||||||
@ -185,6 +185,9 @@ const AutoCompleteSelect = <
|
|||||||
{options.length === 0 && !loading && noOptionsWarning && (
|
{options.length === 0 && !loading && noOptionsWarning && (
|
||||||
<AlertAdornment title={noOptionsWarning} type="warning" />
|
<AlertAdornment title={noOptionsWarning} type="warning" />
|
||||||
)}
|
)}
|
||||||
|
{loading ? (
|
||||||
|
<CircularProgress color="inherit" size={20} />
|
||||||
|
) : null}
|
||||||
{props.InputProps.endAdornment}
|
{props.InputProps.endAdornment}
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
|
90
frontend/src/hooks/crud/useInfiniteFind.ts
Normal file
90
frontend/src/hooks/crud/useInfiniteFind.ts
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
/*
|
||||||
|
* Copyright © 2024 Hexastack. All rights reserved.
|
||||||
|
*
|
||||||
|
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
|
||||||
|
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
|
||||||
|
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useInfiniteQuery, UseInfiniteQueryOptions } from "react-query";
|
||||||
|
|
||||||
|
import {
|
||||||
|
EntityType,
|
||||||
|
Format,
|
||||||
|
QueryType,
|
||||||
|
TPopulateTypeFromFormat,
|
||||||
|
} from "@/services/types";
|
||||||
|
import {
|
||||||
|
IBaseSchema,
|
||||||
|
IDynamicProps,
|
||||||
|
IFindConfigProps,
|
||||||
|
POPULATE_BY_TYPE,
|
||||||
|
TAllowedFormat,
|
||||||
|
TType,
|
||||||
|
} from "@/types/base.types";
|
||||||
|
|
||||||
|
import { useNormalizeAndCache } from "./helpers";
|
||||||
|
import { useGetFromCache } from "./useGet";
|
||||||
|
import { useEntityApiClient } from "../useApiClient";
|
||||||
|
|
||||||
|
export const useInfiniteFind = <
|
||||||
|
TDynamicProps extends IDynamicProps,
|
||||||
|
TAttr = TType<TDynamicProps["entity"]>["attributes"],
|
||||||
|
TBasic extends IBaseSchema = TType<TDynamicProps["entity"]>["basic"],
|
||||||
|
TFull extends IBaseSchema = TType<TDynamicProps["entity"]>["full"],
|
||||||
|
P = TPopulateTypeFromFormat<TDynamicProps>,
|
||||||
|
>(
|
||||||
|
{ entity, format }: TDynamicProps & TAllowedFormat<TDynamicProps["entity"]>,
|
||||||
|
config?: IFindConfigProps,
|
||||||
|
options?: Omit<
|
||||||
|
UseInfiniteQueryOptions<
|
||||||
|
string[],
|
||||||
|
Error,
|
||||||
|
string[],
|
||||||
|
[QueryType, EntityType, any]
|
||||||
|
>,
|
||||||
|
"queryFn" | "onSuccess"
|
||||||
|
> & { onSuccess?: (result: TBasic[]) => void },
|
||||||
|
) => {
|
||||||
|
const { onSuccess, queryKey, ...otherOptions } = options || {};
|
||||||
|
const api = useEntityApiClient<TAttr, TBasic, TFull>(entity);
|
||||||
|
const normalizeAndCache = useNormalizeAndCache<TBasic | TFull, string[]>(
|
||||||
|
entity,
|
||||||
|
);
|
||||||
|
const getFromCache = useGetFromCache(entity);
|
||||||
|
// @TODO : fix the following
|
||||||
|
// @ts-ignore
|
||||||
|
const { data: infiniteData, ...infiniteQuery } = useInfiniteQuery({
|
||||||
|
queryKey,
|
||||||
|
queryFn: async () => {
|
||||||
|
const data = await api.find(
|
||||||
|
{
|
||||||
|
...(config?.params || {}),
|
||||||
|
},
|
||||||
|
format === Format.FULL && (POPULATE_BY_TYPE[entity] as P),
|
||||||
|
);
|
||||||
|
const { entities, result } = normalizeAndCache(data);
|
||||||
|
|
||||||
|
if (onSuccess) {
|
||||||
|
onSuccess(
|
||||||
|
Object.values(entities[entity] as unknown as Record<string, TBasic>),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
...(otherOptions || {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
...infiniteQuery,
|
||||||
|
data: infiniteData
|
||||||
|
? {
|
||||||
|
...infiniteData,
|
||||||
|
pages: (infiniteData?.pages || []).map((page) =>
|
||||||
|
page.map((id) => getFromCache(id) as unknown as TBasic),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
};
|
Loading…
Reference in New Issue
Block a user