web/src/utils/do-searchy-searchy.ts

128 lines · 4181 bytes

7 symbols in this file
  1import Fuse from 'fuse.js';
  2
  3import type { Category, Service } from '../types/Service';
  4import { fetchCategories, slugify } from './fetch-data';
  5
  6export interface SearchItem {
  7  type: 'Category' | 'Section' | 'Service';
  8  category: string;
  9  path: string;
 10  itemCount?: number;
 11  sectionName?: string;
 12  description?: string;
 13  name?: string;
 14  url?: string;
 15  github?: string;
 16  codeberg?: string;
 17  git?: string;
 18  logo?: string;
 19  platforms?: string[];
 20  traits?: string[];
 21  alternativeTo?: string[];
 22  service?: Service;
 23}
 24
 25export const prepareSearchItems = (categories: Category[]): SearchItem[] => {
 26  const items: SearchItem[] = [];
 27  // Add each category
 28  categories.forEach((category) => {
 29    const categoryPath = `/${slugify(category.name)}/`;
 30    items.push({
 31      type: 'Category',
 32      category: category.name,
 33      path: categoryPath,
 34      itemCount: (category.sections || []).reduce((acc, section) => {
 35        return acc + (section.services || []).length;
 36      }, 0),
 37    });
 38
 39    // Add section with category context
 40    (category.sections || []).forEach((section) => {
 41      const sectionPath = `${categoryPath}${slugify(section.name)}/`;
 42      items.push({
 43        type: 'Section',
 44        sectionName: section.name,
 45        description: section.intro || '',
 46        category: category.name,
 47        path: sectionPath,
 48        itemCount: (section.services || []).length,
 49      });
 50
 51      // Add service with section and category context
 52      (section.services || []).forEach((service) => {
 53        items.push({
 54          type: 'Service',
 55          name: service.name,
 56          description: service.description,
 57          url: service.url,
 58          github: service.github || '',
 59          codeberg: service.codeberg || '',
 60          git: service.git || '',
 61          category: category.name,
 62          sectionName: section.name,
 63          path: `${sectionPath}${slugify(service.name)}/`,
 64          logo: service.icon || '',
 65          // Get the platform from followWith field or android/ios app
 66          platforms: Object.keys(service)
 67            .filter((key) => key.endsWith('App'))
 68            .map((key) => key.replace(/App$/, ''))
 69            .concat(service.followWith || []),
 70          // Boolean fields, as words: `openSource` -> "open source"
 71          traits: Object.entries(service)
 72            .filter(([, value]) => value === true)
 73            .map(([key]) =>
 74              key.replace(/[A-Z]/g, (c) => ` ${c.toLowerCase()}`),
 75            ),
 76          // The proprietary tools this section replaces, eg "whatsapp"
 77          alternativeTo: section.alternativeTo || [],
 78          // Kept so results can render a card without a second lookup
 79          service,
 80        });
 81      });
 82    });
 83  });
 84  return items;
 85};
 86
 87// Set the fuzziness power. 0 = perfect match, and 1 = barely matched
 88export const SEARCH_SCORE_CUTOFF = 0.85;
 89
 90export const isRelevant = (result: { score?: number }): boolean =>
 91  (result.score ?? 0) <= SEARCH_SCORE_CUTOFF;
 92
 93export const searchOptions = {
 94  includeScore: true,
 95  ignoreLocation: true,
 96  threshold: 0.3,
 97  keys: [
 98    { name: 'name', weight: 0.9 },
 99    { name: 'sectionName', weight: 0.8 },
100    { name: 'alternativeTo', weight: 0.8 },
101    { name: 'category', weight: 0.7 },
102    { name: 'platforms', weight: 0.6 },
103    { name: 'traits', weight: 0.6 },
104    { name: 'github', weight: 0.4 },
105    { name: 'codeberg', weight: 0.4 },
106    { name: 'git', weight: 0.3 },
107    { name: 'url', weight: 0.2 },
108    { name: 'description', weight: 0.1 },
109  ],
110};
111
112// Built once per page, and shared by the search box and the results island
113let indexPromise: Promise<Fuse<SearchItem>> | null = null;
114
115export const getSearchIndex = (): Promise<Fuse<SearchItem>> =>
116  (indexPromise ??= fetchCategories().then((categories) => {
117    // Caching a failed fetch would leave search empty for the whole session
118    if (!categories.length) indexPromise = null;
119    return new Fuse(prepareSearchItems(categories), searchOptions);
120  }));
121
122export const runSearch = async (term: string): Promise<SearchItem[]> =>
123  term
124    ? (await getSearchIndex())
125        .search(term)
126        .filter(isRelevant)
127        .map((r) => r.item)
128    : [];