Files
smartguide/webapp/src/app/shared/ui/highlighted-text/highlighted-text.component.ts
T

130 lines
4.1 KiB
TypeScript

import { Component, computed, inject, input } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import { TopicHierarchyColorInput } from '../../../resolvers/utils/topic-colors';
export interface HighlightTerm {
/** Literal text to search for and wrap in a <mark>. */
term: string;
/** Colors this term via topicHierarchyColor. Omit for a plain highlight. */
topic?: TopicHierarchyColorInput | null;
}
@Component({
selector: 'app-highlighted-text',
standalone: true,
template: '',
host: {
'[innerHTML]': 'highlightedHtml()',
},
styles: [':host { display: block; }'],
})
export class HighlightedTextComponent {
private readonly sanitizer = inject(DomSanitizer);
content = input<string | null | undefined>('');
highlights = input<HighlightTerm[]>([]);
protected readonly highlightedHtml = computed<SafeHtml>(() => {
const text = this.content();
if (!text) return this.sanitizer.bypassSecurityTrustHtml('');
return this.sanitizer.bypassSecurityTrustHtml(
this.buildHtml(text, this.highlights()),
);
});
private buildHtml(text: string, highlights: HighlightTerm[]): string {
const escapedText = this.escapeHtml(text);
const terms = this.dedupeAndSortTerms(highlights);
if (!terms.length) return escapedText;
const regex = this.buildMatchRegex(terms);
// Single combined pass: scans the original text once and never
// re-scans already-inserted <mark> markup, so a short term can't
// accidentally match inside a previously-injected style/data attribute.
return escapedText.replace(regex, (matched) => {
const origin = this.findOriginTerm(matched, terms);
if (!origin) return matched;
const dataKw = this.escapeHtml(origin.term);
if (!origin.topic) {
return `<mark class="app-highlight-mark" data-kw="${dataKw}">${matched}</mark>`;
}
const color = topicHierarchyColor({
id: origin.topic.id,
name: origin.topic.name,
field_id: origin.topic.field_id,
field_name: origin.topic.field_name,
domain_id: origin.topic.domain_id,
domain_name: origin.topic.domain_name,
});
return `<mark class="app-highlight-mark app-highlight-mark--topic" style="--t:${color}" data-kw="${dataKw}">${matched}</mark>`;
});
}
/** Dedupes by term (case-insensitive, first occurrence wins), longest-first. */
private dedupeAndSortTerms(highlights: HighlightTerm[]): HighlightTerm[] {
const byKey = new Map<string, HighlightTerm>();
for (const highlight of highlights) {
const term = highlight?.term?.trim();
if (!term) continue;
const key = term.toLowerCase();
if (!byKey.has(key)) {
byKey.set(key, { ...highlight, term });
}
}
return Array.from(byKey.values()).sort(
(a, b) => b.term.length - a.term.length,
);
}
/**
* Short/acronym-like terms (<=3 chars, or ALL CAPS) match exactly.
* Longer terms also swallow a trailing suffix (plural/case endings).
*/
private buildMatchRegex(terms: HighlightTerm[]): RegExp {
const before = '(?<![\\w\\u00C0-\\u024F])';
const alternatives = terms.map(({ term }) => {
const escaped = this.escapeRegex(this.escapeHtml(term));
const acronymLike =
term.length <= 3 ||
(term === term.toUpperCase() && term !== term.toLowerCase());
return acronymLike
? `${escaped}(?![\\w\\u00C0-\\u024F])`
: `${escaped}[\\w\\u00C0-\\u024F]*`;
});
return new RegExp(`${before}(?:${alternatives.join('|')})`, 'gi');
}
private findOriginTerm(
matched: string,
terms: HighlightTerm[],
): HighlightTerm | undefined {
const matchedLower = matched.toLowerCase();
return terms.find(({ term }) =>
matchedLower.startsWith(term.toLowerCase()),
);
}
private escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
private escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
}