2023-05-28 23:13:24 +02:00
|
|
|
import { type MaybeRef, get } from '@vueuse/core';
|
2022-12-16 18:10:50 +01:00
|
|
|
import Fuse from 'fuse.js';
|
|
|
|
import { computed } from 'vue';
|
|
|
|
|
|
|
|
export { useFuzzySearch };
|
|
|
|
|
|
|
|
function useFuzzySearch<Data>({
|
|
|
|
search,
|
|
|
|
data,
|
|
|
|
options = {},
|
|
|
|
}: {
|
2023-05-28 23:13:24 +02:00
|
|
|
search: MaybeRef<string>
|
|
|
|
data: Data[]
|
2023-08-07 17:30:00 +02:00
|
|
|
options?: Fuse.IFuseOptions<Data> & { filterEmpty?: boolean }
|
2022-12-16 18:10:50 +01:00
|
|
|
}) {
|
|
|
|
const fuse = new Fuse(data, options);
|
2023-08-07 17:30:00 +02:00
|
|
|
const filterEmpty = options.filterEmpty ?? true;
|
2022-12-16 18:10:50 +01:00
|
|
|
|
2023-08-07 17:30:00 +02:00
|
|
|
const searchResult = computed<Data[]>(() => {
|
|
|
|
const query = get(search);
|
|
|
|
|
|
|
|
if (!filterEmpty && query === '') {
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
return fuse.search(query).map(({ item }) => item);
|
2022-12-16 18:10:50 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
return { searchResult };
|
|
|
|
}
|