2023-07-25 23:33:07 +08:00
|
|
|
// @deno-types="https://deno.land/x/fuse@v6.4.1/dist/fuse.d.ts"
|
2024-03-16 22:29:24 +08:00
|
|
|
import Fuse from "fuse";
|
2024-08-07 02:11:38 +08:00
|
|
|
import type { FilterOption } from "@silverbulletmd/silverbullet/type/client";
|
2023-07-25 23:33:07 +08:00
|
|
|
|
|
|
|
type FuseOption = FilterOption & {
|
|
|
|
baseName: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const fuzzySearchAndSort = (
|
|
|
|
arr: FilterOption[],
|
|
|
|
searchPhrase: string,
|
|
|
|
): FilterOption[] => {
|
|
|
|
if (!searchPhrase) {
|
|
|
|
return arr.sort((a, b) => (a.orderId || 0) - (b.orderId || 0));
|
|
|
|
}
|
2023-12-22 02:49:25 +08:00
|
|
|
|
2023-07-25 23:33:07 +08:00
|
|
|
const enrichedArr: FuseOption[] = arr.map((item) => {
|
2023-12-22 01:37:50 +08:00
|
|
|
return {
|
|
|
|
...item,
|
|
|
|
baseName: item.name.split("/").pop()!,
|
|
|
|
tags: item.tags?.join(" "),
|
|
|
|
aliases: item.aliases?.join(" "),
|
|
|
|
};
|
2023-07-25 23:33:07 +08:00
|
|
|
});
|
|
|
|
const fuse = new Fuse(enrichedArr, {
|
|
|
|
keys: [{
|
|
|
|
name: "name",
|
|
|
|
weight: 0.3,
|
|
|
|
}, {
|
|
|
|
name: "baseName",
|
2024-01-15 23:43:12 +08:00
|
|
|
weight: 1,
|
2023-12-22 01:37:50 +08:00
|
|
|
}, {
|
|
|
|
name: "displayName",
|
2024-01-15 23:43:12 +08:00
|
|
|
weight: 0.7,
|
2023-12-22 01:37:50 +08:00
|
|
|
}, {
|
|
|
|
name: "aliases",
|
2024-01-15 23:43:12 +08:00
|
|
|
weight: 0.5,
|
2024-02-03 02:19:07 +08:00
|
|
|
}, {
|
|
|
|
name: "description",
|
|
|
|
weight: 0.3,
|
2023-07-25 23:33:07 +08:00
|
|
|
}],
|
|
|
|
includeScore: true,
|
|
|
|
shouldSort: true,
|
|
|
|
isCaseSensitive: false,
|
2024-01-15 23:43:12 +08:00
|
|
|
ignoreLocation: true,
|
2023-07-25 23:33:07 +08:00
|
|
|
threshold: 0.6,
|
|
|
|
sortFn: (a, b): number => {
|
|
|
|
if (a.score === b.score) {
|
|
|
|
const aOrder = enrichedArr[a.idx].orderId || 0;
|
|
|
|
const bOrder = enrichedArr[b.idx].orderId || 0;
|
|
|
|
if (aOrder !== bOrder) {
|
|
|
|
return aOrder - bOrder;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return a.score - b.score;
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const results = fuse.search(searchPhrase);
|
|
|
|
// console.log("results", results);
|
|
|
|
return results.map((r) => r.item);
|
|
|
|
};
|