- (items, {
findAllMatches: true,
shouldSort: false,
minMatchCharLength: 2,
threshold: 0.3,
ignoreLocation: true,
includeScore: true,
keys: [
{
name: 'name',
weight: 4,
},
{
name: 'namespace',
weight: 3,
},
{
name: 'tags',
weight: 2,
},
{
name: 'data',
weight: 1,
},
],
getFn: (item: Item, path) => {
// The `path` here can only be names from the `keys` configuration option
// so it is safe to assert the type here. Additionally the argument value
// is typed by the library as string | string[]. Even though the library
// seem to always return an array, we will handle it as if we are not sure
// excatly what is passed here
const key = (Array.isArray(path) ? path[0] : path) as
| 'name'
| 'namespace'
| 'tags'
| 'data';
if (key === 'namespace') {
return `${item.database}.${item.collection}`;
}
if (key === 'tags') {
if (item.type === 'query') {
return ['find', 'query'];
} else {
return ['aggregate', 'aggregation', 'pipeline'];
}
}
if (key === 'data') {
if (item.type === 'query') {
return JSON.stringify({
filter: item.query.filter,
});
} else {
return item.aggregation.pipelineText;
}
}
return item[key];
},
});
return fuse.search(text).map((x) => ({ item: x.item, score: x.score ?? 0 }));
}
function filterByConditions(items: FilterItem[], conditions: SelectState) {
const filterConditions = { ...conditions };
for (const key in filterConditions) {
if (!filterConditions[key as keyof SelectState]) {
delete filterConditions[key as keyof SelectState];
}
}
return [...items].filter((item) =>
filterItemByConditions(item.item, filterConditions)
);
}
export function useGridFilters(items: Item[]): {
controls: React.ReactElement;
conditions: SelectState;
search: string;
} {
const [selectControls, conditions] = useSelectFilter(items);
const [searchControls, search] = useSearchFilter();
const controls = useMemo(() => {
return (
{searchControls}
{selectControls}
);
}, [searchControls, selectControls]);
return {
controls,
conditions,
search,
};
}
export function useFilteredItems(
items: Item[],
conditions: SelectState,
search: string
): FilterItem[] {
const filteredItems: FilterItem[] = filterByText(items, search);
return filterByConditions(filteredItems, conditions);
}