import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; // Interfaces import { ISearchQueryItem } from '../components/ca-search-multiple-states-2/interfaces'; @Pipe({ name: 'tableHighlightSearchText', }) export class TableHighlightSearchTextPipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform( text: string | number | null | undefined, chips: ISearchQueryItem[] ): SafeHtml { // convert to string and handle null/undefined const textString = String(text ?? ''); if (!textString) { return '' as unknown as SafeHtml; } if (!chips?.length) return textString as unknown as SafeHtml; let highlighted = textString; // Apply all chips cumulatively so earlier matches are preserved chips.forEach((chip) => { if (!chip || !chip.text) return; // Escape regex special characters let pattern = chip.text.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); pattern = pattern .split(' ') .filter((_pattern) => !!_pattern.length) .join('|'); if (!pattern) return; const regex = new RegExp('(' + pattern + ')(?!([^<]+)?>)', 'gi'); // Get colorClass from chip const colorClass = chip.colorClass || ''; highlighted = highlighted.replace( regex, (match) => `${match}` ); }); return this.sanitizer.bypassSecurityTrustHtml(highlighted); } }