SPB Git

Repository Public

index.ts 8.3 KB 177 lines typescript

1/**2 * Local full-text search: accent-insensitive, typo-tolerant, faceted. Pure functions, no dependency,3 * no third-party service. The corpus is built server-side from the *public view* only, so a document4 * that the visitor may not see never reaches the index.5 */6import { fold } from "../learning-engine/text";78export const DOC_TYPES = ["seance", "lecon", "explorable", "diapositive", "chapitre", "transcription", "glossaire", "ressource", "schema", "page"] as const;9export type DocType = (typeof DOC_TYPES)[number];1011export const DOC_TYPE_LABELS: Record<DocType, string> = {12  seance: "Séances", lecon: "Leçons interactives", explorable: "Explorables", diapositive: "Diapositives", chapitre: "Chapitres vidéo", transcription: "Transcriptions", glossaire: "Glossaire",13  ressource: "Ressources", schema: "Schémas interactifs", page: "Pages",14};1516export const DOC_TYPE_SINGULAR: Record<DocType, string> = {17  seance: "Séance", lecon: "Leçon interactive", explorable: "Explorable", diapositive: "Diapositive", chapitre: "Chapitre vidéo", transcription: "Transcription", glossaire: "Glossaire",18  ressource: "Ressource", schema: "Schéma interactif", page: "Page",19};2021export interface SearchDoc {22  id: string;23  type: DocType;24  title: string;25  text: string;26  url: string;27  part?: string;28  session?: string;29  level?: string;30  /** Timestamp in seconds, for chapters and transcript segments. */31  t?: number;32  /** Context line shown under the title (e.g. « Séance 1 · Partie I »). */33  context?: string;34}3536export interface Filters { type?: DocType; part?: string; session?: string; level?: string }37export interface Hit { doc: SearchDoc; score: number }38export interface SearchResult {39  hits: Hit[];40  /** Counts over every match of the query, before filters, so a facet shows what it would yield. */41  facets: { type: Record<string, number>; part: Record<string, number>; session: Record<string, number>; level: Record<string, number> };42  terms: string[];43}4445const STOP = new Set("a au aux avec ce ces dans de des du d elle en et il la le les l leur ne ou par pas pour qu que qui sa se ses son sur un une y est".split(" "));4647export function tokenize(text: string): string[] {48  return fold(text).split(/[^a-z0-9]+/).filter(Boolean);49}5051/** Query terms: stop words are dropped unless the query has nothing else. */52export function queryTerms(query: string): string[] {53  const all = tokenize(query), kept = all.filter((t) => !STOP.has(t));54  return [...new Set(kept.length ? kept : all)];55}5657/** Damerau–Levenshtein distance (adjacent transposition = 1), abandoned as soon as it exceeds `max`. */58export function editDistance(a: string, b: string, max: number): number {59  if (Math.abs(a.length - b.length) > max) return max + 1;60  let prev2: number[] = [], prev = Array.from({ length: b.length + 1 }, (_, j) => j);61  for (let i = 1; i <= a.length; i++) {62    const cur = [i];63    let best = i;64    for (let j = 1; j <= b.length; j++) {65      const cost = a[i - 1] === b[j - 1] ? 0 : 1;66      let v = Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + cost);67      if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) v = Math.min(v, prev2[j - 2]! + 1);68      cur[j] = v;69      if (v < best) best = v;70    }71    if (best > max) return max + 1;72    prev2 = prev; prev = cur;73  }74  return prev[b.length]!;75}7677/** Allowed typos for a query term: none for short words, where a typo changes the meaning. */78export const fuzziness = (term: string) => (term.length >= 8 ? 2 : term.length >= 4 ? 1 : 0);7980/** How well an indexed word matches a query term: 1 exact, 0.75 prefix, 0.45 typo, 0 no match. */81export function matchQuality(term: string, word: string): number {82  if (word === term) return 1;83  if (term.length >= 2 && word.startsWith(term)) return 0.75;84  const max = fuzziness(term);85  if (max > 0 && editDistance(term, word, max) <= max) return 0.45;86  // A typo in the typed prefix of a longer word (« tokenisaton » → « tokenisation… »).87  if (max > 0 && word.length > term.length && editDistance(term, word.slice(0, term.length), max) <= max) return 0.35;88  return 0;89}9091interface Entry { title: Map<string, number>; text: Map<string, number> }9293export interface Engine { docs: SearchDoc[]; search(query: string, filters?: Filters, limit?: number): SearchResult }9495const count = (words: string[]) => { const m = new Map<string, number>(); for (const w of words) m.set(w, (m.get(w) ?? 0) + 1); return m; };96const bump = (o: Record<string, number>, k: string | undefined) => { if (k) o[k] = (o[k] ?? 0) + 1; };9798export function createEngine(docs: SearchDoc[]): Engine {99  const entries: Entry[] = docs.map((d) => ({ title: count(tokenize(`${d.title} ${d.context ?? ""}`)), text: count(tokenize(d.text)) }));100  const vocabulary = new Map<string, number>(); // word → number of documents containing it101  for (const e of entries) for (const w of new Set([...e.title.keys(), ...e.text.keys()])) vocabulary.set(w, (vocabulary.get(w) ?? 0) + 1);102  const words = [...vocabulary.keys()];103104  return {105    docs,106    search(query, filters = {}, limit = 60) {107      const terms = queryTerms(query);108      const facets: SearchResult["facets"] = { type: {}, part: {}, session: {}, level: {} };109      if (!terms.length) return { hits: [], facets, terms };110      // For each term, the vocabulary words it matches and how well.111      const expansions = terms.map((t) => {112        const m = new Map<string, number>();113        for (const w of words) { const q = matchQuality(t, w); if (q > 0) m.set(w, q); }114        return m;115      });116      const hits: Hit[] = [];117      docs.forEach((doc, i) => {118        const e = entries[i]!;119        let score = 0;120        for (const exp of expansions) {121          let best = 0;122          for (const [w, q] of exp) {123            const idf = Math.log(1 + docs.length / vocabulary.get(w)!);124            const tf = (e.title.get(w) ?? 0) * 3 + Math.min(e.text.get(w) ?? 0, 3);125            if (tf > 0) best = Math.max(best, q * q * idf * (1 + Math.log(tf)));126          }127          if (best === 0) return; // every term must match (AND)128          score += best;129        }130        // Whole sessions rank above their fragments at equal relevance.131        if (doc.type === "seance") score *= 1.25;132        bump(facets.type, doc.type); bump(facets.part, doc.part); bump(facets.session, doc.session); bump(facets.level, doc.level);133        if (filters.type && doc.type !== filters.type) return;134        if (filters.part && doc.part !== filters.part) return;135        if (filters.session && doc.session !== filters.session) return;136        if (filters.level && doc.level !== filters.level) return;137        hits.push({ doc, score });138      });139      hits.sort((a, b) => b.score - a.score || a.doc.id.localeCompare(b.doc.id));140      return { hits: hits.slice(0, limit), facets, terms };141    },142  };143}144145export interface Fragment { text: string; hit: boolean }146147/** Splits text into fragments, marking the words that match a query term (accents and typos included). */148export function highlight(text: string, terms: string[]): Fragment[] {149  const out: Fragment[] = [];150  const push = (t: string, hit: boolean) => {151    if (!t) return;152    const last = out[out.length - 1];153    if (last && last.hit === hit) last.text += t; else out.push({ text: t, hit });154  };155  // Words are runs of letters and digits; everything else is passed through untouched.156  for (const part of text.split(/([\p{L}\p{N}]+)/u)) {157    if (!part) continue;158    const isWord = /^[\p{L}\p{N}]+$/u.test(part);159    const folded = isWord ? fold(part) : "";160    push(part, isWord && terms.some((t) => matchQuality(t, folded) > 0));161  }162  return out;163}164165/** A window of about `radius` characters on each side of the first match, cut at word boundaries. */166export function snippet(text: string, terms: string[], radius = 90): string {167  if (text.length <= radius * 2) return text;168  const re = /[\p{L}\p{N}]+/gu;169  let at = -1, m: RegExpExecArray | null;170  while ((m = re.exec(text))) { const w = fold(m[0]); if (terms.some((t) => matchQuality(t, w) > 0)) { at = m.index; break; } }171  if (at < 0) return `${text.slice(0, radius * 2).replace(/\s+\S*$/, "")}…`;172  let start = Math.max(0, at - radius), end = Math.min(text.length, at + radius);173  if (start > 0) start = text.indexOf(" ", start) + 1 || start;174  if (end < text.length) end = text.lastIndexOf(" ", end) > start ? text.lastIndexOf(" ", end) : end;175  return `${start > 0 ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`;176}177
Files main
Menu

Theme