From a736539851715bdd7095869ca546153465d65a9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 26 Jul 2026 02:14:13 +0200 Subject: [PATCH 1/9] feat(chips-and-tooltips): started adding reusable chips and tooltips --- service/src/main/inse/authors/v2/router.py | 17 ++ service/src/main/inse/authors/v2/service.py | 27 ++- .../src/main/inse/institutions/v2/router.py | 43 ++++- .../src/main/inse/institutions/v2/service.py | 46 +++++ webapp/src/app/api/api/authorsV2.service.ts | 57 ++++++ .../src/app/api/api/institutionsV2.service.ts | 61 +++++- .../directives/component-tooltip.directive.ts | 173 ++++++++++++++++++ .../src/app/directives/tooltip.directive.ts | 136 ++++++++++++++ .../institutions/institutions.component.html | 77 +------- .../institutions/institutions.component.ts | 52 +----- .../app-author-card.component.html | 61 ++++++ .../app-author-card.component.scss | 34 ++++ .../app-author-card.component.ts | 30 +++ .../app-author-chip.component.html | 13 ++ .../app-author-chip.component.scss | 26 +++ .../app-author-chip.component.ts | 81 ++++++++ .../app-author-tooltip.component.html | 5 + .../app-author-tooltip.component.scss | 0 .../app-author-tooltip.component.ts | 45 +++++ .../app-institution-card.component.html | 82 +++++++++ .../app-institution-card.component.scss | 35 ++++ .../app-institution-card.component.ts | 42 +++++ .../app-institution-chip.component.html | 13 ++ .../app-institution-chip.component.scss | 26 +++ .../app-institution-chip.component.ts | 81 ++++++++ .../app-institution-tooltip.component.html | 5 + .../app-institution-tooltip.component.scss | 0 .../app-institution-tooltip.component.ts | 42 +++++ .../app-topic-chip.component.html | 13 ++ .../app-topic-chip.component.scss | 15 ++ .../app-topic-chip.component.ts | 56 ++++++ .../publication-table.component.html | 104 +++++------ .../publication-table.component.ts | 15 +- .../topic-tooltip.component.html | 23 +++ .../topic-tooltip.component.scss | 12 ++ .../topic-tooltip/topic-tooltip.component.ts | 31 ++++ 36 files changed, 1379 insertions(+), 200 deletions(-) create mode 100644 webapp/src/app/directives/component-tooltip.directive.ts create mode 100644 webapp/src/app/directives/tooltip.directive.ts create mode 100644 webapp/src/app/shared/ui/app-author-card/app-author-card.component.html create mode 100644 webapp/src/app/shared/ui/app-author-card/app-author-card.component.scss create mode 100644 webapp/src/app/shared/ui/app-author-card/app-author-card.component.ts create mode 100644 webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html create mode 100644 webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss create mode 100644 webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts create mode 100644 webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.html create mode 100644 webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.scss create mode 100644 webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts create mode 100644 webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html create mode 100644 webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.scss create mode 100644 webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts create mode 100644 webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html create mode 100644 webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss create mode 100644 webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts create mode 100644 webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.html create mode 100644 webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.scss create mode 100644 webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts create mode 100644 webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html create mode 100644 webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss create mode 100644 webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts create mode 100644 webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.html create mode 100644 webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.scss create mode 100644 webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.ts diff --git a/service/src/main/inse/authors/v2/router.py b/service/src/main/inse/authors/v2/router.py index 207888f0..3474728c 100644 --- a/service/src/main/inse/authors/v2/router.py +++ b/service/src/main/inse/authors/v2/router.py @@ -9,6 +9,7 @@ from inse.authors.v2.model import ( StartCollaborationGraphResponse, ) from inse.database import SessionDep +from inse.models.openalex.author import Author from inse.router_prefixes import RouterPrefixes from inse.tags import Tags @@ -18,6 +19,22 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix=RouterPrefixes.AUTHORS_V2, tags=[Tags.AUTHORS_V2]) +@router.get( + "/{raw_oa_author_id}", + operation_id="getAuthorById", + summary="Returns an author for a given author ID.", +) +async def get_author_by_id( + raw_oa_author_id: Annotated[ + str, + Path(description="The ID of the author to retrieve."), + ], +) -> Author: + return await authors_service.get_author_by_id_strict( + raw_oa_author_id=raw_oa_author_id + ) + + @router.get( "/authors/id", operation_id="getAuthorsByIds", diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index 8b73bb12..3fe2600c 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -18,6 +18,7 @@ from inse.authors.v2.model import ( StartCollaborationGraphResponse, WorkNode, ) +from inse.exceptions import NotFoundException from inse.integrations import elasticsearch from inse.model import ESIndex from inse.models.openalex.author import Author @@ -68,21 +69,41 @@ async def search_authors( return AuthorPage(elements=authors, total=len(authors), page=page, size=size) -async def get_author_by_id(author_id: str) -> Author | None: +async def get_author_by_id(raw_oa_author_id: str) -> Author | None: """Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID. Args: - author_id (str): The ID of the author to retrieve. + raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve. Returns: Optional[Author]: The retrieved author, or None if not found. """ - response = await elasticsearch.get(index=ESIndex.OPENALEX_AUTHORS, doc_id=author_id) + response = await elasticsearch.get( + index=ESIndex.OPENALEX_AUTHORS, doc_id=raw_oa_author_id + ) if not response.get("found"): return None return Author.from_dict(response.get("_source", {})) # type: ignore +async def get_author_by_id_strict(raw_oa_author_id: str) -> Author: + """Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID. + + Args: + raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve. + + Returns: + Author: The retrieved author. + + Raises: + ValueError: If the author is not found. + """ + author = await get_author_by_id(raw_oa_author_id=raw_oa_author_id) + if not author: + raise NotFoundException(f"Author with ID {raw_oa_author_id} not found.") + return author + + async def autocomplete_authors_for_selector(query: str) -> AuthorPage: """Autocompletes authors based on a search term for use in a selector component. diff --git a/service/src/main/inse/institutions/v2/router.py b/service/src/main/inse/institutions/v2/router.py index a7c82fb3..c6119a40 100644 --- a/service/src/main/inse/institutions/v2/router.py +++ b/service/src/main/inse/institutions/v2/router.py @@ -1,8 +1,10 @@ import logging from typing import Annotated -from fastapi import APIRouter, Query +import inse.institutions.v2.service as institutions_service +from fastapi import APIRouter, Path, Query from inse.institutions.v2.model import InstitutionPageV2 +from inse.models.openalex.institution import Institution from inse.router_prefixes import RouterPrefixes from inse.tags import Tags @@ -13,7 +15,32 @@ router = APIRouter(prefix=RouterPrefixes.INSTITUTIONS_V2, tags=[Tags.INSTITUTION @router.get( - "/ids", + "/single/{institution_id}", + operation_id="getInstitutionById2", + summary="Returns an institution based on its ID.", +) +async def get_institution_by_id( + institution_id: Annotated[ + str, + Path(description="The ID of the institution to retrieve."), + ], +) -> Institution: + return await institutions_service.get_institution_by_id_strict( + raw_oa_institution_id=institution_id, + source=[ + "id", + "display_name", + "display_name_alternatives", + "works_count", + "cited_by_count", + "geo", + "summary_stats", + ], + ) + + +@router.get( + "/multiple/ids", operation_id="getInstitutionsByIds", summary="Returns a list of institutions based on their IDs.", ) @@ -23,9 +50,9 @@ async def get_institutions_by_ids( Query(description="A list of institution IDs to retrieve."), ] = None, ) -> InstitutionPageV2: - from inse.institutions.v2.service import get_institutions_by_ids - - return await get_institutions_by_ids(institution_ids=institution_ids or []) + return await institutions_service.get_institutions_by_ids( + institution_ids=institution_ids or [] + ) @router.get( @@ -41,6 +68,6 @@ async def get_institution_autocomplete( ), ] = "", ) -> InstitutionPageV2: - from inse.institutions.v2.service import autocomplete_institutions_for_selector - - return await autocomplete_institutions_for_selector(query=query) + return await institutions_service.autocomplete_institutions_for_selector( + query=query + ) diff --git a/service/src/main/inse/institutions/v2/service.py b/service/src/main/inse/institutions/v2/service.py index 24b04b56..b4bacd50 100644 --- a/service/src/main/inse/institutions/v2/service.py +++ b/service/src/main/inse/institutions/v2/service.py @@ -1,5 +1,6 @@ import logging +from inse.exceptions import NotFoundException from inse.institutions.v2.model import InstitutionPageV2 from inse.integrations import elasticsearch from inse.model import ESIndex @@ -8,6 +9,51 @@ from inse.models.openalex.institution import Institution logger = logging.getLogger(__name__) +async def get_institution_by_id( + raw_oa_institution_id: str, source: list[str] | None = None +) -> Institution | None: + """Retrieves an institution by its ID from the OpenAlex Elasticsearch index. + + Args: + raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve. + source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None. + + Returns: + Institution | None: The institution object if found, otherwise None. + """ + response = await elasticsearch.get( + index=ESIndex.OPENALEX_INSTITUTIONS, doc_id=raw_oa_institution_id, source=source + ) + if not response.get("found"): + return None + return Institution.from_dict(response.get("_source", {})) # type: ignore + + +async def get_institution_by_id_strict( + raw_oa_institution_id: str, source: list[str] | None = None +) -> Institution: + """Retrieves an institution by its ID from the OpenAlex Elasticsearch index, raising an exception if not found. + + Args: + raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve. + source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None. + + Raises: + NotFoundException: If the institution is not found. + + Returns: + Institution: The institution object if found. + """ + institution = await get_institution_by_id( + raw_oa_institution_id=raw_oa_institution_id, source=source + ) + if institution is None: + raise NotFoundException( + f"Institution with ID {raw_oa_institution_id} not found." + ) + return institution + + async def search_institutions( page: int = 0, size: int = 10, diff --git a/webapp/src/app/api/api/authorsV2.service.ts b/webapp/src/app/api/api/authorsV2.service.ts index c5c999e8..05f90608 100644 --- a/webapp/src/app/api/api/authorsV2.service.ts +++ b/webapp/src/app/api/api/authorsV2.service.ts @@ -16,6 +16,8 @@ import { HttpClient, HttpHeaders, HttpParams, import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; +// @ts-ignore +import { Author } from '../model/author'; // @ts-ignore import { AuthorPage } from '../model/authorPage'; // @ts-ignore @@ -98,6 +100,61 @@ export class AuthorsV2Service extends BaseService { ); } + /** + * Returns an author for a given author ID. + * @endpoint get /api/authors/v2/{raw_oa_author_id} + * @param rawOaAuthorId The ID of the author to retrieve. + * @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 getAuthorById(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getAuthorById(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorById(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getAuthorById(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaAuthorId === null || rawOaAuthorId === undefined) { + throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorById.'); + } + + 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; + + + 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/authors/v2/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Returns a paginated list of authors for a given list of author IDs. * @endpoint get /api/authors/v2/authors/id diff --git a/webapp/src/app/api/api/institutionsV2.service.ts b/webapp/src/app/api/api/institutionsV2.service.ts index ba8bc1a0..45877996 100644 --- a/webapp/src/app/api/api/institutionsV2.service.ts +++ b/webapp/src/app/api/api/institutionsV2.service.ts @@ -19,6 +19,8 @@ import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { Institution } from '../model/institution'; +// @ts-ignore import { InstitutionPageV2 } from '../model/institutionPageV2'; // @ts-ignore @@ -94,9 +96,64 @@ export class InstitutionsV2Service extends BaseService { ); } + /** + * Returns an institution based on its ID. + * @endpoint get /api/institutions/v2/single/{institution_id} + * @param institutionId The ID of the institution to retrieve. + * @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 getInstitutionById2(institutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getInstitutionById2(institutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionById2(institutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getInstitutionById2(institutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (institutionId === null || institutionId === undefined) { + throw new Error('Required parameter institutionId was null or undefined when calling getInstitutionById2.'); + } + + 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; + + + 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/institutions/v2/single/${this.configuration.encodeParam({name: "institutionId", value: institutionId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Returns a list of institutions based on their IDs. - * @endpoint get /api/institutions/v2/ids + * @endpoint get /api/institutions/v2/multiple/ids * @param institutionIds A list of institution IDs to retrieve. * @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. @@ -139,7 +196,7 @@ export class InstitutionsV2Service extends BaseService { } } - let localVarPath = `/api/institutions/v2/ids`; + let localVarPath = `/api/institutions/v2/multiple/ids`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { diff --git a/webapp/src/app/directives/component-tooltip.directive.ts b/webapp/src/app/directives/component-tooltip.directive.ts new file mode 100644 index 00000000..eefd8b15 --- /dev/null +++ b/webapp/src/app/directives/component-tooltip.directive.ts @@ -0,0 +1,173 @@ +import { + Directive, + ElementRef, + OnDestroy, + Injector, + ComponentRef, + HostListener, + input, + inject, + effect, + InputSignal, +} from '@angular/core'; +import { + Overlay, + OverlayRef, + OverlayPositionBuilder, + ConnectedPosition, +} from '@angular/cdk/overlay'; +import { ComponentPortal, ComponentType } from '@angular/cdk/portal'; + +type UnwrapInputSignals = { + [K in keyof T]: T[K] extends InputSignal ? V : T[K]; +}; + +@Directive({ + selector: '[appComponentTooltip]', + standalone: true, +}) +export class ComponentTooltipDirective implements OnDestroy { + readonly component = input.required>({ + alias: 'appComponentTooltip', + }); + readonly tooltipInputs = input> | null>(null); + readonly tooltipShowDelay = input(150); + readonly tooltipHideDelay = input(100); + readonly tooltipDisabled = input(false); + + private readonly elementRef = inject(ElementRef); + private readonly overlay = inject(Overlay); + private readonly overlayPositionBuilder = inject(OverlayPositionBuilder); + private readonly injector = inject(Injector); + + private overlayRef: OverlayRef | null = null; + private componentRef: ComponentRef | null = null; + private showTimeout?: ReturnType; + private hideTimeout?: ReturnType; + + private isOverHost = false; + private isOverOverlay = false; + + constructor() { + effect(() => { + const inputs = this.tooltipInputs(); + if (this.componentRef && inputs) { + for (const [key, value] of Object.entries(inputs)) { + this.componentRef.setInput(key, value); + } + } + }); + } + + @HostListener('mouseenter') + @HostListener('focus') + onEnter(): void { + if (this.tooltipDisabled()) return; + this.isOverHost = true; + clearTimeout(this.hideTimeout); + this.showTimeout = setTimeout(() => this.show(), this.tooltipShowDelay()); + } + + @HostListener('mouseleave') + @HostListener('blur') + onLeave(): void { + this.isOverHost = false; + clearTimeout(this.showTimeout); + this.scheduleHide(); + } + + private scheduleHide(): void { + this.hideTimeout = setTimeout(() => { + if (!this.isOverHost && !this.isOverOverlay) { + this.hide(); + } + }, this.tooltipHideDelay()); + } + + private show(): void { + if (this.overlayRef?.hasAttached()) return; + + const positions: ConnectedPosition[] = [ + { + originX: 'center', + originY: 'top', + overlayX: 'center', + overlayY: 'bottom', + offsetY: -8, + }, + { + originX: 'center', + originY: 'bottom', + overlayX: 'center', + overlayY: 'top', + offsetY: 8, + }, + { + originX: 'end', + originY: 'center', + overlayX: 'start', + overlayY: 'center', + offsetX: 8, + }, + { + originX: 'start', + originY: 'center', + overlayX: 'end', + overlayY: 'center', + offsetX: -8, + }, + ]; + + const positionStrategy = this.overlayPositionBuilder + .flexibleConnectedTo(this.elementRef) + .withPositions(positions) + .withFlexibleDimensions(false) + .withPush(true); + + this.overlayRef = this.overlay.create({ + positionStrategy, + scrollStrategy: this.overlay.scrollStrategies.reposition(), + panelClass: 'app-tooltip-panel', + }); + + const portal = new ComponentPortal(this.component(), null, this.injector); + this.componentRef = this.overlayRef.attach(portal); + + const inputs = this.tooltipInputs(); + if (inputs) { + for (const [key, value] of Object.entries(inputs)) { + this.componentRef!.setInput(key, value); + } + } + + const overlayElement = this.overlayRef.overlayElement; + overlayElement.addEventListener('mouseenter', this.onOverlayEnter); + overlayElement.addEventListener('mouseleave', this.onOverlayLeave); + } + + private readonly onOverlayEnter = (): void => { + this.isOverOverlay = true; + clearTimeout(this.hideTimeout); + }; + + private readonly onOverlayLeave = (): void => { + this.isOverOverlay = false; + this.scheduleHide(); + }; + + private hide(): void { + if (this.overlayRef) { + const overlayElement = this.overlayRef.overlayElement; + overlayElement.removeEventListener('mouseenter', this.onOverlayEnter); + overlayElement.removeEventListener('mouseleave', this.onOverlayLeave); + this.overlayRef.detach(); + } + this.componentRef = null; + } + + ngOnDestroy(): void { + clearTimeout(this.showTimeout); + clearTimeout(this.hideTimeout); + this.overlayRef?.dispose(); + } +} diff --git a/webapp/src/app/directives/tooltip.directive.ts b/webapp/src/app/directives/tooltip.directive.ts new file mode 100644 index 00000000..65fae896 --- /dev/null +++ b/webapp/src/app/directives/tooltip.directive.ts @@ -0,0 +1,136 @@ +import { + ConnectedPosition, + Overlay, + OverlayPositionBuilder, + OverlayRef, +} from '@angular/cdk/overlay'; +import { TemplatePortal } from '@angular/cdk/portal'; +import { + Directive, + effect, + ElementRef, + HostListener, + inject, + input, + OnDestroy, + TemplateRef, + ViewContainerRef, +} from '@angular/core'; + +@Directive({ + selector: '[appTooltip]', + standalone: true, +}) +export class TooltipDirective implements OnDestroy { + readonly template = input.required>({ alias: 'appTooltip' }); + + readonly tooltipContext = input(null); + + readonly tooltipShowDelay = input(150); + + readonly tooltipHideDelay = input(150); + + readonly tooltipDisabled = input(false); + + private readonly elementRef = inject(ElementRef); + private readonly overlay = inject(Overlay); + private readonly overlayPositionBuilder = inject(OverlayPositionBuilder); + private readonly viewContainerRef = inject(ViewContainerRef); + + private overlayRef: OverlayRef | null = null; + private portal: TemplatePortal | null = null; + private showTimeout?: ReturnType; + private hideTimeout?: ReturnType; + + constructor() { + effect(() => { + const context = this.tooltipContext(); + if (this.portal?.isAttached) { + Object.assign(this.portal.context as object, context ?? {}); + } + }); + } + + @HostListener('mouseenter') + @HostListener('focus') + onEnter(): void { + if (this.tooltipDisabled()) { + return; + } + clearTimeout(this.hideTimeout); + this.showTimeout = setTimeout(() => this.show(), this.tooltipShowDelay()); + } + + @HostListener('mouseleave') + @HostListener('blur') + onLeave(): void { + clearTimeout(this.showTimeout); + this.hideTimeout = setTimeout(() => this.hide(), this.tooltipHideDelay()); + } + + private show(): void { + if (this.overlayRef?.hasAttached()) return; + + const positions: ConnectedPosition[] = [ + { + originX: 'center', + originY: 'top', + overlayX: 'center', + overlayY: 'bottom', + offsetY: -8, + }, + { + originX: 'center', + originY: 'bottom', + overlayX: 'center', + overlayY: 'top', + offsetY: 8, + }, + { + originX: 'end', + originY: 'center', + overlayX: 'start', + overlayY: 'center', + offsetX: 8, + }, + { + originX: 'start', + originY: 'center', + overlayX: 'end', + overlayY: 'center', + offsetX: -8, + }, + ]; + + const positionStrategy = this.overlayPositionBuilder + .flexibleConnectedTo(this.elementRef) + .withPositions(positions) + .withFlexibleDimensions(false) + .withPush(true); + + this.overlayRef = this.overlay.create({ + positionStrategy, + scrollStrategy: this.overlay.scrollStrategies.reposition(), + panelClass: 'app-tooltip-panel', + }); + + this.portal = new TemplatePortal( + this.template(), + this.viewContainerRef, + (this.tooltipContext() ?? {}) as T, + ); + + this.overlayRef.attach(this.portal); + } + + private hide(): void { + this.overlayRef?.detach(); + this.portal = null; + } + + ngOnDestroy(): void { + clearTimeout(this.showTimeout); + clearTimeout(this.hideTimeout); + this.overlayRef?.dispose(); + } +} diff --git a/webapp/src/app/modules/institutions/institutions.component.html b/webapp/src/app/modules/institutions/institutions.component.html index 42df50d1..03d2d427 100644 --- a/webapp/src/app/modules/institutions/institutions.component.html +++ b/webapp/src/app/modules/institutions/institutions.component.html @@ -15,80 +15,5 @@ - - - {{ getDisplayName(institution) }} - {{ institution.geo?.city }}, - {{ institution.geo?.country }} - - - - - - - - - - - - info - Übersicht - - - article - Publikationen - - - work - Projekte - - @if (hasPatents(institution)) { - - verified - Patente - - } - - - + diff --git a/webapp/src/app/modules/institutions/institutions.component.ts b/webapp/src/app/modules/institutions/institutions.component.ts index a5c7ed0f..ff956e5f 100644 --- a/webapp/src/app/modules/institutions/institutions.component.ts +++ b/webapp/src/app/modules/institutions/institutions.component.ts @@ -1,6 +1,5 @@ -import { Component, computed, effect, inject, input } from '@angular/core'; -import { Institution, InstitutionPage } from '../../api'; -import { PatentsService } from '../../api/api/patents.service'; +import { Component, computed, input } from '@angular/core'; +import { InstitutionPage } from '../../api'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { RouterModule } from '@angular/router'; @@ -13,6 +12,7 @@ import { CardSearchComponent, } from '../../shared/ui/card-search/card-search.component'; import { FilterObserver } from '../../shared/ui/selected-filters/selected-filters.component'; +import { AppInstitutionCardComponent } from '../../shared/ui/app-institution-card/app-institution-card.component'; @Component({ selector: 'app-institutions', @@ -23,13 +23,12 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter MatDividerModule, RouterModule, CardSearchComponent, + AppInstitutionCardComponent, ], templateUrl: './institutions.component.html', styleUrl: './institutions.component.scss', }) export class InstitutionsComponent { - private readonly patentsApi = inject(PatentsService); - institutionPage = input.required(); observers: FilterObserver[] = [ @@ -47,35 +46,6 @@ export class InstitutionsComponent { elements: this.institutionPage().elements || [], })); - // The "Patente" action only makes sense once org_patents has been indexed - // for that institution (currently a manual, per-institution process), so - // it's hidden by default and only shown once a cheap count check confirms - // there is actually data behind it. - private readonly patentsAvailable = new Map(); - - constructor() { - effect(() => { - for (const institution of this.page().elements) { - const id = this.extractInstitutionId(institution); - if (!id || this.patentsAvailable.has(id)) continue; - this.patentsAvailable.set(id, false); - this.patentsApi - .getOrgPatentsByInstitution(id, undefined, 0, 0) - .subscribe({ - next: (result) => { - this.patentsAvailable.set(id, (result.patent_count ?? 0) > 0); - }, - }); - } - }); - } - - hasPatents(institution: Institution): boolean { - return ( - this.patentsAvailable.get(this.extractInstitutionId(institution)) ?? false - ); - } - sortingOptions: SelectorOption[] = [ { value: 'relevance', display_name: 'Relevanz' }, { value: 'name', display_name: 'Name' }, @@ -86,18 +56,4 @@ export class InstitutionsComponent { { value: 'asc', display_name: 'Aufsteigend' }, { value: 'desc', display_name: 'Absteigend' }, ]; - - extractInstitutionId(institution: Institution): string { - return institution.id?.split('/').pop() ?? ''; - } - - getDisplayName(institution: Institution): string { - const primary = institution.display_name?.trim(); - if (primary && primary.length > 0) return primary; - - const alt = institution.display_name_alternatives?.[0]?.trim(); - if (alt && alt.length > 0) return alt; - - return 'Unbekannte Institution'; - } } diff --git a/webapp/src/app/shared/ui/app-author-card/app-author-card.component.html b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.html new file mode 100644 index 00000000..6197f645 --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.html @@ -0,0 +1,61 @@ + + + {{ author().display_name }} + @if (author()?.last_known_institutions?.[0]?.display_name) { + + {{ author()?.last_known_institutions?.[0]?.display_name }} + + } + + + + + + @if (author().works_count) { +
+ menu_book + {{ author().works_count }} Publikationen +
+ } + @if (author().cited_by_count) { +
+ format_quote + {{ author().cited_by_count }} Zitationen +
+ } + @if (author().summary_stats?.h_index) { +
+ trending_up + h-Index: {{ author().summary_stats?.h_index }} +
+ } +
+ + + + + + + info + Übersicht + + + menu_book + Publikationen + + + work + Projekte + + + +
diff --git a/webapp/src/app/shared/ui/app-author-card/app-author-card.component.scss b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.scss new file mode 100644 index 00000000..5514c75b --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.scss @@ -0,0 +1,34 @@ +.card-content { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.institution { + display: flex; + gap: 0.5rem; + color: var(--sg-text-muted); +} + +.metrics { + display: flex; + flex-direction: column; + gap: 0.5rem; + font-size: 0.875rem; +} + +.metric-item { + display: flex; + align-items: center; + gap: 0.25rem; + color: var(--sg-text-muted); +} + +.card-actions { + display: flex; + gap: 0.5rem; +} + +.card-action { + width: 100%; +} diff --git a/webapp/src/app/shared/ui/app-author-card/app-author-card.component.ts b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.ts new file mode 100644 index 00000000..4a930747 --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.ts @@ -0,0 +1,30 @@ +import { Component, input } from '@angular/core'; +import { Author } from '../../../api'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { MatDividerModule } from '@angular/material/divider'; +import { RouterModule } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; + +@Component({ + selector: 'app-author-card', + imports: [ + MatCardModule, + MatIconModule, + MatDividerModule, + RouterModule, + MatButtonModule, + ], + templateUrl: './app-author-card.component.html', + styleUrl: './app-author-card.component.scss', +}) +export class AppAuthorCardComponent { + author = input.required(); + + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); + } +} diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html new file mode 100644 index 00000000..470511be --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html @@ -0,0 +1,13 @@ + + + @if (showIcon()) { + {{ icon() }} + } + {{ _author()?.display_name }} + + diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss new file mode 100644 index 00000000..db1e34d7 --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss @@ -0,0 +1,26 @@ +.author-chip { + font-weight: 500; + border-radius: var(--sg-radius-sm); + background-color: var(--sg-surface-soft); + border: var(--border-width) solid var(--border-color); +} + +:host ::ng-deep .author-chip .mat-mdc-chip-action, +:host ::ng-deep .author-chip .mdc-evolution-chip__action { + background-color: var(--sg-surface-soft); + border-radius: var(--sg-radius-sm); +} + +.author-icon { + --icon-size: 1rem; + + font-size: var(--icon-size); + height: var(--icon-size); + width: var(--icon-size); +} + +:host.is-clickable { + ::ng-deep .mdc-evolution-chip__action { + cursor: pointer; + } +} diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts new file mode 100644 index 00000000..cf63887b --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts @@ -0,0 +1,81 @@ +import { + Component, + computed, + effect, + inject, + input, + output, + signal, +} from '@angular/core'; +import { Author, AuthorsV2Service } from '../../../api'; +import { AppAuthorTooltipComponent } from '../app-author-tooltip/app-author-tooltip.component'; +import { MatIconModule } from '@angular/material/icon'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; +import { MatChipsModule } from '@angular/material/chips'; + +@Component({ + host: { + '[style.--border-width]': 'isSelected() ? "2px" : "1px"', + '[style.--border-color]': + 'isSelected() ? "var(--sg-primary)" : "var(--sg-border)"', + '[class.is-clickable]': 'isClickable()', + }, + selector: 'app-author-chip', + imports: [MatIconModule, MatChipsModule, ComponentTooltipDirective], + templateUrl: './app-author-chip.component.html', + styleUrl: './app-author-chip.component.scss', +}) +export class AppAuthorChipComponent { + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; + private readonly authorsService = inject(AuthorsV2Service); + + isSelected = input(false); + + isClickable = input(false); + handleChipClick = output(); + + showIcon = input(false); + icon = input('person'); + + author = input(undefined); + rawOaAuthorId = computed(() => { + return this.stripOpenAlexId(this.author()?.id); + }); + authorId = input(undefined); + + _author = signal(undefined); + + constructor() { + effect(() => { + const author = this.author(); + const authorId = this.authorId(); + if (!author && !authorId) { + this._author.set(undefined); + } + + if (author) { + this._author.set(author); + } else if (authorId) { + this.authorsService.getAuthorById(authorId).subscribe((author) => { + this._author.set(author); + }); + } + }); + } + + _onChipClick(event: MouseEvent | KeyboardEvent) { + const author = this._author(); + if (this.handleChipClick && author) { + this.handleChipClick.emit(author); + } + + console.log('Chip clicked:', event); + } + + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); + } +} diff --git a/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.html b/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.html new file mode 100644 index 00000000..af36e259 --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.html @@ -0,0 +1,5 @@ +@let author = this._author(); + +@if (author) { + +} \ No newline at end of file diff --git a/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.scss b/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts b/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts new file mode 100644 index 00000000..5b428fcb --- /dev/null +++ b/webapp/src/app/shared/ui/app-author-tooltip/app-author-tooltip.component.ts @@ -0,0 +1,45 @@ +import { Component, effect, inject, input, signal } from '@angular/core'; +import { Author, AuthorsV2Service } from '../../../api'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { RouterModule } from '@angular/router'; +import { MatDividerModule } from '@angular/material/divider'; +import { AppAuthorCardComponent } from '../app-author-card/app-author-card.component'; + +@Component({ + selector: 'app-author-tooltip', + imports: [ + MatCardModule, + MatIconModule, + MatButtonModule, + RouterModule, + MatDividerModule, + AppAuthorCardComponent, + ], + templateUrl: './app-author-tooltip.component.html', + styleUrl: './app-author-tooltip.component.scss', +}) +export class AppAuthorTooltipComponent { + private readonly authorsService = inject(AuthorsV2Service); + + authorId = input.required(); + + _author = signal(undefined); + + _isLoading = signal(false); + + constructor() { + effect(() => { + const authorId = this.authorId(); + if (!authorId) { + this._author.set(undefined); + } + this._isLoading.set(true); + this.authorsService.getAuthorById(authorId).subscribe((author) => { + this._author.set(author); + this._isLoading.set(false); + }); + }); + } +} diff --git a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html new file mode 100644 index 00000000..ddcf6478 --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.html @@ -0,0 +1,82 @@ + + + {{ displayName() }} + {{ institution().geo?.city }}, + {{ institution().geo?.country }} + + + + + +
+ menu_book + {{ + institution().works_count | number: undefined : 'de' + }} + Publikationen +
+
+ format_quote + {{ + institution().cited_by_count | number: undefined : 'de' + }} + Zitationen +
+
+ + + + + + + info + Übersicht + + + menu_book + Publikationen + + + work + Projekte + + + +
diff --git a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.scss b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.scss new file mode 100644 index 00000000..c85ff37c --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.scss @@ -0,0 +1,35 @@ +.card-content { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.city-country { + display: flex; + align-items: center; + gap: 0.5rem; + color: var(--sg-text-muted); +} + +.metrics { + display: flex; + flex-direction: column; + gap: 0.5rem; + font-size: 0.875rem; +} + +.metric-item { + display: flex; + align-items: center; + gap: 0.25rem; + color: var(--sg-text-muted); +} + +.card-actions { + display: flex; + gap: 0.5rem; +} + +.card-action { + width: 100%; +} diff --git a/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts new file mode 100644 index 00000000..aaae7e50 --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-card/app-institution-card.component.ts @@ -0,0 +1,42 @@ +import { Component, computed, input } from '@angular/core'; +import { Institution } from '../../../api'; +import { MatCardModule } from '@angular/material/card'; +import { RouterModule } from '@angular/router'; +import { MatDividerModule } from '@angular/material/divider'; +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { DecimalPipe } from '@angular/common'; + +@Component({ + selector: 'app-institution-card', + imports: [ + MatCardModule, + RouterModule, + MatDividerModule, + MatIconModule, + MatButtonModule, + DecimalPipe + ], + templateUrl: './app-institution-card.component.html', + styleUrl: './app-institution-card.component.scss', +}) +export class AppInstitutionCardComponent { + institution = input.required(); + + displayName = computed(() => { + const primary = this.institution().display_name?.trim(); + if (primary && primary.length > 0) return primary; + + const alt = this.institution().display_name_alternatives?.[0]?.trim(); + if (alt && alt.length > 0) return alt; + + return 'Unbekannte Institution'; + }); + + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); + } +} diff --git a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html new file mode 100644 index 00000000..3e07cb38 --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html @@ -0,0 +1,13 @@ + + + @if (showIcon()) { + {{ icon() }} + } + {{ _institution()?.display_name }} + + diff --git a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss new file mode 100644 index 00000000..c919dcbc --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss @@ -0,0 +1,26 @@ +.institution-chip { + font-weight: 500; + border-radius: var(--sg-radius-sm); + background-color: var(--sg-surface-soft); + border: var(--border-width) solid var(--border-color); +} + +:host ::ng-deep .institution-chip .mat-mdc-chip-action, +:host ::ng-deep .institution-chip .mdc-evolution-chip__action { + background-color: var(--sg-surface-soft); + border-radius: var(--sg-radius-sm); +} + +.institution-icon { + --icon-size: 1rem; + + font-size: var(--icon-size); + height: var(--icon-size); + width: var(--icon-size); +} + +:host.is-clickable { + ::ng-deep .mdc-evolution-chip__action { + cursor: pointer; + } +} diff --git a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts new file mode 100644 index 00000000..9200dd3b --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts @@ -0,0 +1,81 @@ +import { + Component, + computed, + effect, + inject, + input, + output, + signal, +} from '@angular/core'; +import { Institution, InstitutionsV2Service } from '../../../api'; +import { AppInstitutionTooltipComponent } from '../app-institution-tooltip/app-institution-tooltip.component'; +import { MatIconModule } from '@angular/material/icon'; +import { MatChipsModule } from '@angular/material/chips'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; + +@Component({ + host: { + '[style.--border-width]': 'isSelected() ? "2px" : "1px"', + '[style.--border-color]': + 'isSelected() ? "var(--sg-primary)" : "var(--sg-border)"', + '[class.is-clickable]': 'isClickable()', + }, + selector: 'app-institution-chip', + imports: [MatIconModule, MatChipsModule, ComponentTooltipDirective], + templateUrl: './app-institution-chip.component.html', + styleUrl: './app-institution-chip.component.scss', +}) +export class AppInstitutionChipComponent { + readonly InstitutionTooltipComponent = AppInstitutionTooltipComponent; + private readonly institutionsService = inject(InstitutionsV2Service); + + isSelected = input(false); + + isClickable = input(false); + handleChipClick = output(); + + showIcon = input(false); + icon = input('apartment'); + + institution = input(undefined); + rawOaInstitutionId = computed(() => { + return this.stripOpenAlexId(this.institution()?.id); + }); + institutionId = input(undefined); + + _institution = signal(undefined); + + constructor() { + effect(() => { + const institution = this.institution(); + const institutionId = this.institutionId(); + if (!institution && !institutionId) { + this._institution.set(undefined); + } + + if (institution) { + this._institution.set(institution); + } else if (institutionId) { + this.institutionsService + .getInstitutionById2(institutionId) + .subscribe((institution) => { + this._institution.set(institution); + }); + } + }); + } + + _onChipClick(event: MouseEvent | KeyboardEvent) { + const institution = this._institution(); + if (this.isClickable() && this.handleChipClick && institution) { + this.handleChipClick.emit(institution); + } + } + + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); + } +} diff --git a/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.html b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.html new file mode 100644 index 00000000..71932af2 --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.html @@ -0,0 +1,5 @@ +@let institution = this._institution(); + +@if (institution) { + +} diff --git a/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.scss b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts new file mode 100644 index 00000000..4a35f5d9 --- /dev/null +++ b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts @@ -0,0 +1,42 @@ +import { Component, effect, inject, input, signal } from '@angular/core'; +import { Institution, InstitutionsV2Service } from '../../../api'; +import { AppInstitutionCardComponent } from '../app-institution-card/app-institution-card.component'; + +@Component({ + selector: 'app-institution-tooltip', + imports: [AppInstitutionCardComponent], + templateUrl: './app-institution-tooltip.component.html', + styleUrl: './app-institution-tooltip.component.scss', +}) +export class AppInstitutionTooltipComponent { + private readonly institutionsService = inject(InstitutionsV2Service); + + institutionId = input.required(); + + _institution = signal(undefined); + + _isLoading = signal(false); + + constructor() { + effect(() => { + const institutionId = this.institutionId(); + if (!institutionId) { + this._institution.set(undefined); + } + this._isLoading.set(true); + this.institutionsService + .getInstitutionById2(institutionId) + .subscribe((institution) => { + this._institution.set(institution); + this._isLoading.set(false); + }); + }); + } + + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); + } +} diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html new file mode 100644 index 00000000..007218f5 --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html @@ -0,0 +1,13 @@ + + + @if (showIcon()) { + {{ icon() }} + } + {{ topic().display_name }} + + diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss new file mode 100644 index 00000000..e8ee4118 --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss @@ -0,0 +1,15 @@ +.topic-chip { + --topic-background: color-mix(in srgb, hsl(var(--topic-color)) 8%, #ffffff); + --topic-border: color-mix(in srgb, hsl(var(--topic-color)) 72%, #ffffff); + + font-weight: 500; + background-color: var(--topic-background); + border: 1px solid var(--topic-border); + border-radius: var(--sg-radius-sm); +} + +:host.is-clickable { + ::ng-deep .mdc-evolution-chip__action { + cursor: pointer; + } +} diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts new file mode 100644 index 00000000..793ff652 --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts @@ -0,0 +1,56 @@ +import { Component, computed, input, output } from '@angular/core'; +import { Topic } from '../../../api'; +import { TopicTooltipComponent } from '../topic-tooltip/topic-tooltip.component'; +import { MatChipsModule } from '@angular/material/chips'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; +import { MatIconModule } from '@angular/material/icon'; + +@Component({ + host: { + '[style.--topic-color]': 'color()', + '[class.is-clickable]': 'isClickable()', + }, + selector: 'app-topic-chip-2', + imports: [MatChipsModule, ComponentTooltipDirective, MatIconModule], + templateUrl: './app-topic-chip.component.html', + styleUrl: './app-topic-chip.component.scss', +}) +export class AppTopicChipComponent { + readonly TopicToolTipComponent = TopicTooltipComponent; + + topic = input.required(); + + isSelected = input(false); + + isClickable = input(false); + handleChipClick = output(); + + showIcon = input(false); + icon = input('label'); + + showCount = input(false); + count = input(0); + + color = computed(() => { + const topic = this.topic(); + return topicHierarchyColor({ + id: topic.id ?? undefined, + name: topic.display_name ?? undefined, + field_id: topic.field?.id ?? undefined, + field_name: topic.field?.display_name ?? undefined, + domain_id: topic.domain?.id ?? undefined, + domain_name: topic.domain?.display_name ?? undefined, + }) + .replace('hsl(', '') + .replace(')', ''); + }); + + _onChipClick(event: MouseEvent | KeyboardEvent) { + if (this.handleChipClick) { + this.handleChipClick.emit(this.topic()); + } + + console.log('Chip clicked:', event); + } +} 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 7a159f98..9b7cb52e 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 @@ -71,42 +71,6 @@ } - - @let workAuthors = getWorkAuthors(work); - @let workAuthorsExpanded = isWorkAuthorsExpanded(work); - @let visibleAuthors = - workAuthorsExpanded ? workAuthors : workAuthors.slice(0, 3); -
- @for ( - author of visibleAuthors; - track author.id ?? 'name-' + author.display_name - ) { - - } @empty { - - - } - @if (workAuthors.length > 3) { - - } -
-
- @let publicationInstitutions = getWorkInstitutions(work); @let institutionsExpanded = isWorkInstitutionsExpanded(work); @@ -119,31 +83,12 @@ aria-label="Institutionen" style="padding: 0.5rem 0"> @for (institution of visibleInstitutions; track institution.id) { - + } @empty { - } @@ -163,6 +108,37 @@ + + @let workAuthors = getWorkAuthors(work); + @let workAuthorsExpanded = isWorkAuthorsExpanded(work); + @let visibleAuthors = + workAuthorsExpanded ? workAuthors : workAuthors.slice(0, 3); +
+ @for ( + author of visibleAuthors; + track author.id ?? 'name-' + author.display_name + ) { + + } @empty { + - + } + @if (workAuthors.length > 3) { + + } +
+
+ @let workTopics = work.topics ?? [];
@@ -179,6 +155,12 @@ [active]="isTopicActive(topic)" (chipClick)="filterByTopic(topic)"> + } @empty { - } 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 54514bf4..9d3a7f35 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 @@ -4,7 +4,6 @@ import { effect, inject, input, - OnInit, signal, TemplateRef, viewChild, @@ -21,6 +20,7 @@ import { WorkClassification, WorksV2Service, WorkTopic, + Topic, } from '../../../api'; import { TopicChipComponent } from '../topic-chip/topic-chip.component'; import { MatIconModule } from '@angular/material/icon'; @@ -34,6 +34,11 @@ import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { MatButtonModule } from '@angular/material/button'; import { workQueryParamKeys } from '../../../resolvers/work-page.resolver'; import { WorkPrimaryCategoryPipe } from '../../pipes/work-primary-category.pipe'; +import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; +import { TopicTooltipComponent } from '../topic-tooltip/topic-tooltip.component'; +import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; +import { AppAuthorChipComponent } from "../app-author-chip/app-author-chip.component"; +import { AppInstitutionChipComponent } from "../app-institution-chip/app-institution-chip.component"; @Component({ selector: 'app-publication-table', @@ -48,11 +53,17 @@ import { WorkPrimaryCategoryPipe } from '../../pipes/work-primary-category.pipe' WorkTypePipe, LanguageCodePipe, WorkPrimaryCategoryPipe, - ], + ComponentTooltipDirective, + AppTopicChipComponent, + AppAuthorChipComponent, + AppInstitutionChipComponent +], templateUrl: './publication-table.component.html', styleUrl: './publication-table.component.scss', }) export class PublicationTableComponent { + protected readonly TopicTooltipComponent = TopicTooltipComponent; + page = input.required(); authorFilterEnabled = input(false); institutionFilterEnabled = input(false); diff --git a/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.html b/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.html new file mode 100644 index 00000000..0a5be0ad --- /dev/null +++ b/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.html @@ -0,0 +1,23 @@ + + + {{ topic().display_name }} + @if (topic().description) { + {{ topic().description }} + } + + + @if (topic().keywords) { +

Schlüsselwörter: {{ topic().keywords }}

+ } + + @if (topic().subfield) { +

Subfeld: {{ topic().subfield?.display_name }}

+ } + @if (topic().field) { +

Fachgebiet: {{ topic().field?.display_name }}

+ } + @if (topic().domain) { +

Domäne: {{ topic().domain?.display_name }}

+ } +
+
diff --git a/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.scss b/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.scss new file mode 100644 index 00000000..f21f7243 --- /dev/null +++ b/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.scss @@ -0,0 +1,12 @@ +.topic-tooltip-card { + --topic-background: color-mix(in srgb, hsl(var(--topic-color)) 8%, #ffffff); + --topic-border: color-mix(in srgb, hsl(var(--topic-color)) 72%, #ffffff); + + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 0.5rem; + + background-color: var(--topic-background); + border: 1px solid var(--topic-border); +} diff --git a/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.ts b/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.ts new file mode 100644 index 00000000..5a8e032e --- /dev/null +++ b/webapp/src/app/shared/ui/topic-tooltip/topic-tooltip.component.ts @@ -0,0 +1,31 @@ +import { Component, computed, input } from '@angular/core'; +import { Topic } from '../../../api'; +import { MatCardModule } from '@angular/material/card'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; + +@Component({ + host: { + '[style.--topic-color]': 'color()', + }, + selector: 'app-topic-tooltip', + imports: [MatCardModule], + templateUrl: './topic-tooltip.component.html', + styleUrl: './topic-tooltip.component.scss', +}) +export class TopicTooltipComponent { + topic = input.required(); + + color = computed(() => { + const topic = this.topic(); + return topicHierarchyColor({ + id: topic.id ?? undefined, + name: topic.display_name ?? undefined, + field_id: topic.field?.id ?? undefined, + field_name: topic.field?.display_name ?? undefined, + domain_id: topic.domain?.id ?? undefined, + domain_name: topic.domain?.display_name ?? undefined, + }) + .replace('hsl(', '') + .replace(')', ''); + }); +} From 1810918e433c0551b808ffd67b56bee49538f937 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:22:50 +0200 Subject: [PATCH 2/9] move headers to function --- .../main/inse/integrations/elasticsearch.py | 33 ++++++++----------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index afc08614..83532750 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -110,6 +110,10 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: return None +def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]: + return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type} + + def _wrap_exception(e: Exception) -> Exception: logger.exception(f"Elasticsearch raised an exception: {e}") if isinstance(e, httpx.HTTPStatusError): @@ -177,8 +181,6 @@ async def search( elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - payload: Dict[str, Any] = {} if body is not None: @@ -221,7 +223,7 @@ async def search( try: response = await client.post( - f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=_headers(api_key) ) response.raise_for_status() return response.json() @@ -234,14 +236,13 @@ async def open_point_in_time( ) -> str: """Opens a point-in-time on the given index and returns its id.""" elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.post( f"{elasticsearch_url}/{index}/_pit", params={"keep_alive": keep_alive}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json()["id"] @@ -252,7 +253,6 @@ async def open_point_in_time( async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: @@ -260,7 +260,7 @@ async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: "DELETE", f"{elasticsearch_url}/_pit", json={"id": pit_id}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() except Exception as exc: @@ -281,7 +281,6 @@ async def scan( ``index.max_result_window``, so it can stream result sets larger than 10k. """ elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None @@ -301,7 +300,7 @@ async def scan( try: response = await client.post( - f"{elasticsearch_url}/_search", json=payload, headers=headers + f"{elasticsearch_url}/_search", json=payload, headers=_headers(api_key) ) response.raise_for_status() except Exception as exc: @@ -340,7 +339,6 @@ async def get( elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} params = {} if source is not None: @@ -349,7 +347,7 @@ async def get( client = get_client() try: response = await client.get( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers + f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=_headers(api_key) ) response.raise_for_status() return response.json() @@ -364,14 +362,13 @@ async def update( cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.post( f"{elasticsearch_url}/{index}/_update/{doc_id}", json={"doc": doc}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json() @@ -386,14 +383,13 @@ async def index_doc( cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.put( f"{elasticsearch_url}/{index}/_doc/{doc_id}", json=document, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json() @@ -432,7 +428,6 @@ async def count( cluster = clusters.pop() elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) @@ -443,7 +438,7 @@ async def count( client = get_client() try: response = await client.post( - f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=_headers(api_key) ) response.raise_for_status() return response.json().get("count", 0) @@ -474,7 +469,7 @@ async def msearch( cluster = c elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"} + headers = _headers(api_key, content_type="application/x-ndjson") lines = [] for idx, body in searches: @@ -493,7 +488,7 @@ async def msearch( response = await client.post( f"{elasticsearch_url}/_msearch", content=ndjson_payload.encode("utf-8"), - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() res_json = response.json() From b0e4ad639eecf9b57a97405bed31d7cdec0bfe40 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:34:02 +0200 Subject: [PATCH 3/9] centralize HTTP request handling --- .../main/inse/integrations/elasticsearch.py | 186 ++++++++---------- 1 file changed, 77 insertions(+), 109 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 83532750..250786af 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -129,6 +129,51 @@ def _wrap_exception(e: Exception) -> Exception: return ElasticsearchException(f"Unexpected Elasticsearch error: {e}") +async def _request( + method: str, + cluster: ESCluster, + path: str, + *, + json_body: Optional[Any] = None, + params: Optional[Dict[str, Any]] = None, + content: Optional[bytes] = None, + content_type: str = "application/json", +) -> httpx.Response: + """Sends an authenticated request to cluster and returns the raw response. + + Args: + method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE"). + cluster: The Elasticsearch cluster to send the request to. + path: The path appended to the cluster URL (without leading slash). + json_body: Optional JSON-serialisable request body. + params: Optional query parameters. + content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body. + content_type: The Content-Type header value. + + Returns: + httpx.Response: The successful response (status already checked). + """ + + elasticsearch_url, api_key = _cluster_credentials(cluster) + client = get_client() + + try: + response = await client.request( + method, + f"{elasticsearch_url}/{path}", + json=json_body, + params=params, + content=content, + headers=_headers(api_key, content_type=content_type), + ) + + response.raise_for_status() + + return response + except Exception as exc: + raise _wrap_exception(exc) from exc + + async def search( index: ESIndex | List[ESIndex] | str | List[str], query: Optional[Dict] = None, @@ -179,8 +224,6 @@ async def search( elif len(clusters) == 1: cluster = clusters.pop() - elasticsearch_url, api_key = _cluster_credentials(cluster) - payload: Dict[str, Any] = {} if body is not None: @@ -212,59 +255,33 @@ async def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" ) - client = get_client() logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" + f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" ) + if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) else: index_str = str(index) - try: - response = await client.post( - f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload) + + return response.json() async def open_point_in_time( index: str, keep_alive: str = "1m", cluster: str = "nes" ) -> str: """Opens a point-in-time on the given index and returns its id.""" - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive}) - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index}/_pit", - params={"keep_alive": keep_alive}, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json()["id"] - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json()["id"] async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" - elasticsearch_url, api_key = _cluster_credentials(cluster) - client = get_client() - try: - response = await client.request( - "DELETE", - f"{elasticsearch_url}/_pit", - json={"id": pit_id}, - headers=_headers(api_key), - ) - response.raise_for_status() - except Exception as exc: - raise _wrap_exception(exc) from exc + await _request("DELETE", cluster, "_pit", json_body={"id": pit_id}) async def scan( @@ -280,12 +297,9 @@ async def scan( Unlike ``from``/``size`` pagination, this is not bounded by ``index.max_result_window``, so it can stream result sets larger than 10k. """ - elasticsearch_url, api_key = _cluster_credentials(cluster) - pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None try: - client = get_client() while True: payload: Dict[str, Any] = { "size": page_size, @@ -298,14 +312,7 @@ async def scan( if search_after is not None: payload["search_after"] = search_after - try: - response = await client.post( - f"{elasticsearch_url}/_search", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - except Exception as exc: - raise _wrap_exception(exc) from exc - + response = await _request("POST", cluster, "_search", json_body=payload) result = response.json() hits = result.get("hits", {}).get("hits", []) @@ -337,22 +344,13 @@ async def get( if isinstance(index, ESIndex): cluster = _index_to_cluster(index) or cluster - elasticsearch_url, api_key = _cluster_credentials(cluster) - - params = {} if source is not None: params["_source_includes"] = ",".join(source) - client = get_client() - try: - response = await client.get( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params) + + return response.json() async def update( @@ -361,19 +359,11 @@ async def update( doc: Dict[str, Any], cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request( + "POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc} + ) - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index}/_update/{doc_id}", - json={"doc": doc}, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json() async def index_doc( @@ -382,19 +372,11 @@ async def index_doc( document: Dict[str, Any], cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request( + "PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document + ) - client = get_client() - try: - response = await client.put( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", - json=document, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json() async def count( @@ -427,23 +409,15 @@ async def count( if len(clusters) == 1: cluster = clusters.pop() - elasticsearch_url, api_key = _cluster_credentials(cluster) - if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) else: index_str = str(index) payload = {"query": query} if query else {} - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json().get("count", 0) - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload) + + return response.json().get("count", 0) async def msearch( @@ -468,9 +442,6 @@ async def msearch( if c is not None: cluster = c - elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = _headers(api_key, content_type="application/x-ndjson") - lines = [] for idx, body in searches: if isinstance(idx, list): @@ -483,16 +454,13 @@ async def msearch( ndjson_payload = "\n".join(lines) + "\n" - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/_msearch", - content=ndjson_payload.encode("utf-8"), - headers=_headers(api_key), - ) - response.raise_for_status() - res_json = response.json() - return res_json.get("responses", []) - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request( + "POST", + cluster, + "_msearch", + content=ndjson_payload.encode("utf-8"), + content_type="application/x-ndjson", + ) + + return response.json().get("responses", []) From 28726cf4c7c888572fa10ed115790944d0a83840 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:43:39 +0200 Subject: [PATCH 4/9] add env value to enable logging of outgoing Elasticsearch queries --- service/src/main/inse/.env | 3 +++ service/src/main/inse/integrations/elasticsearch.py | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 36f353cf..152f348d 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -12,6 +12,9 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +# Debugging: Log every outgoing Elasticsearch query (index + payload) +PRINT_ES_QUERIES=false + # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 250786af..2f0de418 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -255,9 +255,10 @@ async def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" ) - logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" - ) + if config.settings.print_es_queries: + logger.debug( + f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" + ) if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) From e57875d2a503c8be6b8ce547434903dfa5728a0f Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:48:35 +0200 Subject: [PATCH 5/9] add logging for Elasticsearch request timings --- service/src/main/inse/.env | 2 ++ service/src/main/inse/config.py | 2 ++ service/src/main/inse/integrations/elasticsearch.py | 13 +++++++++++++ 3 files changed, 17 insertions(+) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 152f348d..9fedc0af 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -14,6 +14,8 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Debugging: Log every outgoing Elasticsearch query (index + payload) PRINT_ES_QUERIES=false +# Debugging: Log the duration of every Elasticsearch request +PRINT_ES_TIMINGS=false # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index aebc16c6..6075aa8b 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -69,6 +69,8 @@ class Settings(BaseSettings): elasticsearch_api_key: Optional[str] = None elasticsearch_inse_url: Optional[str] = None elasticsearch_inse_api_key: Optional[str] = None + print_es_queries: bool = False + print_es_timings: bool = False model_config = SettingsConfigDict(env_file=str(ENV_FILE)) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 2f0de418..05a81575 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,5 +1,6 @@ import json import logging +import time from typing import Any, Dict, AsyncIterator, List, Optional, Tuple import httpx @@ -157,6 +158,7 @@ async def _request( elasticsearch_url, api_key = _cluster_credentials(cluster) client = get_client() + start = time.perf_counter() try: response = await client.request( method, @@ -169,8 +171,19 @@ async def _request( response.raise_for_status() + if config.settings.print_es_timings: + elapsed_ms = (time.perf_counter() - start) * 1000 + logger.debug( + f"Elasticsearch request {method} {path} on cluster '{cluster}' took {elapsed_ms:.1f} ms" + ) + return response except Exception as exc: + if config.settings.print_es_timings: + elapsed_ms = (time.perf_counter() - start) * 1000 + logger.debug( + f"Elasticsearch request {method} {path} on cluster '{cluster}' failed after {elapsed_ms:.1f} ms" + ) raise _wrap_exception(exc) from exc From 3ef8c2819139cdb89199b006806cd21293d6b1d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 26 Jul 2026 12:11:02 +0200 Subject: [PATCH 6/9] feat: added topics card search; dedicated chips, cards, and tooltips for authors, institutions, and topics --- service/src/main/inse/authors/v2/router.py | 2 +- service/src/main/inse/authors/v2/service.py | 2 +- .../src/main/inse/institutions/v2/router.py | 2 +- .../src/main/inse/institutions/v2/service.py | 2 +- service/src/main/inse/topics/v2/model.py | 8 ++ service/src/main/inse/topics/v2/router.py | 69 +++++++++- service/src/main/inse/topics/v2/service.py | 107 +++++++++++++- webapp/src/app/api/.openapi-generator/FILES | 1 + webapp/src/app/api/api/topicsV2.service.ts | 130 ++++++++++++++++++ webapp/src/app/api/model/models.ts | 1 + webapp/src/app/api/model/topicSortBy.ts | 18 +++ webapp/src/app/app.routes.ts | 46 +++++++ .../institutions/institutions.component.scss | 52 +------ .../person-publications.component.html | 1 + .../app/modules/topic/topic.component.html | 1 + .../app/modules/topic/topic.component.scss | 0 .../src/app/modules/topic/topic.component.ts | 11 ++ .../app/modules/topics/topics.component.html | 22 +++ .../app/modules/topics/topics.component.scss | 6 + .../app/modules/topics/topics.component.ts | 52 +++++++ .../src/app/resolvers/topic-page.resolver.ts | 39 ++++++ webapp/src/app/resolvers/topic.resolver.ts | 12 ++ .../app-author-card.component.html | 26 ++-- .../app-author-chip.component.html | 2 +- .../app-author-chip.component.scss | 30 ++++ .../app-author-chip.component.ts | 4 + .../app-institution-chip.component.html | 4 +- .../app-institution-chip.component.scss | 22 +++ .../app-institution-chip.component.ts | 6 +- .../app-institution-tooltip.component.ts | 7 - .../shared/ui/app-menu/app-menu.component.ts | 17 ++- .../app-topic-card.component.html | 52 +++++++ .../app-topic-card.component.scss | 49 +++++++ .../app-topic-card.component.ts | 58 ++++++++ .../app-topic-chip.component.html | 6 +- .../app-topic-chip.component.scss | 41 ++++++ .../app-topic-chip.component.ts | 60 ++++++-- .../app-topic-tooltip.component.html | 5 + .../app-topic-tooltip.component.scss | 0 .../app-topic-tooltip.component.ts | 32 +++++ .../publication-table.component.html | 29 ++-- .../publication-table.component.scss | 17 +-- .../publication-table.component.ts | 13 +- 43 files changed, 927 insertions(+), 137 deletions(-) create mode 100644 webapp/src/app/api/model/topicSortBy.ts create mode 100644 webapp/src/app/modules/topic/topic.component.html create mode 100644 webapp/src/app/modules/topic/topic.component.scss create mode 100644 webapp/src/app/modules/topic/topic.component.ts create mode 100644 webapp/src/app/modules/topics/topics.component.html create mode 100644 webapp/src/app/modules/topics/topics.component.scss create mode 100644 webapp/src/app/modules/topics/topics.component.ts create mode 100644 webapp/src/app/resolvers/topic-page.resolver.ts create mode 100644 webapp/src/app/resolvers/topic.resolver.ts create mode 100644 webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html create mode 100644 webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.scss create mode 100644 webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts create mode 100644 webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.html create mode 100644 webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.scss create mode 100644 webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts diff --git a/service/src/main/inse/authors/v2/router.py b/service/src/main/inse/authors/v2/router.py index 3474728c..9fd0aa3d 100644 --- a/service/src/main/inse/authors/v2/router.py +++ b/service/src/main/inse/authors/v2/router.py @@ -30,7 +30,7 @@ async def get_author_by_id( Path(description="The ID of the author to retrieve."), ], ) -> Author: - return await authors_service.get_author_by_id_strict( + return await authors_service.get_author_by_id_strict_or_raise( raw_oa_author_id=raw_oa_author_id ) diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index 3fe2600c..f2abbaba 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -86,7 +86,7 @@ async def get_author_by_id(raw_oa_author_id: str) -> Author | None: return Author.from_dict(response.get("_source", {})) # type: ignore -async def get_author_by_id_strict(raw_oa_author_id: str) -> Author: +async def get_author_by_id_strict_or_raise(raw_oa_author_id: str) -> Author: """Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID. Args: diff --git a/service/src/main/inse/institutions/v2/router.py b/service/src/main/inse/institutions/v2/router.py index c6119a40..6cd9ad36 100644 --- a/service/src/main/inse/institutions/v2/router.py +++ b/service/src/main/inse/institutions/v2/router.py @@ -25,7 +25,7 @@ async def get_institution_by_id( Path(description="The ID of the institution to retrieve."), ], ) -> Institution: - return await institutions_service.get_institution_by_id_strict( + return await institutions_service.get_institution_by_id_or_raise( raw_oa_institution_id=institution_id, source=[ "id", diff --git a/service/src/main/inse/institutions/v2/service.py b/service/src/main/inse/institutions/v2/service.py index b4bacd50..7b6876d0 100644 --- a/service/src/main/inse/institutions/v2/service.py +++ b/service/src/main/inse/institutions/v2/service.py @@ -29,7 +29,7 @@ async def get_institution_by_id( return Institution.from_dict(response.get("_source", {})) # type: ignore -async def get_institution_by_id_strict( +async def get_institution_by_id_or_raise( raw_oa_institution_id: str, source: list[str] | None = None ) -> Institution: """Retrieves an institution by its ID from the OpenAlex Elasticsearch index, raising an exception if not found. diff --git a/service/src/main/inse/topics/v2/model.py b/service/src/main/inse/topics/v2/model.py index 92931d63..7c005cb9 100644 --- a/service/src/main/inse/topics/v2/model.py +++ b/service/src/main/inse/topics/v2/model.py @@ -1,6 +1,14 @@ +from enum import StrEnum + from inse.model import Page from inse.models.openalex.topic import Topic +class TopicSortBy(StrEnum): + DISPLAY_NAME = "display_name" + WORKS_COUNT = "works_count" + CITED_BY_COUNT = "cited_by_count" + + class TopicPageV2(Page[Topic]): pass diff --git a/service/src/main/inse/topics/v2/router.py b/service/src/main/inse/topics/v2/router.py index 770b8af8..f382d5a0 100644 --- a/service/src/main/inse/topics/v2/router.py +++ b/service/src/main/inse/topics/v2/router.py @@ -2,10 +2,12 @@ import logging from typing import Annotated import inse.topics.v2.service as topics_service -from fastapi import APIRouter, Query +from fastapi import APIRouter, Path, Query +from inse.model import SortDirection +from inse.models.openalex.topic import Topic from inse.router_prefixes import RouterPrefixes from inse.tags import Tags -from inse.topics.v2.model import TopicPageV2 +from inse.topics.v2.model import TopicPageV2, TopicSortBy logger = logging.getLogger(__name__) @@ -13,6 +15,69 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix=RouterPrefixes.TOPICS_V2, tags=[Tags.TOPICS_V2]) +@router.get( + "/search", + operation_id="searchTopics", + summary="Searches for topics based on the provided criteria.", +) +async def search_topics( + search_term: Annotated[ + str | None, + Query(description="The term to search for in topic display names."), + ] = None, + page: Annotated[ + int, + Query( + description="The page number to retrieve.", + ge=0, + ), + ] = 0, + size: Annotated[ + int, + Query( + description="The number of topics to retrieve per page.", + ge=1, + le=100, + ), + ] = 10, + sort_by: Annotated[ + TopicSortBy, + Query( + description="The field to sort by.", + ), + ] = TopicSortBy.WORKS_COUNT, + sort_direction: Annotated[ + SortDirection, + Query( + description="The direction to sort.", + ), + ] = SortDirection.DESCENDING, +) -> TopicPageV2: + return await topics_service.search_topics( + search_term=search_term, + page=page, + size=size, + sort_by=sort_by, + sort_direction=sort_direction, + ) + + +@router.get( + "/single/{raw_oa_topic_id}", + operation_id="getTopicById", + summary="Returns a topic for a given topic ID.", +) +async def get_topic_by_id( + raw_oa_topic_id: Annotated[ + str, + Path(description="The ID of the topic to retrieve."), + ], +) -> Topic: + return await topics_service.get_topic_by_id_or_raise( + raw_oa_topic_id=raw_oa_topic_id + ) + + @router.get( "/topics/id", operation_id="getTopicsByIds", diff --git a/service/src/main/inse/topics/v2/service.py b/service/src/main/inse/topics/v2/service.py index 8ffb73e3..d8f3f604 100644 --- a/service/src/main/inse/topics/v2/service.py +++ b/service/src/main/inse/topics/v2/service.py @@ -1,11 +1,11 @@ - +from inse.exceptions import NotFoundException from inse.integrations import elasticsearch -from inse.model import ESIndex +from inse.model import ESIndex, SortDirection from inse.models.openalex.topic import Topic -from inse.topics.v2.model import TopicPageV2 +from inse.topics.v2.model import TopicPageV2, TopicSortBy -async def search_topics( +async def _search_topics( page: int = 0, size: int = 10, query: dict | None = None, @@ -45,6 +45,54 @@ async def search_topics( return TopicPageV2(elements=topics, total=len(topics), page=page, size=size) +async def search_topics( + search_term: str | None = None, + page: int = 0, + size: int = 10, + sort_by: TopicSortBy = TopicSortBy.WORKS_COUNT, + sort_direction: SortDirection = SortDirection.DESCENDING, +) -> TopicPageV2: + """Searches for topics based on a search term. + + Args: + search_term (str | None): The term to search for in topic display names. Defaults to None. + page (int, optional): The page number to retrieve. Defaults to 0. + size (int, optional): The number of topics to retrieve per page. Defaults to 10. + sort_by (TopicSortBy, optional): The field to sort by. Defaults to TopicSortBy.WORKS_COUNT. + sort_direction (SortDirection, optional): The direction to sort. Defaults to SortDirection.DESCENDING. + + Returns: + TopicPageV2: A page of topics matching the search term. + """ + + sort = None + if sort_by in [TopicSortBy.DISPLAY_NAME]: + sort = [{f"{sort_by.value}.keyword": {"order": sort_direction.value}}] + else: + sort = [{sort_by.value: {"order": sort_direction.value}}] + + query = None + if search_term: + query = {"match_phrase_prefix": {"display_name": search_term}} + + return await _search_topics( + page=page, + size=size, + query=query, + source=[ + "id", + "display_name", + "description", + "subfield", + "field", + "domain", + "works_count", + "cited_by_count", + ], + sort=sort, + ) + + async def autocomplete_topics_for_selector(query: str) -> TopicPageV2: """Autocompletes topics based on a search term for use in a selector component. @@ -54,7 +102,7 @@ async def autocomplete_topics_for_selector(query: str) -> TopicPageV2: Returns: TopicPageV2: A page of topics matching the autocomplete criteria. """ - return await search_topics( + return await _search_topics( page=0, size=10, query={"match_phrase_prefix": {"display_name": query}}, @@ -68,6 +116,53 @@ async def autocomplete_topics_for_selector(query: str) -> TopicPageV2: ) +async def get_topic_by_id(raw_oa_topic_id: str) -> Topic | None: + """Retrieves a topic based on its ID. + + Args: + raw_oa_topic_id (str): The ID of the topic to retrieve. + + Returns: + Topic | None: The topic matching the provided ID, or None if not found. + """ + response = await elasticsearch.get( + index=ESIndex.OPENALEX_TOPICS, + doc_id=raw_oa_topic_id, + source=[ + "id", + "display_name", + "description", + "subfield", + "field", + "domain", + "works_count", + "cited_by_count", + ], + ) + if response.get("found"): + _source = response.get("_source", {}) + return Topic.from_dict(_source) # type: ignore + return None + + +async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic: + """Retrieves a topic based on its ID, raising an exception if not found. + + Args: + raw_oa_topic_id (str): The ID of the topic to retrieve. + + Raises: + NotFoundException: If the topic with the specified ID is not found. + + Returns: + Topic: The topic matching the provided ID. + """ + topic = await get_topic_by_id(raw_oa_topic_id) + if topic is None: + raise NotFoundException(f"Topic with ID {raw_oa_topic_id} not found.") + return topic + + async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2: """Retrieves topics based on a list of topic IDs. @@ -80,7 +175,7 @@ async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2: if not topic_ids: return TopicPageV2(elements=[], total=0, page=0, size=0) - return await search_topics( + return await _search_topics( page=0, size=len(topic_ids), query={"terms": {"id": topic_ids}}, diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index ebf76e14..aa27aeaa 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -249,6 +249,7 @@ model/topicHeatmapTopic.ts model/topicHeatmapValue.ts model/topicIds.ts model/topicPageV2.ts +model/topicSortBy.ts model/topicSubfield.ts model/topicWordCloud.ts model/topicWordCloudWord.ts diff --git a/webapp/src/app/api/api/topicsV2.service.ts b/webapp/src/app/api/api/topicsV2.service.ts index 92f5b93f..674c4906 100644 --- a/webapp/src/app/api/api/topicsV2.service.ts +++ b/webapp/src/app/api/api/topicsV2.service.ts @@ -19,7 +19,13 @@ import { Observable } from 'rxjs'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { SortDirection } from '../model/sortDirection'; +// @ts-ignore +import { Topic } from '../model/topic'; +// @ts-ignore import { TopicPageV2 } from '../model/topicPageV2'; +// @ts-ignore +import { TopicSortBy } from '../model/topicSortBy'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -94,6 +100,61 @@ export class TopicsV2Service extends BaseService { ); } + /** + * Returns a topic for a given topic ID. + * @endpoint get /api/topics/v2/single/{raw_oa_topic_id} + * @param rawOaTopicId The ID of the topic to retrieve. + * @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 getTopicById(rawOaTopicId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicById(rawOaTopicId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicById(rawOaTopicId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicById(rawOaTopicId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaTopicId === null || rawOaTopicId === undefined) { + throw new Error('Required parameter rawOaTopicId was null or undefined when calling getTopicById.'); + } + + 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; + + + 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/topics/v2/single/${this.configuration.encodeParam({name: "rawOaTopicId", value: rawOaTopicId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Returns a paginated list of topics for a given list of topic IDs. * @endpoint get /api/topics/v2/topics/id @@ -155,4 +216,73 @@ export class TopicsV2Service extends BaseService { ); } + /** + * Searches for topics based on the provided criteria. + * @endpoint get /api/topics/v2/search + * @param searchTerm The term to search for in topic display names. + * @param page The page number to retrieve. + * @param size The number of topics to retrieve per page. + * @param sortBy The field to sort by. + * @param sortDirection The direction to sort. + * @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 searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + searchTerm, 'search_term'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortDirection, 'sort_direction'); + + 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; + + + 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/topics/v2/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index e20b3035..8d3b5ec2 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -214,6 +214,7 @@ export * from './topicHeatmapTopic'; export * from './topicHeatmapValue'; export * from './topicIds'; export * from './topicPageV2'; +export * from './topicSortBy'; export * from './topicSubfield'; export * from './topicWordCloud'; export * from './topicWordCloudWord'; diff --git a/webapp/src/app/api/model/topicSortBy.ts b/webapp/src/app/api/model/topicSortBy.ts new file mode 100644 index 00000000..be83fa8e --- /dev/null +++ b/webapp/src/app/api/model/topicSortBy.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. + */ + + +export const TopicSortBy = { + DisplayName: 'display_name', + WorksCount: 'works_count', + CitedByCount: 'cited_by_count' +} as const; +export type TopicSortBy = typeof TopicSortBy[keyof typeof TopicSortBy]; + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index fc5488c8..43ef3e86 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -58,6 +58,11 @@ import { collaborationGraphQueryParamKeys, collaborationGraphResolver, } from './resolvers/collaboration-graph.resolver'; +import { + topicPageResolver, + topicQueryParamKeys, +} from './resolvers/topic-page.resolver'; +import { topicResolver } from './resolvers/topic.resolver'; export const routes: Routes = [ { path: '', @@ -704,6 +709,47 @@ export const routes: Routes = [ }, ], }, + { + path: 'topics', + canActivate: [ + roleGuard([ + UserRole.User, + UserRole.Manager, + UserRole.Admin, + UserRole.SuperAdmin, + ]), + ], + loadComponent: () => + import('./modules/topics/topics.component').then( + (mod) => mod.TopicsComponent, + ), + resolve: { + topicPage: topicPageResolver, + }, + runGuardsAndResolvers: (from, to) => { + return Object.values(topicQueryParamKeys).some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, + }, + { + path: 'topic/:topicId', + canActivate: [ + roleGuard([ + UserRole.User, + UserRole.Manager, + UserRole.Admin, + UserRole.SuperAdmin, + ]), + ], + loadComponent: () => + import('./modules/topic/topic.component').then( + (mod) => mod.TopicComponent, + ), + resolve: { + topic: topicResolver, + }, + }, { path: 'projects', canActivate: [ diff --git a/webapp/src/app/modules/institutions/institutions.component.scss b/webapp/src/app/modules/institutions/institutions.component.scss index ce9afb83..080f9ff6 100644 --- a/webapp/src/app/modules/institutions/institutions.component.scss +++ b/webapp/src/app/modules/institutions/institutions.component.scss @@ -3,54 +3,4 @@ flex-direction: column; gap: 1rem; padding: 1rem; -} - -.cards { - display: grid; - gap: 1.5rem; - grid-template-columns: repeat(auto-fit, minmax(550px, 1fr)); - padding: 0 1rem; -} - -.card { - padding: 0.5rem; - background-color: var(--sg-background); - transition: transform 0.3s ease; - display: flex; - flex-direction: column; - gap: 0.5rem; -} - -.card:hover { - cursor: pointer; - transform: scale(1.05); -} - -.card-content { - display: flex; - flex-direction: column; - justify-content: flex-end; - gap: 0.5rem; - flex: 1; -} - -.card-metadata { - display: flex; - flex-direction: column; - gap: 0.2rem; - font-size: 0.9rem; - color: var(--sg-text-secondary); -} - -mat-card-actions { - padding-top: 0.5rem; - display: flex; - gap: 0.5rem; -} - -mat-card-actions a { - width: 100%; - text-decoration: none; - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); -} +} \ No newline at end of file diff --git a/webapp/src/app/modules/person-publications/person-publications.component.html b/webapp/src/app/modules/person-publications/person-publications.component.html index 57660c31..97c89212 100644 --- a/webapp/src/app/modules/person-publications/person-publications.component.html +++ b/webapp/src/app/modules/person-publications/person-publications.component.html @@ -32,6 +32,7 @@ topic works!

diff --git a/webapp/src/app/modules/topic/topic.component.scss b/webapp/src/app/modules/topic/topic.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/modules/topic/topic.component.ts b/webapp/src/app/modules/topic/topic.component.ts new file mode 100644 index 00000000..c1827f18 --- /dev/null +++ b/webapp/src/app/modules/topic/topic.component.ts @@ -0,0 +1,11 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-topic', + imports: [], + templateUrl: './topic.component.html', + styleUrl: './topic.component.scss', +}) +export class TopicComponent { + +} diff --git a/webapp/src/app/modules/topics/topics.component.html b/webapp/src/app/modules/topics/topics.component.html new file mode 100644 index 00000000..c0c6ff23 --- /dev/null +++ b/webapp/src/app/modules/topics/topics.component.html @@ -0,0 +1,22 @@ +
+

Passende Themen finden

+ + + + +
+ + + + diff --git a/webapp/src/app/modules/topics/topics.component.scss b/webapp/src/app/modules/topics/topics.component.scss new file mode 100644 index 00000000..ef8c12a0 --- /dev/null +++ b/webapp/src/app/modules/topics/topics.component.scss @@ -0,0 +1,6 @@ +.content { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1rem; +} diff --git a/webapp/src/app/modules/topics/topics.component.ts b/webapp/src/app/modules/topics/topics.component.ts new file mode 100644 index 00000000..1e017d27 --- /dev/null +++ b/webapp/src/app/modules/topics/topics.component.ts @@ -0,0 +1,52 @@ +import { Component, computed, input } from '@angular/core'; +import { + CardSearchComponent, + Page, +} from '../../shared/ui/card-search/card-search.component'; +import { MatDividerModule } from '@angular/material/divider'; +import { AppTopicCardComponent } from '../../shared/ui/app-topic-card/app-topic-card.component'; +import { SortDirection, TopicPageV2, TopicSortBy } from '../../api'; +import { FilterObserver } from '../../shared/ui/selected-filters/selected-filters.component'; +import { topicQueryParamKeys } from '../../resolvers/topic-page.resolver'; +import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; + +@Component({ + selector: 'app-topics', + imports: [CardSearchComponent, MatDividerModule, AppTopicCardComponent], + templateUrl: './topics.component.html', + styleUrl: './topics.component.scss', +}) +export class TopicsComponent { + topicPage = input.required(); + + observers: FilterObserver[] = [ + { + id: 'query', + queryParamKey: topicQueryParamKeys.query, + icon: 'search', + }, + ]; + + readonly topicSearchQueryParamKey = topicQueryParamKeys.query; + readonly topicSortByQueryParamKey = topicQueryParamKeys.sortBy; + readonly topicSortingDirectionQueryParamKey = + topicQueryParamKeys.sortDirection; + + page = computed(() => ({ + page: this.topicPage().page || 0, + size: this.topicPage().size || 10, + total: this.topicPage().total || 0, + elements: this.topicPage().elements || [], + })); + + sortingOptions: SelectorOption[] = [ + { value: TopicSortBy.DisplayName, display_name: 'Name' }, + { value: TopicSortBy.WorksCount, display_name: 'Anzahl Publikationen' }, + { value: TopicSortBy.CitedByCount, display_name: 'Anzahl Zitationen' }, + ]; + + sortingDirectionOptions: SelectorOption[] = [ + { value: SortDirection.Asc, display_name: 'Aufsteigend' }, + { value: SortDirection.Desc, display_name: 'Absteigend' }, + ]; +} diff --git a/webapp/src/app/resolvers/topic-page.resolver.ts b/webapp/src/app/resolvers/topic-page.resolver.ts new file mode 100644 index 00000000..42122955 --- /dev/null +++ b/webapp/src/app/resolvers/topic-page.resolver.ts @@ -0,0 +1,39 @@ +import { ResolveFn } from '@angular/router'; +import { + SortDirection, + TopicPageV2, + TopicSortBy, + TopicsV2Service, +} from '../api'; +import { inject } from '@angular/core'; + +export const topicQueryParamKeys = { + query: 'query', + page: 'page', + size: 'size', + sortBy: 'sortBy', + sortDirection: 'sortDirection', +} as const; + +export const topicPageResolver: ResolveFn = (route, state) => { + const query = route.queryParamMap.get(topicQueryParamKeys.query) || undefined; + const page = Number(route.queryParamMap.get(topicQueryParamKeys.page) ?? '0'); + const size = Number( + route.queryParamMap.get(topicQueryParamKeys.size) ?? '10', + ); + const sortBy: TopicSortBy = + (route.queryParamMap.get(topicQueryParamKeys.sortBy) as TopicSortBy) ?? + TopicSortBy.WorksCount; + const sortDirection = + (route.queryParamMap.get( + topicQueryParamKeys.sortDirection, + ) as SortDirection) ?? SortDirection.Desc; + + return inject(TopicsV2Service).searchTopics( + query, + page, + size, + sortBy, + sortDirection, + ); +}; diff --git a/webapp/src/app/resolvers/topic.resolver.ts b/webapp/src/app/resolvers/topic.resolver.ts new file mode 100644 index 00000000..62bb4050 --- /dev/null +++ b/webapp/src/app/resolvers/topic.resolver.ts @@ -0,0 +1,12 @@ +import { ResolveFn } from '@angular/router'; +import { Topic, TopicsV2Service } from '../api'; +import { inject } from '@angular/core'; + +export const topicResolver: ResolveFn = (route, state) => { + const topicId = route.paramMap.get('topicId'); + if (!topicId) { + throw new Error('Topic ID is required'); + } + + return inject(TopicsV2Service).getTopicById(topicId); +}; diff --git a/webapp/src/app/shared/ui/app-author-card/app-author-card.component.html b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.html index 6197f645..b0db0217 100644 --- a/webapp/src/app/shared/ui/app-author-card/app-author-card.component.html +++ b/webapp/src/app/shared/ui/app-author-card/app-author-card.component.html @@ -1,9 +1,11 @@ +@let author = this.author(); + - {{ author().display_name }} - @if (author()?.last_known_institutions?.[0]?.display_name) { + {{ author.display_name }} + @if (author.last_known_institutions?.[0]?.display_name) { - {{ author()?.last_known_institutions?.[0]?.display_name }} + {{ author.last_known_institutions?.[0]?.display_name }} } @@ -11,22 +13,22 @@ - @if (author().works_count) { + @if (author.works_count) {
menu_book - {{ author().works_count }} Publikationen + {{ author.works_count }} Publikationen
} - @if (author().cited_by_count) { + @if (author.cited_by_count) {
format_quote - {{ author().cited_by_count }} Zitationen + {{ author.cited_by_count }} Zitationen
} - @if (author().summary_stats?.h_index) { + @if (author.summary_stats?.h_index) {
trending_up - h-Index: {{ author().summary_stats?.h_index }} + h-Index: {{ author.summary_stats?.h_index }}
}
@@ -37,21 +39,21 @@ info Übersicht menu_book Publikationen work Projekte diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html index 470511be..f7f171da 100644 --- a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.html @@ -4,7 +4,7 @@ [tooltipInputs]="{ authorId: rawOaAuthorId() }" (keydown)="_onChipClick($event)" (click)="_onChipClick($event)"> - + @if (showIcon()) { {{ icon() }} } diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss index db1e34d7..6414ee8a 100644 --- a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.scss @@ -24,3 +24,33 @@ cursor: pointer; } } + +.chip-content { + display: flex; + align-items: center; + gap: 0.5rem; +} + +:host.is-mini-size { + ::ng-deep .mat-mdc-chip { + height: 1.5rem; + } + + .chip-content { + font-size: 0.75rem; + } + + mat-icon { + font-size: 0.75rem; + width: 0.75rem; + height: 0.75rem; + } +} + +.topic-icon { + --icon-size: 1rem; + + font-size: var(--icon-size); + height: var(--icon-size); + width: var(--icon-size); +} diff --git a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts index cf63887b..60995687 100644 --- a/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts +++ b/webapp/src/app/shared/ui/app-author-chip/app-author-chip.component.ts @@ -19,6 +19,7 @@ import { MatChipsModule } from '@angular/material/chips'; '[style.--border-color]': 'isSelected() ? "var(--sg-primary)" : "var(--sg-border)"', '[class.is-clickable]': 'isClickable()', + '[class.is-mini-size]': 'isMiniSize()', }, selector: 'app-author-chip', imports: [MatIconModule, MatChipsModule, ComponentTooltipDirective], @@ -45,6 +46,9 @@ export class AppAuthorChipComponent { _author = signal(undefined); + size = input<'normal' | 'mini'>('normal'); + isMiniSize = computed(() => this.size() === 'mini'); + constructor() { effect(() => { const author = this.author(); diff --git a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html index 3e07cb38..b643580c 100644 --- a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html +++ b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.html @@ -1,10 +1,10 @@ - + @if (showIcon()) { {{ icon() }} } diff --git a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss index c919dcbc..5ec57954 100644 --- a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss +++ b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.scss @@ -24,3 +24,25 @@ cursor: pointer; } } + +.chip-content { + display: flex; + align-items: center; + gap: 0.5rem; +} + +:host.is-mini-size { + ::ng-deep .mat-mdc-chip { + height: 1.5rem; + } + + .chip-content { + font-size: 0.75rem; + } + + mat-icon { + font-size: 0.75rem; + width: 0.75rem; + height: 0.75rem; + } +} diff --git a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts index 9200dd3b..5a2a333b 100644 --- a/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts +++ b/webapp/src/app/shared/ui/app-institution-chip/app-institution-chip.component.ts @@ -19,6 +19,7 @@ import { ComponentTooltipDirective } from '../../../directives/component-tooltip '[style.--border-color]': 'isSelected() ? "var(--sg-primary)" : "var(--sg-border)"', '[class.is-clickable]': 'isClickable()', + '[class.is-mini-size]': 'isMiniSize()', }, selector: 'app-institution-chip', imports: [MatIconModule, MatChipsModule, ComponentTooltipDirective], @@ -26,7 +27,7 @@ import { ComponentTooltipDirective } from '../../../directives/component-tooltip styleUrl: './app-institution-chip.component.scss', }) export class AppInstitutionChipComponent { - readonly InstitutionTooltipComponent = AppInstitutionTooltipComponent; + readonly AppInstitutionTooltipComponent = AppInstitutionTooltipComponent; private readonly institutionsService = inject(InstitutionsV2Service); isSelected = input(false); @@ -45,6 +46,9 @@ export class AppInstitutionChipComponent { _institution = signal(undefined); + size = input<'normal' | 'mini'>('normal'); + isMiniSize = computed(() => this.size() === 'mini'); + constructor() { effect(() => { const institution = this.institution(); diff --git a/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts index 4a35f5d9..2204746e 100644 --- a/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts +++ b/webapp/src/app/shared/ui/app-institution-tooltip/app-institution-tooltip.component.ts @@ -32,11 +32,4 @@ export class AppInstitutionTooltipComponent { }); }); } - - stripOpenAlexId(id: string | null | undefined): string | undefined { - if (!id) { - return undefined; - } - return id.replace('https://openalex.org/', ''); - } } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 25b9782e..df9ee95e 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -12,6 +12,8 @@ import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation import { MatCardContent, MatCardModule } from '@angular/material/card'; import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { activeInstitutionPersonListQueryParams } from '../../person-list-query-params'; +import { topicQueryParamKeys } from '../../../resolvers/topic-page.resolver'; +import { SortDirection, TopicSortBy } from '../../../api'; type NavItem = { label: string; @@ -101,7 +103,20 @@ export class AppMenuComponent { page: 0, size: 10, sort_by: 'works_count', - sorting_order: 'desc', + sorting_order: SortDirection.Desc, + }, + }, + { + label: 'Themen', + icon: 'topic', + route: '/topics', + disabled: false, + queryParams: { + [topicQueryParamKeys.query]: '', + [topicQueryParamKeys.page]: 0, + [topicQueryParamKeys.size]: 10, + [topicQueryParamKeys.sortBy]: TopicSortBy.CitedByCount, + [topicQueryParamKeys.sortDirection]: SortDirection.Desc, }, }, { diff --git a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html new file mode 100644 index 00000000..66b53915 --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html @@ -0,0 +1,52 @@ +@let topic = this.topic(); + + + + {{ topic.display_name }} + {{ subtitle() }} + + + + + +

{{ description() }}

+
+
+ menu_book + {{ + topic.works_count | number: undefined : 'de' + }} + Publikationen +
+
+ format_quote + {{ + topic.cited_by_count | number: undefined : 'de' + }} + Zitationen +
+
+
+ + + + + +
+ info + Übersicht + +
+ +
diff --git a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.scss b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.scss new file mode 100644 index 00000000..4545bac8 --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.scss @@ -0,0 +1,49 @@ +:host { + --topic-border: color-mix(in srgb, hsl(var(--topic-color)) 72%, #ffffff); + --topic-background: color-mix(in srgb, hsl(var(--topic-color)) 8%, #ffffff); + + --mat-divider-color: var(--topic-border); + + ::ng-deep .mdc-button--outlined { + border-color: var(--topic-border) !important; + } +} + +.card-content { + display: flex; + flex-direction: column; + gap: 1rem; + + background-color: var(--topic-background); + border: 1px solid var(--topic-border); +} + +.subtitle { + display: flex; + align-items: center; + gap: 0.5rem; + color: var(--sg-text-muted); +} + +.metrics { + display: flex; + flex-direction: column; + gap: 0.5rem; + font-size: 0.875rem; +} + +.metric-item { + display: flex; + align-items: center; + gap: 0.25rem; + color: var(--sg-text-muted); +} + +.card-actions { + display: flex; + gap: 0.5rem; +} + +.card-action { + width: 100%; +} diff --git a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts new file mode 100644 index 00000000..ecf8affe --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.ts @@ -0,0 +1,58 @@ +import { Component, computed, input } from '@angular/core'; +import { Topic } from '../../../api'; +import { MatCardModule } from '@angular/material/card'; +import { MatDividerModule } from '@angular/material/divider'; +import { MatIconModule } from '@angular/material/icon'; +import { RouterModule } from '@angular/router'; +import { DecimalPipe } from '@angular/common'; +import { MatButtonModule } from '@angular/material/button'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; + +@Component({ + host: { + '[style.--topic-color]': 'color()', + }, + selector: 'app-topic-card', + imports: [ + MatCardModule, + MatDividerModule, + MatIconModule, + MatButtonModule, + RouterModule, + DecimalPipe, + ], + templateUrl: './app-topic-card.component.html', + styleUrl: './app-topic-card.component.scss', +}) +export class AppTopicCardComponent { + topic = input.required(); + + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); + } + + subtitle = computed(() => { + return `${this.topic().subfield?.display_name} - ${this.topic().field?.display_name} - ${this.topic().domain?.display_name}`; + }); + + description = computed(() => { + return this.topic().description || 'Keine Beschreibung verfügbar'; + }); + + color = computed(() => { + const topic = this.topic(); + return topicHierarchyColor({ + id: topic.id ?? undefined, + name: topic.display_name ?? undefined, + field_id: topic.field?.id ?? undefined, + field_name: topic.field?.display_name ?? undefined, + domain_id: topic.domain?.id ?? undefined, + domain_name: topic.domain?.display_name ?? undefined, + }) + .replace('hsl(', '') + .replace(')', ''); + }); +} diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html index 007218f5..11bbb37d 100644 --- a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html @@ -1,10 +1,10 @@ - + @if (showIcon()) { {{ icon() }} } diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss index e8ee4118..f6e768ce 100644 --- a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss @@ -6,6 +6,9 @@ background-color: var(--topic-background); border: 1px solid var(--topic-border); border-radius: var(--sg-radius-sm); + display: flex; + align-items: center; + gap: 0.5rem; } :host.is-clickable { @@ -13,3 +16,41 @@ cursor: pointer; } } + +:host.is-selected { + --topic-border: color-mix(in srgb, hsl(var(--topic-color)) 72%, #ffffff); + + border: 1px solid white; + border-radius: var(--sg-radius-sm); + box-shadow: 0 0 0 2px var(--topic-border); +} + +.chip-content { + display: flex; + align-items: center; + gap: 0.5rem; +} + +:host.is-mini-size { + ::ng-deep .mat-mdc-chip { + height: 1.5rem; + } + + .chip-content { + font-size: 0.75rem; + } + + mat-icon { + font-size: 0.75rem; + width: 0.75rem; + height: 0.75rem; + } +} + +.topic-icon { + --icon-size: 1rem; + + font-size: var(--icon-size); + height: var(--icon-size); + width: var(--icon-size); +} diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts index 793ff652..d0859901 100644 --- a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.ts @@ -1,15 +1,26 @@ -import { Component, computed, input, output } from '@angular/core'; -import { Topic } from '../../../api'; -import { TopicTooltipComponent } from '../topic-tooltip/topic-tooltip.component'; +import { + Component, + computed, + effect, + inject, + input, + output, + signal, +} from '@angular/core'; +import { Topic, TopicsV2Service } from '../../../api'; import { MatChipsModule } from '@angular/material/chips'; import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { MatIconModule } from '@angular/material/icon'; +import { AppTopicTooltipComponent } from '../app-topic-tooltip/app-topic-tooltip.component'; @Component({ host: { '[style.--topic-color]': 'color()', + '[style.--border-width]': 'isSelected() ? "3px" : "1px"', '[class.is-clickable]': 'isClickable()', + '[class.is-selected]': 'isSelected()', + '[class.is-mini-size]': 'isMiniSize()', }, selector: 'app-topic-chip-2', imports: [MatChipsModule, ComponentTooltipDirective, MatIconModule], @@ -17,9 +28,18 @@ import { MatIconModule } from '@angular/material/icon'; styleUrl: './app-topic-chip.component.scss', }) export class AppTopicChipComponent { - readonly TopicToolTipComponent = TopicTooltipComponent; + readonly AppTopicTooltipComponent = AppTopicTooltipComponent; + private readonly topicsService = inject(TopicsV2Service); topic = input.required(); + rawOaTopicId = computed(() => { + return this.stripOpenAlexId(this.topic()?.id); + }); + topicId = input(undefined); + _topic = signal(undefined); + + size = input<'normal' | 'mini'>('normal'); + isMiniSize = computed(() => this.size() === 'mini'); isSelected = input(false); @@ -27,11 +47,29 @@ export class AppTopicChipComponent { handleChipClick = output(); showIcon = input(false); - icon = input('label'); + icon = input('topic'); showCount = input(false); count = input(0); + constructor() { + effect(() => { + const topic = this.topic(); + const topicId = this.topicId(); + if (!topic && !topicId) { + this._topic.set(undefined); + } + + if (topic) { + this._topic.set(topic); + } else if (topicId) { + this.topicsService.getTopicById(topicId).subscribe((fetchedTopic) => { + this._topic.set(fetchedTopic); + }); + } + }); + } + color = computed(() => { const topic = this.topic(); return topicHierarchyColor({ @@ -47,10 +85,16 @@ export class AppTopicChipComponent { }); _onChipClick(event: MouseEvent | KeyboardEvent) { - if (this.handleChipClick) { - this.handleChipClick.emit(this.topic()); + const topic = this.topic(); + if (this.isClickable() && this.handleChipClick && topic) { + this.handleChipClick.emit(topic); } + } - console.log('Chip clicked:', event); + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); } } diff --git a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.html b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.html new file mode 100644 index 00000000..e34a20b3 --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.html @@ -0,0 +1,5 @@ +@let topic = this._topic(); + +@if (topic) { + +} diff --git a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.scss b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts new file mode 100644 index 00000000..f86a6750 --- /dev/null +++ b/webapp/src/app/shared/ui/app-topic-tooltip/app-topic-tooltip.component.ts @@ -0,0 +1,32 @@ +import { Component, effect, inject, input, signal } from '@angular/core'; +import { Topic, TopicsV2Service } from '../../../api'; +import { AppTopicCardComponent } from '../app-topic-card/app-topic-card.component'; + +@Component({ + selector: 'app-app-topic-tooltip', + imports: [AppTopicCardComponent], + templateUrl: './app-topic-tooltip.component.html', + styleUrl: './app-topic-tooltip.component.scss', +}) +export class AppTopicTooltipComponent { + private readonly topicsService = inject(TopicsV2Service); + + topicId = input.required(); + + _topic = signal(undefined); + + _isLoading = signal(false); + constructor() { + effect(() => { + const topicId = this.topicId(); + if (!topicId) { + this._topic.set(undefined); + } + this._isLoading.set(true); + this.topicsService.getTopicById(topicId).subscribe((topic) => { + this._topic.set(topic); + this._isLoading.set(false); + }); + }); + } +} 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 9b7cb52e..a54e65a6 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 @@ -79,15 +79,16 @@ ? publicationInstitutions : publicationInstitutions.slice(0, 3);
@for (institution of visibleInstitutions; track institution.id) { } @empty { - @@ -113,16 +114,17 @@ @let workAuthorsExpanded = isWorkAuthorsExpanded(work); @let visibleAuthors = workAuthorsExpanded ? workAuthors : workAuthors.slice(0, 3); -
+
@for ( author of visibleAuthors; track author.id ?? 'name-' + author.display_name ) { } @empty { - @@ -141,25 +143,14 @@ @let workTopics = work.topics ?? []; -
+
@for (topic of workTopics; track topic.id) { - - } @empty { - 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 fe4f1b94..11d10c7f 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 @@ -432,18 +432,10 @@ table.is-hidden { } } -.topic-chips, .institution-tags { display: flex; flex-wrap: wrap; gap: 6px; -} - -.topic-chips { - max-width: 320px; -} - -.institution-tags { align-items: flex-start; max-width: 280px; } @@ -585,10 +577,13 @@ mat-panel-description { } // ------------------------ -.author-tags { +.institution-chips, +.topic-chips, +.author-chips { + padding: 0.5rem 0; display: flex; flex-wrap: wrap; - gap: 0.5rem; + gap: 0.25rem; align-items: flex-start; - max-width: 280px; + max-width: 350px; } 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 9d3a7f35..57cf16bf 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 @@ -20,9 +20,7 @@ import { WorkClassification, WorksV2Service, WorkTopic, - Topic, } from '../../../api'; -import { TopicChipComponent } from '../topic-chip/topic-chip.component'; import { MatIconModule } from '@angular/material/icon'; import { toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; @@ -34,11 +32,10 @@ import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; import { MatButtonModule } from '@angular/material/button'; import { workQueryParamKeys } from '../../../resolvers/work-page.resolver'; import { WorkPrimaryCategoryPipe } from '../../pipes/work-primary-category.pipe'; -import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive'; import { TopicTooltipComponent } from '../topic-tooltip/topic-tooltip.component'; import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; -import { AppAuthorChipComponent } from "../app-author-chip/app-author-chip.component"; -import { AppInstitutionChipComponent } from "../app-institution-chip/app-institution-chip.component"; +import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component'; +import { AppInstitutionChipComponent } from '../app-institution-chip/app-institution-chip.component'; @Component({ selector: 'app-publication-table', @@ -48,16 +45,14 @@ import { AppInstitutionChipComponent } from "../app-institution-chip/app-institu MatButtonModule, RouterModule, DataTableComponent, - TopicChipComponent, ChipComponent, WorkTypePipe, LanguageCodePipe, WorkPrimaryCategoryPipe, - ComponentTooltipDirective, AppTopicChipComponent, AppAuthorChipComponent, - AppInstitutionChipComponent -], + AppInstitutionChipComponent, + ], templateUrl: './publication-table.component.html', styleUrl: './publication-table.component.scss', }) From 448922d907cd580ca35bc56f88d143d8dda031db Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 12:58:38 +0200 Subject: [PATCH 7/9] enable logging of Elasticsearch request timings --- service/src/main/inse/.env | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 9fedc0af..a49ebae6 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -15,7 +15,7 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Debugging: Log every outgoing Elasticsearch query (index + payload) PRINT_ES_QUERIES=false # Debugging: Log the duration of every Elasticsearch request -PRINT_ES_TIMINGS=false +PRINT_ES_TIMINGS=true # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base From def210b4b9417d6926bcb4f0a6fb2734afe66992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 26 Jul 2026 13:15:29 +0200 Subject: [PATCH 8/9] feat(topic): added topic detail page with publication table --- service/src/main/inse/works/v2/router.py | 59 ++++++++++ service/src/main/inse/works/v2/service.py | 96 +++++++++++++--- webapp/src/app/api/api/worksV2.service.ts | 108 ++++++++++++++++++ webapp/src/app/app.routes.ts | 29 +++++ .../topic-publications.component.html | 15 +++ .../topic-publications.component.scss | 0 .../topic-publications.component.ts | 20 ++++ .../app/modules/topic/topic.component.html | 53 ++++++++- .../app/modules/topic/topic.component.scss | 36 ++++++ .../src/app/modules/topic/topic.component.ts | 57 ++++++++- .../src/app/resolvers/work-page.resolver.ts | 24 ++++ .../app-topic-card.component.html | 6 +- 12 files changed, 483 insertions(+), 20 deletions(-) create mode 100644 webapp/src/app/modules/topic-publications/topic-publications.component.html create mode 100644 webapp/src/app/modules/topic-publications/topic-publications.component.scss create mode 100644 webapp/src/app/modules/topic-publications/topic-publications.component.ts diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index cb38a0db..02907ba9 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -218,6 +218,65 @@ async def get_institution_works( ) +@router.get( + "/topic/{raw_oa_topic_id}", + operation_id="getTopicWorkPage", + summary="Returns a paginated list of works for a given topic based on its ID.", +) +async def get_topic_works( + raw_oa_topic_id: Annotated[str, Path(description="The raw OpenAlex topic id.")], + page: Annotated[ + int, Query(description="The page number to retrieve. (0-based)", ge=0) + ] = 0, + size: Annotated[ + int, + Query(description="The number of works to retrieve per page.", ge=1, le=100), + ] = 10, + title: Annotated[ + str, Query(description="A title to filter by (partial matches allowed).") + ] = "", + publication_years: Annotated[ + list[int] | None, + Query(description="A list of publication years to filter by."), + ] = None, + publication_types: Annotated[ + list[str] | None, + Query(description="A list of publication types to filter by."), + ] = None, + author_ids: Annotated[ + list[str] | None, + Query(description="A list of author IDs to filter by."), + ] = None, + institution_ids: Annotated[ + list[str] | None, + Query(description="A list of institution IDs to filter by."), + ] = None, + language_codes: Annotated[ + list[str] | None, + Query(description="A list of language codes to filter by."), + ] = None, + sort_by: Annotated[ + WorkSortBy, Query(description="The field to sort by.") + ] = WorkSortBy.PUBLICATION_YEAR, + sort_order: Annotated[ + SortDirection, Query(description="The order to sort by.") + ] = SortDirection.DESCENDING, +) -> WorkPageV2: + return await works_service.get_topic_works( + raw_oa_topic_id=raw_oa_topic_id, + page=page, + size=size, + title=title, + publication_years=publication_years or [], + publication_types=publication_types or [], + author_ids=author_ids or [], + institution_ids=institution_ids or [], + language_codes=language_codes or [], + sort_by=sort_by, + sort_order=sort_order, + ) + + @router.get( "/classification/work/{raw_oa_work_id}", operation_id="getWorkClassificationByWorkId", diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 4138084c..10f580d2 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -60,6 +60,19 @@ def _institutions_nested_query(institution_ids: list[str]) -> dict: } +def _topics_nested_query(topic_ids: list[str]) -> dict: + """Returns a nested query for filtering works by a list of topic IDs. + + Args: + topic_ids (list[str]): A list of topic IDs to filter by. + + Returns: + dict: A nested query for filtering works by the specified topic IDs. + """ + prefixed = [_prefix_id(tid) for tid in topic_ids] + return {"nested": {"path": "topics", "query": {"terms": {"topics.id": prefixed}}}} + + def _title_query(title: str) -> dict: """Returns a query for filtering works by title using a multi-match query. @@ -87,7 +100,6 @@ def _apply_common_filters( publication_years: list[int] | None, publication_types: list[str] | None, language_codes: list[str] | None, - topic_ids: list[str] | None, title: str | None = None, ) -> None: """Applies common filters to the provided list of must conditions for filtering works. @@ -106,10 +118,6 @@ def _apply_common_filters( must.append({"terms": {"type": publication_types}}) if language_codes: must.append({"terms": {"language": language_codes}}) - if topic_ids: - must.append( - {"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}} - ) if title and len(title.strip()) > 0: must.append(_title_query(title)) @@ -174,6 +182,7 @@ async def get_works( size: int, raw_oa_author_id: str | None = None, raw_oa_institution_id: str | None = None, + raw_oa_topic_id: str | None = None, title: str | None = None, author_ids: list[str] | None = None, institution_ids: list[str] | None = None, @@ -191,6 +200,7 @@ async def get_works( size (int): The number of results per page. raw_oa_author_id (Optional[str], optional): The ID of the author to filter by. Defaults to None. raw_oa_institution_id (Optional[str], optional): The ID of the institution to filter by. Defaults to None. + raw_oa_topic_id (Optional[str], optional): The ID of the topic to filter by. Defaults to None. title (Optional[str], optional): The title of the works to filter by. Defaults to None. author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None. institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None. @@ -202,33 +212,44 @@ async def get_works( sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING. Raises: - ValueError: If neither raw_oa_author_id nor raw_oa_institution_id is provided. + ValueError: If neither raw_oa_author_id nor raw_oa_institution_id nor raw_oa_topic_id is provided. Returns: WorkPageV2: The page of works matching the criteria. """ - if not raw_oa_author_id and not raw_oa_institution_id: + if not raw_oa_author_id and not raw_oa_institution_id and not raw_oa_topic_id: raise ValueError( - "get_works requires at least one of raw_oa_author_id or raw_oa_institution_id" + "get_works requires at least one of raw_oa_author_id or raw_oa_institution_id or raw_oa_topic_id" ) must: list = [] if raw_oa_author_id: - must.append(_authors_nested_query([raw_oa_author_id])) + must.append(_authors_nested_query(author_ids=[raw_oa_author_id])) elif author_ids: - must.append(_authors_nested_query(author_ids)) + must.append(_authors_nested_query(author_ids=author_ids)) if raw_oa_institution_id: - must.append(_institutions_nested_query([raw_oa_institution_id])) + must.append(_institutions_nested_query(institution_ids=[raw_oa_institution_id])) elif institution_ids: - must.append(_institutions_nested_query(institution_ids)) + must.append(_institutions_nested_query(institution_ids=institution_ids)) + + if raw_oa_topic_id: + must.append(_topics_nested_query(topic_ids=[raw_oa_topic_id])) + elif topic_ids: + must.append(_topics_nested_query(topic_ids=topic_ids)) _apply_common_filters( - must, publication_years, publication_types, language_codes, topic_ids, title + must=must, + publication_years=publication_years, + publication_types=publication_types, + language_codes=language_codes, + title=title, ) - return await _execute_works_search(must, page, size, sort_by, sort_order) + return await _execute_works_search( + must=must, page=page, size=size, sort_by=sort_by, sort_order=sort_order + ) async def get_works_by_keywords( @@ -486,6 +507,53 @@ async def get_institution_works( ) +async def get_topic_works( + raw_oa_topic_id: str, + page: int, + size: int, + title: str = "", + publication_years: list[int] | None = None, + publication_types: list[str] | None = None, + institution_ids: list[str] | None = None, + author_ids: list[str] | None = None, + language_codes: list[str] | None = None, + sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR, + sort_order: SortDirection = SortDirection.DESCENDING, +) -> WorkPageV2: + """Retrieves works for a specific topic based on the provided criteria. + + Args: + raw_oa_topic_id (str): The ID of the topic for whom to retrieve works. + page (int): The page number of the results to retrieve. + size (int): The number of results per page. + title (str, optional): The title of the works to filter by. Defaults to "". + publication_years (Optional[List[int]], optional): A list of publication years to filter by. Defaults to None. + publication_types (Optional[List[str]], optional): A list of publication types to filter by. Defaults to None. + institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None. + author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None. + language_codes (Optional[List[str]], optional): A list of language codes to filter by. Defaults to None. + sort_by (WorkSortBy, optional): The field by which to sort the results. Defaults to WorkSortBy.PUBLICATION_YEAR. + sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING. + + Returns: + WorkPageV2: The page of works matching the criteria. + """ + + return await get_works( + page=page, + size=size, + raw_oa_topic_id=raw_oa_topic_id, + title=title, + institution_ids=institution_ids, + author_ids=author_ids, + publication_years=publication_years, + publication_types=publication_types, + language_codes=language_codes, + sort_by=sort_by, + sort_order=sort_order, + ) + + async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work | None: """Retrieves a work based on its OpenAlex ID. diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts index 1eceeb9d..993978a0 100644 --- a/webapp/src/app/api/api/worksV2.service.ts +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -399,6 +399,114 @@ export class WorksV2Service extends BaseService { ); } + /** + * Returns a paginated list of works for a given topic based on its ID. + * @endpoint get /api/works/v2/topic/{raw_oa_topic_id} + * @param rawOaTopicId The raw OpenAlex topic id. + * @param page The page number to retrieve. (0-based) + * @param size The number of works to retrieve per page. + * @param title A title to filter by (partial matches allowed). + * @param publicationYears A list of publication years to filter by. + * @param publicationTypes A list of publication types to filter by. + * @param authorIds A list of author IDs to filter by. + * @param institutionIds A list of institution IDs to filter by. + * @param languageCodes A list of language codes to filter by. + * @param sortBy The field to sort by. + * @param sortOrder The order to sort by. + * @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 getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (rawOaTopicId === null || rawOaTopicId === undefined) { + throw new Error('Required parameter rawOaTopicId was null or undefined when calling getTopicWorkPage.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + if (publicationYears) { + publicationYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_years'); + }) + } + if (publicationTypes) { + publicationTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_types'); + }) + } + if (authorIds) { + authorIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'author_ids'); + }) + } + if (institutionIds) { + institutionIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_ids'); + }) + } + if (languageCodes) { + languageCodes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'language_codes'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sort_order'); + + 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; + + + 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/works/v2/topic/${this.configuration.encodeParam({name: "rawOaTopicId", value: rawOaTopicId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Returns the classifications of a work based on its ID. * @endpoint get /api/works/v2/classification/work/{raw_oa_work_id} diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 43ef3e86..179ee7c9 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -35,6 +35,7 @@ import { UniTrendParentComponent } from './modules/university-ranking/uni-trend- import { RESOLVING_WORK_PAGE_FOR, workPageResolver, + workQueryParamKeys, } from './resolvers/work-page.resolver'; import { selectedTopicsResolver } from './resolvers/selected-topics.resolver'; import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver'; @@ -749,6 +750,34 @@ export const routes: Routes = [ resolve: { topic: topicResolver, }, + runGuardsAndResolvers: 'paramsChange', + children: [ + { + path: '', + pathMatch: 'full', + redirectTo: 'publications', + }, + { + path: 'publications', + loadComponent: () => + import('./modules/topic-publications/topic-publications.component').then( + (mod) => mod.TopicPublicationsComponent, + ), + runGuardsAndResolvers: (from, to) => { + return Object.values(workQueryParamKeys).some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, + resolve: { + workPage: workPageResolver, + selectedAuthorsPage: selectedAuthorsResolver, + selectedInstitutionsPage: selectedInstitutionsResolver, + }, + data: { + resolvingFor: RESOLVING_WORK_PAGE_FOR.TOPIC, + }, + }, + ], }, { path: 'projects', diff --git a/webapp/src/app/modules/topic-publications/topic-publications.component.html b/webapp/src/app/modules/topic-publications/topic-publications.component.html new file mode 100644 index 00000000..efd6c8c1 --- /dev/null +++ b/webapp/src/app/modules/topic-publications/topic-publications.component.html @@ -0,0 +1,15 @@ + + + + + diff --git a/webapp/src/app/modules/topic-publications/topic-publications.component.scss b/webapp/src/app/modules/topic-publications/topic-publications.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/webapp/src/app/modules/topic-publications/topic-publications.component.ts b/webapp/src/app/modules/topic-publications/topic-publications.component.ts new file mode 100644 index 00000000..7d7f1443 --- /dev/null +++ b/webapp/src/app/modules/topic-publications/topic-publications.component.ts @@ -0,0 +1,20 @@ +import { Component, computed, input } from '@angular/core'; +import { AuthorPage, InstitutionPageV2, WorkPageV2 } from '../../api'; +import { PublicationFilterComponent } from "../../shared/ui/publication-filters/publication-filters.component"; +import { PublicationTableComponent } from "../../shared/ui/publication-table/publication-table.component"; +import { QueryParamPaginatorComponent } from "../../shared/ui/query-param-paginator/query-param-paginator.component"; + +@Component({ + selector: 'app-topic-publications', + imports: [PublicationFilterComponent, PublicationTableComponent, QueryParamPaginatorComponent], + templateUrl: './topic-publications.component.html', + styleUrl: './topic-publications.component.scss', +}) +export class TopicPublicationsComponent { + workPage = input.required(); + + selectedAuthorsPage = input.required(); + selectedInstitutionsPage = input.required(); + + total = computed(() => this.workPage().total ?? 0); +} diff --git a/webapp/src/app/modules/topic/topic.component.html b/webapp/src/app/modules/topic/topic.component.html index d71c7aaa..fb4bc779 100644 --- a/webapp/src/app/modules/topic/topic.component.html +++ b/webapp/src/app/modules/topic/topic.component.html @@ -1 +1,52 @@ -

topic works!

+
+ @if (topic(); as topic) { +
+

{{ topic.display_name }}

+ {{ subtitle() }} +
+ +

{{ description() }}

+ +
+
+ menu_book + {{ + topic.works_count | number: undefined : 'de' + }} + Publikationen +
+
+ format_quote + {{ + topic.cited_by_count | number: undefined : 'de' + }} + Zitationen +
+
+ } +
+ + + + +
+ +
+
diff --git a/webapp/src/app/modules/topic/topic.component.scss b/webapp/src/app/modules/topic/topic.component.scss index e69de29b..65ceca16 100644 --- a/webapp/src/app/modules/topic/topic.component.scss +++ b/webapp/src/app/modules/topic/topic.component.scss @@ -0,0 +1,36 @@ +.content { + --topic-border: color-mix(in srgb, hsl(var(--topic-color)) 72%, #ffffff); + --topic-background: color-mix(in srgb, hsl(var(--topic-color)) 8%, #ffffff); + + padding: 2rem; + display: flex; + flex-direction: column; + gap: 1.5rem; + background-color: var(--topic-background); + --mat-divider-color: var(--topic-border); +} + +.outlet-container { + margin: 2rem; +} + +.subtitle { + display: flex; + align-items: center; + gap: 0.5rem; + color: var(--sg-text-muted); +} + +.metrics { + display: flex; + flex-direction: column; + gap: 0.5rem; + font-size: 0.875rem; +} + +.metric-item { + display: flex; + align-items: center; + gap: 0.25rem; + color: var(--sg-text-muted); +} diff --git a/webapp/src/app/modules/topic/topic.component.ts b/webapp/src/app/modules/topic/topic.component.ts index c1827f18..38c102f6 100644 --- a/webapp/src/app/modules/topic/topic.component.ts +++ b/webapp/src/app/modules/topic/topic.component.ts @@ -1,11 +1,64 @@ -import { Component } from '@angular/core'; +import { Component, computed, input } from '@angular/core'; +import { Topic } from '../../api'; +import { MatTabsModule } from '@angular/material/tabs'; +import { RouterModule } from '@angular/router'; +import { MatDividerModule } from '@angular/material/divider'; +import { MatIconModule } from '@angular/material/icon'; +import { DecimalPipe } from '@angular/common'; +import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; @Component({ + host: { + '[style.--topic-color]': 'color()', + }, selector: 'app-topic', - imports: [], + imports: [ + MatTabsModule, + RouterModule, + MatDividerModule, + MatIconModule, + DecimalPipe, + ], templateUrl: './topic.component.html', styleUrl: './topic.component.scss', }) export class TopicComponent { + topic = input.required(); + links = [ + { + label: 'Publikationen', + path: 'publications', + disabled: false, + queryParams: { + page: 0, + size: 10, + title: '', + sort_by: 'title', + sort_direction: 'asc', + }, + }, + ]; + + subtitle = computed(() => { + return `${this.topic().subfield?.display_name} - ${this.topic().field?.display_name} - ${this.topic().domain?.display_name}`; + }); + + description = computed(() => { + return this.topic().description || 'Keine Beschreibung verfügbar'; + }); + + color = computed(() => { + const topic = this.topic(); + return topicHierarchyColor({ + id: topic.id ?? undefined, + name: topic.display_name ?? undefined, + field_id: topic.field?.id ?? undefined, + field_name: topic.field?.display_name ?? undefined, + domain_id: topic.domain?.id ?? undefined, + domain_name: topic.domain?.display_name ?? undefined, + }) + .replace('hsl(', '') + .replace(')', ''); + }); } diff --git a/webapp/src/app/resolvers/work-page.resolver.ts b/webapp/src/app/resolvers/work-page.resolver.ts index 95833a75..be963c87 100644 --- a/webapp/src/app/resolvers/work-page.resolver.ts +++ b/webapp/src/app/resolvers/work-page.resolver.ts @@ -10,6 +10,7 @@ const RESOLVING_WORK_PAGE_FOR_KEY = 'resolvingFor'; export const RESOLVING_WORK_PAGE_FOR = { PERSON: 'PERSON', INSTITUTION: 'INSTITUTION', + TOPIC: 'TOPIC', KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', } as const; @@ -151,6 +152,29 @@ export const workPageResolver: ResolveFn = ( sortBy, sortDirection, ); + } else if (resolvingFor === RESOLVING_WORK_PAGE_FOR.TOPIC) { + const topicId = + route.parent?.paramMap.get('topicId') || route.paramMap.get('topicId'); + if (!topicId) { + throw new Error('Topic ID is required to resolve topic works.'); + } + const authorIds = route.queryParamMap.getAll(workQueryParamKeys.authorId); + const institutionIds = route.queryParamMap.getAll( + workQueryParamKeys.institutionId, + ); + return inject(WorksV2Service).getTopicWorkPage( + topicId, + page, + size, + title, + publicationYears, + publicationTypes, + authorIds, + institutionIds, + languages, + sortBy, + sortDirection, + ); } else { throw new Error(`Unknown resolvingFor value: ${resolvingFor}`); } diff --git a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html index 66b53915..60f5625b 100644 --- a/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html +++ b/webapp/src/app/shared/ui/app-topic-card/app-topic-card.component.html @@ -41,11 +41,11 @@ - info - Übersicht + menu_book + Publikationen From af00bc46357230fa96985d092c96922696dd57f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Sun, 26 Jul 2026 14:49:23 +0200 Subject: [PATCH 9/9] feat(publication-search): added publication card search and respective card --- service/src/main/inse/authors/v2/service.py | 2 +- service/src/main/inse/topics/v2/service.py | 3 +- service/src/main/inse/works/v2/router.py | 62 ++++++++++ service/src/main/inse/works/v2/service.py | 87 +++++++++----- webapp/src/app/api/api/worksV2.service.ts | 111 ++++++++++++++++++ webapp/src/app/app.routes.ts | 29 +++++ .../directives/component-tooltip.directive.ts | 22 ++++ .../publications/publications.component.html | 30 +++++ .../publications/publications.component.scss | 10 ++ .../publications/publications.component.ts | 51 ++++++++ .../src/app/resolvers/work-page.resolver.ts | 20 ++++ .../shared/ui/app-menu/app-menu.component.ts | 16 ++- .../app-publication-card.component.html | 53 +++++++++ .../app-publication-card.component.scss | 50 ++++++++ .../app-publication-card.component.ts | 58 +++++++++ .../app-topic-chip.component.html | 1 + .../app-topic-chip.component.scss | 7 +- 17 files changed, 578 insertions(+), 34 deletions(-) create mode 100644 webapp/src/app/modules/publications/publications.component.html create mode 100644 webapp/src/app/modules/publications/publications.component.scss create mode 100644 webapp/src/app/modules/publications/publications.component.ts create mode 100644 webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.html create mode 100644 webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.scss create mode 100644 webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.ts diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index f2abbaba..0c82f1bc 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -388,7 +388,7 @@ async def _build_collaboration_graph( f"Searching works for collaboration graph of author {raw_oa_author_id} with query: {query}" ) - work_page: WorkPageV2 = await works_service.search_works( + work_page: WorkPageV2 = await works_service._search_works( query=query, source=COLLABORATION_GRAPH_SOURCE_FIELDS, page=0, diff --git a/service/src/main/inse/topics/v2/service.py b/service/src/main/inse/topics/v2/service.py index d8f3f604..2538b860 100644 --- a/service/src/main/inse/topics/v2/service.py +++ b/service/src/main/inse/topics/v2/service.py @@ -38,11 +38,12 @@ async def _search_topics( hits_block = response.get("hits", {}) hits = hits_block.get("hits", []) + total_hits = hits_block.get("total", {}).get("value", 0) topics: list[Topic] = [] for hit in hits: _source = hit.get("_source", {}) topics.append(Topic.from_dict(_source)) # type: ignore - return TopicPageV2(elements=topics, total=len(topics), page=page, size=size) + return TopicPageV2(elements=topics, total=total_hits, page=page, size=size) async def search_topics( diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index 02907ba9..b0d413f0 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -22,6 +22,68 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2]) +@router.get( + "/search", + operation_id="searchWorks", + summary="Search works with filters.", +) +async def search_works( + page: Annotated[ + int, Query(description="The page number to retrieve. (0-based)", ge=0) + ] = 0, + size: Annotated[ + int, + Query(description="The number of works to retrieve per page.", ge=1, le=100), + ] = 10, + title: Annotated[ + str, Query(description="A title to filter by (partial matches allowed).") + ] = "", + publication_years: Annotated[ + list[int] | None, + Query(description="A list of publication years to filter by."), + ] = None, + publication_types: Annotated[ + list[str] | None, + Query(description="A list of publication types to filter by."), + ] = None, + author_ids: Annotated[ + list[str] | None, + Query(description="A list of author IDs to filter by."), + ] = None, + institution_ids: Annotated[ + list[str] | None, + Query(description="A list of institution IDs to filter by."), + ] = None, + topic_ids: Annotated[ + list[str] | None, + Query(description="A list of topic IDs to filter by."), + ] = None, + language_codes: Annotated[ + list[str] | None, + Query(description="A list of language codes to filter by."), + ] = None, + sort_by: Annotated[ + WorkSortBy, Query(description="The field to sort by.") + ] = WorkSortBy.PUBLICATION_YEAR, + sort_order: Annotated[ + SortDirection, Query(description="The order to sort by.") + ] = SortDirection.DESCENDING, +) -> WorkPageV2: + return await works_service.search_works( + page=page, + size=size, + title=title, + publication_years=publication_years or [], + publication_types=publication_types or [], + author_ids=author_ids or [], + institution_ids=institution_ids or [], + topic_ids=topic_ids or [], + language_codes=language_codes or [], + sort_by=sort_by, + sort_order=sort_order, + ) + + @router.get( "/author/{raw_oa_author_id}", operation_id="getAuthorWorkPage", diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 10f580d2..65f6a358 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -156,7 +156,7 @@ async def _execute_works_search( Returns: WorkPageV2: The page of works matching the search criteria. """ - return await search_works( + return await _search_works( source=[ "id", "title", @@ -180,9 +180,6 @@ async def _execute_works_search( async def get_works( page: int, size: int, - raw_oa_author_id: str | None = None, - raw_oa_institution_id: str | None = None, - raw_oa_topic_id: str | None = None, title: str | None = None, author_ids: list[str] | None = None, institution_ids: list[str] | None = None, @@ -198,9 +195,6 @@ async def get_works( Args: page (int): The page number for pagination. size (int): The number of results per page. - raw_oa_author_id (Optional[str], optional): The ID of the author to filter by. Defaults to None. - raw_oa_institution_id (Optional[str], optional): The ID of the institution to filter by. Defaults to None. - raw_oa_topic_id (Optional[str], optional): The ID of the topic to filter by. Defaults to None. title (Optional[str], optional): The title of the works to filter by. Defaults to None. author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None. institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None. @@ -211,32 +205,18 @@ async def get_works( sort_by (WorkSortBy, optional): The field to sort by. Defaults to WorkSortBy.PUBLICATION_YEAR. sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING. - Raises: - ValueError: If neither raw_oa_author_id nor raw_oa_institution_id nor raw_oa_topic_id is provided. - Returns: WorkPageV2: The page of works matching the criteria. """ - if not raw_oa_author_id and not raw_oa_institution_id and not raw_oa_topic_id: - raise ValueError( - "get_works requires at least one of raw_oa_author_id or raw_oa_institution_id or raw_oa_topic_id" - ) - must: list = [] - if raw_oa_author_id: - must.append(_authors_nested_query(author_ids=[raw_oa_author_id])) - elif author_ids: + if author_ids: must.append(_authors_nested_query(author_ids=author_ids)) - if raw_oa_institution_id: - must.append(_institutions_nested_query(institution_ids=[raw_oa_institution_id])) - elif institution_ids: + if institution_ids: must.append(_institutions_nested_query(institution_ids=institution_ids)) - if raw_oa_topic_id: - must.append(_topics_nested_query(topic_ids=[raw_oa_topic_id])) - elif topic_ids: + if topic_ids: must.append(_topics_nested_query(topic_ids=topic_ids)) _apply_common_filters( @@ -448,7 +428,7 @@ async def get_author_works( return await get_works( page=page, size=size, - raw_oa_author_id=raw_oa_author_id, + author_ids=[raw_oa_author_id], title=title, institution_ids=institution_ids, publication_years=publication_years, @@ -495,7 +475,7 @@ async def get_institution_works( return await get_works( page=page, size=size, - raw_oa_institution_id=raw_oa_institution_id, + institution_ids=[raw_oa_institution_id], author_ids=author_ids, title=title, publication_years=publication_years, @@ -542,7 +522,7 @@ async def get_topic_works( return await get_works( page=page, size=size, - raw_oa_topic_id=raw_oa_topic_id, + topic_ids=[raw_oa_topic_id], title=title, institution_ids=institution_ids, author_ids=author_ids, @@ -554,6 +534,53 @@ async def get_topic_works( ) +async def search_works( + page: int, + size: int, + title: str | None = None, + author_ids: list[str] | None = None, + institution_ids: list[str] | None = None, + publication_years: list[int] | None = None, + publication_types: list[str] | None = None, + topic_ids: list[str] | None = None, + language_codes: list[str] | None = None, + sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR, + sort_order: SortDirection = SortDirection.DESCENDING, +) -> WorkPageV2: + """Searches for works based on the provided criteria. + + Args: + page (int): The page number of the results to retrieve. + size (int): The number of results per page. + title (str | None, optional): The title of the works to filter by. Defaults to None. + author_ids (list[str] | None, optional): A list of author IDs to filter by. Defaults to None. + institution_ids (list[str] | None, optional): A list of institution IDs to filter by. Defaults to None. + publication_years (list[int] | None, optional): A list of publication years to filter by. Defaults to None. + publication_types (list[str] | None, optional): A list of publication types to filter by. Defaults to None. + topic_ids (list[str] | None, optional): A list of topic IDs to filter by. Defaults to None. + language_codes (list[str] | None, optional): A list of language codes to filter by. Defaults to None. + sort_by (WorkSortBy, optional): The field by which to sort the results. Defaults to WorkSortBy.PUBLICATION_YEAR. + sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING. + + Returns: + WorkPageV2: The page of works matching the criteria. + """ + + return await get_works( + page=page, + size=size, + title=title, + author_ids=author_ids, + institution_ids=institution_ids, + publication_years=publication_years, + publication_types=publication_types, + topic_ids=topic_ids, + language_codes=language_codes, + sort_by=sort_by, + sort_order=sort_order, + ) + + async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work | None: """Retrieves a work based on its OpenAlex ID. @@ -566,7 +593,7 @@ async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work """ # search instead of get, because multiple indices are used for works - work_page = await search_works( + work_page = await _search_works( query={"term": {"id": _prefix_id(raw_oa_work_id)}}, source=source, page=0, @@ -578,7 +605,7 @@ async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work return None -async def search_works( +async def _search_works( query: dict | None = None, source: list[str] | None = None, page: int = 0, @@ -636,7 +663,7 @@ async def _get_works_by_work_ids_and_institution_id( prefixed_work_ids = [_prefix_id(wid) for wid in work_ids] prefixed_institution_id = _prefix_id(raw_oa_institution_id) - return await search_works( + return await _search_works( query={ "bool": { "must": [ diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts index 993978a0..5f629ee0 100644 --- a/webapp/src/app/api/api/worksV2.service.ts +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -778,4 +778,115 @@ export class WorksV2Service extends BaseService { ); } + /** + * Search works with filters. + * @endpoint get /api/works/v2/search + * @param page The page number to retrieve. (0-based) + * @param size The number of works to retrieve per page. + * @param title A title to filter by (partial matches allowed). + * @param publicationYears A list of publication years to filter by. + * @param publicationTypes A list of publication types to filter by. + * @param authorIds A list of author IDs to filter by. + * @param institutionIds A list of institution IDs to filter by. + * @param topicIds A list of topic IDs to filter by. + * @param languageCodes A list of language codes to filter by. + * @param sortBy The field to sort by. + * @param sortOrder The order to sort by. + * @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 searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array, publicationTypes?: Array, authorIds?: Array, institutionIds?: Array, topicIds?: Array, languageCodes?: Array, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + size, 'size'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); + if (publicationYears) { + publicationYears.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_years'); + }) + } + if (publicationTypes) { + publicationTypes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'publication_types'); + }) + } + if (authorIds) { + authorIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'author_ids'); + }) + } + if (institutionIds) { + institutionIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'institution_ids'); + }) + } + if (topicIds) { + topicIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'topic_ids'); + }) + } + if (languageCodes) { + languageCodes.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'language_codes'); + }) + } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortBy, 'sort_by'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + sortOrder, 'sort_order'); + + 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; + + + 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/works/v2/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 179ee7c9..27ab1022 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -710,6 +710,35 @@ export const routes: Routes = [ }, ], }, + { + path: 'publications', + canActivate: [ + roleGuard([ + UserRole.User, + UserRole.Manager, + UserRole.Admin, + UserRole.SuperAdmin, + ]), + ], + loadComponent: () => + import('./modules/publications/publications.component').then( + (mod) => mod.PublicationsComponent, + ), + resolve: { + workPage: workPageResolver, + selectedAuthorsPage: selectedAuthorsResolver, + selectedInstitutionsPage: selectedInstitutionsResolver, + selectedTopicsPage: selectedTopicsResolver, + }, + data: { + resolvingFor: RESOLVING_WORK_PAGE_FOR.PUBLICATION_SEARCH, + }, + runGuardsAndResolvers: (from, to) => { + return Object.values(workQueryParamKeys).some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, + }, { path: 'topics', canActivate: [ diff --git a/webapp/src/app/directives/component-tooltip.directive.ts b/webapp/src/app/directives/component-tooltip.directive.ts index eefd8b15..9a945510 100644 --- a/webapp/src/app/directives/component-tooltip.directive.ts +++ b/webapp/src/app/directives/component-tooltip.directive.ts @@ -34,6 +34,7 @@ export class ComponentTooltipDirective implements OnDestroy { readonly tooltipShowDelay = input(150); readonly tooltipHideDelay = input(100); readonly tooltipDisabled = input(false); + readonly tooltipMaxWidth = input(null); private readonly elementRef = inject(ElementRef); private readonly overlay = inject(Overlay); @@ -57,6 +58,13 @@ export class ComponentTooltipDirective implements OnDestroy { } } }); + + effect(() => { + const maxWidth = this.tooltipMaxWidth(); + if (this.overlayRef?.hasAttached()) { + this.applyMaxWidth(this.overlayRef.overlayElement, maxWidth); + } + }); } @HostListener('mouseenter') @@ -141,10 +149,24 @@ export class ComponentTooltipDirective implements OnDestroy { } const overlayElement = this.overlayRef.overlayElement; + this.applyMaxWidth(overlayElement, this.tooltipMaxWidth()); + overlayElement.addEventListener('mouseenter', this.onOverlayEnter); overlayElement.addEventListener('mouseleave', this.onOverlayLeave); } + private applyMaxWidth( + element: HTMLElement, + maxWidth: string | number | null, + ): void { + if (maxWidth === null) { + element.style.maxWidth = ''; + return; + } + element.style.maxWidth = + typeof maxWidth === 'number' ? `${maxWidth}px` : maxWidth; + } + private readonly onOverlayEnter = (): void => { this.isOverOverlay = true; clearTimeout(this.hideTimeout); diff --git a/webapp/src/app/modules/publications/publications.component.html b/webapp/src/app/modules/publications/publications.component.html new file mode 100644 index 00000000..11992125 --- /dev/null +++ b/webapp/src/app/modules/publications/publications.component.html @@ -0,0 +1,30 @@ +
+

Passende Publikationen finden

+ + + + +
+ + + + + + +
+ +
+
diff --git a/webapp/src/app/modules/publications/publications.component.scss b/webapp/src/app/modules/publications/publications.component.scss new file mode 100644 index 00000000..1b215c59 --- /dev/null +++ b/webapp/src/app/modules/publications/publications.component.scss @@ -0,0 +1,10 @@ +.content { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1rem; +} + +.additional-filters { + margin: 0rem 1rem; +} diff --git a/webapp/src/app/modules/publications/publications.component.ts b/webapp/src/app/modules/publications/publications.component.ts new file mode 100644 index 00000000..50259642 --- /dev/null +++ b/webapp/src/app/modules/publications/publications.component.ts @@ -0,0 +1,51 @@ +import { Component, computed, input } from '@angular/core'; +import { + AuthorPage, + InstitutionPageV2, + SortDirection, + TopicPageV2, + WorkPageV2, + WorkSortBy, +} from '../../api'; +import { + Page, + CardSearchComponent, +} from '../../shared/ui/card-search/card-search.component'; +import { MatDivider } from '@angular/material/divider'; +import { AppPublicationCardComponent } from '../../shared/ui/app-publication-card/app-publication-card.component'; +import { PublicationFilterComponent } from '../../shared/ui/publication-filters/publication-filters.component'; +import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; + +@Component({ + selector: 'app-publications', + imports: [ + MatDivider, + CardSearchComponent, + AppPublicationCardComponent, + PublicationFilterComponent, + ], + templateUrl: './publications.component.html', + styleUrl: './publications.component.scss', +}) +export class PublicationsComponent { + workPage = input.required(); + selectedAuthorsPage = input.required(); + selectedInstitutionsPage = input.required(); + selectedTopicsPage = input.required(); + + page = computed(() => ({ + page: this.workPage().page || 0, + size: this.workPage().size || 10, + total: this.workPage().total || 0, + elements: this.workPage().elements || [], + })); + + sortingOptions: SelectorOption[] = [ + { value: WorkSortBy.Title, display_name: 'Titel' }, + { value: WorkSortBy.CitedByCount, display_name: 'Anzahl Zitationen' }, + ]; + sortingDirectionOptions: SelectorOption[] = [ + { value: SortDirection.Asc, display_name: 'Aufsteigend' }, + { value: SortDirection.Desc, display_name: 'Absteigend' }, + ]; +} diff --git a/webapp/src/app/resolvers/work-page.resolver.ts b/webapp/src/app/resolvers/work-page.resolver.ts index be963c87..4e7b6b04 100644 --- a/webapp/src/app/resolvers/work-page.resolver.ts +++ b/webapp/src/app/resolvers/work-page.resolver.ts @@ -11,6 +11,7 @@ export const RESOLVING_WORK_PAGE_FOR = { PERSON: 'PERSON', INSTITUTION: 'INSTITUTION', TOPIC: 'TOPIC', + PUBLICATION_SEARCH: 'PUBLICATION_SEARCH', KEYWORDS_SEARCH: 'KEYWORDS_SEARCH', } as const; @@ -175,6 +176,25 @@ export const workPageResolver: ResolveFn = ( sortBy, sortDirection, ); + } else if (resolvingFor === RESOLVING_WORK_PAGE_FOR.PUBLICATION_SEARCH) { + const authorIds = route.queryParamMap.getAll(workQueryParamKeys.authorId); + const institutionIds = route.queryParamMap.getAll( + workQueryParamKeys.institutionId, + ); + const topicIds = route.queryParamMap.getAll(workQueryParamKeys.topicId); + return inject(WorksV2Service).searchWorks( + page, + size, + title, + publicationYears, + publicationTypes, + authorIds, + institutionIds, + topicIds, + languages, + WorkSortBy.CitedByCount, + sortDirection, + ); } else { throw new Error(`Unknown resolvingFor value: ${resolvingFor}`); } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index df9ee95e..2db3a978 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -13,7 +13,8 @@ import { MatCardContent, MatCardModule } from '@angular/material/card'; import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { activeInstitutionPersonListQueryParams } from '../../person-list-query-params'; import { topicQueryParamKeys } from '../../../resolvers/topic-page.resolver'; -import { SortDirection, TopicSortBy } from '../../../api'; +import { SortDirection, TopicSortBy, WorkSortBy } from '../../../api'; +import { workQueryParamKeys } from '../../../resolvers/work-page.resolver'; type NavItem = { label: string; @@ -106,6 +107,19 @@ export class AppMenuComponent { sorting_order: SortDirection.Desc, }, }, + { + label: 'Publikationen', + icon: 'menu_book', + route: '/publications', + disabled: false, + queryParams: { + [workQueryParamKeys.title]: '', + [workQueryParamKeys.page]: 0, + [workQueryParamKeys.size]: 10, + [workQueryParamKeys.sortBy]: WorkSortBy.CitedByCount, + [workQueryParamKeys.sortDirection]: SortDirection.Desc, + }, + }, { label: 'Themen', icon: 'topic', diff --git a/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.html b/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.html new file mode 100644 index 00000000..14444dae --- /dev/null +++ b/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.html @@ -0,0 +1,53 @@ +@let work = this.work(); + + + + {{ work.title }} + + {{ work.publication_year }} - {{ work.type | workType }} - + {{ work.language | languageCode }} + + + + + +
+ @for (topic of topics(); track topic.id) { + + } + @for (author of authors(); track author.id) { + + } +
+ + + +
+
+ format_quote + {{ work.cited_by_count | number: undefined : 'de' }} Zitationen +
+
+
+ + + + + + + open_in_new + Öffnen + + + +
diff --git a/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.scss b/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.scss new file mode 100644 index 00000000..ce2961eb --- /dev/null +++ b/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.scss @@ -0,0 +1,50 @@ +.card-content { + display: flex; + flex-direction: column; + gap: 1rem; + height: 100%; +} + +.subtitle { + display: flex; + align-items: center; + gap: 0.5rem; + color: var(--sg-text-muted); +} + +.metrics { + display: flex; + flex-direction: column; + gap: 0.5rem; + font-size: 0.875rem; +} + +.metric-item { + display: flex; + align-items: center; + gap: 0.25rem; + color: var(--sg-text-muted); +} + +.card-actions { + display: flex; + gap: 0.5rem; +} + +.card-action { + width: 100%; +} + +.chips { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + height: 100%; +} + +.mat-card-content { + display: flex; + flex-direction: column; + gap: 1rem; + height: 100%; +} diff --git a/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.ts b/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.ts new file mode 100644 index 00000000..41c8a29a --- /dev/null +++ b/webapp/src/app/shared/ui/app-publication-card/app-publication-card.component.ts @@ -0,0 +1,58 @@ +import { Component, computed, input } from '@angular/core'; +import { DehydratedAuthor, Work } from '../../../api'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { MatButtonModule } from '@angular/material/button'; +import { RouterModule } from '@angular/router'; +import { MatDividerModule } from '@angular/material/divider'; +import { DecimalPipe } from '@angular/common'; +import { WorkTypePipe } from '../../pipes/work-type.pipe'; +import { LanguageCodePipe } from '../../pipes/language-code.pipe'; +import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component'; +import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component'; + +@Component({ + selector: 'app-publication-card', + imports: [ + MatCardModule, + MatIconModule, + MatButtonModule, + RouterModule, + MatDividerModule, + DecimalPipe, + WorkTypePipe, + LanguageCodePipe, + AppTopicChipComponent, + AppAuthorChipComponent, + ], + templateUrl: './app-publication-card.component.html', + styleUrl: './app-publication-card.component.scss', +}) +export class AppPublicationCardComponent { + work = input.required(); + + stripOpenAlexId(id: string | null | undefined): string | undefined { + if (!id) { + return undefined; + } + return id.replace('https://openalex.org/', ''); + } + + topics = computed(() => { + const work = this.work(); + if (!work?.topics) { + return []; + } + return work.topics; + }); + + authors = computed(() => { + const work = this.work(); + if (!work?.authorships) { + return []; + } + return work.authorships + .map((authorship) => authorship.author) + .filter((author): author is DehydratedAuthor => !!author); + }); +} diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html index 11bbb37d..7dea292f 100644 --- a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.html @@ -2,6 +2,7 @@ class="topic-chip" [appComponentTooltip]="AppTopicTooltipComponent" [tooltipInputs]="{ topicId: rawOaTopicId() }" + [tooltipMaxWidth]="'500px'" (keydown)="_onChipClick($event)" (click)="_onChipClick($event)"> diff --git a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss index f6e768ce..9ce202bf 100644 --- a/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss +++ b/webapp/src/app/shared/ui/app-topic-chip/app-topic-chip.component.scss @@ -3,7 +3,6 @@ --topic-border: color-mix(in srgb, hsl(var(--topic-color)) 72%, #ffffff); font-weight: 500; - background-color: var(--topic-background); border: 1px solid var(--topic-border); border-radius: var(--sg-radius-sm); display: flex; @@ -11,6 +10,12 @@ gap: 0.5rem; } +:host ::ng-deep .topic-chip .mat-mdc-chip-action, +:host ::ng-deep .topic-chip .mdc-evolution-chip__action { + background-color: var(--topic-background); + border-radius: var(--sg-radius-sm); +} + :host.is-clickable { ::ng-deep .mdc-evolution-chip__action { cursor: pointer;