From 32d1e27fc5d1b86ca44fc33b8b190ebd421f2e72 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 22 Aug 2026 20:21:47 +0200 Subject: [PATCH 01/29] Add top person subtitles --- .../app/modules/dashboard/dashboard.component.html | 3 +++ .../src/app/modules/dashboard/dashboard.component.ts | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index ffa6554d..85acf5fb 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -519,6 +519,9 @@ {{ dataset.icon }}{{ dataset.title }} +

+ {{ dataset.subtitle }} +

@for ( entry of dataset.entries; track entry.id || entry.name; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 827c12fe..2c08b53c 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -69,6 +69,7 @@ type DashboardStatisticKey = | 'dfg_projects'; type TopAuthorDataset = { title: string; + subtitle: string; icon: string; entries: TopAuthor[]; stripAuthorTitle?: boolean; @@ -276,27 +277,37 @@ export class DashboardComponent implements OnInit, AfterViewInit { return [ { title: 'Publikationen', + subtitle: + 'Top 10 Personen mit Publikationen der ausgewählten Institution. Die Zahl zeigt die Anzahl der Publikationen der jeweiligen Person.', icon: MENU_BOOK_ICON, entries: this.topAuthors?.works ?? [], }, { title: 'EU-Projekte', + subtitle: + 'Top 10 Personen, die an EU-Projekten der ausgewählten Institution beteiligt sind. Die Zahl zeigt, an wie vielen EU-Projekten die jeweilige Person beteiligt ist.', icon: PUBLIC_ICON, entries: this.topAuthors?.eu_projects ?? [], }, { title: 'Patente', + subtitle: + 'Top 10 Personen mit Zuordnung zu Patenten der ausgewählten Institution. Die Zahl zeigt, wie vielen Patenten die jeweilige Person zugeordnet wurde.', icon: DESCRIPTION_ICON, entries: this.topAuthors?.patents ?? [], }, { title: 'DFG Projekte', + subtitle: + 'Top 10 Personen, die an DFG-Projekten der ausgewählten Institution beteiligt sind. Die Zahl zeigt, an wie vielen DFG-Projekten die jeweilige Person beteiligt ist.', icon: ACCOUNT_TREE_ICON, entries: this.topAuthors?.projects ?? [], stripAuthorTitle: true, }, { title: 'News', + subtitle: + 'Top 10 Personen der ausgewählten Institution, die in Nachrichten genannt werden. Die Zahl zeigt, in wie vielen Nachrichten die jeweilige Person vorkommt.', icon: ARTICLE_ICON, entries: this.topAuthors?.news ?? [], }, From ad1e789e8e9bda50cb5ff0331c3d17e4ca46f72f Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Sat, 22 Aug 2026 20:22:06 +0200 Subject: [PATCH 02/29] Style top person subtitles --- .../src/app/modules/dashboard/dashboard.component.scss | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 6df707ba..448825c5 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -381,11 +381,18 @@ display: flex; align-items: center; gap: 0.5rem; - margin: 0 0 1rem; + margin: 0; color: var(--sg-text); } } + .top-authors-chart-subtitle { + margin: 0.35rem 0 1rem; + color: var(--sg-text-muted); + font-size: 13px; + line-height: 1.45; + } + .author-bar-row { display: flex; align-items: center; From d8de0c2156d6c7939fe8a81ef6c69a0c4471ae76 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 23 Aug 2026 16:46:37 +0200 Subject: [PATCH 03/29] changed person-card to use global institution chip --- .../person-card/person-card.component.html | 53 ++------- .../person-card/person-card.component.scss | 105 ------------------ .../person-card/person-card.component.ts | 28 +---- 3 files changed, 11 insertions(+), 175 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.html b/webapp/src/app/modules/person-card/person-card.component.html index 21633c95..1f8906ee 100644 --- a/webapp/src/app/modules/person-card/person-card.component.html +++ b/webapp/src/app/modules/person-card/person-card.component.html @@ -51,52 +51,13 @@
@if (institution(); as inst) {
- +
} diff --git a/webapp/src/app/modules/person-card/person-card.component.scss b/webapp/src/app/modules/person-card/person-card.component.scss index fb46ab44..da6232db 100644 --- a/webapp/src/app/modules/person-card/person-card.component.scss +++ b/webapp/src/app/modules/person-card/person-card.component.scss @@ -136,111 +136,6 @@ overflow: hidden; text-overflow: ellipsis; } -.institution { - display: flex; - align-items: center; - gap: 6px; - margin: 0; - font-size: 12px; - color: var(--sg-text-muted); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.institution-tag { - background: var(--sg-primary-soft); - border: 1px solid var(--sg-primary-border, var(--sg-border)); - color: var(--sg-primary); - font-size: 10px; - font-weight: 600; - padding: 2px 6px; - border-radius: 4px; - cursor: pointer; - display: inline-flex; - align-items: center; - transition: all 0.2s ease; - max-width: 100%; - box-sizing: border-box; - margin: 0; - line-height: normal; - font-family: inherit; - - .institution-name { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - min-width: 0; - flex: 1; - } - - app-country-flag { - flex-shrink: 0; - } - - .country-code { - display: inline-block; - flex-shrink: 0; - white-space: nowrap; - } - - .institution-open-icon { - flex-shrink: 0; - width: 12px; - height: 12px; - margin-left: 5px; - font-size: 12px; - line-height: 1; - vertical-align: middle; - cursor: pointer; - opacity: 0; - transition: opacity 0.15s ease; - - &:hover { - opacity: 1; - } - } - - &:hover .institution-open-icon { - opacity: 0.7; - - &:hover { - opacity: 1; - } - } - - &:hover, - &:focus-visible { - background: var(--sg-primary); - color: var(--sg-background); - border-color: var(--sg-primary); - outline: none; - box-shadow: - 0 0 0 2px var(--sg-background), - 0 0 0 4px var(--sg-primary); - } - - &.active { - border-color: var(--sg-primary); - box-shadow: - 0 0 0 1px var(--sg-background), - 0 0 0 3px var(--sg-primary); - } - - &.active:hover, - &.active:focus-visible { - background: var(--sg-primary); - color: var(--sg-background); - } - - &.is-loading { - pointer-events: none; - background: var(--sg-surface-soft); - border-color: var(--sg-border); - color: var(--sg-text-soft); - box-shadow: none; - } -} .person-id { margin: 2px 0 0; diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 0dacd32e..14a3cfe2 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -1,20 +1,18 @@ -import { Component, inject, input, computed, output } from '@angular/core'; +import { Component, input, computed, output } from '@angular/core'; import { CommonModule } from '@angular/common'; -import { Router, RouterLink } from '@angular/router'; +import { RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; import { SkTextDirective } from '../../custom-directives/sk-text.directive'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; -import { CountryFlagComponent } from '../../shared/ui/country-flag/country-flag.component'; +import { AppInstitutionChipComponent } from '../../shared/ui/app-institution-chip/app-institution-chip.component'; import { CareerStageChipComponent } from '../../shared/ui/career-stage-chip/career-stage-chip.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { - APARTMENT_ICON, BOOKMARK_BORDER_ICON, BOOKMARK_ICON, NETWORK_ICON, - OPEN_IN_NEW_ICON, OVERVIEW_ICON, PUBLICATION_ICON, } from '../../shared/ui/icons'; @@ -29,7 +27,7 @@ import { SkTextDirective, MatTooltipModule, TopicChipComponent, - CountryFlagComponent, + AppInstitutionChipComponent, CareerStageChipComponent, ], templateUrl: './person-card.component.html', @@ -38,14 +36,10 @@ import { export class PersonCardComponent { readonly BOOKMARK_ICON = BOOKMARK_ICON; readonly BOOKMARK_BORDER_ICON = BOOKMARK_BORDER_ICON; - readonly APARTMENT_ICON = APARTMENT_ICON; - readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON; readonly OVERVIEW_ICON = OVERVIEW_ICON; readonly PUBLICATION_ICON = PUBLICATION_ICON; readonly NETWORK_ICON = NETWORK_ICON; - private readonly router = inject(Router); - person = input.required(); isBookmarked = input(false); loading = input(false); @@ -89,20 +83,6 @@ export class PersonCardComponent { return newestInstitution; }); - institutionPageId = computed( - () => this.institution()?.id?.split('/').pop() ?? null, - ); - - openInstitutionPage(event: Event): void { - event.stopPropagation(); - event.preventDefault(); - - const id = this.institutionPageId(); - if (!id) return; - - void this.router.navigate(['/institution', id]); - } - isInstitutionActive = computed(() => { const active = this.normalizeInstitutionId(this.activeInstitutionId()); if (!active) return false; From a21d5eaea4ba5352104490ef9e535287437139c4 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 23 Aug 2026 17:06:20 +0200 Subject: [PATCH 04/29] changed other hardcoded icon values to variables --- webapp/src/app/modules/dashboard/dashboard.component.html | 4 ++-- webapp/src/app/modules/dashboard/dashboard.component.ts | 5 +++++ .../institution-patents/institution-patents.component.html | 4 ++-- .../keywords-patents/keywords-patents.component.html | 2 +- .../app/modules/person-funding/person-funding.component.html | 4 ++-- .../app/modules/person-patents/person-patents.component.html | 2 +- .../query-param-selector/query-param-selector.component.html | 2 +- .../ui/searchable-select/searchable-select.component.html | 2 +- .../app/shared/ui/source-filter/source-filter.component.html | 2 +- 9 files changed, 16 insertions(+), 11 deletions(-) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index ffa6554d..8629679a 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -205,7 +205,7 @@ [disabled]="!canScrollAnalyticalInstitutionTabsLeft" aria-label="Vorherige Institutionen anzeigen" (click)="scrollAnalyticalInstitutionTabs(-1)"> - chevron_left + {{ CHEVRON_LEFT_ICON }}
- chevron_right + {{ CHEVRON_RIGHT_ICON }}
@if (dashboardInstitutionsError) { diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 827c12fe..bc185919 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -20,6 +20,8 @@ import { ACCOUNT_BALANCE_ICON, ACCOUNT_TREE_ICON, ARTICLE_ICON, + CHEVRON_LEFT_ICON, + CHEVRON_RIGHT_ICON, DESCRIPTION_ICON, GROUPS_ICON, MENU_BOOK_ICON, @@ -102,6 +104,9 @@ export class DashboardComponent implements OnInit, AfterViewInit { readonly AuthorTooltipComponent = AppAuthorTooltipComponent; readonly patentIcon = PATENT_ICON; + readonly PATENT_ICON = PATENT_ICON; + readonly CHEVRON_LEFT_ICON = CHEVRON_LEFT_ICON; + readonly CHEVRON_RIGHT_ICON = CHEVRON_RIGHT_ICON; readonly MENU_BOOK_ICON = MENU_BOOK_ICON; readonly GROUPS_ICON = GROUPS_ICON; readonly PUBLIC_ICON = PUBLIC_ICON; diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html index 3a3a40d8..ed0ff933 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.html +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -25,7 +25,7 @@ - + {{ RULE_ICON }} @@ -42,7 +42,7 @@ - + {{ SORT_ICON }} diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 9de1f52e..bfb93778 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -19,7 +19,7 @@ - + {{ SORT_ICON }} diff --git a/webapp/src/app/modules/person-funding/person-funding.component.html b/webapp/src/app/modules/person-funding/person-funding.component.html index f968c24d..cecb84c9 100644 --- a/webapp/src/app/modules/person-funding/person-funding.component.html +++ b/webapp/src/app/modules/person-funding/person-funding.component.html @@ -17,7 +17,7 @@ - + {{ FILTER_ICON }} @@ -31,7 +31,7 @@ - + {{ SORT_ICON }} diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 1ee63846..ceb0e87d 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -19,7 +19,7 @@ - + {{ SORT_ICON }} diff --git a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html index ad4e23c8..9cd5dfb4 100644 --- a/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html +++ b/webapp/src/app/shared/ui/query-param-selector/query-param-selector.component.html @@ -3,7 +3,7 @@ {{ label() }} } @if (icon()) { - + {{ icon() }} } @if (icon()) { - + {{ icon() }} } - + {{ FILTER_ICON }} From 767f532e6f09a68dcde5f1b614e2efb884fbc4e7 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 23 Aug 2026 17:15:56 +0200 Subject: [PATCH 05/29] removed old unused components --- .../uni-line-chart.component.html | 5 -- .../uni-line-chart.component.scss | 4 -- .../uni-line-chart.component.ts | 69 ------------------- .../uni-ranking-table.component.html | 42 ----------- .../uni-ranking-table.component.scss | 0 .../uni-ranking-table.component.ts | 21 ------ 6 files changed, 141 deletions(-) delete mode 100644 webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html delete mode 100644 webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.scss delete mode 100644 webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts delete mode 100644 webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.html delete mode 100644 webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.scss delete mode 100644 webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.ts diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html deleted file mode 100644 index 059525c8..00000000 --- a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html +++ /dev/null @@ -1,5 +0,0 @@ -
diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.scss b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.scss deleted file mode 100644 index f51d8c68..00000000 --- a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.scss +++ /dev/null @@ -1,4 +0,0 @@ -.chart-container { - height: 500px; - width: 100%; -} diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts deleted file mode 100644 index cb123796..00000000 --- a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { - Component, - ChangeDetectionStrategy, - input, - computed, -} from '@angular/core'; -import { EChartsOption } from 'echarts'; -import { NgxEchartsDirective } from 'ngx-echarts'; -import { UniversityTopicData } from '../../../api'; - -export type DashboardMetric = 'publications' | 'citations'; - -@Component({ - selector: 'app-university-line-chart', - templateUrl: './uni-line-chart.component.html', - styleUrl: './uni-line-chart.component.scss', - imports: [NgxEchartsDirective], - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class UniversityLineChartComponent { - readonly data = input(null); - readonly metric = input('publications'); - - readonly chartOption = computed(() => { - const rawData = this.data(); - if (!rawData || rawData.length === 0) { - return {}; - } - - const years = rawData[0].yearly_data.map((d) => d.year); - const chosenMetric = this.metric(); - - const series = rawData.map((uni) => ({ - name: uni.university, - type: 'line', - smooth: true, - emphasis: { focus: 'series' }, - animationDuration: 2000, - data: uni.yearly_data.map((d) => { - if (chosenMetric === 'citations') { - return d.citations || 0; - } - return d.publications || 0; - }), - })); - - return { - title: { - text: 'Research Output Over Time', - left: 'center', - textStyle: { fontWeight: 'lighter' }, - }, - tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, - legend: { bottom: 0 }, - grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }, - xAxis: { - type: 'category', - boundaryGap: false, - data: years.map(String), - }, - yAxis: { - type: 'value', - name: chosenMetric === 'citations' ? 'Citations' : 'Publications', - }, - dataZoom: [{ type: 'slider', show: true, bottom: 40 }], - series: series as any, - }; - }); -} diff --git a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.html b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.html deleted file mode 100644 index 99da5bcb..00000000 --- a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.html +++ /dev/null @@ -1,42 +0,0 @@ -
-

Topic Rankings

- @if (loading) { -
Loading rankings...
- } @else { - - - - - - - - - - - - @for (row of rankings; track $index) { - - - - - - - - } - -
RankUniversityLatest5Y GrowthTrend
#{{ row.rank }} - {{ row.university }} - @if (row.is_top_mover) { - 🔥 - } - {{ row.publications | number }} - {{ row.growth_rate | number: '1.0-1' }}% - - {{ getTrendIcon(row.trend) }} -
- } -
diff --git a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.scss b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.scss deleted file mode 100644 index e69de29b..00000000 diff --git a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.ts b/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.ts deleted file mode 100644 index 05db1334..00000000 --- a/webapp/src/app/modules/university-ranking/uni-ranking-table/uni-ranking-table.component.ts +++ /dev/null @@ -1,21 +0,0 @@ -// src/app/modules/university-ranking/components/ranking-table/university-ranking-table.component.ts -import { Component, Input } from '@angular/core'; -import { UniversityRanking } from '../../../api'; -import { DecimalPipe } from '@angular/common'; - -@Component({ - selector: 'app-university-ranking-table', - templateUrl: './uni-ranking-table.component.html', - styleUrls: ['./uni-ranking-table.component.scss'], - imports: [DecimalPipe], -}) -export class UniversityRankingTableComponent { - @Input() rankings: UniversityRanking[] = []; - @Input() loading: boolean = false; - - getTrendIcon(trend: string): string { - if (trend === 'up') return '↑'; - if (trend === 'down') return '↓'; - return '→'; - } -} From 9440605a6f87a02044d0a8222a9a4e82bcb0d86c Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 13:32:04 +0200 Subject: [PATCH 06/29] 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, From 84073854bf650f68cf341473b56f1298f7c14a88 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 14:49:36 +0200 Subject: [PATCH 07/29] 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); } From 50ff313a57a0b4abf449f9910cbe293b77355e6a Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 16:32:47 +0200 Subject: [PATCH 08/29] 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, '\\$&'); } From a1889f13f6fe2187e4cc250523e78f76dec3410a Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 24 Aug 2026 18:23:55 +0200 Subject: [PATCH 09/29] consolidated same icons, created transient helper component to identify icons --- webapp/src/app/app.routes.ts | 7 ++++ .../icon-preview/icon-preview.component.html | 10 ++++++ .../icon-preview/icon-preview.component.scss | 34 +++++++++++++++++++ .../icon-preview/icon-preview.component.ts | 24 +++++++++++++ webapp/src/app/shared/ui/icons.ts | 11 +++--- 5 files changed, 81 insertions(+), 5 deletions(-) create mode 100644 webapp/src/app/modules/icon-preview/icon-preview.component.html create mode 100644 webapp/src/app/modules/icon-preview/icon-preview.component.scss create mode 100644 webapp/src/app/modules/icon-preview/icon-preview.component.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 43d09f3f..44bafe3d 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -72,6 +72,13 @@ export const routes: Routes = [ pathMatch: 'full', redirectTo: 'dashboard', }, + { + path: 'icons', + loadComponent: () => + import('./modules/icon-preview/icon-preview.component').then( + (mod) => mod.IconPreviewComponent, + ), + }, { path: 'login', loadComponent: () => diff --git a/webapp/src/app/modules/icon-preview/icon-preview.component.html b/webapp/src/app/modules/icon-preview/icon-preview.component.html new file mode 100644 index 00000000..754d2185 --- /dev/null +++ b/webapp/src/app/modules/icon-preview/icon-preview.component.html @@ -0,0 +1,10 @@ +
+ @for (item of icons; track item.constName) { +
+ {{ item.iconString }} + {{ item.iconString }} +
+ } +
diff --git a/webapp/src/app/modules/icon-preview/icon-preview.component.scss b/webapp/src/app/modules/icon-preview/icon-preview.component.scss new file mode 100644 index 00000000..08adab01 --- /dev/null +++ b/webapp/src/app/modules/icon-preview/icon-preview.component.scss @@ -0,0 +1,34 @@ +.icon-container { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); + gap: 4px; + padding: 8px; + box-sizing: border-box; +} + +.icon-item { + display: flex; + align-items: center; + gap: 6px; + padding: 3px 6px; + border: 1px solid #e2e8f0; + border-radius: 4px; + background: #ffffff; + font-family: monospace; + font-size: 11px; + color: #1e293b; + overflow: hidden; + white-space: nowrap; + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + flex-shrink: 0; + } + + .name { + overflow: hidden; + text-overflow: ellipsis; + } +} diff --git a/webapp/src/app/modules/icon-preview/icon-preview.component.ts b/webapp/src/app/modules/icon-preview/icon-preview.component.ts new file mode 100644 index 00000000..5a2a96c8 --- /dev/null +++ b/webapp/src/app/modules/icon-preview/icon-preview.component.ts @@ -0,0 +1,24 @@ +import { Component } from '@angular/core'; +import { MatIconModule } from '@angular/material/icon'; +import * as ALL_ICONS from '../../shared/ui/icons'; + +@Component({ + selector: 'app-icon-preview', + standalone: true, + imports: [MatIconModule], + templateUrl: './icon-preview.component.html', + styleUrl: './icon-preview.component.scss', +}) +export class IconPreviewComponent { + readonly icons = Object.entries(ALL_ICONS) + .filter(([key, val]) => typeof val === 'string' && key.endsWith('_ICON')) + .map(([constName, iconString]) => ({ + constName, + iconString: iconString as string, + })) + .sort( + (a, b) => + a.iconString.localeCompare(b.iconString) || + a.constName.localeCompare(b.constName), + ); +} diff --git a/webapp/src/app/shared/ui/icons.ts b/webapp/src/app/shared/ui/icons.ts index d89491d4..f2528650 100644 --- a/webapp/src/app/shared/ui/icons.ts +++ b/webapp/src/app/shared/ui/icons.ts @@ -28,7 +28,8 @@ export const PERSON_OFF_ICON = 'person_off' as const; // person off and no accou export const ACCOUNT_BALANCE_ICON = FUNDING_ICON; // TODO export const ACCOUNT_CIRCLE_ICON = 'account_circle' as const; //Person Icon in company-connections -export const COMPANY_CONNECTION_ICON = 'business' as const; +export const BUSINESS_ICON = 'business' as const; +export const COMPANY_CONNECTION_ICON = BUSINESS_ICON; // TODO // ============================================================================ // 2. Navigation, Layout & Hierarchy Icons @@ -72,8 +73,8 @@ export const MANAGE_ACCOUNTS_ICON = 'manage_accounts' as const; export const MANAGE_SEARCH_ICON = 'manage_search' as const; export const PERSON_ADD_ICON = 'person_add' as const; export const PERSON_SEARCH_ICON = 'person_search' as const; -export const PLAY_ARROW_ICON = 'play_arrow' as const; export const PLAY_ICON = 'play_arrow' as const; +export const PLAY_ARROW_ICON = PLAY_ICON; // TODO export const REFRESH_ICON = 'refresh' as const; export const RESTART_ICON = 'restart_alt' as const; export const SAVE_ICON = 'save' as const; @@ -111,7 +112,7 @@ export const INFO_OUTLINE_ICON = 'info_outline' as const; // same as info but in export const RULE_ICON = 'rule' as const; export const STAR_ICON = 'star' as const; export const VERIFIED_ICON = 'verified' as const; -export const VISIBILITY_ICON = 'visibility' as const; +export const VISIBILITY_ICON = OVERVIEW_ICON; // TODO export const VISIBILITY_OFF_ICON = 'visibility_off' as const; export const WARNING_ICON = 'warning' as const; @@ -139,13 +140,13 @@ export const TRENDING_UP_ICON = 'trending_up' as const; // ============================================================================ // 7. Other // ============================================================================ -export const APARTMENT_ICON = 'apartment' as const; +export const APARTMENT_ICON = FUNDING_ICON; // TODO export const ARTICLE_ICON = PUBLICATION_ICON; // was 'article' (TODO change in some components like dashboard) export const ASSIGNMENT_ICON = 'assignment' as const; export const ATTACH_MONEY_ICON = 'attach_money' as const; export const BIOTECH_ICON = 'biotech' as const; export const BUILD_ICON = 'build' as const; -export const BUSINESS_ICON = 'business' as const; + export const BUSINESS_CENTER_ICON = 'business_center' as const; export const CAMPAIGN_ICON = 'campaign' as const; export const CATEGORY_ICON = 'category' as const; From 6609b64076844ed8e32237289c54d1cd8f0dcd99 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 24 Aug 2026 21:06:03 +0200 Subject: [PATCH 10/29] fixed wrong fuzzy search toggler behaviour on navigating --- .../search-results.component.ts | 37 ++++++++----------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts index 1588a49a..e2928df0 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts @@ -80,8 +80,8 @@ export class KeywordsSearchResultsComponent { path: 'persons', queryParams: { keywords: this.state.payload()?.keywords?.join(','), - fuzzy: this.tabFuzzyValue('persons'), - topics: this.tabFuzzyValue('persons') ? this.state.topicIds() : null, + fuzzy: this.currentFuzzy(), + topics: this.currentFuzzy() ? this.state.topicIds() : null, topicId: null, }, queryParamsHandling: 'replace', @@ -93,8 +93,8 @@ export class KeywordsSearchResultsComponent { path: 'projects', queryParams: { keywords: this.state.payload()?.keywords?.join(','), - fuzzy: this.tabFuzzyValue('projects'), - topics: this.tabFuzzyValue('projects') ? this.state.topicIds() : null, + fuzzy: this.currentFuzzy(), + topics: this.currentFuzzy() ? this.state.topicIds() : null, topicId: null, }, queryParamsHandling: 'replace', @@ -106,8 +106,8 @@ export class KeywordsSearchResultsComponent { path: 'patents', queryParams: { keywords: this.state.payload()?.keywords?.join(','), - fuzzy: this.tabFuzzyValue('patents'), - topics: this.tabFuzzyValue('patents') ? this.state.topicIds() : null, + fuzzy: this.currentFuzzy(), + topics: this.currentFuzzy() ? this.state.topicIds() : null, topicId: null, }, queryParamsHandling: 'replace', @@ -119,8 +119,8 @@ export class KeywordsSearchResultsComponent { path: 'works', queryParams: { keywords: this.state.payload()?.keywords?.join(','), - fuzzy: this.tabFuzzyValue('works'), - topics: this.tabFuzzyValue('works') ? this.state.topicIds() : null, + fuzzy: this.currentFuzzy(), + topics: this.currentFuzzy() ? this.state.topicIds() : null, topicId: null, }, queryParamsHandling: 'replace', @@ -132,8 +132,8 @@ export class KeywordsSearchResultsComponent { path: 'news', queryParams: { keywords: this.state.payload()?.keywords?.join(','), - fuzzy: this.tabFuzzyValue('news'), - topics: this.tabFuzzyValue('news') ? this.state.topicIds() : null, + fuzzy: this.currentFuzzy(), + topics: this.currentFuzzy() ? this.state.topicIds() : null, topicId: null, }, queryParamsHandling: 'replace', @@ -145,8 +145,8 @@ export class KeywordsSearchResultsComponent { path: 'trends', queryParams: { keywords: this.state.payload()?.keywords?.join(','), - fuzzy: this.tabFuzzyValue('trends'), - topics: this.tabFuzzyValue('trends') ? this.state.topicIds() : null, + fuzzy: this.currentFuzzy(), + topics: this.currentFuzzy() ? this.state.topicIds() : null, topicId: null, }, queryParamsHandling: 'replace', @@ -156,7 +156,9 @@ export class KeywordsSearchResultsComponent { return links; }); - private readonly lastUserFuzzy = signal(false); + private currentFuzzy(): boolean { + return this.route.snapshot.queryParamMap.get('fuzzy') === 'true'; + } readonly selectedKeywordCount = computed(() => this.state.keywords().length); readonly allKeywordEntries = computed(() => { @@ -198,15 +200,6 @@ export class KeywordsSearchResultsComponent { }); } - // the Fuzzy Search toggle is locked on while the Personen tab is active - isPersonsTab(): boolean { - return this.route.snapshot.firstChild?.routeConfig?.path === 'persons'; - } - - tabFuzzyValue(path: string): boolean { - if (path === 'persons') return true; - return this.lastUserFuzzy(); - } goBackToSearch(): void { void this.router.navigate(['/keywords'], { queryParamsHandling: 'merge', From 2f509fbbfee2ddbd24d84873c2fd05a3721aca4d Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sat, 15 Aug 2026 19:44:04 +0200 Subject: [PATCH 11/29] 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() From 56ada07d97e1fdcb21ecd2f9e36ded91f331500d Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sat, 15 Aug 2026 21:46:29 +0200 Subject: [PATCH 12/29] 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, []); + } +} From 3f4b032e345beab1502260a5168e621c0f7ab11d Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 10:41:05 +0200 Subject: [PATCH 13/29] 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, '\\$&'); } From 1482e3fdc540de88a38368442eb252272fae0f1c Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 11:44:14 +0200 Subject: [PATCH 14/29] 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; } From 1bfa0f113d65fe0f730bba087473ee806bcacbd5 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 11:50:51 +0200 Subject: [PATCH 15/29] 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 16/29] 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 17/29] 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 // ------------------------ From 68f1cae4d9e9d85cf35bd43736535978a63107b1 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sun, 16 Aug 2026 13:57:32 +0200 Subject: [PATCH 18/29] 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; } From 2878667727acbab52bc1640f85ba3c44e830c925 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 17:26:17 +0200 Subject: [PATCH 19/29] 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, []); - } -} From ab87b87072a0eafebaa6b29605f3d06d734a9b87 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 17:45:32 +0200 Subject: [PATCH 20/29] 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; From 05eb4c49f71e865b1ce2f62ef344d392ccc6a546 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 18:27:32 +0200 Subject: [PATCH 21/29] 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 From 27433efe72cb3047597684eabba44200a5ff9c0e Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 24 Aug 2026 21:48:49 +0200 Subject: [PATCH 22/29] 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, ); }; From eb61f1a8b0381a4dbe5a9d5b76688c93fad567f0 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 25 Aug 2026 01:09:24 +0200 Subject: [PATCH 23/29] feat(auth): validate password reset links --- service/src/main/inse/auth/router.py | 19 +++ service/src/main/inse/auth/service.py | 61 ++++++--- .../src/main/inse/auth/test_auth_service.py | 62 +++++++++ webapp/src/app/api/.openapi-generator/FILES | 1 + webapp/src/app/api/api/auth.service.ts | 120 ++++++++++++++++++ .../model/bodyValidatePasswordResetToken.ts | 16 +++ webapp/src/app/api/model/models.ts | 1 + .../reset-password.component.html | 10 ++ .../reset-password.component.ts | 20 +++ .../app/shared/services/credential.service.ts | 11 ++ 10 files changed, 303 insertions(+), 18 deletions(-) create mode 100644 webapp/src/app/api/model/bodyValidatePasswordResetToken.ts diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 378be6fc..c23d69d0 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -61,6 +61,25 @@ async def request_password_reset( return auth_service.request_password_reset(session=session, email=email) +@router.post( + "/validate-password-reset-token", + summary="Validate Password Reset Token", + description="Validate a password reset token without consuming it.", + operation_id="validatePasswordResetToken", + responses={status.HTTP_200_OK: {"description": "Password reset token is valid."}}, +) +async def validate_password_reset_token( + session: SessionDep, + reset_token: Annotated[ + str, Body(embed=True, description="Password reset token from the reset link") + ], +) -> dict[str, bool]: + return auth_service.validate_password_reset_token( + session=session, + reset_token=reset_token, + ) + + @router.post( "/reset-password", summary="Reset Password", diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index e7ec3d48..8418b33f 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -442,24 +442,8 @@ def request_password_reset(session: Session, email: str) -> dict[str, Any]: } -def reset_password( - session: Session, - reset_token: str, - new_password: str, -) -> dict[str, str]: - """Resets an account password using a one-time password reset token. - - Args: - session (Session): The database session used to query the account and secret. - reset_token (str): The raw reset token from the password reset link. - new_password (str): The new password to store for the account. - - Raises: - HTTPException: If the reset token is invalid or expired. - - Returns: - Dict[str, str]: A status response. - """ +def _valid_password_reset_secret(session: Session, reset_token: str) -> Secret: + """Return the valid password-reset secret without consuming it.""" now = datetime.datetime.now(datetime.UTC) reset_token_hash = _hash_reset_token(reset_token.strip()) @@ -498,6 +482,47 @@ def reset_password( detail="Invalid or expired password reset token", ) + return secret + + +def validate_password_reset_token( + session: Session, + reset_token: str, +) -> dict[str, bool]: + """Validate a password-reset token without consuming it.""" + _valid_password_reset_secret(session, reset_token) + return {"valid": True} + + +def reset_password( + session: Session, + reset_token: str, + new_password: str, +) -> dict[str, str]: + """Resets an account password using a one-time password reset token. + + Args: + session (Session): The database session used to query the account and secret. + reset_token (str): The raw reset token from the password reset link. + new_password (str): The new password to store for the account. + + Raises: + HTTPException: If the reset token is invalid or expired. + + Returns: + Dict[str, str]: A status response. + """ + secret = _valid_password_reset_secret(session, reset_token) + account = session.get(Account, secret.account_id) + + # _valid_password_reset_secret already checked the account. Keep the guard + # for type narrowing and to avoid relying on an assertion in production. + if account is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired password reset token", + ) + account.password_hash = _hash_password(new_password) account.epoch += 1 diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index a02e0a0f..db35c6ce 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -817,6 +817,68 @@ def test_reset_password_changes_password_and_increments_epoch(in_memory_session) assert deleted_secret is None +def test_validate_password_reset_token_does_not_consume_token(in_memory_session): + email = "validate-reset@example.com" + password = "oldpw123" + _, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + reset_token = "valid-token-to-check" + secret = Secret( + account_id=acc.id, + purpose=SecretPurpose.PASSWORD_RESET, + secret_value=auth_service._hash_reset_token(reset_token), + expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5), + ) + in_memory_session.add(secret) + in_memory_session.commit() + + assert auth_service.validate_password_reset_token( + in_memory_session, reset_token + ) == {"valid": True} + + result = auth_service.reset_password( + in_memory_session, + reset_token=reset_token, + new_password="NewPassword123", + ) + assert result == {"status": "ok"} + + +def test_validate_password_reset_token_rejects_invalid_token(in_memory_session): + with pytest.raises(HTTPException) as exc_info: + auth_service.validate_password_reset_token( + in_memory_session, "invalid-token" + ) + + assert exc_info.value.status_code == 401 + + +def test_validate_password_reset_token_rejects_and_deletes_expired_token( + in_memory_session, +): + email = "validate-expired-reset@example.com" + password = "oldpw123" + _, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + reset_token = "expired-token-to-check" + secret = Secret( + account_id=acc.id, + purpose=SecretPurpose.PASSWORD_RESET, + secret_value=auth_service._hash_reset_token(reset_token), + expires_at=_dt.datetime.now(_dt.UTC) - timedelta(minutes=1), + ) + in_memory_session.add(secret) + in_memory_session.commit() + + with pytest.raises(HTTPException) as exc_info: + auth_service.validate_password_reset_token(in_memory_session, reset_token) + + assert exc_info.value.status_code == 401 + assert in_memory_session.get(Secret, secret.id) is None + + def test_reset_password_rejects_reused_token(in_memory_session): email = "reuse-reset@example.com" password = "oldpw123" diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 8c7da681..3f8e63e4 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -69,6 +69,7 @@ model/bodyLogin.ts model/bodyRequestOtk.ts model/bodyRequestPasswordReset.ts model/bodyResetPassword.ts +model/bodyValidatePasswordResetToken.ts model/bundInstitutionSummary.ts model/bundInstitutionSummaryPage.ts model/bundProjectDetails.ts diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 535c7da5..e8a5b735 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -43,6 +43,8 @@ import { BodyRequestPasswordReset } from '../model/bodyRequestPasswordReset'; // @ts-ignore import { BodyResetPassword } from '../model/bodyResetPassword'; // @ts-ignore +import { BodyValidatePasswordResetToken } from '../model/bodyValidatePasswordResetToken'; +// @ts-ignore import { CreateAccountRequest } from '../model/createAccountRequest'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -1929,4 +1931,122 @@ export class AuthService extends BaseService { }, ); } + + /** + * Validate Password Reset Token + * Validate a password reset token without consuming it. + * @endpoint post /api/auth/v2/validate-password-reset-token + * @param bodyValidatePasswordResetToken + * @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. + */ + public validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable<{ [key: string]: boolean | null }>; + public validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + bodyValidatePasswordResetToken === null || + bodyValidatePasswordResetToken === undefined + ) { + throw new Error( + 'Required parameter bodyValidatePasswordResetToken was null or undefined when calling validatePasswordResetToken.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/auth/v2/validate-password-reset-token`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request<{ [key: string]: boolean | null }>( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyValidatePasswordResetToken, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/model/bodyValidatePasswordResetToken.ts b/webapp/src/app/api/model/bodyValidatePasswordResetToken.ts new file mode 100644 index 00000000..a91ed455 --- /dev/null +++ b/webapp/src/app/api/model/bodyValidatePasswordResetToken.ts @@ -0,0 +1,16 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface BodyValidatePasswordResetToken { + /** + * Password reset token from the reset link + */ + reset_token: string; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 49619f6b..9929cf3c 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -35,6 +35,7 @@ export * from './bodyLogin'; export * from './bodyRequestOtk'; export * from './bodyRequestPasswordReset'; export * from './bodyResetPassword'; +export * from './bodyValidatePasswordResetToken'; export * from './bundInstitutionSummary'; export * from './bundInstitutionSummaryPage'; export * from './bundProjectDetails'; diff --git a/webapp/src/app/modules/reset-password/reset-password.component.html b/webapp/src/app/modules/reset-password/reset-password.component.html index bf4fc4f9..5a4964b5 100644 --- a/webapp/src/app/modules/reset-password/reset-password.component.html +++ b/webapp/src/app/modules/reset-password/reset-password.component.html @@ -69,6 +69,16 @@ Zurück zum Login
+ } @else if (isCheckingLink()) { + } @else {
+ @@ -84,7 +90,7 @@ { + this.funderSearch = params.get('funderSearch') ?? ''; + this.funderPageIndex = this.parsePageIndexParam(params.get('funderPage')); + this.funderPageSize = this.parsePageSizeParam(params.get('funderSize')); + }); + this.route.parent?.paramMap.subscribe((params) => { const authorId = params.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); @@ -130,6 +143,8 @@ export class PersonFundingComponent implements OnInit { const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir'); this.initialSelectedFunderKey = this.route.snapshot.queryParamMap.get('funder'); + this.funderSearch = + this.route.snapshot.queryParamMap.get('funderSearch') ?? ''; this.initialFunderPageIndex = this.parsePageIndexParam( this.route.snapshot.queryParamMap.get('funderPage'), ); @@ -161,7 +176,7 @@ export class PersonFundingComponent implements OnInit { this.funderPageIndex = this.clampPageIndex( this.initialFunderPageIndex, this.funderPageSize, - this.filteredFunders.length, + this.getDisplayedFunders().length, ); this.restoreSelectedFunderFromUrl(); this.loading = false; @@ -228,14 +243,15 @@ export class PersonFundingComponent implements OnInit { return; } - const matchedFunder = this.filteredFunders.find( + const displayedFunders = this.getDisplayedFunders(); + const matchedFunder = displayedFunders.find( (funder: any) => this.getFunderKey(funder) === this.initialSelectedFunderKey, ); if (matchedFunder) { this.selectedFunder = matchedFunder; - const matchedIndex = this.filteredFunders.findIndex( + const matchedIndex = displayedFunders.findIndex( (funder: any) => this.getFunderKey(funder) === this.getFunderKey(matchedFunder), ); @@ -266,6 +282,7 @@ export class PersonFundingComponent implements OnInit { : null, funderPage: this.funderPageIndex, funderSize: this.funderPageSize, + funderSearch: this.funderSearch || null, pubPage: this.selectedFunder ? this.publicationPageIndex : null, pubSize: this.selectedFunder ? this.publicationPageSize : null, }, @@ -322,14 +339,22 @@ export class PersonFundingComponent implements OnInit { return funder.publication_ids[this.activeFilter] ?? []; } - getPagedFunders(): any[] { - const startIndex = this.funderPageIndex * this.funderPageSize; - return this.filteredFunders.slice( - startIndex, - startIndex + this.funderPageSize, + getDisplayedFunders(): any[] { + const search = this.funderSearch.trim().toLowerCase(); + if (!search) { + return this.filteredFunders; + } + return this.filteredFunders.filter((funder: any) => + (funder.funder_name ?? '').toLowerCase().includes(search), ); } + getPagedFunders(): any[] { + const displayed = this.getDisplayedFunders(); + const startIndex = this.funderPageIndex * this.funderPageSize; + return displayed.slice(startIndex, startIndex + this.funderPageSize); + } + getSelectedPublicationIdsPage(): string[] { if (!this.selectedFunder) { return []; diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 16bfad24..8a1b214f 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -31,6 +31,11 @@ + + { + this.patentSearch = params.get('patentSearch') ?? ''; + this.pageIndex = this.parsePageIndexParam(params.get('page')); + this.pageSize = this.parsePageSizeParam(params.get('size')); + }); + this.route.parent?.data .pipe( switchMap((data) => { @@ -196,6 +209,7 @@ export class PersonPatentsComponent { sortDir: this.sortDirection, page: this.pageIndex, size: this.pageSize, + patentSearch: this.patentSearch || null, }, queryParamsHandling: 'merge', replaceUrl: true, @@ -226,9 +240,20 @@ export class PersonPatentsComponent { return value === 'asc' || value === 'desc'; } + getDisplayedPatents(): PatentEntry[] { + const search = this.patentSearch.trim().toLowerCase(); + if (!search) { + return this.filteredPatents; + } + return this.filteredPatents.filter((patent) => + (patent.title ?? patent.patent_id ?? '').toLowerCase().includes(search), + ); + } + getPagedPatents(): PatentEntry[] { + const displayed = this.getDisplayedPatents(); const start = this.pageIndex * this.pageSize; - return this.filteredPatents.slice(start, start + this.pageSize); + return displayed.slice(start, start + this.pageSize); } formatDate(date: string | null | undefined): string { 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..8da95cde 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 @@ -7,7 +7,7 @@ [dataSource]="dataSource" matSort (matSortChange)="_handleSortChange($event)" - multiTemplateDataRows> + [multiTemplateDataRows]="!!detailTemplate()"> @for (col of columns(); track col.id) { @if (col.headerTemplate) { @@ -36,22 +36,22 @@ } - - - @if (row === expandedElement() && detailTemplate()) { - @if (detailTemplate(); as tpl) { + @if (detailTemplate()) { + + + @if (row === expandedElement() && detailTemplate(); as tpl) { } - } - - + + + } - + @if (detailTemplate()) { + + } @if (this.dataSource.filteredData.length === 0) {
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..705fc197 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 @@ -4,6 +4,22 @@ .mat-mdc-table { background-color: var(--sg-background); + width: 100%; +} + +.mat-mdc-header-cell, +.mat-mdc-cell { + padding: 12px 16px; +} + +.mat-mdc-header-cell:first-of-type, +.mat-mdc-cell:first-of-type { + padding-left: 16px; +} + +.mat-mdc-header-cell:last-of-type, +.mat-mdc-cell:last-of-type { + padding-right: 16px; } .no-data { @@ -27,3 +43,7 @@ tr.detail-row { background: var(--sg-surface-soft); cursor: pointer; } + +.element-row.selected { + background: #f0f0f0; +} 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..ced1a5fd 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 @@ -54,6 +54,8 @@ export class DataTableComponent implements AfterViewInit { detailTemplate = input | null>(null); expandedElement = signal(null); + selectedRow = input(null); + rowClick = output(); maxHeight = input(null); containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible')); @@ -161,7 +163,12 @@ export class DataTableComponent implements AfterViewInit { } toggleRow(row: T): void { + this.rowClick.emit(row); if (!this.detailTemplate()) return; this.expandedElement.update((current) => (current === row ? null : row)); } + + isSelectedRow(row: T): boolean { + return this.selectedRow() === row; + } } From 99dbd3ba47e38e6932fbdb967e0c2fc36765f232 Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 25 Aug 2026 08:19:10 +0200 Subject: [PATCH 28/29] build error (fix): increase initial bundle budget --- webapp/angular.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/angular.json b/webapp/angular.json index dadf2610..4e6e27de 100644 --- a/webapp/angular.json +++ b/webapp/angular.json @@ -34,7 +34,7 @@ { "type": "initial", "maximumWarning": "1500kb", - "maximumError": "2mb" + "maximumError": "3mb" }, { "type": "anyComponentStyle", From 4c8255e600332d74f392caec77553ce3812e9b8c Mon Sep 17 00:00:00 2001 From: Khalti Date: Tue, 25 Aug 2026 10:05:58 +0200 Subject: [PATCH 29/29] feat(patents): keyword search matches title/abstract via Elasticsearch highlighting, plus server-side pagination and colored keyword matches like DFG projects --- service/src/main/inse/patents/common/model.py | 3 + .../src/main/inse/patents/common/parsing.py | 4 + .../src/main/inse/patents/keywords/logic.py | 298 +++++++++++------- .../src/main/inse/patents/keywords/model.py | 32 ++ .../inse/patents/keywords/search_queries.py | 88 ++++++ .../main/inse/patents/keywords/test_logic.py | 207 +++++------- service/uv.lock | 88 ++++++ .../app/api/model/keywordPatentHighlight.ts | 18 ++ .../src/app/api/model/keywordPatentMatch.ts | 2 + webapp/src/app/api/model/patentEntry.ts | 3 + .../app/api/model/patentsByKeywordsRequest.ts | 22 +- .../api/model/patentsByKeywordsResponse.ts | 12 + .../keywords-patents.component.html | 12 +- .../keywords-patents.component.ts | 156 ++++----- .../keywords-search.component.ts | 3 - .../keywords-search/patent-search.utils.ts | 57 ---- .../patents-results.component.html | 10 +- .../patents-results.component.ts | 146 ++++++--- .../patent-table/patent-table.component.html | 53 ++++ .../ui/patent-table/patent-table.component.ts | 109 ++++++- 20 files changed, 861 insertions(+), 462 deletions(-) create mode 100644 webapp/src/app/api/model/keywordPatentHighlight.ts diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py index e9e9bb26..7dea37c2 100644 --- a/service/src/main/inse/patents/common/model.py +++ b/service/src/main/inse/patents/common/model.py @@ -23,7 +23,10 @@ class PatentEntry(BaseModel): patent_id: str source: str title: str | None = None + title_de: str | None = None + title_en: str | None = None abstract: str | None = None + abstract_lang: str | None = None publication_date: str | None = None publication_year: str | None = None application_number: str | None = None diff --git a/service/src/main/inse/patents/common/parsing.py b/service/src/main/inse/patents/common/parsing.py index 314ca6fa..6489e9ab 100644 --- a/service/src/main/inse/patents/common/parsing.py +++ b/service/src/main/inse/patents/common/parsing.py @@ -35,7 +35,10 @@ def parse_epo_hits(data: dict) -> list[model.PatentEntry]: patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", source="EPO", title=src.get("title_en") or src.get("title_de"), + title_de=src.get("title_de"), + title_en=src.get("title_en"), abstract=src.get("abstract"), + abstract_lang=src.get("abstract_lang"), publication_date=str(src.get("date_publication")) if src.get("date_publication") else None, publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None, application_number=src.get("application_number"), @@ -63,6 +66,7 @@ def parse_uspto_hits(data: dict) -> list[model.PatentEntry]: source="USPTO", title=src.get("title"), abstract=src.get("abstract"), + abstract_lang=src.get("lang"), publication_date=str(src.get("publication_date")) if src.get("publication_date") else None, publication_year=str(src.get("publication_year")) if src.get("publication_year") else None, application_number=src.get("application_number"), diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 138602cb..eeddfcff 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -31,22 +31,19 @@ from inse.patents.ipc_lookup import ( ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( - KeywordPatentMappingStatus, + KeywordPatentHighlight, KeywordPatentMatch, KeywordPatentSearchDiagnostics, KeywordPatentSearchItem, PatentsByKeywordsRequest, PatentsByKeywordsResponse, ) -from inse.patents.keywords.reverse_lookup import ( - IpcCodeMatch, - KeywordIpcReverseLookup, -) +from inse.patents.keywords.reverse_lookup import IpcCodeMatch from inse.patents.keywords.reverse_lookup import ( _topic_group_key as _match_topic_group_key, ) from inse.patents.keywords.search_queries import ( - IpcPatentSearchQueries, + TextPatentSearchQueries, _search_terms_for_symbol, ) from inse.patents.patents_openalex_keywords.ipc_entries import ( @@ -59,7 +56,7 @@ from inse.patents.patents_openalex_keywords.resolver import ( logger = logging.getLogger(__name__) -_MAX_PATENTS = 100 +_MAX_PATENTS = 2000 # Raw mapping candidates before cluster selection (avoid early truncation bias). _MAX_IPC_LOOKUP_CANDIDATES = 200 _MAX_IPC_CODES_PER_KEYWORD = 3 @@ -874,12 +871,16 @@ def _score_patent( ) -async def _fetch_patents_for_queries( +async def _fetch_patents_with_highlights( client: BasePatentSearchClient, epo_query: dict, uspto_query: dict, -) -> list[model.PatentEntry] | None: - """Run EPO+USPTO search. Returns None on configuration/transport failure.""" +) -> tuple[list[model.PatentEntry], dict[str, dict], dict[str, float]] | None: + """Run EPO+USPTO search, keeping each hit's ES highlight and _score + alongside the parsed patent (keyed the same way deduplicate_patents + groups patents), so the caller can trust Elasticsearch's own match + decision instead of re-deriving it in Python. + """ try: epo_data, uspto_data = await asyncio.gather( client.search_epo(epo_query), @@ -892,7 +893,19 @@ async def _fetch_patents_for_queries( logger.warning("Patent search failed: %s", exc) return None - return deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) + epo_patents = parse_epo_hits(epo_data) + uspto_patents = parse_uspto_hits(uspto_data) + + highlights: dict[str, dict] = {} + es_scores: dict[str, float] = {} + for patents, data in ((epo_patents, epo_data), (uspto_patents, uspto_data)): + for patent, hit in zip(patents, data.get("hits", {}).get("hits", [])): + key = patent_map_key(patent) + highlights[key] = hit.get("highlight", {}) + es_scores[key] = hit.get("_score") or 0.0 + + deduped = deduplicate_patents(epo_patents + uspto_patents) + return deduped, highlights, es_scores def _cluster_selection_dicts( @@ -926,6 +939,27 @@ def _empty_diagnostics( ) +def _sort_key_for(sort_by: str | None): + if sort_by == "title": + return lambda item: ( + item.patent.title + or item.patent.title_en + or item.patent.title_de + or "" + ).casefold() + if sort_by == "source": + return lambda item: item.patent.source or "" + if sort_by == "publication_year": + return lambda item: item.patent.publication_date or str( + item.patent.publication_year or "" + ) + return lambda item: ( + item.match_score, + item.patent.publication_date or "", + item.patent.patent_id, + ) + + def _finalize_scored_patents( scored: list[KeywordPatentMatch], *, @@ -935,18 +969,28 @@ def _finalize_scored_patents( filtered_by_min_score: int, passed_relevance_gate: int, search_path: str, + source: str | None = None, + sort_by: str | None = None, + sort_direction: str = "desc", + page: int = 0, + size: int = 10, ipc_cluster_selections: list[dict] | None = None, -) -> tuple[list[KeywordPatentMatch], KeywordPatentSearchDiagnostics]: +) -> tuple[list[KeywordPatentMatch], int, int, int, KeywordPatentSearchDiagnostics]: scored_before_cap = len(scored) - scored.sort( - key=lambda item: ( - item.match_score, - item.patent.publication_date or "", - item.patent.patent_id, - ), - reverse=True, + epo_count = sum(1 for item in scored if item.patent.source == "EPO") + uspto_count = sum(1 for item in scored if item.patent.source == "USPTO") + + filtered = ( + [item for item in scored if item.patent.source == source] + if source + else scored ) - returned = scored[:_MAX_PATENTS] + filtered.sort(key=_sort_key_for(sort_by), reverse=sort_direction != "asc") + + total_count = len(filtered) + start = max(page, 0) * max(size, 1) + page_items = filtered[start : start + max(size, 1)] + diagnostics = KeywordPatentSearchDiagnostics( search_path=search_path, es_query_size_per_index=_MAX_PATENTS, @@ -956,12 +1000,12 @@ def _finalize_scored_patents( filtered_by_min_score=filtered_by_min_score, passed_relevance_gate=passed_relevance_gate, scored_before_cap=scored_before_cap, - returned=len(returned), + returned=len(page_items), max_patents_cap=_MAX_PATENTS, hit_return_cap=scored_before_cap >= _MAX_PATENTS, ipc_cluster_selections=list(ipc_cluster_selections or []), ) - return returned, diagnostics + return page_items, total_count, epo_count, uspto_count, diagnostics async def _score_patents_with_ipc( @@ -1054,26 +1098,95 @@ async def _score_patents_with_ipc( } +_EM_TAG_RE = re.compile(r"(.*?)", re.IGNORECASE) + + +def _extract_highlight_terms(fragments: list[str]) -> list[str]: + """Distinct matched terms out of Elasticsearch highlight fragments + (terms wrapped in ...), like the frontend's extractHighlightTerms. + """ + terms: list[str] = [] + seen: set[str] = set() + for fragment in fragments: + for match in _EM_TAG_RE.finditer(fragment): + term = match.group(1).strip() + key = term.casefold() + if term and key not in seen: + seen.add(key) + terms.append(term) + return terms + + +def _build_matches_from_highlights( + patents: list[model.PatentEntry], + highlights: dict[str, dict], + es_scores: dict[str, float], +) -> list[KeywordPatentMatch]: + """Build matches trusting Elasticsearch's own phrase-prefix decision — + every patent returned by the query already satisfied the OR-search, like + DFG projects. matched_keywords/highlight come from ES's own highlight + fragments (the real matched text span), not a re-derived substring check, + so a short/acronym keyword that only matched as part of a longer word + (e.g. "LRO" inside "LROC") is shown as what actually matched ("LROC"), + never as an invisible, unhighlightable "match". + """ + matches: list[KeywordPatentMatch] = [] + for patent in patents: + key = patent_map_key(patent) + raw_highlight = highlights.get(key, {}) + title_de = raw_highlight.get("title_de") or [] + title_en = (raw_highlight.get("title_en") or []) or ( + raw_highlight.get("title") or [] + ) + abstract = raw_highlight.get("abstract") or [] + highlight = KeywordPatentHighlight( + title_de=title_de, title_en=title_en, abstract=abstract + ) + + matched_keywords = list( + dict.fromkeys( + _extract_highlight_terms(title_de) + + _extract_highlight_terms(title_en) + + _extract_highlight_terms(abstract) + ) + ) + score = round(es_scores.get(key, 0.0), 4) + matches.append( + KeywordPatentMatch( + patent=patent, + match_score=score, + ipc_score=0.0, + topic_score=0.0, + text_score=score, + matched_keywords=matched_keywords, + matched_ipc_symbols=[], + highlight=highlight, + text_retrieval=True, + topic_match_kind=None, + ) + ) + return matches + + async def get_patents_by_keywords( request: PatentsByKeywordsRequest, *, - reverse_lookup: KeywordIpcReverseLookup | None = None, search_client: BasePatentSearchClient | None = None, ipc_client: IpcSearchClient | None = None, - mapping_resolver: PatentOpenAlexMappingResolver | None = None, ) -> PatentsByKeywordsResponse: - lookup = reverse_lookup or KeywordIpcReverseLookup() + """Find patents by matching keywords against patent titles/abstracts. + + Mirrors the DFG project search: each keyword is OR-matched (phrase-prefix) + against title/abstract fields, trusting Elasticsearch's own match and + highlight fragments — no IPC/CPC classification lookup involved. + """ client = search_client or BasePatentSearchClient() ipc_search = ipc_client or IpcSearchClient() - resolver = mapping_resolver or PatentOpenAlexMappingResolver() - queries = IpcPatentSearchQueries() + queries = TextPatentSearchQueries() - search_keywords = _filter_keywords_for_patent_search(request.keywords) - if not search_keywords: - logger.info( - "Keyword patent search: no searchable keywords in %s", - [item.keyword for item in request.keywords], - ) + keywords = [item.keyword.strip() for item in request.keywords if item.keyword.strip()] + if not keywords: + logger.info("Keyword patent search: no keywords in request") return PatentsByKeywordsResponse( patent_count=0, patents=[], @@ -1081,107 +1194,60 @@ async def get_patents_by_keywords( diagnostics=_empty_diagnostics(search_path="none"), ) - logger.info( - "Keyword patent search: using keywords=%s (from %d requested)", - [ - { - "keyword": item.keyword, - "level": item.keyword_level, - "relevance_score": item.relevance_score, - "field_name": item.field_name, - } - for item in search_keywords - ], - len(request.keywords), - ) - keyword_topic_ids, keyword_subfield_names, keyword_soft_field_names = ( - _keyword_overlap_criteria(search_keywords) - ) + logger.info("Keyword patent search (text): keywords=%s", keywords) - raw_ipc_matches = await lookup.lookup_ipc_codes( - search_keywords, - max_codes=_MAX_IPC_LOOKUP_CANDIDATES, - ) - had_usable_mapping = bool(_usable_ipc_matches(raw_ipc_matches)) - ipc_matches, cluster_selections = select_ipc_matches_by_cluster_mass(raw_ipc_matches) - cluster_dicts = _cluster_selection_dicts(cluster_selections) - logger.info( - "Keyword patent search: search_keywords=%s selected_ipc=%s", - [item.keyword for item in search_keywords], - cluster_dicts, - ) - symbols = _patent_search_terms(ipc_matches) - if not symbols: - mapping_status: KeywordPatentMappingStatus = ( - "uncertain" if had_usable_mapping else "no_mapping" - ) - logger.info( - "Keyword patent search: no IPC search terms for keywords %s " - "(mapping_status=%s)", - [item.keyword for item in search_keywords], - mapping_status, - ) - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status=mapping_status, - diagnostics=_empty_diagnostics( - search_path="none", - ipc_cluster_selections=cluster_dicts, - ), - ) - - text_search_terms = _text_search_terms(search_keywords) - logger.info("Keyword patent search: patent_search_terms=%s", symbols) - - raw_patents = await _fetch_patents_for_queries( + raw_result = await _fetch_patents_with_highlights( client, - queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), - queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), + queries.epo_query_by_keywords(keywords, size=_MAX_PATENTS), + queries.uspto_query_by_keywords(keywords, size=_MAX_PATENTS), ) - if raw_patents is None: + if raw_result is None: return PatentsByKeywordsResponse( patent_count=0, patents=[], mapping_status="search_error", - diagnostics=_empty_diagnostics( - search_path="ipc", - ipc_cluster_selections=cluster_dicts, - ), + diagnostics=_empty_diagnostics(search_path="text"), ) - logger.info("Keyword patent search: raw_patents=%d", len(raw_patents)) - scored, filter_counts = await _score_patents_with_ipc( - raw_patents=raw_patents, - ipc_matches=ipc_matches, - text_search_terms=text_search_terms, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - resolver=resolver, - ) - scored, diagnostics = _finalize_scored_patents( - scored, - raw_count=len(raw_patents), - filtered_by_ipc=filter_counts["filtered_by_ipc"], - filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"], - filtered_by_min_score=filter_counts["filtered_by_min_score"], - passed_relevance_gate=filter_counts["passed_relevance_gate"], - search_path="ipc", - ipc_cluster_selections=cluster_dicts, + raw_patents, highlights, es_scores = raw_result + logger.info("Keyword patent search (text): raw_patents=%d", len(raw_patents)) + all_scored = _build_matches_from_highlights(raw_patents, highlights, es_scores) + page_items, total_count, epo_count, uspto_count, diagnostics = ( + _finalize_scored_patents( + all_scored, + raw_count=len(raw_patents), + filtered_by_ipc=0, + filtered_by_relevance_gate=0, + filtered_by_min_score=0, + passed_relevance_gate=len(all_scored), + search_path="text", + source=request.source, + sort_by=request.sort_by, + sort_direction=request.sort_direction, + page=request.page, + size=request.size, + ) ) - if scored: - await enrich_patents_classifications([item.patent for item in scored], ipc_search) + if page_items: + await enrich_patents_classifications( + [item.patent for item in page_items], ipc_search + ) return PatentsByKeywordsResponse( - patent_count=len(scored), - patents=scored, + patent_count=len(page_items), + total_count=total_count, + epo_count=epo_count, + uspto_count=uspto_count, + patents=page_items, mapping_status="mapped", diagnostics=diagnostics, ) return PatentsByKeywordsResponse( patent_count=0, + total_count=total_count, + epo_count=epo_count, + uspto_count=uspto_count, patents=[], mapping_status="no_patents_found", diagnostics=diagnostics, diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py index 978eb46b..2d8bb40f 100644 --- a/service/src/main/inse/patents/keywords/model.py +++ b/service/src/main/inse/patents/keywords/model.py @@ -53,6 +53,20 @@ class PatentsByKeywordsRequest(BaseModel): min_length=1, description="Keywords to match against patents_openalex_keywords.", ) + page: int = Field(default=0, ge=0, description="Zero-based page index.") + size: int = Field(default=10, ge=1, le=100, description="Page size.") + source: str | None = Field( + default=None, + description="Filter to a single source: EPO or USPTO. Omit for both.", + ) + sort_by: str | None = Field( + default=None, + description="title | publication_year | source. Omit to sort by match quality.", + ) + sort_direction: str = Field( + default="desc", + description="asc | desc", + ) class KeywordEvidence(BaseModel): @@ -73,6 +87,14 @@ class KeywordEvidence(BaseModel): ) +class KeywordPatentHighlight(BaseModel): + """Elasticsearch highlight fragments (terms wrapped in ...).""" + + title_de: list[str] = Field(default_factory=list) + title_en: list[str] = Field(default_factory=list) + abstract: list[str] = Field(default_factory=list) + + class KeywordPatentMatch(BaseModel): patent: PatentEntry match_score: float = Field(description="Combined match quality score.") @@ -86,6 +108,10 @@ class KeywordPatentMatch(BaseModel): text_score: float = Field(description="Title/abstract keyword overlap score.") matched_keywords: list[str] = Field(default_factory=list) matched_ipc_symbols: list[str] = Field(default_factory=list) + highlight: KeywordPatentHighlight | None = Field( + default=None, + description="Elasticsearch highlight fragments for title/abstract, like DFG projects.", + ) text_retrieval: bool = Field( default=False, description=( @@ -124,6 +150,12 @@ class KeywordPatentSearchDiagnostics(BaseModel): class PatentsByKeywordsResponse(BaseModel): patent_count: int + total_count: int = Field( + default=0, + description="Total matches across all pages (before page/size slicing).", + ) + epo_count: int = Field(default=0, description="Total EPO matches, unfiltered by source.") + uspto_count: int = Field(default=0, description="Total USPTO matches, unfiltered by source.") patents: list[KeywordPatentMatch] mapping_status: KeywordPatentMappingStatus = Field( description=( diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py index 780e3903..460f1798 100644 --- a/service/src/main/inse/patents/keywords/search_queries.py +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -21,6 +21,7 @@ _PATENT_SOURCE_FIELDS = [ "title_en", "title_de", "abstract", + "abstract_lang", "inventors_name", "applicants_name", "ipc", @@ -39,6 +40,7 @@ _USPTO_SOURCE_FIELDS = [ "status", "title", "abstract", + "lang", "inventors_names", "assignees_orgs", "ipcr", @@ -222,3 +224,89 @@ class IpcPatentSearchQueries: size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size) + + +def _keyword_text_should_clauses( + keywords: list[str], + fields: list[str], +) -> list[dict[str, Any]]: + return [ + { + "multi_match": { + "query": keyword, + "fields": fields, + "type": "phrase_prefix", + "max_expansions": 100, + } + } + for keyword in keywords + if keyword.strip() + ] + + +def _highlight_config( + query: dict[str, Any], + fields: list[str], +) -> dict[str, Any]: + return { + "fragment_size": 200, + "number_of_fragments": 0, + "pre_tags": [""], + "post_tags": [""], + "require_field_match": True, + "fields": {field: {"highlight_query": query} for field in fields}, + } + + +class TextPatentSearchQueries: + """Plain title/abstract keyword search, mirroring the DFG project search.""" + + def epo_query_by_keywords( + self, + keywords: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + fields = ["title_de^4", "title_en^4", "abstract^2"] + should = _keyword_text_should_clauses(keywords, fields) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"date_publication": {"order": "desc", "missing": "_last"}}, + ], + "_source": _PATENT_SOURCE_FIELDS, + "query": query, + "highlight": _highlight_config( + query, ["title_de", "title_en", "abstract"] + ), + } + + def uspto_query_by_keywords( + self, + keywords: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + fields = ["title^4", "abstract^2"] + should = _keyword_text_should_clauses(keywords, fields) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"publication_date": {"order": "desc", "missing": "_last"}}, + ], + "_source": _USPTO_SOURCE_FIELDS, + "query": query, + "highlight": _highlight_config(query, ["title", "abstract"]), + } diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index 5ac08818..355c2d92 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -40,6 +40,7 @@ from inse.patents.keywords.reverse_lookup import ( from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest from inse.patents.keywords.search_queries import ( IpcPatentSearchQueries, + TextPatentSearchQueries, _search_terms_for_symbol, _weighted_search_terms_for_symbol, ) @@ -716,14 +717,32 @@ def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None: assert result is None -def test_get_patents_by_keywords_uses_symbol_queries() -> None: - queries = IpcPatentSearchQueries() +def test_get_patents_by_keywords_matches_title_and_abstract() -> None: + """Retrieval/scoring trusts Elasticsearch's own phrase-prefix match and + highlight fragments, like DFG projects — no Python-side re-verification. + """ + queries = TextPatentSearchQueries() captured: list[str] = [] + epo_hit = { + "_score": 3.5, + "_source": { + "doc_number": "1", + "country": "EP", + "kind": "A1", + "title_de": "Verfahren zur organischen Chemie", + "abstract": "Ein neues Syntheseverfahren.", + }, + "highlight": { + "title_de": ["Verfahren zur organischen Chemie"], + }, + } + async def fake_search_epo(query): captured.append("epo") assert "query" in query - return {"hits": {"hits": []}} + assert "highlight" in query + return {"hits": {"hits": [epo_hit]}} async def fake_search_uspto(query): captured.append("uspto") @@ -732,56 +751,77 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None: request = PatentsByKeywordsRequest( keywords=[ KeywordPatentSearchItem( - keyword="Organische Chemie", + keyword="organischen Chemie", keyword_level="coarse", - topic_id="https://openalex.org/T13859", - field_name="Chemistry", relevance_score=1.0, ) ] ) with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock( - return_value=[ - IpcCodeMatch( - "subgroup", - "C07C243/08", - 0.8989, - "Organische Chemie", - "keyword", - ) - ] - ), - ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", new=AsyncMock(side_effect=fake_search_epo), ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", new=AsyncMock(side_effect=fake_search_uspto), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), ), patch( "inse.patents.keywords.logic.enrich_patents_classifications", new=AsyncMock(), ), patch.object( - IpcPatentSearchQueries, - "epo_query_by_ipc_symbols", - wraps=queries.epo_query_by_ipc_symbols, - ) as epo_symbols, patch.object( - IpcPatentSearchQueries, - "uspto_query_by_ipc_symbols", - wraps=queries.uspto_query_by_ipc_symbols, - ) as uspto_symbols: - asyncio.run(get_patents_by_keywords(request)) + TextPatentSearchQueries, + "epo_query_by_keywords", + wraps=queries.epo_query_by_keywords, + ) as epo_keywords, patch.object( + TextPatentSearchQueries, + "uspto_query_by_keywords", + wraps=queries.uspto_query_by_keywords, + ) as uspto_keywords: + response = asyncio.run(get_patents_by_keywords(request)) - epo_symbols.assert_called_once() - uspto_symbols.assert_called_once() - assert epo_symbols.call_args.args[0][0] == "C07C243/08" - assert "C07C" in epo_symbols.call_args.args[0] + epo_keywords.assert_called_once() + uspto_keywords.assert_called_once() + assert epo_keywords.call_args.args[0] == ["organischen Chemie"] assert captured == ["epo", "uspto"] + assert response.mapping_status == "mapped" + assert response.patent_count == 1 + assert response.patents[0].matched_keywords == ["organischen", "Chemie"] + assert response.patents[0].highlight.title_de == [ + "Verfahren zur organischen Chemie" + ] + assert response.patents[0].match_score == 3.5 + assert response.patents[0].ipc_score == 0.0 + + +def test_get_patents_by_keywords_no_keywords_returns_no_mapping() -> None: + request = PatentsByKeywordsRequest( + keywords=[KeywordPatentSearchItem(keyword=" ", relevance_score=1.0)] + ) + + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_mapping" + assert response.patent_count == 0 + + +def test_get_patents_by_keywords_no_hits_returns_no_patents_found() -> None: + """No search-path re-verification happens anymore — Elasticsearch's own + phrase-prefix query is trusted, so an empty hit list is the only way to + end up with no_patents_found.""" + request = PatentsByKeywordsRequest( + keywords=[KeywordPatentSearchItem(keyword="Quantencomputer", relevance_score=1.0)] + ) + + with patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ): + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_patents_found" + assert response.patent_count == 0 def test_text_search_terms_include_topic_metadata() -> None: @@ -865,28 +905,12 @@ def test_technical_search_failure_returns_search_error_not_no_patents_found() -> KeywordPatentSearchItem( keyword="organische Chemie", keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", relevance_score=1.0, ) ] ) - ipc_matches = [ - IpcCodeMatch( - "subgroup", - "C07C243/08", - 0.90, - "organische Chemie", - "topic", - "TORG", - ) - ] with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=ipc_matches), - ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", new=AsyncMock(side_effect=httpx.HTTPError("boom")), ), patch( @@ -899,87 +923,6 @@ def test_technical_search_failure_returns_search_error_not_no_patents_found() -> assert response.patent_count == 0 -def test_no_ipc_search_terms_returns_without_text_fallback() -> None: - """Without usable IPC symbols the search abstains — no title/abstract path.""" - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - search_epo = AsyncMock(return_value={"hits": {"hits": []}}) - search_uspto = AsyncMock(return_value={"hits": {"hits": []}}) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=search_epo, - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=search_uspto, - ): - response = asyncio.run(get_patents_by_keywords(request)) - - assert response.mapping_status == "no_mapping" - assert response.patent_count == 0 - assert response.patents == [] - search_epo.assert_not_called() - search_uspto.assert_not_called() - - -def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None: - """Fragmented IPC mapping abstains without falling back to text retrieval.""" - fragmented = [ - IpcCodeMatch( - "subgroup", - f"A{index:02d}B1/00", - 0.70, - "organische Chemie", - "topic", - "TORG", - ) - for index in range(1, 16) - ] - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - search_epo = AsyncMock(return_value={"hits": {"hits": []}}) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=fragmented), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=search_epo, - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(return_value={"hits": {"hits": []}}), - ): - response = asyncio.run(get_patents_by_keywords(request)) - - assert response.mapping_status == "uncertain" - assert response.patent_count == 0 - assert response.patents == [] - search_epo.assert_not_called() - - def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None: clear_reverse_lookup_caches() monkeypatch.setattr( diff --git a/service/uv.lock b/service/uv.lock index 2305fae5..3992b104 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -712,6 +712,53 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, ] +[[package]] +name = "pandas" +version = "2.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" }, + { url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" }, + { url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" }, + { url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" }, + { url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" }, + { url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" }, + { url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" }, + { url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671, upload-time = "2025-09-29T23:21:05.024Z" }, + { url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807, upload-time = "2025-09-29T23:21:15.979Z" }, + { url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872, upload-time = "2025-09-29T23:21:27.165Z" }, + { url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371, upload-time = "2025-09-29T23:21:40.532Z" }, + { url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333, upload-time = "2025-09-29T23:21:55.77Z" }, + { url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120, upload-time = "2025-09-29T23:22:10.109Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991, upload-time = "2025-09-29T23:25:04.889Z" }, + { url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227, upload-time = "2025-09-29T23:22:24.343Z" }, + { url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056, upload-time = "2025-09-29T23:22:37.762Z" }, + { url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189, upload-time = "2025-09-29T23:22:51.688Z" }, + { url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912, upload-time = "2025-09-29T23:23:05.042Z" }, + { url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160, upload-time = "2025-09-29T23:23:28.57Z" }, + { url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233, upload-time = "2025-09-29T23:24:24.876Z" }, + { url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635, upload-time = "2025-09-29T23:25:52.486Z" }, + { url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079, upload-time = "2025-09-29T23:26:33.204Z" }, + { url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049, upload-time = "2025-09-29T23:27:15.384Z" }, + { url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638, upload-time = "2025-09-29T23:27:51.625Z" }, + { url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834, upload-time = "2025-09-29T23:28:21.289Z" }, + { url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925, upload-time = "2025-09-29T23:28:58.261Z" }, + { url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071, upload-time = "2025-09-29T23:32:27.484Z" }, + { url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504, upload-time = "2025-09-29T23:29:31.47Z" }, + { url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702, upload-time = "2025-09-29T23:29:54.591Z" }, + { url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535, upload-time = "2025-09-29T23:30:21.003Z" }, + { url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582, upload-time = "2025-09-29T23:30:43.391Z" }, + { url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963, upload-time = "2025-09-29T23:31:10.009Z" }, + { url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175, upload-time = "2025-09-29T23:31:59.173Z" }, +] + [[package]] name = "pluggy" version = "1.6.0" @@ -823,6 +870,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" }, ] +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + [[package]] name = "python-dotenv" version = "1.2.2" @@ -841,6 +900,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8f/cb/769cfc37177252872a45a71f3fbdde9d51b471a3f3c14bfe95dde3407386/python_multipart-0.0.29-py3-none-any.whl", hash = "sha256:2ddcc971cef266225f54f552d8fa10bcfbb1f14446caec199060daac59ff2d69", size = 29640, upload-time = "2026-05-17T17:29:45.69Z" }, ] +[[package]] +name = "pytz" +version = "2026.3.post1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fb/48/fb042503b6ca6cd271261dc559fd6432f7d8c713153e9ec5c591af4dfc1c/pytz-2026.3.post1.tar.gz", hash = "sha256:2211d3fcf9a797d3405cac96ac7f61d80e6a644f72a3309607282fe8a2010c5d", size = 319745, upload-time = "2026-07-25T15:12:07.385Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0f/7b/39c34ca613b0b198cb866466651b26b045e2009864c5183c979a3b83f383/pytz-2026.3.post1-py2.py3-none-any.whl", hash = "sha256:dd95840dd199baea12d9cc096a1d452caa6596a1c1e4b5f3dbd1541855d5e815", size = 508283, upload-time = "2026-07-25T15:12:05.782Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -1143,6 +1211,7 @@ dependencies = [ { name = "fastapi" }, { name = "httpx" }, { name = "openai" }, + { name = "pandas" }, { name = "pydantic" }, { name = "pydantic-settings" }, { name = "pyjwt" }, @@ -1165,6 +1234,7 @@ requires-dist = [ { name = "fastapi", specifier = "~=0.115.0" }, { name = "httpx", specifier = "~=0.27.0" }, { name = "openai", specifier = "~=2.41.0" }, + { name = "pandas", specifier = "~=2.3.3" }, { name = "pydantic", specifier = "~=2.7.1" }, { name = "pydantic-settings", specifier = "~=2.2.1" }, { name = "pyjwt", specifier = "~=2.8.0" }, @@ -1196,6 +1266,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "sniffio" version = "1.3.1" @@ -1441,6 +1520,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] +[[package]] +name = "tzdata" +version = "2026.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" }, +] + [[package]] name = "uvicorn" version = "0.29.0" diff --git a/webapp/src/app/api/model/keywordPatentHighlight.ts b/webapp/src/app/api/model/keywordPatentHighlight.ts new file mode 100644 index 00000000..7269e32c --- /dev/null +++ b/webapp/src/app/api/model/keywordPatentHighlight.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Elasticsearch highlight fragments (terms wrapped in ...). + */ +export interface KeywordPatentHighlight { + title_de?: Array; + title_en?: Array; + abstract?: Array; +} diff --git a/webapp/src/app/api/model/keywordPatentMatch.ts b/webapp/src/app/api/model/keywordPatentMatch.ts index 3e412bdf..48ff2291 100644 --- a/webapp/src/app/api/model/keywordPatentMatch.ts +++ b/webapp/src/app/api/model/keywordPatentMatch.ts @@ -8,6 +8,7 @@ * Do not edit the class manually. */ import { KeywordEvidence } from './keywordEvidence'; +import { KeywordPatentHighlight } from './keywordPatentHighlight'; import { PatentEntry } from './patentEntry'; export interface KeywordPatentMatch { @@ -30,6 +31,7 @@ export interface KeywordPatentMatch { text_score: number; matched_keywords?: Array; matched_ipc_symbols?: Array; + highlight?: KeywordPatentHighlight | null; /** * True when the patent was retrieved via title/abstract keyword search because IPC mapping was uncertain, missing, or yielded no hits. */ diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index 7f6d7809..18d4fb08 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -15,7 +15,10 @@ export interface PatentEntry { patent_id: string; source: string; title?: string | null; + title_de?: string | null; + title_en?: string | null; 'abstract'?: string | null; + abstract_lang?: string | null; publication_date?: string | null; publication_year?: string | null; application_number?: string | null; diff --git a/webapp/src/app/api/model/patentsByKeywordsRequest.ts b/webapp/src/app/api/model/patentsByKeywordsRequest.ts index 1e9d3021..6a0b41a5 100644 --- a/webapp/src/app/api/model/patentsByKeywordsRequest.ts +++ b/webapp/src/app/api/model/patentsByKeywordsRequest.ts @@ -10,10 +10,30 @@ import { KeywordPatentSearchItem } from './keywordPatentSearchItem'; -export interface PatentsByKeywordsRequest { +export interface PatentsByKeywordsRequest { /** * Keywords to match against patents_openalex_keywords. */ keywords: Array; + /** + * Zero-based page index. + */ + page?: number; + /** + * Page size. + */ + size?: number; + /** + * Filter to a single source: EPO or USPTO. Omit for both. + */ + source?: string | null; + /** + * title | publication_year | source. Omit to sort by match quality. + */ + sort_by?: string | null; + /** + * asc | desc + */ + sort_direction?: string; } diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts index f801c6d5..707add21 100644 --- a/webapp/src/app/api/model/patentsByKeywordsResponse.ts +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -13,6 +13,18 @@ import { KeywordPatentMatch } from './keywordPatentMatch'; export interface PatentsByKeywordsResponse { patent_count: number; + /** + * Total matches across all pages (before page/size slicing). + */ + total_count: number; + /** + * Total EPO matches, unfiltered by source. + */ + epo_count: number; + /** + * Total USPTO matches, unfiltered by source. + */ + uspto_count: number; patents: Array; /** * IPC mapping outcome: mapped (IPC used), uncertain (fragmented evidence; may include text-retrieved patents), no_mapping (no usable IPC evidence; may include text-retrieved patents), no_patents_found (neither IPC nor keyword text search produced relevant patents), or search_error (technical failure talking to the search backend). diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 2899e79a..eadc47dc 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -6,7 +6,7 @@ [diameter]="150" /> } @else if (error()) {

Fehler beim Laden der Patente.

-} @else if (matches().length === 0) { +} @else if (totalCount() === 0) {

{{ emptyMessage() }}

} @else {
@@ -32,13 +32,13 @@
Patente mit passenden Keywords.

- {{ matches().length }} + {{ totalCount() }} Patente
- {{ getEpoCount() }} + {{ epoCount() }} EPO
- {{ getUsptoCount() }} + {{ usptoCount() }} USPTO
diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index ebb5b168..a719442b 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -6,13 +6,11 @@ import { output, signal, } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; import { PageEvent } from '@angular/material/paginator'; -import { Sort } from '@angular/material/sort'; -import { ActivatedRoute, Router } from '@angular/router'; +import { Router } from '@angular/router'; import { PatentEntry } from '../../../api/model/patentEntry'; import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch'; import { LoadingComponent } from '../../../shared/ui/loading/loading.component'; @@ -22,14 +20,25 @@ import { getPublicationStageLabel, } from '../../patent-detail/patent-detail.utils'; import { KeywordPatentMappingStatus } from '../../../api'; -import { PatentTableComponent } from '../../../shared/ui/patent-table/patent-table.component'; -import { SourceFilterComponent } from '../../../shared/ui/source-filter/source-filter.component'; +import { + PatentTableComponent, + PatentTableEntry, +} from '../../../shared/ui/patent-table/patent-table.component'; +import { + SourceFilterComponent, + SourceFilterValue, +} from '../../../shared/ui/source-filter/source-filter.component'; -type SourceFilter = 'all' | 'EPO' | 'USPTO'; -type SortColumn = 'title' | 'publication_year' | 'source'; -type SortDirection = 'asc' | 'desc'; +export type PatentSourceFilter = SourceFilterValue; +export type PatentSortColumn = 'title' | 'publication_year' | 'source'; +export type PatentSortDirection = 'asc' | 'desc'; -function isValidSortColumn(value: string | null): value is SortColumn { +export interface PatentSortChange { + column: PatentSortColumn; + direction: PatentSortDirection; +} + +function isValidSortColumn(value: string | null): value is PatentSortColumn { return ( value === 'title' || value === 'publication_year' || value === 'source' ); @@ -50,46 +59,41 @@ function isValidSortColumn(value: string | null): value is SortColumn { styleUrl: './keywords-patents.component.scss', }) export class KeywordsPatentsComponent { - private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); - private readonly queryParams = toSignal(this.route.queryParams); readonly matches = input([]); + readonly totalCount = input(0); + readonly epoCount = input(0); + readonly usptoCount = input(0); + readonly activeFilter = input('all'); + readonly sortColumn = input('publication_year'); + readonly sortDirection = input('desc'); readonly mappingStatus = input(null); readonly loading = input(false); readonly error = input(false); readonly showReload = input(false); readonly reloadDisabled = input(false); readonly reload = output(); + readonly filterChange = output(); + readonly sortChange = output(); - activeFilter = signal('all'); - sortColumn = signal('publication_year'); - sortDirection = signal('desc'); selectedMatch = signal(null); - readonly pageIndex = computed(() => { - const params = this.queryParams(); - return params?.['page'] ? +params['page'] || 0 : 0; - }); - - readonly pageSize = computed(() => { - const params = this.queryParams(); - return params?.['size'] ? +params['size'] || 10 : 10; - }); - - readonly filteredMatches = computed(() => { - const filter = this.activeFilter(); - let items = this.matches(); - if (filter !== 'all') { - items = items.filter((item) => item.patent.source === filter); - } - return this.sortMatches(items); - }); - readonly selectedPatent = computed( () => this.selectedMatch()?.patent ?? null, ); + // Memoized so row objects keep a stable identity across change-detection + // cycles — the table's expand/collapse state tracks the selected row by + // reference, which breaks if a fresh object is spread on every read. + readonly pagedPatents = computed(() => + this.matches().map((item) => ({ + ...item.patent, + matched_keywords: item.matched_keywords, + highlight: item.highlight, + })), + ); + emptyMessage(): string { switch (this.mappingStatus()) { case 'search_error': @@ -99,44 +103,41 @@ export class KeywordsPatentsComponent { } } - getPagedMatches(): KeywordPatentMatch[] { - const start = this.pageIndex() * this.pageSize(); - return this.filteredMatches().slice(start, start + this.pageSize()); - } - - getPagedPatents(): PatentEntry[] { - return this.getPagedMatches().map((item) => item.patent); - } - - setFilter(filter: SourceFilter): void { - this.activeFilter.set(filter); + setFilter(filter: PatentSourceFilter): void { + this.filterChange.emit(filter); this.selectedMatch.set(null); - this.resetPage(); } - onSortChange(sort: Sort): void { + onSortChange(sort: { active: string; direction: string }): void { if (!sort.direction || !isValidSortColumn(sort.active)) { return; } - this.sortColumn.set(sort.active); - this.sortDirection.set(sort.direction); + this.sortChange.emit({ + column: sort.active, + direction: sort.direction as PatentSortDirection, + }); this.selectedMatch.set(null); - this.resetPage(); } - setSort(column: SortColumn): void { + setSort(column: PatentSortColumn): void { if (this.sortColumn() === column) { - this.sortDirection.set(this.sortDirection() === 'asc' ? 'desc' : 'asc'); + this.sortChange.emit({ + column, + direction: this.sortDirection() === 'asc' ? 'desc' : 'asc', + }); } else { - this.sortColumn.set(column); - this.sortDirection.set(column === 'publication_year' ? 'desc' : 'asc'); + this.sortChange.emit({ + column, + direction: column === 'publication_year' ? 'desc' : 'asc', + }); } this.selectedMatch.set(null); - this.resetPage(); } selectPatentFromTable(patent: PatentEntry): void { - const match = this.matches().find((item) => item.patent === patent); + const match = this.matches().find( + (item) => item.patent.patent_id === patent.patent_id, + ); if (match) { this.selectMatch(match); } @@ -146,15 +147,6 @@ export class KeywordsPatentsComponent { this.selectedMatch.set(null); } - private resetPage(): void { - void this.router.navigate([], { - relativeTo: this.route, - queryParams: { page: 0 }, - queryParamsHandling: 'merge', - replaceUrl: true, - }); - } - selectMatch(item: KeywordPatentMatch): void { this.selectedMatch.set(item); } @@ -165,15 +157,6 @@ export class KeywordsPatentsComponent { void this.router.navigate(['/patent', match.patent.patent_id]); } - getEpoCount(): number { - return this.matches().filter((item) => item.patent.source === 'EPO').length; - } - - getUsptoCount(): number { - return this.matches().filter((item) => item.patent.source === 'USPTO') - .length; - } - formatDate(date: string | null | undefined): string { return formatPatentDate(date); } @@ -192,31 +175,4 @@ export class KeywordsPatentsComponent { } return `${text.slice(0, 160).trimEnd()}…`; } - - private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] { - const column = this.sortColumn(); - const direction = this.sortDirection() === 'asc' ? 1 : -1; - return [...items].sort((a, b) => { - switch (column) { - case 'publication_year': { - const yearA = - a.patent.publication_date ?? - String(a.patent.publication_year ?? ''); - const yearB = - b.patent.publication_date ?? - String(b.patent.publication_year ?? ''); - return direction * yearA.localeCompare(yearB); - } - case 'source': - return direction * a.patent.source.localeCompare(b.patent.source); - default: - return ( - direction * - (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', { - sensitivity: 'base', - }) - ); - } - }); - } } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 2253d1b1..b5f3b596 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -54,7 +54,6 @@ import { MatTooltipModule } from '@angular/material/tooltip'; import { A11yModule } from '@angular/cdk/a11y'; import { DomSanitizer } from '@angular/platform-browser'; import { SearchResultsPayload } from './search-results/search-results-state.service'; -import { clearPatentsCache } from './patent-search.utils'; type InputMode = 'url' | 'text' | 'file'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; @@ -325,7 +324,6 @@ export class KeywordsSearchComponent { this.broadKeywordEntries.set([]); this.coarseKeywordEntries.set([]); this.fineKeywordEntries.set([]); - clearPatentsCache(); this.websocketService.close(); this.isExtracting.set(false); this.loadingNewKeyword.set(false); @@ -576,7 +574,6 @@ export class KeywordsSearchComponent { this.manualKeywordEntries.set([]); this.sourceContent.set(''); this.sourceUrl.set(null); - clearPatentsCache(); const manualSet = new Set(this.getKeywordLabels(this.manualKeywords())); this.selectedKeywords.set( this.selectedKeywords().filter((k) => manualSet.has(k)), diff --git a/webapp/src/app/modules/keywords-search/patent-search.utils.ts b/webapp/src/app/modules/keywords-search/patent-search.utils.ts index 46c879af..5965f25a 100644 --- a/webapp/src/app/modules/keywords-search/patent-search.utils.ts +++ b/webapp/src/app/modules/keywords-search/patent-search.utils.ts @@ -1,25 +1,10 @@ -import { KeywordPatentMappingStatus } from '../../api'; import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; -import { KeywordPatentMatch } from '../../api/model/keywordPatentMatch'; import { KeywordPatentSearchItem } from '../../api/model/keywordPatentSearchItem'; import { PatentKeywordEntry, SearchResultsPayload, } from './search-results/search-results-state.service'; -export const PATENTS_CACHE_KEY = 'keywords-patents-cache'; - -export interface PatentsCache { - keywords: string[]; - matches: KeywordPatentMatch[]; - mappingStatus?: KeywordPatentMappingStatus | null; -} - -export interface PatentsCacheResult { - matches: KeywordPatentMatch[]; - mappingStatus: KeywordPatentMappingStatus | null; -} - export function buildPatentSearchItems( items: PatentKeywordEntry[], ): KeywordPatentSearchItem[] { @@ -63,48 +48,6 @@ export function buildPatentSearchItemsFromPayload( return buildPatentSearchItems(fallbackEntries); } -export function readPatentsCache( - keywords: string[], -): PatentsCacheResult | null { - const raw = sessionStorage.getItem(PATENTS_CACHE_KEY); - if (!raw) return null; - - try { - const cache = JSON.parse(raw) as PatentsCache; - if (!sameKeywordSet(cache.keywords, keywords)) return null; - return { - matches: cache.matches ?? [], - mappingStatus: cache.mappingStatus ?? null, - }; - } catch { - sessionStorage.removeItem(PATENTS_CACHE_KEY); - return null; - } -} - -export function writePatentsCache( - keywords: string[], - matches: KeywordPatentMatch[], - mappingStatus: KeywordPatentMappingStatus | null = null, -): void { - try { - const cache: PatentsCache = { keywords, matches, mappingStatus }; - sessionStorage.setItem(PATENTS_CACHE_KEY, JSON.stringify(cache)); - } catch (error) { - console.error('Failed to cache patent results:', error); - } -} - -export function clearPatentsCache(): void { - sessionStorage.removeItem(PATENTS_CACHE_KEY); -} - function normalizeKeyword(value: string): string { return value.trim().toLowerCase(); } - -function sameKeywordSet(a: string[], b: string[]): boolean { - if (a.length !== b.length) return false; - const setA = new Set(a.map((keyword) => normalizeKeyword(keyword))); - return b.every((keyword) => setA.has(normalizeKeyword(keyword))); -} diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html index bd5b16b4..b38b1081 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html @@ -2,11 +2,19 @@
+ (reload)="reloadPatents()" + (filterChange)="setFilter($event)" + (sortChange)="setSort($event.column, $event.direction)" />
diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts index 572229f3..ded27672 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts @@ -1,15 +1,17 @@ -import { Component, inject, OnInit, signal } from '@angular/core'; +import { Component, effect, inject, signal } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; import { KeywordsService } from '../../../../api/api/keywords.service'; -import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch'; import { PatentsByKeywordsResponse } from '../../../../api/model/patentsByKeywordsResponse'; -import { KeywordsPatentsComponent } from '../../keywords-patents/keywords-patents.component'; +import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch'; import { - buildPatentSearchItemsFromPayload, - clearPatentsCache, - readPatentsCache, - writePatentsCache, -} from '../../patent-search.utils'; + KeywordsPatentsComponent, + PatentSortColumn, + PatentSortDirection, + PatentSourceFilter, +} from '../../keywords-patents/keywords-patents.component'; +import { buildPatentSearchItemsFromPayload } from '../../patent-search.utils'; import { SearchResultsStateService } from '../search-results-state.service'; import { KeywordPatentMappingStatus } from '../../../../api'; @@ -19,63 +21,117 @@ import { KeywordPatentMappingStatus } from '../../../../api'; templateUrl: './patents-results.component.html', styleUrl: './patents-results.component.scss', }) -export class KeywordsToPatentsResultsComponent implements OnInit { +export class KeywordsToPatentsResultsComponent { protected readonly state = inject(SearchResultsStateService); private readonly keywordsService = inject(KeywordsService); + private readonly route = inject(ActivatedRoute); + + private readonly queryParams = toSignal(this.route.queryParams, { + initialValue: this.route.snapshot.queryParams, + }); + + readonly pageIndex = signal(0); + readonly pageSize = signal(10); + readonly activeFilter = signal('all'); + readonly sortColumn = signal('publication_year'); + readonly sortDirection = signal('desc'); readonly patentMatches = signal([]); + readonly totalCount = signal(0); + readonly epoCount = signal(0); + readonly usptoCount = signal(0); readonly mappingStatus = signal(null); readonly loadingPatents = signal(false); readonly patentsError = signal(false); - ngOnInit(): void { - const cached = readPatentsCache(this.state.keywords()); - if (cached) { - this.setPatentMatches(cached.matches, cached.mappingStatus); - return; - } + constructor() { + effect(() => { + const params = this.queryParams(); + this.pageIndex.set(params?.['page'] ? +params['page'] || 0 : 0); + this.pageSize.set(params?.['size'] ? +params['size'] || 10 : 10); + }); - this.loadMatchingPatents(); + effect(() => { + // Re-run whenever the search keywords or any page/filter/sort state changes. + const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); + const page = this.pageIndex(); + const size = this.pageSize(); + const source = this.activeFilter(); + const sortBy = this.sortColumn(); + const sortDirection = this.sortDirection(); + + this.loadMatchingPatents(keywords, page, size, source, sortBy, sortDirection); + }); } reloadPatents(): void { - clearPatentsCache(); - this.loadMatchingPatents(); + const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); + this.loadMatchingPatents( + keywords, + this.pageIndex(), + this.pageSize(), + this.activeFilter(), + this.sortColumn(), + this.sortDirection(), + ); } - private loadMatchingPatents(): void { - const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); + setFilter(filter: PatentSourceFilter): void { + this.activeFilter.set(filter); + } + + setSort(column: PatentSortColumn, direction: PatentSortDirection): void { + this.sortColumn.set(column); + this.sortDirection.set(direction); + } + + private loadMatchingPatents( + keywords: ReturnType, + page: number, + size: number, + source: PatentSourceFilter, + sortBy: PatentSortColumn, + sortDirection: PatentSortDirection, + ): void { if (keywords.length === 0) { - this.setPatentMatches([], 'no_mapping'); + this.patentMatches.set([]); + this.totalCount.set(0); + this.epoCount.set(0); + this.usptoCount.set(0); + this.mappingStatus.set('no_mapping'); return; } this.loadingPatents.set(true); this.patentsError.set(false); - this.keywordsService.getPatentsByKeywords({ keywords }).subscribe({ - next: (response: PatentsByKeywordsResponse) => { - this.setPatentMatches( - response.patents ?? [], - response.mapping_status ?? null, - ); - this.loadingPatents.set(false); - }, - error: (error: unknown) => { - console.error('Patent search failed:', error); - this.setPatentMatches([], null); - this.patentsError.set(true); - this.loadingPatents.set(false); - }, - }); - } - - private setPatentMatches( - matches: KeywordPatentMatch[], - mappingStatus: KeywordPatentMappingStatus | null = null, - ): void { - this.patentMatches.set(matches); - this.mappingStatus.set(mappingStatus); - writePatentsCache(this.state.keywords(), matches, mappingStatus); + this.keywordsService + .getPatentsByKeywords({ + keywords, + page, + size, + source: source === 'all' ? null : source, + sort_by: sortBy, + sort_direction: sortDirection, + }) + .subscribe({ + next: (response: PatentsByKeywordsResponse) => { + this.patentMatches.set(response.patents ?? []); + this.totalCount.set(response.total_count ?? 0); + this.epoCount.set(response.epo_count ?? 0); + this.usptoCount.set(response.uspto_count ?? 0); + this.mappingStatus.set(response.mapping_status ?? null); + this.loadingPatents.set(false); + }, + error: (error: unknown) => { + console.error('Patent search failed:', error); + this.patentMatches.set([]); + this.totalCount.set(0); + this.epoCount.set(0); + this.usptoCount.set(0); + this.patentsError.set(true); + this.loadingPatents.set(false); + }, + }); } } diff --git a/webapp/src/app/shared/ui/patent-table/patent-table.component.html b/webapp/src/app/shared/ui/patent-table/patent-table.component.html index cd86abe3..cb69ba37 100644 --- a/webapp/src/app/shared/ui/patent-table/patent-table.component.html +++ b/webapp/src/app/shared/ui/patent-table/patent-table.component.html @@ -1,6 +1,7 @@ @@ -125,3 +126,55 @@ open_in_new + + + @if (hasAnyHighlight(patent)) { + +
+

Fundstelle im Patent

+
+ + +
+
+ + +
+
+ @if (getDisplayedTitle(patent); as displayedTitle) { +
+

Titel

+ +
+ } + + @if (patent.abstract) { +
+

Abstract

+ +
+ } +
+
+ } +
diff --git a/webapp/src/app/shared/ui/patent-table/patent-table.component.ts b/webapp/src/app/shared/ui/patent-table/patent-table.component.ts index 7e4d449a..e61eb75d 100644 --- a/webapp/src/app/shared/ui/patent-table/patent-table.component.ts +++ b/webapp/src/app/shared/ui/patent-table/patent-table.component.ts @@ -1,6 +1,7 @@ import { Component, TemplateRef, + computed, inject, input, output, @@ -14,6 +15,7 @@ import { MatTooltipModule } from '@angular/material/tooltip'; import { Sort } from '@angular/material/sort'; import { PatentEntry } from '../../../api/model/patentEntry'; import { MatchedAuthor } from '../../../api/model/matchedAuthor'; +import { KeywordPatentHighlight } from '../../../api/model/keywordPatentHighlight'; import { DataTableComponent, GenericColumn, @@ -21,12 +23,22 @@ import { import { ChipComponent } from '../chip/chip.component'; import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component'; import { isAssigneeLikelyPerson } from '../../../modules/patent-detail/patent-detail.utils'; +import { SearchResultsStateService } from '../../../modules/keywords-search/search-results/search-results-state.service'; +import { + HighlightedTextComponent, + HighlightTerm, +} from '../highlighted-text/highlighted-text.component'; +import { TableDetailRowComponent } from '../table-detail-row/table-detail-row.component'; export interface PatentTableEntry extends PatentEntry { match_type?: string; matched_authors?: MatchedAuthor[]; + matched_keywords?: string[]; + highlight?: KeywordPatentHighlight | null; } +type TitleLanguage = 'de' | 'en'; + @Component({ selector: 'app-patent-table', imports: [ @@ -37,6 +49,8 @@ export interface PatentTableEntry extends PatentEntry { DataTableComponent, ChipComponent, AppAuthorChipComponent, + HighlightedTextComponent, + TableDetailRowComponent, ], templateUrl: './patent-table.component.html', styleUrl: './patent-table.component.scss', @@ -45,6 +59,10 @@ export class PatentTableComponent< T extends PatentTableEntry = PatentTableEntry, > { private readonly router = inject(Router); + private readonly searchResultsStateService = inject( + SearchResultsStateService, + { optional: true }, + ); patents = input.required(); selectedPatent = input(null); @@ -56,6 +74,10 @@ export class PatentTableComponent< selectPatent = output(); handleSortChange = output(); + highlightRowEnabled = computed(() => + this.patents().some((patent) => this.hasAnyHighlight(patent)), + ); + titleTmp = viewChild.required>('titleTmp'); sourceTmp = viewChild.required>('sourceTmp'); yearTmp = viewChild.required>('yearTmp'); @@ -149,7 +171,92 @@ export class PatentTableComponent< } isSelected(patent: T): boolean { - return this.selectedPatent() === patent; + const selected = this.selectedPatent(); + return !!selected && selected.patent_id === patent.patent_id; + } + + /** + * Extracts the distinct matched terms out of Elasticsearch-style + * highlight fragments (terms wrapped in ...). + */ + extractHighlightTerms(fragments: string[] | null | undefined): string[] { + const terms = new Set(); + + for (const fragment of fragments ?? []) { + if (typeof fragment !== 'string') continue; + + const matches = fragment.matchAll(/(.*?)<\/em>/gi); + for (const match of matches) { + const term = match[1]?.trim(); + if (term) { + terms.add(term); + } + } + } + + return Array.from(terms); + } + + getHighlightTerms(terms: string[] | null | undefined): HighlightTerm[] { + return (terms ?? []).map((term) => ({ + term, + topic: this.searchResultsStateService?.resolveTopicForTerm(term) ?? null, + })); + } + + hasAnyHighlight(patent: T): boolean { + const highlight = patent.highlight; + return !!( + highlight?.title_de?.length || + highlight?.title_en?.length || + highlight?.abstract?.length + ); + } + + getTitleHighlightTerms(patent: T): HighlightTerm[] { + const highlight = patent.highlight; + const fragments = + this.getTitleLanguage(patent) === 'de' + ? highlight?.title_de + : highlight?.title_en; + return this.getHighlightTerms(this.extractHighlightTerms(fragments)); + } + + getAbstractHighlightTerms(patent: T): HighlightTerm[] { + return this.getHighlightTerms( + this.extractHighlightTerms(patent.highlight?.abstract), + ); + } + + private readonly selectedTitleLanguage = new Map(); + + hasDeTitle(patent: T): boolean { + return !!patent.title_de?.trim(); + } + + hasEnTitle(patent: T): boolean { + return !!patent.title_en?.trim(); + } + + getTitleLanguage(patent: T): TitleLanguage { + return ( + this.selectedTitleLanguage.get(patent.patent_id) ?? + (this.hasDeTitle(patent) ? 'de' : 'en') + ); + } + + setTitleLanguage(patent: T, language: TitleLanguage): void { + this.selectedTitleLanguage.set(patent.patent_id, language); + } + + getDisplayedTitle(patent: T): string { + if (this.getTitleLanguage(patent) === 'de' && this.hasDeTitle(patent)) { + return patent.title_de!; + } + if (this.hasEnTitle(patent)) { + return patent.title_en!; + } + return patent.title_de ?? patent.title ?? patent.patent_id; } isAssigneeLikelyPerson(assignee: string, patent: T): boolean {