Spaces:
Running
Running
File size: 1,902 Bytes
2fdc543 c28008c 2fdc543 c28008c 2fdc543 c28008c 2fdc543 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | import Fuse from 'fuse.js';
let fuse = null;
const FUSE_OPTIONS = {
keys: [
{ name: 'name', weight: 3 },
{ name: 'id', weight: 2 },
{ name: '_searchAuthor', weight: 2 },
{ name: '_searchDescription', weight: 1.5 },
{ name: '_searchTags', weight: 1 },
],
threshold: 0.35,
ignoreLocation: true,
includeScore: true,
includeMatches: true,
};
/**
* Build a Fuse.js index from app data.
* Flattens searchable fields for better matching.
*/
function buildIndex(apps) {
const enriched = apps.map((app) => ({
id: app.id,
name: app.name,
_searchAuthor: app.extra?.author || app.id?.split('/')?.[0] || '',
_searchDescription:
app.extra?.cardData?.short_description || app.description || '',
_searchTags: [...(app.extra?.tags || []), ...(app.extra?.cardData?.tags || [])]
.filter(Boolean)
.join(' '),
}));
fuse = new Fuse(enriched, FUSE_OPTIONS);
}
/**
* Search and return ordered list of matching app IDs with scores.
*/
/**
* Search and return ordered list of matching app IDs with scores and match indices.
* Matches are keyed by field name for easy highlight rendering.
*/
function search(query) {
if (!fuse || !query.trim()) return [];
const results = fuse.search(query.trim());
return results.map((r) => {
// Convert Fuse matches array into a map: fieldName → [[start, end], ...]
const matches = {};
if (r.matches) {
for (const m of r.matches) {
matches[m.key] = m.indices;
}
}
return { id: r.item.id, score: r.score, matches };
});
}
// Handle messages from the main thread
self.onmessage = (e) => {
const { type, apps, query } = e.data;
if (type === 'INDEX') {
buildIndex(apps);
self.postMessage({ type: 'INDEXED' });
} else if (type === 'SEARCH') {
const results = search(query);
self.postMessage({ type: 'RESULTS', results, query });
}
};
|