diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html
index fa8728fe..c9c04f61 100644
--- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html
+++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html
@@ -39,13 +39,62 @@
}
+
+ @if (article.snippet) {
+ @let expanded = isSnippetExpanded(article);
+
+ }
+
+
+
+
+
+
+ @if (snippetSegments().get(article.id); as segments) {
+
Fundstelle im Artikel
+
+ @for (segment of segments; track $index) {
+ @if (segment.isSearchMatch) {
+ {{ segment.text }}
+ } @else {
+ {{ segment.text }}
+ }
+ }
+
+ } @else {
+
+ Für diesen Artikel liegt keine Textstelle zu den gesuchten Keywords
+ vor.
+
}
@@ -86,7 +135,10 @@
@let visibleTopics =
topicsExpanded ? topics : topics.slice(0, topicPreviewCount);
-
+
@for (topic of visibleTopics; track topic.id ?? topic.display_name) {
+ matTooltip="Details anzeigen"
+ (click)="$event.stopPropagation()">
open_in_new
@@ -141,7 +194,10 @@
} @else {
0 || this.selectedTopicIds().length > 0;
});
+ expandTmp = viewChild.required>('expandTmp');
titleTmp = viewChild.required>('titleTmp');
dateTmp = viewChild.required>('dateTmp');
relevanceTmp = viewChild.required>('relevanceTmp');
topicsTmp = viewChild.required>('topicsTmp');
actionsTmp = viewChild.required>('actionsTmp');
+ private readonly dataTable = viewChild(DataTableComponent);
+
readonly columns = computed[]>(() => [
+ {
+ id: 'expand',
+ header: '',
+ type: 'display',
+ cellTemplate: this.expandTmp(),
+ },
{
id: 'maintitle',
header: 'Titel',
@@ -222,6 +243,85 @@ export class KeywordsToNewsResultsComponent {
return !!topic.id && this.selectedTopicIds().includes(topic.id);
}
+ isSnippetExpanded(article: NewsResult): boolean {
+ return this.dataTable()?.expandedElement() === article;
+ }
+
+ readonly snippetSegments = computed(() => {
+ const byArticleId = new Map();
+
+ for (const article of this.elements()) {
+ const segments = this.buildSnippetSegments(article);
+ if (segments.length) {
+ byArticleId.set(article.id, segments);
+ }
+ }
+
+ return byArticleId;
+ });
+
+ private buildSnippetSegments(article: NewsResult): SnippetSegment[] {
+ const snippet = article.snippet;
+ if (!snippet) {
+ return [];
+ }
+
+ const keywordColors = topicKeywordColors(article.topics);
+ const searchMatch = /([\s\S]*?)<\/em>/g;
+
+ 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) {
+ 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;
+ }
+
+ pushPlain(snippet.slice(lastIndex));
+
+ return segments;
+ }
+
+ private decodeHtml(value: string): string {
+ return value
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/"/g, '"')
+ .replace(/(?:39|x27);/g, "'")
+ .replace(/&/g, '&');
+ }
+
isTopicsExpanded(article: NewsResult): boolean {
return this.expandedTopicsIds().has(article.id);
}
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss
index 1d31ab79..4b091f89 100644
--- a/webapp/src/app/modules/news-detail/news-detail.component.scss
+++ b/webapp/src/app/modules/news-detail/news-detail.component.scss
@@ -587,8 +587,6 @@ main {
--topic-color: var(--sg-error);
}
-// ── Keyword highlights in article text ───────────────────────────────────────
-
@keyframes kw-flash {
0% {
background: color-mix(in srgb, var(--t) 45%, var(--sg-color-mix-base));
@@ -612,6 +610,7 @@ main {
font-weight: inherit;
border-radius: 2px;
padding: 0 1px;
+ cursor: help;
transition: background 0.15s;
&:hover {
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts
index fdbb74f9..039c7feb 100644
--- a/webapp/src/app/modules/news-detail/news-detail.component.ts
+++ b/webapp/src/app/modules/news-detail/news-detail.component.ts
@@ -16,6 +16,10 @@ import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { WorksService } from '../../api';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
+import {
+ highlightKeywords,
+ topicKeywordColors,
+} from '../../resolvers/utils/keyword-highlight';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
interface MentionedPerson {
@@ -187,53 +191,12 @@ export class NewsDetailComponent implements OnInit {
private buildHighlightedContent(article: NewsArticleDetail): SafeHtml {
const text = article.full_content;
if (!text) return this.sanitizer.bypassSecurityTrustHtml('');
- const keywords = article.keywords ?? [];
- const keywordColorMap = new Map();
- for (const topic of article.topics ?? []) {
- if (topic.source_keyword) {
- keywordColorMap.set(
- topic.source_keyword.toLowerCase(),
- this.getTopicColor(topic),
- );
- }
- }
-
- let html = this.escapeHtml(text);
- [...keywords]
- .sort((a, b) => b.length - a.length)
- .forEach((kw) => {
- const color = keywordColorMap.get(kw.toLowerCase());
- if (!color) return;
- const kwHtml = this.escapeHtml(kw);
- const escaped = this.escapeRegex(kwHtml);
- const before = '(?$1`,
- );
- });
- return this.sanitizer.bypassSecurityTrustHtml(html);
- }
-
- private escapeHtml(text: string): string {
- return text
- .replace(/&/g, '&')
- .replace(//g, '>')
- .replace(/"/g, '"');
- }
-
- private escapeRegex(text: string): string {
- return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return this.sanitizer.bypassSecurityTrustHtml(
+ highlightKeywords(
+ text,
+ topicKeywordColors(article.topics, article.keywords),
+ ),
+ );
}
}
diff --git a/webapp/src/app/resolvers/utils/keyword-highlight.ts b/webapp/src/app/resolvers/utils/keyword-highlight.ts
new file mode 100644
index 00000000..b22ec493
--- /dev/null
+++ b/webapp/src/app/resolvers/utils/keyword-highlight.ts
@@ -0,0 +1,186 @@
+import { MatchedTopic } from '../../api';
+import { topicHierarchyColor } from './topic-colors';
+
+/** 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. */
+export function topicKeywordColors(
+ topics: readonly MatchedTopic[] | null | undefined,
+ keywords?: readonly string[] | null,
+): KeywordColor[] {
+ const byKeyword = new Map>();
+
+ for (const topic of topics ?? []) {
+ if (!topic.source_keyword) {
+ continue;
+ }
+
+ 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 =
+ keywords ??
+ (topics ?? [])
+ .map((topic) => topic.source_keyword)
+ .filter((keyword): keyword is string => !!keyword);
+
+ const seen = new Set();
+ const result: KeywordColor[] = [];
+
+ for (const keyword of source) {
+ const key = keyword.toLowerCase();
+ const entry = byKeyword.get(key);
+ if (!entry || seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ 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]';
+
+export const KW_MARK_CLASS = 'kw-mark';
+
+export interface KeywordSegment {
+ text: string;
+ match: KeywordColor | null;
+}
+export function splitByKeywords(
+ text: string,
+ keywordColors: readonly KeywordColor[],
+): KeywordSegment[] {
+ const sorted = [...keywordColors]
+ .filter(({ keyword }) => keyword.trim())
+ .sort((a, b) => b.keyword.length - a.keyword.length);
+
+ if (!sorted.length) {
+ return text ? [{ text, match: null }] : [];
+ }
+
+ // Acronyms are matched exactly, everything else may carry an inflection
+ // ("Gründung" also marks "Gründungen").
+ const alternatives = sorted.map(({ keyword }) =>
+ isAcronymLike(keyword)
+ ? `${escapeRegex(keyword)}(?!${WORD_CHAR})`
+ : `${escapeRegex(keyword)}${WORD_CHAR}*`,
+ );
+ const pattern = new RegExp(
+ `(? {
+ if (value) {
+ segments.push({ text: value, match: null });
+ }
+ };
+
+ while ((match = pattern.exec(text)) !== null) {
+ const matched = match[0];
+ const entry = sorted.find(({ keyword }) =>
+ matched.toLowerCase().startsWith(keyword.toLowerCase()),
+ );
+ if (!entry) {
+ continue;
+ }
+
+ pushPlain(text.slice(lastIndex, match.index));
+ segments.push({ text: matched, match: entry });
+
+ lastIndex = match.index + matched.length;
+ }
+
+ 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 (
+ `` +
+ `${escapeHtml(value)}`
+ );
+ })
+ .join('');
+}
+
+export function escapeHtml(text: string): string {
+ return text
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"');
+}
+
+function escapeRegex(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function isAcronymLike(keyword: string): boolean {
+ return (
+ keyword.length <= 3 ||
+ (keyword === keyword.toUpperCase() && keyword !== keyword.toLowerCase())
+ );
+}