From 9440605a6f87a02044d0a8222a9a4e82bcb0d86c Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 13:32:04 +0200 Subject: [PATCH 1/3] refactor(news-keyword-search): adapt projects' highlighting approach and drop tooltips --- .../news-results/news-results.component.html | 22 +--- .../news-results/news-results.component.scss | 15 --- .../news-results/news-results.component.ts | 116 ++++++++++-------- .../news-detail/news-detail.component.ts | 4 - 4 files changed, 69 insertions(+), 88 deletions(-) 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 4b6f9497..bcb4777e 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 @@ -72,24 +72,12 @@
- @if (snippetSegments().get(article.id); as segments) { + @if (snippetHighlights().get(article.id); as snippet) { 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 diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss index 117b1e3a..11f36e2c 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss @@ -153,21 +153,6 @@ 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; } diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index 9de89e9e..b279388a 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -42,18 +42,15 @@ import { SORT_ICON, } from '../../../../shared/ui/icons'; import { - keywordTooltip, - splitByKeywords, - topicKeywordColors, -} from '../../../../resolvers/utils/keyword-highlight'; + HighlightedTextComponent, + HighlightTerm, +} from '../../../../shared/ui/highlighted-text/highlighted-text.component'; type NewsResult = NewsPage['results'][number]; -interface SnippetSegment { - text: string; - color: string | null; - tooltip: string | null; - isSearchMatch: boolean; +interface SnippetHighlight { + content: string; + terms: HighlightTerm[]; } @Component({ @@ -64,6 +61,7 @@ interface SnippetSegment { MatIconModule, MatTooltipModule, DataTableComponent, + HighlightedTextComponent, AppTopicChipComponent, ChipOverflowToggleComponent, FilterCardComponent, @@ -264,70 +262,84 @@ export class KeywordsToNewsResultsComponent { return this.dataTable()?.expandedElement() === article; } - readonly snippetSegments = computed(() => { - const byArticleId = new Map(); + readonly snippetHighlights = computed(() => { + const byArticleId = new Map(); for (const article of this.elements()) { - const segments = this.buildSnippetSegments(article); - if (segments.length) { - byArticleId.set(article.id, segments); + const snippet = this.buildSnippetHighlight(article); + if (snippet) { + byArticleId.set(article.id, snippet); } } return byArticleId; }); - private buildSnippetSegments(article: NewsResult): SnippetSegment[] { + private buildSnippetHighlight(article: NewsResult): SnippetHighlight | null { const snippet = article.snippet; if (!snippet) { - return []; + return null; } - const keywordColors = topicKeywordColors(article.topics); - const searchMatch = /([\s\S]*?)<\/em>/g; + const topicByKeyword = new Map(); + for (const topic of article.topics ?? []) { + const keyword = topic.source_keyword?.toLowerCase(); + if (keyword && !topicByKeyword.has(keyword)) { + topicByKeyword.set(keyword, topic); + } + } - const segments: SnippetSegment[] = []; - let lastIndex = 0; + const terms: HighlightTerm[] = []; + const seen = new Set(); + const searchMatch = /([\s\S]*?)<\/em>/g; 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, - }); + const matched = this.decodeHtml(match[1]).trim(); + const topic = this.topicForTerm(matched, topicByKeyword); + const term = topic?.source_keyword ?? matched; + const key = term.toLowerCase(); + if (!term || seen.has(key)) { + continue; } + seen.add(key); - lastIndex = searchMatch.lastIndex; + terms.push({ + term, + topic: topic + ? { + id: topic.id, + name: topic.display_name, + field_name: topic.field_name, + domain_name: topic.domain_name, + } + : null, + }); } - pushPlain(snippet.slice(lastIndex)); + return { + content: this.decodeHtml(snippet.replace(/<\/?em>/g, '')), + terms, + }; + } - return segments; + private topicForTerm( + term: string, + topicByKeyword: ReadonlyMap, + ): MatchedTopic | null { + const lower = term.toLowerCase(); + const exact = topicByKeyword.get(lower); + if (exact) { + return exact; + } + + for (const [keyword, topic] of topicByKeyword) { + if (lower.startsWith(keyword)) { + return topic; + } + } + + return null; } private decodeHtml(value: string): string { 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 702a37c8..c7d48c35 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -18,10 +18,6 @@ import { } from '../../shared/ui/highlighted-text/highlighted-text.component'; 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'; import { ARROW_BACK_ICON, -- 2.56.1 From 84073854bf650f68cf341473b56f1298f7c14a88 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 14:49:36 +0200 Subject: [PATCH 2/3] feat(news-keyword-search): preview bigger excerpt --- service/src/main/inse/news/logic.py | 154 +++++++++++++++--- .../news-results/news-results.component.ts | 13 +- 2 files changed, 137 insertions(+), 30 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index aa2625ed..2cc1b6fb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -4,6 +4,7 @@ Business logic for the "aktuell" news index on the INSE cluster. """ import logging +import re from pydantic import ValidationError @@ -30,6 +31,32 @@ TOPICS_INDEX = "aktuell_openalex_topics" _SESSION_TOPIC_CACHE: dict[str, list] = {} +SNIPPET_FRAGMENT_CHARS = 500 +SNIPPET_FRAGMENT_COUNT = 3 +SNIPPET_FRAGMENT_SEPARATOR = " … " + +SNIPPET_CONTEXT_BEFORE_CHARS = 400 +SNIPPET_CONTEXT_AFTER_CHARS = 1100 +SNIPPET_BOUNDARY_CHARS = 150 +SNIPPET_ELLIPSIS = "…" + +_EM_TAG = re.compile(r"(.*?)", re.DOTALL) + +PREVIEW_WORD_COUNT = 80 + +CONTENT_HIGHLIGHT = { + "fields": { + "full_content": { + "fragment_size": SNIPPET_FRAGMENT_CHARS, + "number_of_fragments": SNIPPET_FRAGMENT_COUNT, + "no_match_size": SNIPPET_FRAGMENT_CHARS, + } + }, + "pre_tags": [""], + "post_tags": [""], + "require_field_match": False, +} + KEYWORD_LIMIT = 6 KEYWORD_CONTENT_CHARS = 4000 KEYWORD_SYSTEM_PROMPT = """\ @@ -87,13 +114,6 @@ async def search_news( ) -> NewsPage: offset = (page - 1) * page_size - highlight = { - "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, - "pre_tags": [""], - "post_tags": [""], - "encoder": "html", - } - # Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage). clauses = await _filter_clauses(year_from, year_to, relevance_values) exact_query = { @@ -115,7 +135,7 @@ async def search_news( size=page_size, offset=offset, sort=None, - highlight=highlight, + highlight=CONTENT_HIGHLIGHT, ) news_page = await _build_page(response, page, page_size) @@ -185,13 +205,6 @@ async def search_news_by_keywords( } } - highlight = { - "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, - "pre_tags": [""], - "post_tags": [""], - "encoder": "html", - } - sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None response = await _run_search( @@ -200,7 +213,7 @@ async def search_news_by_keywords( size=page_size, offset=(page - 1) * page_size, sort=sort, - highlight=None if wanted_topic_ids else highlight, + highlight=None if wanted_topic_ids else CONTENT_HIGHLIGHT, ) news_page = await _build_page(response, page, page_size) @@ -761,7 +774,7 @@ def _parse_hit(hit: dict) -> NewsArticle: fragments = hit.get("highlight", {}).get("full_content") if fragments: - snippet = fragments[0] + snippet = _snippet_with_context(source, fragments) else: snippet = _make_preview(source) @@ -775,15 +788,118 @@ def _parse_hit(hit: dict) -> NewsArticle: ) +def _snippet_with_context(source: dict, fragments: list) -> str: + + joined = SNIPPET_FRAGMENT_SEPARATOR.join(fragments) + text = source.get("full_content") + terms = _marked_terms(joined) + + if not text or not terms: + return joined + + span = _first_term_span(text, terms) + if span is None: + return joined + + start, end = _window_bounds(text, *span) + window = _mark_terms(text[start:end], terms) + + if start > 0: + window = f"{SNIPPET_ELLIPSIS} {window}" + if end < len(text): + window = f"{window} {SNIPPET_ELLIPSIS}" + + return window + + +def _marked_terms(fragment_text: str) -> list: + + by_key: dict[str, str] = {} + for match in _EM_TAG.finditer(fragment_text): + term = match.group(1).strip() + if term: + by_key.setdefault(term.lower(), term) + return list(by_key.values()) + + +def _first_term_span(text: str, terms: list) -> tuple | None: + + lowered = text.lower() + spans = [ + (index, index + len(term)) + for term, index in ((term, lowered.find(term.lower())) for term in terms) + if index >= 0 + ] + return min(spans) if spans else None + + +def _window_bounds(text: str, match_start: int, match_end: int) -> tuple: + + start = max(0, match_start - SNIPPET_CONTEXT_BEFORE_CHARS) + end = min(len(text), match_end + SNIPPET_CONTEXT_AFTER_CHARS) + + if start > 0: + start = _forward_to_boundary(text, start, match_start) + if end < len(text): + end = _back_to_boundary(text, end, match_end) + + return start, end + + +def _forward_to_boundary(text: str, start: int, limit: int) -> int: + + ahead = text[start : min(limit, start + SNIPPET_BOUNDARY_CHARS)] + + sentence = ahead.find(". ") + if sentence >= 0: + return start + sentence + 2 + + space = ahead.find(" ") + return start + space + 1 if space >= 0 else start + + +def _back_to_boundary(text: str, end: int, floor: int) -> int: + + ahead = text[end : end + SNIPPET_BOUNDARY_CHARS] + + sentence = ahead.find(". ") + if sentence >= 0: + return end + sentence + 1 + + space = text.rfind(" ", floor, end) + return space if space > floor else end + + +def _mark_terms(window: str, terms: list) -> str: + + lowered = window.lower() + spans = sorted( + (index, index + len(term)) + for term, index in ((term, lowered.find(term.lower())) for term in terms) + if index >= 0 + ) + + marked = [] + cursor = 0 + for start, end in spans: + if start < cursor: + continue + marked.append(window[cursor:start]) + marked.append(f"{window[start:end]}") + cursor = end + marked.append(window[cursor:]) + + return "".join(marked) + + def _make_preview(source: dict) -> str | None: - text = source.get("intro_content") or source.get("full_content") + text = source.get("full_content") or source.get("intro_content") if not text: return None words = text.split() - PREVIEW_WORD_COUNT = 10 preview = " ".join(words[:PREVIEW_WORD_COUNT]) if len(words) > PREVIEW_WORD_COUNT: preview = preview + " …" diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index b279388a..0d6c50a9 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -295,7 +295,7 @@ export class KeywordsToNewsResultsComponent { let match: RegExpExecArray | null; while ((match = searchMatch.exec(snippet)) !== null) { - const matched = this.decodeHtml(match[1]).trim(); + const matched = match[1].trim(); const topic = this.topicForTerm(matched, topicByKeyword); const term = topic?.source_keyword ?? matched; const key = term.toLowerCase(); @@ -318,7 +318,7 @@ export class KeywordsToNewsResultsComponent { } return { - content: this.decodeHtml(snippet.replace(/<\/?em>/g, '')), + content: snippet.replace(/<\/?em>/g, ''), terms, }; } @@ -342,15 +342,6 @@ export class KeywordsToNewsResultsComponent { return null; } - 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); } -- 2.56.1 From 50ff313a57a0b4abf449f9910cbe293b77355e6a Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 16:32:47 +0200 Subject: [PATCH 3/3] refactor(news-keyword-search): adapt styling from projects --- .../news-results/news-results.component.html | 50 +++++++---- .../news-results/news-results.component.scss | 31 +------ .../news-results/news-results.component.ts | 88 ++++++++----------- .../highlighted-text.component.ts | 59 +++++++++---- 4 files changed, 118 insertions(+), 110 deletions(-) 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 bcb4777e..7c21c0a7 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 @@ -65,26 +65,46 @@ class="title" [routerLink]="['/news', article.id]" (click)="$event.stopPropagation()"> - {{ article.maintitle || 'Kein Titel' }} +
-
- @if (snippetHighlights().get(article.id); as snippet) { - Fundstelle im Artikel - - } @else { - - Für diesen Artikel liegt keine Textstelle zu den gesuchten Keywords - vor. - - } -
+ +
+

Fundstelle im Artikel

+
+ + + @if (titleHighlights().get(article.id); as titleTerms) { +
+

Titel

+ +
+ } + + @if (snippetHighlights().get(article.id); as snippet) { +
+

Artikeltext

+ +
+ } @else { + + Für diesen Artikel liegt keine Textstelle zu den gesuchten Keywords + vor. + + } +
+
diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss index 11f36e2c..2e9112b4 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.scss @@ -115,6 +115,10 @@ color: var(--sg-text); text-decoration: underline; } + + app-highlighted-text { + display: inline; + } } .expand-icon { @@ -126,33 +130,6 @@ } } -/* ============================================================ - 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.6; - color: var(--sg-text-secondary); - overflow-wrap: anywhere; -} - .date-text { white-space: nowrap; } diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index 0d6c50a9..dbe251f1 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -42,9 +42,11 @@ import { SORT_ICON, } from '../../../../shared/ui/icons'; import { + containsHighlightTerm, HighlightedTextComponent, HighlightTerm, } from '../../../../shared/ui/highlighted-text/highlighted-text.component'; +import { TableDetailRowComponent } from '../../../../shared/ui/table-detail-row/table-detail-row.component'; type NewsResult = NewsPage['results'][number]; @@ -62,6 +64,7 @@ interface SnippetHighlight { MatTooltipModule, DataTableComponent, HighlightedTextComponent, + TableDetailRowComponent, AppTopicChipComponent, ChipOverflowToggleComponent, FilterCardComponent, @@ -275,71 +278,58 @@ export class KeywordsToNewsResultsComponent { return byArticleId; }); + readonly titleHighlights = computed(() => { + const byArticleId = new Map(); + const keywords = this.state.keywords(); + + for (const article of this.elements()) { + const found = keywords.filter((keyword) => + containsHighlightTerm(article.maintitle, [keyword]), + ); + if (found.length) { + byArticleId.set(article.id, this.toHighlightTerms(found)); + } + } + + return byArticleId; + }); + private buildSnippetHighlight(article: NewsResult): SnippetHighlight | null { const snippet = article.snippet; if (!snippet) { return null; } - const topicByKeyword = new Map(); - for (const topic of article.topics ?? []) { - const keyword = topic.source_keyword?.toLowerCase(); - if (keyword && !topicByKeyword.has(keyword)) { - topicByKeyword.set(keyword, topic); - } - } + return { + content: snippet.replace(/<\/?em>/g, ''), + terms: this.toHighlightTerms([ + ...this.state.keywords(), + ...this.markedTerms(snippet), + ]), + }; + } - const terms: HighlightTerm[] = []; + private markedTerms(snippet: string): string[] { + return [...snippet.matchAll(/([\s\S]*?)<\/em>/g)].map((match) => + match[1].trim(), + ); + } + + private toHighlightTerms(terms: string[]): HighlightTerm[] { const seen = new Set(); - const searchMatch = /([\s\S]*?)<\/em>/g; - let match: RegExpExecArray | null; + const result: HighlightTerm[] = []; - while ((match = searchMatch.exec(snippet)) !== null) { - const matched = match[1].trim(); - const topic = this.topicForTerm(matched, topicByKeyword); - const term = topic?.source_keyword ?? matched; + for (const raw of terms) { + const term = raw.trim(); const key = term.toLowerCase(); if (!term || seen.has(key)) { continue; } seen.add(key); - - terms.push({ - term, - topic: topic - ? { - id: topic.id, - name: topic.display_name, - field_name: topic.field_name, - domain_name: topic.domain_name, - } - : null, - }); + result.push({ term, topic: this.state.resolveTopicForTerm(term) }); } - return { - content: snippet.replace(/<\/?em>/g, ''), - terms, - }; - } - - private topicForTerm( - term: string, - topicByKeyword: ReadonlyMap, - ): MatchedTopic | null { - const lower = term.toLowerCase(); - const exact = topicByKeyword.get(lower); - if (exact) { - return exact; - } - - for (const [keyword, topic] of topicByKeyword) { - if (lower.startsWith(keyword)) { - return topic; - } - } - - return null; + return result; } isTopicsExpanded(article: NewsResult): boolean { diff --git a/webapp/src/app/shared/ui/highlighted-text/highlighted-text.component.ts b/webapp/src/app/shared/ui/highlighted-text/highlighted-text.component.ts index ece59f8e..327c566a 100644 --- a/webapp/src/app/shared/ui/highlighted-text/highlighted-text.component.ts +++ b/webapp/src/app/shared/ui/highlighted-text/highlighted-text.component.ts @@ -85,24 +85,11 @@ export class HighlightedTextComponent { ); } - /** - * 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 = '(? { - 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'); + return termsRegex( + terms.map(({ term }) => this.escapeHtml(term)), + 'gi', + ); } private findOriginTerm( @@ -122,8 +109,42 @@ export class HighlightedTextComponent { .replace(/>/g, '>') .replace(/"/g, '"'); } +} - private escapeRegex(text: string): string { - return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +const WORD_CHAR = '[\\w\\u00C0-\\u024F]'; + +/** + * Short/acronym-like terms (<=3 chars, or ALL CAPS) match exactly. + * Longer terms also swallow a trailing suffix (plural/case endings). + */ +function termPattern(term: string): string { + const escaped = escapeRegex(term); + const acronymLike = + term.length <= 3 || + (term === term.toUpperCase() && term !== term.toLowerCase()); + + return acronymLike ? `${escaped}(?!${WORD_CHAR})` : `${escaped}${WORD_CHAR}*`; +} + +function termsRegex(terms: string[], flags: string): RegExp { + return new RegExp( + `(? term.trim()).filter(Boolean); + if (!text || !usable.length) { + return false; } + + return termsRegex(usable, 'i').test(text); +} + +function escapeRegex(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } -- 2.56.1