// Library search and facet filtering (runs in the browser; the library is small). export type SearchableModel = { repoId: string; author: string; families: string[]; baseModels: string[]; architecture: string | null; quants: string[]; tags: string[]; hubTags: string[]; pipelineTag: string | null; license: string | null; status: string; }; export const FACETS = ["author", "family", "quant", "tag", "status"] as const; export type Facet = (typeof FACETS)[number]; export type Filters = Record; export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [] }; export function facetValues(m: SearchableModel, facet: Facet): string[] { switch (facet) { case "author": return [m.author]; case "family": return m.families; case "quant": return m.quants; case "tag": return m.tags; case "status": return [m.status]; } } function haystack(m: SearchableModel): string { return [ m.repoId, m.author, ...m.families, ...m.baseModels, m.architecture, ...m.quants, ...m.tags, ...m.hubTags, m.pipelineTag, m.license, m.status, ] .filter(Boolean) .join(" ") .toLowerCase(); } /** Every whitespace-separated term must appear somewhere (case-insensitive substring). */ export function matchesQuery(m: SearchableModel, query: string): boolean { const terms = query.toLowerCase().split(/\s+/).filter(Boolean); if (terms.length === 0) return true; const text = haystack(m); return terms.every((t) => text.includes(t)); } /** OR within a facet, AND across facets. Values compare case-insensitively. */ export function matchesFilters(m: SearchableModel, filters: Filters, except?: Facet): boolean { return FACETS.every((facet) => { const wanted = filters[facet]; if (facet === except || wanted.length === 0) return true; const have = facetValues(m, facet).map((v) => v.toLowerCase()); return wanted.some((w) => have.includes(w.toLowerCase())); }); } /** * Value counts for one facet, computed over the models that match the query and all *other* * facets, so picking e.g. an author narrows the quant counts but not the author list itself. */ export function facetCounts(models: SearchableModel[], facet: Facet, query: string, filters: Filters) { const counts = new Map(); for (const m of models) { if (!matchesQuery(m, query) || !matchesFilters(m, filters, facet)) continue; for (const v of new Set(facetValues(m, facet))) counts.set(v, (counts.get(v) ?? 0) + 1); } // Keep selected values visible even if their count dropped to 0. for (const v of filters[facet]) if (!counts.has(v)) counts.set(v, 0); return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], undefined, { numeric: true })); }