All files / src/lib/search client.ts

95.71% Statements 67/70
89.47% Branches 34/38
100% Functions 18/18
100% Lines 58/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163                1x 1x   1x         391x                         26x   26x 91x 82x         82x       13x 13x   13x 3x     10x 10x       25x   33x     25x   3x           22x             34x   34x   34x         13x     21x 21x 21x 21x   21x 249x   249x 231x 231x 231x     249x     21x   21x   9x             31x       4x   4x 2x     2x       10x   10x 9x 7x 5x 3x 2x               5x   5x   5x 12x   12x 28x         5x       9x    
export type LocalSearchDocument = {
  title: string;
  url: string;
  description: string;
  category: string;
  tags: string[];
};
 
const ignoredSearchCharacters = /[\p{P}\p{S}\s]+/gu;
const chineseCharacterPattern = /\p{Script=Han}/u;
const chineseWordSegmenter =
  typeof Intl.Segmenter === "function"
    ? new Intl.Segmenter("zh-CN", { granularity: "word" })
    : null;
 
export function normalizeSearchText(value: string): string {
  return value.normalize("NFKC").toLocaleLowerCase().replace(ignoredSearchCharacters, "");
}
 
export type SearchMatchRange = {
  start: number;
  end: number;
};
 
type SearchWordSegment = SearchMatchRange & {
  value: string;
};
 
function getSearchWordSegments(value: string): SearchWordSegment[] {
  Iif (!chineseWordSegmenter) return [];
 
  return [...chineseWordSegmenter.segment(value)]
    .filter((segment) => segment.isWordLike)
    .map((segment) => ({
      value: normalizeSearchText(segment.segment),
      start: segment.index,
      end: segment.index + segment.segment.length,
    }))
    .filter((segment) => segment.value.length > 0);
}
 
function findChinesePhraseRange(value: string, query: string): SearchMatchRange | null {
  const querySegments = getSearchWordSegments(query);
  const valueSegments = getSearchWordSegments(value);
 
  if (!querySegments.length || querySegments.length > valueSegments.length) {
    return null;
  }
 
  for (
    let startIndex = 0;
    startIndex <= valueSegments.length - querySegments.length;
    startIndex += 1
  ) {
    const matches = querySegments.every(
      (segment, queryIndex) =>
        valueSegments[startIndex + queryIndex].value === segment.value,
    );
 
    if (!matches) continue;
 
    return {
      start: valueSegments[startIndex].start,
      end: valueSegments[startIndex + querySegments.length - 1].end,
    };
  }
 
  return null;
}
 
export function findSearchMatchRange(
  value: string,
  query: string,
): SearchMatchRange | null {
  const normalizedQuery = normalizeSearchText(query);
 
  Iif (!normalizedQuery) return null;
 
  if (
    normalizedQuery.length > 1 &&
    chineseCharacterPattern.test(normalizedQuery) &&
    chineseWordSegmenter
  ) {
    return findChinesePhraseRange(value, query);
  }
 
  let normalizedValue = "";
  const starts: number[] = [];
  const ends: number[] = [];
  let offset = 0;
 
  for (const character of value) {
    const normalizedCharacter = normalizeSearchText(character);
 
    for (let index = 0; index < normalizedCharacter.length; index += 1) {
      normalizedValue += normalizedCharacter[index];
      starts.push(offset);
      ends.push(offset + character.length);
    }
 
    offset += character.length;
  }
 
  const matchIndex = normalizedValue.indexOf(normalizedQuery);
 
  if (matchIndex === -1) return null;
 
  return {
    start: starts[matchIndex],
    end: ends[matchIndex + normalizedQuery.length - 1],
  };
}
 
export function hasContiguousSearchMatch(value: string, query: string): boolean {
  return findSearchMatchRange(value, query) !== null;
}
 
export function buildPagefindQuery(query: string): string {
  const normalizedQuery = normalizeSearchText(query);
 
  if (normalizedQuery.length > 1 && chineseCharacterPattern.test(normalizedQuery)) {
    return `"${query.replaceAll('"', "").trim()}"`;
  }
 
  return query;
}
 
function getMatchRank(document: LocalSearchDocument, query: string): number {
  const title = normalizeSearchText(document.title);
 
  if (title === query) return 0;
  if (title.startsWith(query)) return 1;
  if (title.includes(query)) return 2;
  if (document.tags.some((tag) => normalizeSearchText(tag) === query)) return 3;
  if (normalizeSearchText(document.category) === query) return 4;
  return 5;
}
 
export function findLocalSearchMatches(
  documents: LocalSearchDocument[],
  query: string,
  limit = 12,
): LocalSearchDocument[] {
  const normalizedQuery = normalizeSearchText(query);
 
  Iif (!normalizedQuery) return [];
 
  return documents
    .map((document, index) => ({ document, index }))
    .filter(({ document }) =>
      [document.title, document.description, document.category, ...document.tags].some(
        (value) => hasContiguousSearchMatch(value, normalizedQuery),
      ),
    )
    .sort(
      (a, b) =>
        getMatchRank(a.document, normalizedQuery) -
          getMatchRank(b.document, normalizedQuery) || a.index - b.index,
    )
    .slice(0, limit)
    .map(({ document }) => document);
}