All files / typeahead si-typeahead.search.ts

98.66% Statements 74/75
96.77% Branches 30/31
100% Functions 17/17
98.63% Lines 72/73

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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275                                                                                                                                    1x       281x     423x     281x 281x 281x       567x       423x 423x   423x 432x         423x 144x     423x 423x 826x   826x 826x                             826x 511x 511x             511x   315x 315x   315x     315x 329x   329x 128x           128x 89x   128x 110x   128x       315x     315x             103x       103x 24x   124x 24x 28x       24x 8x       8x 7x   8x 8x 6x   8x     116x               103x       211x         121x   108x       103x 103x     103x     103x 116x 116x 29x             116x           116x 116x 116x       103x           97x 97x 61x             97x           423x              
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { computed, Signal } from '@angular/core';
 
export interface SearchOptions<T> {
  /** The text that will be used for searching. */
  text: string;
  /** The raw option that will be also included in the Match results */
  option: T;
}
 
export interface MatchSegment {
  text: string;
  isMatching: boolean;
  matches: number;
  uniqueMatches: number;
}
 
export interface Match<T> {
  option: T;
  text: string;
  result: MatchSegment[];
  stringMatch: boolean;
  atBeginning: boolean;
  matches: number;
  uniqueMatches: number;
  uniqueSeparateMatches: number;
  matchesEntireQuery: boolean;
  matchesAllParts: boolean;
  matchesAllPartsSeparately: boolean;
}
 
export interface SearchConfig {
  /** Defines whether to tokenize the search or match the whole search. */
  disableTokenizing?: boolean;
  /**
   * Defines whether and how to require to match with all the tokens if {@link typeaheadTokenize} is enabled.
   * - `no` does not require all of the tokens to match.
   * - `once` requires all of the parts to be found in the search.
   * - `separately` requires all of the parts to be found in the search where there is not an overlapping different result.
   * - `independently` requires all of the parts to be found in the search where there is not an overlapping or adjacent different result.
   *  ('independently' also slightly changes sorting behavior in the same way.)
   */
  matchAllTokens: 'no' | 'once' | 'separately' | 'independently';
}
 
/**
 * Constructs a typeahead search and provides the matches as a signal.
 *
 * @param options - Factory function that should return the array of options to search in.
 * Is run in a reactive context.
 * @param query - Factory function that should return the current search query. Is run in a reactive context.
 * @param config - Configuration for the search. Is run in a reactive context.
 *
 * @example
 * In a real world, myOptions and mayQuery would be signals.
 * ```ts
 * const search = typeaheadSearch(
 *   () => myOptions().map(...),
 *   () => myQuery().toLowerCase(),
 *   () => ({ matchAllTokens: 'separately' })
 * )
 * ```
 */
export const typeaheadSearch = <T>(
  options: () => SearchOptions<T>[],
  query: () => string,
  config: () => SearchConfig
): Signal<Match<T>[]> => computed(() => new TypeaheadSearch<T>(options, query, config()).matches());
 
class TypeaheadSearch<T> {
  readonly matches = computed<Match<T>[]>(() => this.search(this.datasource(), this.query()));
 
  constructor(
    private readonly datasource: () => SearchOptions<T>[],
    private readonly query: () => string,
    private readonly options: SearchConfig
  ) {}
 
  private escapeRegex(query: string): string {
    return query.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  }
 
  private search(options: SearchOptions<T>[], query: string): Match<T>[] {
    try {
      const entireQueryRegex = new RegExp(this.escapeRegex(query), 'gi');
 
      const queryParts = !this.options.disableTokenizing
        ? query.split(/\s+/g).filter(queryPart => queryPart)
        : query
          ? [query]
          : [];
 
      const queryRegexes = queryParts.map(
        queryPart => new RegExp(this.escapeRegex(queryPart), 'gi')
      );
      // Process the options.
      const matches: Match<T>[] = [];
      options.forEach(option => {
        const optionValue = option.text;
        const stringMatch =
          optionValue.toLocaleLowerCase().trim() === query.toLocaleLowerCase().trim();
        const candidate: Match<T> = {
          option: option.option,
          text: optionValue,
          result: [],
          stringMatch,
          atBeginning: false,
          matches: 0,
          uniqueMatches: 0,
          uniqueSeparateMatches: 0,
          matchesEntireQuery: false,
          matchesAllParts: false,
          matchesAllPartsSeparately: false
        };
 
        // Only search the options if a part of the query is at least one character long to prevent an endless loop.
        if (queryParts.length === 0) {
          if (optionValue) {
            candidate.result.push({
              text: optionValue,
              isMatching: false,
              matches: 0,
              uniqueMatches: 0
            });
          }
          matches.push(candidate);
        } else {
          const allResults: { index: number; start: number; end: number; result: string }[] = [];
          const allIndexes: number[] = [];
 
          candidate.matchesEntireQuery = !!optionValue.match(entireQueryRegex);
 
          // Loop through the option value to find multiple matches, then store every segment (matching or non-matching) in the results.
          queryRegexes.forEach((queryRegex, index) => {
            let regexMatch = queryRegex.exec(optionValue);
 
            while (regexMatch) {
              allResults.push({
                index,
                start: regexMatch.index,
                end: regexMatch.index + regexMatch[0].length,
                result: regexMatch[0]
              });
              if (!regexMatch.index) {
                candidate.atBeginning = true;
              }
              if (!allIndexes.includes(index)) {
                allIndexes.push(index);
              }
              regexMatch = queryRegex.exec(optionValue);
            }
          });
 
          candidate.matchesAllParts = allIndexes.length === queryParts.length;
 
          // Check if all parts of the query match at least once (if required).
          if (this.options.matchAllTokens === 'no' || candidate.matchesAllParts) {
            const combinedResults: {
              indexes: number[];
              uniqueIndexes: number[];
              start: number;
              end: number;
              result: string;
            }[] = [];
 
            // First combine intersecting (or if set to independently adjacent) results to combined results.
            // We achieve this by first sorting them by the starting index, then by the ending index and then looking for overlaps.
            allResults
              .sort((a, b) => a.start - b.start || a.end - b.end)
              .forEach(result => {
                if (combinedResults.length) {
                  const foundPreviousResult = combinedResults.find(previousResult =>
                    this.options.matchAllTokens === 'independently'
                      ? result.start <= previousResult.end
                      : result.start < previousResult.end
                  );
                  if (foundPreviousResult) {
                    foundPreviousResult.result += result.result.slice(
                      foundPreviousResult.end - result.start,
                      result.result.length
                    );
                    if (result.end > foundPreviousResult.end) {
                      foundPreviousResult.end = result.end;
                    }
                    foundPreviousResult.indexes.push(result.index);
                    if (!foundPreviousResult.uniqueIndexes.includes(result.index)) {
                      foundPreviousResult.uniqueIndexes.push(result.index);
                    }
                    return;
                  }
                }
                combinedResults.push({
                  ...result,
                  indexes: [result.index],
                  uniqueIndexes: [result.index]
                });
              });
 
            // Recursively go through all unique combinations of the unique indexes to get the option which has the most indexes.
            const countUniqueSubindexes = (
              indexIndex = 0,
              previousIndexes: number[] = []
            ): number =>
              indexIndex === combinedResults.length
                ? previousIndexes.length
                : Math.max(
                    previousIndexes.length,
                    ...combinedResults[indexIndex].uniqueIndexes
                      .filter(index => !previousIndexes.includes(index))
                      .map(index =>
                        countUniqueSubindexes(indexIndex + 1, [index, ...previousIndexes])
                      )
                  );
 
            candidate.uniqueSeparateMatches = countUniqueSubindexes();
            candidate.matchesAllPartsSeparately =
              candidate.uniqueSeparateMatches === queryParts.length;
 
            let currentPreviousEnd = 0;
 
            // Add the combined results to the candidate including the non-matching parts in between.
            combinedResults.forEach(result => {
              const textBefore = optionValue.slice(currentPreviousEnd, result.start);
              if (textBefore) {
                candidate.result.push({
                  text: textBefore,
                  isMatching: false,
                  matches: 0,
                  uniqueMatches: 0
                });
              }
              candidate.result.push({
                text: result.result,
                isMatching: true,
                matches: result.indexes.length,
                uniqueMatches: result.uniqueIndexes.length
              });
              currentPreviousEnd = result.end;
              candidate.matches += result.indexes.length;
              candidate.uniqueMatches += result.uniqueIndexes.length;
            });
 
            // Check if there are result segments and all parts are matched independently (if required).
            if (
              candidate.result.length !== 0 &&
              ((this.options.matchAllTokens !== 'separately' &&
                this.options.matchAllTokens !== 'independently') ||
                candidate.matchesAllPartsSeparately)
            ) {
              const textAtEnd = optionValue.slice(currentPreviousEnd);
              if (textAtEnd) {
                candidate.result.push({
                  text: textAtEnd,
                  isMatching: false,
                  matches: 0,
                  uniqueMatches: 0
                });
              }
              matches.push(candidate);
            }
          }
        }
      });
 
      return matches;
    } catch {
      // Could not create regex (only in extremely rare cases, maybe even impossible), so return an empty array.
      return [];
    }
  }
}