From 715f775071cdba61b9b73c2d7d4a93c56ab7e646 Mon Sep 17 00:00:00 2001 From: genja Date: Fri, 17 Jul 2026 15:14:59 +0200 Subject: [PATCH] used generic publication-table component for keyword-search --- service/src/main/inse/works/v2/router.py | 4 + service/src/main/inse/works/v2/service.py | 27 +- webapp/src/app/api/api/worksV2.service.ts | 18 +- .../works-results.component.html | 181 +------ .../works-results/works-results.component.ts | 442 ++++-------------- 5 files changed, 148 insertions(+), 524 deletions(-) diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index 372b2d1a..9b4f1631 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -93,7 +93,9 @@ async def search_works_by_keywords( publication_year: Annotated[list[int] | None, Query(description="A list of publication years to filter by.")] = None, publication_type: Annotated[list[str] | None, Query(description="A list of publication types to filter by.")] = None, institution_ids: Annotated[list[str] | None, Query(description="A list of institution IDs to filter by.")] = None, + author_ids: Annotated[list[str] | None, Query(description="A list of author IDs to filter by.")] = None, language: Annotated[list[str] | None, Query(description="A list of language codes to filter by.")] = None, + title: Annotated[str | None, Query(description="Title to search for in works.")] = None, 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, sort_by: Annotated[WorkSortBy, Query(description="The field to sort by.")] = WorkSortBy.PUBLICATION_YEAR, @@ -106,9 +108,11 @@ async def search_works_by_keywords( publication_year=publication_year or [], publication_type=publication_type or [], institution_ids=institution_ids or [], + author_ids=author_ids or [], topic_ids=topic_ids or [], filter_topic_ids=filter_topic_ids or [], language=language or [], + title=title, page=page, size=size, sort_by=sort_by, diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index cc898111..3c965f34 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -43,7 +43,7 @@ def _institutions_nested_query(institution_ids: List[str]) -> dict: } -def _title_query(title: str) -> dict: +def _title_query(title: str = "") -> dict: return { "multi_match": { "query": title, @@ -282,17 +282,19 @@ async def get_works_by_keywords( "applied independently of the fuzzy/keyword search mode.", ), keywords: Optional[List[str]] = Query(None, description="Raw keywords to search in title/abstract."), + title: Optional[str] = None, fuzzy: bool = Query(True, description="Use topic resolution if True, otherwise use raw keywords."), publication_year: Optional[List[int]] = Query(None), publication_type: Optional[List[str]] = Query(None, alias="type"), language: Optional[List[str]] = Query(None), institution_ids: Optional[List[str]] = Query(None), + author_ids: Optional[List[str]] = Query(None), page: int = 0, size: int = 10, sort_by: WorkSortBy = Query(WorkSortBy.PUBLICATION_YEAR), sort_order: SortDirection = Query(SortDirection.DESCENDING), ) -> WorkPage: - print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}") + #print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language},title={title}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}") def _topics_nested_clause(should_clauses: List[Dict]) -> Dict: return { "nested": { @@ -362,7 +364,9 @@ async def get_works_by_keywords( # "minimum_should_match": 1, # } # }) - + + if title: + must.append(_title_query(title)) if publication_year: must.append({"terms": {"publication_year": publication_year}}) if publication_type: @@ -370,24 +374,16 @@ async def get_works_by_keywords( if language: must.append({"terms": {"language": language}}) if institution_ids: - must.append({ - "nested": { - "path": "authorships", - "query": { - "nested": { - "path": "authorships.institutions", - "query": {"terms": {"authorships.institutions.id": institution_ids}}, - } - }, - } - }) + must.append(_institutions_nested_query(institution_ids)) + if author_ids: + must.append(_authors_nested_query(author_ids)) #sorting if sort_by == WorkSortBy.TITLE: sort = [{"title.keyword": sort_order.value}] else: sort = [{sort_by.value: sort_order.value}] - + print(f"Final query:",must) #search response = await elasticsearch.search( index=ESIndex.OPENALEX_WORKS_WILDCARD, @@ -414,6 +410,7 @@ async def get_works_by_keywords( sort=sort, cluster=ESCluster.NES, ) + print(f"Elasticsearch response: {response}") logger.debug(f"Query: {{'bool': {{'must': {must}}}}}") #model mapping hits_block = response.get("hits", {}) diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts index 5f1a28b5..3f052ad5 100644 --- a/webapp/src/app/api/api/worksV2.service.ts +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -630,7 +630,9 @@ export class WorksV2Service extends BaseService { * @param publicationYear A list of publication years to filter by. * @param publicationType A list of publication types to filter by. * @param institutionIds A list of institution IDs to filter by. + * @param authorIds A list of author IDs to filter by. * @param language A list of language codes to filter by. + * @param title Title to search for in works. * @param page The page number to retrieve. (0-based) * @param size The number of works to retrieve per page. * @param sortBy The field to sort by. @@ -638,10 +640,10 @@ export class WorksV2Service extends BaseService { * @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 getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, language?: Array, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, language?: Array, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, language?: Array, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, language?: Array, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, authorIds?: Array, language?: Array, title?: string, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, authorIds?: Array, language?: Array, title?: string, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, authorIds?: Array, language?: Array, title?: string, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getWorksByKeywords(topics?: Array, topicIds?: Array, filterTopicIds?: Array, keywords?: Array, fuzzy?: boolean, publicationYear?: Array, publicationType?: Array, institutionIds?: Array, authorIds?: Array, language?: Array, title?: string, page?: number, size?: number, 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}); if (topics) { @@ -688,12 +690,20 @@ export class WorksV2Service extends BaseService { element, 'institution_ids'); }) } + if (authorIds) { + authorIds.forEach((element) => { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + element, 'author_ids'); + }) + } if (language) { language.forEach((element) => { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, element, 'language'); }) } + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + title, 'title'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, page, 'page'); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index 977efe0c..4d0a78cf 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -1,165 +1,22 @@ -
-
-
- - calendar_today - - {{ yearSelectionSummary() }} - - @for (year of filteredYearOptions(); track year) { - {{ year }} - } @empty { -
Keine Treffer
- } -
-
+
+ - - category - - {{ typeSelectionSummary() }} - - @for (type of filteredTypeOptions(); track type.value) { - {{ type.label }} - } @empty { -
Keine Treffer
- } -
-
+ @if (loading()) { + + } @else { + + } - - translate - - {{ - languageSelectionSummary() - }} - - @for (language of filteredLanguageOptions(); track language.value) { - {{ - language.label - }} - } @empty { -
Keine Treffer
- } -
-
- - - apartment - - - @for (institution of institutionOptions(); track institution.id) { - - {{ institution.display_name }} - @if (institution.hint) { - {{ institution.hint }} - } - - } - @if ( - !institutionLookupLoading() && - institutionOptions().length === 0 && - institutionSearchControl.value - ) { - Keine Institution gefunden - } - - - - - -
- - - -
- @if (loading()) { - - } @else if (works().elements?.length === 0) { - - - groups - Keine Publikationen gefunden. - - - } @else { - - - - - - - } -
+
diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts index f2d19da0..a295d423 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts @@ -2,61 +2,28 @@ import { Component, DestroyRef, OnInit, - effect, inject, signal, computed, } from '@angular/core'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; -import { MatSelectChange, MatSelectModule } from '@angular/material/select'; import { workQueryParamKeys } from '../../../../resolvers/work-page.resolver'; -import { - MatAutocompleteModule, - MatAutocompleteSelectedEvent, -} from '@angular/material/autocomplete'; -import { - catchError, - debounceTime, - distinctUntilChanged, - finalize, - map, - of, - switchMap, -} from 'rxjs'; +import { PublicationFilterComponent } from '../../../../shared/ui/publication-filters/publication-filters.component'; +import { catchError, finalize, of, switchMap } from 'rxjs'; import { PublicationTableComponent } from '../../../../shared/ui/publication-table/publication-table.component'; import { LoadingComponent } from '../../../../shared/ui/loading/loading.component'; import { InseWorksV2ModelWorkPage as WorkPage } from '../../../../api/model/inseWorksV2ModelWorkPage'; import { PaginationService } from '../../../../shared/services/pagination.service'; import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component'; -import { InstitutionsService } from '../../../../api'; -import { - FilterObserver, - SelectedFiltersComponent, -} from '../../../../shared/ui/selected-filters/selected-filters.component'; -import { translateWorkType } from '../../../../shared/pipes/work-type.pipe'; -import { translateLanguageCode } from '../../../../shared/pipes/language-code.pipe'; +import { Author, Institution, Topic, WorkTopic } from '../../../../api'; import { SortDirection, WorkSortBy, WorksV2Service } from '../../../../api'; - import { SearchResultsStateService } from '../search-results-state.service'; -interface InstitutionAutocompleteOption { - id?: string | null; - display_name?: string | null; - hint?: string | null; - cited_by_count?: number | null; - works_count?: number | null; - entity_type?: string | null; - external_id?: string | null; -} - const EMPTY_WORK_PAGE: WorkPage = { elements: [], total: 0, page: 0, size: 10 }; @Component({ @@ -64,16 +31,11 @@ const EMPTY_WORK_PAGE: WorkPage = { elements: [], total: 0, page: 0, size: 10 }; imports: [ MatCardModule, MatIconModule, - MatFormFieldModule, - MatInputModule, MatButtonModule, - MatSelectModule, - MatAutocompleteModule, - ReactiveFormsModule, LoadingComponent, PublicationTableComponent, + PublicationFilterComponent, QueryParamPaginatorComponent, - SelectedFiltersComponent, ], templateUrl: './works-results.component.html', styleUrl: './works-results.component.scss', @@ -83,7 +45,6 @@ export class KeywordsToWorksResultsComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly worksService = inject(WorksV2Service); - private readonly institutionsService = inject(InstitutionsService); private readonly destroyRef = inject(DestroyRef); public readonly paginationService = inject(PaginationService); @@ -93,167 +54,30 @@ export class KeywordsToWorksResultsComponent implements OnInit { private readonly typeParamKey = workQueryParamKeys.types; private readonly languageParamKey = workQueryParamKeys.language; private readonly institutionParamKey = workQueryParamKeys.institutionId; + private readonly authorParamKey = workQueryParamKeys.authorId; private readonly topicParamKey = workQueryParamKeys.topicId; private readonly pageParamKey = workQueryParamKeys.page; - // --- Filter option lists --- - readonly publicationYearOptions = this.createPublicationYearOptions(); - - readonly typeOptions = [ - { value: 'article', label: 'article' }, - { value: 'book', label: 'book' }, - { value: 'book-chapter', label: 'book-chapter' }, - { value: 'dataset', label: 'dataset' }, - { value: 'dissertation', label: 'dissertation' }, - { value: 'editorial', label: 'editorial' }, - { value: 'erratum', label: 'erratum' }, - { value: 'letter', label: 'letter' }, - { value: 'libguides', label: 'libguides' }, - { value: 'other', label: 'other' }, - { value: 'paratext', label: 'paratext' }, - { value: 'peer-review', label: 'peer-review' }, - { value: 'preprint', label: 'preprint' }, - { value: 'reference-entry', label: 'reference-entry' }, - { value: 'report', label: 'report' }, - { value: 'retraction', label: 'retraction' }, - { value: 'review', label: 'review' }, - { value: 'standard', label: 'standard' }, - { value: 'supplementary-materials', label: 'supplementary-materials' }, - ]; - - readonly languageOptions = [ - { value: 'en', label: 'Englisch' }, - { value: 'de', label: 'Deutsch' }, - ]; - - // --- Search-in-panel controls --- - readonly yearSearchControl = new FormControl('', { nonNullable: true }); - readonly typeSearchControl = new FormControl('', { nonNullable: true }); - readonly languageSearchControl = new FormControl('', { nonNullable: true }); - readonly institutionSearchControl = new FormControl< - string | InstitutionAutocompleteOption - >('', { nonNullable: true }); - - // Signals instead of plain fields: these are written from inside an RxJS - // subscription (outside Angular's normal template-binding update path), - // so under OnPush change detection plain field mutation is not guaranteed - // to refresh the view. Signals make that update explicit and reliable. - readonly institutionLookupLoading = signal(false); - readonly institutionOptions = signal([]); - private readonly selectedInstitutionsMap = signal( - new Map(), - ); - queryParamMap = toSignal(this.route.queryParamMap, { initialValue: this.route.snapshot.queryParamMap, }); - selectedYearsQueryParams = computed(() => - this.queryParamMap().getAll(this.yearParamKey).map(Number), - ); - selectedTypesQueryParams = computed(() => - this.queryParamMap().getAll(this.typeParamKey), - ); - selectedLanguagesQueryParams = computed(() => - this.queryParamMap().getAll(this.languageParamKey), - ); selectedInstitutionIdsQueryParams = computed(() => this.queryParamMap().getAll(this.institutionParamKey), ); + selectedAuthorIdsQueryParams = computed(() => + this.queryParamMap().getAll(this.authorParamKey), + ); + + selectedTopicIdsQueryParams = computed(() => + this.queryParamMap().getAll(this.topicParamKey), + ); + + total = computed(() => this.works()?.total ?? 0); + totalElements = computed(() => this.works()?.total ?? 0); + elements = computed(() => this.works()?.elements ?? []); fuzzySearch = computed(() => this.queryParamMap().get('fuzzy') === 'true'); - // --- Reactive filtering of the in-panel search boxes, memoized as - // computed signals instead of being re-run as plain methods on every - // change-detection pass. --- - private readonly yearSearchTerm = toSignal( - this.yearSearchControl.valueChanges, - { initialValue: '' }, - ); - private readonly typeSearchTerm = toSignal( - this.typeSearchControl.valueChanges, - { initialValue: '' }, - ); - private readonly languageSearchTerm = toSignal( - this.languageSearchControl.valueChanges, - { initialValue: '' }, - ); - - readonly filteredYearOptions = computed(() => { - const term = this.yearSearchTerm().trim(); - if (!term) return this.publicationYearOptions; - return this.publicationYearOptions.filter((year) => - String(year).includes(term), - ); - }); - - readonly filteredTypeOptions = computed(() => { - const term = this.typeSearchTerm().trim().toLowerCase(); - if (!term) return this.typeOptions; - return this.typeOptions.filter((type) => - type.label.toLowerCase().includes(term), - ); - }); - - readonly filteredLanguageOptions = computed(() => { - const term = this.languageSearchTerm().trim().toLowerCase(); - if (!term) return this.languageOptions; - return this.languageOptions.filter((language) => - language.label.toLowerCase().includes(term), - ); - }); - - // Memoized instead of being rebuilt with a `flatMap` over every work on - // every single chip render inside the "topics" valueFormatter below. - private readonly worksTopicsById = computed(() => { - const map = new Map< - string, - { id?: string | null; display_name?: string | null } - >(); - for (const work of this.works().elements ?? []) { - for (const topic of work.topics ?? []) { - if (topic.id) map.set(topic.id, topic); - } - } - return map; - }); - - readonly observers: FilterObserver[] = [ - { - id: 'types', - queryParamKey: this.typeParamKey, - icon: 'category', - valueFormatter: (value: string) => translateWorkType(value) || value, - }, - { - id: 'years', - queryParamKey: this.yearParamKey, - icon: 'calendar_today', - }, - { - id: 'languages', - queryParamKey: this.languageParamKey, - icon: 'translate', - valueFormatter: (value: string) => translateLanguageCode(value) || value, - }, - { - id: 'institutions', - queryParamKey: this.institutionParamKey, - icon: 'apartment', - valueFormatter: (value: string) => - this.selectedInstitutionsMap().get(value)?.display_name ?? value, - }, - { - id: 'topics', - queryParamKey: this.topicParamKey, - icon: 'topic', - valueFormatter: (value: string) => { - const stateTopic = this.state.topics().find((t) => t.id === value); - if (stateTopic) return stateTopic.display_name ?? value; - return this.worksTopicsById().get(value)?.display_name ?? value; - }, - }, - ]; - // --- Data loading --- // Driven declaratively off route.queryParamMap via switchMap, instead of // a manual subscribe-per-change. This fixes two real bugs from the @@ -274,41 +98,88 @@ export class KeywordsToWorksResultsComponent implements OnInit { { initialValue: EMPTY_WORK_PAGE }, ); - totalElements = computed(() => this.works()?.total ?? 0); - elements = computed(() => this.works()?.elements ?? []); + private readonly institutionsFromWorks = computed(() => { + const map = new Map(); + for (const work of this.works().elements ?? []) { + for (const authorship of work.authorships ?? []) { + for (const institution of authorship.institutions ?? []) { + if (institution.id) map.set(institution.id, institution); + } + } + } + return map; + }); + private readonly authorsFromWorks = computed(() => { + const map = new Map(); + for (const work of this.works().elements ?? []) { + for (const authorship of work.authorships ?? []) { + const author = authorship.author; + if (author?.id) map.set(author.id, author); + } + } + return map; + }); - constructor() { - // Best-effort hydration of institution display names for institution - // IDs that arrived via the URL (shared link, page refresh, back - // button) rather than through the autocomplete — those never populate - // `selectedInstitutionsMap`, so the filter chip falls back to showing - // the raw ID. Wire this up to whatever "get institutions by id" - // endpoint your generated API client exposes. - effect( - () => { - const ids = this.selectedInstitutionIdsQueryParams(); - const known = this.selectedInstitutionsMap(); - const unresolved = ids.filter((id) => !known.has(id)); - if (unresolved.length === 0) return; + private readonly topicsFromWorks = computed(() => { + const map = new Map(); + for (const work of this.works().elements ?? []) { + for (const topic of work.topics ?? []) { + if (topic.id) map.set(topic.id, topic); + } + } + return map; + }); + selectedAuthors = computed(() => { + const byId = this.authorsFromWorks(); + console.log(byId); + return this.selectedAuthorIdsQueryParams() + .map((id) => byId.get(id)) + .filter((author): author is Author => !!author); + }); - // TODO: replace with your actual by-id institution lookup, e.g.: - // this.institutionsService.getInstitutionsByIds(unresolved).subscribe((results) => { - // this.selectedInstitutionsMap.update((map) => { - // const next = new Map(map); - // for (const inst of results) { - // if (inst.id) next.set(inst.id, inst); - // } - // return next; - // }); - // }); - }, - { allowSignalWrites: true }, - ); - } + selectedInstitutions = computed(() => { + const byId = this.institutionsFromWorks(); + return this.selectedInstitutionIdsQueryParams() + .map((id) => byId.get(id)) + .filter((inst): inst is Institution => !!inst); - ngOnInit(): void { - this.setupInstitutionAutocomplete(); - } + // TODO(institution-fallback): if an institution id from the URL isn't + // present in the currently loaded page's works (e.g. deep link to page + // 2 of a differently-sorted result, or a stale/removed id), it's + // silently dropped here and the filter chip/dropdown will show the + // raw id instead of a name. If that turns out to happen in practice, + // add a real by-id InstitutionsService lookup as a secondary fallback + // for just the unresolved ids, the same way `works` topics could also + // be backed by a topics-by-id call if needed. + }); + + selectedTopics = computed(() => { + const stateTopics = this.state.topics(); + const stateTopicIds = new Set(stateTopics.map((t) => t.id)); + const fromWorks = this.topicsFromWorks(); + + const extra = this.selectedTopicIdsQueryParams() + .filter((id) => !stateTopicIds.has(id)) + .map((id) => fromWorks.get(id)) + .filter((t): t is WorkTopic => !!t) + .map((t) => ({ id: t.id, display_name: t.display_name }) as Topic); + + return [...stateTopics, ...extra]; + }); + + // TODO(institutions-chip): PublicationFilterComponent.observers has no + // 'institutions' entry (only search/types/years/languages/authors/topics), + // so the institution filter chip won't render via + // 's internal , even + // though [showInstitutionFilter] exists as an input and we now pass + // resolved [selectedInstitutions] in above. Fix this upstream in + // PublicationFilterComponent.observers (add an 'institutions' entry + // using its own selectedInstitutions() input for the label) rather than + // patching around it here — person-publications.component doesn't work + // around it locally either, implying this is the intended single point + // of the fix. + + ngOnInit(): void {} private fetchWorks(params: ParamMap) { this.loading.set(true); @@ -325,7 +196,7 @@ export class KeywordsToWorksResultsComponent implements OnInit { this.loading.set(false); return of(EMPTY_WORK_PAGE); } - + const title = params.get('title') ?? undefined; const filterTopicIds = params.getAll(this.topicParamKey); const page = Number(params.get(this.pageParamKey)) || 0; const size = Number(params.get('size')) || 10; @@ -336,15 +207,12 @@ export class KeywordsToWorksResultsComponent implements OnInit { const publicationTypes = params.getAll(this.typeParamKey); const publicationLanguages = params.getAll(this.languageParamKey); const institutionIds = params.getAll(this.institutionParamKey); + const authorIds = params.getAll(this.authorParamKey); const fuzzy = params.get('fuzzy') === 'true'; const sortBy = (params.get('sort_by') ?? 'publication_year') as WorkSortBy; const sortDirection = (params.get('sort_direction') ?? 'desc') as SortDirection; - // ✅ Argument order matches the regenerated client exactly: - // topics, topicIds, filterTopicIds, keywords, fuzzy, - // publicationYear, publicationType, institutionIds, language, - // page, size, sortBy, sortOrder return this.worksService .getWorksByKeywords( [], @@ -355,7 +223,9 @@ export class KeywordsToWorksResultsComponent implements OnInit { publicationYears, publicationTypes, institutionIds, + authorIds, publicationLanguages, + title, page, size, sortBy, @@ -370,54 +240,6 @@ export class KeywordsToWorksResultsComponent implements OnInit { ); } - // ---------------- Filter handlers ---------------- - - private updateQueryParams(paramKey: string, value: unknown): void { - this.router.navigate([], { - queryParams: { - [paramKey]: value, - [this.pageParamKey]: 0, - }, - queryParamsHandling: 'merge', - }); - } - - handleYearSelectionChange(event: MatSelectChange): void { - this.updateQueryParams(this.yearParamKey, event.value); - } - - handleTypeSelectionChange(event: MatSelectChange): void { - this.updateQueryParams(this.typeParamKey, event.value); - } - - handleLanguageSelectionChange(event: MatSelectChange): void { - this.updateQueryParams(this.languageParamKey, event.value); - } - - displayInstitution(option: string | InstitutionAutocompleteOption): string { - return typeof option === 'string' ? option : (option.display_name ?? ''); - } - - selectInstitution(event: MatAutocompleteSelectedEvent): void { - const institution = event.option.value as InstitutionAutocompleteOption; - if (!institution.id) return; - - this.selectedInstitutionsMap.update((map) => { - const next = new Map(map); - next.set(institution.id!, institution); - return next; - }); - - const current = this.selectedInstitutionIdsQueryParams(); - if (!current.includes(institution.id)) { - this.updateQueryParams(this.institutionParamKey, [ - ...current, - institution.id, - ]); - } - this.institutionSearchControl.setValue(''); - } - clearFilters(): void { this.router.navigate([], { queryParams: { @@ -431,70 +253,4 @@ export class KeywordsToWorksResultsComponent implements OnInit { }, }); } - - yearSelectionSummary(): string { - return this.summarizeSelection(this.selectedYearsQueryParams().map(String)); - } - - typeSelectionSummary(): string { - return this.summarizeSelection(this.selectedTypesQueryParams()); - } - - languageSelectionSummary(): string { - return this.summarizeSelection( - this.selectedLanguagesQueryParams().map(String), - ); - } - - private summarizeSelection(labels: string[]): string { - if (labels.length === 0) return ''; - if (labels.length === 1) return labels[0]; - return `+${labels.length}`; - } - - focusSelectSearch(input: HTMLInputElement): void { - setTimeout(() => input.focus()); - } - - private setupInstitutionAutocomplete(): void { - this.institutionSearchControl.valueChanges - .pipe( - debounceTime(250), - map((value) => (typeof value === 'string' ? value.trim() : '')), - distinctUntilChanged(), - switchMap((query) => { - if (query.length < 2) { - this.institutionOptions.set([]); - return of([]); - } - this.institutionLookupLoading.set(true); - return this.institutionsService - .autocompleteInstitutions(query, undefined, undefined, 10) - .pipe( - map( - (response) => - (response?.results ?? []) as InstitutionAutocompleteOption[], - ), - catchError(() => of([])), - finalize(() => { - this.institutionLookupLoading.set(false); - }), - ); - }), - takeUntilDestroyed(this.destroyRef), - ) - .subscribe((options) => { - const selectedIds = new Set(this.selectedInstitutionIdsQueryParams()); - this.institutionOptions.set( - options.filter( - (option) => !!option.id && !selectedIds.has(option.id), - ), - ); - }); - } - - private createPublicationYearOptions(): number[] { - const currentYear = new Date().getFullYear(); - return Array.from({ length: 90 }, (_, index) => currentYear - index); - } }