refactor(news-keyword-search): refactor keyword highlighting to show tooltips
This commit is contained in:
+17
-2
@@ -72,9 +72,24 @@
|
||||
|
||||
<ng-template #snippetTmp let-article>
|
||||
<div class="snippet-detail">
|
||||
@if (snippetHtml().get(article.id); as snippet) {
|
||||
@if (snippetSegments().get(article.id); as segments) {
|
||||
<span class="snippet-label">Fundstelle im Artikel</span>
|
||||
<span class="snippet" [innerHTML]="snippet"></span>
|
||||
<p class="snippet">
|
||||
@for (segment of segments; track $index) {
|
||||
@if (segment.isSearchMatch) {
|
||||
<mark
|
||||
class="snippet-mark"
|
||||
[class.has-topic]="!!segment.color"
|
||||
[style.--t]="segment.color"
|
||||
[matTooltip]="segment.tooltip ?? ''"
|
||||
matTooltipPosition="above"
|
||||
>{{ segment.text }}</mark
|
||||
>
|
||||
} @else {
|
||||
<span>{{ segment.text }}</span>
|
||||
}
|
||||
}
|
||||
</p>
|
||||
} @else {
|
||||
<span class="empty-text">
|
||||
Für diesen Artikel liegt keine Textstelle zu den gesuchten Keywords
|
||||
|
||||
+16
-1
@@ -151,14 +151,29 @@
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* .kw-mark / .search-mark inside are styled globally in styles.scss. */
|
||||
.snippet {
|
||||
margin: 0;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--sg-text-secondary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.snippet-mark {
|
||||
background: transparent;
|
||||
color: var(--sg-blue-highlight);
|
||||
font-weight: 700;
|
||||
cursor: help;
|
||||
|
||||
&.has-topic {
|
||||
color: var(--t);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: var(--t);
|
||||
text-decoration-thickness: 2px;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.date-text {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
+50
-23
@@ -9,7 +9,6 @@ import {
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
|
||||
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
@@ -34,13 +33,20 @@ import { keywordsNewsQueryParamKeys } from '../../../../resolvers/keywords-news-
|
||||
import { SearchResultsStateService } from '../search-results-state.service';
|
||||
import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component';
|
||||
import {
|
||||
escapeHtml,
|
||||
highlightKeywords,
|
||||
keywordTooltip,
|
||||
splitByKeywords,
|
||||
topicKeywordColors,
|
||||
} from '../../../../resolvers/utils/keyword-highlight';
|
||||
|
||||
type NewsResult = NewsPage['results'][number];
|
||||
|
||||
interface SnippetSegment {
|
||||
text: string;
|
||||
color: string | null;
|
||||
tooltip: string | null;
|
||||
isSearchMatch: boolean;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-news-results',
|
||||
imports: [
|
||||
@@ -66,7 +72,6 @@ export class KeywordsToNewsResultsComponent {
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly sanitizer = inject(DomSanitizer);
|
||||
|
||||
newsPage = input.required<NewsPage>();
|
||||
|
||||
@@ -242,48 +247,70 @@ export class KeywordsToNewsResultsComponent {
|
||||
return this.dataTable()?.expandedElement() === article;
|
||||
}
|
||||
|
||||
readonly snippetHtml = computed(() => {
|
||||
const byArticleId = new Map<string, SafeHtml>();
|
||||
readonly snippetSegments = computed(() => {
|
||||
const byArticleId = new Map<string, SnippetSegment[]>();
|
||||
|
||||
for (const article of this.elements()) {
|
||||
const html = this.buildSnippetHtml(article);
|
||||
if (html !== null) {
|
||||
byArticleId.set(
|
||||
article.id,
|
||||
this.sanitizer.bypassSecurityTrustHtml(html),
|
||||
);
|
||||
const segments = this.buildSnippetSegments(article);
|
||||
if (segments.length) {
|
||||
byArticleId.set(article.id, segments);
|
||||
}
|
||||
}
|
||||
|
||||
return byArticleId;
|
||||
});
|
||||
|
||||
private buildSnippetHtml(article: NewsResult): string | null {
|
||||
private buildSnippetSegments(article: NewsResult): SnippetSegment[] {
|
||||
const snippet = article.snippet;
|
||||
if (!snippet) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
|
||||
const keywordColors = topicKeywordColors(article.topics);
|
||||
const searchMatch = /<em>([\s\S]*?)<\/em>/g;
|
||||
|
||||
let html = '';
|
||||
const segments: SnippetSegment[] = [];
|
||||
let lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
const pushPlain = (raw: string) => {
|
||||
const text = this.decodeHtml(raw);
|
||||
if (text) {
|
||||
segments.push({
|
||||
text,
|
||||
color: null,
|
||||
tooltip: null,
|
||||
isSearchMatch: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
while ((match = searchMatch.exec(snippet)) !== null) {
|
||||
html += escapeHtml(
|
||||
this.decodeHtml(snippet.slice(lastIndex, match.index)),
|
||||
);
|
||||
html += `<mark class="search-mark">${highlightKeywords(
|
||||
this.decodeHtml(match[1]),
|
||||
keywordColors,
|
||||
)}</mark>`;
|
||||
pushPlain(snippet.slice(lastIndex, match.index));
|
||||
|
||||
const term = this.decodeHtml(match[1]);
|
||||
const parts = splitByKeywords(term, keywordColors);
|
||||
const hasTopic = parts.some((part) => part.match);
|
||||
|
||||
for (const part of parts) {
|
||||
segments.push({
|
||||
text: part.text,
|
||||
color: part.match?.color ?? null,
|
||||
tooltip: part.match
|
||||
? keywordTooltip(part.match.keyword, part.match.topicNames)
|
||||
: hasTopic
|
||||
? null
|
||||
: keywordTooltip(term, []),
|
||||
isSearchMatch: true,
|
||||
});
|
||||
}
|
||||
|
||||
lastIndex = searchMatch.lastIndex;
|
||||
}
|
||||
|
||||
return html + escapeHtml(this.decodeHtml(snippet.slice(lastIndex)));
|
||||
pushPlain(snippet.slice(lastIndex));
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
private decodeHtml(value: string): string {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { MatchedTopic } from '../../api';
|
||||
import { topicHierarchyColor } from './topic-colors';
|
||||
|
||||
/** A keyword together with the colour of the topic it resolved to. */
|
||||
/** A keyword together with the colour and names of the topics it resolved to. */
|
||||
export interface KeywordColor {
|
||||
keyword: string;
|
||||
color: string;
|
||||
topicNames: string[];
|
||||
}
|
||||
|
||||
/** Pairs every keyword that resolved to a topic with that topic's colour. */
|
||||
@@ -12,22 +13,33 @@ export function topicKeywordColors(
|
||||
topics: readonly MatchedTopic[] | null | undefined,
|
||||
keywords?: readonly string[] | null,
|
||||
): KeywordColor[] {
|
||||
const colorByKeyword = new Map<string, string>();
|
||||
const byKeyword = new Map<string, Omit<KeywordColor, 'keyword'>>();
|
||||
|
||||
for (const topic of topics ?? []) {
|
||||
if (!topic.source_keyword) {
|
||||
continue;
|
||||
}
|
||||
|
||||
colorByKeyword.set(
|
||||
topic.source_keyword.toLowerCase(),
|
||||
topicHierarchyColor({
|
||||
const key = topic.source_keyword.toLowerCase();
|
||||
const topicName = topic.display_name?.trim();
|
||||
const existing = byKeyword.get(key);
|
||||
|
||||
if (existing) {
|
||||
if (topicName && !existing.topicNames.includes(topicName)) {
|
||||
existing.topicNames.push(topicName);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
byKeyword.set(key, {
|
||||
color: topicHierarchyColor({
|
||||
id: topic.id,
|
||||
name: topic.display_name,
|
||||
field_name: topic.field_name,
|
||||
domain_name: topic.domain_name,
|
||||
}),
|
||||
);
|
||||
topicNames: topicName ? [topicName] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const source =
|
||||
@@ -41,33 +53,52 @@ export function topicKeywordColors(
|
||||
|
||||
for (const keyword of source) {
|
||||
const key = keyword.toLowerCase();
|
||||
const color = colorByKeyword.get(key);
|
||||
if (!color || seen.has(key)) {
|
||||
const entry = byKeyword.get(key);
|
||||
if (!entry || seen.has(key)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(key);
|
||||
result.push({ keyword, color });
|
||||
result.push({ keyword, ...entry });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Explains, for a mark in the text, which topics its keyword is assigned to. */
|
||||
export function keywordTooltip(
|
||||
keyword: string,
|
||||
topicNames: readonly string[],
|
||||
): string {
|
||||
if (!topicNames.length) {
|
||||
return `„${keyword}“ ist keinem der aufgelisteten Themen zugeordnet.`;
|
||||
}
|
||||
|
||||
if (topicNames.length === 1) {
|
||||
return `„${keyword}“ ist dem Thema „${topicNames[0]}“ zugeordnet.`;
|
||||
}
|
||||
|
||||
const names = topicNames.map((name) => `„${name}“`).join(', ');
|
||||
return `„${keyword}“ ist den Themen ${names} zugeordnet.`;
|
||||
}
|
||||
|
||||
const WORD_CHAR = '[\\w\\u00C0-\\u024F]';
|
||||
|
||||
/**
|
||||
* Escapes `text` and wraps every occurrence of a keyword in a `<mark>` carrying
|
||||
* the keyword's topic colour in `--t`.
|
||||
*/
|
||||
export function highlightKeywords(
|
||||
export const KW_MARK_CLASS = 'kw-mark';
|
||||
|
||||
export interface KeywordSegment {
|
||||
text: string;
|
||||
match: KeywordColor | null;
|
||||
}
|
||||
export function splitByKeywords(
|
||||
text: string,
|
||||
keywordColors: readonly KeywordColor[],
|
||||
): string {
|
||||
): KeywordSegment[] {
|
||||
const sorted = [...keywordColors]
|
||||
.filter(({ keyword }) => keyword.trim())
|
||||
.sort((a, b) => b.keyword.length - a.keyword.length);
|
||||
|
||||
if (!sorted.length) {
|
||||
return escapeHtml(text);
|
||||
return text ? [{ text, match: null }] : [];
|
||||
}
|
||||
|
||||
// Acronyms are matched exactly, everything else may carry an inflection
|
||||
@@ -82,10 +113,16 @@ export function highlightKeywords(
|
||||
'gi',
|
||||
);
|
||||
|
||||
let html = '';
|
||||
const segments: KeywordSegment[] = [];
|
||||
let lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
const pushPlain = (value: string) => {
|
||||
if (value) {
|
||||
segments.push({ text: value, match: null });
|
||||
}
|
||||
};
|
||||
|
||||
while ((match = pattern.exec(text)) !== null) {
|
||||
const matched = match[0];
|
||||
const entry = sorted.find(({ keyword }) =>
|
||||
@@ -95,15 +132,38 @@ export function highlightKeywords(
|
||||
continue;
|
||||
}
|
||||
|
||||
html += escapeHtml(text.slice(lastIndex, match.index));
|
||||
html +=
|
||||
`<mark class="kw-mark" style="--t:${entry.color}"` +
|
||||
` data-kw="${escapeHtml(entry.keyword)}">${escapeHtml(matched)}</mark>`;
|
||||
pushPlain(text.slice(lastIndex, match.index));
|
||||
segments.push({ text: matched, match: entry });
|
||||
|
||||
lastIndex = match.index + matched.length;
|
||||
}
|
||||
|
||||
return html + escapeHtml(text.slice(lastIndex));
|
||||
pushPlain(text.slice(lastIndex));
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function highlightKeywords(
|
||||
text: string,
|
||||
keywordColors: readonly KeywordColor[],
|
||||
): string {
|
||||
return splitByKeywords(text, keywordColors)
|
||||
.map(({ text: value, match }) => {
|
||||
if (!match) {
|
||||
return escapeHtml(value);
|
||||
}
|
||||
|
||||
const tooltip = escapeHtml(
|
||||
keywordTooltip(match.keyword, match.topicNames),
|
||||
);
|
||||
|
||||
return (
|
||||
`<mark class="${KW_MARK_CLASS}" style="--t:${match.color}"` +
|
||||
` data-kw="${escapeHtml(match.keyword)}" title="${tooltip}">` +
|
||||
`${escapeHtml(value)}</mark>`
|
||||
);
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
|
||||
export function escapeHtml(text: string): string {
|
||||
|
||||
@@ -652,6 +652,7 @@ html.dark-theme {
|
||||
font-weight: inherit;
|
||||
border-radius: 2px;
|
||||
padding: 0 1px;
|
||||
cursor: help;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
@@ -662,9 +663,3 @@ html.dark-theme {
|
||||
animation: kw-flash 2.4s ease-out forwards;
|
||||
}
|
||||
}
|
||||
|
||||
.search-mark {
|
||||
background: transparent;
|
||||
color: var(--sg-blue-highlight);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user