feat(news-keyword-search): expand rows to show article excerpt and highlight keyword in topic color.

This commit is contained in:
2026-08-15 20:49:41 +02:00
parent 0ec47e42e4
commit e37f636236
7 changed files with 338 additions and 98 deletions
@@ -39,13 +39,47 @@
}
</div>
<ng-template #expandTmp let-article>
@if (article.snippet) {
@let expanded = isSnippetExpanded(article);
<button
mat-icon-button
class="expand-toggle"
[attr.aria-expanded]="expanded"
[matTooltip]="
expanded ? 'Textstelle ausblenden' : 'Textstelle anzeigen'
"
[attr.aria-label]="
expanded ? 'Textstelle ausblenden' : 'Textstelle anzeigen'
">
<mat-icon class="expand-icon" [class.is-expanded]="expanded">
expand_more
</mat-icon>
</button>
}
</ng-template>
<ng-template #titleTmp let-article>
<div class="title-cell">
<a class="title" [routerLink]="['/news', article.id]">
<a
class="title"
[routerLink]="['/news', article.id]"
(click)="$event.stopPropagation()">
{{ article.maintitle || 'Kein Titel' }}
</a>
@if (article.snippet) {
<span class="snippet" [innerHTML]="article.snippet"></span>
</div>
</ng-template>
<ng-template #snippetTmp let-article>
<div class="snippet-detail">
@if (snippetHtml().get(article.id); as snippet) {
<span class="snippet-label">Fundstelle im Artikel</span>
<span class="snippet" [innerHTML]="snippet"></span>
} @else {
<span class="empty-text">
Für diesen Artikel liegt keine Textstelle zu den gesuchten Keywords
vor.
</span>
}
</div>
</ng-template>
@@ -86,7 +120,10 @@
@let visibleTopics =
topicsExpanded ? topics : topics.slice(0, topicPreviewCount);
<div class="topic-chips" aria-label="Themen">
<div
class="topic-chips"
aria-label="Themen"
(click)="$event.stopPropagation()">
@for (topic of visibleTopics; track topic.id ?? topic.display_name) {
<app-topic-chip-2
size="mini"
@@ -113,7 +150,8 @@
mat-icon-button
color="primary"
[routerLink]="['/news', article.id]"
matTooltip="Details anzeigen">
matTooltip="Details anzeigen"
(click)="$event.stopPropagation()">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@@ -141,7 +179,10 @@
</div>
} @else {
<div class="table-wrap">
<app-data-table [columns]="columns()" [data]="elements()" />
<app-data-table
[columns]="columns()"
[data]="elements()"
[detailTemplate]="snippetTmp" />
</div>
<app-query-param-paginator
@@ -54,8 +54,7 @@
::ng-deep .table-wrap table {
width: 100%;
min-width: 960px;
border-collapse: separate;
border-spacing: 0 10px;
border-collapse: collapse;
box-shadow: none;
background: transparent;
}
@@ -86,6 +85,16 @@
.mat-column-topics {
overflow: visible;
}
.mat-column-expand {
width: 48px;
padding-right: 0;
}
.detail-row .mat-mdc-cell {
padding: 0;
border-bottom: none;
}
}
/* ============================================================
@@ -114,17 +123,40 @@
}
}
.expand-icon {
color: var(--sg-text-muted);
transition: transform 150ms ease-in-out;
&.is-expanded {
transform: rotate(180deg);
}
}
/* ============================================================
EXPANDED DETAIL ROW
============================================================ */
.snippet-detail {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.875rem 1rem 1rem 3rem;
background: var(--sg-surface-soft);
}
.snippet-label {
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
}
/* .kw-mark / .search-mark inside are styled globally in styles.scss. */
.snippet {
font-size: 12.5px;
line-height: 1.5;
line-height: 1.6;
color: var(--sg-text-secondary);
overflow-wrap: anywhere;
::ng-deep em {
font-style: normal;
font-weight: 700;
color: var(--sg-blue-highlight);
}
}
.date-text {
@@ -9,6 +9,7 @@ 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';
@@ -32,6 +33,11 @@ import { NEWS_MIN_YEAR } from '../../../../shared/ui/news-card/news-card.compone
import { keywordsNewsQueryParamKeys } from '../../../../resolvers/keywords-news-page.resolver';
import { SearchResultsStateService } from '../search-results-state.service';
import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component';
import {
escapeHtml,
highlightKeywords,
topicKeywordColors,
} from '../../../../resolvers/utils/keyword-highlight';
type NewsResult = NewsPage['results'][number];
@@ -60,6 +66,7 @@ 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>();
@@ -136,13 +143,22 @@ export class KeywordsToNewsResultsComponent {
return baseTopicIds.length > 0 || this.selectedTopicIds().length > 0;
});
expandTmp = viewChild.required<TemplateRef<any>>('expandTmp');
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
dateTmp = viewChild.required<TemplateRef<any>>('dateTmp');
relevanceTmp = viewChild.required<TemplateRef<any>>('relevanceTmp');
topicsTmp = viewChild.required<TemplateRef<any>>('topicsTmp');
actionsTmp = viewChild.required<TemplateRef<any>>('actionsTmp');
private readonly dataTable = viewChild(DataTableComponent);
readonly columns = computed<GenericColumn<NewsResult>[]>(() => [
{
id: 'expand',
header: '',
type: 'display',
cellTemplate: this.expandTmp(),
},
{
id: 'maintitle',
header: 'Titel',
@@ -222,6 +238,63 @@ export class KeywordsToNewsResultsComponent {
return !!topic.id && this.selectedTopicIds().includes(topic.id);
}
isSnippetExpanded(article: NewsResult): boolean {
return this.dataTable()?.expandedElement() === article;
}
readonly snippetHtml = computed(() => {
const byArticleId = new Map<string, SafeHtml>();
for (const article of this.elements()) {
const html = this.buildSnippetHtml(article);
if (html !== null) {
byArticleId.set(
article.id,
this.sanitizer.bypassSecurityTrustHtml(html),
);
}
}
return byArticleId;
});
private buildSnippetHtml(article: NewsResult): string | null {
const snippet = article.snippet;
if (!snippet) {
return null;
}
const keywordColors = topicKeywordColors(article.topics);
const searchMatch = /<em>([\s\S]*?)<\/em>/g;
let html = '';
let lastIndex = 0;
let match: RegExpExecArray | null;
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>`;
lastIndex = searchMatch.lastIndex;
}
return html + escapeHtml(this.decodeHtml(snippet.slice(lastIndex)));
}
private decodeHtml(value: string): string {
return value
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#(?:39|x27);/g, "'")
.replace(/&amp;/g, '&');
}
isTopicsExpanded(article: NewsResult): boolean {
return this.expandedTopicsIds().has(article.id);
}
@@ -586,39 +586,3 @@ main {
--topic-bg: color-mix(in srgb, var(--sg-error) 8%, var(--sg-color-mix-base));
--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));
}
40% {
background: color-mix(in srgb, var(--t) 45%, var(--sg-color-mix-base));
}
100% {
background: transparent;
}
}
:host ::ng-deep .kw-mark {
background: transparent;
color: var(--t);
text-decoration: underline;
text-decoration-color: var(--t);
text-decoration-style: solid;
text-decoration-thickness: 2px;
text-underline-offset: 2px;
font-weight: inherit;
border-radius: 2px;
padding: 0 1px;
transition: background 0.15s;
&:hover {
background: color-mix(in srgb, var(--t) 15%, var(--sg-color-mix-base));
}
&.kw-flash {
animation: kw-flash 2.4s ease-out forwards;
}
}
@@ -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<string, string>();
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 = '(?<![\\w\\u00C0-\\u024F])';
const acronymLike =
kw.length <= 3 ||
(kw === kw.toUpperCase() && kw !== kw.toLowerCase());
const re = new RegExp(
acronymLike
? `${before}(${escaped})(?![\\w\\u00C0-\\u024F])`
: `${before}(${escaped}[\\w\\u00C0-\\u024F]*)`,
'gi',
);
html = html.replace(
re,
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
);
});
return this.sanitizer.bypassSecurityTrustHtml(html);
}
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, '\\$&');
return this.sanitizer.bypassSecurityTrustHtml(
highlightKeywords(
text,
topicKeywordColors(article.topics, article.keywords),
),
);
}
}
@@ -0,0 +1,126 @@
import { MatchedTopic } from '../../api';
import { topicHierarchyColor } from './topic-colors';
/** A keyword together with the colour of the topic it resolved to. */
export interface KeywordColor {
keyword: string;
color: 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 colorByKeyword = new Map<string, string>();
for (const topic of topics ?? []) {
if (!topic.source_keyword) {
continue;
}
colorByKeyword.set(
topic.source_keyword.toLowerCase(),
topicHierarchyColor({
id: topic.id,
name: topic.display_name,
field_name: topic.field_name,
domain_name: topic.domain_name,
}),
);
}
const source =
keywords ??
(topics ?? [])
.map((topic) => topic.source_keyword)
.filter((keyword): keyword is string => !!keyword);
const seen = new Set<string>();
const result: KeywordColor[] = [];
for (const keyword of source) {
const key = keyword.toLowerCase();
const color = colorByKeyword.get(key);
if (!color || seen.has(key)) {
continue;
}
seen.add(key);
result.push({ keyword, color });
}
return result;
}
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(
text: string,
keywordColors: readonly KeywordColor[],
): string {
const sorted = [...keywordColors]
.filter(({ keyword }) => keyword.trim())
.sort((a, b) => b.keyword.length - a.keyword.length);
if (!sorted.length) {
return escapeHtml(text);
}
// 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(
`(?<!${WORD_CHAR})(?:${alternatives.join('|')})`,
'gi',
);
let html = '';
let lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = pattern.exec(text)) !== null) {
const matched = match[0];
const entry = sorted.find(({ keyword }) =>
matched.toLowerCase().startsWith(keyword.toLowerCase()),
);
if (!entry) {
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>`;
lastIndex = match.index + matched.length;
}
return html + escapeHtml(text.slice(lastIndex));
}
export function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function isAcronymLike(keyword: string): boolean {
return (
keyword.length <= 3 ||
(keyword === keyword.toUpperCase() && keyword !== keyword.toLowerCase())
);
}
+41
View File
@@ -627,3 +627,44 @@ html.dark-theme {
flex-shrink: 0;
transition: transform 0.3s ease;
}
/* Keyword highlight */
@keyframes kw-flash {
0% {
background: color-mix(in srgb, var(--t) 45%, var(--sg-color-mix-base));
}
40% {
background: color-mix(in srgb, var(--t) 45%, var(--sg-color-mix-base));
}
100% {
background: transparent;
}
}
.kw-mark {
background: transparent;
color: var(--t);
text-decoration: underline;
text-decoration-color: var(--t);
text-decoration-style: solid;
text-decoration-thickness: 2px;
text-underline-offset: 2px;
font-weight: inherit;
border-radius: 2px;
padding: 0 1px;
transition: background 0.15s;
&:hover {
background: color-mix(in srgb, var(--t) 15%, var(--sg-color-mix-base));
}
&.kw-flash {
animation: kw-flash 2.4s ease-out forwards;
}
}
.search-mark {
background: transparent;
color: var(--sg-blue-highlight);
font-weight: 700;
}