From 2f509fbbfee2ddbd24d84873c2fd05a3721aca4d Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sat, 15 Aug 2026 19:44:04 +0200 Subject: [PATCH 01/12] feat(keyword-search-works): expand rows to show matched content --- service/src/main/inse/models/openalex/work.py | 10 ++- service/src/main/inse/works/v2/service.py | 65 ++++++++++++++ webapp/src/app/api/model/work.ts | 85 ++++++++++--------- .../works-results.component.html | 38 ++++++++- .../works-results.component.scss | 53 ++++++++++++ .../works-results/works-results.component.ts | 63 +++++++++++++- .../ui/data-table/data-table.component.html | 1 + .../publication-table.component.html | 43 ++++++++-- .../publication-table.component.scss | 9 ++ .../publication-table.component.ts | 18 ++++ 10 files changed, 332 insertions(+), 53 deletions(-) diff --git a/service/src/main/inse/models/openalex/work.py b/service/src/main/inse/models/openalex/work.py index 31934220..3ad6f785 100644 --- a/service/src/main/inse/models/openalex/work.py +++ b/service/src/main/inse/models/openalex/work.py @@ -94,7 +94,10 @@ class Work(BaseModel): content_url: StrictStr | None = Field(default=None, description="URL for downloading full-text content. Only present when `has_content.pdf` or `has_content.grobid_xml` is true.") created_date: date | None = Field(default=None, description="When this work was added to OpenAlex (ISO 8601 date).") updated_date: datetime | None = Field(default=None, description="When this work was last updated (ISO 8601 datetime).") - __properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date"] + snippet: StrictStr | None = Field(default=None, description="Passage of the title or abstract containing the searched keyword, with the matches wrapped in ``. Only set by the keyword search, and only when the keyword actually occurs in the text.") + snippet_field: StrictStr | None = Field(default=None, description="Which field `snippet` was taken from: `title` or `abstract`.") + matched_via: list[StrictStr] | None = Field(default=None, description="Names of the topics and OpenAlex keywords that matched the searched keywords. Set by the keyword search so a work matched purely on metadata can explain itself when there is no `snippet`.") + __properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date", "snippet", "snippet_field", "matched_via"] model_config = ConfigDict( validate_by_name=True, @@ -273,7 +276,10 @@ class Work(BaseModel): "has_content": WorkHasContent.from_dict(obj["has_content"]) if obj.get("has_content") is not None else None, "content_url": obj.get("content_url"), "created_date": obj.get("created_date"), - "updated_date": obj.get("updated_date") + "updated_date": obj.get("updated_date"), + "snippet": obj.get("snippet"), + "snippet_field": obj.get("snippet_field"), + "matched_via": obj.get("matched_via") }) return _obj diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 20e139a8..5d9630bc 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -372,6 +372,19 @@ async def get_works_by_keywords( track_total_hits=True, offset=page * size, sort=sort, + # A work matches on its topic and keyword metadata as well as on its + # text, so roughly half the hits contain the searched keyword nowhere in + # title or abstract. Highlighting tells the two apart: a fragment comes + # back only for the works that really do carry the phrase. + highlight={ + "fields": { + "title": {"number_of_fragments": 0}, + "abstract": {"fragment_size": 240, "number_of_fragments": 1}, + }, + "pre_tags": [""], + "post_tags": [""], + "encoder": "html", + }, cluster=ESCluster.NES, ) print(f"Elasticsearch response: {response}") @@ -388,11 +401,63 @@ async def get_works_by_keywords( work = Work.from_dict(source) # type: ignore if work is not None: + snippet, snippet_field = _keyword_snippet(hit) + work.snippet = snippet + work.snippet_field = snippet_field + work.matched_via = _matched_via(source, keywords) elements.append(work) return WorkPageV2(elements=elements, total=total, page=page, size=size) +def _keyword_snippet(hit: dict) -> tuple[str | None, str | None]: + """Picks the passage to show for a hit, preferring the title over the abstract.""" + highlight = hit.get("highlight") or {} + + for field in ("title", "abstract"): + fragments = highlight.get(field) + if fragments: + return fragments[0], field + + return None, None + + +def _matched_via(source: dict, keywords: list[str] | None) -> list[str] | None: + """Names the topics and keywords a work was matched through. + + Only needed when there is no snippet: those works carry the searched term in + their metadata rather than in their text, and would otherwise expand into an + empty row. Matching mirrors the `match_phrase` clauses above closely enough + for a label - it is not used for retrieval. + """ + wanted = [kw.strip().lower() for kw in (keywords or []) if kw and kw.strip()] + if not wanted: + return None + + candidates: list[str] = [] + + primary_topic = source.get("primary_topic") or {} + candidates.append(primary_topic.get("display_name")) + + for topic in source.get("topics") or []: + candidates.append(topic.get("display_name")) + for level in ("field", "subfield", "domain"): + candidates.append((topic.get(level) or {}).get("display_name")) + + for keyword in source.get("keywords") or []: + candidates.append(keyword.get("display_name")) + + names: list[str] = [] + for name in candidates: + if not name or name in names: + continue + lowered = name.lower() + if any(kw in lowered for kw in wanted): + names.append(name) + + return names or None + + async def get_author_works( raw_oa_author_id: str, page: int, diff --git a/webapp/src/app/api/model/work.ts b/webapp/src/app/api/model/work.ts index 07d94a1c..97c4d648 100644 --- a/webapp/src/app/api/model/work.ts +++ b/webapp/src/app/api/model/work.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -24,48 +24,49 @@ import { WorkHasContent } from './workHasContent'; import { Location } from './location'; import { WorkBiblio } from './workBiblio'; - /** * A scholarly document (article, book, dataset, thesis, etc.) */ -export interface Work { - id?: string | null; - doi?: string | null; - title?: string | null; - display_name?: string | null; - publication_year?: number | null; - publication_date?: string | null; - type?: string | null; - language?: string | null; - cited_by_count?: number | null; - is_retracted?: boolean | null; - is_paratext?: boolean | null; - primary_location?: Location | null; - locations?: Array | null; - best_oa_location?: Location | null; - open_access?: OpenAccess | null; - authorships?: Array | null; - ids?: WorkIds | null; - biblio?: WorkBiblio | null; - abstract_inverted_index?: object | null; - referenced_works?: Array | null; - referenced_works_count?: number | null; - related_works?: Array | null; - topics?: Array | null; - primary_topic?: WorkTopic | null; - keywords?: Array | null; - funders?: Array | null; - awards?: Array | null; - fwci?: Fwci | null; - citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; - cited_by_percentile_year?: WorkCitedByPercentileYear | null; - counts_by_year?: Array | null; - sustainable_development_goals?: Array | null; - mesh?: Array | null; - indexed_in?: Array | null; - has_content?: WorkHasContent | null; - content_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Work { + id?: string | null; + doi?: string | null; + title?: string | null; + display_name?: string | null; + publication_year?: number | null; + publication_date?: string | null; + type?: string | null; + language?: string | null; + cited_by_count?: number | null; + is_retracted?: boolean | null; + is_paratext?: boolean | null; + primary_location?: Location | null; + locations?: Array | null; + best_oa_location?: Location | null; + open_access?: OpenAccess | null; + authorships?: Array | null; + ids?: WorkIds | null; + biblio?: WorkBiblio | null; + abstract_inverted_index?: object | null; + referenced_works?: Array | null; + referenced_works_count?: number | null; + related_works?: Array | null; + topics?: Array | null; + primary_topic?: WorkTopic | null; + keywords?: Array | null; + funders?: Array | null; + awards?: Array | null; + fwci?: Fwci | null; + citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; + cited_by_percentile_year?: WorkCitedByPercentileYear | null; + counts_by_year?: Array | null; + sustainable_development_goals?: Array | null; + mesh?: Array | null; + indexed_in?: Array | null; + has_content?: WorkHasContent | null; + content_url?: string | null; + created_date?: string | null; + updated_date?: string | null; + snippet?: string | null; + snippet_field?: string | null; + matched_via?: Array | null; } - diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index 7f6d987c..aa5496a9 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -5,11 +5,47 @@ [selectedAuthorsPage]="selectedAuthorsPage()" [showTopicFilter]="fuzzySearch()" /> + +
+ @if (snippetSegments().get(work.id); as segments) { + + Fundstelle im {{ snippetSourceLabel(work) }} + +

+ @for (segment of segments; track $index) { + @if (segment.isSearchMatch) { + {{ segment.text }} + } @else { + {{ segment.text }} + } + } +

+ } @else if (work.matched_via?.length) { + Kein Treffer im Text +

+ Das gesuchte Keyword kommt weder im Titel noch im Abstract vor. Die + Publikation wurde über + {{ work.matched_via!.length === 1 ? 'das Thema' : 'die Themen' }} + @for (name of work.matched_via; track name; let last = $last) { + {{ name }}{{ last ? '' : ', ' }} + } + gefunden. +

+ } @else { + + Für diese Publikation liegt keine Fundstelle vor. + + } +
+
+ + [topicFilterEnabled]="fuzzySearch()" + [detailTemplate]="snippetTmp" /> ') + .replace(/"/g, '"') + .replace(/&#(?:39|x27);/g, "'") + .replace(/&/g, '&'); +} + @Component({ selector: 'app-works-results', imports: [ @@ -64,6 +83,48 @@ export class KeywordsToWorksResultsComponent implements OnInit { fuzzySearch = computed(() => this.queryParamMap().get('fuzzy') === 'true'); + readonly snippetSegments = computed(() => { + const byWorkId = new Map(); + + for (const work of this.elements()) { + if (!work.id || !work.snippet) { + continue; + } + byWorkId.set(work.id, this.buildSegments(work.snippet)); + } + + return byWorkId; + }); + + private buildSegments(snippet: string): SnippetSegment[] { + const searchMatch = /([\s\S]*?)<\/em>/g; + const segments: SnippetSegment[] = []; + + let lastIndex = 0; + let match: RegExpExecArray | null; + + const pushPlain = (raw: string) => { + const text = decodeHtml(raw); + if (text) { + segments.push({ text, isSearchMatch: false }); + } + }; + + while ((match = searchMatch.exec(snippet)) !== null) { + pushPlain(snippet.slice(lastIndex, match.index)); + segments.push({ text: decodeHtml(match[1]), isSearchMatch: true }); + lastIndex = searchMatch.lastIndex; + } + + pushPlain(snippet.slice(lastIndex)); + + return segments; + } + + snippetSourceLabel(work: Work): string { + return work.snippet_field === 'title' ? 'Titel' : 'Abstract'; + } + ngOnInit(): void {} clearFilters(): void { diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index 85b8df3f..61871fe2 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -61,6 +61,7 @@ mat-row *matRowDef="let row; columns: displayedColumns()" class="element-row" + [class.is-expanded]="row === expandedElement()" (click)="toggleRow(row)"> + + @let expanded = isRowExpanded(work); + + + {{ work.title }} @@ -16,7 +33,7 @@ [class.active]="isTypeActive(work.type)" matTooltip="Nach Typ filtern" matTooltipPosition="above" - (click)="toggleTypeFilter(work.type)"> + (click)="$event.stopPropagation(); toggleTypeFilter(work.type)"> {{ work.type | workType }} @@ -34,7 +51,9 @@ [class.active]="isYearActive(work.publication_year)" matTooltip="Nach Jahr filtern" matTooltipPosition="above" - (click)="toggleYearFilter(work.publication_year)"> + (click)=" + $event.stopPropagation(); toggleYearFilter(work.publication_year) + "> {{ work.publication_year }} } @else { @@ -50,7 +69,7 @@ [class.active]="isLanguageActive(work.language)" matTooltip="Nach Sprache filtern" matTooltipPosition="above" - (click)="toggleLanguageFilter(work.language)"> + (click)="$event.stopPropagation(); toggleLanguageFilter(work.language)"> {{ work.language | languageCode }} } @else { @@ -81,7 +100,8 @@
+ style="padding: 0.5rem 0" + (click)="$event.stopPropagation()"> @for (institution of visibleInstitutions; track institution.id) { +
@for ( author of visibleAuthors; track author.id ?? 'name-' + author.display_name @@ -133,7 +157,11 @@ @let workTopics = work.topics ?? []; -
+
@for (topic of workTopics; track topic.id) { + matTooltip="Details anzeigen" + (click)="$event.stopPropagation()"> {{ OPEN_IN_NEW_ICON }} diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss index 6df1e4e9..7a1d7b66 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss @@ -562,3 +562,12 @@ mat-panel-description { align-items: flex-start; max-width: 350px; } + +.expand-icon { + color: var(--sg-text-muted); + transition: transform 150ms ease-in-out; + + &.is-expanded { + transform: rotate(180deg); + } +} diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts index 4977dea8..e5d6532a 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts @@ -70,6 +70,8 @@ export class PublicationTableComponent { rawOaAuthorId = input(undefined); rawOaInstitutionId = input(undefined); + detailTemplate = input | null>(null); + shouldFetchClassifications = computed(() => { return ( this.rawOaAuthorId() !== undefined || @@ -85,6 +87,7 @@ export class PublicationTableComponent { elements = computed(() => this.page().elements ?? []); + expandTmp = viewChild.required>('expandTmp'); titleTmp = viewChild.required>('titleTmp'); typeTmp = viewChild.required>('typeTmp'); yearTmp = viewChild.required>('yearTmp'); @@ -202,9 +205,24 @@ export class PublicationTableComponent { }, ); + if (this.detailTemplate()) { + baseColumns.unshift({ + id: 'expand', + header: '', + type: 'display', + cellTemplate: this.expandTmp(), + }); + } + return baseColumns; }); + private readonly dataTable = viewChild(DataTableComponent); + + isRowExpanded(work: Work): boolean { + return this.dataTable()?.expandedElement() === work; + } + workIds = computed( () => this.elements() -- 2.56.1 From 56ada07d97e1fdcb21ecd2f9e36ded91f331500d Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sat, 15 Aug 2026 21:46:29 +0200 Subject: [PATCH 02/12] refactor(keyword-highlighting): remove duplication after rebase --- .../news-results/news-results.component.html | 23 +------ .../news-results/news-results.component.scss | 14 ----- .../news-results/news-results.component.ts | 17 +----- .../works-results.component.html | 10 +-- .../works-results.component.scss | 6 -- .../works-results/works-results.component.ts | 47 +++----------- .../app/resolvers/utils/keyword-highlight.ts | 61 +++++++++++++++++++ .../ui/data-table/data-table.component.html | 25 ++++++++ .../ui/data-table/data-table.component.scss | 15 +++++ .../ui/data-table/data-table.component.ts | 28 ++++++++- .../publication-table.component.html | 16 ----- .../publication-table.component.scss | 9 --- .../publication-table.component.ts | 16 ----- .../snippet-text/snippet-text.component.html | 16 +++++ .../snippet-text/snippet-text.component.scss | 25 ++++++++ .../ui/snippet-text/snippet-text.component.ts | 43 +++++++++++++ 16 files changed, 222 insertions(+), 149 deletions(-) create mode 100644 webapp/src/app/shared/ui/snippet-text/snippet-text.component.html create mode 100644 webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss create mode 100644 webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts 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 7c21c0a7..be417d50 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,26 +39,6 @@ }
- - @if (article.snippet) { - @let expanded = isSnippetExpanded(article); - - } - - 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', @@ -261,10 +250,6 @@ export class KeywordsToNewsResultsComponent { return !!topic.id && this.selectedTopicIds().includes(topic.id); } - isSnippetExpanded(article: NewsResult): boolean { - return this.dataTable()?.expandedElement() === article; - } - readonly snippetHighlights = computed(() => { const byArticleId = new Map(); @@ -332,6 +317,8 @@ export class KeywordsToNewsResultsComponent { return result; } + readonly hasSnippet = (article: NewsResult): boolean => !!article.snippet; + isTopicsExpanded(article: NewsResult): boolean { return this.expandedTopicsIds().has(article.id); } diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index aa5496a9..58e23f77 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -11,15 +11,7 @@ Fundstelle im {{ snippetSourceLabel(work) }} -

- @for (segment of segments; track $index) { - @if (segment.isSearchMatch) { - {{ segment.text }} - } @else { - {{ segment.text }} - } - } -

+ } @else if (work.matched_via?.length) { Kein Treffer im Text

diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.scss index 7cab69b1..6449903c 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.scss @@ -121,12 +121,6 @@ overflow-wrap: anywhere; } -.snippet-mark { - background: transparent; - color: var(--sg-blue-highlight); - font-weight: 700; -} - .matched-topic { color: var(--sg-text); font-weight: 600; diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts index ec24a966..13077372 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts @@ -18,20 +18,11 @@ import { Work, } from '../../../../api'; import { SearchResultsStateService } from '../search-results-state.service'; - -interface SnippetSegment { - text: string; - isSearchMatch: boolean; -} - -function decodeHtml(text: string): string { - return text - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/"/g, '"') - .replace(/&#(?:39|x27);/g, "'") - .replace(/&/g, '&'); -} +import { + SnippetSegment, + splitSnippet, +} from '../../../../resolvers/utils/keyword-highlight'; +import { SnippetTextComponent } from '../../../../shared/ui/snippet-text/snippet-text.component'; @Component({ selector: 'app-works-results', @@ -42,6 +33,7 @@ function decodeHtml(text: string): string { PublicationTableComponent, PublicationFilterComponent, QueryParamPaginatorComponent, + SnippetTextComponent, ], templateUrl: './works-results.component.html', styleUrl: './works-results.component.scss', @@ -90,37 +82,12 @@ export class KeywordsToWorksResultsComponent implements OnInit { if (!work.id || !work.snippet) { continue; } - byWorkId.set(work.id, this.buildSegments(work.snippet)); + byWorkId.set(work.id, splitSnippet(work.snippet)); } return byWorkId; }); - private buildSegments(snippet: string): SnippetSegment[] { - const searchMatch = /([\s\S]*?)<\/em>/g; - const segments: SnippetSegment[] = []; - - let lastIndex = 0; - let match: RegExpExecArray | null; - - const pushPlain = (raw: string) => { - const text = decodeHtml(raw); - if (text) { - segments.push({ text, isSearchMatch: false }); - } - }; - - while ((match = searchMatch.exec(snippet)) !== null) { - pushPlain(snippet.slice(lastIndex, match.index)); - segments.push({ text: decodeHtml(match[1]), isSearchMatch: true }); - lastIndex = searchMatch.lastIndex; - } - - pushPlain(snippet.slice(lastIndex)); - - return segments; - } - snippetSourceLabel(work: Work): string { return work.snippet_field === 'title' ? 'Titel' : 'Abstract'; } diff --git a/webapp/src/app/resolvers/utils/keyword-highlight.ts b/webapp/src/app/resolvers/utils/keyword-highlight.ts index b22ec493..c48459d1 100644 --- a/webapp/src/app/resolvers/utils/keyword-highlight.ts +++ b/webapp/src/app/resolvers/utils/keyword-highlight.ts @@ -166,6 +166,67 @@ export function highlightKeywords( .join(''); } +export interface SnippetSegment { + text: string; + isSearchMatch: boolean; + match: KeywordColor | null; + groupHasMatch: boolean; +} + +export function splitSnippet( + snippet: string, + keywordColors: readonly KeywordColor[] = [], +): SnippetSegment[] { + const searchMatch = /([\s\S]*?)<\/em>/g; + const segments: SnippetSegment[] = []; + + let lastIndex = 0; + let match: RegExpExecArray | null; + + const pushPlain = (raw: string) => { + const text = decodeHtml(raw); + if (text) { + segments.push({ + text, + isSearchMatch: false, + match: null, + groupHasMatch: false, + }); + } + }; + + while ((match = searchMatch.exec(snippet)) !== null) { + pushPlain(snippet.slice(lastIndex, match.index)); + + const parts = splitByKeywords(decodeHtml(match[1]), keywordColors); + const groupHasMatch = parts.some((part) => part.match); + + for (const part of parts) { + segments.push({ + text: part.text, + isSearchMatch: true, + match: part.match, + groupHasMatch, + }); + } + + lastIndex = searchMatch.lastIndex; + } + + pushPlain(snippet.slice(lastIndex)); + + return segments; +} + +export function decodeHtml(text: string): string { + return text + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/&#(?:39|x27);/g, "'") + .replace(/&/g, '&'); +} + export function escapeHtml(text: string): string { return text .replace(/&/g, '&') diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index 61871fe2..5834271f 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -8,6 +8,31 @@ matSort (matSortChange)="_handleSortChange($event)" multiTemplateDataRows> + @if (detailTemplate()) { + + + + @if (isExpandable(row)) { + @let expanded = row === expandedElement(); + + } + + + } + @for (col of columns(); track col.id) { @if (col.headerTemplate) { diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.scss b/webapp/src/app/shared/ui/data-table/data-table.component.scss index 05b619f9..0f27deef 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.scss +++ b/webapp/src/app/shared/ui/data-table/data-table.component.scss @@ -27,3 +27,18 @@ tr.detail-row { background: var(--sg-surface-soft); cursor: pointer; } + +.expand-cell { + width: 1%; + white-space: nowrap; + padding-right: 0; +} + +.expand-icon { + color: var(--sg-text-muted); + transition: transform 150ms ease-in-out; + + &.is-expanded { + transform: rotate(180deg); + } +} diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.ts b/webapp/src/app/shared/ui/data-table/data-table.component.ts index 092488b2..e6a188b6 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.ts +++ b/webapp/src/app/shared/ui/data-table/data-table.component.ts @@ -19,6 +19,9 @@ import { SortDirection, } from '@angular/material/sort'; import { MatTableDataSource, MatTableModule } from '@angular/material/table'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { ActivatedRoute, Router } from '@angular/router'; import { SkTextDirective } from '../../../custom-directives/sk-text.directive'; export interface BaseColumn { @@ -43,7 +46,15 @@ export type GenericColumn = AccessorColumn | DisplayColumn; @Component({ selector: 'app-data-table', standalone: true, - imports: [MatTableModule, NgTemplateOutlet, MatSortModule, SkTextDirective], + imports: [ + MatTableModule, + NgTemplateOutlet, + MatSortModule, + MatButtonModule, + MatIconModule, + MatTooltipModule, + SkTextDirective, + ], templateUrl: './data-table.component.html', styleUrl: './data-table.component.scss', }) @@ -54,6 +65,7 @@ export class DataTableComponent implements AfterViewInit { detailTemplate = input | null>(null); expandedElement = signal(null); + canExpand = input<((row: T) => boolean) | null>(null); maxHeight = input(null); containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible')); @@ -78,7 +90,12 @@ export class DataTableComponent implements AfterViewInit { handleSortChange = output(); - displayedColumns = computed(() => this.columns().map((col) => col.id)); + readonly expandColumnId = 'expand'; + + displayedColumns = computed(() => { + const ids = this.columns().map((col) => col.id); + return this.detailTemplate() ? [this.expandColumnId, ...ids] : ids; + }); dataSource = new MatTableDataSource([]); sort = viewChild.required(MatSort); @@ -160,8 +177,13 @@ export class DataTableComponent implements AfterViewInit { } } + isExpandable(row: T): boolean { + if (!this.detailTemplate()) return false; + return this.canExpand()?.(row) ?? true; + } + toggleRow(row: T): void { - if (!this.detailTemplate()) return; + if (!this.isExpandable(row)) return; this.expandedElement.update((current) => (current === row ? null : row)); } } diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.html b/webapp/src/app/shared/ui/publication-table/publication-table.component.html index 393ba1d9..c9014f46 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.html +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.html @@ -5,22 +5,6 @@ queryParamSortKey="sort_by" queryParamSortDirectionKey="sort_direction" /> - - @let expanded = isRowExpanded(work); - - - {{ work.title }} diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss index 7a1d7b66..6df1e4e9 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss @@ -562,12 +562,3 @@ mat-panel-description { align-items: flex-start; max-width: 350px; } - -.expand-icon { - color: var(--sg-text-muted); - transition: transform 150ms ease-in-out; - - &.is-expanded { - transform: rotate(180deg); - } -} diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts index e5d6532a..98300190 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts @@ -87,7 +87,6 @@ export class PublicationTableComponent { elements = computed(() => this.page().elements ?? []); - expandTmp = viewChild.required>('expandTmp'); titleTmp = viewChild.required>('titleTmp'); typeTmp = viewChild.required>('typeTmp'); yearTmp = viewChild.required>('yearTmp'); @@ -205,24 +204,9 @@ export class PublicationTableComponent { }, ); - if (this.detailTemplate()) { - baseColumns.unshift({ - id: 'expand', - header: '', - type: 'display', - cellTemplate: this.expandTmp(), - }); - } - return baseColumns; }); - private readonly dataTable = viewChild(DataTableComponent); - - isRowExpanded(work: Work): boolean { - return this.dataTable()?.expandedElement() === work; - } - workIds = computed( () => this.elements() diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html new file mode 100644 index 00000000..6f39bd6d --- /dev/null +++ b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html @@ -0,0 +1,16 @@ +

+ @for (segment of rendered(); track $index) { + @if (segment.isSearchMatch) { + {{ segment.text }} + } @else { + {{ segment.text }} + } + } +

diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss new file mode 100644 index 00000000..5eabaa09 --- /dev/null +++ b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss @@ -0,0 +1,25 @@ +.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; + + &.has-topic { + color: var(--t); + text-decoration: underline; + text-decoration-color: var(--t); + text-decoration-thickness: 2px; + text-underline-offset: 2px; + } +} + +:host(.has-tooltips) .snippet-mark { + cursor: help; +} diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts new file mode 100644 index 00000000..a9e1e3a3 --- /dev/null +++ b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts @@ -0,0 +1,43 @@ +import { Component, computed, input } from '@angular/core'; +import { MatTooltipModule } from '@angular/material/tooltip'; + +import { + keywordTooltip, + SnippetSegment, +} from '../../../resolvers/utils/keyword-highlight'; + +@Component({ + host: { + '[class.has-tooltips]': 'showTooltips()', + }, + selector: 'app-snippet-text', + imports: [MatTooltipModule], + templateUrl: './snippet-text.component.html', + styleUrl: './snippet-text.component.scss', +}) +export class SnippetTextComponent { + segments = input.required(); + + showTooltips = input(false); + + protected readonly rendered = computed(() => + this.segments().map((segment) => ({ + text: segment.text, + isSearchMatch: segment.isSearchMatch, + color: segment.match?.color ?? null, + tooltip: this.tooltipFor(segment), + })), + ); + + private tooltipFor(segment: SnippetSegment): string { + if (!this.showTooltips() || !segment.isSearchMatch) { + return ''; + } + + if (segment.match) { + return keywordTooltip(segment.match.keyword, segment.match.topicNames); + } + + return segment.groupHasMatch ? '' : keywordTooltip(segment.text, []); + } +} -- 2.56.1 From 3f4b032e345beab1502260a5168e621c0f7ab11d Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 10:41:05 +0200 Subject: [PATCH 03/12] refactor(keyword-highlighting): drop the HTML-string path left unused after rebase --- .../app/resolvers/utils/keyword-highlight.ts | 33 ------------------- 1 file changed, 33 deletions(-) diff --git a/webapp/src/app/resolvers/utils/keyword-highlight.ts b/webapp/src/app/resolvers/utils/keyword-highlight.ts index c48459d1..d0879a84 100644 --- a/webapp/src/app/resolvers/utils/keyword-highlight.ts +++ b/webapp/src/app/resolvers/utils/keyword-highlight.ts @@ -83,8 +83,6 @@ export function keywordTooltip( const WORD_CHAR = '[\\w\\u00C0-\\u024F]'; -export const KW_MARK_CLASS = 'kw-mark'; - export interface KeywordSegment { text: string; match: KeywordColor | null; @@ -143,29 +141,6 @@ export function splitByKeywords( 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 interface SnippetSegment { text: string; isSearchMatch: boolean; @@ -227,14 +202,6 @@ export function decodeHtml(text: string): string { .replace(/&/g, '&'); } -export function escapeHtml(text: string): string { - return text - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} - function escapeRegex(text: string): string { return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } -- 2.56.1 From 1482e3fdc540de88a38368442eb252272fae0f1c Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 11:44:14 +0200 Subject: [PATCH 04/12] feat(news-keyword-search): expand row on click instead of opening article --- .../news-results/news-results.component.html | 7 ++----- .../news-results/news-results.component.scss | 6 ------ .../src/app/shared/ui/data-table/data-table.component.html | 1 + .../src/app/shared/ui/data-table/data-table.component.scss | 2 +- 4 files changed, 4 insertions(+), 12 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 be417d50..a177f947 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 @@ -41,14 +41,11 @@
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 00c544cf..0991f1a0 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 @@ -104,12 +104,6 @@ color: var(--sg-text); font-size: 14px; font-weight: 700; - text-decoration: none; - - &:hover { - color: var(--sg-text); - text-decoration: underline; - } app-highlighted-text { display: inline; diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index 5834271f..498fb20b 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -86,6 +86,7 @@ mat-row *matRowDef="let row; columns: displayedColumns()" class="element-row" + [class.is-expandable]="isExpandable(row)" [class.is-expanded]="row === expandedElement()" (click)="toggleRow(row)"> diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.scss b/webapp/src/app/shared/ui/data-table/data-table.component.scss index 0f27deef..c4b41c87 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.scss +++ b/webapp/src/app/shared/ui/data-table/data-table.component.scss @@ -23,7 +23,7 @@ tr.detail-row { display: flex; } -.element-row:hover { +.element-row.is-expandable:hover { background: var(--sg-surface-soft); cursor: pointer; } -- 2.56.1 From 1bfa0f113d65fe0f730bba087473ee806bcacbd5 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 11:50:51 +0200 Subject: [PATCH 05/12] refactor(works/news/-keyword-search): remove expandable rows for fuzzy search --- .../search-results/news-results/news-results.component.html | 2 +- .../search-results/works-results/works-results.component.html | 2 +- 2 files changed, 2 insertions(+), 2 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 a177f947..4383dcc3 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 @@ -182,7 +182,7 @@
diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index 58e23f77..d9711a68 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -37,7 +37,7 @@ [authorFilterEnabled]="true" [institutionFilterEnabled]="true" [topicFilterEnabled]="fuzzySearch()" - [detailTemplate]="snippetTmp" /> + [detailTemplate]="fuzzySearch() ? null : snippetTmp" /> Date: Sun, 16 Aug 2026 13:08:27 +0200 Subject: [PATCH 06/12] refactor(data-table): extract styling into shared css --- .../news-results/news-results.component.html | 12 ++--- .../news-results/news-results.component.scss | 54 ++----------------- .../bund-project-table.component.scss | 42 --------------- .../dfg-project-table.component.scss | 42 --------------- .../eu-project-table.component.scss | 40 -------------- .../publication-table.component.scss | 54 ------------------- webapp/src/styles.scss | 23 ++++++++ 7 files changed, 33 insertions(+), 234 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 4383dcc3..3b70ae04 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 @@ -178,13 +178,11 @@ }
} @else { -
- -
+ Date: Sun, 16 Aug 2026 13:26:19 +0200 Subject: [PATCH 07/12] feat(projects-keyword-search): set min-width for title and author columns --- .../bund-project-table.component.scss | 4 ++++ .../dfg-project-table/dfg-project-table.component.scss | 10 ++++++++++ .../eu-project-table/eu-project-table.component.scss | 10 ++++++++++ 3 files changed, 24 insertions(+) diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss index 3732ed25..3da75c51 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss @@ -4,6 +4,10 @@ margin: 0 auto; } +:host ::ng-deep .mat-column-title { + min-width: 280px; +} + // ------------------------ // Shared tags & chips // ------------------------ diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss index 1b2ba2a8..c56c94f4 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss @@ -4,6 +4,16 @@ margin: 0 auto; } +:host ::ng-deep { + .mat-column-title { + min-width: 280px; + } + + .mat-column-names { + min-width: 200px; + } +} + // ------------------------ // Shared tags & chips // ------------------------ diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss index 985edf21..a79e6da8 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss @@ -4,6 +4,16 @@ margin: 0 auto; } +:host ::ng-deep { + .mat-column-title { + min-width: 280px; + } + + .mat-column-authors { + min-width: 200px; + } +} + // ------------------------ // Shared tags & chips // ------------------------ -- 2.56.1 From 68f1cae4d9e9d85cf35bd43736535978a63107b1 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 13:57:32 +0200 Subject: [PATCH 08/12] feat(works-keyword-search): highlight keywords in their topic colors --- .../search-results-state.service.ts | 23 ++++++++++++++++++- .../works-results/works-results.component.ts | 4 +++- .../snippet-text/snippet-text.component.scss | 9 +++++--- webapp/src/styles.scss | 5 +++- 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index 802abafb..08aa1bd1 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -1,7 +1,11 @@ import { Injectable, computed, signal } from '@angular/core'; import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic'; import { Topic } from '../../../api'; -import { TopicHierarchyColorInput } from '../../../resolvers/utils/topic-colors'; +import { KeywordColor } from '../../../resolvers/utils/keyword-highlight'; +import { + topicHierarchyColor, + TopicHierarchyColorInput, +} from '../../../resolvers/utils/topic-colors'; export type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom'; export interface PatentKeywordEntry { @@ -183,6 +187,23 @@ export class SearchResultsStateService { return null; } + + /** The searched keywords with their topic colour, for the snippet marks. */ + readonly keywordColors = computed(() => + Array.from(this.keywordTopicMap(), ([keyword, topic]) => ({ + keyword, + color: topicHierarchyColor({ + id: topic.id, + name: topic.display_name, + field_id: topic.field?.id, + field_name: topic.field?.display_name, + domain_id: topic.domain?.id, + domain_name: topic.domain?.display_name, + }), + topicNames: topic.display_name ? [topic.display_name] : [], + })), + ); + // Parallel topic-name list for trend dashboard strategies. Entries // without a resolvable keyword are skipped when building the lookup map // so they can never collide on an `undefined` key and shadow a real one. diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts index 13077372..f7c0760a 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts @@ -78,11 +78,13 @@ export class KeywordsToWorksResultsComponent implements OnInit { readonly snippetSegments = computed(() => { const byWorkId = new Map(); + const keywordColors = this.state.keywordColors(); + for (const work of this.elements()) { if (!work.id || !work.snippet) { continue; } - byWorkId.set(work.id, splitSnippet(work.snippet)); + byWorkId.set(work.id, splitSnippet(work.snippet, keywordColors)); } return byWorkId; diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss index 5eabaa09..5a25d88c 100644 --- a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss +++ b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss @@ -7,12 +7,15 @@ } .snippet-mark { - background: transparent; - color: var(--sg-blue-highlight); - font-weight: 700; + background: var(--sg-highlight-mark-bg); + border-radius: 2px; + padding: 0 1px; &.has-topic { + background: transparent; + padding: 0; color: var(--t); + font-weight: 700; text-decoration: underline; text-decoration-color: var(--t); text-decoration-thickness: 2px; diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index b37e0340..1885b80f 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -130,6 +130,9 @@ body { --sg-radius-lg: 18px; --sg-blue-highlight: #3d7cff; + /* Backdrop for a keyword match that resolved to no topic. Topic-bound matches carry + their topic's colour instead. */ + --sg-highlight-mark-bg: rgba(255, 214, 0, 0.35); --sg-default-bold-weight: 900; /* Additional Design Tokens for Dark Mode Support */ @@ -507,7 +510,7 @@ html.dark-theme { } /* highlighted text */ .app-highlight-mark { - background-color: rgba(255, 214, 0, 0.35); + background-color: var(--sg-highlight-mark-bg); border-radius: 2px; padding: 0 1px; } -- 2.56.1 From 2878667727acbab52bc1640f85ba3c44e830c925 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 17:26:17 +0200 Subject: [PATCH 09/12] feat(works-keyword-search): match keyword highlighting approach --- .../news-results/news-results.component.ts | 58 +---- .../search-results-state.service.ts | 60 +++-- .../works-results.component.html | 59 +++-- .../works-results.component.scss | 38 ---- .../works-results/works-results.component.ts | 24 +- .../app/resolvers/utils/keyword-highlight.ts | 214 ------------------ .../snippet-text/snippet-text.component.html | 16 -- .../snippet-text/snippet-text.component.scss | 28 --- .../ui/snippet-text/snippet-text.component.ts | 43 ---- 9 files changed, 96 insertions(+), 444 deletions(-) delete mode 100644 webapp/src/app/resolvers/utils/keyword-highlight.ts delete mode 100644 webapp/src/app/shared/ui/snippet-text/snippet-text.component.html delete mode 100644 webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss delete mode 100644 webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts 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 7a304133..8efe6b23 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 @@ -30,7 +30,10 @@ import { } from '../../../../shared/ui/query-param-selector/query-param-selector.component'; import { NEWS_MIN_YEAR } from '../../../../shared/ui/news-card/news-card.component'; import { keywordsNewsQueryParamKeys } from '../../../../resolvers/keywords-news-page.resolver'; -import { SearchResultsStateService } from '../search-results-state.service'; +import { + SearchResultsStateService, + SnippetHighlight, +} from '../search-results-state.service'; import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component'; import { CANCEL_ICON, @@ -49,11 +52,6 @@ import { TableDetailRowComponent } from '../../../../shared/ui/table-detail-row/ type NewsResult = NewsPage['results'][number]; -interface SnippetHighlight { - content: string; - terms: HighlightTerm[]; -} - @Component({ selector: 'app-news-results', imports: [ @@ -254,9 +252,11 @@ export class KeywordsToNewsResultsComponent { const byArticleId = new Map(); for (const article of this.elements()) { - const snippet = this.buildSnippetHighlight(article); - if (snippet) { - byArticleId.set(article.id, snippet); + if (article.snippet) { + byArticleId.set( + article.id, + this.state.snippetHighlight(article.snippet), + ); } } @@ -272,51 +272,13 @@ export class KeywordsToNewsResultsComponent { containsHighlightTerm(article.maintitle, [keyword]), ); if (found.length) { - byArticleId.set(article.id, this.toHighlightTerms(found)); + byArticleId.set(article.id, this.state.highlightTerms(found)); } } return byArticleId; }); - private buildSnippetHighlight(article: NewsResult): SnippetHighlight | null { - const snippet = article.snippet; - if (!snippet) { - return null; - } - - return { - content: snippet.replace(/<\/?em>/g, ''), - terms: this.toHighlightTerms([ - ...this.state.keywords(), - ...this.markedTerms(snippet), - ]), - }; - } - - 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 result: HighlightTerm[] = []; - - for (const raw of terms) { - const term = raw.trim(); - const key = term.toLowerCase(); - if (!term || seen.has(key)) { - continue; - } - seen.add(key); - result.push({ term, topic: this.state.resolveTopicForTerm(term) }); - } - - return result; - } - readonly hasSnippet = (article: NewsResult): boolean => !!article.snippet; isTopicsExpanded(article: NewsResult): boolean { diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index 08aa1bd1..e4ba48c8 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -1,13 +1,15 @@ import { Injectable, computed, signal } from '@angular/core'; import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic'; import { Topic } from '../../../api'; -import { KeywordColor } from '../../../resolvers/utils/keyword-highlight'; -import { - topicHierarchyColor, - TopicHierarchyColorInput, -} from '../../../resolvers/utils/topic-colors'; +import { HighlightTerm } from '../../../shared/ui/highlighted-text/highlighted-text.component'; +import { TopicHierarchyColorInput } from '../../../resolvers/utils/topic-colors'; export type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom'; +export interface SnippetHighlight { + content: string; + terms: HighlightTerm[]; +} + export interface PatentKeywordEntry { entry: KeywordEntryWithTopic; level: KeywordPatentLevel; @@ -188,21 +190,39 @@ export class SearchResultsStateService { return null; } - /** The searched keywords with their topic colour, for the snippet marks. */ - readonly keywordColors = computed(() => - Array.from(this.keywordTopicMap(), ([keyword, topic]) => ({ - keyword, - color: topicHierarchyColor({ - id: topic.id, - name: topic.display_name, - field_id: topic.field?.id, - field_name: topic.field?.display_name, - domain_id: topic.domain?.id, - domain_name: topic.domain?.display_name, - }), - topicNames: topic.display_name ? [topic.display_name] : [], - })), - ); + /** + * Splits an Elasticsearch snippet into the text to show and the terms to + * mark in it: the searched keywords, plus whatever the search marked with + * that catches the inflected forms the analyzer found. + */ + public snippetHighlight(snippet: string): SnippetHighlight { + const marked = [...snippet.matchAll(/([\s\S]*?)<\/em>/g)].map((match) => + match[1].trim(), + ); + + return { + content: snippet.replace(/<\/?em>/g, ''), + terms: this.highlightTerms([...this.keywords(), ...marked]), + }; + } + + /** Pairs each term with the topic it resolved to; the first spelling wins. */ + public highlightTerms(terms: readonly string[]): HighlightTerm[] { + const seen = new Set(); + const result: HighlightTerm[] = []; + + for (const raw of terms) { + const term = raw.trim(); + const key = term.toLowerCase(); + if (!term || seen.has(key)) { + continue; + } + seen.add(key); + result.push({ term, topic: this.resolveTopicForTerm(term) }); + } + + return result; + } // Parallel topic-name list for trend dashboard strategies. Entries // without a resolvable keyword are skipped when building the lookup map diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index d9711a68..447b0fae 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -6,30 +6,41 @@ [showTopicFilter]="fuzzySearch()" /> -
- @if (snippetSegments().get(work.id); as segments) { - - Fundstelle im {{ snippetSourceLabel(work) }} - - - } @else if (work.matched_via?.length) { - Kein Treffer im Text -

- Das gesuchte Keyword kommt weder im Titel noch im Abstract vor. Die - Publikation wurde über - {{ work.matched_via!.length === 1 ? 'das Thema' : 'die Themen' }} - @for (name of work.matched_via; track name; let last = $last) { - {{ name }}{{ last ? '' : ', ' }} - } - gefunden. -

- } @else { - - Für diese Publikation liegt keine Fundstelle vor. - - } -
+ +
+

Fundstelle in der Publikation

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

{{ snippetSourceLabel(work) }}

+ +
+ } @else if (work.matched_via?.length) { +
+

Kein Treffer im Text

+

+ Das gesuchte Keyword kommt weder im Titel noch im Abstract vor. + Die Publikation wurde über + {{ work.matched_via!.length === 1 ? 'das Thema' : 'die Themen' }} + @for (name of work.matched_via; track name; let last = $last) { + {{ name }}{{ last ? '' : ', ' }} + } + gefunden. +

+
+ } @else { + + Für diese Publikation liegt keine Fundstelle vor. + + } +
+
this.queryParamMap().get('fuzzy') === 'true'); - readonly snippetSegments = computed(() => { - const byWorkId = new Map(); - - const keywordColors = this.state.keywordColors(); + readonly snippetHighlights = computed(() => { + const byWorkId = new Map(); for (const work of this.elements()) { - if (!work.id || !work.snippet) { - continue; + if (work.id && work.snippet) { + byWorkId.set(work.id, this.state.snippetHighlight(work.snippet)); } - byWorkId.set(work.id, splitSnippet(work.snippet, keywordColors)); } return byWorkId; diff --git a/webapp/src/app/resolvers/utils/keyword-highlight.ts b/webapp/src/app/resolvers/utils/keyword-highlight.ts deleted file mode 100644 index d0879a84..00000000 --- a/webapp/src/app/resolvers/utils/keyword-highlight.ts +++ /dev/null @@ -1,214 +0,0 @@ -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 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 interface SnippetSegment { - text: string; - isSearchMatch: boolean; - match: KeywordColor | null; - groupHasMatch: boolean; -} - -export function splitSnippet( - snippet: string, - keywordColors: readonly KeywordColor[] = [], -): SnippetSegment[] { - const searchMatch = /([\s\S]*?)<\/em>/g; - const segments: SnippetSegment[] = []; - - let lastIndex = 0; - let match: RegExpExecArray | null; - - const pushPlain = (raw: string) => { - const text = decodeHtml(raw); - if (text) { - segments.push({ - text, - isSearchMatch: false, - match: null, - groupHasMatch: false, - }); - } - }; - - while ((match = searchMatch.exec(snippet)) !== null) { - pushPlain(snippet.slice(lastIndex, match.index)); - - const parts = splitByKeywords(decodeHtml(match[1]), keywordColors); - const groupHasMatch = parts.some((part) => part.match); - - for (const part of parts) { - segments.push({ - text: part.text, - isSearchMatch: true, - match: part.match, - groupHasMatch, - }); - } - - lastIndex = searchMatch.lastIndex; - } - - pushPlain(snippet.slice(lastIndex)); - - return segments; -} - -export function decodeHtml(text: string): string { - return text - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/"/g, '"') - .replace(/&#(?:39|x27);/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()) - ); -} diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html deleted file mode 100644 index 6f39bd6d..00000000 --- a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html +++ /dev/null @@ -1,16 +0,0 @@ -

- @for (segment of rendered(); track $index) { - @if (segment.isSearchMatch) { - {{ segment.text }} - } @else { - {{ segment.text }} - } - } -

diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss deleted file mode 100644 index 5a25d88c..00000000 --- a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss +++ /dev/null @@ -1,28 +0,0 @@ -.snippet { - margin: 0; - font-size: 12.5px; - line-height: 1.6; - color: var(--sg-text-secondary); - overflow-wrap: anywhere; -} - -.snippet-mark { - background: var(--sg-highlight-mark-bg); - border-radius: 2px; - padding: 0 1px; - - &.has-topic { - background: transparent; - padding: 0; - color: var(--t); - font-weight: 700; - text-decoration: underline; - text-decoration-color: var(--t); - text-decoration-thickness: 2px; - text-underline-offset: 2px; - } -} - -:host(.has-tooltips) .snippet-mark { - cursor: help; -} diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts deleted file mode 100644 index a9e1e3a3..00000000 --- a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Component, computed, input } from '@angular/core'; -import { MatTooltipModule } from '@angular/material/tooltip'; - -import { - keywordTooltip, - SnippetSegment, -} from '../../../resolvers/utils/keyword-highlight'; - -@Component({ - host: { - '[class.has-tooltips]': 'showTooltips()', - }, - selector: 'app-snippet-text', - imports: [MatTooltipModule], - templateUrl: './snippet-text.component.html', - styleUrl: './snippet-text.component.scss', -}) -export class SnippetTextComponent { - segments = input.required(); - - showTooltips = input(false); - - protected readonly rendered = computed(() => - this.segments().map((segment) => ({ - text: segment.text, - isSearchMatch: segment.isSearchMatch, - color: segment.match?.color ?? null, - tooltip: this.tooltipFor(segment), - })), - ); - - private tooltipFor(segment: SnippetSegment): string { - if (!this.showTooltips() || !segment.isSearchMatch) { - return ''; - } - - if (segment.match) { - return keywordTooltip(segment.match.keyword, segment.match.topicNames); - } - - return segment.groupHasMatch ? '' : keywordTooltip(segment.text, []); - } -} -- 2.56.1 From ab87b87072a0eafebaa6b29605f3d06d734a9b87 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 17:45:32 +0200 Subject: [PATCH 10/12] fix(data-table): fill full background in extended row --- .../src/app/shared/ui/data-table/data-table.component.scss | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.scss b/webapp/src/app/shared/ui/data-table/data-table.component.scss index c4b41c87..202491d4 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.scss +++ b/webapp/src/app/shared/ui/data-table/data-table.component.scss @@ -18,6 +18,11 @@ tr.detail-row { height: 0 !important; } +.detail-row .mat-mdc-cell { + padding: 0; + border-bottom: none; +} + .detail-row-wrapper { overflow: hidden; display: flex; -- 2.56.1 From 05eb4c49f71e865b1ce2f62ef344d392ccc6a546 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 18:27:32 +0200 Subject: [PATCH 11/12] refactor(news-/works-keyword-search): extract snippet logic --- service/src/main/inse/news/logic.py | 130 ++-------------------- service/src/main/inse/snippets.py | 125 +++++++++++++++++++++ service/src/main/inse/works/v2/service.py | 26 +++-- 3 files changed, 151 insertions(+), 130 deletions(-) create mode 100644 service/src/main/inse/snippets.py diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 2cc1b6fb..fce81993 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -4,7 +4,6 @@ Business logic for the "aktuell" news index on the INSE cluster. """ import logging -import re from pydantic import ValidationError @@ -12,6 +11,12 @@ from inse.exceptions import ElasticsearchException from ..integrations import elasticsearch, llm from ..persons.logic import find_ude_author_by_name, get_author_name_by_id +from ..snippets import ( + FRAGMENT_FIELD, + HIGHLIGHT_TAGS, + SNIPPET_FRAGMENT_CHARS, + snippet_with_context, +) from ..topics.logic import vector_search_topics_batch from .model import ( MatchedTopic, @@ -31,29 +36,16 @@ 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, + **FRAGMENT_FIELD, "no_match_size": SNIPPET_FRAGMENT_CHARS, } }, - "pre_tags": [""], - "post_tags": [""], + **HIGHLIGHT_TAGS, "require_field_match": False, } @@ -774,7 +766,7 @@ def _parse_hit(hit: dict) -> NewsArticle: fragments = hit.get("highlight", {}).get("full_content") if fragments: - snippet = _snippet_with_context(source, fragments) + snippet = snippet_with_context(source.get("full_content"), fragments) else: snippet = _make_preview(source) @@ -788,110 +780,6 @@ 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("full_content") or source.get("intro_content") diff --git a/service/src/main/inse/snippets.py b/service/src/main/inse/snippets.py new file mode 100644 index 00000000..0d8d662a --- /dev/null +++ b/service/src/main/inse/snippets.py @@ -0,0 +1,125 @@ +import re + +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) + +_SENTENCE_BREAK = re.compile(r"(?"], "post_tags": ["
"]} + + +def snippet_with_context(text: str | None, fragments: list) -> str: + joined = SNIPPET_FRAGMENT_SEPARATOR.join(fragments) + 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 = _SENTENCE_BREAK.search(text, start, min(limit, start + SNIPPET_BOUNDARY_CHARS)) + if ahead: + return ahead.end() + + behind_from = max(0, start - SNIPPET_BOUNDARY_CHARS) + behind = list(_SENTENCE_BREAK.finditer(text, behind_from, start)) + if behind: + return behind[-1].end() + + if behind_from == 0: + return 0 + + space = text.find(" ", start, start + SNIPPET_BOUNDARY_CHARS) + return space + 1 if space >= 0 else start + + +def _back_to_boundary(text: str, end: int, floor: int) -> int: + + sentence = _SENTENCE_BREAK.search(text, end, end + SNIPPET_BOUNDARY_CHARS) + if sentence: + return sentence.start() + + 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) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 5d9630bc..8309edf9 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -6,6 +6,12 @@ from inse.exceptions import ElasticsearchNotFoundException, NotFoundException from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex, SortDirection from inse.models.openalex.work import Work +from inse.snippets import ( + FRAGMENT_FIELD, + HIGHLIGHT_TAGS, + WHOLE_FIELD, + snippet_with_context, +) from inse.works.v2.model import ( PrimaryCategoryYearAggregation, PrimaryCategoryYearAggregationPage, @@ -378,12 +384,10 @@ async def get_works_by_keywords( # back only for the works that really do carry the phrase. highlight={ "fields": { - "title": {"number_of_fragments": 0}, - "abstract": {"fragment_size": 240, "number_of_fragments": 1}, + "title": WHOLE_FIELD, + "abstract": FRAGMENT_FIELD, }, - "pre_tags": [""], - "post_tags": [""], - "encoder": "html", + **HIGHLIGHT_TAGS, }, cluster=ESCluster.NES, ) @@ -414,10 +418,14 @@ def _keyword_snippet(hit: dict) -> tuple[str | None, str | None]: """Picks the passage to show for a hit, preferring the title over the abstract.""" highlight = hit.get("highlight") or {} - for field in ("title", "abstract"): - fragments = highlight.get(field) - if fragments: - return fragments[0], field + title_fragments = highlight.get("title") + if title_fragments: + return title_fragments[0], "title" + + abstract_fragments = highlight.get("abstract") + if abstract_fragments: + abstract = (hit.get("_source") or {}).get("abstract") + return snippet_with_context(abstract, abstract_fragments), "abstract" return None, None -- 2.56.1 From 27433efe72cb3047597684eabba44200a5ff9c0e Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 21:48:49 +0200 Subject: [PATCH 12/12] feat(news-keyword-search): add search bar --- service/src/main/inse/news/logic.py | 4 + service/src/main/inse/news/service.py | 5 ++ webapp/src/app/api/api/news.service.ts | 20 +++++ .../news-results/news-results.component.html | 77 +++++++++++-------- .../news-results/news-results.component.scss | 14 +++- .../news-results/news-results.component.ts | 5 ++ .../resolvers/keywords-news-page.resolver.ts | 3 + 7 files changed, 92 insertions(+), 36 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index fce81993..453323bb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -154,6 +154,7 @@ async def search_news_by_keywords( year_to: int | None = None, relevance_values: list | None = None, sort_order: str | None = None, + title: str | None = None, ) -> NewsPage: """Searches the news for the keywords of a keywords-search run. @@ -189,6 +190,9 @@ async def search_news_by_keywords( return _empty_page(page, page_size) clauses = await _filter_clauses(year_from, year_to, relevance_values) + if title and title.strip(): + clauses.append({"match_phrase_prefix": {"maintitle": title.strip()}}) + query = { "bool": { "should": should, diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index eeeeb564..bfc6d105 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -147,6 +147,10 @@ async def search_news_by_keywords( pattern="^(asc|desc)$", ), ] = None, + title: Annotated[ + str | None, + Query(description="Narrows the results to articles whose title matches this text."), + ] = None, ): return await logic.search_news_by_keywords( keywords=keywords or [], @@ -159,6 +163,7 @@ async def search_news_by_keywords( year_from=year_from, year_to=year_to, relevance_values=_parse_relevance(relevance), + title=title, ) diff --git a/webapp/src/app/api/api/news.service.ts b/webapp/src/app/api/api/news.service.ts index 6d7a4c53..b789f410 100644 --- a/webapp/src/app/api/api/news.service.ts +++ b/webapp/src/app/api/api/news.service.ts @@ -563,6 +563,7 @@ export class NewsService extends BaseService { * @param yearFrom Earliest publication year (inclusive). * @param yearTo Latest publication year (inclusive). * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @param title Narrows the results to articles whose title matches this text. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ @@ -577,6 +578,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -596,6 +598,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -615,6 +618,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -634,6 +638,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -705,6 +710,11 @@ export class NewsService extends BaseService { sortOrder, 'sortOrder', ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); let localVarHeaders = this.defaultHeaders; @@ -769,6 +779,7 @@ export class NewsService extends BaseService { * @param yearFrom Earliest publication year (inclusive). * @param yearTo Latest publication year (inclusive). * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @param title Narrows the results to articles whose title matches this text. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ @@ -783,6 +794,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -802,6 +814,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -821,6 +834,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -840,6 +854,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -911,6 +926,11 @@ export class NewsService extends BaseService { sortOrder, 'sortOrder', ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); let localVarHeaders = this.defaultHeaders; 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 3b70ae04..d1cb0a6e 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 @@ -1,42 +1,51 @@
- - + - - +
+ + - - + + - @if (hasActiveFilters()) { - - } + + + + @if (hasActiveFilters()) { + + } +
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 f6fa92de..9823e13b 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 @@ -9,10 +9,20 @@ ============================================================ */ .filters { display: flex; - flex-wrap: wrap; - align-items: stretch; + flex-direction: column; gap: 0.75rem; + .title-field { + width: 100%; + } + + .filter-row { + display: flex; + flex-wrap: wrap; + align-items: stretch; + gap: 0.75rem; + } + .relevance-field, .sort-order-field { min-width: 200px; 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 8efe6b23..76ca5ea6 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 @@ -21,6 +21,7 @@ import { GenericColumn, } from '../../../../shared/ui/data-table/data-table.component'; import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component'; +import { QueryParamInputComponent } from '../../../../shared/ui/query-param-input/query-param-input.component'; import { AppTopicChipComponent } from '../../../../shared/ui/app-topic-chip/app-topic-chip.component'; import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component'; import { FilterCardComponent } from '../../../../shared/ui/filter-card/filter-card.component'; @@ -66,6 +67,7 @@ type NewsResult = NewsPage['results'][number]; ChipOverflowToggleComponent, FilterCardComponent, QueryParamPaginatorComponent, + QueryParamInputComponent, QueryParamSelectorComponent, YearRangeSliderComponent, ], @@ -138,6 +140,7 @@ export class KeywordsToNewsResultsComponent { !!params.get(keywordsNewsQueryParamKeys.yearFrom) || !!params.get(keywordsNewsQueryParamKeys.yearTo) || !!params.get(keywordsNewsQueryParamKeys.sortOrder) || + !!params.get(keywordsNewsQueryParamKeys.title) || this.selectedTopicIds().length > 0 ); }); @@ -148,6 +151,7 @@ export class KeywordsToNewsResultsComponent { !!params.get(keywordsNewsQueryParamKeys.relevance) || !!params.get(keywordsNewsQueryParamKeys.yearFrom) || !!params.get(keywordsNewsQueryParamKeys.yearTo) || + !!params.get(keywordsNewsQueryParamKeys.title) || this.selectedTopicIds().length > 0 ); }); @@ -330,6 +334,7 @@ export class KeywordsToNewsResultsComponent { [keywordsNewsQueryParamKeys.yearTo]: null, [keywordsNewsQueryParamKeys.topicId]: null, [keywordsNewsQueryParamKeys.sortOrder]: null, + [keywordsNewsQueryParamKeys.title]: null, [keywordsNewsQueryParamKeys.page]: 0, }, queryParamsHandling: 'merge', diff --git a/webapp/src/app/resolvers/keywords-news-page.resolver.ts b/webapp/src/app/resolvers/keywords-news-page.resolver.ts index a347122c..c8515505 100644 --- a/webapp/src/app/resolvers/keywords-news-page.resolver.ts +++ b/webapp/src/app/resolvers/keywords-news-page.resolver.ts @@ -12,6 +12,7 @@ export const keywordsNewsQueryParamKeys = { yearTo: 'yearTo', topicId: 'topicId', sortOrder: 'sorting_order', + title: 'title', } as const; const emptyPage = (page: number, pageSize: number): NewsPage => ({ @@ -47,6 +48,7 @@ export const keywordsNewsPageResolver: ResolveFn = (route) => { const sortOrder = parseSortOrder( params.get(keywordsNewsQueryParamKeys.sortOrder), ); + const title = params.get(keywordsNewsQueryParamKeys.title) || undefined; return inject(NewsService).getNewsByKeywords( keywords, @@ -59,6 +61,7 @@ export const keywordsNewsPageResolver: ResolveFn = (route) => { yearFrom, yearTo, sortOrder, + title, ); }; -- 2.56.1