Files
smartguide/webapp/src/app/modules/hierarchy/hierarchy-chart/hierarchy-chart.component.ts
T

423 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
Component,
DestroyRef,
OnInit,
signal,
inject,
input,
Output,
computed,
EventEmitter,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router, ActivatedRoute } from '@angular/router';
import { NgxEchartsDirective } from 'ngx-echarts';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatTooltipModule } from '@angular/material/tooltip';
import type { EChartsOption } from 'echarts';
import { CredentialService } from '../../../shared/services/credential.service';
interface RawNode {
id?: string;
name_de: string;
name_en?: string;
link_de?: string;
link_en?: string;
type?: string; // 'faculty' | 'institutes' | 'chairs' | 'leaf' | 'university'
color?: string;
value?: number;
children?: RawNode[];
[key: string]: any; // faculty_de, institutes_aggregator, chairs_aggregator, ...
}
interface TreeLevel {
id: string;
title: string;
height: number;
options: EChartsOption;
}
const QUERY_PARAM_PATH = 'path';
const QUERY_PARAM_LANG = 'lang';
const LEAF_ROW_HEIGHT = 22;
const MIN_TREE_HEIGHT = 200;
@Component({
selector: 'app-hierarchy-chart',
standalone: true,
imports: [
NgxEchartsDirective,
MatProgressSpinnerModule,
MatToolbarModule,
MatCardModule,
MatButtonModule,
MatIconModule,
MatChipsModule,
MatTooltipModule,
],
templateUrl: './hierarchy-chart.component.html',
styleUrls: ['./hierarchy-chart.component.scss'],
})
export class HierarchyChartComponent implements OnInit {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly destroyRef = inject(DestroyRef);
private readonly credentialService = inject(CredentialService);
readonly loading = signal<boolean>(true);
readonly lang = signal<'de' | 'en'>('de');
readonly levels = signal<TreeLevel[]>([]);
private idMap = new Map<string, RawNode>();
private universityRoot: RawNode | null = null;
private isOwnNavigation = false;
hierarchyData = input.required<any>();
university_name = computed(
() => this.credentialService.organizationName() ?? 'Universität',
);
@Output() analyzeOrgEvent = new EventEmitter<{ name: string; url: string }>();
ngOnInit(): void {
this.loadData();
this.route.queryParamMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
if (this.isOwnNavigation) {
this.isOwnNavigation = false;
return;
}
this.restoreFromUrl(params);
});
}
/* ----------------------------- data loading ----------------------------- */
private loadData(): void {
this.loading.set(true);
this.assignIds(this.hierarchyData(), 'root');
this.universityRoot = {
id: 'root',
name_de: this.university_name(),
name_en: this.university_name(),
type: 'university',
children: this.hierarchyData(),
};
this.idMap.set('root', this.universityRoot);
this.loading.set(false);
}
private assignIds(nodes: RawNode[], parentId: string): void {
nodes.forEach((node, index) => {
const id = `${parentId}-${index}`;
node.id = id;
this.idMap.set(id, node);
if (node.children?.length) {
this.assignIds(node.children, id);
}
});
}
/* -------------------------------- URL state ------------------------------- */
/** Rebuilds `levels`/`lang` from the current query params (called once on init). */
private restoreFromUrl(qp: import('@angular/router').ParamMap): void {
const langParam = qp.get(QUERY_PARAM_LANG);
if (langParam === 'de' || langParam === 'en') {
this.lang.set(langParam);
}
const pathParam = qp.get(QUERY_PARAM_PATH);
const ids = pathParam ? pathParam.split(',').filter(Boolean) : [];
const restored: TreeLevel[] = [];
for (const id of ids) {
const raw = this.idMap.get(id);
if (!raw) break; // stale/unknown id -> stop restoring, keep what we have so far
restored.push(this.buildLevel(raw));
}
this.levels.set(
restored.length ? restored : [this.buildLevel(this.universityRoot!)],
);
// normalize the URL (fills in defaults / drops invalid trailing ids)
this.syncUrl();
}
/** Writes the current levels path + language into the URL as query params. */
private syncUrl(): void {
const path = this.levels()
.map((l) => l.id)
.join(',');
this.isOwnNavigation = true;
this.router
.navigate([], {
relativeTo: this.route,
queryParams: {
[QUERY_PARAM_PATH]: path,
[QUERY_PARAM_LANG]: this.lang(),
},
queryParamsHandling: 'merge',
replaceUrl: true,
})
.then((navigated) => {
if (!navigated) this.isOwnNavigation = false;
});
}
/* ------------------------------- UI actions ------------------------------ */
toggleLanguage(): void {
this.lang.set(this.lang() === 'de' ? 'en' : 'de');
// rebuild every currently opened level with the new language, keep the path
const rebuilt = this.levels().map((level) => {
const raw = this.idMap.get(level.id);
return raw ? this.buildLevel(raw) : level;
});
this.levels.set(rebuilt);
this.syncUrl();
}
resetToRoot(): void {
if (this.universityRoot) {
this.levels.set([this.buildLevel(this.universityRoot)]);
this.syncUrl();
}
}
/** closes the given level and everything opened below it */
removeLevelsFrom(index: number): void {
this.levels.set(this.levels().slice(0, index));
this.syncUrl();
}
/** collapsed strip / breadcrumb chip clicked -> make that level active again */
jumpToLevel(index: number): void {
this.removeLevelsFrom(index + 1);
}
/* ------------------------------ click handling ---------------------------- */
onNodeClick(params: any, levelIndex: number): void {
const nodeData = params?.data;
if (!nodeData?.id) return;
const raw = this.idMap.get(nodeData.id);
if (!raw) return;
// Group headers ("Instituten" / "Lehrstühle") are already fully expanded
if (raw.type === 'institutes' || raw.type === 'chairs') {
return;
}
const hasChildren = !!(raw.children && raw.children.length);
if (hasChildren) {
const newLevel = this.buildLevel(raw);
// if the user clicks a different branch, drop any deeper levels first
const truncated = this.levels().slice(0, levelIndex + 1);
this.levels.set([...truncated, newLevel]);
this.syncUrl();
} else {
this.onLeafSelect(raw);
}
}
private onLeafSelect(raw: RawNode): void {
console.log('[UniversityHierarchy] leaf node clicked:', raw);
this.analyzeOrgEvent.emit({
name: raw.name_de ?? raw.name_en ?? '',
url: raw.link_de ?? raw.link_en ?? '',
});
}
/* ------------------------------ tree building ----------------------------- */
private getLink(raw: RawNode): string | undefined {
return this.lang() === 'en'
? (raw.link_en ?? raw.link_de)
: (raw.link_de ?? raw.link_en);
}
private displayName(raw: RawNode): string {
return this.lang() === 'en'
? (raw.name_en ?? raw.name_de)
: (raw.name_de ?? raw.name_en ?? '');
}
/**
* Converts one raw node into an ECharts tree node.
* `expandGroup` controls whether an `institutes`/`chairs` GROUP node is
* allowed to reveal its direct items in this pass (used once per drill step).
* `parentType` is the *group's* raw type ('institutes' | 'chairs'); it lets a
* generic 'leaf' item (an individual institute/chair entry, which usually has
* no more specific type of its own) inherit an icon from the group it came
* from, instead of falling back to a generic dot.
*/
private toChartNode(
raw: RawNode,
expandGroup: boolean,
parentType?: string,
): any {
const isGroup = raw.type === 'institutes' || raw.type === 'chairs';
const hasChildren = !!(raw.children && raw.children.length);
const effectiveType =
raw.type === 'leaf' && parentType ? parentType : raw.type;
const node: any = {
id: raw.id,
name: this.displayName(raw),
nodeType: effectiveType,
hasChildren,
link: this.getLink(raw),
itemStyle: {
color: raw.color || (isGroup ? '#5B8FF9' : '#3BA272'),
},
};
// Only a GROUP node may reveal one more layer (its actual items) –
// those items themselves are NOT expanded further here.
if (isGroup && expandGroup && hasChildren) {
node.children = raw.children!.map((c) =>
this.toChartNode(c, false, raw.type),
);
}
return node;
}
private countLeaves(node: any): number {
if (!node.children || node.children.length === 0) return 1;
return node.children.reduce(
(sum: number, c: any) => sum + this.countLeaves(c),
0,
);
}
private buildLevel(raw: RawNode): TreeLevel {
const children = (raw.children || []).map((c) => this.toChartNode(c, true));
const rootData = {
id: raw.id,
name: this.displayName(raw),
nodeType: raw.type,
hasChildren: true,
itemStyle: { color: raw.color || '#333' },
children,
};
const leafCount = Math.max(children.length, this.countLeaves(rootData));
const height = Math.max(MIN_TREE_HEIGHT, leafCount * LEAF_ROW_HEIGHT);
return {
id: raw.id!,
title: this.displayName(raw),
height,
options: this.createTreeOption(rootData),
};
}
/**
* Symbol per node category. `nodeType` here is the *effective* type from
* `toChartNode` — for institute/chair leaves this is already resolved to
* 'institutes' / 'chairs' via inheritance, so they get the same icon as
* their group header. Anything that doesn't map to a known category (a
* genuinely untyped leaf) falls back to a plain circle, which is a valid
* ECharts built-in symbol — unlike an arbitrary string, which ECharts
* would silently fail to render.
*/
private getNodeIcon(nodeType: string | undefined): string {
switch (nodeType) {
case 'faculty':
return this.getIconPath() + 'mortarboard.png';
case 'institutes':
return this.getIconPath() + 'building.png';
case 'chairs':
return this.getIconPath() + 'teach.png';
case 'university':
return this.getIconPath() + 'school.png';
default:
return 'circle';
}
}
private getIconPath() {
return 'image://assets/icons/';
}
private createTreeOption(rootData: any): EChartsOption {
return {
tooltip: {
trigger: 'item',
triggerOn: 'mousemove',
formatter: (p: any) => p?.data?.name ?? '',
},
series: [
{
type: 'tree',
data: [rootData],
top: '2%',
left: '15%',
right: '35%',
orient: 'LR',
symbol: (_value: any, params: any) =>
this.getNodeIcon(params?.data?.nodeType),
symbolSize: 24,
itemStyle: {
borderWidth: 1,
borderColor: '#fff',
},
label: {
position: 'left',
offset: [0, 0],
verticalAlign: 'middle',
align: 'right',
fontSize: 11,
color: '#333',
formatter: (params: any) => {
if (params.data.hasChildren) {
return '{bold|' + params.name + '}';
}
return '{normal|' + params.name + '}';
},
rich: {
bold: {
fontWeight: 'bold',
},
normal: {
fontWeight: 'normal',
},
},
},
leaves: {
label: {
position: 'right',
verticalAlign: 'middle',
align: 'left',
offset: [0, 0],
},
},
emphasis: { focus: 'descendant' },
expandAndCollapse: false,
initialTreeDepth: -1,
roam: 'move',
lineStyle: {
color: '#c9cdd4',
width: 1.2,
curveness: 0.3,
},
animationDuration: 300,
animationDurationUpdate: 300,
} as any,
],
};
}
}