All files / lib/internal/text-highlight text-highlight.component.ts

96.26% Statements 206/214
97.05% Branches 33/34
92.85% Functions 13/14
96.26% Lines 206/214

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 2151x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 500x 500x 500x 1x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 1x 1000x 1000x 500x 500x 500x 1000x 1000x 1x 1x 1x 1x       1x 1x 1489x 1489x 1x 1x 131x 131x 131x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 500x 500x 500x 500x 500x 500x 500x 500x 26x 26x 26x 26x 242x 242x 241x 242x 242x 500x 500x 500x 461x 500x 500x 500x 1x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 500x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 85521x 85521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5116x 1489x 1489x   1489x 1489x 1489x 588x 1489x 1489x 5116x 1x 1x 1x 875x 875x 1x 1x 1x 5603x 5603x 5603x 5603x 5603x 5603x 5603x         500x 500x 500x 500x 500x 5603x 5603x 5603x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  Component,
  DestroyRef,
  EventEmitter,
  Injectable,
  Optional,
  computed,
  inject,
  input,
  signal,
} from '@angular/core';
 
import { TextRange } from '../../utils/util.types';
 
// Defined in MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
function escapeRegExp(expression: string) {
  return expression.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
 
function createRegex(
  search: string,
  prefixOnly: boolean,
  patterns: Patterns[],
): RegExp {
  const out = escapeRegExp(search);
  let regex = prefixOnly ? '^' + out : out;
  for (const pattern of patterns) {
    regex = escapePattern(regex, pattern);
  }
  return new RegExp(regex, 'gi');
}
 
function escapePattern(regex: string, pattern: Patterns) {
  if (pattern === 'asterisk') {
    return regex.replaceAll('\\*', '.*');
  } else {
    return regex.replaceAll('\\?', '.');
  }
}
 
@Injectable()
export class TextHighlightService {
  public set highlightString(val: string | undefined) {
    this._highlightString = val;
    this.highlightStringChange.emit(val);
  }
 
  public get highlightString(): string | undefined {
    return this._highlightString;
  }
 
  public readonly highlightStringChange: EventEmitter<string | undefined> =
    new EventEmitter<string | undefined>();
 
  private _highlightString?: string;
}
 
interface TextHighlightPart {
  text: string;
  mark?: boolean;
}
 
export type Patterns = 'asterisk' | 'question-mark';
 
/**
 *
 * @param text
 * @param range text range - assumed to be sorted in order of start indices
 * @returns
 */
function computeRangeHighlights(
  text: string,
  range: TextRange[],
): TextHighlightPart[] {
  const parts: TextHighlightPart[] = [];
  let lastPartEnd = 0;
  for (const [start, end] of range) {
    if (start - lastPartEnd > 0) {
      // store text between the previous part and the current one as unmarked part
      parts.push({
        text: text.substring(lastPartEnd, start),
      });
    }
    if (end - start > 0) {
      parts.push({ text: text.substring(start, end), mark: true });
    }
    lastPartEnd = end;
  }
  // store text following after the last part
  if (lastPartEnd < text.length) {
    parts.push({ text: text.substring(lastPartEnd) });
  }
  return parts;
}
 
function computeRegexHighlights(
  text: string,
  highlight: string,
  prefixOnly: boolean,
  supportedPatterns: Patterns[],
): TextHighlightPart[] {
  const regex = createRegex(highlight, prefixOnly, supportedPatterns);
  const ranges: TextRange[] = [];
 
  // using String.matchAll instead of RegExp.exec, as looping over exec gets stuck at the end when using the regex ".*"
  // matchAll doesn't have this problem as it returns an iterator and can be used as direct replacement otherwise
  // see also:
  // - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#finding_successive_matches ("pitfalls [...] match zero-length characters")
  // - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll#regexp.prototype.exec_and_matchall)
  for (const match of text.matchAll(regex)) {
    ranges.push([match.index, match.index + match[0].length]);
  }
  return computeRangeHighlights(text, ranges);
}
 
/**
 * Highlight substrings within a text.
 */
@Component({
  selector: 'gc-text-highlight',
  templateUrl: './text-highlight.component.html',
  styleUrls: ['./text-highlight.component.css'],
  standalone: false,
  host: {
    '[class]': '"gc-text-highlight-variant-" + this.variant()',
  },
})
export class TextHighlightComponent {
  /**
   * The text to display.
   */
  public readonly text = input.required<string>();
 
  /**
   * Optional substring to highlight within the displayed text.
   */
  public readonly highlight = input<string | TextRange[]>();
 
  /**
   * If `true`, the highlight is only shown if it's a prefix of the displayed text. Otherwise, all
   * occurrences of the highlight are marked.
   */
  public readonly prefixOnly = input<boolean>(false);
 
  /**
   * List of patterns supported by the highlighting
   * - asterisk: `*` in highlight means any number of character
   * - question-mark: `?` in highlight means one character
   */
  public readonly supportedPatterns = input<Patterns[]>([
    'asterisk',
    'question-mark',
  ]);
 
  /**
   * Display variant of the marked highlights.
   */
  public readonly variant = input<'default' | 'inverted' | 'reduced'>(
    'default',
  );
 
  /** @ignore */
  protected readonly highlightParts = computed<TextHighlightPart[]>(() =>
    this.calculateHighlightParts(),
  );
 
  /** @ignore */
  private readonly serviceHighlight = signal<string | undefined>(undefined);
 
  constructor(@Optional() private service: TextHighlightService | null) {
    if (service) {
      // https://v19.angular.dev/api/core/rxjs-interop/toSignal is in dev-preview
      const subscription = service.highlightStringChange.subscribe(val => {
        this.serviceHighlight.set(val);
      });
      this.serviceHighlight.set(service.highlightString);
      inject(DestroyRef).onDestroy(() => {
        subscription.unsubscribe();
      });
    }
  }
 
  /** @ignore */
  public _partTrackBy(index: number, part: TextHighlightPart): string {
    return `${index.toString()}_${part.mark ? 't' : 'f'}_${part.text}`;
  }
 
  /** @ignore */
  private calculateHighlightParts(): TextHighlightPart[] {
    const highlight = this.highlight() ?? this.serviceHighlight();
    const text = this.text();
    if (!text) {
      return [];
    } else if (!highlight) {
      return [{ text }];
    } else if (Array.isArray(highlight)) {
      const sortedRanges = [...highlight];
      sortedRanges.sort((a, b) => a[0] - b[0]);
      return computeRangeHighlights(text, sortedRanges);
    } else {
      return computeRegexHighlights(
        text,
        highlight,
        this.prefixOnly(),
        this.supportedPatterns(),
      );
    }
  }
}