First demo implementation of trend analysis frontend

This commit is contained in:
Kazgatari
2026-07-03 20:04:35 +02:00
parent 3c910fa0e4
commit 15fc57da51
5 changed files with 614 additions and 1 deletions
@@ -1,7 +1,15 @@
// src/app/modules/university-ranking/services/university-data.service.ts
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { InstitutionsService, RankingResponse } from '../../../api';
import {
InstitutionsService,
RankingResponse,
TrendResponse,
TopInstitutionItem,
AutocompleteResponse,
AutocompleteLocationItem,
} from '../../../api';
export type ResearchTopic =
| 'Artificial Intelligence'
| 'Quantum Computing'
@@ -26,4 +34,60 @@ export class UniversityRankingService {
metric,
);
}
//trend analysis part
/**
* Fetches the comparative trend analysis data.
*/
getTrend(
topics: string[],
institutions?: string[],
countries?: string[],
regions?: string[],
): Observable<TrendResponse> {
return this.apiService.getTrendApiInseServiceUniversityRankingsTrendGet(
topics as any,
institutions,
countries,
regions,
);
}
/**
* Fetches recommendations/suggestions of top institutions based on a specific topic.
*/
getTopInstitutions(
topic: string,
region?: string,
country?: string,
limit?: number,
): Observable<TopInstitutionItem[]> {
return this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
topic,
region,
country,
limit,
);
}
/**
* Autocompletes institutions based on query text.
*/
autocomplete(query: string): Observable<AutocompleteResponse> {
return this.apiService.autocompleteInstitutions(
query,
undefined,
'education',
10,
);
}
/**
* Autocompletes countries and continents.
*/
autocompleteLocations(query: string): Observable<AutocompleteLocationItem[]> {
return this.apiService.getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(
query,
);
}
}
@@ -0,0 +1,14 @@
<div class="chart-wrapper">
@if (data() && data()!.series && data()!.series.length > 0) {
<div echarts [options]="chartOptions()" class="trend-chart-render"></div>
} @else {
<div class="no-data-msg">
<div class="icon">📊</div>
<h3>No Trend Data Available</h3>
<p>
Please select at least one topic and choose institutions or regions to
compare in the control panel.
</p>
</div>
}
</div>
@@ -0,0 +1,62 @@
.chart-wrapper {
position: relative;
width: 100%;
height: 100%;
min-height: 450px;
background: rgba(255, 255, 255, 0.6);
backdrop-filter: blur(10px);
border-radius: 12px;
padding: 16px;
box-sizing: border-box;
.trend-chart-render {
width: 100%;
height: 480px;
}
.no-data-msg {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 380px;
text-align: center;
color: #4b5563;
padding: 24px;
border: 2px dashed #e5e7eb;
border-radius: 12px;
background: rgba(249, 250, 251, 0.5);
.icon {
font-size: 48px;
margin-bottom: 16px;
animation: pulse 2s infinite ease-in-out;
}
h3 {
font-size: 18px;
font-weight: 600;
color: #111827;
margin-bottom: 8px;
}
p {
font-size: 14px;
color: #6b7280;
max-width: 320px;
line-height: 1.5;
}
}
}
@keyframes pulse {
0%,
100% {
transform: scale(1);
opacity: 0.8;
}
50% {
transform: scale(1.08);
opacity: 1;
}
}
@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UniTrendChartComponent } from './uni-trend-chart.component';
describe('UniTrendChartComponent', () => {
let component: UniTrendChartComponent;
let fixture: ComponentFixture<UniTrendChartComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UniTrendChartComponent],
}).compileComponents();
fixture = TestBed.createComponent(UniTrendChartComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,451 @@
import {
Component,
ChangeDetectionStrategy,
input,
computed,
} from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { TrendResponse } from '../../../api';
@Component({
selector: 'app-uni-trend-chart',
templateUrl: './uni-trend-chart.component.html',
styleUrl: './uni-trend-chart.component.scss',
imports: [NgxEchartsDirective],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UniTrendChartComponent {
// Input signals following Angular v21 standards
readonly data = input<TrendResponse | null>(null);
readonly mode = input<'normalized' | 'total'>('total');
readonly activeTopic = input<string | null>(null);
readonly startYear = input<number>(2015);
readonly endYear = input<number>(2026);
// Computed signal to automatically rebuild ECharts options when data or mode changes
readonly chartOptions = computed<EChartsOption>(() => {
const trendData = this.data();
if (!trendData || !trendData.series || trendData.series.length === 0) {
return {};
}
const currentMode = this.mode();
const startYr = this.startYear();
const endYr = this.endYear();
const years = trendData.years.filter((y) => y >= startYr && y <= endYr);
const xAxisData = years.map(String);
// Resolve the active topic to compare one at a time to prevent line overlaps
const topics = Object.keys(trendData.series[0].topic_data || {});
const active = this.activeTopic();
const selectedTopic =
active && topics.includes(active)
? active
: topics.length > 0
? topics[0]
: null;
if (!selectedTopic) {
return {};
}
const series: any[] = [];
const entityColors = [
'#ec4899', // Pink
'#3b82f6', // Blue
'#10b981', // Emerald Green
'#f59e0b', // Amber/Yellow
'#8b5cf6', // Purple
'#06b6d4', // Cyan
'#6366f1', // Indigo
];
// Build series: Line in top grid, growth volume bars and S-Curve in bottom grid
trendData.series.forEach((entity, entityIdx) => {
const color = entityColors[entityIdx % entityColors.length];
// 1. Add line series for the currently selected topic (placed in Grid 0)
const yrTopicData = entity.topic_data[selectedTopic];
const lineData = years.map((year) => {
const yrData = yrTopicData?.find((y) => y.year === year);
if (!yrData) return 0;
return currentMode === 'normalized' ? yrData.normalized : yrData.raw;
});
series.push({
name: `${entity.entity_name}`,
type: 'line',
xAxisIndex: 0,
yAxisIndex: 0,
data: lineData,
smooth: true,
lineStyle: {
width: 2.5,
color: color,
},
itemStyle: {
color: color,
},
emphasis: {
lineStyle: { width: 3.5 },
},
});
// 2. Add YoY growth volume bars for the selected topic (placed in Grid 1)
const volumeData = years.map((year) => {
const yrData = yrTopicData?.find((y) => y.year === year);
return yrData ? yrData.raw : 0;
});
const bars = years.map((year, idx) => {
const val = volumeData[idx];
const prevVal = idx > 0 ? volumeData[idx - 1] : val;
const trendSign = val >= prevVal ? 1 : -1;
return [idx, val, trendSign];
});
series.push({
name: `${entity.entity_name} (YoY Growth)`,
type: 'bar',
xAxisIndex: 1,
yAxisIndex: 1,
data: bars,
itemStyle: {
color: (params: any) => {
const trendSign = params.value[2];
return trendSign >= 0 ? '#10b981' : '#ef4444'; // Green vs Red
},
},
});
// 3. Add S-Curve cumulative publications trend overlay (placed in Grid 1)
let cumulativeSum = 0;
const cumulativeData = volumeData.map((val) => {
cumulativeSum += val;
return cumulativeSum;
});
series.push({
name: `${entity.entity_name} (S-Curve)`,
type: 'line',
xAxisIndex: 1,
yAxisIndex: 2,
data: cumulativeData,
smooth: true,
symbol: 'none',
lineStyle: {
width: 2,
color: color,
type: 'dashed',
},
itemStyle: {
color: color,
},
});
});
const yAxisName =
currentMode === 'normalized'
? 'Normalized Scale (0 - 1)'
: 'Publications Volume';
return {
title: {
text: `Publication Trends: ${selectedTopic}`,
left: 'left',
textStyle: {
fontSize: 16,
fontWeight: 600,
color: '#1f2937',
},
},
tooltip: {
trigger: 'axis',
axisPointer: { type: 'cross' },
backgroundColor: 'rgba(255, 255, 255, 0.95)',
borderColor: '#e5e7eb',
borderWidth: 1,
textStyle: {
color: '#374151',
fontSize: 12,
},
formatter: (params: any) => {
if (!params || params.length === 0) return '';
const yearNum = parseInt(params[0].name, 10);
let res = `<div style="padding: 4px 8px; font-family: 'Inter', sans-serif;">`;
res += `<strong style="font-size: 13px; color: #111827;">Year: ${yearNum}</strong><br/>`;
res += `<hr style="border: 0; border-top: 1px solid #e5e7eb; margin: 4px 0 8px 0;"/>`;
trendData.series.forEach((entity, entityIdx) => {
const color = entityColors[entityIdx % entityColors.length];
res += `<div style="margin-bottom: 6px;">`;
res += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${color};"></span>`;
res += `<strong style="color: #374151;">${entity.entity_name}</strong>:<br/>`;
const yrData = entity.topic_data[selectedTopic]?.find(
(y) => y.year === yearNum,
);
if (yrData) {
const val =
currentMode === 'normalized' ? yrData.normalized : yrData.raw;
const displayVal =
currentMode === 'normalized'
? val.toFixed(2)
: val.toLocaleString();
let contributionStr = '';
if (currentMode === 'total') {
if (entity.entity_type === 'institution') {
const instCountryCode = entity.country_code?.toUpperCase();
const parentCountry = trendData.series.find(
(s) =>
s.entity_type === 'country' &&
s.entity_id.toUpperCase() === instCountryCode,
);
const parentContinent = trendData.series.find((s) => {
if (s.entity_type !== 'region') return false;
const memberCountries =
trendData.location_mappings?.[s.entity_id] || [];
return memberCountries.some(
(c) => c.toUpperCase() === instCountryCode,
);
});
if (parentCountry) {
const parentYr = parentCountry.topic_data[
selectedTopic
]?.find((y) => y.year === yearNum);
if (parentYr && parentYr.raw > 0) {
const pct = (yrData.raw / parentYr.raw) * 100;
contributionStr = ` (${pct.toFixed(1)}% of ${parentCountry.entity_name})`;
}
} else if (parentContinent) {
const parentYr = parentContinent.topic_data[
selectedTopic
]?.find((y) => y.year === yearNum);
if (parentYr && parentYr.raw > 0) {
const pct = (yrData.raw / parentYr.raw) * 100;
contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`;
}
} else {
const sumInsts = trendData.series
.filter((s) => s.entity_type === 'institution')
.reduce((sum, s) => {
const y = s.topic_data[selectedTopic]?.find(
(yd) => yd.year === yearNum,
);
return sum + (y ? y.raw : 0);
}, 0);
if (sumInsts > 0) {
const pct = (yrData.raw / sumInsts) * 100;
contributionStr = ` (${pct.toFixed(1)}% of compared institutions)`;
}
}
} else if (entity.entity_type === 'country') {
const countryCode = entity.entity_id.toUpperCase();
const parentContinent = trendData.series.find((s) => {
if (s.entity_type !== 'region') return false;
const memberCountries =
trendData.location_mappings?.[s.entity_id] || [];
return memberCountries.some(
(c) => c.toUpperCase() === countryCode,
);
});
const childInstsSum = trendData.series
.filter(
(s) =>
s.entity_type === 'institution' &&
s.country_code?.toUpperCase() === countryCode,
)
.reduce((sum, s) => {
const y = s.topic_data[selectedTopic]?.find(
(yd) => yd.year === yearNum,
);
return sum + (y ? y.raw : 0);
}, 0);
const remainingVal = Math.max(0, yrData.raw - childInstsSum);
const remainingPct = (remainingVal / yrData.raw) * 100;
if (parentContinent) {
const parentYr = parentContinent.topic_data[
selectedTopic
]?.find((y) => y.year === yearNum);
if (parentYr && parentYr.raw > 0) {
const pct = (yrData.raw / parentYr.raw) * 100;
contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`;
}
}
if (childInstsSum > 0) {
contributionStr += `<br/><span style="padding-left: 14px; color: #9ca3af; font-size: 10px;">(excl. compared institutions: ${remainingVal.toLocaleString()} / ${remainingPct.toFixed(1)}%)</span>`;
}
} else if (entity.entity_type === 'region') {
const continentId = entity.entity_id;
const memberCountries =
trendData.location_mappings?.[continentId] || [];
const childSum = trendData.series
.filter((s) => {
if (s.entity_type === 'country') {
return memberCountries.some(
(c) => c.toUpperCase() === s.entity_id.toUpperCase(),
);
}
if (s.entity_type === 'institution') {
return memberCountries.some(
(c) =>
c.toUpperCase() === s.country_code?.toUpperCase(),
);
}
return false;
})
.reduce((sum, s) => {
const y = s.topic_data[selectedTopic]?.find(
(yd) => yd.year === yearNum,
);
return sum + (y ? y.raw : 0);
}, 0);
const remainingVal = Math.max(0, yrData.raw - childSum);
const remainingPct = (remainingVal / yrData.raw) * 100;
if (childSum > 0) {
contributionStr = `<br/><span style="padding-left: 14px; color: #9ca3af; font-size: 10px;">(excl. compared elements: ${remainingVal.toLocaleString()} / ${remainingPct.toFixed(1)}%)</span>`;
}
}
}
res += `<span style="padding-left: 14px; color: #6b7280; font-size: 11px;">• ${selectedTopic}: <strong>${displayVal}</strong>${contributionStr}</span><br/>`;
}
res += `</div>`;
});
res += `</div>`;
return res;
},
},
legend: {
bottom: 5,
left: 'center',
type: 'scroll',
textStyle: { color: '#4b5563' },
},
axisPointer: {
link: [{ xAxisIndex: 'all' }],
label: { backgroundColor: '#777' },
},
grid: [
{
left: '6%',
right: '8%',
top: '12%',
height: '52%',
},
{
left: '6%',
right: '8%',
top: '73%',
height: '14%',
},
],
xAxis: [
{
type: 'category',
data: xAxisData,
boundaryGap: false,
axisLine: { onZero: false, lineStyle: { color: '#e5e7eb' } },
axisLabel: { color: '#4b5563' },
splitLine: { show: false },
min: 'dataMin',
max: 'dataMax',
axisPointer: { z: 100 },
},
{
type: 'category',
gridIndex: 1,
data: xAxisData,
boundaryGap: false,
axisLine: { onZero: false, lineStyle: { color: '#e5e7eb' } },
axisTick: { show: false },
splitLine: { show: false },
axisLabel: { show: false },
min: 'dataMin',
max: 'dataMax',
},
],
yAxis: [
{
scale: true,
name: yAxisName,
nameTextStyle: { color: '#4b5563', padding: [0, 0, 8, 0] },
axisLabel: { color: '#4b5563' },
axisLine: { lineStyle: { color: '#e5e7eb' } },
splitLine: { lineStyle: { color: '#f3f4f6' } },
},
{
scale: true,
gridIndex: 1,
splitNumber: 2,
axisLabel: { show: false },
axisLine: { show: false },
axisTick: { show: false },
splitLine: { show: false },
},
{
scale: true,
gridIndex: 1,
position: 'right',
axisLabel: { color: '#9ca3af', show: true },
axisLine: { lineStyle: { color: '#e5e7eb' } },
splitLine: { show: false },
},
],
brush: {
toolbox: ['rect', 'lineX', 'clear'],
xAxisIndex: 'all',
brushLink: 'all',
outOfBrush: { colorAlpha: 0.15 },
},
toolbox: {
left: 'right',
top: 'top',
feature: {
brush: { type: ['rect', 'lineX', 'clear'] },
saveAsImage: { title: 'Save' },
},
},
dataZoom: [
{
type: 'inside',
xAxisIndex: [0, 1],
},
{
type: 'slider',
show: true,
xAxisIndex: [0, 1],
bottom: 30,
height: 15,
borderColor: '#e5e7eb',
fillerColor: 'rgba(236, 72, 153, 0.1)',
handleIcon:
'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
handleSize: '120%',
handleStyle: {
color: '#ec4899',
shadowBlur: 3,
shadowColor: 'rgba(0, 0, 0, 0.2)',
},
textStyle: { color: '#4b5563' },
},
],
series: series,
};
});
}