feature/news-in-keywords #281

Merged
kallweit merged 4 commits from feature/news-in-keywords into dev 2026-08-15 20:54:25 +02:00
6 changed files with 413 additions and 68 deletions
@@ -39,13 +39,62 @@
}
</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 (snippetSegments().get(article.id); as segments) {
<span class="snippet-label">Fundstelle im Artikel</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
vor.
</span>
}
</div>
</ng-template>
@@ -86,7 +135,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 +165,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 +194,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;
}
@@ -77,15 +76,19 @@
}
::ng-deep .table-wrap {
.mat-column-date,
.mat-column-relevant,
.mat-mdc-header-cell {
text-align: center;
}
.mat-column-topics {
overflow: visible;
}
.mat-column-expand {
width: 48px;
padding-right: 0;
}
.detail-row .mat-mdc-cell {
padding: 0;
border-bottom: none;
}
}
/* ============================================================
@@ -114,16 +117,54 @@
}
}
.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;
}
.snippet {
margin: 0;
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);
.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;
}
}
@@ -32,9 +32,21 @@ 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 {
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: [
@@ -136,13 +148,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 +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<string, SnippetSegment[]>();
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 = /<em>([\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(/&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);
}
@@ -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 {
@@ -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,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<string, Omit<KeywordColor, 'keyword'>>();
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<string>();
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(
`(?<!${WORD_CHAR})(?:${alternatives.join('|')})`,
'gi',
);
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 }) =>
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 (
`<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 {
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())
);
}