feat(collaboration-graph): updated frontend view for graph, updated filters, and forms
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Mats Paul Tončik
2026-07-24 16:53:23 +02:00
parent e7afd7e68a
commit e6eabf08c9
29 changed files with 1132 additions and 635 deletions
+7 -1
View File
@@ -401,7 +401,13 @@ def _build_collaboration_graph(
internal_graph.add_edge(Edge(source=author.id, target=work.id, weight=1.0))
return CollaborationGraph.from_internal_graph(internal_graph)
graph = CollaborationGraph.from_internal_graph(internal_graph)
logger.debug(
f"Built collaboration graph for author {raw_oa_author_id} {len(graph.authors)} authors, {len(graph.works)} works, {len(graph.institutions)} institutions, {len(graph.edges)} edges"
)
return graph
def _prefix_id(raw_oa_id: str) -> str:
@@ -43,6 +43,7 @@ model/authorCountsByYearInner.ts
model/authorIds.ts
model/authorMetricsRequest.ts
model/authorNetworkNode.ts
model/authorNode.ts
model/authorPage.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
@@ -69,6 +70,7 @@ model/bundProjectDetails.ts
model/bundProjectPage.ts
model/careerMetrics.ts
model/careerStage.ts
model/collaborationGraph.ts
model/collaborationNetwork.ts
model/collaborationNetworkEdge.ts
model/collaborationNetworkNodeType.ts
@@ -98,6 +100,7 @@ model/dfgPersonSummaryPage.ts
model/dfgProjectDetails.ts
model/dfgProjectPage.ts
model/dfgProjectSummary.ts
model/edge.ts
model/euCordisEurosciVocSummary.ts
model/euCordisOrganizationSelectorPage.ts
model/euCordisOrganizationSelectorSummary.ts
@@ -161,6 +164,7 @@ model/institutionGeo.ts
model/institutionIds.ts
model/institutionInformation.ts
model/institutionNetworkNode.ts
model/institutionNode.ts
model/institutionPage.ts
model/institutionPageV2.ts
model/institutionsListResponse.ts
@@ -276,6 +280,7 @@ model/workIds.ts
model/workKeyword.ts
model/workMeshInner.ts
model/workNetworkNode.ts
model/workNode.ts
model/workPage.ts
model/workPageV2.ts
model/workPrimaryCategory.ts
@@ -19,6 +19,8 @@ import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorPage } from '../model/authorPage';
// @ts-ignore
import { CollaborationGraph } from '../model/collaborationGraph';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
@@ -155,4 +157,88 @@ export class AuthorsV2Service extends BaseService {
);
}
/**
* Returns a collaboration graph for a given author ID.
* @endpoint get /api/authors/v2/collaboration-graph/{raw_oa_author_id}
* @param rawOaAuthorId The raw OpenAlex author ID for which to retrieve the collaboration graph.
* @param yearFrom The starting year to filter the works by (optional).
* @param yearTo The ending year to filter the works by (optional).
* @param minCollaborators The minimum number of collaborators to filter the works by (optional).
* @param maxCollaborators The maximum number of collaborators to filter the works by (optional).
* @param topicIds A list of topic IDs to filter the works by (optional).
* @param institutionIds A list of institution IDs to filter the works by (optional).
* @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 getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CollaborationGraph>;
public getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CollaborationGraph>>;
public getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CollaborationGraph>>;
public getCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getCollaborationGraph.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>yearFrom, 'year_from');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>yearTo, 'year_to');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>minCollaborators, 'min_collaborators');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>maxCollaborators, 'max_collaborators');
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/authors/v2/collaboration-graph/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CollaborationGraph>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface AuthorNode {
/**
* The ID of the author.
*/
id: string;
/**
* The display name of the author.
*/
display_name: string;
}
@@ -0,0 +1,38 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { WorkNode } from './workNode';
import { Edge } from './edge';
import { InstitutionNode } from './institutionNode';
import { AuthorNode } from './authorNode';
export interface CollaborationGraph {
/**
* The ID of the root author.
*/
root_author_id: string;
/**
* A list of author nodes.
*/
authors?: Array<AuthorNode>;
/**
* A list of institution nodes.
*/
institutions?: Array<InstitutionNode>;
/**
* A list of work nodes.
*/
works?: Array<WorkNode>;
/**
* A list of edges in the collaboration graph.
*/
edges?: Array<Edge>;
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface Edge {
/**
* The ID of the source node.
*/
source: string;
/**
* The ID of the target node.
*/
target: string;
/**
* The weight of the edge.
*/
weight: number;
}
@@ -0,0 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface InstitutionNode {
/**
* The ID of the institution.
*/
id: string;
/**
* The display name of the institution.
*/
display_name: string;
}
+5
View File
@@ -9,6 +9,7 @@ export * from './authorCountsByYearInner';
export * from './authorIds';
export * from './authorMetricsRequest';
export * from './authorNetworkNode';
export * from './authorNode';
export * from './authorPage';
export * from './authorParsedLongestName';
export * from './authorPositionCount';
@@ -35,6 +36,7 @@ export * from './bundProjectDetails';
export * from './bundProjectPage';
export * from './careerMetrics';
export * from './careerStage';
export * from './collaborationGraph';
export * from './collaborationNetwork';
export * from './collaborationNetworkEdge';
export * from './collaborationNetworkNodeType';
@@ -64,6 +66,7 @@ export * from './dfgPersonSummaryPage';
export * from './dfgProjectDetails';
export * from './dfgProjectPage';
export * from './dfgProjectSummary';
export * from './edge';
export * from './euCordisEurosciVocSummary';
export * from './euCordisOrganizationSelectorPage';
export * from './euCordisOrganizationSelectorSummary';
@@ -127,6 +130,7 @@ export * from './institutionGeo';
export * from './institutionIds';
export * from './institutionInformation';
export * from './institutionNetworkNode';
export * from './institutionNode';
export * from './institutionPage';
export * from './institutionPageV2';
export * from './institutionsListResponse';
@@ -241,6 +245,7 @@ export * from './workIds';
export * from './workKeyword';
export * from './workMeshInner';
export * from './workNetworkNode';
export * from './workNode';
export * from './workPage';
export * from './workPageV2';
export * from './workPrimaryCategory';
+26
View File
@@ -0,0 +1,26 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface WorkNode {
/**
* The ID of the work.
*/
id: string;
/**
* The title of the work.
*/
display_name: string;
/**
* The publication year of the work.
*/
publication_year: number;
}
+11 -15
View File
@@ -1,6 +1,5 @@
import { Routes } from '@angular/router';
import { guestOnlyGuard } from './shared/guards/guest-only.guard';
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
import { personListResolver } from './resolvers/person-list.resolver';
import { personBioResolver } from './resolvers/person-bio.resolver';
import { personPatentsResolver } from './resolvers/person-patents.resolver';
@@ -40,7 +39,6 @@ import { selectedInstitutionsResolver } from './resolvers/selected-institutions.
import { SearchResultsStateService } from './modules/keywords-search/search-results/search-results-state.service';
import { roleGuard } from './shared/guards/role.guard';
import { UserRole } from './api';
import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver';
import { euCordisProjectsResolver } from './resolvers/eu-cordis-projects.resolver';
import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver';
import { workClassificationResolver } from './resolvers/work-classification.resolver';
@@ -51,6 +49,10 @@ import { selectedEuInstitutionsResolver } from './resolvers/selected-eu-institut
import { uniTrendResolver } from './resolvers/uni-trend.resolver';
import { EuProjectsComponent } from './shared/ui/eu-projects/eu-projects.component';
import { DfgProjectsComponent } from './shared/ui/dfg-projects/dfg-projects.component';
import {
collaborationGraphQueryParamKeys,
collaborationGraphResolver,
} from './resolvers/collaboration-graph.resolver';
export const routes: Routes = [
{
path: '',
@@ -528,20 +530,14 @@ export const routes: Routes = [
import('./modules/person-network/person-network.component').then(
(mod) => mod.PersonNetworkComponent,
),
resolve: { collaborationNetwork: collaborationNetworkResolver },
resolve: {
collaborationGraph: collaborationGraphResolver,
selectedTopics: selectedTopicsResolver,
selectedInstitutions: selectedInstitutionsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = [
'filter_by',
'start_year',
'end_year',
'min_contributors',
'max_contributors',
'min_collaborations',
'max_collaborations',
'institutions',
'topics',
];
return keys.some(
// IT SHOULD ALWAYS HAVE BEEN .values INSTEAD OF .keys, + 30 Minutes
return Object.values(collaborationGraphQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
@@ -0,0 +1,18 @@
@if (isEmptyGraph()) {
<div class="warning-container">
<mat-icon>warning</mat-icon>
<p>Das Netzwerk ist leer.</p>
</div>
} @else if (!isDisplayableGraph()) {
<div class="warning-container">
<mat-icon>warning</mat-icon>
<p>Das Netzwerk ist zu groß für eine detaillierte Darstellung.</p>
</div>
} @else {
<div
class="graph"
echarts
[options]="options()"
[autoResize]="true"
(chartClick)="onChartEvent($event, 'chartClick')"></div>
}
@@ -0,0 +1,37 @@
:host {
display: flex;
width: 100%;
}
mat-card {
display: flex;
flex-direction: column;
width: 100%;
background-color: var(--sg-background);
}
mat-card > mat-card-content {
flex: 1 1 auto;
min-height: 0;
align-items: center;
padding: 0px;
}
.graph {
width: 100%;
height: 100%;
min-height: 60vh;
overscroll-behavior: contain;
touch-action: none;
user-select: none;
cursor: grab;
}
.warning-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
padding: 24px;
}
@@ -0,0 +1,200 @@
import { Component, computed, input, output } from '@angular/core';
import { CollaborationGraph } from '../../api';
import { EChartsCoreOption } from 'echarts';
import { MatIconModule } from '@angular/material/icon';
import { NgxEchartsDirective } from 'ngx-echarts';
import * as echarts from 'echarts/core';
import {
GridComponent,
LegendComponent,
TitleComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { GraphChart } from 'echarts/charts';
echarts.use([
GridComponent,
CanvasRenderer,
GraphChart,
TitleComponent,
LegendComponent,
]);
export type NodeCategory = 'author' | 'collaborator' | 'work' | 'institution';
export interface NodeClickEvent {
id: string;
name: string;
category: NodeCategory;
}
@Component({
selector: 'app-collaboration-graph',
imports: [MatIconModule, NgxEchartsDirective],
templateUrl: './collaboration-graph.component.html',
styleUrl: './collaboration-graph.component.scss',
})
export class CollaborationGraphComponent {
collaborationGraph = input.required<CollaborationGraph>();
handleNodeClick = output<NodeClickEvent>();
readonly isEmptyGraph = computed(() => {
const graph = this.collaborationGraph();
return (
graph === undefined ||
(graph.authors?.length ?? 0) === 0 ||
(graph.edges?.length ?? 0) === 0
);
});
readonly isDisplayableGraph = computed(() => {
const graph = this.collaborationGraph();
return (
graph !== undefined &&
(graph.authors?.length ?? 0) > 0 &&
(graph.authors?.length ?? 0) < 1000 &&
(graph.edges?.length ?? 0) > 0
);
});
categoryLabels: Record<string, string> = {
author: 'Autor',
collaborator: 'Kollaborierender',
institution: 'Institution',
work: 'Publikation',
};
options = computed<EChartsCoreOption>(() => {
const graph = this.collaborationGraph();
if (!graph) {
return {};
}
const frequencies = this.occurenceFrequencies();
const minFrequency = Math.min(...Object.values(frequencies));
const maxFrequency = Math.max(...Object.values(frequencies));
const frequencyDenominator = maxFrequency - minFrequency || 1;
const nodes = [
...(graph.authors ?? []).map((author) => ({
id: author.id,
name: author.display_name,
category:
author.id === graph.root_author_id ? 'author' : 'collaborator',
label: {
show: true,
formatter: '{b}',
},
symbolSize:
25 +
(((frequencies[author.id] ?? 0) - minFrequency) /
frequencyDenominator) *
30,
})),
...(graph.institutions ?? []).map((institution) => ({
id: institution.id,
name: institution.display_name,
category: 'institution' as NodeCategory,
label: {
show: true,
formatter: '{b}',
},
symbolSize:
25 +
(((frequencies[institution.id] ?? 0) - minFrequency) /
frequencyDenominator) *
30,
})),
...(graph.works ?? []).map((work) => ({
id: work.id,
name: work.display_name,
category: 'work' as NodeCategory,
label: {
show: false,
},
emphasis: {
label: {
show: true,
formatter: '{b}',
},
},
symbolSize: 15,
})),
];
const links = (graph.edges ?? []).map((edge) => ({
source: edge.source,
target: edge.target,
}));
const categories = [
{ name: 'author' },
{ name: 'collaborator' },
{ name: 'institution' },
{ name: 'work' },
];
return {
legend: {
data: categories.map((category) => category.name),
bottom: 0,
orient: 'horizontal',
formatter: (name: string) => this.categoryLabels[name] || name,
itemGap: 20,
},
series: {
type: 'graph',
layout: 'force',
symbolSize: 15,
animation: false,
data: nodes,
links: links,
categories: categories,
roam: true,
roamTrigger: 'global', // + 2 hours because of incomplete documentation https://github.com/apache/echarts/issues/17214
zoom: 0.1,
force: {
repulsion: 10000,
friction: 0.9,
gravity: 0.2,
},
emphasis: {
focus: 'adjacency',
lineStyle: {
width: 5,
},
},
},
};
});
occurenceFrequencies = computed(() => {
const graph = this.collaborationGraph();
if (!graph) {
return {};
}
const frequencies: Record<string, number> = {};
graph.edges?.forEach((edge) => {
frequencies[edge.source] = (frequencies[edge.source] ?? 0) + 1;
frequencies[edge.target] = (frequencies[edge.target] ?? 0) + 1;
});
return frequencies;
});
onChartEvent(event: any, type: string) {
if (type !== 'chartClick') {
return;
}
const id = event?.data?.id;
const name = event?.data?.name;
const category = event?.data?.category;
if (!id || !name || !category) {
return;
}
this.handleNodeClick.emit({ id, name, category });
}
}
@@ -1,104 +1,50 @@
<h2 mat-dialog-title>Netzwerkfilter</h2>
<mat-dialog-content>
<mat-tab-group
(selectedTabChange)="onTabChange($event)"
[selectedIndex]="selectedTabIndex()">
<mat-tab label="Publikationen">
<form [formGroup]="worksFilterForm">
<div class="pair-field">
<mat-form-field>
<mat-label>Startjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="startYear" />
</mat-form-field>
<mat-form-field>
<mat-label>Endjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="endYear" />
</mat-form-field>
</div>
<mat-form-field>
<mat-label>Minimale Anzahl von Kollaborierenden (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="minContributors" />
</mat-form-field>
<mat-form-field>
<mat-label>Maximale Anzahl von Kollaborierenden (exklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="maxContributors" />
</mat-form-field>
<mat-form-field>
<mat-label>Themen</mat-label>
<mat-select
formControlName="topics"
multiple
appearance="outline"
placeholder="Alle Themen">
@for (
topic of collaborationNetwork.filter_information.topics;
track topic.raw_topic_id
) {
<mat-option [value]="topic.raw_topic_id">
{{ topic.display_name }}
</mat-option>
}
</mat-select>
</mat-form-field>
</form>
</mat-tab>
<mat-tab label="Kollaborierende">
<form [formGroup]="authorsFilterForm">
<mat-form-field>
<mat-label>Minimale Anzahl von Kollaborationen (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="minCollaborations" />
</mat-form-field>
<mat-form-field>
<mat-label>Maximale Anzahl von Kollaborationen (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
formControlName="maxCollaborations" />
</mat-form-field>
<mat-form-field>
<mat-label>Institutionen</mat-label>
<mat-select
formControlName="institutions"
multiple
appearance="outline"
placeholder="Alle Institutionen">
@for (
institution of collaborationNetwork.filter_information
.institutions;
track institution.raw_id
) {
<mat-option [value]="institution.raw_id">
{{ institution.display_name }}
</mat-option>
}
</mat-select>
</mat-form-field>
</form>
</mat-tab>
</mat-tab-group>
<form>
<div class="pair-field">
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Startjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.startYear" />
</mat-form-field>
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Endjahr (inklusive)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.endYear" />
</mat-form-field>
</div>
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Minimale Anzahl von Kollaborierenden (inklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.minContributors" />
</mat-form-field>
<mat-form-field [subscriptSizing]="'dynamic'">
<mat-label>Maximale Anzahl von Kollaborierenden (exklusiv)</mat-label>
<input
matInput
type="number"
appearance="outline"
[formField]="filterForm.maxContributors" />
</mat-form-field>
<app-searchable-topic-select
[selectedTopics]="this.data.selectedTopics"
(handleTopicSelectChange)="handleSelectedTopicsChange($event)" />
<app-searchable-institution-select
[selectedInstitutions]="this.data.selectedInstitutions"
(handleInstitutionSelectChange)="
handleSelectedInstitutionsChange($event)
" />
</form>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="onCancel()">Abbrechen</button>
@@ -1,9 +1,10 @@
form {
padding-top: 20px;
padding: 0.5rem;
display: flex;
flex-direction: column;
min-width: 500px;
min-height: 350px;
gap: 1rem;
}
.form-field-full {
@@ -1,35 +1,36 @@
import { Component, inject, OnInit, signal } from '@angular/core';
import {
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { CollaborationNetwork } from '../../api';
import { Institution, Topic } from '../../api';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatTabsModule } from '@angular/material/tabs';
import { SearchableTopicSelectComponent } from '../../shared/ui/searchable-topic-select/searchable-topic-select.component';
import { SearchableInstitutionSelectComponent } from '../../shared/ui/searchable-institution-select/searchable-institution-select.component';
import { form, FormField } from '@angular/forms/signals';
export interface PersonNetworkFilterDialogData {
collaborationNetwork: CollaborationNetwork;
filterBy: 'works' | 'authors';
selectedInstitutions: Institution[];
selectedTopics: Topic[];
startYear: number;
endYear: number;
topics: string[];
minContributors: number;
maxContributors: number;
}
minCollaborations: number;
maxCollaborations: number;
institutions: string[];
interface FilterData {
startYear: number;
endYear: number;
minContributors: number;
maxContributors: number;
topics: Topic[];
institutions: Institution[];
}
@Component({
@@ -43,6 +44,9 @@ export interface PersonNetworkFilterDialogData {
MatInputModule,
MatButtonModule,
MatTabsModule,
SearchableTopicSelectComponent,
SearchableInstitutionSelectComponent,
FormField,
],
templateUrl: './person-network-filter-dialog.component.html',
styleUrl: './person-network-filter-dialog.component.scss',
@@ -51,45 +55,25 @@ export class PersonNetworkFilterDialogComponent implements OnInit {
readonly dialogRef = inject(MatDialogRef<PersonNetworkFilterDialogComponent>);
readonly data = inject<PersonNetworkFilterDialogData>(MAT_DIALOG_DATA);
readonly collaborationNetwork = this.data.collaborationNetwork;
worksFilterForm = new FormGroup({
startYear: new FormControl(this.data.startYear),
endYear: new FormControl(this.data.endYear),
topics: new FormControl<string[]>(this.data.topics),
minContributors: new FormControl(this.data.minContributors),
maxContributors: new FormControl(this.data.maxContributors),
filterModel = signal<FilterData>({
startYear: this.data.startYear,
endYear: this.data.endYear,
minContributors: this.data.minContributors,
maxContributors: this.data.maxContributors,
topics: this.data.selectedTopics,
institutions: this.data.selectedInstitutions,
});
authorsFilterForm = new FormGroup({
minCollaborations: new FormControl(this.data.minCollaborations),
maxCollaborations: new FormControl(this.data.maxCollaborations),
institutions: new FormControl<string[]>(this.data.institutions),
});
filterForm = form(this.filterModel);
selectedTabIndex = signal(0);
ngOnInit() {
console.log('Received data:', this.data);
if (this.data.filterBy === 'works') {
this.selectedTabIndex.set(0);
} else if (this.data.filterBy === 'authors') {
this.selectedTabIndex.set(1);
}
this.authorsFilterForm.patchValue({
minCollaborations: this.data.minCollaborations,
maxCollaborations: this.data.maxCollaborations,
institutions: this.data.institutions,
});
this.worksFilterForm.patchValue({
ngOnInit(): void {
this.filterModel.set({
startYear: this.data.startYear,
endYear: this.data.endYear,
topics: this.data.topics,
minContributors: this.data.minContributors,
maxContributors: this.data.maxContributors,
topics: this.data.selectedTopics,
institutions: this.data.selectedInstitutions,
});
}
@@ -98,24 +82,41 @@ export class PersonNetworkFilterDialogComponent implements OnInit {
}
onApply() {
const filterData = {
filterBy: this.filterBy(),
worksFilterProperties: this.worksFilterForm.value,
authorsFilterProperties: this.authorsFilterForm.value,
};
this.dialogRef.close(filterData);
this.dialogRef.close({
startYear: this.filterForm.startYear().value(),
endYear: this.filterForm.endYear().value(),
minContributors: this.filterForm.minContributors().value(),
maxContributors: this.filterForm.maxContributors().value(),
topics: this.filterForm.topics().value(),
institutions: this.filterForm.institutions().value(),
});
}
filterBy() {
return this.selectedTabIndex() === 0 ? 'works' : 'authors';
handleSelectedTopicsChange(selectedTopic: Topic) {
const value = this.filterForm.topics().value();
if (value.some((topic) => topic.id === selectedTopic.id)) {
this.filterForm
.topics()
.value.set(value.filter((topic) => topic.id !== selectedTopic.id));
} else {
this.filterForm.topics().value.set([...value, selectedTopic]);
}
}
onTabChange(event: any) {
this.selectedTabIndex.set(event.index);
if (event.index === 0) {
console.log('Switched to Works tab');
} else if (event.index === 1) {
console.log('Switched to Authors tab');
handleSelectedInstitutionsChange(selectedInstitution: Institution) {
const value = this.filterForm.institutions().value();
if (
value.some((institution) => institution.id === selectedInstitution.id)
) {
this.filterForm
.institutions()
.value.set(
value.filter(
(institution) => institution.id !== selectedInstitution.id,
),
);
} else {
this.filterForm.institutions().value.set([...value, selectedInstitution]);
}
}
}
@@ -5,69 +5,69 @@
</div>
<div class="cards">
<app-person-network-graph
[collaborationNetwork]="collaborationNetwork()"
(handleNodeClick)="handleNodeClick($event)"
style="width: 50%" />
<mat-card appearance="outlined" style="width: 50%">
<mat-card-content>
<app-collaboration-graph
[collaborationGraph]="collaborationGraph()"
(handleNodeClick)="handleNodeClick($event)" />
</mat-card-content>
</mat-card>
<div class="right-card">
<form [formGroup]="filterForm">
<div>
<mat-button-toggle-group
class="toggle-group"
aria-label="Select view"
(change)="onToggleChange($event)"
formControlName="displayedTable"
style="margin-top: 20px; width: 100%">
<mat-button-toggle value="collaborators">
Kollaborierende
</mat-button-toggle>
<mat-button-toggle value="publications"
>Publikationen</mat-button-toggle
>
<mat-button-toggle value="institutions">
Institutionen
</mat-button-toggle>
</mat-button-toggle-group>
<button mat-stroked-button type="button" (click)="openFilterDialog()">
<mat-icon>filter_alt</mat-icon>
Filter
</button>
</div>
<mat-form-field style="width: 100%">
<mat-label>{{ this.searchTermLabel() }}</mat-label>
<input
matInput
#input
appearance="outline"
formControlName="searchTerm" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearch()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
</form>
<div class="toggle-group">
<mat-button-toggle-group
class="mat-button-toggle-group"
aria-label="Select view"
(change)="onToggleChange($event)"
[formField]="filterForm2.displayedTable"
style="width: 100%">
<mat-button-toggle value="collaborators">
Kollaborierende
</mat-button-toggle>
<mat-button-toggle value="publications"
>Publikationen</mat-button-toggle
>
<mat-button-toggle value="institutions">
Institutionen
</mat-button-toggle>
</mat-button-toggle-group>
<button
class="filter-button"
mat-stroked-button
type="button"
(click)="openFilterDialog()">
<mat-icon>filter_alt</mat-icon>
Filter
</button>
</div>
<app-query-param-input
style="width: 100%"
queryParamKey="search_term"
[label]="this.searchTermLabel()" />
<app-selected-filters [observers]="observers" [enabledRemoval]="false" />
<mat-card appearance="outlined">
<mat-card-content class="scroll-viewport-container">
@if (this.displayedTable() === 'collaborators') {
<app-data-table
[columns]="collaboratorsColumns"
[data]="collaboratorsData"
[data]="collaboratorsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="collaboratorsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'publications') {
<app-data-table
[columns]="publicationsColumns"
[data]="publicationsData"
[data]="publicationsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="publicationsDetailRow"
[maxHeight]="'100%'" />
} @else if (this.displayedTable() === 'institutions') {
<app-data-table
[columns]="institutionsColumns"
[data]="institutionsData"
[data]="institutionsData()"
[filterTerm]="searchTerm()"
[detailTemplate]="institutionsDetailRow"
[maxHeight]="'100%'" />
@@ -88,7 +88,10 @@
</div>
<ng-template #collaboratorsActionTmp let-element>
<a mat-icon-button color="primary" [routerLink]="['/person', element.id]">
<a
mat-icon-button
color="primary"
[routerLink]="['/person', this.stripOpenAlexIdPrefix(element.id)]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@@ -99,15 +102,36 @@
<ng-template #collaboratorsDetailRow let-element>
<div class="detail-row">
<ul>
@for (work of element.works; track $index) {
<li>
<a class="work-link" [routerLink]="['/publication', work.id]">
{{ work.title }}
@if (element.works.length > 0) {
<span style="font-weight: bold">Publikationen:</span>
<ul>
@for (work of element.works; track $index) {
<a
class="link"
[routerLink]="[
'/publication',
this.stripOpenAlexIdPrefix(work.id),
]">
<li>{{ work.display_name }}</li>
</a>
</li>
}
</ul>
}
</ul>
}
@if (element.institutions.length > 0) {
<span style="font-weight: bold">Institutionen:</span>
<ul>
@for (institution of element.institutions; track $index) {
<a
class="link"
[routerLink]="[
'/institution',
this.stripOpenAlexIdPrefix(institution.id),
]">
<li>{{ institution.display_name }}</li>
</a>
}
</ul>
}
</div>
</ng-template>
@@ -115,26 +139,34 @@
<a
mat-icon-button
color="primary"
[routerLink]="['/publication', element.id]">
[routerLink]="['/publication', this.stripOpenAlexIdPrefix(element.id)]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
<ng-template #publicationsCollaborationFrequencyTmp let-element>
{{ element.collaborators.length }}
{{ element.authors.length }}
</ng-template>
<ng-template #publicationsDetailRow let-element>
<div class="detail-row">
<ul>
@for (collaborator of element.collaborators; track $index) {
<li>
<a class="person-link" [routerLink]="['/person', collaborator.id]">
{{ collaborator.name }}
</a>
</li>
}
</ul>
@if (element.authors.length > 0) {
<span style="font-weight: bold">Mitwirkende:</span>
<ul>
@for (collaborator of element.authors; track $index) {
<li>
<a
class="person-link"
[routerLink]="[
'/person',
this.stripOpenAlexIdPrefix(collaborator.id),
]">
{{ collaborator.display_name }}
</a>
</li>
}
</ul>
}
</div>
</ng-template>
@@ -142,25 +174,33 @@
<a
mat-icon-button
color="primary"
[routerLink]="['/institution', element.id]">
[routerLink]="['/institution', this.stripOpenAlexIdPrefix(element.id)]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
<ng-template #institutionsFrequencyTmp let-element>
{{ element.collaborators.length }}
{{ element.authors.length }}
</ng-template>
<ng-template #institutionsDetailRow let-element>
<div class="detail-row">
<ul>
@for (collaborator of element.collaborators; track $index) {
<li>
<a class="person-link" [routerLink]="['/person', collaborator.id]">
{{ collaborator.name }}
</a>
</li>
}
</ul>
@if (element.authors.length > 0) {
<span style="font-weight: bold">Mitwirkende:</span>
<ul>
@for (collaborator of element.authors; track $index) {
<li>
<a
class="link"
[routerLink]="[
'/person',
this.stripOpenAlexIdPrefix(collaborator.id),
]">
{{ collaborator.display_name }}
</a>
</li>
}
</ul>
}
</div></ng-template
>
@@ -1,8 +1,8 @@
.content {
display: flex;
flex-direction: column;
padding: 30px;
gap: 20px;
padding: 2rem;
gap: 1rem;
}
.description-container {
@@ -11,33 +11,40 @@
}
.cards {
width: 100%;
display: flex;
flex-direction: row;
gap: 20px;
gap: 2rem;
max-height: 80vh;
}
form > div {
.right-card {
width: 50%;
display: flex;
flex-direction: row;
gap: 20px;
flex-direction: column;
gap: 1rem;
}
form > div > button,
form > div > mat-button-toggle-group {
margin-top: 20px;
margin-bottom: 20px;
.toggle-group {
display: flex;
flex-direction: row;
gap: 1rem;
}
.filter-button {
border-radius: var(--sg-radius-sm);
color: var(--sg-text);
}
.content > app-person-network-graph,
.right-card {
flex: 1 1 0;
.mat-button-toggle-group {
width: 100%;
height: 100%;
border-radius: var(--sg-radius-sm);
color: var(--sg-text);
text-transform: none;
}
.toggle-group .mat-button-toggle {
text-transform: none;
width: 100%;
}
@@ -60,12 +67,10 @@ mat-card {
background-color: var(--sg-background);
}
.person-link,
.work-link {
.link {
color: var(--sg-primary);
text-decoration: none;
}
.person-link:hover,
.work-link:hover {
.link:hover {
text-decoration: underline;
}
@@ -14,69 +14,68 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { provideEchartsCore } from 'ngx-echarts';
import * as echarts from 'echarts/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import {
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { CollaborationNetwork } from '../../api';
import { debounceTime } from 'rxjs';
import {
NodeCategory,
NodeClickEvent,
PersonNetworkGraphComponent,
} from '../person-network-graph/person-network-graph.component';
AuthorNode,
CollaborationGraph,
Institution,
InstitutionNode,
InstitutionPageV2,
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 } from '../person-network-filter-dialog/person-network-filter-dialog.component';
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';
type CWork = {
id: string;
title: string;
type DetailedWorkNode = WorkNode & {
authors: AuthorNode[];
};
type CCollaborator = {
id: string;
name: string;
category: string;
works: CWork[];
type DetailedAuthorNode = AuthorNode & {
works: WorkNode[];
institutions: InstitutionNode[];
};
type PCollaborator = {
id: string;
name: string;
category: string;
type DetailedInstitutionNode = InstitutionNode & {
authors: AuthorNode[];
};
type PWork = {
id: string;
title: string;
collaborators: PCollaborator[];
};
type ICollaborator = {
id: string;
name: string;
};
type IInstitution = {
id: string;
name: string;
collaborators: ICollaborator[];
};
interface FilterData {
displayedTable: string;
startYear: number;
endYear: number;
minContributors: number;
maxContributors: number;
topics: Topic[];
institutions: Institution[];
}
@Component({
selector: 'app-person-network',
@@ -91,22 +90,120 @@ type IInstitution = {
RouterModule,
ReactiveFormsModule,
FormsModule,
PersonNetworkGraphComponent,
MatSelectModule,
MatExpansionModule,
MatDialogModule,
AppInfoCardComponent,
DataTableComponent,
CollaborationGraphComponent,
FormField,
SelectedFiltersComponent,
QueryParamInputComponent,
],
templateUrl: './person-network.component.html',
styleUrl: './person-network.component.scss',
providers: [provideEchartsCore({ echarts })],
providers: [],
})
export class PersonNetworkComponent implements OnInit {
collaborationNetwork = input.required<CollaborationNetwork>();
collaborationGraph = input.required<CollaborationGraph>();
selectedTopics = input.required<TopicPageV2>();
selectedInstitutions = input.required<InstitutionPageV2>();
collaboratorsColumns: GenericColumn<CCollaborator>[] = [];
collaboratorsData: CCollaborator[] = [];
filterModel = signal<FilterData>({
displayedTable: 'collaborators',
startYear: 2020,
endYear: new Date().getFullYear(),
minContributors: 2,
maxContributors: 10,
topics: [],
institutions: [],
});
displayedTable = computed(() => this.filterForm2.displayedTable().value());
filterForm2 = form(this.filterModel);
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;
},
},
{
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;
},
},
];
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',
);
@@ -117,8 +214,18 @@ export class PersonNetworkComponent implements OnInit {
'collaboratorsDetailRow',
);
publicationsColumns: GenericColumn<PWork>[] = [];
publicationsData: PWork[] = [];
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',
);
@@ -129,8 +236,19 @@ export class PersonNetworkComponent implements OnInit {
'publicationsDetailRow',
);
institutionsColumns: GenericColumn<IInstitution>[] = [];
institutionsData: IInstitution[] = [];
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',
);
@@ -141,30 +259,15 @@ export class PersonNetworkComponent implements OnInit {
'institutionsDetailRow',
);
filterForm = new FormGroup({
searchTerm: new FormControl(''),
filterBy: new FormControl<'works' | 'authors'>('works'),
displayedTable: new FormControl('collaborators'),
startYear: new FormControl(2000),
endYear: new FormControl(2025),
topics: new FormControl([]),
minContributors: new FormControl(2),
maxContributors: new FormControl(10),
minCollaborations: new FormControl(1),
maxCollaborations: new FormControl(100),
institutions: new FormControl([]),
});
persons = signal(0);
institutions = signal(0);
publications = signal(0);
connections = signal(0);
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();
const displayedTable = this.filterForm2.displayedTable().value();
switch (displayedTable) {
case 'collaborators':
return 'Suche Kollaborierende nach Name';
@@ -197,15 +300,25 @@ export class PersonNetworkComponent implements OnInit {
return;
}
this.filterForm.patchValue({
displayedTable: this.categoryTableMap[category],
searchTerm: name,
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
search_term: name,
table: this.categoryTableMap[category] || 'collaborators',
},
queryParamsHandling: 'merge',
});
};
clearSearch() {
this.latestNodeId.set(null);
this.filterForm.patchValue({ searchTerm: '' });
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
search_term: null,
},
queryParamsHandling: 'merge',
});
}
readonly summaryCards = computed(() => [
@@ -231,20 +344,11 @@ export class PersonNetworkComponent implements OnInit {
},
]);
readonly formValue = toSignal(this.filterForm.valueChanges);
readonly debouncedFormValue = toSignal(
this.filterForm.valueChanges.pipe(debounceTime(300)),
);
displayedTable = computed(() => {
return this.formValue()?.displayedTable;
queryParamMap = toSignal(this.activatedRoute.queryParamMap, {
initialValue: this.activatedRoute.snapshot.queryParamMap,
});
readonly searchTerm = computed(() => {
return this.debouncedFormValue()?.searchTerm || '';
});
readonly activatedRouteData = toSignal(this.activatedRoute.data);
searchTerm = computed(() => this.queryParamMap().get('search_term') || '');
constructor(
private readonly activatedRoute: ActivatedRoute,
@@ -252,105 +356,89 @@ export class PersonNetworkComponent implements OnInit {
private readonly dialog: MatDialog,
) {
effect(() => {
this.collaboratorsData = this.buildCollaboratorsDataSource(
this.collaborationNetwork(),
);
this.publicationsData = this.buildWorksDataSource(
this.collaborationNetwork(),
);
this.institutionsData = this.buildInstitutionsDataSource(
this.collaborationNetwork(),
);
this.calculateSummary(this.collaborationNetwork());
const currentParams = this.activatedRoute.snapshot.queryParams;
this.filterForm.setValue({
searchTerm: currentParams['search_term'] || '',
filterBy: currentParams['filter_by'] || 'works',
displayedTable: currentParams['table'] || 'collaborators',
startYear:
Number(currentParams['start_year']) ||
this.collaborationNetwork().filter_information.min_possible_year,
endYear:
Number(currentParams['end_year']) ||
this.collaborationNetwork().filter_information.max_possible_year,
topics: currentParams['topics']
? currentParams['topics'].split(',')
: [],
minContributors: Number(currentParams['min_contributors']) || 2,
maxContributors: Number(currentParams['max_contributors']) || 10,
minCollaborations: Number(currentParams['min_collaborations']) || 1,
maxCollaborations: Number(currentParams['max_collaborations']) || 100,
institutions: currentParams['institutions']
? currentParams['institutions'].split(',')
: [],
const filters = this.filterModel();
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
table: filters.displayedTable || null,
[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).join(',')
: null,
[collaborationGraphQueryParamKeys.institutionId]:
filters.institutions.length > 0
? filters.institutions.map((inst) => inst.id).join(',')
: null,
},
queryParamsHandling: 'merge',
});
});
}
openFilterDialog() {
console.log('Form value when opening dialog:', this.filterForm.value);
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: {
collaborationNetwork: this.collaborationNetwork(),
filterBy: this.filterForm.get('filterBy')?.value || 'works',
startYear: this.filterForm.get('startYear')?.value,
endYear: this.filterForm.get('endYear')?.value,
topics: this.filterForm.get('topics')?.value,
minContributors: this.filterForm.get('minContributors')!.value,
maxContributors: this.filterForm.get('maxContributors')?.value,
minCollaborations: this.filterForm.get('minCollaborations')?.value,
maxCollaborations: this.filterForm.get('maxCollaborations')?.value,
institutions: this.filterForm.get('institutions')?.value,
},
data: data,
});
dialogRef.afterClosed().subscribe((result) => {
console.log('Dialog closed with result:', result);
console.log(result.filterBy);
console.log(result.worksFilterProperties);
console.log(result.authorsFilterProperties);
if (result) {
this.filterForm.patchValue({
filterBy: result.filterBy,
startYear: result.worksFilterProperties.startYear,
endYear: result.worksFilterProperties.endYear,
topics: result.worksFilterProperties.topics,
minContributors: result.worksFilterProperties.minContributors,
maxContributors: result.worksFilterProperties.maxContributors,
minCollaborations: result.authorsFilterProperties.minCollaborations,
maxCollaborations: result.authorsFilterProperties.maxCollaborations,
institutions: result.authorsFilterProperties.institutions,
this.filterModel.set({
displayedTable: this.filterForm2.displayedTable().value(),
startYear: result.startYear,
endYear: result.endYear,
minContributors: result.minContributors,
maxContributors: result.maxContributors,
topics: result.topics,
institutions: result.institutions,
});
}
});
}
calculateSummary(collaborationNetwork: CollaborationNetwork) {
this.persons.set(collaborationNetwork.author_nodes.length);
this.institutions.set(collaborationNetwork.institution_nodes.length);
this.publications.set(collaborationNetwork.work_nodes.length);
this.connections.set(collaborationNetwork.collaboration_edges.length);
}
ngOnInit(): void {
const queryParamMap = this.queryParamMap();
this.filterModel.set({
displayedTable: queryParamMap.get('table') || 'collaborators',
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: 'name',
accessorKey: 'display_name',
},
{
id: 'works',
@@ -370,7 +458,7 @@ export class PersonNetworkComponent implements OnInit {
id: 'title',
header: 'Titel',
type: 'accessor',
accessorKey: 'title',
accessorKey: 'display_name',
},
{
id: 'collaborators',
@@ -390,7 +478,7 @@ export class PersonNetworkComponent implements OnInit {
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'name',
accessorKey: 'display_name',
},
{
id: 'collaborators',
@@ -405,38 +493,6 @@ export class PersonNetworkComponent implements OnInit {
cellTemplate: this.institutionsActionTmp(),
},
];
this.filterForm.valueChanges.pipe(debounceTime(300)).subscribe((value) => {
const queryParams = {
table: value.displayedTable ?? 'collaborators',
search_term: value.searchTerm ?? '',
filter_by: value.filterBy ?? 'works',
start_year: value.startYear ?? '',
end_year: value.endYear ?? '',
min_contributors: value.minContributors ?? 2,
max_contributors: value.maxContributors ?? 10,
min_collaborations: value.minCollaborations ?? 1,
max_collaborations: value.maxCollaborations ?? 100,
institutions: value.institutions?.join(',') ?? '',
topics: value.topics?.join(',') ?? '',
};
const currentQueryParams = this.activatedRoute.snapshot.queryParams;
const hasChanged = Object.entries(queryParams).some(([key, value]) => {
return String(currentQueryParams[key] ?? '') !== String(value ?? '');
});
if (!hasChanged) {
return;
}
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams,
replaceUrl: true,
});
});
}
onToggleChange(event: any) {
@@ -444,153 +500,13 @@ export class PersonNetworkComponent implements OnInit {
if (!value) {
return;
}
this.filterForm.get('displayedTable')?.setValue(value);
this.filterForm2.displayedTable().value.set(value);
}
buildCollaboratorsDataSource(
collaborationNetwork: CollaborationNetwork,
): CCollaborator[] {
// key: collaborator id, value: set of work ids
const worksByCollaborator: Record<string, Set<string>> = {};
// key: work id, value: work
const works: Record<string, CWork> = {};
const allWorks: Record<string, CWork> = collaborationNetwork.work_nodes
.map((node) => ({
id: node.raw_id,
title: node.display_name,
}))
.reduce(
(acc, work) => {
acc[work.id] = work;
return acc;
},
{} as Record<string, CWork>,
);
const allAuthors: Record<string, CCollaborator> =
collaborationNetwork.author_nodes
.map((node) => ({
id: node.raw_id,
name: node.display_name,
category: node.category,
works: [],
}))
.reduce(
(acc, author) => {
acc[author.id] = author;
return acc;
},
{} as Record<string, CCollaborator>,
);
collaborationNetwork.collaboration_edges.forEach((edge) => {
if (
edge.raw_source_id.toUpperCase().startsWith('A') &&
edge.raw_target_id.toUpperCase().startsWith('W')
) {
allAuthors[edge.raw_source_id]?.works.push(
allWorks[edge.raw_target_id],
);
}
});
Object.values(allAuthors).forEach((author) => {
author.works.sort((a, b) => a.title.localeCompare(b.title));
});
return Object.values(allAuthors).filter(
(author) =>
author.works.length > 0 &&
author.id !== collaborationNetwork.raw_person_id,
);
}
buildWorksDataSource(collaborationNetwork: CollaborationNetwork): PWork[] {
const allWorks: Record<string, PWork> = collaborationNetwork.work_nodes
.map((node) => ({
id: node.raw_id,
title: node.display_name,
collaborators: [],
}))
.reduce(
(acc, work) => {
acc[work.id] = work;
return acc;
},
{} as Record<string, PWork>,
);
const allAuthors: Record<string, PCollaborator> =
collaborationNetwork.author_nodes
.map((node) => ({
id: node.raw_id,
name: node.display_name,
category:
node.raw_id === collaborationNetwork.raw_person_id
? 'author'
: 'collaborator',
}))
.reduce(
(acc, person) => {
acc[person.id] = person;
return acc;
},
{} as Record<string, PCollaborator>,
);
collaborationNetwork.collaboration_edges.forEach((edge) => {
if (
edge.raw_source_id.toUpperCase().startsWith('A') &&
edge.raw_target_id.toUpperCase().startsWith('W')
) {
allWorks[edge.raw_target_id]?.collaborators.push(
allAuthors[edge.raw_source_id],
);
}
});
Object.values(allWorks).forEach((work) => {
work.collaborators.sort((a, b) => a.name.localeCompare(b.name));
});
return Object.values(allWorks).filter(
(work) => work.collaborators.length > 0,
);
}
buildInstitutionsDataSource(
collaborationNetwork: CollaborationNetwork,
): IInstitution[] {
const institutionsMap: Record<string, IInstitution> = {};
for (const node of collaborationNetwork.institution_nodes) {
institutionsMap[node.raw_id] = {
id: node.raw_id,
name: node.display_name,
collaborators: [],
};
stripOpenAlexIdPrefix(id: string): string {
if (id.startsWith('https://openalex.org/')) {
return id.substring(21);
}
for (const edge of collaborationNetwork.collaboration_edges) {
if (edge.raw_target_id in institutionsMap) {
const institution = institutionsMap[edge.raw_target_id];
institution.collaborators.push({
id: edge.raw_source_id,
name:
collaborationNetwork.author_nodes.find(
(node) => node.raw_id === edge.raw_source_id,
)?.display_name || 'Unbekannt',
});
}
}
for (const institution of Object.values(institutionsMap)) {
institution.collaborators.sort((a, b) =>
a.name.localeCompare(b.name, 'de', { sensitivity: 'base' }),
);
}
return Object.values(institutionsMap);
return id;
}
}
@@ -26,6 +26,7 @@ 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 { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
@Component({
selector: 'app-person',
@@ -278,7 +279,17 @@ export class PersonComponent {
disabled: false,
},
{ label: 'Publikationen', path: 'publications', disabled: false },
{ label: 'Netzwerk', path: 'network', disabled: false },
{
label: 'Netzwerk',
path: 'network',
disabled: false,
queryParams: {
[collaborationGraphQueryParamKeys.minCollaborators]: '2',
[collaborationGraphQueryParamKeys.maxCollaborators]: '10',
[collaborationGraphQueryParamKeys.yearFrom]: '1900',
[collaborationGraphQueryParamKeys.yearTo]: new Date().getFullYear(),
},
},
...(this.companyConnectionsAvailable()
? [
{
@@ -0,0 +1,58 @@
import { ResolveFn } from '@angular/router';
import { AuthorsV2Service, CollaborationGraph } from '../api';
import { inject } from '@angular/core';
export const collaborationGraphQueryParamKeys = {
yearFrom: 'year_from',
yearTo: 'year_to',
minCollaborators: 'min_collaborators',
maxCollaborators: 'max_collaborators',
topicId: 'topicId',
institutionId: 'institutionId',
} as const;
export const collaborationGraphResolver: ResolveFn<CollaborationGraph> = (
route,
state,
) => {
const id = route.parent?.paramMap.get('id');
if (!id) {
throw new Error('No author ID provided in route parameters');
}
const yearFrom =
Number(
route.queryParamMap.get(collaborationGraphQueryParamKeys.yearFrom),
) || 2020;
const yearTo =
Number(route.queryParamMap.get(collaborationGraphQueryParamKeys.yearTo)) ||
new Date().getFullYear();
const minCollaborators =
Number(
route.queryParamMap.get(
collaborationGraphQueryParamKeys.minCollaborators,
),
) || 2;
const maxCollaborators =
Number(
route.queryParamMap.get(
collaborationGraphQueryParamKeys.maxCollaborators,
),
) || 10;
const topicIds = route.queryParamMap.getAll(
collaborationGraphQueryParamKeys.topicId,
);
const institutionIds = route.queryParamMap.getAll(
collaborationGraphQueryParamKeys.institutionId,
);
return inject(AuthorsV2Service).getCollaborationGraph(
id,
yearFrom,
yearTo,
minCollaborators,
maxCollaborators,
topicIds.length > 0 ? topicIds : undefined,
institutionIds.length > 0 ? institutionIds : undefined,
);
};
@@ -3,13 +3,7 @@ import {
ResolveFn,
RouterStateSnapshot,
} from '@angular/router';
import {
WorkPageV2,
SortDirection,
WorkSortBy,
WorksV2Service,
WorksService,
} from '../api';
import { WorkPageV2, SortDirection, WorkSortBy, WorksV2Service } from '../api';
import { inject } from '@angular/core';
const RESOLVING_WORK_PAGE_FOR_KEY = 'resolvingFor';
@@ -60,7 +60,7 @@ export class AppSearchbarComponent {
// Autocomplete suggestions
this.searchControl.valueChanges
.pipe(
debounceTime(100),
debounceTime(300),
distinctUntilChanged(),
switchMap((v) => {
const value = v ?? '';
@@ -1,7 +1,7 @@
<app-searchable-select
inputPlaceholder="Institution suchen..."
icon="apartment"
[label]="label()"
[label]="_label()"
selectedLabel="Ausgewählte Institutionen"
fetchedLabel="Gefundene Institutionen"
[fetchElements]="fetchInstitutions"
@@ -1,4 +1,4 @@
import { Component, inject, input, output } from '@angular/core';
import { Component, computed, inject, input, output } from '@angular/core';
import { Institution, InstitutionsV2Service, TopicPageV2 } from '../../../api';
import { Observable } from 'rxjs';
import { SearchableSelectComponent } from '../searchable-select/searchable-select.component';
@@ -12,9 +12,26 @@ import { SearchableSelectComponent } from '../searchable-select/searchable-selec
export class SearchableInstitutionSelectComponent {
private readonly institutionsV2Service = inject(InstitutionsV2Service);
label = input<string>('Institutionen');
label = input<string | undefined>(undefined);
selectedInstitutions = input.required<Institution[]>();
_label = computed(() => {
return this.label() ?? this._defaultLabel();
});
_defaultLabel = computed(() => {
const selectedInstitutionIds = this.selectedInstitutions().map((i) => i.id);
if (selectedInstitutionIds.length === 0) return 'Institution';
if (selectedInstitutionIds.length === 1) {
const institution = this.selectedInstitutions()[0];
return institution.display_name || 'Institutionen';
}
return `${selectedInstitutionIds.length} Institutionen`;
});
handleInstitutionSelectChange = output<Institution>();
fetchInstitutions = (searchTerm: string): Observable<TopicPageV2> => {
@@ -1,7 +1,7 @@
<app-searchable-select
inputPlaceholder="Thema suchen..."
icon="label"
[label]="label()"
[label]="_label()"
selectedLabel="Ausgewählte Themen"
fetchedLabel="Gefundene Themen"
[fetchElements]="fetchTopics"
@@ -1,4 +1,4 @@
import { Component, inject, input, output } from '@angular/core';
import { Component, computed, inject, input, output } from '@angular/core';
import { SearchableSelectComponent } from '../searchable-select/searchable-select.component';
import { Topic, TopicPageV2, TopicsV2Service } from '../../../api';
import { Observable } from 'rxjs';
@@ -12,9 +12,26 @@ import { Observable } from 'rxjs';
export class SearchableTopicSelectComponent {
private readonly topicsV2Service = inject(TopicsV2Service);
label = input<string>('Themen');
label = input<string | undefined>(undefined);
selectedTopics = input.required<Topic[]>();
_label = computed(() => {
return this.label() ?? this._defaultLabel();
});
_defaultLabel = computed(() => {
const selectedTopicIds = this.selectedTopics().map((t) => t.id);
if (selectedTopicIds.length === 0) return 'Thema';
if (selectedTopicIds.length === 1) {
const topic = this.selectedTopics()[0];
return topic.display_name || 'Thema';
}
return `${selectedTopicIds.length} Themen`;
});
handleTopicSelectChange = output<Topic>();
fetchTopics = (searchTerm: string): Observable<TopicPageV2> => {
@@ -26,12 +26,14 @@
}}</span>
</div>
}
<button
type="button"
class="remove-chip-btn"
(click)="_handleRemove(observer, value)">
<mat-icon>close</mat-icon>
</button>
@if (enabledRemoval()) {
<button
type="button"
class="remove-chip-btn"
(click)="_handleRemove(observer, value)">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
}
@@ -23,6 +23,8 @@ export interface FilterObserver {
export class SelectedFiltersComponent {
observers = input.required<FilterObserver[]>();
enabledRemoval = input<boolean>(true);
observedQueryParamKeys = computed(() =>
this.observers().map((observer) => observer.queryParamKey),
);