added hierarchy tree chart

This commit is contained in:
2026-09-26 18:09:36 +02:00
parent 5cd13dc8a4
commit 478cededcd
3 changed files with 692 additions and 0 deletions
@@ -0,0 +1,90 @@
<div class="university-hierarchy">
@if (loading()) {
<div class="uh-loader-overlay">
<mat-spinner diameter="40"></mat-spinner>
<span class="uh-loader-text">Lade Daten...</span>
</div>
}
@if (!loading()) {
<div class="uh-spacer">
<mat-chip-set
class="uh-breadcrumb"
aria-label="Pfad durch die Hierarchie">
@for (level of levels(); track level.id; let i = $index) {
<mat-chip
(click)="jumpToLevel(i)"
[class.uh-chip-active]="i === levels().length - 1">
<span class="uh-chip-index">{{ i + 1 }}</span>
{{ level.title }}
</mat-chip>
}
</mat-chip-set>
<div>
<button
mat-icon-button
(click)="toggleLanguage()"
[matTooltip]="
lang() === 'de' ? 'Switch to English' : 'Auf Deutsch wechseln'
">
<mat-icon>translate</mat-icon>
</button>
<button
mat-icon-button
(click)="resetToRoot()"
[disabled]="levels().length <= 1"
matTooltip="Zurücksetzen">
<mat-icon>restart_alt</mat-icon>
</button>
</div>
</div>
<div class="uh-row">
@for (
level of levels();
track level.id;
let i = $index;
let last = $last
) {
@if (!last) {
<button
type="button"
class="uh-strip"
(click)="jumpToLevel(i)"
[matTooltip]="level.title"
matTooltipPosition="right">
<span class="uh-strip-index">{{ i + 1 }}</span>
<span class="uh-strip-label">{{ level.title }}</span>
</button>
} @else {
<mat-card class="uh-level-card" appearance="outlined">
<div class="uh-level-header">
<div class="uh-level-titles">
<span class="uh-level-index">Ebene {{ i + 1 }}</span>
<span class="uh-level-name">{{ level.title }}</span>
</div>
@if (i > 0) {
<button
mat-icon-button
class="uh-level-close"
(click)="removeLevelsFrom(i)"
matTooltip="Diese Ebene schließen">
<mat-icon>close</mat-icon>
</button>
}
</div>
<mat-card-content class="uh-chart-viewport">
<div
echarts
[options]="level.options"
[autoResize]="true"
(chartClick)="onNodeClick($event, i)"
class="uh-chart"
[style.height.px]="level.height"></div>
</mat-card-content>
</mat-card>
}
}
</div>
}
</div>
@@ -0,0 +1,180 @@
:host {
--uh-gap: 8px;
--uh-strip-width: 44px;
--uh-radius: 8px;
--uh-row-height: min(72vh, 680px);
display: block;
}
.university-hierarchy {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
gap: var(--uh-gap);
}
/* ---------------------------------- toolbar --------------------------------- */
.uh-spacer {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.uh-loader-overlay {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 48px 0;
color: rgba(0, 0, 0, 0.6);
.uh-loader-text {
font-size: 13px;
}
}
/* --------------------------------- breadcrumb -------------------------------- */
.uh-breadcrumb {
display: flex;
flex-wrap: wrap;
gap: 6px;
mat-chip {
font-size: 12px;
cursor: pointer;
}
.uh-chip-index {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
margin-right: 6px;
border-radius: 50%;
background: rgba(0, 0, 0, 0.08);
font-size: 10px;
}
.uh-chip-active {
font-weight: 600;
}
}
/* ----------------------------------- row ------------------------------------ */
.uh-row {
display: flex;
flex-grow: 1;
flex-direction: row;
flex-wrap: nowrap;
align-items: stretch;
gap: var(--uh-gap);
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 2px;
}
/* collapsed (already-opened, not the active) level */
.uh-strip {
flex: 0 0 var(--uh-strip-width);
width: var(--uh-strip-width);
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 12px 0;
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: var(--uh-radius);
background: rgba(0, 0, 0, 0.02);
cursor: pointer;
font: inherit;
transition:
background 0.15s ease,
border-color 0.15s ease;
&:hover,
&:focus-visible {
background: rgba(0, 0, 0, 0.05);
border-color: rgba(0, 0, 0, 0.24);
}
.uh-strip-index {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 50%;
background: var(--mat-sys-primary, #3f51b5);
color: #fff;
font-size: 11px;
}
.uh-strip-label {
writing-mode: vertical-rl;
transform: rotate(180deg);
min-height: calc(100% - 32px);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
color: rgba(0, 0, 0, 0.75);
}
}
/* active (currently drilled-into) level */
.uh-level-card {
flex: 1 1 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
.uh-level-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 8px 8px 14px;
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
.uh-level-titles {
display: flex;
align-items: baseline;
gap: 8px;
min-width: 0;
}
.uh-level-index {
flex: 0 0 auto;
font-size: 11px;
font-weight: 600;
color: rgba(0, 0, 0, 0.5);
}
.uh-level-name {
overflow: hidden;
font-size: 14px;
font-weight: 500;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.uh-chart-viewport {
overflow-x: hidden;
overflow-y: auto;
height: 100%;
padding: 0 !important;
}
.uh-chart {
height: 100% !important;
width: 100%;
}
@@ -0,0 +1,422 @@
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() + 'teaching.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,
],
};
}
}