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

642 lines
18 KiB
TypeScript

import {
takeUntilDestroyed,
toObservable,
toSignal,
} from '@angular/core/rxjs-interop';
import {
Component,
computed,
DestroyRef,
effect,
input,
OnInit,
signal,
TemplateRef,
viewChild,
} from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import {
AuthorNode,
AuthorsV2Service,
CollaborationGraph,
CollaborationGraphStatus,
Edge,
Institution,
InstitutionNode,
InstitutionPageV2,
StartCollaborationGraphResponse,
Topic,
TopicPageV2,
WorkNode,
} from '../../api';
import { MatSelectModule } from '@angular/material/select';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import {
PersonNetworkFilterDialogComponent,
PersonNetworkFilterDialogData,
} from '../person-network-filter-dialog/person-network-filter-dialog.component';
import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component';
import {
GenericColumn,
DataTableComponent,
} from '../../shared/ui/data-table/data-table.component';
import {
CollaborationGraphComponent,
NodeCategory,
NodeClickEvent,
} from '../collaboration-graph/collaboration-graph.component';
import { form, FormField } from '@angular/forms/signals';
import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
import {
FilterObserver,
SelectedFiltersComponent,
} from '../../shared/ui/selected-filters/selected-filters.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
import { from, interval, startWith, switchMap, takeWhile, tap } from 'rxjs';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
type DetailedWorkNode = WorkNode & {
authors: AuthorNode[];
};
type DetailedAuthorNode = AuthorNode & {
works: WorkNode[];
institutions: InstitutionNode[];
};
type DetailedInstitutionNode = InstitutionNode & {
authors: AuthorNode[];
};
interface FilterData {
startYear: number;
endYear: number;
minContributors: number;
maxContributors: number;
topics: Topic[];
institutions: Institution[];
}
@Component({
selector: 'app-person-network',
imports: [
MatCardModule,
MatButtonModule,
MatIconModule,
MatButtonToggleModule,
MatFormFieldModule,
FormsModule,
MatInputModule,
RouterModule,
ReactiveFormsModule,
FormsModule,
MatSelectModule,
MatExpansionModule,
MatDialogModule,
AppInfoCardComponent,
DataTableComponent,
CollaborationGraphComponent,
FormField,
SelectedFiltersComponent,
QueryParamInputComponent,
LoadingComponent,
],
templateUrl: './person-network.component.html',
styleUrl: './person-network.component.scss',
providers: [],
})
export class PersonNetworkComponent implements OnInit {
startCollaborationGraphResponse =
input.required<StartCollaborationGraphResponse>();
collaborationGraph = signal<CollaborationGraph | undefined>(undefined);
collaborationGraphStatus = signal<CollaborationGraphStatus>(
CollaborationGraphStatus.Pending,
);
collaborationGraphError = signal<string | undefined>(undefined);
selectedTopics = input.required<TopicPageV2>();
selectedInstitutions = input.required<InstitutionPageV2>();
filterModel = signal<FilterData>({
startYear: 2020,
endYear: new Date().getFullYear(),
minContributors: 2,
maxContributors: 10,
topics: [],
institutions: [],
});
displayedTable = computed(
() => this.queryParamMap().get('table') || 'collaborator',
);
filterForm2 = form(this.filterModel);
isPending = computed(
() => this.collaborationGraphStatus() === CollaborationGraphStatus.Pending,
);
isCompleted = computed(
() =>
this.collaborationGraphStatus() === CollaborationGraphStatus.Completed,
);
isFailed = computed(
() => this.collaborationGraphStatus() === CollaborationGraphStatus.Failed,
);
observers: FilterObserver[] = [
{
id: 'searchTerm',
queryParamKey: 'search_term',
icon: 'search',
},
{
id: 'yearFrom',
queryParamKey: collaborationGraphQueryParamKeys.yearFrom,
icon: 'calendar_today',
valueFormatter: (value: string) => {
return value ? `Ab ${value}` : null;
},
},
{
id: 'yearTo',
queryParamKey: collaborationGraphQueryParamKeys.yearTo,
icon: 'calendar_today',
valueFormatter: (value: string) => {
return value ? `Bis ${value}` : null;
},
},
{
id: 'minContributors',
queryParamKey: collaborationGraphQueryParamKeys.minCollaborators,
icon: 'person',
valueFormatter: (value: string) => {
return value ? `Mindestens ${value} Autoren` : null;
},
},
{
id: 'maxContributors',
queryParamKey: collaborationGraphQueryParamKeys.maxCollaborators,
icon: 'group',
valueFormatter: (value: string) => {
return value ? `Höchstens ${value} Autoren` : null;
},
},
{
id: 'topics',
queryParamKey: collaborationGraphQueryParamKeys.topicId,
icon: 'label',
valueFormatter: (value: string) => {
const topic = this.selectedTopics().elements?.find(
(topic) => topic.id === value,
);
return topic ? topic.display_name : value;
},
removable: true,
},
{
id: 'institutions',
queryParamKey: collaborationGraphQueryParamKeys.institutionId,
icon: 'apartment',
valueFormatter: (value: string) => {
const institution = this.selectedInstitutions().elements?.find(
(inst) => inst.id === value,
);
return institution ? institution.display_name : value;
},
removable: true,
},
];
collaboratorsColumns: GenericColumn<DetailedAuthorNode>[] = [];
collaboratorsData = computed<DetailedAuthorNode[]>(
() =>
this.collaborationGraph()?.authors?.map((author) => ({
...author,
works: (this.collaborationGraph()?.works ?? []).filter((work) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) => edge.source === author.id && edge.target === work.id,
),
),
institutions: (this.collaborationGraph()?.institutions ?? []).filter(
(institution) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) =>
edge.source === author.id && edge.target === institution.id,
),
),
})) ?? [],
);
collaboratorsActionTmp = viewChild.required<TemplateRef<any>>(
'collaboratorsActionTmp',
);
collaboratorsFrequencyTmp = viewChild.required<TemplateRef<any>>(
'collaboratorsFrequencyTmp',
);
collaboratorsDetailRow = viewChild.required<TemplateRef<any>>(
'collaboratorsDetailRow',
);
publicationsColumns: GenericColumn<DetailedWorkNode>[] = [];
publicationsData = computed(
() =>
this.collaborationGraph()?.works?.map((work) => ({
...work,
authors: (this.collaborationGraph()?.authors ?? []).filter((author) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) => edge.source === author.id && edge.target === work.id,
),
),
})) ?? [],
);
publicationsActionTmp = viewChild.required<TemplateRef<any>>(
'publicationsActionTmp',
);
publicationsCollaborationFrequencyTmp = viewChild.required<TemplateRef<any>>(
'publicationsCollaborationFrequencyTmp',
);
publicationsDetailRow = viewChild.required<TemplateRef<any>>(
'publicationsDetailRow',
);
institutionsColumns: GenericColumn<DetailedInstitutionNode>[] = [];
institutionsData = computed(
() =>
this.collaborationGraph()?.institutions?.map((institution) => ({
...institution,
authors: (this.collaborationGraph()?.authors ?? []).filter((author) =>
(this.collaborationGraph()?.edges ?? []).some(
(edge) =>
edge.source === author.id && edge.target === institution.id,
),
),
})) ?? [],
);
institutionsActionTmp = viewChild.required<TemplateRef<any>>(
'institutionsActionTmp',
);
institutionsFrequencyTmp = viewChild.required<TemplateRef<any>>(
'institutionsFrequencyTmp',
);
institutionsDetailRow = viewChild.required<TemplateRef<any>>(
'institutionsDetailRow',
);
persons = computed(() => this.collaborationGraph()?.authors?.length ?? 0);
institutions = computed(
() => this.collaborationGraph()?.institutions?.length ?? 0,
);
publications = computed(() => this.collaborationGraph()?.works?.length ?? 0);
connections = computed(() => this.collaborationGraph()?.edges?.length ?? 0);
searchTermLabel = computed(() => {
const displayedTable = this.displayedTable();
switch (displayedTable) {
case 'collaborator':
return 'Suche Kollaborierende nach Name';
case 'publication':
return 'Suche Publikationen nach Titel';
case 'institution':
return 'Suche Institutionen nach Name';
default:
return 'Suchbegriff';
}
});
private readonly categoryTableMap: Record<NodeCategory, string> = {
author: 'collaborator',
collaborator: 'collaborator',
work: 'publication',
institution: 'institution',
};
latestNodeId = signal<string | null>(null);
rebuildCollaborationGraph(
collaborationGraph: CollaborationGraph,
): CollaborationGraph {
const rebuiltGraph = this.rebuildEdges(collaborationGraph);
return rebuiltGraph;
}
rebuildEdges(collaborationGraph: CollaborationGraph): CollaborationGraph {
const edges = collaborationGraph.edges ?? [];
const authors = collaborationGraph.authors ?? [];
const authorInstitutionEdges = authors.flatMap((author) =>
(author.institution_ids ?? []).map((institutionId) => ({
source: author.id,
target: institutionId,
weight: 1,
})),
);
const works = collaborationGraph.works ?? [];
const workAuthorEdges = works.flatMap((work) =>
(work.author_ids ?? []).map((authorId) => ({
source: authorId,
target: work.id,
weight: 1,
})),
);
return {
...collaborationGraph,
edges: this.reduceEdges([
...edges,
...authorInstitutionEdges,
...workAuthorEdges,
]),
};
}
reduceEdges(edges: Edge[]): Edge[] {
const reducedEdgesMap = new Map<string, Edge>();
for (const edge of edges) {
const key = `${edge.source}-${edge.target}`;
if (reducedEdgesMap.has(key)) {
reducedEdgesMap.get(key)!.weight += edge.weight;
} else {
reducedEdgesMap.set(key, edge);
}
}
return Array.from(reducedEdgesMap.values());
}
handleNodeClick = ({ id, name, category }: NodeClickEvent): void => {
console.log('Node clicked:', { id, name, category });
if (this.latestNodeId() === id) {
this.clearSearch();
return;
}
this.latestNodeId.set(id);
if (category === 'author') {
return;
}
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
search_term: name,
table: this.categoryTableMap[category] || 'collaborator',
},
queryParamsHandling: 'merge',
});
};
clearSearch() {
this.latestNodeId.set(null);
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
search_term: null,
},
queryParamsHandling: 'merge',
});
}
readonly summaryCards = computed(() => [
{
icon: 'person',
value: this.persons(),
description: 'Personen',
},
{
icon: 'apartment',
value: this.institutions(),
description: 'Institutionen',
},
{
icon: 'menu_book',
value: this.publications(),
description: 'Gemeinsame Publikationen',
},
{
icon: 'share',
value: this.connections(),
description: 'Verbindungen im Netzwerk',
},
]);
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
searchTerm = computed(() => this.queryParamMap().get('search_term') || '');
private readonly POLL_INTERVAL_MS = 3000;
constructor(
private readonly activatedRoute: ActivatedRoute,
private readonly router: Router,
private readonly dialog: MatDialog,
private readonly authorsService: AuthorsV2Service,
private readonly destroyRef: DestroyRef,
) {
toObservable(this.startCollaborationGraphResponse)
.pipe(
switchMap((startResponse) =>
interval(this.POLL_INTERVAL_MS).pipe(
startWith(0),
switchMap(() =>
from(
this.authorsService.getCollaborationGraphStatus(
startResponse.graph_id,
),
),
),
tap((statusResponse) => {
this.collaborationGraphStatus.set(statusResponse.status);
this.collaborationGraphError.set(
statusResponse.error_message ?? undefined,
);
if (
statusResponse.result &&
statusResponse.status === CollaborationGraphStatus.Completed
) {
this.collaborationGraph.set(
this.rebuildCollaborationGraph(statusResponse.result),
);
}
}),
takeWhile((statusResponse) => {
return statusResponse.status === CollaborationGraphStatus.Pending;
}, true),
),
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe();
effect(() => {
const filters = this.filterModel();
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
[collaborationGraphQueryParamKeys.yearFrom]:
filters.startYear || null,
[collaborationGraphQueryParamKeys.yearTo]: filters.endYear || null,
[collaborationGraphQueryParamKeys.minCollaborators]:
filters.minContributors || null,
[collaborationGraphQueryParamKeys.maxCollaborators]:
filters.maxContributors || null,
[collaborationGraphQueryParamKeys.topicId]:
filters.topics.length > 0
? filters.topics.map((topic) => topic.id)
: null,
[collaborationGraphQueryParamKeys.institutionId]:
filters.institutions.length > 0
? filters.institutions.map((inst) => inst.id)
: null,
},
queryParamsHandling: 'merge',
});
});
}
openFilterDialog() {
const data: PersonNetworkFilterDialogData = {
selectedTopics: this.selectedTopics().elements ?? [],
selectedInstitutions: this.selectedInstitutions().elements ?? [],
startYear: this.filterForm2.startYear().value(),
endYear: this.filterForm2.endYear().value(),
minContributors: this.filterForm2.minContributors().value(),
maxContributors: this.filterForm2.maxContributors().value(),
};
const dialogRef = this.dialog.open(PersonNetworkFilterDialogComponent, {
data: data,
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.filterModel.set({
startYear: result.startYear,
endYear: result.endYear,
minContributors: result.minContributors,
maxContributors: result.maxContributors,
topics: result.topics,
institutions: result.institutions,
});
}
});
}
ngOnInit(): void {
const queryParamMap = this.queryParamMap();
this.filterModel.set({
startYear:
Number(queryParamMap.get(collaborationGraphQueryParamKeys.yearFrom)) ||
2020,
endYear:
Number(queryParamMap.get(collaborationGraphQueryParamKeys.yearTo)) ||
new Date().getFullYear(),
minContributors:
Number(
queryParamMap.get(collaborationGraphQueryParamKeys.minCollaborators),
) || 2,
maxContributors:
Number(
queryParamMap.get(collaborationGraphQueryParamKeys.maxCollaborators),
) || 10,
topics: this.selectedTopics().elements || [],
institutions: this.selectedInstitutions().elements || [],
});
this.collaboratorsColumns = [
{
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'display_name',
},
{
id: 'works',
header: 'Häufigkeit',
type: 'display',
cellTemplate: this.collaboratorsFrequencyTmp(),
},
{
id: 'actions',
header: '',
type: 'display',
cellTemplate: this.collaboratorsActionTmp(),
},
];
this.publicationsColumns = [
{
id: 'title',
header: 'Titel',
type: 'accessor',
accessorKey: 'display_name',
},
{
id: 'collaborators',
header: 'Mitwirkende',
type: 'display',
cellTemplate: this.publicationsCollaborationFrequencyTmp(),
},
{
id: 'actions',
header: '',
type: 'display',
cellTemplate: this.publicationsActionTmp(),
},
];
this.institutionsColumns = [
{
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'display_name',
},
{
id: 'collaborators',
header: 'Mitwirkende',
type: 'display',
cellTemplate: this.institutionsFrequencyTmp(),
},
{
id: 'actions',
header: '',
type: 'display',
cellTemplate: this.institutionsActionTmp(),
},
];
}
onToggleChange(event: any) {
const value = event.value;
if (!value) {
return;
}
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
table: value,
},
queryParamsHandling: 'merge',
});
}
stripOpenAlexIdPrefix(id: string): string {
if (id.startsWith('https://openalex.org/')) {
return id.substring(21);
}
return id;
}
}