Files
smartguide/webapp/src/app/modules/person/person.component.ts
T

483 lines
14 KiB
TypeScript

import { DecimalPipe } from '@angular/common';
import {
Component,
computed,
inject,
signal,
DestroyRef,
ElementRef,
input,
viewChild,
} from '@angular/core';
import {
toSignal,
toObservable,
takeUntilDestroyed,
} from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon';
import { MatTabsModule } from '@angular/material/tabs';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
ActivatedRoute,
NavigationEnd,
Router,
RouterModule,
RouterOutlet,
} from '@angular/router';
import {
of,
switchMap,
finalize,
map,
catchError,
combineLatest,
filter,
} from 'rxjs';
import { PersonInterestingComponent } from '../person-interesting/person-interesting.component';
import { CareerStageChipComponent } from '../../shared/ui/career-stage-chip/career-stage-chip.component';
import { AppInstitutionChipComponent } from '../../shared/ui/app-institution-chip/app-institution-chip.component';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { PersonInstitutionTooltipListComponent } from '../../shared/ui/person-institution-tooltip-list/person-institution-tooltip-list.component';
import { DehydratedInstitution, WorksService } from '../../api';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
import { PersonDataResolved } from '../../resolvers/person.resolver';
import { BookmarkService } from '../../shared/services/bookmark.service';
import { AuthorAffiliationService } from '../../shared/services/author-affiliation.service';
import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import {
LinkTabNavBarComponent,
LinkTabNavBarItem,
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
import {
AI_GENERATED_ICON,
BOOKMARK_BORDER_ICON,
BOOKMARK_ICON,
BUSINESS_ICON,
CITATION_ICON,
DESCRIPTION_ICON,
FUNDING_ICON,
INSTITUTION_ICON,
MORE_INFO_ICON,
NETWORK_ICON,
NEWS_ICON,
OVERVIEW_ICON,
PATENT_ICON,
PERSON_ICON,
PROJECT_ICON,
PUBLICATION_ICON,
TRENDING_UP_ICON,
VERIFIED_ICON,
} from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
@Component({
selector: 'app-person',
imports: [
DecimalPipe,
MatIconModule,
MatTabsModule,
MatTooltipModule,
PersonInterestingComponent,
RouterOutlet,
RouterModule,
LoadingComponent,
CareerStageChipComponent,
LinkTabNavBarComponent,
AppInstitutionChipComponent,
ComponentTooltipDirective,
PageContainerComponent,
],
templateUrl: './person.component.html',
styleUrl: './person.component.scss',
})
export class PersonComponent {
readonly BOOKMARK_ICON = BOOKMARK_ICON;
readonly BOOKMARK_BORDER_ICON = BOOKMARK_BORDER_ICON;
readonly INSTITUTION_ICON = INSTITUTION_ICON;
readonly PUBLICATION_ICON = PUBLICATION_ICON;
readonly CITATION_ICON = CITATION_ICON;
readonly TRENDING_UP_ICON = TRENDING_UP_ICON;
readonly VERIFIED_ICON = VERIFIED_ICON;
readonly DESCRIPTION_ICON = DESCRIPTION_ICON;
readonly PERSON_ICON = PERSON_ICON;
readonly AI_GENERATED_ICON = AI_GENERATED_ICON;
readonly MORE_INFO_ICON = MORE_INFO_ICON;
readonly PersonInstitutionTooltipListComponent =
PersonInstitutionTooltipListComponent;
private readonly router = inject(Router);
private readonly activatedRoute = inject(ActivatedRoute);
private readonly worksApi = inject(WorksService);
private readonly destroyRef = inject(DestroyRef);
readonly bookmarkService = inject(BookmarkService);
private readonly authorAffiliationService = inject(AuthorAffiliationService);
canFetchGdprRelevantData = input.required<boolean>();
protected readonly navBar = viewChild<LinkTabNavBarComponent>('navBar');
protected readonly activeLink = computed(
() => this.navBar()?.activeLink() ?? null,
);
private readonly tabPanelElement = viewChild('tabPanel', {
read: ElementRef,
});
private publicationFilterKey: string | null = null;
constructor() {
this.bookmarkService
.load()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
this.router.events
.pipe(
filter(
(event): event is NavigationEnd => event instanceof NavigationEnd,
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((event) =>
this.scrollToPanelOnFilterChange(event.urlAfterRedirects),
);
}
readonly params = toSignal(this.activatedRoute.paramMap);
readonly routerEvents = toSignal(this.router.events);
readonly currentUrl = toSignal(
this.router.events.pipe(switchMap(() => of(this.router.url))),
);
// derive authorID directly from route
private readonly authorId = toSignal(
this.activatedRoute.paramMap.pipe(
map((params) => params.get('id') ?? null),
takeUntilDestroyed(this.destroyRef),
),
);
readonly isPersonLoading = signal(false);
readonly isBioLoading = signal(false);
readonly person = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
const resolved = data['personData'] as PersonDataResolved | undefined;
if (!resolved) {
this.isPersonLoading.set(false);
return of(null);
}
this.isPersonLoading.set(true);
return resolved.personData$.pipe(
map((response) => response?.results?.[0] ?? null),
finalize(() => this.isPersonLoading.set(false)),
);
}),
),
{ initialValue: null },
);
readonly companyConnectionsAvailable = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
const resolved = data['personData'] as PersonDataResolved | undefined;
if (!resolved) {
return of(false);
}
return resolved.companyConnectionsAvailable$;
}),
),
{ initialValue: false },
);
toggleBookmark(): void {
const person = this.person();
if (!person) return;
this.bookmarkService
.confirmToggle(person)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
}
readonly personBio = toSignal(
combineLatest([this.activatedRoute.data, toObservable(this.person)]).pipe(
switchMap(([data, person]) => {
if (!person) {
this.isBioLoading.set(false);
return of(null);
}
const resolved = data['personBio'] as PersonBioResolved | undefined;
if (!resolved) {
this.isBioLoading.set(false);
return of(null);
}
this.isBioLoading.set(true);
return resolved.bio$.pipe(finalize(() => this.isBioLoading.set(false)));
}),
),
{ initialValue: null },
);
readonly displayName = computed(
() => this.person()?.display_name ?? 'Unbekannte Person',
);
readonly personName = computed(() => this.person()?.display_name ?? '');
readonly personPublicationsLink = computed<unknown[] | null>(() => {
const authorId = this.authorId();
return authorId ? ['/person', authorId, 'publications'] : null;
});
readonly initials = computed(() => this.buildInitials(this.displayName()));
readonly primaryAffiliation = computed(
() => this.person()?.affiliations?.[0] ?? null,
);
readonly lastAffiliation = computed(
() =>
this.authorAffiliationService.getLatestAffiliation(this.person()) ?? null,
);
readonly resolvedInstitution = computed(() =>
this.authorAffiliationService.resolveInstitution(this.person()),
);
readonly secondaryInstitutions = computed<DehydratedInstitution[]>(() =>
this.authorAffiliationService.resolveSecondaryInstitutions(this.person()),
);
readonly worksCount = computed(() => this.person()?.works_count ?? null);
readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null);
readonly h_index = computed(
() => this.person()?.summary_stats?.h_index ?? null,
);
readonly displayCareerStage = computed(() => {
const stage = this.person()?.career_metrics?.career_stage;
if (!stage || stage === 'unknown') {
return null;
}
return stage;
});
readonly orcid = computed(() => {
const rawOrcid = this.getId('orcid');
if (!rawOrcid) {
return null;
}
return rawOrcid.replace('https://orcid.org/', '');
});
readonly orcidUrl = computed(() =>
this.orcid() ? `https://orcid.org/${this.orcid()}` : null,
);
readonly worksApiUrl = computed(() => this.person()?.works_api_url ?? null);
readonly isTopicsLoading = signal(false);
readonly primaryTopicCounts = toSignal(
toObservable(this.person).pipe(
switchMap((person) => {
const id = this.authorId();
if (!person || !id) {
this.isTopicsLoading.set(false);
return of([]);
}
this.isTopicsLoading.set(true);
return this.worksApi.getPrimaryTopicCountsByAuthor(id).pipe(
catchError((err) => {
console.error('Failed to load primary topic counts:', err);
return of([]);
}),
finalize(() => this.isTopicsLoading.set(false)),
);
}),
),
{ initialValue: [] },
);
readonly links = computed<LinkTabNavBarItem[]>(() => {
const links = [
{
label: 'Übersicht',
description: 'Übersicht über die Person',
icon: OVERVIEW_ICON,
path: 'overview',
disabled: false,
},
...(this.canFetchGdprRelevantData()
? [
{
label: 'Projekte',
description: 'Übersicht der durchgeführten Projekte der Person',
icon: PROJECT_ICON,
path: 'projects',
queryParams: {
page: 0,
size: 10,
sort_by: 'title',
sort_direction: 'asc',
search: '',
},
disabled: false,
},
]
: []),
{
label: 'Publikationen',
description: 'Übersicht der Publikationen der Person',
icon: PUBLICATION_ICON,
path: 'publications',
},
{
label: 'Netzwerk',
description: 'Kooperationsnetzwerk der Person',
icon: NETWORK_ICON,
path: 'network',
disabled: false,
queryParams: {
[collaborationGraphQueryParamKeys.minCollaborators]: '2',
[collaborationGraphQueryParamKeys.maxCollaborators]: '10',
[collaborationGraphQueryParamKeys.yearFrom]: '1900',
[collaborationGraphQueryParamKeys.yearTo]: new Date().getFullYear(),
},
},
...(this.companyConnectionsAvailable()
? [
{
label: 'Unternehmen',
description: 'Unternehmen, mit denen die Person verbunden ist',
icon: BUSINESS_ICON,
path: 'company-connections',
disabled: false,
},
]
: []),
{
label: 'Förderungen',
description: 'Übersicht der Förderungen der Person',
icon: FUNDING_ICON,
path: 'funding',
disabled: false,
},
{
label: 'Nachrichten',
description: 'Nachrichten über die Person',
icon: NEWS_ICON,
path: 'news',
disabled: false,
},
{
label: 'Patente',
description: 'Patente der Person',
icon: PATENT_ICON,
path: 'patents',
disabled: false,
},
];
return links;
});
// readonly activeLink = computed<LinkTabNavBarItem | null>(() => {
// const currentUrl = this.currentUrl();
// if (!currentUrl) {
// return null;
// }
// for (const link of this.links()) {
// const linkUrl = this.router
// .createUrlTree([link.path], {
// relativeTo: this.activatedRoute,
// })
// .toString();
// if (linkUrl.startsWith(currentUrl) || currentUrl.startsWith(linkUrl)) {
// return link;
// }
// }
// return null;
// });
onInterestingTagClick(selection: {
id: string;
name: string;
fieldName?: string;
domainName?: string;
}): void {
if (!selection.id) return;
void this.router.navigate(['publications'], {
relativeTo: this.activatedRoute,
queryParams: {
[workQueryParamKeys.page]: 0,
[workQueryParamKeys.topicId]: selection.id,
},
});
}
private scrollToPanelOnFilterChange(url: string): void {
const { queryParams } = this.router.parseUrl(url);
const filterKey = [workQueryParamKeys.topicId, workQueryParamKeys.years]
.map((key) => {
const value = queryParams[key];
return Array.isArray(value) ? value.join(',') : (value ?? '');
})
.join('|');
const previousFilterKey = this.publicationFilterKey;
this.publicationFilterKey = filterKey;
const hasFilter = filterKey !== '|';
const isFirstNavigation = previousFilterKey === null;
if (isFirstNavigation || !hasFilter || filterKey === previousFilterKey) {
return;
}
this.scrollPanelIntoView();
}
private scrollPanelIntoView(): void {
const scrollToPanel = (): void => {
this.tabPanelElement()?.nativeElement.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
};
requestAnimationFrame(scrollToPanel);
setTimeout(() => {
const panel = this.tabPanelElement();
if (panel && panel.nativeElement.getBoundingClientRect().top > 8) {
scrollToPanel();
}
}, 400);
}
private getId(key: string): string | null {
const ids = this.person()?.ids as Record<string, string> | undefined;
if (!ids) {
return null;
}
const value = ids[key];
return value ? String(value) : null;
}
private buildInitials(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) {
return '??';
}
if (parts.length === 1) {
return parts[0].slice(0, 2).toUpperCase();
}
return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
}
}