SPB Git

Repository Public

highlight.tsx 3.5 KB 86 lines tsx

1import type { ReactNode } from 'react';23/** One UTF-16 unit, lower-cased and stripped of diacritics, so indices stay aligned with the source string. */4function foldUnit(c: string): string {5  const f = c.normalize('NFD').charAt(0).toLowerCase();6  return f.length === 1 ? f : c;7}8const fold = (s: string): string => Array.from({ length: s.length }, (_, i) => foldUnit(s.charAt(i))).join('');910/** Positive terms of a query: operators (site:, lang:), exclusions and punctuation are dropped. */11export function queryTerms(q: string): string[] {12  const out = new Set<string>();13  for (const raw of q.replace(/["“”«»]/g, ' ').split(/\s+/)) {14    if (!raw || raw.startsWith('-') || /^(site|lang):/i.test(raw)) continue;15    const term = fold(raw).replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');16    if (term.length >= 2) out.add(term);17  }18  return [...out].sort((a, b) => b.length - a.length).slice(0, 12);19}2021/**22 * Emphasises query terms in plain text. The string is split into text nodes and <mark>23 * elements; nothing is ever parsed as HTML. Matching ignores case and accents and starts24 * at word boundaries.25 */26export function Highlight({ text, terms }: { text: string; terms: string[] }): ReactNode {27  if (terms.length === 0 || !text) return text;28  const hay = fold(text);29  const out: ReactNode[] = [];30  let i = 0;31  let from = 0;32  const isWord = (c: string) => /[\p{L}\p{N}]/u.test(c);33  while (i < hay.length) {34    const boundary = i === 0 || !isWord(hay.charAt(i - 1));35    const hit = boundary ? terms.find((t) => hay.startsWith(t, i)) : undefined;36    if (hit) {37      // Extend to the end of the word so that "recherche" also marks "recherches".38      let end = i + hit.length;39      while (end < hay.length && isWord(hay.charAt(end)) && end - i < hit.length + 3) end++;40      if (end < hay.length && isWord(hay.charAt(end))) {41        i++;42        continue;43      }44      if (i > from) out.push(text.slice(from, i));45      out.push(<mark key={i}>{text.slice(i, end)}</mark>);46      i = end;47      from = end;48    } else {49      i++;50    }51  }52  if (from < text.length) out.push(text.slice(from));53  return out;54}5556/** Deterministic colour slot (0–7) for a domain's monogram tile. */57export function monoSlot(domain: string): number {58  let h = 0;59  for (let i = 0; i < domain.length; i++) h = (h * 31 + domain.charCodeAt(i)) >>> 0;60  return h % 8;61}6263export function monoLetter(domain: string): string {64  const m = /[\p{L}\p{N}]/u.exec(domain.replace(/^www\./, ''));65  return (m ? m[0] : '·').toUpperCase();66}6768const NAMED: Record<string, string> = { amp: '&', quot: '"', apos: "'", lt: '<', gt: '>', nbsp: '\u00a0' };6970/**71 * Some pages reach the index with their entities encoded twice, so the API text still reads72 * "L&#039;intelligence". Decoded here for display only, into a plain string that React renders as73 * text (never as markup): numeric, hexadecimal and the six common named entities.74 */75export function decodeEntities(text: string): string {76  if (!text || text.indexOf('&') < 0) return text;77  return text.replace(/&(#\d{1,7}|#x[0-9a-f]{1,6}|amp|quot|apos|lt|gt|nbsp);/gi, (m, e: string) => {78    if (e.charAt(0) !== '#') return NAMED[e.toLowerCase()] ?? m;79    const code = /^#x/i.test(e) ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);80    if (!Number.isFinite(code) || code <= 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return m;81    // Control characters would be invisible noise: keep the original text instead.82    if (code < 32 && code !== 9 && code !== 10) return m;83    return String.fromCodePoint(code);84  });85}86
Files main
Menu

Theme