All files / app/assets/javascripts/lib/utils highlight.js

100% Statements 10/10
100% Branches 9/9
100% Functions 2/2
100% Lines 10/10

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                                    192x 2x     190x 173x     17x       17x   17x     157x 9x     148x        
import fuzzaldrinPlus from 'fuzzaldrin-plus';
import { sanitize } from '~/lib/dompurify';
 
/**
 * Wraps substring matches with HTML `<span>` elements.
 * Inputs are sanitized before highlighting, so this
 * filter is safe to use with `v-html` (as long as `matchPrefix`
 * and `matchSuffix` are not being dynamically generated).
 *
 * Note that this function can't be used inside `v-html` as a filter
 * (Vue filters cannot be used inside `v-html`).
 *
 * @param {String} string The string to highlight
 * @param {String} match The substring match to highlight in the string
 * @param {String} matchPrefix The string to insert at the beginning of a match
 * @param {String} matchSuffix The string to insert at the end of a match
 */
export default function highlight(string, match = '', matchPrefix = '<b>', matchSuffix = '</b>') {
  if (!string) {
    return '';
  }
 
  if (!match) {
    return string;
  }
 
  const sanitizedValue = sanitize(string.toString(), { ALLOWED_TAGS: [] });
 
  // occurrences is an array of character indices that should be
  // highlighted in the original string, i.e. [3, 4, 5, 7]
  const occurrences = fuzzaldrinPlus.match(sanitizedValue, match.toString());
 
  return sanitizedValue
    .split('')
    .map((character, i) => {
      if (occurrences.includes(i)) {
        return `${matchPrefix}${character}${matchSuffix}`;
      }
 
      return character;
    })
    .join('');
}