fixed search

This commit is contained in:
Claudio Maggioni 2023-05-31 12:01:54 +02:00
parent 81dd531e03
commit 9aad3e3ca0

View file

@ -116,37 +116,56 @@ const sortSelected = ref<number>(sortItems.length - 1);
const loading = ref(true);
const companies = ref<Company[]>([]);
const filteredCompanies = ref<(Company & { score?: number })[]>([]);
const tags = ref<string[]>([]);
const tickers = ref<string[]>([]);
type CompanyWithScore = Company & { score?: number }
const filteredCompanies = ref<CompanyWithScore[]>([]);
const selected = reactive<string[]>([]);
const searchText = ref("");
const router = useRouter();
let fuse: Fuse<Company> | undefined = undefined;
const sortCompanies = () => {
const sortCompanies = (companiesToSort: CompanyWithScore[]) => {
const sorter = sortItems[sortSelected.value]!;
if (sorter.sortBy !== undefined) {
const key: keyof Company = sorter.sortBy;
filteredCompanies.value = filteredCompanies.value.sort(naturalOrder(c => c[key]))
filteredCompanies.value = companiesToSort.sort(naturalOrder(c => c[key]))
} else {
filteredCompanies.value = companiesToSort.sort(naturalOrder(c => c.score ?? c.ticker));
}
}
const search = debounce(() => setTimeout(() => {
filteredCompanies.value = fuse!.search(searchText.value).map(e => ({ ...e.item, score: e.score }))
sortCompanies();
let companiesToSort: CompanyWithScore[];
if (tags.value.indexOf(searchText.value) !== -1) {
companiesToSort = companies.value.filter(e => e.tags.indexOf(searchText.value) !== -1);
} else {
const ticker = searchText.value.trim().toUpperCase();
if (tickers.value.indexOf(ticker) !== -1) {
companiesToSort = [companies.value.find(c => c.ticker == ticker)!];
} else {
companiesToSort = fuse!.search(searchText.value).map(e => ({ ...e.item, score: e.score }));
}
}
sortCompanies(companiesToSort);
}, 0), 1000);
watch(sortSelected, () => sortCompanies());
const searchAll = debounce(() => {
sortCompanies(companies.value);
}, 1000);
watch(sortSelected, () => {
sortCompanies(filteredCompanies.value)
});
watch(searchText, () => {
if (!fuse) return;
loading.value = true;
if (searchText.value === '') {
filteredCompanies.value = companies.value;
sortCompanies();
loading.value = false;
return;
}
else {
loading.value = true;
searchAll();
} else {
search();
}
});
@ -171,8 +190,16 @@ watch(filteredCompanies, () => loading.value = false);
getCompanies().then(cs => {
companies.value = cs;
const myIndex = Fuse.createIndex(['ceo', 'company name', 'description', 'sector', 'tags', 'ticker', 'website'], cs);
fuse = new Fuse(cs, { threshold: 0.5, ignoreLocation: true }, myIndex);
tags.value = cs.flatMap(c => c.tags);
tickers.value = cs.map(c => c.ticker);
const myIndex = Fuse.createIndex([
{ name: 'company name', weight: 2 },
'sector',
'tags',
{ name: 'ticker', weight: 10 },
'website'
], cs);
fuse = new Fuse(cs, { threshold: 0.6 }, myIndex);
filteredCompanies.value = cs;
});
</script>