used generic publication-table component for keyword-search

This commit is contained in:
2026-07-17 15:14:59 +02:00
parent 272979cd58
commit 715f775071
5 changed files with 148 additions and 524 deletions
+4
View File
@@ -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,
+12 -15
View File
@@ -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", {})
+14 -4
View File
@@ -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<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseWorksV2ModelWorkPage>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, authorIds?: Array<string>, language?: Array<string>, title?: string, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseWorksV2ModelWorkPage>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, authorIds?: Array<string>, language?: Array<string>, title?: string, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, authorIds?: Array<string>, language?: Array<string>, title?: string, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, authorIds?: Array<string>, language?: Array<string>, 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<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (topics) {
@@ -688,12 +690,20 @@ export class WorksV2Service extends BaseService {
<any>element, 'institution_ids');
})
}
if (authorIds) {
authorIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'author_ids');
})
}
if (language) {
language.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'language');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>title, 'title');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -1,165 +1,22 @@
<div class="page">
<div class="publication-filter-stack">
<form class="publication-filters">
<mat-form-field>
<mat-icon matPrefix class="filter-prefix-icon">calendar_today</mat-icon>
<mat-select
placeholder="Jahr"
multiple
[panelWidth]="null"
(selectionChange)="handleYearSelectionChange($event)"
(opened)="focusSelectSearch(yearSearchInput)"
[value]="selectedYearsQueryParams()">
<mat-select-trigger>{{ yearSelectionSummary() }}</mat-select-trigger>
<div class="select-search" (click)="$event.stopPropagation()">
<mat-icon class="select-search__icon">search</mat-icon>
<input
#yearSearchInput
type="text"
class="select-search__input"
[formControl]="yearSearchControl"
placeholder="Jahr suchen…"
(keydown)="$event.stopPropagation()" />
</div>
@for (year of filteredYearOptions(); track year) {
<mat-option [value]="year">{{ year }}</mat-option>
} @empty {
<div class="select-search__empty">Keine Treffer</div>
}
</mat-select>
</mat-form-field>
<div class="content">
<app-publication-filter
[selectedTopics]="selectedTopics()"
[selectedInstitutions]="selectedInstitutions()"
[selectedAuthors]="selectedAuthors()"
[showTopicFilter]="fuzzySearch()" />
<mat-form-field>
<mat-icon matPrefix class="filter-prefix-icon">category</mat-icon>
<mat-select
placeholder="Typ"
multiple
[panelWidth]="null"
(selectionChange)="handleTypeSelectionChange($event)"
(opened)="focusSelectSearch(typeSearchInput)"
[value]="selectedTypesQueryParams()">
<mat-select-trigger>{{ typeSelectionSummary() }}</mat-select-trigger>
<div class="select-search" (click)="$event.stopPropagation()">
<mat-icon class="select-search__icon">search</mat-icon>
<input
#typeSearchInput
type="text"
class="select-search__input"
[formControl]="typeSearchControl"
placeholder="Typ suchen…"
(keydown)="$event.stopPropagation()" />
</div>
@for (type of filteredTypeOptions(); track type.value) {
<mat-option [value]="type.value">{{ type.label }}</mat-option>
} @empty {
<div class="select-search__empty">Keine Treffer</div>
}
</mat-select>
</mat-form-field>
@if (loading()) {
<app-loading [icon]="'article'" />
} @else {
<app-publication-table
[page]="works()"
[authorFilterEnabled]="true"
[institutionFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()" />
}
<mat-form-field>
<mat-icon matPrefix class="filter-prefix-icon">translate</mat-icon>
<mat-select
placeholder="Sprache"
multiple
[panelWidth]="null"
(selectionChange)="handleLanguageSelectionChange($event)"
(opened)="focusSelectSearch(languageSearchInput)"
[value]="selectedLanguagesQueryParams()">
<mat-select-trigger>{{
languageSelectionSummary()
}}</mat-select-trigger>
<div class="select-search" (click)="$event.stopPropagation()">
<mat-icon class="select-search__icon">search</mat-icon>
<input
#languageSearchInput
type="text"
class="select-search__input"
[formControl]="languageSearchControl"
placeholder="Sprache suchen…"
(keydown)="$event.stopPropagation()" />
</div>
@for (language of filteredLanguageOptions(); track language.value) {
<mat-option [value]="language.value">{{
language.label
}}</mat-option>
} @empty {
<div class="select-search__empty">Keine Treffer</div>
}
</mat-select>
</mat-form-field>
<mat-form-field class="institution-filter">
<mat-icon matPrefix class="filter-prefix-icon">apartment</mat-icon>
<input
type="text"
matInput
[formControl]="institutionSearchControl"
[matAutocomplete]="institutionAutocomplete"
placeholder="Institution suchen" />
<mat-autocomplete
#institutionAutocomplete="matAutocomplete"
[displayWith]="displayInstitution"
(optionSelected)="selectInstitution($event)">
@for (institution of institutionOptions(); track institution.id) {
<mat-option [value]="institution">
<span>{{ institution.display_name }}</span>
@if (institution.hint) {
<small>{{ institution.hint }}</small>
}
</mat-option>
}
@if (
!institutionLookupLoading() &&
institutionOptions().length === 0 &&
institutionSearchControl.value
) {
<mat-option disabled>Keine Institution gefunden</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<button
class="reset-filter-btn"
mat-stroked-button
type="button"
(click)="clearFilters()"
aria-label="Filter zurücksetzen">
<mat-icon>filter_alt_off</mat-icon>
<span>Zurücksetzen</span>
</button>
</form>
</div>
<app-selected-filters [observers]="observers" />
<div class="result-layout">
@if (loading()) {
<app-loading
text="Publikationsliste wird geladen..."
icon="groups"
[size]="200"
[diameter]="200" />
} @else if (works().elements?.length === 0) {
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<mat-icon>groups</mat-icon>
<span>Keine Publikationen gefunden.</span>
</mat-card-content>
</mat-card>
} @else {
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<app-publication-table
[page]="works()"
[institutionFilterEnabled]="true" />
<app-query-param-paginator
[total]="totalElements()"
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="paginationService.options" />
</mat-card-content>
</mat-card>
}
</div>
<app-query-param-paginator
[total]="total()"
queryParamPageKey="page"
queryParamSizeKey="size" />
</div>
@@ -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<InstitutionAutocompleteOption[]>([]);
private readonly selectedInstitutionsMap = signal(
new Map<string, InstitutionAutocompleteOption>(),
);
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<string, Institution>();
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<string, Author>();
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<string, WorkTopic>();
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<Author[]>(() => {
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<Institution[]>(() => {
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<Topic[]>(() => {
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
// <app-publication-filter>'s internal <app-selected-filters>, 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);
}
}