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

99% Statements 199/201
94.44% Branches 34/36
100% Functions 13/13
99% Lines 199/201

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 2021x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 948x 948x 948x 1x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 1x 1896x 1896x 948x 948x 948x 1896x 1896x 1x 1x 1x 1x 64x 64x 64x 1x 1x 1448x 1448x 1x 1x 128x 128x 128x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47786x 47786x 47786x 1x 1x 1x 1x 1x 1x 1x 1x 3405x     3405x 3405x 1x 1x 1x 1056x 1056x 1x 1x 1x 3405x 1448x 1448x 3405x 3405x 1x 1x 1x 4412x 4412x 864x 37x 4375x 4375x 4412x 4412x 1x 1x 1x 1953x 1953x 1x 1x 1x 5823x 5823x 5823x 5823x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 948x 51x 51x 332x 332x 331x 332x 332x 948x 948x 948x 897x 948x 948x 948x 948x 5823x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  AfterContentInit,
  Component,
  EventEmitter,
  HostBinding,
  Injectable,
  Input,
  OnChanges,
  OnDestroy,
  Optional,
  SimpleChanges,
} from '@angular/core';
import { Subscription } from 'rxjs';
 
// 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';
 
/**
 * Highlight substrings within a text.
 */
@Component({
  selector: 'gc-text-highlight',
  templateUrl: './text-highlight.component.html',
  styleUrls: ['./text-highlight.component.css'],
  standalone: false,
})
export class TextHighlightComponent
  implements AfterContentInit, OnChanges, OnDestroy
{
  /**
   * The text to display.
   */
  @Input()
  public text?: string;
 
  /**
   * Optional substring to highlight within the displayed text.
   */
  @Input()
  public highlight?: string;
 
  /**
   * If `true`, the highlight is only shown if it's a prefix of the displayed text. Otherwise, all
   * occurrences of the highlight are marked.
   */
  @Input()
  public prefixOnly = false;
 
  /**
   * List of patterns supported by the highlighting
   * - asterisk: `*` in highlight means any number of character
   * - question-mark: `?` in highlight means one character
   */
  @Input()
  public supportedPatterns: Patterns[] = ['asterisk', 'question-mark'];
 
  /**
   * Display variant of the marked highlights.
   */
  @Input()
  public variant: 'default' | 'inverted' | 'reduced' = 'default';
 
  /** @ignore */
  @HostBinding('class')
  private get cssClass(): string {
    return `gc-text-highlight-variant-${this.variant}`;
  }
 
  /** @ignore */
  public _highlightParts: TextHighlightPart[] = [];
 
  /** @ignore */
  private readonly highlightStringChangeSubscription?: Subscription;
 
  constructor(@Optional() private service: TextHighlightService | null) {
    service?.highlightStringChange.subscribe(val => {
      this.highlight = val;
      this.calculateHighlightParts(); // direct setting does not trigger Angular change detection, update thus invoked manually
    });
  }
 
  /** @ignore */
  public ngOnDestroy(): void {
    this.highlightStringChangeSubscription?.unsubscribe();
  }
 
  /** @ignore */
  public ngAfterContentInit(): void {
    if (this.service) {
      this.highlight = this.service.highlightString;
      this.calculateHighlightParts();
    }
  }
 
  /** @ignore */
  public ngOnChanges(changes: SimpleChanges): void {
    if (
      'text' in changes ||
      'highlight' in changes ||
      'prefixOnly' in changes
    ) {
      this.calculateHighlightParts();
    }
  }
 
  /** @ignore */
  public _partTrackBy(index: number, part: TextHighlightPart): string {
    return `${index.toString()}_${part.mark ? 't' : 'f'}_${part.text}`;
  }
 
  /** @ignore */
  private calculateHighlightParts(): void {
    if (!this.text) {
      this._highlightParts = [];
    } else if (!this.highlight) {
      this._highlightParts = [{ text: this.text }];
    } else {
      const regex = createRegex(
        this.highlight,
        this.prefixOnly,
        this.supportedPatterns,
      );
      const parts: TextHighlightPart[] = [];
 
      // 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)
      let lastMatchEnd = 0;
      for (const match of this.text.matchAll(regex)) {
        if (match.index - lastMatchEnd > 0) {
          // store text between the previous match and the current one as unmarked part
          parts.push({ text: this.text.substring(lastMatchEnd, match.index) });
        }
        if (match[0].length > 0) {
          parts.push({ text: match[0], mark: true });
        }
        lastMatchEnd = match.index + match[0].length;
      }
      // store text following after the last match
      if (lastMatchEnd < this.text.length) {
        parts.push({ text: this.text.substring(lastMatchEnd) });
      }
 
      this._highlightParts = parts;
    }
  }
}