Compare commits

...
Author SHA1 Message Date
genja 73ef00be8c Merge pull request 'Feature/standardize layout' (#325) from feature/standardize-layout into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #325
2026-11-25 11:52:16 +01:00
genja cf9cf16a77 feat(navigation): section-aware page skeletons and accessible navigation
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-11-24 23:25:21 +01:00
genja a8b7c63897 (fix): fetch the right field from ude_verified_persons index 2026-11-24 14:33:49 +01:00
genja 4ebf1df32a choose the users organization on dashboard per default
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-11-24 13:25:00 +01:00
genja 3645069ded stretched the multipler nertwok component and made it responsive 2026-11-24 13:07:01 +01:00
genja 977cf442a8 changed the multipliers network route to "collaboration-network:id" 2026-11-24 13:03:22 +01:00
genja 9b0783b80a (fix): Fixed wrong adding nodes to breadcrumb 2026-11-23 22:23:06 +01:00
genja e8c7488489 disable the organization badge view for users not from own org 2026-11-19 23:13:28 +01:00
genja 3d5ed7dd2d added organization information to ude verified staff script 2026-11-19 21:40:35 +01:00
genja 00f54d117d Merge pull request 'Feature/standardize layout' (#324) from feature/standardize-layout into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #324
2026-11-18 18:35:06 +01:00
genja d90bf9b837 navigate to founders with no threshold per default
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-11-18 18:21:55 +01:00
genja ea5e3ca942 added filter params to founders resolver 2026-11-18 18:21:34 +01:00
genja 722f95fad1 added founder table filters to the founder dashboard 2026-11-18 18:21:07 +01:00
genja eb2fa92225 show all founder profiles per default 2026-11-18 18:20:45 +01:00
genja e2be1fc57d added filters for founder table 2026-11-18 18:18:53 +01:00
genja e9a72f88c1 moved selected row to table detail row 2026-11-18 15:12:27 +01:00
genja 48a10dbca3 threshold is opt-in now 2026-11-18 15:10:58 +01:00
genja dc79d16dfb removed "suspicious profile" note next to person names 2026-11-18 15:10:22 +01:00
genja d1827cf86b new model files added
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-11-17 23:07:34 +01:00
genja 728d8c9646 added to_person_profile navigation 2026-11-17 23:07:21 +01:00
genja d60c17abf4 added highlighting for organization on navigation 2026-11-17 21:28:42 +01:00
genja 6b6a5c7cff added organization badge to person profile 2026-11-17 21:25:51 +01:00
genja 41cc3a7ac6 tests for verified organization and institution helper added 2026-11-17 21:20:28 +01:00
genja a1317810c9 added verified organization endpoint with models 2026-11-17 21:20:13 +01:00
genja 22997f6a16 added normalize org uri helper 2026-11-17 21:16:10 +01:00
genja 8322fea036 reused existing normalize org uri function 2026-11-17 21:10:51 +01:00
genja 492987100c added verified persons job 2026-11-16 14:43:12 +01:00
genja cb4e7465b1 added helper function to transfer NES credentials to the container/ added persistent directory for verified persons script 2026-11-16 14:42:45 +01:00
genja ef6df95b54 fixed verification helper for stop creating Edge/CollaborationGraph objects, added new helper function 2026-11-16 14:34:24 +01:00
genja a9e7a0f3ab optimized route-scroll behaviour 2026-11-15 00:03:59 +01:00
genja 23b112beb9 optimized charts rendering 2026-11-15 00:03:52 +01:00
genja 739669021b added explain panel to founder-dashobard component 2026-11-15 00:03:22 +01:00
genja 4c39933b8d minor layout fixes 2026-11-13 12:02:35 +01:00
genja e6e8d192cc fixed bug where the page title was shown as tooltip on mouse hover 2026-11-12 23:07:52 +01:00
genja 9535bfedf5 standartized "goBack" button 2026-11-12 23:01:38 +01:00
genja faa22e0a8f added skeleton loading to person-card's university display 2026-11-12 22:53:07 +01:00
genja 83e0bc3e01 minor ui fixes 2026-11-12 22:43:23 +01:00
genja 30eea4aa22 prevented hierarchy to reresolbe on node click 2026-11-12 22:35:38 +01:00
genja 8b374681c2 added page title service for displaying page title 2026-11-12 22:25:42 +01:00
genja e984372259 made the "Zurück" button visible only within components 2026-11-12 21:58:55 +01:00
genja 8c45c29fc6 standartized resolving state of components 2026-11-12 21:55:44 +01:00
genja 0775f3efc7 fixed hierarchy chart render warning 2026-11-12 21:17:36 +01:00
genja 5153e5876d adjusted tooltips for better explanability 2026-11-12 21:02:39 +01:00
genja 90c6fa56c8 research-wordcloud component replaced by the shared keywords-component 2026-11-12 14:26:13 +01:00
genja e63f2e99d8 created utils for research wordcloud to enable compatibility to the shared keywords-wordcloud component 2026-11-12 14:24:26 +01:00
genja 34c0235112 updated keywords-wordcloud component. Adde more optional fields for reusability 2026-11-12 14:22:57 +01:00
genja 50350fcc12 Merge pull request 'Feature/multipliers frontend' (#323) from feature/multipliers-frontend into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #323
2026-11-12 13:13:34 +01:00
123 changed files with 7446 additions and 1508 deletions
+6
View File
@@ -1,3 +1,4 @@
# Root-context job images only need service code, never the webapp or repo data.
* *
!background-jobs !background-jobs
!service !service
@@ -7,6 +8,11 @@ service/*
# Keyword extraction contract, shared with background-jobs/app/llm/client.py. # Keyword extraction contract, shared with background-jobs/app/llm/client.py.
!service/src/main/inse/news/keyword_extraction.py !service/src/main/inse/news/keyword_extraction.py
# UDE verified-persons job image imports the full service package and one
# institution hierarchy, so these are the only extra paths it needs.
!service/src/main/inse
!service/src/data/hierarchies/I62318514/hierarchy.json
# Data-only folders that do not belong in the job image. # Data-only folders that do not belong in the job image.
service/scripts/multipliers service/scripts/multipliers
+3
View File
@@ -26,3 +26,6 @@ service/sentence_transformer/models/
llm_evaluations/bio_generation/.venv llm_evaluations/bio_generation/.venv
.devcontainer .devcontainer
# Runtime checkpoint for the UDE OrgMiner verified-person uploader.
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json.tmp
+29
View File
@@ -82,6 +82,7 @@ differ only by their `command`.
| Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | | Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend |
| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend | | News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend |
| News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | | News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index |
| UDE OrgMiner Verified Persons | `jobs/orgminer-verified-persons-ude` | `upload_orgminer_verified_persons_ude.py --progress-file /state/orgminer_verified_persons_ude_progress.json` | Writes `orgminer_verified_persons_ude`; image-scoped NES creds; persistent checkpoint |
| Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows | | Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows |
Each image is its own repository under the `jobs/` path namespace, prefixed Each image is its own repository under the `jobs/` path namespace, prefixed
@@ -106,6 +107,30 @@ docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
Each image's Dockerfile header lists its own build command. Each image's Dockerfile header lists its own build command.
### UDE OrgMiner verified persons
```bash
docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest .
docker push docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest
```
Create a manual-only job in the Jobs UI with this image and set **Persistent
directory** to `/state`. The image's entrypoint writes its JSON checkpoint to
`/state/orgminer_verified_persons_ude_progress.json`; the runner mounts a task-specific Docker volume there so
separate runs resume. Keep the job definition if you need to keep its checkpoint
(deleting the definition also removes its volume). Leave **Command** empty for a
full resumable run, or set it to `--limit 5` for a small first run. Set **Command**
to `--fresh` if every invocation should delete the checkpoint and start at the
first organization. Organizations are processed sequentially; no concurrency
flags exist. The target index is `orgminer_verified_persons_ude`.
If the run stops without a `Finished:` line and reports exit `137`, the
container was killed (usually by the host's out-of-memory killer) and no Python
traceback exists. The run log then gets a `[system] ... ran out of memory ...`
note from the runner. A job without a **Persistent directory** always starts
from the first organization, which makes such a restart look identical.
## Running locally without pushing ## Running locally without pushing
Before each run the backend pulls the job's image from the registry when it is a Before each run the backend pulls the job's image from the registry when it is a
@@ -127,6 +152,10 @@ is enough for local runs.
Because every tag lives under the `docker.nes.uni-due.de` registry host, the Because every tag lives under the `docker.nes.uni-due.de` registry host, the
backend treats these as registry images and injects the INSE Elasticsearch / LLM backend treats these as registry images and injects the INSE Elasticsearch / LLM
credentials automatically (plus any per-job `env`). credentials automatically (plus any per-job `env`).
The `orgminer-verified-persons-ude` image also receives `ELASTICSEARCH_URL` and
`ELASTICSEARCH_API_KEY` from backend settings, and only that exact repository
gets those NES credentials. Other job images continue to receive INSE/LLM
credentials only.
Most images write to the test index by default: the crawlers upload into the Most images write to the test index by default: the crawlers upload into the
index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to
@@ -0,0 +1,27 @@
# UDE OrgMiner staff verification using the collaboration graph.
# Build from the repository root:
# docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \
# -t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest .
#
# The runner injects INSE credentials for registry images and NES credentials
# only for this image. The persistent /state volume holds the JSON checkpoint.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1 \
PYTHONPATH=/app/service/src/main
COPY service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/src/main/inse/ ./service/src/main/inse/
COPY service/src/data/hierarchies/I62318514/hierarchy.json \
./service/src/data/hierarchies/I62318514/hierarchy.json
COPY service/scripts/upload_orgminer_verified_persons_ude/ \
./service/scripts/upload_orgminer_verified_persons_ude/
# Fail the image build if the service verification/author code is missing a dependency.
RUN python -c "import inse.orgminer.logic, inse.authors.v2.service"
ENTRYPOINT ["python", "/app/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py", \
"--progress-file", "/state/orgminer_verified_persons_ude_progress.json"]
@@ -0,0 +1,5 @@
fastapi~=0.115.0
httpx~=0.27.0
pydantic-settings~=2.2.1
python-dotenv~=1.0
sqlmodel~=0.0.33
@@ -0,0 +1,94 @@
# Upload verified UDE OrgMiner persons
Run from the repository root:
```bash
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py
```
The script reads `ude_organization_content_august_2025_draft`, applies the
OrgMiner collaboration-graph verification rule, and upserts one document per
verified OpenAlex person and organization into `orgminer_verified_persons_ude`
on the INSE Elasticsearch cluster.
For the background-job image and persistent checkpoint setup, see
[`../jobs-image/README.md`](../jobs-image/README.md#ude-orgminer-verified-persons).
INSE credentials must be available as `ELASTICSEARCH_INSE_URL` and
`ELASTICSEARCH_INSE_API_KEY` for reading/writing OrgMiner data. NES credentials
must also be available as `ELASTICSEARCH_URL` and `ELASTICSEARCH_API_KEY` for
OpenAlex author resolution during verification. They can be set in the
environment or the service `.env` file.
The default checkpoint is `orgminer_verified_persons_ude_progress.json` next to
the script. It records completed source organization document IDs and the last
completed organization URI. On restart the scan resumes from that URI, skips
completed organizations, and safely retries upserts if an interrupted request did
not get checkpointed. Use `--progress-file PATH` to keep the checkpoint elsewhere.
Each document also exposes the organization context explicitly:
- `faculty`: root hierarchy node, for example `Chemie`
- `organization_type`: immediate parent label, for example `Lehrstühle` or
`Instituten`
- `organization_level`: hierarchy node type code (`leaf`, `chairs`,
`institutes`, `faculty`)
Each person document also carries the person's OpenAlex organizations, loaded
from `openalex-authors`:
- `oa_organization_ids`: deduplicated short OpenAlex organization IDs
(`I62318514`), used for filtering and joins
- `oa_organization`: deduplicated OpenAlex organization objects with `id`,
`openalex_url`, `display_name`, `ror`, `country_code`, `type`, `lineage`,
`years`, and `last_known`
`last_known_institutions` and `affiliations` are merged by institution ID;
affiliation years are unioned and institutions without an OpenAlex ID are
skipped. Missing author documents do not drop the person; the document is written
with empty institution fields and a warning is logged.
The script processes one organization at a time, so a run needs no concurrency
flags.
Useful options:
```bash
# Run verification without writing to Elasticsearch or changing the checkpoint
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --dry-run
# Smoke-test a limited number of pending organizations
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --limit 5
# Delete the checkpoint and scan from the first organization again
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh
```
Verification requests only the collaboration weights towards the organization's
other staff candidates. It does not materialize every co-author pair, which is
unbounded for works with hundreds or thousands of authors. The progress log ends
each line with the process's peak `rss` so memory growth is visible.
`--fresh` removes the selected checkpoint and its temporary atomic-write file,
but does not clear the output index. Existing person/organization IDs are
upserted; output documents that are no longer produced are left in the index.
When configured on a background-job task, `--fresh` applies on every run, so the
task always restarts from the first source organization. If the checkpoint
directory is not a mounted volume, a warning is logged because progress cannot
survive the container.
## Rebuilding after a mapping change
The script creates the output index with its mapping only when the index does
not exist. After changing the document fields, delete the old index first and
then run a full upload:
```bash
curl -X DELETE "$ELASTICSEARCH_INSE_URL/orgminer_verified_persons_ude" \
-H "Authorization: ApiKey $ELASTICSEARCH_INSE_API_KEY"
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh
```
`--fresh` also removes the checkpoint so every source organization is processed
again.
@@ -0,0 +1,277 @@
"""Tests for the institution projection helpers in the upload script."""
from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
from types import SimpleNamespace
from inse.models.openalex.author import Author
from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
SCRIPT_PATH = Path(__file__).with_name("upload_orgminer_verified_persons_ude.py")
_SPEC = importlib.util.spec_from_file_location(
"upload_orgminer_verified_persons_ude", SCRIPT_PATH
)
assert _SPEC and _SPEC.loader
upload = importlib.util.module_from_spec(_SPEC)
sys.modules[_SPEC.name] = upload
_SPEC.loader.exec_module(upload)
def _institution(
institution_id: str | None,
display_name: str | None,
*,
ror: str | None = None,
country_code: str | None = None,
institution_type: str | None = None,
lineage: list[str] | None = None,
) -> DehydratedInstitution:
return DehydratedInstitution(
id=institution_id,
display_name=display_name,
ror=ror,
country_code=country_code,
type=institution_type,
lineage=lineage,
)
def test_extract_merges_last_known_and_historical_institutions() -> None:
ude_last_known = _institution(
"https://openalex.org/I62318514",
"University of Duisburg-Essen",
country_code="DE",
institution_type="education",
lineage=["https://openalex.org/I1", "https://openalex.org/I62318514"],
)
ude_affiliation = _institution(
"I62318514",
"University of Duisburg-Essen",
ror="https://ror.org/021ft7s37",
)
previous = _institution(
"https://openalex.org/I999",
"Previous University",
country_code="NL",
institution_type="education",
)
author = Author(
id="https://openalex.org/A1",
last_known_institutions=[ude_last_known],
affiliations=[
AuthorAffiliationsInner(institution=ude_affiliation, years=[2020, 2021]),
AuthorAffiliationsInner(institution=previous, years=[2017, 2018]),
AuthorAffiliationsInner(institution=ude_affiliation, years=[2019]),
],
)
institutions = upload.extract_openalex_institutions(author)
assert [item["id"] for item in institutions] == ["I62318514", "I999"]
assert institutions[0] == {
"id": "I62318514",
"openalex_url": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen",
"ror": "https://ror.org/021ft7s37",
"country_code": "DE",
"type": "education",
"lineage": ["https://openalex.org/I1", "https://openalex.org/I62318514"],
"years": [2019, 2020, 2021],
"last_known": True,
}
assert institutions[1]["last_known"] is False
assert institutions[1]["years"] == [2017, 2018]
assert upload.openalex_institution_ids(institutions) == ["I62318514", "I999"]
def test_extract_skips_institutions_without_an_openalex_id() -> None:
author = Author(
id="https://openalex.org/A1",
last_known_institutions=[
_institution(None, "Unknown Institute"),
_institution("", "Empty Id Institute"),
],
affiliations=[
AuthorAffiliationsInner(
institution=_institution("I123", "Known Institute"),
years=[2021],
)
],
)
institutions = upload.extract_openalex_institutions(author)
assert [item["id"] for item in institutions] == ["I123"]
assert institutions[0]["last_known"] is False
assert institutions[0]["years"] == [2021]
def test_extract_handles_missing_author_and_empty_institutions() -> None:
assert upload.extract_openalex_institutions(None) == []
assert (
upload.extract_openalex_institutions(Author(id="https://openalex.org/A1"))
== []
)
assert upload.openalex_institution_ids([]) == []
def _node(
name: str,
*,
node_type: str,
link: str | None = None,
children: list[SimpleNamespace] | None = None,
) -> SimpleNamespace:
return SimpleNamespace(
name_de=name,
name_en=None,
link_de=link,
link_en=None,
type=node_type,
children=children or [],
)
def test_organization_details_splits_faculty_type_and_organization() -> None:
hierarchy = [
_node(
"Chemie",
node_type="faculty",
link="https://example.org/chemie",
children=[
_node(
"Lehrstühle",
node_type="chairs",
link="https://example.org/chemie/lehrstuehle",
children=[
_node(
"Applied Analytical Chemistry",
node_type="leaf",
link="https://example.org/chemie/aac",
)
],
)
],
)
]
lookup = upload.build_hierarchy_lookup(hierarchy)
details = upload.organization_details(
{"uri": "https://example.org/chemie/aac"}, lookup
)
assert details.faculty == "Chemie"
assert details.organization_type == "Lehrstühle"
assert details.name == "Applied Analytical Chemistry"
assert details.organization_level == "leaf"
assert details.hierarchy_path == [
"Chemie",
"Lehrstühle",
"Applied Analytical Chemistry",
]
def test_organization_details_uses_immediate_parent_for_deep_paths() -> None:
hierarchy = [
_node(
"Chemie",
node_type="faculty",
link="https://example.org/chemie",
children=[
_node(
"Instituten",
node_type="institutes",
link="https://example.org/chemie/institute",
children=[
_node(
"ACTIVE SITES",
node_type="leaf",
link="https://example.org/chemie/active-sites",
children=[
_node(
"Lehrstühle",
node_type="chairs",
link="https://example.org/chemie/active-sites/chairs",
children=[
_node(
"Applied Analytical Chemistry",
node_type="leaf",
link="https://example.org/chemie/active-sites/aac",
)
],
)
],
)
],
)
],
)
]
lookup = upload.build_hierarchy_lookup(hierarchy)
details = upload.organization_details(
{"uri": "https://example.org/chemie/active-sites/aac"}, lookup
)
assert details.faculty == "Chemie"
assert details.organization_type == "Lehrstühle"
assert details.name == "Applied Analytical Chemistry"
def test_organization_details_describes_aggregator_nodes() -> None:
hierarchy = [
_node(
"Chemie",
node_type="faculty",
link="https://example.org/chemie",
children=[
_node(
"Lehrstühle",
node_type="chairs",
link="https://example.org/chemie/lehrstuehle",
)
],
)
]
lookup = upload.build_hierarchy_lookup(hierarchy)
details = upload.organization_details(
{"uri": "https://example.org/chemie/lehrstuehle"}, lookup
)
assert details.faculty == "Chemie"
assert details.organization_type == "Lehrstühle"
assert details.name == "Lehrstühle"
assert details.organization_level == "chairs"
def test_extract_merges_lineage_and_metadata_from_multiple_sources() -> None:
author = Author(
id="https://openalex.org/A1",
last_known_institutions=[
_institution("I42", "Example University", lineage=["I1"])
],
affiliations=[
AuthorAffiliationsInner(
institution=_institution(
"I42",
"Example University",
ror="https://ror.org/example",
lineage=["I1", "I42"],
),
years=[2022],
)
],
)
institutions = upload.extract_openalex_institutions(author)
assert len(institutions) == 1
assert institutions[0]["ror"] == "https://ror.org/example"
assert institutions[0]["lineage"] == ["I1", "I42"]
assert institutions[0]["years"] == [2022]
@@ -28,6 +28,9 @@ settings = config.get_settings()
RUN_STATE_LOCK = RLock() RUN_STATE_LOCK = RLock()
ORGMINER_DEFAULT_PERSISTENT_DIR = "/app/orgminer_pipeline/runs" ORGMINER_DEFAULT_PERSISTENT_DIR = "/app/orgminer_pipeline/runs"
ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY = (
"inse/jobs/orgminer-verified-persons-ude"
)
_client: docker.DockerClient | None = None _client: docker.DockerClient | None = None
@@ -131,6 +134,22 @@ def is_registry_image(image: str | None) -> bool:
return bool(image) and image.split("/", 1)[0] == registry_host() return bool(image) and image.split("/", 1)[0] == registry_host()
def uses_nes_credentials(image: str | None) -> bool:
"""Only the OrgMiner verified-person job needs direct NES access."""
if not image or not is_registry_image(image):
return False
registry, _, image_path = image.partition("/")
image_path = image_path.split("@", 1)[0]
path_parts = image_path.rsplit("/", 1)
repository_name = path_parts[-1].split(":", 1)[0]
repository = "/".join([*path_parts[:-1], repository_name])
return (
registry == registry_host()
and repository == ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY
)
def container_name(definition: JobDefinition, run: JobRun) -> str: def container_name(definition: JobDefinition, run: JobRun) -> str:
slug = definition.name.lower() slug = definition.name.lower()
slug = ( slug = (
@@ -198,7 +217,20 @@ def is_orgminer(definition: JobDefinition) -> bool:
def resolve_environment(definition: JobDefinition) -> dict[str, str]: def resolve_environment(definition: JobDefinition) -> dict[str, str]:
base = job_environment() if is_registry_image(resolve_image(definition)) else {} image = resolve_image(definition)
base = job_environment() if is_registry_image(image) else {}
if uses_nes_credentials(image):
nes_environment = {
"ELASTICSEARCH_URL": settings.elasticsearch_url,
"ELASTICSEARCH_API_KEY": settings.elasticsearch_api_key,
}
base.update(
{
key: value
for key, value in nes_environment.items()
if value
}
)
return {**base, **(definition.env or {})} return {**base, **(definition.env or {})}
@@ -399,7 +431,16 @@ def _reconcile_runs(session: Session) -> None:
container.reload() container.reload()
if container.status in ("exited", "dead"): if container.status in ("exited", "dead"):
exit_code = container.attrs["State"]["ExitCode"] state = container.attrs.get("State", {})
exit_code = state["ExitCode"]
logs = container.logs().decode("utf-8", errors="replace")
if state.get("OOMKilled"):
logs = append_system_log(
logs,
"The container ran out of memory and was killed by the kernel "
f"(exit {exit_code}). No Python traceback is written for this; "
"the log above simply stops.",
)
new_status = ( new_status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
) )
@@ -408,7 +449,7 @@ def _reconcile_runs(session: Session) -> None:
run, run,
new_status=new_status, new_status=new_status,
exit_code=exit_code, exit_code=exit_code,
logs=container.logs().decode("utf-8", errors="replace"), logs=logs,
) )
if applied: if applied:
session.commit() session.commit()
@@ -0,0 +1,49 @@
from types import SimpleNamespace
from . import runner
from .model import JobDefinition
def _settings():
return SimpleNamespace(
background_jobs_image="docker.nes.uni-due.de/inse/background-jobs:latest",
elasticsearch_url="https://nes.example/elastic",
elasticsearch_api_key="nes-api-key",
elasticsearch_inse_url="https://inse.example/elastic",
elasticsearch_inse_api_key="inse-api-key",
llm_api_url="https://llm.example",
llm_api_key="llm-api-key",
llm_model="test-model",
sentence_transformers_model_name="test-embedding-model",
)
def _job(image: str) -> JobDefinition:
return JobDefinition(name="test", image=image)
def test_nes_credentials_are_injected_only_for_verified_person_image(monkeypatch):
monkeypatch.setattr(runner, "settings", _settings())
verified_image = (
"docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:v1"
)
regular_image = "docker.nes.uni-due.de/inse/jobs/news-topics:latest"
verified_environment = runner.resolve_environment(_job(verified_image))
regular_environment = runner.resolve_environment(_job(regular_image))
assert verified_environment["ELASTICSEARCH_URL"] == "https://nes.example/elastic"
assert verified_environment["ELASTICSEARCH_API_KEY"] == "nes-api-key"
assert regular_environment["ELASTICSEARCH_INSE_API_KEY"] == "inse-api-key"
assert "ELASTICSEARCH_URL" not in regular_environment
assert "ELASTICSEARCH_API_KEY" not in regular_environment
def test_nes_credentials_are_not_injected_for_non_registry_copy(monkeypatch):
monkeypatch.setattr(runner, "settings", _settings())
local_image = "localhost/inse/jobs/orgminer-verified-persons-ude:dev"
environment = runner.resolve_environment(_job(local_image))
assert "ELASTICSEARCH_URL" not in environment
assert "ELASTICSEARCH_API_KEY" not in environment
@@ -12,10 +12,16 @@ from .model import JobRun, JobRunStatus, JobTriggeredBy
class FakeContainer: class FakeContainer:
def __init__( def __init__(
self, *, status: str, exit_code: int, logs: str, stop_error=None self,
*,
status: str,
exit_code: int,
logs: str,
stop_error=None,
oom_killed: bool = False,
): ):
self.status = status self.status = status
self.attrs = {"State": {"ExitCode": exit_code}} self.attrs = {"State": {"ExitCode": exit_code, "OOMKilled": oom_killed}}
self._logs = logs self._logs = logs
self.stop_calls = 0 self.stop_calls = 0
self.removed = False self.removed = False
@@ -126,6 +132,26 @@ def test_reconciler_keeps_running_container_after_backend_restart(
assert container.removed is False assert container.removed is False
def test_reconciler_annotates_container_killed_by_oom(session, monkeypatch):
run = _run(session)
container = FakeContainer(
status="exited",
exit_code=137,
logs="last org: https://www.uni-due.de/zmb",
oom_killed=True,
)
_use_container(monkeypatch, container)
runner.reconcile_runs(session)
session.refresh(run)
assert run.status == JobRunStatus.FAILED
assert run.exit_code == 137
assert "last org: https://www.uni-due.de/zmb" in run.logs
assert "ran out of memory" in run.logs
assert container.removed is True
def test_failed_docker_stop_leaves_database_run_running(session, monkeypatch): def test_failed_docker_stop_leaves_database_run_running(session, monkeypatch):
run = _run(session) run = _run(session)
container = FakeContainer( container = FakeContainer(
@@ -122,10 +122,10 @@ async def search_founder_candidates(
in_population: Annotated[ in_population: Annotated[
bool | None, bool | None,
Query( Query(
description="Restrict to researchers the model can score (default). " description="Restrict to researchers the model can score. "
"Pass false for the unscored, or leave unset for everyone." "Pass true for the scored, false for the unscored, or leave unset for everyone."
), ),
] = True, ] = None,
min_external_percentile: Annotated[ min_external_percentile: Annotated[
float | None, float | None,
Query(description="Minimum founder percentile (0-100, vs the external reference cohort).", ge=0, le=100), Query(description="Minimum founder percentile (0-100, vs the external reference cohort).", ge=0, le=100),
@@ -39,6 +39,21 @@ def strip_openalex_prefix(institution_id: str) -> str:
return institution_id.rsplit("/", 1)[-1] return institution_id.rsplit("/", 1)[-1]
def normalize_org_uri(uri: str | None) -> str | None:
"""Normalize an organization URL so hierarchy links compare reliably.
Trims whitespace, drops a trailing slash and the common ``/index`` suffix,
so ``https://www.example.org/x/``, ``https://www.example.org/x/index`` and
``https://www.example.org/x`` all map to the same value.
"""
if not uri:
return None
normalized = uri.strip().rstrip("/")
if normalized.endswith("/index"):
normalized = normalized[: -len("/index")].rstrip("/")
return normalized or None
def full_institution_url(institution_id: str) -> str: def full_institution_url(institution_id: str) -> str:
"""Normalize any institution id form to the full OpenAlex URL form.""" """Normalize any institution id form to the full OpenAlex URL form."""
return f"https://openalex.org/{strip_openalex_prefix(institution_id)}" return f"https://openalex.org/{strip_openalex_prefix(institution_id)}"
+185 -56
View File
@@ -2,11 +2,14 @@
from collections import defaultdict from collections import defaultdict
import asyncio import asyncio
from typing import Any, Callable, Optional from typing import Any, Awaitable, Callable, Optional
from inse.integrations.elasticsearch import search from inse.integrations.elasticsearch import search
from inse.utils import normalize_name from inse.utils import normalize_name
from inse.model import ESCluster, ESIndex from inse.model import ESCluster, ESIndex
from inse.authors.v2.service import _build_collaboration_graph from inse.authors.v2.service import (
_build_collaboration_graph,
_build_collaboration_graph_query,
)
from inse.auth.model import Account, Organization from inse.auth.model import Account, Organization
from inse import config from inse import config
from .model import ( from .model import (
@@ -134,6 +137,180 @@ async def get_person_collaborator_weights(
return weights return weights
async def get_collaborator_weights_for_targets(
author_id: str,
institution_id: str,
target_ids: set[str] | frozenset[str] | list[str],
) -> dict[str, float]:
"""Return ``{collaborator_id: shared_work_weight}`` only for ``target_ids``.
The collaboration-graph builder expands every pair of authors on every work,
which explodes for works with hundreds or thousands of authors. Verification
only needs the weights towards the other staff candidates in the same
organization, so this asks Elasticsearch for those counts directly.
"""
targets = sorted(set(target_ids) - {author_id})
if not targets:
return {}
query = _build_collaboration_graph_query(
raw_oa_author_id=author_id,
institution_ids=[institution_id],
)
body = {
"size": 0,
"query": query,
"aggs": {
"collaborators": {
"nested": {"path": "authorships"},
"aggs": {
"targets": {
"terms": {
"field": "authorships.author.id",
"include": targets,
"size": len(targets),
}
}
},
}
},
}
results = await search(
body=body,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
cluster=ESCluster.NES,
)
buckets = (
results.get("aggregations", {})
.get("collaborators", {})
.get("targets", {})
.get("buckets", [])
)
return {
bucket["key"]: float(bucket["doc_count"])
for bucket in buckets
if bucket.get("key")
}
async def get_verified_staff_with_collab_graph(
staff_list: list[dict[str, Any]],
institution_id: str = DEFAULT_INSTITUTION_ID,
max_concurrent_queries: int | None = None,
) -> list[dict[str, Any]]:
"""Return verified staff entries with the OpenAlex IDs and edges proving verification.
A staff entry is verified when at least one of its OpenAlex author candidates
has a collaboration edge to a candidate belonging to a different staff entry
in the same organization.
Only collaborator weights towards the organization's other staff candidates
are fetched, so verification memory does not grow with the size of an
author's full co-author network.
``max_concurrent_queries`` bounds the OpenAlex candidate and graph searches.
It is useful for batch jobs processing organizations with large staff lists.
"""
if max_concurrent_queries is not None and max_concurrent_queries < 1:
raise ValueError("max_concurrent_queries must be at least 1.")
query_semaphore = (
asyncio.Semaphore(max_concurrent_queries)
if max_concurrent_queries is not None
else None
)
async def _run_query(operation: Callable[[], Awaitable[Any]]) -> Any:
if query_semaphore is None:
return await operation()
async with query_semaphore:
return await operation()
async def _resolve_staff(staff: dict[str, Any]) -> set[str]:
name = staff.get("name")
if not name:
return set()
candidate_ids = await _run_query(
lambda: resolve_author_candidates(
normalize_name(name),
institution_id,
)
)
return set(candidate_ids)
async def _get_neighbor_weights(
author_id: str, target_ids: set[str]
) -> dict[str, float]:
return await _run_query(
lambda: get_collaborator_weights_for_targets(
author_id,
institution_id,
target_ids,
)
)
candidate_sets = await asyncio.gather(
*(_resolve_staff(staff) for staff in staff_list)
)
async def _verify_staff(
staff_index: int, own_ids: set[str]
) -> dict[str, Any] | None:
if not own_ids:
return None
other_ids = (
set().union(
*(
candidate_ids
for index, candidate_ids in enumerate(candidate_sets)
if index != staff_index
)
)
- own_ids
)
if not other_ids:
return None
# ``other_ids`` only contains OpenAlex candidates of the other staff
# entries in this organization, and every candidate set was resolved
# against ``institution_id``. Collaborator weights are therefore
# restricted to same-university colleagues; no external co-author can
# contribute evidence.
author_ids = sorted(own_ids)
neighbor_weights = await asyncio.gather(
*(_get_neighbor_weights(author_id, other_ids) for author_id in author_ids)
)
evidence = [
{
"openalex_id": author_id,
"collaborator_openalex_id": collaborator_id,
"shared_work_weight": weights[collaborator_id],
}
for author_id, weights in zip(author_ids, neighbor_weights)
for collaborator_id in sorted(weights.keys() & other_ids)
]
if not evidence:
return None
return {
"staff_index": staff_index,
"staff": staff_list[staff_index],
"openalex_ids": sorted({item["openalex_id"] for item in evidence}),
"collaboration_evidence": evidence,
}
checked_entries = await asyncio.gather(
*(
_verify_staff(staff_index, candidate_ids)
for staff_index, candidate_ids in enumerate(candidate_sets)
)
)
return [entry for entry in checked_entries if entry is not None]
async def find_org_for_person( async def find_org_for_person(
name: str, name: str,
institution_id: str = None, institution_id: str = None,
@@ -567,62 +744,14 @@ async def get_orgminer_content_verified_by_collab_graph(
orgminer_content = hits[0]["_source"] orgminer_content = hits[0]["_source"]
staff_list = orgminer_content.get("staff") or [] staff_list = orgminer_content.get("staff") or []
async def _resolve_staff(staff: dict) -> set[str]: verified_entries = await get_verified_staff_with_collab_graph(
name = staff.get("name") staff_list,
if not name: institution_id,
return set()
candidate_ids = await resolve_author_candidates(
normalize_name(name),
institution_id,
)
return set(candidate_ids)
async def _get_neighbor_ids(author_id: str) -> set[str]:
collaborator_weights = await get_person_collaborator_weights(
author_id,
institution_id,
)
return set(collaborator_weights.keys())
candidate_sets = await asyncio.gather(
*(_resolve_staff(staff) for staff in staff_list)
)
async def _is_verified(staff_index: int) -> bool:
own_ids = candidate_sets[staff_index]
if not own_ids:
return False
# Candidates belonging to other staff members only.
other_ids = (
set().union(
*(
candidate_ids
for index, candidate_ids in enumerate(candidate_sets)
if index != staff_index
)
)
- own_ids
)
if not other_ids:
return False
neighbor_sets = await asyncio.gather(
*(_get_neighbor_ids(author_id) for author_id in own_ids)
)
return any(neighbor_ids & other_ids for neighbor_ids in neighbor_sets)
verified_flags = await asyncio.gather(
*(_is_verified(index) for index in range(len(staff_list)))
) )
orgminer_content["verified_staff"] = [ orgminer_content["verified_staff"] = [
staff entry["staff"]
for staff, is_verified in zip(staff_list, verified_flags) for entry in verified_entries
if is_verified
] ]
return OrgminerContent.from_elastic_hit(orgminer_content) return OrgminerContent.from_elastic_hit(orgminer_content)
@@ -704,4 +833,4 @@ async def get_classified_pages(org_url: str,institution_id: str = DEFAULT_INSTIT
return ClassifiedPageResponse( return ClassifiedPageResponse(
total=response["hits"]["total"]["value"], total=response["hits"]["total"]["value"],
pages=classified_pages pages=classified_pages
) )
@@ -0,0 +1,32 @@
from inse.orgminer.institutions_helper import (
normalize_org_uri,
strip_openalex_prefix,
)
def test_normalize_org_uri_matches_equivalent_hierarchy_links():
assert (
normalize_org_uri(" https://www.uni-due.de/zmb/ ")
== "https://www.uni-due.de/zmb"
)
assert (
normalize_org_uri("https://www.uni-due.de/zmb/index")
== "https://www.uni-due.de/zmb"
)
assert (
normalize_org_uri("https://www.uni-due.de/zmb/index/")
== "https://www.uni-due.de/zmb"
)
def test_normalize_org_uri_returns_none_for_missing_values():
assert normalize_org_uri(None) is None
assert normalize_org_uri(" ") is None
def test_strip_openalex_prefix_accepts_raw_and_full_author_ids():
assert strip_openalex_prefix("A5018971503") == "A5018971503"
assert (
strip_openalex_prefix("https://openalex.org/A5018971503")
== "A5018971503"
)
@@ -1,8 +1,170 @@
import asyncio
import json import json
from inse.orgminer import logic from inse.orgminer import logic
def test_get_verified_staff_with_collab_graph_returns_matching_ids_and_edges(
monkeypatch,
):
staff = [
{"name": "Person One", "email": "one@example.org"},
{"name": "Person Two"},
]
resolved = {
"person one": ["https://openalex.org/A1", "https://openalex.org/A2"],
"person two": ["https://openalex.org/B1"],
}
neighbors = {
"https://openalex.org/A1": {"https://openalex.org/B1": 2.5},
"https://openalex.org/A2": {},
"https://openalex.org/B1": {},
}
async def resolve_author_candidates(name, institution_id):
return resolved[name]
async def get_collaborator_weights_for_targets(
author_id, institution_id, target_ids
):
return {
collaborator_id: weight
for collaborator_id, weight in neighbors[author_id].items()
if collaborator_id in target_ids
}
monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates)
monkeypatch.setattr(
logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets
)
result = asyncio.run(
logic.get_verified_staff_with_collab_graph(staff, "I123")
)
assert result == [
{
"staff_index": 0,
"staff": staff[0],
"openalex_ids": ["https://openalex.org/A1"],
"collaboration_evidence": [
{
"openalex_id": "https://openalex.org/A1",
"collaborator_openalex_id": "https://openalex.org/B1",
"shared_work_weight": 2.5,
}
],
}
]
def test_get_verified_staff_with_collab_graph_respects_query_concurrency(
monkeypatch,
):
staff = [{"name": "Person One"}, {"name": "Person Two"}]
active_queries = 0
peak_queries = 0
async def tracked(result):
nonlocal active_queries, peak_queries
active_queries += 1
peak_queries = max(peak_queries, active_queries)
try:
await asyncio.sleep(0.001)
return result
finally:
active_queries -= 1
async def resolve_author_candidates(name, institution_id):
author_id = "https://openalex.org/A1" if name == "person one" else "https://openalex.org/A2"
return await tracked([author_id])
async def get_collaborator_weights_for_targets(
author_id, institution_id, target_ids
):
neighbor_id = (
"https://openalex.org/A2"
if author_id == "https://openalex.org/A1"
else "https://openalex.org/A1"
)
return await tracked(
{neighbor_id: 1.0} if neighbor_id in target_ids else {}
)
monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates)
monkeypatch.setattr(
logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets
)
result = asyncio.run(
logic.get_verified_staff_with_collab_graph(
staff,
"I123",
max_concurrent_queries=1,
)
)
assert len(result) == 2
assert peak_queries == 1
def test_get_collaborator_weights_for_targets_uses_bounded_aggregation(
monkeypatch,
):
captured = {}
async def fake_search(**kwargs):
captured.update(kwargs)
return {
"aggregations": {
"collaborators": {
"targets": {
"buckets": [
{"key": "https://openalex.org/B1", "doc_count": 7},
]
}
}
}
}
monkeypatch.setattr(logic, "search", fake_search)
result = asyncio.run(
logic.get_collaborator_weights_for_targets(
"https://openalex.org/A1",
"I123",
{"https://openalex.org/B1", "https://openalex.org/A1"},
)
)
assert result == {"https://openalex.org/B1": 7.0}
body = captured["body"]
assert body["size"] == 0
nested = body["aggs"]["collaborators"]
assert nested["nested"] == {"path": "authorships"}
assert nested["aggs"]["targets"]["terms"]["include"] == [
"https://openalex.org/B1"
]
assert "query" in body
def test_get_collaborator_weights_for_targets_without_targets_skips_request(
monkeypatch,
):
async def fail_search(**kwargs):
raise AssertionError("search must not be called")
monkeypatch.setattr(logic, "search", fail_search)
result = asyncio.run(
logic.get_collaborator_weights_for_targets(
"https://openalex.org/A1", "I123", set()
)
)
assert result == {}
def test_update_hierarchy_removes_deleted_nodes_and_edit_markers(tmp_path, monkeypatch): def test_update_hierarchy_removes_deleted_nodes_and_edit_markers(tmp_path, monkeypatch):
monkeypatch.setattr(logic, "HIERARCHIES_DIR", tmp_path) monkeypatch.setattr(logic, "HIERARCHIES_DIR", tmp_path)
+81 -1
View File
@@ -15,14 +15,20 @@ from inse.exceptions import (
NotFoundException, NotFoundException,
) )
from inse.integrations import elasticsearch from inse.integrations import elasticsearch
from inse.model import ESIndex from inse.model import ESCluster, ESIndex
from inse.models.openalex.author import Author from inse.models.openalex.author import Author
from inse.models.openalex.authors_list_response import AuthorsListResponse from inse.models.openalex.authors_list_response import AuthorsListResponse
from inse.models.openalex.meta import Meta from inse.models.openalex.meta import Meta
from inse.orgminer.institutions_helper import (
DEFAULT_INSTITUTION_ID,
normalize_org_uri,
strip_openalex_prefix,
)
from inse.persons.model import ( from inse.persons.model import (
CareerMetrics, CareerMetrics,
CustomAuthor, CustomAuthor,
CustomAuthorsListResponse, CustomAuthorsListResponse,
VerifiedOrganization,
) )
from inse.persons.query_builder import build_authors_search_rescored from inse.persons.query_builder import build_authors_search_rescored
from inse.works.logic import enrich_topic_descriptions from inse.works.logic import enrich_topic_descriptions
@@ -32,6 +38,80 @@ from .. import config, util
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors" INDEX_NAME = "openalex-authors"
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
VERIFIED_PERSONS_INDEX = "orgminer_verified_persons_ude"
VERIFIED_PERSONS_INSTITUTION_ID = DEFAULT_INSTITUTION_ID
VERIFIED_PERSON_FIELDS = [
"openalex_id",
"organization",
"org_name",
"org_uri",
"org_hierarchy_path",
"verified_at",
]
async def get_verified_organizations(author_id: str) -> list[VerifiedOrganization]:
"""Return organizations where ``author_id`` is a verified staff member.
Reads the OrgMiner verified-persons index on the INSE cluster. Documents are
keyed by the person's OpenAlex id field (both raw and full-URL forms are
accepted), so the lookup does not depend on the index's ``_id`` scheme.
An unavailable index must not break the person page, so failures are logged
and reported as "not verified".
"""
short_id = strip_openalex_prefix(author_id.strip().rstrip("/"))
if not short_id:
return []
query = {
"_source": VERIFIED_PERSON_FIELDS,
"size": 50,
"query": {
"terms": {
"openalex_id": [short_id, f"https://openalex.org/{short_id}"]
}
},
"sort": [
{"verified_at": {"order": "desc", "missing": "_last"}},
{"organization.keyword": {"order": "asc", "missing": "_last"}},
],
}
try:
data = await elasticsearch.search(
body=query, index=VERIFIED_PERSONS_INDEX, cluster=ESCluster.INSE
)
except Exception:
logger.exception(
"Verified-organization lookup failed for author %r.", author_id
)
return []
organizations: dict[str, VerifiedOrganization] = {}
for hit in data.get("hits", {}).get("hits", []):
source = hit.get("_source") or {}
org_uri = normalize_org_uri(source.get("org_uri"))
org_name = (
source.get("organization") or source.get("org_name") or ""
).strip()
key = org_uri or org_name.casefold()
if not key:
continue
# Old sha256-ID and new person-level documents can coexist until the
# index is rebuilt. The newest document wins because of the sort above.
organizations.setdefault(
key,
VerifiedOrganization(
org_name=org_name or org_uri or "Unbekannte Organisation",
org_uri=org_uri,
org_hierarchy_path=source.get("org_hierarchy_path") or [],
verified_at=source.get("verified_at"),
),
)
return list(organizations.values())
async def find_ude_author_by_name(display_name: str) -> dict | None: async def find_ude_author_by_name(display_name: str) -> dict | None:
+27
View File
@@ -4,6 +4,8 @@ Data models for persons / authors.
""" """
from datetime import datetime
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from inse.models.openalex.author import Author from inse.models.openalex.author import Author
@@ -71,6 +73,31 @@ class PersonBio(BaseModel):
bio: str = Field(description="The generated biography.") bio: str = Field(description="The generated biography.")
class VerifiedOrganization(BaseModel):
org_name: str = Field(description="Display name of the verified organization.")
org_uri: str | None = Field(
default=None, description="Organization URL, normalized for hierarchy matching."
)
org_hierarchy_path: list[str] = Field(
default_factory=list,
description="Path from the hierarchy root to the organization node.",
)
verified_at: datetime | None = Field(
default=None, description="When the organization membership was verified."
)
class VerifiedOrganizationsResponse(BaseModel):
institution_id: str | None = Field(
default=None,
description="OpenAlex institution ID that the verified memberships belong to.",
)
organizations: list[VerifiedOrganization] = Field(
default_factory=list,
description="Organizations where the person has verified staff membership.",
)
class PersonFilters(BaseModel): class PersonFilters(BaseModel):
institution: str | None = None institution: str | None = None
cited_by_count: int | None = None cited_by_count: int | None = None
+19
View File
@@ -75,6 +75,25 @@ async def get_person_by_id(
return await logic.get_person_by_id(author_id=id, include=include) return await logic.get_person_by_id(author_id=id, include=include)
@router.get(
"/person/{id}/verified-organizations",
operation_id="getVerifiedOrganizations",
response_model=model.VerifiedOrganizationsResponse,
summary="Returns the organizations where a person is a verified staff member.",
tags=["Persons"],
)
async def get_verified_organizations(
id: Annotated[
str, Path(description="OpenAlex author ID", example=["A5093075883"])
],
):
organizations = await logic.get_verified_organizations(author_id=id)
return model.VerifiedOrganizationsResponse(
institution_id=logic.VERIFIED_PERSONS_INSTITUTION_ID,
organizations=organizations,
)
@router.get( @router.get(
"/persons/searchByName", "/persons/searchByName",
operation_id="searchPersonsByName", operation_id="searchPersonsByName",
@@ -0,0 +1,119 @@
import asyncio
from inse.model import ESCluster
from inse.persons import logic, service
def _hit(
*,
org_name: str,
org_uri: str | None,
verified_at: str | None = "2026-01-02T03:04:05Z",
) -> dict:
return {
"_source": {
"openalex_id": "https://openalex.org/A5018971503",
"org_name": org_name,
"org_uri": org_uri,
"org_hierarchy_path": ["Fakultät", org_name],
"verified_at": verified_at,
}
}
def test_get_verified_organizations_uses_person_id_field_and_deduplicates(monkeypatch):
calls: list[dict] = []
async def fake_search(**kwargs):
calls.append(kwargs)
return {
"hits": {
"hits": [
_hit(
org_name="Zentrum für Mikroskopie",
org_uri="https://www.uni-due.de/zmb/",
),
# Same organization from an older sha256-ID document.
_hit(
org_name="Zentrum für Mikroskopie",
org_uri="https://www.uni-due.de/zmb/index",
),
_hit(org_name="Institut für Physik", org_uri=None),
_hit(org_name="Institut für Physik", org_uri=None),
]
}
}
monkeypatch.setattr(logic.elasticsearch, "search", fake_search)
result = asyncio.run(
logic.get_verified_organizations("https://openalex.org/A5018971503")
)
assert len(calls) == 1
assert calls[0]["index"] == logic.VERIFIED_PERSONS_INDEX
assert calls[0]["cluster"] == ESCluster.INSE
assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [
"A5018971503",
"https://openalex.org/A5018971503",
]
assert [organization.org_name for organization in result] == [
"Zentrum für Mikroskopie",
"Institut für Physik",
]
assert result[0].org_uri == "https://www.uni-due.de/zmb"
assert result[0].org_hierarchy_path == [
"Fakultät",
"Zentrum für Mikroskopie",
]
assert result[0].verified_at is not None
def test_get_verified_organizations_accepts_raw_author_id(monkeypatch):
calls: list[dict] = []
async def fake_search(**kwargs):
calls.append(kwargs)
return {"hits": {"hits": []}}
monkeypatch.setattr(logic.elasticsearch, "search", fake_search)
assert asyncio.run(logic.get_verified_organizations(" A5018971503/ ")) == []
assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [
"A5018971503",
"https://openalex.org/A5018971503",
]
def test_get_verified_organizations_returns_empty_on_search_failure(monkeypatch):
async def failing_search(**kwargs):
raise RuntimeError("INSE is unavailable")
monkeypatch.setattr(logic.elasticsearch, "search", failing_search)
assert asyncio.run(logic.get_verified_organizations("A5018971503")) == []
def test_get_verified_organizations_skips_search_without_author_id(monkeypatch):
async def unexpected_search(**kwargs):
raise AssertionError("search must not be called without an author id")
monkeypatch.setattr(logic.elasticsearch, "search", unexpected_search)
assert asyncio.run(logic.get_verified_organizations(" ")) == []
def test_service_response_includes_verified_data_institution(monkeypatch):
async def fake_get_verified_organizations(author_id: str):
return []
monkeypatch.setattr(
logic, "get_verified_organizations", fake_get_verified_organizations
)
response = asyncio.run(
service.get_verified_organizations(id="A5018971503")
)
assert response.institution_id == logic.VERIFIED_PERSONS_INSTITUTION_ID
assert response.organizations == []
@@ -356,6 +356,8 @@ model/userRole.ts
model/validationError.ts model/validationError.ts
model/validationErrorLocInner.ts model/validationErrorLocInner.ts
model/value.ts model/value.ts
model/verifiedOrganization.ts
model/verifiedOrganizationsResponse.ts
model/work.ts model/work.ts
model/workBiblio.ts model/workBiblio.ts
model/workCitationNormalizedPercentile.ts model/workCitationNormalizedPercentile.ts
+57
View File
@@ -24,6 +24,8 @@ import { CustomAuthorsListResponse } from '../model/customAuthorsListResponse';
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { PersonBio } from '../model/personBio'; import { PersonBio } from '../model/personBio';
// @ts-ignore
import { VerifiedOrganizationsResponse } from '../model/verifiedOrganizationsResponse';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -747,4 +749,59 @@ export class PersonsService extends BaseService {
); );
} }
/**
* Returns the organizations where a person is a verified staff member.
* @endpoint get /api/inse-service/person/{id}/verified-organizations
* @param id OpenAlex author ID
* @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 getVerifiedOrganizations(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<VerifiedOrganizationsResponse>;
public getVerifiedOrganizations(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<VerifiedOrganizationsResponse>>;
public getVerifiedOrganizations(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<VerifiedOrganizationsResponse>>;
public getVerifiedOrganizations(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getVerifiedOrganizations.');
}
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/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/verified-organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<VerifiedOrganizationsResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
} }
+2
View File
@@ -319,6 +319,8 @@ export * from './userRole';
export * from './validationError'; export * from './validationError';
export * from './validationErrorLocInner'; export * from './validationErrorLocInner';
export * from './value'; export * from './value';
export * from './verifiedOrganization';
export * from './verifiedOrganizationsResponse';
export * from './work'; export * from './work';
export * from './workBiblio'; export * from './workBiblio';
export * from './workCitationNormalizedPercentile'; export * from './workCitationNormalizedPercentile';
@@ -0,0 +1,24 @@
/**
* 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 VerifiedOrganization {
/**
* Display name of the verified organization.
*/
org_name: string;
org_uri?: string | null;
/**
* Path from the hierarchy root to the organization node.
*/
org_hierarchy_path?: Array<string>;
verified_at?: string | null;
}
@@ -0,0 +1,23 @@
/**
* 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 { VerifiedOrganization } from './verifiedOrganization';
export interface VerifiedOrganizationsResponse {
/**
* OpenAlex institution ID that the verified memberships belong to.
*/
institution_id?: string | null;
/**
* Organizations where the person has verified staff membership.
*/
organizations?: Array<VerifiedOrganization>;
}
+30 -11
View File
@@ -151,9 +151,9 @@ export const routes: Routes = [
]), ]),
], ],
loadComponent: () => loadComponent: () =>
import( import('./modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component').then(
'./modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component' (mod) => mod.MultipliersDashboardComponent,
).then((mod) => mod.MultipliersDashboardComponent), ),
resolve: { resolve: {
researchers: multiplicatorResearchersResolver, researchers: multiplicatorResearchersResolver,
}, },
@@ -170,9 +170,9 @@ export const routes: Routes = [
]), ]),
], ],
loadComponent: () => loadComponent: () =>
import( import('./modules/founder-potential/founder-dashboard/founder-dashboard.component').then(
'./modules/founder-potential/founder-dashboard/founder-dashboard.component' (mod) => mod.FounderDashboardComponent,
).then((mod) => mod.FounderDashboardComponent), ),
resolve: { resolve: {
statistics: founderStatisticsResolver, statistics: founderStatisticsResolver,
candidates: founderCandidatesResolver, candidates: founderCandidatesResolver,
@@ -180,7 +180,7 @@ export const routes: Routes = [
runGuardsAndResolvers: 'paramsOrQueryParamsChange', runGuardsAndResolvers: 'paramsOrQueryParamsChange',
}, },
{ {
path: 'founders/:authorId', path: 'collaboration-network/:authorId',
canActivate: [ canActivate: [
roleGuard([ roleGuard([
UserRole.User, UserRole.User,
@@ -190,9 +190,9 @@ export const routes: Routes = [
]), ]),
], ],
loadComponent: () => loadComponent: () =>
import( import('./modules/founder-potential/researcher-network/researcher-network.component').then(
'./modules/founder-potential/researcher-network/researcher-network.component' (mod) => mod.ResearcherNetworkComponent,
).then((mod) => mod.ResearcherNetworkComponent), ),
resolve: { resolve: {
page: multiplierResearcherPageResolver, page: multiplierResearcherPageResolver,
}, },
@@ -284,7 +284,26 @@ export const routes: Routes = [
hierarchyData: hierarchyResolver, hierarchyData: hierarchyResolver,
suggestions: suggestionResolver, suggestions: suggestionResolver,
}, },
runGuardsAndResolvers: 'always', // Chart navigation only changes `path`/`lang`; do not refetch the whole
// hierarchy on every node click. An explicit same-URL reload (used by
// `reloadSuggestions`) still re-runs the resolvers.
runGuardsAndResolvers: (from, to) => {
if (from.routeConfig !== to.routeConfig) return true;
const keys = new Set([
...from.queryParamMap.keys,
...to.queryParamMap.keys,
]);
const changedKeys = [...keys].filter(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
// No query change at all -> explicit same-URL reload.
if (changedKeys.length === 0) return true;
// Only the chart's own state changed -> keep the loaded hierarchy.
return changedKeys.some((key) => key !== 'path' && key !== 'lang');
},
loadComponent: () => loadComponent: () =>
import('./modules/hierarchy/hierarchy.component').then( import('./modules/hierarchy/hierarchy.component').then(
(mod) => mod.HierarchyComponent, (mod) => mod.HierarchyComponent,
@@ -8,7 +8,7 @@ import {
effect, effect,
inject, inject,
} from '@angular/core'; } from '@angular/core';
import { ResolverStateService } from '../../app/shared/services/resolver-state.service'; import { NavigationStateService } from '../../app/shared/services/navigation-state.service';
@Directive({ @Directive({
selector: 'span, [skText]', selector: 'span, [skText]',
@@ -19,11 +19,11 @@ export class SkTextDirective implements OnChanges {
private readonly el = inject(ElementRef<HTMLElement>); private readonly el = inject(ElementRef<HTMLElement>);
private readonly renderer = inject(Renderer2); private readonly renderer = inject(Renderer2);
private readonly resolverStateService = inject(ResolverStateService); private readonly navigationState = inject(NavigationStateService);
constructor() { constructor() {
effect(() => { effect(() => {
const loading = this.skText || this.resolverStateService.isResolving(); const loading = this.skText || this.navigationState.isResolving();
if (loading) { if (loading) {
this.showSkeleton(); this.showSkeleton();
@@ -38,7 +38,7 @@ export class SkTextDirective implements OnChanges {
return; return;
} }
if (this.skText || this.resolverStateService.isResolving()) { if (this.skText || this.navigationState.isResolving()) {
this.showSkeleton(); this.showSkeleton();
} else { } else {
this.hideSkeleton(); this.hideSkeleton();
@@ -0,0 +1,58 @@
import { Directive, ElementRef, inject } from '@angular/core';
const PASSIVE_WHEEL_SELECTOR = '[data-passive-wheel]';
let wheelPatchInstalled = false;
/**
* Chrome flags non-passive `wheel`/`mousewheel` listeners as scroll-blocking.
* zrender (ECharts) mounts them on the chart's inner viewport without listener
* options. The hierarchy tree only uses `roam: 'move'` and never calls
* `preventDefault()` on wheel events, so marking them passive is safe.
*
* The patch is global but only affects wheel listeners inside an element that
* carries this directive.
*/
function installPassiveWheelPatch(): void {
if (wheelPatchInstalled) return;
wheelPatchInstalled = true;
const nativeAddEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (
this: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions,
): void {
const isWheelEvent = type === 'wheel' || type === 'mousewheel';
const hasOptions = options !== undefined && typeof options !== 'boolean';
if (
isWheelEvent &&
!hasOptions &&
this instanceof Element &&
this.closest(PASSIVE_WHEEL_SELECTOR)
) {
nativeAddEventListener.call(this, type, listener, {
capture: options === true,
passive: true,
});
return;
}
nativeAddEventListener.call(this, type, listener, options);
};
}
@Directive({
selector: '[appPassiveWheel]',
standalone: true,
})
export class PassiveWheelDirective {
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
this.host.nativeElement.setAttribute('data-passive-wheel', '');
installPassiveWheelPatch();
}
}
@@ -69,7 +69,7 @@
<button <button
mat-icon-button mat-icon-button
type="button" type="button"
aria-label="Impersonate" aria-label="Als diesen Account anmelden"
matTooltip="Als dieser Account anmelden (Impersonation)" matTooltip="Als dieser Account anmelden (Impersonation)"
[disabled]="!canImpersonate(row)" [disabled]="!canImpersonate(row)"
(click)="impersonate(row)"> (click)="impersonate(row)">
@@ -44,10 +44,17 @@ export class DashboardComponent implements OnInit {
ngOnInit() { ngOnInit() {
this.restoreTreemapNodeState(); this.restoreTreemapNodeState();
this.dashboard.initialize((institutionId) => { this.dashboard.initialize((institutionId, source) => {
if (institutionId === this.selectedAnalyticalInstitutionId) return; const changed = institutionId !== this.selectedAnalyticalInstitutionId;
this.selectedAnalyticalInstitutionId = institutionId; this.selectedAnalyticalInstitutionId = institutionId;
this.reloadAnalyticalData(); // When the organization was auto-selected from the account (no explicit
// URL parameter), persist it so the URL reflects the current state.
if (source === 'default' && institutionId) {
this.updateDashboardPeriodUrl();
}
if (changed) {
this.reloadAnalyticalData();
}
}); });
} }
@@ -21,6 +21,10 @@ import {
TopAuthorStatistics, TopAuthorStatistics,
} from '../dashboard-statistics.service'; } from '../dashboard-statistics.service';
import { mapProjectTopicsToTreemap } from './dashboard-topic-treemap.mapper'; import { mapProjectTopicsToTreemap } from './dashboard-topic-treemap.mapper';
import { CredentialService } from '../../../shared/services/credential.service';
/** Where the initially selected institution came from. */
export type InstitutionRestoreSource = 'url' | 'default';
@Injectable() @Injectable()
export class DashboardFacade { export class DashboardFacade {
@@ -88,9 +92,15 @@ export class DashboardFacade {
constructor( constructor(
private readonly statisticsService: DashboardStatisticsService, private readonly statisticsService: DashboardStatisticsService,
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
private readonly credentials: CredentialService,
) {} ) {}
initialize(onInstitutionRestored: (institutionId: string) => void): void { initialize(
onInstitutionRestored: (
institutionId: string,
source: InstitutionRestoreSource,
) => void,
): void {
this.restorePeriodState(); this.restorePeriodState();
this.loadStatistics(); this.loadStatistics();
this.loadInstitutions(onInstitutionRestored); this.loadInstitutions(onInstitutionRestored);
@@ -191,7 +201,10 @@ export class DashboardFacade {
} }
private loadInstitutions( private loadInstitutions(
onInstitutionRestored: (institutionId: string) => void, onInstitutionRestored: (
institutionId: string,
source: InstitutionRestoreSource,
) => void,
): void { ): void {
this.institutionsLoading = true; this.institutionsLoading = true;
this.institutionsError = false; this.institutionsError = false;
@@ -202,18 +215,23 @@ export class DashboardFacade {
next: (institutions) => { next: (institutions) => {
this.institutions = institutions; this.institutions = institutions;
const requestedInstitution = const requestedInstitution =
this.route.snapshot.queryParamMap.get('institution') ?? 'all'; this.route.snapshot.queryParamMap.get('institution');
const restoredInstitution = institutions.some( // An explicit URL parameter wins; otherwise start with the logged-in
(institution) => institution.id === requestedInstitution, // person's organization (the effective institution, which follows
) // impersonation) and fall back to all institutions.
? requestedInstitution const restoredInstitution = requestedInstitution
: 'all'; ? this.findInstitution(institutions, requestedInstitution) ?? 'all'
: this.findInstitution(
institutions,
this.credentials.effectiveInstitutionId(),
) ?? 'all';
if (restoredInstitution !== this.selectedInstitutionId) { if (restoredInstitution !== this.selectedInstitutionId) {
this.selectedInstitutionId = restoredInstitution; this.selectedInstitutionId = restoredInstitution;
this.loadStatistics(); this.loadStatistics();
} }
onInstitutionRestored( onInstitutionRestored(
restoredInstitution === 'all' ? '' : restoredInstitution, restoredInstitution === 'all' ? '' : restoredInstitution,
requestedInstitution ? 'url' : 'default',
); );
}, },
error: () => { error: () => {
@@ -223,6 +241,16 @@ export class DashboardFacade {
}); });
} }
private findInstitution(
institutions: DashboardInstitution[],
institutionId: string | null | undefined,
): string | undefined {
if (!institutionId) return undefined;
return institutions.some((institution) => institution.id === institutionId)
? institutionId
: undefined;
}
private loadDfgProjectTopics( private loadDfgProjectTopics(
period: DashboardPeriodBounds, period: DashboardPeriodBounds,
institutionId: string, institutionId: string,
@@ -3,8 +3,17 @@
title="Wer hat Gründungspotenzial?" title="Wer hat Gründungspotenzial?"
subtitle="Kandidat:innen für Gründungsgespräche und -angebote." subtitle="Kandidat:innen für Gründungsgespräche und -angebote."
[titleTooltip]="pageTooltip"> [titleTooltip]="pageTooltip">
<button
pageActions
mat-stroked-button
color="primary"
type="button"
(click)="openExplainer()">
<mat-icon>{{ INSIGHTS_ICON }}</mat-icon>
Erklären
</button>
<div class="founder-dashboard"> <div class="founder-dashboard">
@if (hasData() && hasScores()) { @if (hasData()) {
<section class="statistics-grid" aria-label="Kennzahlen"> <section class="statistics-grid" aria-label="Kennzahlen">
<app-dashboard-statistic-card <app-dashboard-statistic-card
label="Forschende gesamt" label="Forschende gesamt"
@@ -25,27 +34,18 @@
[detail]="scoreableDetail()" /> [detail]="scoreableDetail()" />
<app-dashboard-statistic-card <app-dashboard-statistic-card
label="Unauffällige Profile" label="Top Kandidat:innen"
[value]="kpis().passed"
[icon]="VERIFIED_ICON"
variant="quality"
[ariaLabel]="'Unauffällige Profile: ' + fmtInt(kpis().passed)"
[tooltip]="qualityTooltip()"
[detail]="qualityDetail()" />
<app-dashboard-statistic-card
label="Auf der Shortlist"
[value]="kpis().shortlisted" [value]="kpis().shortlisted"
[icon]="STAR_ICON" [icon]="STAR_ICON"
variant="shortlist" variant="shortlist"
[ariaLabel]="'Auf der Shortlist: ' + fmtInt(kpis().shortlisted)" [ariaLabel]="'Top Kandidat:innen: ' + fmtInt(kpis().shortlisted)"
[tooltip]="shortlistTooltip()" [tooltip]="shortlistTooltip()"
[detail]="shortlistDetail()" /> [detail]="shortlistDetail()" />
</section> </section>
<section class="shortlist-section"> <section class="shortlist-section">
<div class="section-heading"> <div class="section-heading">
<h2>Shortlist: Top-Kandidat:innen</h2> <h2>Top-Kandidat:innen</h2>
<mat-icon <mat-icon
class="info-icon" class="info-icon"
[matTooltip]="shortlistSectionTooltip" [matTooltip]="shortlistSectionTooltip"
@@ -55,6 +55,8 @@
</mat-icon> </mat-icon>
</div> </div>
<app-founder-filters [statistics]="statistics()" />
<div class="controls"> <div class="controls">
<span class="controls__range"> <span class="controls__range">
Mindestwert Mindestwert
@@ -66,20 +68,29 @@
{{ INFO_OUTLINE_ICON }} {{ INFO_OUTLINE_ICON }}
</mat-icon> </mat-icon>
</span> </span>
<mat-slide-toggle
[checked]="thresholdEnabled()"
(change)="onThresholdEnabledChange($event.checked)"
[matTooltip]="thresholdToggleTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
Aktiv
</mat-slide-toggle>
<mat-slider <mat-slider
class="controls__slider" class="controls__slider"
[min]="50" [min]="50"
[max]="100" [max]="100"
[step]="1" [step]="1"
[discrete]="true" [discrete]="true"
[displayWith]="formatThreshold"> [displayWith]="formatThreshold"
[disabled]="!thresholdEnabled()">
<input <input
matSliderThumb matSliderThumb
[value]="thresholdDraft()" [value]="thresholdDraft()"
(valueChange)="onSliderInput($event)" (valueChange)="onSliderInput($event)"
(dragEnd)="onSliderCommit($event.value)" (dragEnd)="onSliderCommit($event.value)"
(keyup)="onSliderCommit()" (keyup)="onSliderCommit()"
aria-label="Mindestwert für die Shortlist" /> aria-label="Mindestwert für die Liste der Top-Kandidat:innen" />
</mat-slider> </mat-slider>
<span class="controls__value">{{ thresholdDraft() }}</span> <span class="controls__value">{{ thresholdDraft() }}</span>
<mat-slide-toggle <mat-slide-toggle
@@ -101,14 +112,13 @@
<app-data-table <app-data-table
[columns]="columns()" [columns]="columns()"
[data]="rows()" [data]="rows()"
[selectedRow]="selectedRow()" [detailTemplate]="detailTemplate()"
queryParamSortKey="sortBy" queryParamSortKey="sortBy"
queryParamSortDirectionKey="sortOrder" queryParamSortDirectionKey="sortOrder" />
(rowClick)="selectCandidate($event.candidate.author_id)" />
} @else { } @else {
<div class="list__empty"> <div class="list__empty">
<p>{{ emptyListMessage() }}</p> <p>{{ emptyListMessage() }}</p>
@if (threshold() > 50) { @if (thresholdEnabled() && threshold() > 50) {
<button <button
mat-stroked-button mat-stroked-button
color="primary" color="primary"
@@ -122,153 +132,10 @@
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
@if (selectedRow(); as row) {
<mat-card appearance="outlined" class="card">
<mat-card-content>
<div class="card__head">
<div>
<span class="card__eyebrow">Ausgewählt</span>
<h3>{{ row.name }}</h3>
<div class="card__meta">
<span
class="card__career"
[matTooltip]="careerBucketTooltip(row.candidate.career_bucket)"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
{{ row.candidate.career_bucket ?? '–' }}
</span>
@if (row.areaLabel) {
· {{ row.areaLabel }}
}
· {{ fmtInt(row.candidate.active_years) }} Jahre mit
Publikationen
@if (!row.candidate.screen.passed && row.flagLabel) {
·
<span
class="card__flag"
[matTooltip]="flagTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
auffällig: {{ row.flagLabel }}
</span>
}
</div>
</div>
</div>
<p class="score-caption">
Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten.
90 heißt: stärker als 90 % der Vergleichsgruppe.
</p>
<div class="score-tiles">
<div
class="score-tile score-tile--primary"
[matTooltip]="scoreTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Potenzial</span>
<strong>{{ fmt1(row.score) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 1 Jahr</span>
<strong>{{ fmt1(row.within[0]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 3 Jahre</span>
<strong>{{ fmt1(row.within[1]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 5 Jahre</span>
<strong>{{ fmt1(row.within[2]) }}</strong>
</div>
</div>
<div class="facts">
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Publikationen der Person."
matTooltipClass="sg-tooltip-wide">
Publikationen
<b>{{
fmtInt(row.candidate.founder_features?.publications)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Patente mit Bezug zur Einrichtung."
matTooltipClass="sg-tooltip-wide">
Patente
<b>{{
fmtInt(row.candidate.founder_features?.patents)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Arbeiten mit Beteiligung aus Unternehmen."
matTooltipClass="sg-tooltip-wide">
Arbeiten mit Industrie
<b>{{
fmtInt(
row.candidate.founder_features?.industry_collab_papers
)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Förderprojekte."
matTooltipClass="sg-tooltip-wide">
Förderprojekte
<b>{{
fmtInt(row.candidate.founder_features?.grants)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Jahre mit mindestens einer Publikation."
matTooltipClass="sg-tooltip-wide">
Aktive Jahre
<b>{{ fmtInt(row.candidate.active_years) }}</b>
</app-chip>
</div>
</mat-card-content>
</mat-card>
}
<app-query-param-paginator <app-query-param-paginator
[total]="total()" [total]="total()"
[pageSizeOptions]="[10, 25, 50]" /> [pageSizeOptions]="[10, 25, 50]" />
</section> </section>
} @else if (hasData()) {
<mat-card appearance="outlined" class="empty-state">
<mat-card-content>
<mat-icon class="empty-state__icon">{{ FOUNDER_ICON }}</mat-icon>
<h2>Noch keine Gründungspotenzial-Scores</h2>
<p>
Für die <strong>{{ universityName() }}</strong> liegen Forschungsdaten
vor, aber die Gründungspotenzial-Auswertung wurde noch nicht
berechnet. Sobald sie vorliegt, erscheinen hier die Kandidat:innen und
ihre Werte.
</p>
</mat-card-content>
</mat-card>
} @else { } @else {
<mat-card appearance="outlined" class="empty-state"> <mat-card appearance="outlined" class="empty-state">
<mat-card-content> <mat-card-content>
@@ -305,7 +172,17 @@
</ng-template> </ng-template>
<ng-template #scoreTemplate let-row> <ng-template #scoreTemplate let-row>
<span class="list__score-value">{{ fmt1(row.score) }}</span> @if (row.score === null) {
<span
class="list__score-missing"
[matTooltip]="row.notScoredReason"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
(nicht bewertet)
</span>
} @else {
<span class="list__score-value">{{ fmt1(row.score) }}</span>
}
</ng-template> </ng-template>
<ng-template #withinTemplate let-row> <ng-template #withinTemplate let-row>
@@ -366,3 +243,124 @@
</mat-icon> </mat-icon>
</span> </span>
</ng-template> </ng-template>
<ng-template #rowDetailTemplate let-row>
<div class="row-detail">
<div class="row-detail__head">
<span class="row-detail__eyebrow">Details</span>
<a
class="author-name author-link"
[routerLink]="['/person', row.candidate.author_id, 'overview']"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: row.candidate.author_id }"
tooltipMaxWidth="500px"
[title]="row.name"
(click)="$event.stopPropagation()">
<h3>{{ row.name }}</h3>
</a>
<div class="row-detail__meta">
<span
class="row-detail__career"
[matTooltip]="careerBucketTooltip(row.candidate.career_bucket)"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
{{ row.candidate.career_bucket ?? '–' }}
</span>
@if (row.areaLabel) {
· {{ row.areaLabel }}
}
· {{ fmtInt(row.candidate.active_years) }} Jahre mit Publikationen
</div>
</div>
<p class="score-caption">
Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten. 90
heißt: stärker als 90 % der Vergleichsgruppe.
</p>
<div class="score-tiles">
<div
class="score-tile score-tile--primary"
[matTooltip]="row.notScoredReason ?? scoreTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Potenzial</span>
@if (row.score === null) {
<strong class="score-tile__missing">(nicht bewertet)</strong>
} @else {
<strong>{{ fmt1(row.score) }}</strong>
}
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 1 Jahr</span>
<strong>{{ fmt1(row.within[0]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 3 Jahre</span>
<strong>{{ fmt1(row.within[1]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 5 Jahre</span>
<strong>{{ fmt1(row.within[2]) }}</strong>
</div>
</div>
<div class="facts">
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Publikationen der Person."
matTooltipClass="sg-tooltip-wide">
Publikationen
<b>{{ fmtInt(row.candidate.founder_features?.publications) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Patente mit Bezug zur Einrichtung."
matTooltipClass="sg-tooltip-wide">
Patente
<b>{{ fmtInt(row.candidate.founder_features?.patents) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Arbeiten mit Beteiligung aus Unternehmen."
matTooltipClass="sg-tooltip-wide">
Arbeiten mit Industrie
<b>{{
fmtInt(row.candidate.founder_features?.industry_collab_papers)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Förderprojekte."
matTooltipClass="sg-tooltip-wide">
Förderprojekte
<b>{{ fmtInt(row.candidate.founder_features?.grants) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Jahre mit mindestens einer Publikation."
matTooltipClass="sg-tooltip-wide">
Aktive Jahre
<b>{{ fmtInt(row.candidate.active_years) }}</b>
</app-chip>
</div>
</div>
</ng-template>
@@ -142,6 +142,10 @@
color: var(--sg-text); color: var(--sg-text);
} }
tr.detail-row .mat-mdc-cell {
padding: 0;
}
.mat-column-name { .mat-column-name {
width: 32%; width: 32%;
} }
@@ -205,7 +209,7 @@
} }
.list__career, .list__career,
.card__career { .row-detail__career {
cursor: help; cursor: help;
text-decoration: underline dotted; text-decoration: underline dotted;
text-underline-offset: 2px; text-underline-offset: 2px;
@@ -220,6 +224,14 @@
text-align: right; text-align: right;
} }
.list__score-missing {
color: var(--sg-text-soft);
font-size: 11.5px;
font-style: italic;
cursor: help;
white-space: nowrap;
}
.list__within-nums { .list__within-nums {
color: var(--sg-text-muted); color: var(--sg-text-muted);
font-size: 12px; font-size: 12px;
@@ -238,32 +250,28 @@
font-size: 13.5px; font-size: 13.5px;
} }
// -- Detail card -------------------------------------------------------- // -- Detail row ---------------------------------------------------------
.card { .row-detail {
margin-top: 16px; padding: 18px 20px 20px;
border-top: 1px solid var(--sg-border);
background: var(--sg-surface-muted); background: var(--sg-surface-muted);
.mat-mdc-card-content {
padding: 20px;
}
h3 { h3 {
margin: 0 0 2px; margin: 0 0 2px;
color: var(--sg-text); color: var(--sg-text);
font-size: 20px; font-size: 18px;
} }
} }
.card__head { .row-detail__head {
display: flex; display: flex;
flex-wrap: wrap; flex-direction: column;
align-items: flex-start; align-items: flex-start;
justify-content: space-between; gap: 2px;
gap: 12px;
} }
.card__eyebrow { .row-detail__eyebrow {
display: block; display: block;
margin-bottom: 2px; margin-bottom: 2px;
color: var(--sg-text-soft); color: var(--sg-text-soft);
@@ -273,17 +281,12 @@
text-transform: uppercase; text-transform: uppercase;
} }
.card__meta { .row-detail__meta {
margin-bottom: 16px; margin-bottom: 14px;
color: var(--sg-text-soft); color: var(--sg-text-soft);
font-size: 12.5px; font-size: 12.5px;
} }
.card__flag {
color: var(--sg-error);
cursor: help;
}
.score-caption { .score-caption {
margin: 0 0 12px; margin: 0 0 12px;
color: var(--sg-text-soft); color: var(--sg-text-soft);
@@ -325,6 +328,13 @@
&--primary strong { &--primary strong {
color: var(--sg-blue-highlight); color: var(--sg-blue-highlight);
} }
&__missing {
color: var(--sg-text-soft);
font-size: 15px;
font-weight: 600;
font-style: italic;
}
} }
.facts { .facts {
@@ -13,11 +13,14 @@ import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop'; import { toSignal } from '@angular/core/rxjs-interop';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSliderModule } from '@angular/material/slider'; import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { RouterLink } from '@angular/router';
import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component';
import { import {
FounderCandidate, FounderCandidate,
FounderCandidatePage, FounderCandidatePage,
@@ -42,18 +45,21 @@ import {
FOUNDER_ICON, FOUNDER_ICON,
HELP_OUTLINE_ICON, HELP_OUTLINE_ICON,
INFO_OUTLINE_ICON, INFO_OUTLINE_ICON,
INSIGHTS_ICON,
PERSONS_ICON, PERSONS_ICON,
STAR_ICON, STAR_ICON,
VERIFIED_ICON,
} from '../../../shared/ui/icons'; } from '../../../shared/ui/icons';
import { CredentialService } from '../../../shared/services/credential.service'; import { CredentialService } from '../../../shared/services/credential.service';
import { FounderExplainerPanelComponent } from './founder-explainer-panel/founder-explainer-panel.component';
import { FounderFiltersComponent } from '../founder-filters/founder-filters.component';
const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen'; const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen';
const DEFAULT_THRESHOLD = 90;
/** /**
* A shortlist row: the generated candidate plus only the values that the * A shortlist row: the generated candidate plus only the values that the
* table derives from it (display name, the 1/3/5-year slice, the headline * table derives from it (display name, the 1/3/5-year slice, and the reason a
* screen reason). Everything else is read from `candidate` directly. * profile has no score).
*/ */
interface FounderRow { interface FounderRow {
candidate: FounderCandidate; candidate: FounderCandidate;
@@ -61,7 +67,8 @@ interface FounderRow {
areaLabel: string | null; areaLabel: string | null;
score: number | null; score: number | null;
within: (number | null)[]; within: (number | null)[];
flagLabel: string | null; /** Explanation shown in the "(nicht bewertet)" tooltip; null when scored. */
notScoredReason: string | null;
} }
@Component({ @Component({
@@ -72,31 +79,36 @@ interface FounderRow {
MatCardModule, MatCardModule,
MatButtonModule, MatButtonModule,
MatIconModule, MatIconModule,
MatSlideToggleModule,
MatSliderModule, MatSliderModule,
MatSlideToggleModule,
MatTooltipModule, MatTooltipModule,
QueryParamPaginatorComponent, QueryParamPaginatorComponent,
ChipComponent, ChipComponent,
DataTableComponent, DataTableComponent,
DashboardStatisticCardComponent, DashboardStatisticCardComponent,
PageContainerComponent, PageContainerComponent,
RouterLink,
ComponentTooltipDirective,
FounderFiltersComponent,
], ],
templateUrl: './founder-dashboard.component.html', templateUrl: './founder-dashboard.component.html',
styleUrl: './founder-dashboard.component.scss', styleUrl: './founder-dashboard.component.scss',
}) })
export class FounderDashboardComponent { export class FounderDashboardComponent {
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly FOUNDER_ICON = FOUNDER_ICON; readonly FOUNDER_ICON = FOUNDER_ICON;
readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON; readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON;
readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON; readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON;
readonly INSIGHTS_ICON = INSIGHTS_ICON;
readonly PERSONS_ICON = PERSONS_ICON; readonly PERSONS_ICON = PERSONS_ICON;
readonly STAR_ICON = STAR_ICON; readonly STAR_ICON = STAR_ICON;
readonly VERIFIED_ICON = VERIFIED_ICON;
readonly statistics = input.required<FounderStatistics>(); readonly statistics = input.required<FounderStatistics>();
readonly candidates = input.required<FounderCandidatePage>(); readonly candidates = input.required<FounderCandidatePage>();
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private readonly dialog = inject(MatDialog);
private readonly credentials = inject(CredentialService, { optional: true }); private readonly credentials = inject(CredentialService, { optional: true });
/** The university whose cohort is shown; comes from the account profile. */ /** The university whose cohort is shown; comes from the account profile. */
@@ -113,22 +125,22 @@ export class FounderDashboardComponent {
initialValue: this.route.snapshot.queryParamMap, initialValue: this.route.snapshot.queryParamMap,
}); });
readonly threshold = computed( /** The threshold is opt-in: it only applies when the URL param is present. */
() => Math.max(50, Math.min(100, toNumber(this.queryParams().get('threshold')) ?? 90)), readonly thresholdEnabled = computed(
() => toNumber(this.queryParams().get('threshold')) !== null,
); );
readonly threshold = computed(() => {
const value = toNumber(this.queryParams().get('threshold'));
return value === null
? DEFAULT_THRESHOLD
: Math.max(50, Math.min(100, value));
});
readonly screened = computed( readonly screened = computed(
() => this.queryParams().get('screened') === 'true', () => this.queryParams().get('screened') === 'true',
); );
/** Live value while dragging the slider; committed to the URL on release. */
readonly thresholdDraft = signal<number>(90);
constructor() {
effect(() => this.thresholdDraft.set(this.threshold()), {
allowSignalWrites: true,
});
}
// -- Explanations (tooltips only) -------------------------------------- // -- Explanations (tooltips only) --------------------------------------
readonly pageTooltip = readonly pageTooltip =
@@ -140,28 +152,18 @@ export class FounderDashboardComponent {
readonly scoreableTooltip = readonly scoreableTooltip =
'Nur diese Personen haben genug Publikationen (mindestens 4), um vom Modell bewertet zu werden. Für alle anderen gibt es keinen Score.'; 'Nur diese Personen haben genug Publikationen (mindestens 4), um vom Modell bewertet zu werden. Für alle anderen gibt es keinen Score.';
readonly qualityTooltip = computed( readonly shortlistTooltip = computed(() => {
() => const thresholdPart = this.thresholdEnabled()
`${this.kpis().passed.toLocaleString('de-DE')} von ${this.kpis().total.toLocaleString('de-DE')} Forschenden (${this.kpis().share} %) haben ein vollständiges und plausibles Profil. Nur diese Werte sind gut belastbar.`, ? `Ab einem Rang von ${this.threshold()}.`
); : 'Ohne Mindestwert werden alle Profile angezeigt.';
const screenPart = this.screened()
readonly shortlistTooltip = computed( ? 'Auffällige Profile sind ausgeblendet.'
() => : 'Auffällige Profile sind enthalten.';
`Personen mit dem stärksten Gründungspotenzial. Angezeigt werden alle ab einem Rang von ${this.threshold()}. ${ return `Personen mit dem stärksten Gründungspotenzial. ${thresholdPart} ${screenPart}`;
this.screened() });
? 'Auffällige Profile sind ausgeblendet.'
: 'Auffällige Profile sind enthalten.'
}`,
);
readonly shortlistSectionTooltip = readonly shortlistSectionTooltip =
'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Regler legt fest, ab welchem Rang jemand in die Liste kommt.'; 'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Mindestwert ist optional: ohne ihn werden alle Profile angezeigt.';
readonly thresholdTooltip =
'Legt fest, ab welchem Rang Personen in der Shortlist erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte.';
readonly screeningTooltip =
'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Scores dieser Personen sind weniger verlässlich.';
readonly scoreTooltip = readonly scoreTooltip =
'Rang des Gründungspotenzials von 0 bis 100. 90 heißt: stärker als 90 % der rund 9.000 vergleichbaren Wissenschaftler:innen anderer Universitäten. Kein Wahrscheinlichkeitswert.'; 'Rang des Gründungspotenzials von 0 bis 100. 90 heißt: stärker als 90 % der rund 9.000 vergleichbaren Wissenschaftler:innen anderer Universitäten. Kein Wahrscheinlichkeitswert.';
@@ -172,45 +174,52 @@ export class FounderDashboardComponent {
readonly evidenceTooltip = readonly evidenceTooltip =
'Die Signale, auf denen die Einschätzung beruht: Publikationen, Patente, Förderungen und gemeinsame Arbeiten mit der Industrie. Die Werte sind Zählungen, keine Bewertung der Person.'; 'Die Signale, auf denen die Einschätzung beruht: Publikationen, Patente, Förderungen und gemeinsame Arbeiten mit der Industrie. Die Werte sind Zählungen, keine Bewertung der Person.';
readonly flagTooltip =
'Möglicherweise wurden mehrere Personen mit gleichem Namen zusammengeführt oder die Karriereangaben sind unplausibel. Die Werte sind dann unsicher. Bitte Identität und Profil prüfen, bevor Sie die Person ansprechen.';
readonly careerBucketTooltip = careerBucketDescription; readonly careerBucketTooltip = careerBucketDescription;
readonly thresholdTooltip =
'Legt fest, ab welchem Rang Personen in der Liste erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte. Ohne Mindestwert werden alle Profile angezeigt.';
readonly thresholdToggleTooltip =
'Standardmäßig werden alle Profile angezeigt. Aktiviere den Mindestwert, um nur Personen ab einem bestimmten Rang zu sehen.';
readonly screeningTooltip =
'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Werte dieser Personen sind weniger verlässlich. Ist die Option aus, werden alle Profile angezeigt.';
// -- KPIs --------------------------------------------------------------- // -- KPIs ---------------------------------------------------------------
readonly kpis = computed(() => { readonly kpis = computed(() => {
const stats = this.statistics(); const stats = this.statistics();
const total = stats.provenance?.document_count ?? 0; const total = stats.provenance?.document_count ?? 0;
const scoreable = stats.overall?.in_population ?? 0; const scoreable = stats.overall?.in_population ?? 0;
const passed = stats.overall?.screened ?? 0;
const share = total ? Math.round((passed / total) * 100) : 0;
const shortlisted = this.candidates().total ?? 0; const shortlisted = this.candidates().total ?? 0;
return { total, scoreable, passed, share, shortlisted }; return { total, scoreable, shortlisted };
}); });
/** True when the pipeline has produced at least one score for this university. */
readonly hasScores = computed(
() => (this.statistics().overall?.in_population ?? 0) > 0,
);
readonly scoreableShare = computed(() => { readonly scoreableShare = computed(() => {
const { total, scoreable } = this.kpis(); const { total, scoreable } = this.kpis();
return total ? Math.round((scoreable / total) * 100) : 0; return total ? Math.round((scoreable / total) * 100) : 0;
}); });
readonly qualityDetail = computed(
() => `${this.kpis().share} % der Forschenden`,
);
readonly scoreableDetail = computed( readonly scoreableDetail = computed(
() => `${this.scoreableShare()} % der Forschenden`, () => `${this.scoreableShare()} % der Forschenden`,
); );
readonly shortlistDetail = computed(() => `ab Rang ${this.threshold()}`);
readonly shortlistDetail = computed(() =>
this.thresholdEnabled() ? `ab Rang ${this.threshold()}` : 'alle Profile',
);
readonly emptyListMessage = computed(() => readonly emptyListMessage = computed(() =>
this.screened() this.thresholdEnabled()
? `Niemand erreicht den Mindestwert von ${this.threshold()} und hat zugleich ein unauffälliges Profil. Senken Sie den Mindestwert oder blenden Sie auffällige Profile wieder ein.` ? `Niemand erreicht den Mindestwert von ${this.threshold()}${
: `Niemand erreicht den Mindestwert von ${this.threshold()}. Senken Sie den Mindestwert, um mehr Personen zu sehen.`, this.screened() ? ' und hat zugleich ein unauffälliges Profil' : ''
}. Senken Sie den Mindestwert${
this.screened()
? ' oder blenden Sie auffällige Profile wieder ein'
: ' oder deaktivieren Sie ihn'
}, um mehr Profile zu sehen.`
: this.screened()
? 'Mit ausgeblendeten auffälligen Profilen wurde niemand gefunden. Blenden Sie auffällige Profile wieder ein, um mehr zu sehen.'
: 'Für diese Auswahl wurden keine Personen gefunden. Setzen Sie die Filter zurück, um mehr Profile zu sehen.',
); );
// -- Shortlist ---------------------------------------------------------- // -- Shortlist ----------------------------------------------------------
@@ -229,6 +238,8 @@ export class FounderDashboardComponent {
viewChild.required<TemplateRef<void>>('withinHeader'); viewChild.required<TemplateRef<void>>('withinHeader');
private readonly evidenceHeader = private readonly evidenceHeader =
viewChild.required<TemplateRef<void>>('evidenceHeader'); viewChild.required<TemplateRef<void>>('evidenceHeader');
readonly detailTemplate =
viewChild.required<TemplateRef<FounderRow>>('rowDetailTemplate');
readonly columns = computed<GenericColumn<FounderRow>[]>(() => [ readonly columns = computed<GenericColumn<FounderRow>[]>(() => [
{ {
@@ -267,32 +278,36 @@ export class FounderDashboardComponent {
(this.candidates().elements ?? []).map((c) => toRow(c)), (this.candidates().elements ?? []).map((c) => toRow(c)),
); );
readonly selectedId = signal<string | null>(null);
readonly selectedRow = computed<FounderRow | null>(() => {
const id = this.selectedId();
const rows = this.rows();
if (id) {
return rows.find((r) => r.candidate.author_id === id) ?? null;
}
return rows[0] ?? null;
});
selectCandidate(id: string): void {
this.selectedId.set(id);
}
// -- Controls ----------------------------------------------------------- // -- Controls -----------------------------------------------------------
/** Discrete label inside the Material slider thumb. */ /** Live slider value while dragging; committed to the URL on release. */
readonly thresholdDraft = signal<number>(DEFAULT_THRESHOLD);
constructor() {
effect(() => this.thresholdDraft.set(this.threshold()));
}
readonly formatThreshold = (value: number): string => String(value); readonly formatThreshold = (value: number): string => String(value);
/** Enables or disables the threshold filter (writes/removes the URL param). */
onThresholdEnabledChange(enabled: boolean): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: {
threshold: enabled ? this.thresholdDraft() : null,
page: 0,
},
queryParamsHandling: 'merge',
});
}
onSliderInput(value: number): void { onSliderInput(value: number): void {
if (Number.isFinite(value)) this.thresholdDraft.set(value); if (Number.isFinite(value)) this.thresholdDraft.set(value);
} }
/** Commits the threshold value to the URL. */
onSliderCommit(value = this.thresholdDraft()): void { onSliderCommit(value = this.thresholdDraft()): void {
if (!Number.isFinite(value)) return; if (!this.thresholdEnabled() || !Number.isFinite(value)) return;
this.thresholdDraft.set(value); this.thresholdDraft.set(value);
if (value === this.threshold()) return; if (value === this.threshold()) return;
void this.router.navigate([], { void this.router.navigate([], {
@@ -302,17 +317,40 @@ export class FounderDashboardComponent {
}); });
} }
/**
* `screened=false` means "only rejected profiles" on the backend, so turning
* the toggle off must REMOVE the param (everyone), not set false.
*/
onScreenedChange(checked: boolean): void { onScreenedChange(checked: boolean): void {
void this.router.navigate([], { void this.router.navigate([], {
relativeTo: this.route, relativeTo: this.route,
queryParams: { screened: checked ? 'true' : 'false', page: 0 }, queryParams: { screened: checked ? 'true' : null, page: 0 },
queryParamsHandling: 'merge', queryParamsHandling: 'merge',
}); });
} }
onLowerThreshold(): void { onLowerThreshold(): void {
const next = Math.max(50, this.threshold() - 10); const next = Math.max(50, this.threshold() - 10);
this.onSliderCommit(next); void this.router.navigate([], {
relativeTo: this.route,
queryParams: { threshold: next, page: 0 },
queryParamsHandling: 'merge',
});
}
/** Opens the global model explanation; independent of the selection. */
openExplainer(): void {
this.dialog.open(FounderExplainerPanelComponent, {
panelClass: 'sg-side-panel',
position: { right: '0', top: '0' },
height: '100dvh',
width: 'min(520px, 100vw)',
maxWidth: '100vw',
maxHeight: '100dvh',
ariaLabel: 'Modell-Erklärung zum Gründungspotenzial',
autoFocus: 'first-tabbable',
restoreFocus: true,
});
} }
// -- Formatting helpers for the template -------------------------------- // -- Formatting helpers for the template --------------------------------
@@ -323,24 +361,32 @@ export class FounderDashboardComponent {
function toRow(c: FounderCandidate): FounderRow { function toRow(c: FounderCandidate): FounderRow {
const fp = c.founder_potential; const fp = c.founder_potential;
const reasons = c.screen.reasons ?? []; const score = fp?.external_percentile ?? null;
return { return {
candidate: c, candidate: c,
name: c.display_name ?? c.author_id, name: c.display_name ?? c.author_id,
areaLabel: c.founder_features?.publication_research_area_label ?? null, areaLabel: c.founder_features?.publication_research_area_label ?? null,
score: fp?.external_percentile ?? null, score,
within: [ within: [
fp?.external_percentile_within_1y ?? null, fp?.external_percentile_within_1y ?? null,
fp?.external_percentile_within_3y ?? null, fp?.external_percentile_within_3y ?? null,
fp?.external_percentile_within_5y ?? null, fp?.external_percentile_within_5y ?? null,
], ],
flagLabel: notScoredReason: score === null ? notScoredReason(c) : null,
reasons.length > 0
? (SCREEN_REASON_LABELS[reasons[0]] ?? reasons[0])
: null,
}; };
} }
/** Plain-language explanation for why a profile has no score. */
function notScoredReason(c: FounderCandidate): string {
const reasons = (c.screen.reasons ?? []).map(
(reason) => SCREEN_REASON_LABELS[reason] ?? reason,
);
const detail = reasons.length
? ` Gründe: ${reasons.join(', ')}.`
: '';
return `Für dieses Profil liegt kein Score vor. Das Modell braucht mindestens 4 Publikationen und ein vollständiges, plausibles Profil.${detail}`;
}
function toNumber(value: string | null): number | null { function toNumber(value: string | null): number | null {
if (value === null || value === '') return null; if (value === null || value === '') return null;
const parsed = Number(value); const parsed = Number(value);
@@ -0,0 +1,116 @@
<div class="explainer">
<header class="explainer__head">
<div class="explainer__heading">
<p class="explainer__eyebrow">Modell-Erklärung</p>
<h2 class="explainer__title">Woher kommt das Gründungspotenzial?</h2>
</div>
<button
mat-icon-button
type="button"
class="explainer__close"
aria-label="Erklärung schließen"
(click)="close()">
<mat-icon>{{ CLOSE_ICON }}</mat-icon>
</button>
</header>
<div class="explainer__body">
@if (loading()) {
<div class="explainer__state">
<mat-spinner diameter="32" />
<p>Modellinformationen werden geladen …</p>
</div>
} @else if (error()) {
<div class="explainer__state explainer__state--error">
<mat-icon>{{ ERROR_OUTLINE_ICON }}</mat-icon>
<p>Die Modellinformationen konnten nicht geladen werden.</p>
<button mat-stroked-button type="button" (click)="load()">
Erneut versuchen
</button>
</div>
} @else {
<p class="explainer__lead">
Das Modell schätzt aus Publikationen, Patenten, Förderungen und
Industriekontakten, wie wahrscheinlich eine Person gründet. Die Balken
zeigen, auf welche Merkmale sich das Modell insgesamt am stärksten
stützt.
</p>
<div class="explainer__metrics" aria-label="Modellgüte">
<span>
ROC-AUC <strong>{{ fmtAuc(modelInfo()?.oof_roc_auc) }}</strong>
</span>
<span>
PR-AUC <strong>{{ fmtAuc(modelInfo()?.oof_pr_auc) }}</strong>
</span>
@if (modelInfo()?.reference_cohort_size) {
<span>
Referenz
<strong>{{ fmtInt(modelInfo()?.reference_cohort_size) }}</strong>
Profile
</span>
}
@if (modelInfo()?.reference_founders) {
<span>
<strong>{{ fmtInt(modelInfo()?.reference_founders) }}</strong>
Gründer:innen
</span>
}
</div>
@if (entries().length) {
<div
echarts
[options]="chartOptions()"
[autoResize]="true"
class="explainer__chart"
[style.height.px]="chartHeight()"
role="img"
aria-label="Balkendiagramm: Einfluss der Merkmale auf die Gründungsprognose"></div>
<section
class="explainer__origin"
aria-labelledby="explainer-origin-title">
<h3 id="explainer-origin-title">Woher kommen die Zahlen?</h3>
<p>
Für jedes Merkmal – zum Beispiel Publikationen pro Jahr, Patente
oder Industriekontakte – macht das Modell denselben Test:
</p>
<ol class="explainer__steps">
<li>
Ein Merkmal wird zufällig vertauscht, alle anderen bleiben gleich.
</li>
<li>Das Modell bewertet dieselben Personen erneut.</li>
<li>
Je stärker die Trefferqualität danach sinkt, desto größer ist der
Balken.
</li>
</ol>
<p>
Ein großer Balken heißt also: Das Modell verlässt sich stark auf
dieses Merkmal. Die Prozentwerte sind der Anteil an der
Gesamtbedeutung der angezeigten Merkmale. Sie sind keine Punkte,
keine Wahrscheinlichkeit und kein Beitrag einer einzelnen Person.
Die Werte gelten für das Modell insgesamt und sind für alle Personen
gleich.
</p>
</section>
<p class="explainer__note">
Ausgeblendet: Das wichtigste Trainingsmerkmal (Patent-Fachgebiet) ist
im aktuellen Datenbestand für alle gleich und trennt daher niemanden.
Institutionsmerkmale sind im Produktionsmodell nicht enthalten.
</p>
} @else {
<p class="explainer__note">
Für dieses Modell sind keine darstellbaren Merkmale verfügbar.
</p>
}
<p class="explainer__caveat">
Die Werte beschreiben das trainierte Modell, nicht die einzelne Person.
Sie belegen keinen Ursache-Wirkungs-Zusammenhang.
</p>
}
</div>
</div>
@@ -0,0 +1,161 @@
:host {
display: block;
height: 100%;
}
.explainer {
display: flex;
flex-direction: column;
height: 100%;
background: var(--sg-card-bg);
color: var(--sg-text);
}
.explainer__head {
display: flex;
flex: none;
align-items: flex-start;
gap: 12px;
padding: 20px 18px 14px 24px;
border-bottom: 1px solid var(--sg-border);
}
.explainer__heading {
flex: 1;
min-width: 0;
}
.explainer__eyebrow {
margin: 0 0 4px;
color: var(--sg-text-soft);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.explainer__title {
margin: 0;
color: var(--sg-text);
font-size: 19px;
font-weight: 700;
line-height: 1.3;
}
.explainer__close {
flex: none;
margin: -4px -4px 0 0;
color: var(--sg-text-muted);
}
.explainer__body {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 18px 24px 24px;
}
.explainer__lead {
margin: 0 0 14px;
color: var(--sg-text-muted);
font-size: 13px;
line-height: 1.55;
}
.explainer__metrics {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
margin-bottom: 18px;
padding: 10px 12px;
border: 1px solid var(--sg-border);
border-radius: 10px;
background: var(--sg-surface-muted);
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.4;
strong {
color: var(--sg-text);
font-variant-numeric: tabular-nums;
}
}
.explainer__chart {
width: 100%;
}
.explainer__origin {
margin-top: 18px;
padding: 14px 16px 16px;
border: 1px solid var(--sg-border);
border-radius: 12px;
background: var(--sg-surface-muted);
h3 {
margin: 0 0 8px;
color: var(--sg-text);
font-size: 13px;
font-weight: 700;
}
p {
margin: 0;
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.5;
}
}
.explainer__steps {
margin: 10px 0;
padding-left: 18px;
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.5;
li + li {
margin-top: 4px;
}
li::marker {
color: var(--sg-primary);
font-weight: 700;
}
}
.explainer__note,
.explainer__caveat {
margin: 10px 0 0;
color: var(--sg-text-soft);
font-size: 11.5px;
line-height: 1.5;
}
.explainer__caveat {
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--sg-border);
}
.explainer__state {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 48px 12px;
color: var(--sg-text-muted);
font-size: 13px;
text-align: center;
p {
margin: 0;
}
&--error mat-icon {
width: 30px;
height: 30px;
color: var(--sg-error);
font-size: 30px;
}
}
@@ -0,0 +1,242 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { FounderModelInfo, MultiplicatorsService } from '../../../../api';
import { ChartThemeService } from '../../../../shared/services/chart-theme.service';
import { CLOSE_ICON, ERROR_OUTLINE_ICON } from '../../../../shared/ui/icons';
import { fmtInt } from '../../founder-potential.utils';
/**
* German labels for the features the founder classifier exposes. Features
* missing here fall back to a readable version of their technical name.
*/
const FEATURE_LABELS: Record<string, string> = {
pub_rate: 'Publikationen pro Jahr',
first_publication_year: 'Jahr der ersten Publikation',
industry_collab_at_index: 'Publikationen mit Industriebeteiligung',
career_age_at_index: 'Karrierealter',
patents_at_index: 'Patente',
patent_rate: 'Patente pro Jahr',
patent_research_area_46: 'Patent-Fachgebiet: Informatik',
publication_research_area_32: 'Fachgebiet: Biomedizin & Klinik',
years_since_first_grant: 'Jahre seit erster Förderung',
grant_research_area_51: 'Förder-Fachgebiet: Physik',
};
/** One bar in the chart, with the share of the displayed total. */
interface ImportanceEntry {
label: string;
share: number;
importance: number;
std: number | null;
}
function isVisibleFeature(feature: string): boolean {
// Constant in this deployment (no IPC-to-FOR mapping) and dropped from the
// production bundle, respectively. Showing them would mislead locally.
return (
feature !== 'patent_research_area_n.' &&
!feature.startsWith('institution_')
);
}
function featureLabel(feature: string): string {
return (
FEATURE_LABELS[feature] ??
feature
.replace(/_/g, ' ')
.replace(/\b\w/g, (letter) => letter.toUpperCase())
);
}
function fmtShare(value: number): string {
return value.toLocaleString('de-DE', {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
});
}
function fmtImportance(value: number): string {
return value.toLocaleString('de-DE', {
minimumFractionDigits: 3,
maximumFractionDigits: 3,
});
}
function fmtAuc(value: number | null | undefined): string {
if (value === null || value === undefined) return '—';
return value.toLocaleString('de-DE', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
/**
* Right-hand overlay that explains where the founder score comes from.
*
* It shows the model's global permutation importances, not per-person
* contributions: the API exposes only raw feature values per candidate.
*/
@Component({
selector: 'app-founder-explainer-panel',
standalone: true,
imports: [
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
NgxEchartsDirective,
],
templateUrl: './founder-explainer-panel.component.html',
styleUrl: './founder-explainer-panel.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FounderExplainerPanelComponent {
readonly CLOSE_ICON = CLOSE_ICON;
readonly ERROR_OUTLINE_ICON = ERROR_OUTLINE_ICON;
private readonly service = inject(MultiplicatorsService);
private readonly dialogRef = inject(
MatDialogRef<FounderExplainerPanelComponent>,
);
private readonly chartTheme = inject(ChartThemeService);
readonly modelInfo = signal<FounderModelInfo | null>(null);
readonly loading = signal(false);
readonly error = signal(false);
readonly fmtInt = fmtInt;
readonly fmtAuc = fmtAuc;
readonly entries = computed<ImportanceEntry[]>(() => {
const importances = (this.modelInfo()?.importances ?? []).filter((item) =>
isVisibleFeature(item.feature),
);
const total = importances.reduce(
(sum, item) => sum + item.importance_mean,
0,
);
if (total <= 0) return [];
return [...importances]
.sort((a, b) => b.importance_mean - a.importance_mean)
.map((item) => ({
label: featureLabel(item.feature),
share: (item.importance_mean / total) * 100,
importance: item.importance_mean,
std: item.importance_std ?? null,
}));
});
/** Enough vertical room for every bar; the panel body scrolls if needed. */
readonly chartHeight = computed(() =>
Math.max(240, this.entries().length * 44 + 24),
);
readonly chartOptions = computed<EChartsOption>(() => {
const colors = this.chartTheme.colors();
const entries = this.entries();
return {
animationDuration: 350,
grid: { left: 4, right: 50, top: 8, bottom: 4, containLabel: true },
tooltip: {
trigger: 'item',
confine: true,
backgroundColor: colors.tooltipBg,
borderColor: colors.tooltipBorder,
textStyle: { color: colors.tooltipTextColor, fontSize: 12 },
formatter: (params: any) => {
const entry = entries[params.dataIndex];
if (!entry) return '';
const std =
entry.std !== null
? ` ± ${fmtImportance(entry.std)}`
: '';
return [
`<strong>${entry.label}</strong>`,
`Anteil an der Gesamtbedeutung: <strong>${fmtShare(entry.share)} %</strong>`,
`Beitrag zur Trefferqualität: ${fmtImportance(entry.importance)}${std}`,
].join('<br/>');
},
},
xAxis: {
type: 'value',
axisLabel: {
color: colors.mutedTextColor,
fontSize: 11,
formatter: (value: any) =>
`${value.toLocaleString('de-DE', { maximumFractionDigits: 0 })} %`,
},
axisLine: { show: false },
axisTick: { show: false },
splitLine: { lineStyle: { color: colors.splitLine } },
},
yAxis: {
type: 'category',
inverse: true,
data: entries.map((entry) => entry.label),
axisLabel: {
color: colors.text,
fontSize: 12,
width: 170,
overflow: 'break',
lineHeight: 15,
},
axisLine: { show: false },
axisTick: { show: false },
},
series: [
{
type: 'bar',
data: entries.map((entry) => entry.share),
barMaxWidth: 20,
itemStyle: {
color: colors.primary,
borderRadius: [0, 4, 4, 0],
},
label: {
show: true,
position: 'right',
color: colors.text,
fontSize: 11,
formatter: (params: any) => `${fmtShare(params.value)} %`,
},
},
],
};
});
constructor() {
this.load();
}
load(): void {
this.loading.set(true);
this.error.set(false);
this.service.getFounderModelInfo().subscribe({
next: (info) => {
this.modelInfo.set(info);
this.loading.set(false);
},
error: () => {
this.error.set(true);
this.loading.set(false);
},
});
}
close(): void {
this.dialogRef.close();
}
}
@@ -0,0 +1,28 @@
<div class="content">
<app-query-param-input
queryParamKey="name"
label="Name suchen"
[debounceTime]="300" />
<div class="filter-grid">
<app-query-param-selector
[options]="careerOptions"
queryParamKey="careerBucket"
label="Karrierestufe"
[multiple]="true"
matTooltip="Early: 1–4 aktive Publikationsjahre, Emerging: 5–9, Established: 10–14, Senior: 15 oder mehr."
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above" />
<app-query-param-selector
[options]="researchAreaOptions()"
queryParamKey="researchArea"
label="Forschungsgebiet"
[multiple]="true"
matTooltip="Filtert nach dem Fachgebiet der Publikationen (2-stelliger FOR-Code)."
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above" />
</div>
<app-selected-filters [observers]="observers" />
</div>
@@ -0,0 +1,12 @@
.content {
display: flex;
flex-direction: column;
gap: 1rem;
}
.filter-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1rem;
align-items: start;
}
@@ -0,0 +1,89 @@
import { Component, computed, input } from '@angular/core';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CareerBucket, FounderStatistics } from '../../../api';
import { QueryParamInputComponent } from '../../../shared/ui/query-param-input/query-param-input.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../../shared/ui/query-param-selector/query-param-selector.component';
import {
FilterObserver,
SelectedFiltersComponent,
} from '../../../shared/ui/selected-filters/selected-filters.component';
import { PERSON_ICON, SEARCH_ICON } from '../../../shared/ui/icons';
@Component({
selector: 'app-founder-filters',
standalone: true,
imports: [
MatTooltipModule,
QueryParamInputComponent,
QueryParamSelectorComponent,
SelectedFiltersComponent,
],
templateUrl: './founder-filters.component.html',
styleUrl: './founder-filters.component.scss',
})
export class FounderFiltersComponent {
/** Stats carry the research-area codes/labels that the backend filters on. */
readonly statistics = input.required<FounderStatistics>();
readonly careerOptions: SelectorOption[] = [
{ value: CareerBucket.Early, display_name: 'Early (1–4 Jahre)' },
{ value: CareerBucket.Emerging, display_name: 'Emerging (5–9 Jahre)' },
{
value: CareerBucket.Established,
display_name: 'Established (10–14 Jahre)',
},
{ value: CareerBucket.Senior, display_name: 'Senior (15+ Jahre)' },
];
/**
* The backend filters research areas by the 2-digit FOR division code
* (`founding_features.publication_research_area`), so the selector must use
* the code as its value, not the human-readable label.
*/
readonly researchAreaOptions = computed<SelectorOption[]>(() =>
(this.statistics().research_areas ?? [])
.filter((area) => !!area.code)
.map((area) => ({
value: area.code,
display_name: area.label ? `${area.label} (${area.code})` : area.code,
}))
.sort((a, b) => a.display_name.localeCompare(b.display_name, 'de')),
);
readonly observers: FilterObserver[] = [
{
id: 'name',
queryParamKey: 'name',
icon: SEARCH_ICON,
removable: true,
template: undefined,
},
{
id: 'researchArea',
queryParamKey: 'researchArea',
icon: SEARCH_ICON,
valueFormatter: (value) =>
value
.split(',')
.map((code) => {
const area = this.statistics().research_areas?.find(
(a) => a.code === code,
);
return area?.label ? `${area.label} (${code})` : code;
})
.join(', '),
removable: true,
},
{
id: 'career',
queryParamKey: 'careerBucket',
icon: PERSON_ICON,
valueFormatter: (value) => value.split(',').join(', '),
removable: true,
},
];
}
@@ -92,15 +92,6 @@ export const METRIC_GROUP_META: Record<
}, },
}; };
/** German labels for the funnel stages, keyed by their stable key. */
export const FUNNEL_STAGE_LABELS: Record<string, string> = {
ALL: 'Alle Forschenden im Index',
IN_POPULATION: 'Vom Modell bewertbar (mind. 4 Publikationen)',
NOT_SUSPICIOUS: 'Kein zusammengeführtes Profil',
CAREER_AGE_PLAUSIBLE: 'Plausible Karrieredauer (max. 40 Jahre)',
MIN_PUBLICATIONS: 'Mind. 7 Publikationen',
};
/** Ordered metric definitions for the researcher detail table. */ /** Ordered metric definitions for the researcher detail table. */
export interface MetricDef { export interface MetricDef {
key: keyof ResearcherMetrics; key: keyof ResearcherMetrics;
@@ -78,20 +78,6 @@
} }
} }
.warning {
display: inline-flex;
align-items: center;
gap: 3px;
color: var(--sg-warning);
cursor: help;
&__icon {
width: 13px;
height: 13px;
font-size: 13px;
}
}
.th-help { .th-help {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -12,7 +12,6 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { import {
MultiplierTag, MultiplierTag,
ResearcherSummary, ResearcherSummary,
@@ -206,6 +205,9 @@ export class MultipliersDashboardComponent {
}; };
openNetwork(row: MultiplierRow): void { openNetwork(row: MultiplierRow): void {
void this.router.navigate(['/founders', row.researcher.author_id]); void this.router.navigate([
'/collaboration-network',
row.researcher.author_id,
]);
} }
} }
@@ -1,13 +1,22 @@
<app-page-container <app-page-container
[eyebrow]="'Multiplikatoren · ' + universityName()" [eyebrow]="'Multiplikatoren · ' + universityName()"
[title]="unavailable()?.title ?? name()"
[subtitle]="unavailable()?.body ?? null" [subtitle]="unavailable()?.body ?? null"
[titleTooltip]="unavailable() ? null : pageTooltip"> [titleTooltip]="unavailable() ? null : pageTooltip">
<div pageMeta class="meta-block"> <div pageMeta class="meta-block">
<a class="back-link" routerLink="/multipliers"> <h3 class="author-name">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon> @if (researcher()?.author_id; as authorId) {
Zurück zur Multiplikatoren-Übersicht <a
</a> class="author-name__link"
[routerLink]="['/person', authorId, 'overview']"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: authorId }"
tooltipMaxWidth="500px">
{{ name() }}
</a>
} @else {
{{ name() }}
}
</h3>
@if (!unavailable()) { @if (!unavailable()) {
<div class="meta-line"> <div class="meta-line">
@if (careerBucket()) { @if (careerBucket()) {
@@ -20,17 +29,6 @@
{{ fmtInt(nWorks()) }} Publikationen · {{ fmtInt(nWorks()) }} Publikationen ·
{{ fmtInt(activeYears()) }} aktive Jahre {{ fmtInt(activeYears()) }} aktive Jahre
</span> </span>
@if (suspicious()) {
<span
class="suspicious"
[matTooltip]="suspiciousTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<mat-icon>{{ WARNING_ICON }}</mat-icon>
Zusammengeführtes Profil · Daten vorsichtig interpretieren
<mat-icon class="help-icon">{{ HELP_OUTLINE_ICON }}</mat-icon>
</span>
}
</div> </div>
@if (tags().length) { @if (tags().length) {
<div class="tags"> <div class="tags">
@@ -88,18 +86,19 @@
<span class="legend__item">Knotengröße = aktive Jahre</span> <span class="legend__item">Knotengröße = aktive Jahre</span>
</div> </div>
<p class="graph-hint"> <p class="graph-hint">
Personen anklicken, um ihr Profil zu öffnen · ziehen zum Verschieben · <span class="graph-hint__desktop">
scrollen zum Zoomen Personen anklicken, um ihr Profil zu öffnen · ziehen zum Verschieben ·
scrollen zum Zoomen
</span>
</p> </p>
<div class="case-grid"> <div class="case-grid">
<mat-card appearance="outlined" class="netbox"> <mat-card appearance="outlined" class="netbox">
<mat-card-content> <mat-card-content class="netbox__content">
@if (network(); as net) { @if (network(); as net) {
@if ((net.nodes?.length ?? 0) > 0) { @if ((net.nodes?.length ?? 0) > 0) {
<app-multiplier-network-graph <app-multiplier-network-graph
[network]="net" [network]="net"
[height]="640"
(nodeClick)="onNodeClick($event)" /> (nodeClick)="onNodeClick($event)" />
} @else { } @else {
<div class="netbox__empty">Kein Netzwerk verfügbar.</div> <div class="netbox__empty">Kein Netzwerk verfügbar.</div>
@@ -147,8 +146,8 @@
</mat-icon> </mat-icon>
</h2> </h2>
<p class="metrics-caption"> <p class="metrics-caption">
Rang 0–100 im Vergleich zu Personen derselben Karrierestufe. Rang 0–100 im Vergleich zu Personen derselben Karrierestufe. Ab
Ab 85 % wird ein Rollen-Badge vergeben. 85 % wird ein Rollen-Badge vergeben.
</p> </p>
@for (group of metricGroups(); track group.key) { @for (group of metricGroups(); track group.key) {
<div class="metric-group"> <div class="metric-group">
@@ -3,26 +3,6 @@
min-width: 0; min-width: 0;
} }
.back-link {
display: inline-flex;
align-items: center;
gap: 4px;
margin-bottom: 6px;
color: var(--sg-text-muted);
font-size: 13px;
text-decoration: none;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
&:hover {
color: var(--sg-blue-highlight);
}
}
.meta-block { .meta-block {
margin-top: 8px; margin-top: 8px;
} }
@@ -47,28 +27,6 @@
margin: 2px 0 8px; margin: 2px 0 8px;
} }
.suspicious {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--sg-error);
font-size: 12.5px;
cursor: help;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
.help-icon {
color: var(--sg-text-soft);
font-size: 15px;
width: 15px;
height: 15px;
}
}
.tags { .tags {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -86,6 +44,20 @@
margin: 8px 0 0; margin: 8px 0 0;
color: var(--sg-text-soft); color: var(--sg-text-soft);
font-size: 12px; font-size: 12px;
&__touch {
display: none;
}
}
@media (hover: none), (pointer: coarse) {
.graph-hint__desktop {
display: none;
}
.graph-hint__touch {
display: inline;
}
} }
.legend { .legend {
@@ -143,22 +115,45 @@
} }
.netbox { .netbox {
display: flex;
flex-direction: column;
background: var(--sg-surface-muted); background: var(--sg-surface-muted);
overflow: hidden; overflow: hidden;
height: 100%;
// Keep the chart usable even when the surrounding grid row has no
// definite height (single-column phone layout).
min-height: clamp(420px, 58vh, 760px);
.mat-mdc-card-content { .mat-mdc-card-content {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
padding: 0; padding: 0;
} }
&__empty { &__empty {
height: 640px;
display: flex; display: flex;
flex: 1 1 auto;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
color: var(--sg-text-soft); color: var(--sg-text-soft);
} }
} }
.netbox__content {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
}
app-multiplier-network-graph {
display: block;
flex: 1 1 auto;
min-height: 0;
}
.detail-card { .detail-card {
overflow: hidden; overflow: hidden;
@@ -236,7 +231,25 @@
line-height: 1.4; line-height: 1.4;
} }
} }
.author-name {
margin: 0;
color: var(--sg-text);
}
.author-name__link {
color: inherit;
text-decoration: none;
&:hover {
text-decoration: underline;
}
&:focus-visible {
border-radius: 2px;
outline: 2px solid var(--sg-blue-highlight);
outline-offset: 2px;
}
}
.metric-label { .metric-label {
cursor: help; cursor: help;
text-decoration: underline dotted; text-decoration: underline dotted;
@@ -312,9 +325,49 @@
@media (max-width: 1000px) { @media (max-width: 1000px) {
.case-grid { .case-grid {
grid-template-columns: 1fr; grid-template-columns: 1fr;
gap: 20px;
} }
.netbox {
// The grid row no longer gives the card a definite height here, so give
// the chart an explicit viewport-based height instead of collapsing.
height: auto;
min-height: 0;
}
// The legend sits directly above the graph in the single-column layout, so
// it does not need to stick, and the narrower column needs tighter wrapping.
.legend {
position: static;
margin-top: 16px;
padding: 6px 0;
gap: 6px 12px;
font-size: 11.5px;
line-height: 1.35;
}
app-multiplier-network-graph,
.netbox__empty { .netbox__empty {
height: 420px; flex: none;
height: clamp(340px, 52vh, 500px);
}
}
@media (max-width: 700px) {
.case-grid {
gap: 16px;
margin-top: 18px;
}
.detail-card .mat-mdc-card-content {
padding: 14px;
}
.network-footer {
margin-top: 28px;
}
.unavailable .mat-mdc-card-content {
padding: 20px;
} }
} }
@@ -1,6 +1,13 @@
import { Component, computed, inject, input, TemplateRef, viewChild } from '@angular/core'; import {
Component,
computed,
inject,
input,
TemplateRef,
viewChild,
} from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router'; import { Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
@@ -36,8 +43,9 @@ import {
HELP_OUTLINE_ICON, HELP_OUTLINE_ICON,
INFO_OUTLINE_ICON, INFO_OUTLINE_ICON,
PERSON_OFF_ICON, PERSON_OFF_ICON,
WARNING_ICON,
} from '../../../shared/ui/icons'; } from '../../../shared/ui/icons';
import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component';
const ROLE_ORDER = ['ego', 'cohort', 'mentee', 'industry', 'external']; const ROLE_ORDER = ['ego', 'cohort', 'mentee', 'industry', 'external'];
const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen'; const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen';
@@ -70,7 +78,6 @@ interface MetricGroup {
standalone: true, standalone: true,
imports: [ imports: [
CommonModule, CommonModule,
RouterModule,
MatButtonModule, MatButtonModule,
MatCardModule, MatCardModule,
MatIconModule, MatIconModule,
@@ -81,17 +88,18 @@ interface MetricGroup {
ChipComponent, ChipComponent,
MultiplierRoleScoresComponent, MultiplierRoleScoresComponent,
PageContainerComponent, PageContainerComponent,
RouterLink,
ComponentTooltipDirective,
], ],
templateUrl: './researcher-network.component.html', templateUrl: './researcher-network.component.html',
styleUrl: './researcher-network.component.scss', styleUrl: './researcher-network.component.scss',
}) })
export class ResearcherNetworkComponent { export class ResearcherNetworkComponent {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON; readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly WARNING_ICON = WARNING_ICON;
readonly PERSON_OFF_ICON = PERSON_OFF_ICON; readonly PERSON_OFF_ICON = PERSON_OFF_ICON;
readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON; readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON;
readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON; readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON;
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly page = input.required<ResearcherPageState>(); readonly page = input.required<ResearcherPageState>();
private readonly router = inject(Router); private readonly router = inject(Router);
@@ -146,10 +154,11 @@ export class ResearcherNetworkComponent {
this.researcher()?.author_id ?? this.researcher()?.author_id ??
'Unbekannt', 'Unbekannt',
); );
readonly careerBucket = computed(() => this.researcher()?.career_bucket ?? null); readonly careerBucket = computed(
() => this.researcher()?.career_bucket ?? null,
);
readonly activeYears = computed(() => this.researcher()?.active_years ?? 0); readonly activeYears = computed(() => this.researcher()?.active_years ?? 0);
readonly nWorks = computed(() => this.researcher()?.n_works ?? 0); readonly nWorks = computed(() => this.researcher()?.n_works ?? 0);
readonly suspicious = computed(() => this.researcher()?.suspicious_profile ?? false);
readonly tags = computed(() => this.researcher()?.tags ?? []); readonly tags = computed(() => this.researcher()?.tags ?? []);
readonly tagLabel = tagLabel; readonly tagLabel = tagLabel;
readonly tagDescription = tagDescription; readonly tagDescription = tagDescription;
@@ -159,9 +168,6 @@ export class ResearcherNetworkComponent {
readonly pageTooltip = readonly pageTooltip =
'Das Netzwerk zeigt, mit wem diese Person gemeinsam publiziert hat. Je dicker die Linie, desto häufiger haben die beiden zusammengearbeitet.'; 'Das Netzwerk zeigt, mit wem diese Person gemeinsam publiziert hat. Je dicker die Linie, desto häufiger haben die beiden zusammengearbeitet.';
readonly suspiciousTooltip =
'Bei diesem Profil wurden vermutlich mehrere Personen vermischt, zum Beispiel wegen gleicher Namen oder einer unplausibel langen Karriere. Die Angaben zu Publikationen, Netzwerk und Rollen sind deshalb unsicher.';
readonly rolesTooltip = readonly rolesTooltip =
'Wie stark die drei Rollen ausgeprägt sind. Ab 85 % wird ein Badge vergeben.'; 'Wie stark die drei Rollen ausgeprägt sind. Ab 85 % wird ein Badge vergeben.';
@@ -189,8 +195,9 @@ export class ResearcherNetworkComponent {
private readonly metricTemplate = private readonly metricTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricTemplate'); viewChild.required<TemplateRef<MetricRow>>('metricTemplate');
private readonly metricValueTemplate = private readonly metricValueTemplate = viewChild.required<
viewChild.required<TemplateRef<MetricRow>>('metricValueTemplate'); TemplateRef<MetricRow>
>('metricValueTemplate');
private readonly metricRankTemplate = private readonly metricRankTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricRankTemplate'); viewChild.required<TemplateRef<MetricRow>>('metricRankTemplate');
private readonly metricHeader = private readonly metricHeader =
@@ -88,13 +88,13 @@
</div> </div>
<mat-card-content class="uh-chart-viewport"> <mat-card-content class="uh-chart-viewport">
<div @if (expanded()) {
echarts <div
[options]="level.options" #chartHost
[autoResize]="true" appPassiveWheel
(chartClick)="onNodeClick($event, i)" class="uh-chart"
class="uh-chart" [style.height.px]="level.height"></div>
[style.height.px]="level.height"></div> }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} }
@@ -66,11 +66,14 @@
.uh-row { .uh-row {
display: flex; display: flex;
flex-grow: 1; flex-grow: 0;
flex-shrink: 0;
flex-basis: auto;
flex-direction: row; flex-direction: row;
flex-wrap: nowrap; flex-wrap: nowrap;
align-items: stretch; align-items: stretch;
gap: var(--uh-gap); gap: var(--uh-gap);
height: var(--uh-row-height);
overflow-x: auto; overflow-x: auto;
overflow-y: hidden; overflow-y: hidden;
padding-bottom: 2px; padding-bottom: 2px;
@@ -132,6 +135,7 @@
flex: 1 1 100%; flex: 1 1 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-height: 0;
overflow: hidden; overflow: hidden;
} }
@@ -167,13 +171,14 @@
} }
.uh-chart-viewport { .uh-chart-viewport {
flex: 1 1 auto;
min-height: 0;
overflow-x: hidden; overflow-x: hidden;
overflow-y: auto; overflow-y: auto;
height: 100%;
padding: 0 !important; padding: 0 !important;
} }
.uh-chart { .uh-chart {
height: 100% !important;
width: 100%; width: 100%;
height: 100% !important;
} }
@@ -1,6 +1,7 @@
import { import {
Component, Component,
DestroyRef, DestroyRef,
ElementRef,
OnInit, OnInit,
signal, signal,
inject, inject,
@@ -10,10 +11,10 @@ import {
EventEmitter, EventEmitter,
effect, effect,
untracked, untracked,
viewChild,
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router, ActivatedRoute } from '@angular/router'; import { Router, ActivatedRoute } from '@angular/router';
import { NgxEchartsDirective } from 'ngx-echarts';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatToolbarModule } from '@angular/material/toolbar'; import { MatToolbarModule } from '@angular/material/toolbar';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
@@ -21,7 +22,8 @@ import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips'; import { MatChipsModule } from '@angular/material/chips';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import type { EChartsOption } from 'echarts'; import type { ECharts, EChartsOption } from 'echarts';
import { PassiveWheelDirective } from '../../../directives/passive-wheel.directive';
import { CredentialService } from '../../../shared/services/credential.service'; import { CredentialService } from '../../../shared/services/credential.service';
import { ChartThemeService } from '../../../shared/services/chart-theme.service'; import { ChartThemeService } from '../../../shared/services/chart-theme.service';
import { HierarchyEditDialogComponent } from './hierarchy-edit-dialog/hierarchy-edit-dialog.component'; import { HierarchyEditDialogComponent } from './hierarchy-edit-dialog/hierarchy-edit-dialog.component';
@@ -48,6 +50,9 @@ interface TreeLevel {
const QUERY_PARAM_PATH = 'path'; const QUERY_PARAM_PATH = 'path';
const QUERY_PARAM_LANG = 'lang'; const QUERY_PARAM_LANG = 'lang';
const QUERY_PARAM_ORGANIZATION_FOCUS = 'orgFocus';
const QUERY_PARAM_ORGANIZATION_FOCUS_PATH = 'orgFocusPath';
const QUERY_PARAM_ORGANIZATION_URL = 'orgUrl';
const LEAF_ROW_HEIGHT = 22; const LEAF_ROW_HEIGHT = 22;
const MIN_TREE_HEIGHT = 200; const MIN_TREE_HEIGHT = 200;
@@ -64,7 +69,7 @@ const MIN_TREE_HEIGHT = 200;
selector: 'app-hierarchy-chart', selector: 'app-hierarchy-chart',
standalone: true, standalone: true,
imports: [ imports: [
NgxEchartsDirective, PassiveWheelDirective,
MatProgressSpinnerModule, MatProgressSpinnerModule,
MatToolbarModule, MatToolbarModule,
MatCardModule, MatCardModule,
@@ -92,12 +97,27 @@ export class HierarchyChartComponent implements OnInit {
private readonly credentialService = inject(CredentialService); private readonly credentialService = inject(CredentialService);
private readonly orgminerService = inject(OrgminerService); private readonly orgminerService = inject(OrgminerService);
private readonly chartTheme = inject(ChartThemeService); private readonly chartTheme = inject(ChartThemeService);
/** Reference of the theme colors used for the current chart options. */
private lastChartTheme = this.chartTheme.colors();
readonly loading = signal<boolean>(true); readonly loading = signal<boolean>(true);
readonly lang = signal<'de' | 'en'>('de'); readonly lang = signal<'de' | 'en'>('de');
readonly levels = signal<TreeLevel[]>([]); readonly levels = signal<TreeLevel[]>([]);
/** Node highlighted after a badge navigation or an analysis click. */
readonly highlightedId = signal<string | null>(null);
private readonly chartHost =
viewChild<ElementRef<HTMLDivElement>>('chartHost');
private chart: ECharts | null = null;
private chartHostElement: HTMLDivElement | null = null;
private chartResizeObserver: ResizeObserver | null = null;
private chartInitToken = 0;
private readonly snackBar = inject(MatSnackBar); private readonly snackBar = inject(MatSnackBar);
private readonly idMap = new Map<string, RawNode>(); private readonly idMap = new Map<string, RawNode>();
/** Several hierarchy nodes can share one URL; keep every candidate. */
private readonly urlToNodeIds = new Map<string, string[]>();
/** Last `orgFocus` value + path that was applied, so unrelated query changes don't re-focus. */
private lastFocusKey: string | null = null;
universityRoot: RawNode | null = null; universityRoot: RawNode | null = null;
/** /**
@@ -109,6 +129,8 @@ export class HierarchyChartComponent implements OnInit {
private isOwnNavigation = false; private isOwnNavigation = false;
hierarchyData = input.required<HierarchyResponse>(); hierarchyData = input.required<HierarchyResponse>();
/** False while the parent expansion panel is collapsed. */
readonly expanded = input<boolean>(true);
pendingSuggestion = input<HierarchySuggestion | null>(null); pendingSuggestion = input<HierarchySuggestion | null>(null);
can_edit = computed(() => this.hierarchyData().can_edit ?? false); can_edit = computed(() => this.hierarchyData().can_edit ?? false);
can_suggest = computed(() => this.hierarchyData().can_suggest ?? false); can_suggest = computed(() => this.hierarchyData().can_suggest ?? false);
@@ -133,7 +155,10 @@ export class HierarchyChartComponent implements OnInit {
}); });
}); });
effect(() => { effect(() => {
this.chartTheme.colors(); const colors = this.chartTheme.colors();
if (colors === this.lastChartTheme) return;
this.lastChartTheme = colors;
untracked(() => { untracked(() => {
if (!this.universityRoot) return; if (!this.universityRoot) return;
this.levels.update((levels) => this.levels.update((levels) =>
@@ -148,6 +173,15 @@ export class HierarchyChartComponent implements OnInit {
const suggestion = this.pendingSuggestion(); const suggestion = this.pendingSuggestion();
untracked(() => this.loadPendingSuggestionIntoEditor(suggestion)); untracked(() => this.loadPendingSuggestionIntoEditor(suggestion));
}); });
effect(() => {
const levels = this.levels();
const expanded = this.expanded();
const host = this.chartHost()?.nativeElement ?? null;
const level = expanded ? (levels[levels.length - 1] ?? null) : null;
untracked(() => this.syncChart(host, level));
});
this.destroyRef.onDestroy(() => this.disposeChart());
} }
ngOnInit(): void { ngOnInit(): void {
@@ -162,7 +196,37 @@ export class HierarchyChartComponent implements OnInit {
this.isOwnNavigation = false; this.isOwnNavigation = false;
return; return;
} }
const langParam = params.get(QUERY_PARAM_LANG);
if (langParam === 'de' || langParam === 'en') {
this.lang.set(langParam);
}
const focus = this.normalizeOrgUrl(
params.get(QUERY_PARAM_ORGANIZATION_FOCUS),
);
const focusPath = this.parseFocusPath(
params.get(QUERY_PARAM_ORGANIZATION_FOCUS_PATH),
);
const focusKey = focus
? `${focus}\u0000${focusPath.join('\u0000')}`
: null;
if (
focus &&
focusKey !== this.lastFocusKey &&
this.focusOrganization(focus, focusPath)
) {
this.lastFocusKey = focusKey;
return;
}
if (!focus) {
this.lastFocusKey = null;
}
this.restoreFromUrl(params); this.restoreFromUrl(params);
this.highlightAnalyzedOrganization(
params.get(QUERY_PARAM_ORGANIZATION_URL),
);
}); });
this.initialized = true; this.initialized = true;
} }
@@ -216,6 +280,7 @@ export class HierarchyChartComponent implements OnInit {
const copy = structuredClone(children ?? []) as RawNode[]; const copy = structuredClone(children ?? []) as RawNode[];
this.idMap.clear(); this.idMap.clear();
this.urlToNodeIds.clear();
this.assignIds(copy, 'root'); this.assignIds(copy, 'root');
this.universityRoot = { this.universityRoot = {
@@ -242,6 +307,16 @@ export class HierarchyChartComponent implements OnInit {
node.id = id; node.id = id;
if (registerInMap) { if (registerInMap) {
this.idMap.set(id, node); this.idMap.set(id, node);
for (const link of [node.link_de, node.link_en]) {
const normalized = this.normalizeOrgUrl(link);
if (!normalized) continue;
const candidates = this.urlToNodeIds.get(normalized);
if (candidates) {
if (!candidates.includes(id)) candidates.push(id);
} else {
this.urlToNodeIds.set(normalized, [id]);
}
}
} }
if (node.children?.length) { if (node.children?.length) {
this.assignIds(node.children, id, registerInMap); this.assignIds(node.children, id, registerInMap);
@@ -276,6 +351,184 @@ export class HierarchyChartComponent implements OnInit {
this.updateQueryParams(); this.updateQueryParams();
} }
/* --------------------------- organization focus --------------------------- */
/**
* Normalizes a hierarchy organization URL the same way the backend does:
* trim, drop trailing slashes and the common `/index` suffix.
*/
private normalizeOrgUrl(value: string | null | undefined): string | null {
if (!value) return null;
const normalized = value.trim().replace(/\/+$/, '');
const withoutIndex = normalized.endsWith('/index')
? normalized.slice(0, -'/index'.length).replace(/\/+$/, '')
: normalized;
return withoutIndex || null;
}
private findNodeIdByUrl(
value: string | null | undefined,
expectedPath: string[] = [],
preferVisible = false,
): string | null {
const normalized = this.normalizeOrgUrl(value);
const candidates = normalized
? (this.urlToNodeIds.get(normalized) ?? [])
: [];
if (!candidates.length) return null;
// Hierarchy URLs are not unique (several nodes can link to the same site),
// so the index-provided name path decides which node is meant.
if (expectedPath.length) {
const pathMatch = candidates.find((id) =>
this.matchesNamePath(id, expectedPath),
);
if (pathMatch) return pathMatch;
}
// Reloads only carry `orgUrl`; prefer the candidate on the open path.
if (preferVisible) {
const visible = candidates.find((id) => this.isNodeVisible(id));
if (visible) return visible;
}
return candidates[0];
}
/** Parses the hierarchy path (`orgFocusPath`) sent by the person badge. */
private parseFocusPath(value: string | null | undefined): string[] {
if (!value) return [];
try {
const parsed: unknown = JSON.parse(value);
if (!Array.isArray(parsed)) return [];
return parsed
.filter((segment): segment is string => typeof segment === 'string')
.map((segment) => segment.trim())
.filter(Boolean);
} catch {
return [];
}
}
/** Ancestor + node names from the faculty down (synthetic `root` excluded). */
private nodeNamePath(nodeId: string): RawNode[] {
return [...this.ancestorIds(nodeId).slice(1), nodeId]
.map((id) => this.idMap.get(id))
.filter((node): node is RawNode => !!node);
}
private matchesNamePath(nodeId: string, expectedPath: string[]): boolean {
if (!expectedPath.length) return false;
const actual = this.nodeNamePath(nodeId);
if (actual.length !== expectedPath.length) return false;
return expectedPath.every((name, index) =>
this.nodeMatchesName(actual[index], name),
);
}
private nodeMatchesName(node: RawNode, expected: string): boolean {
const normalize = (value: string | null | undefined) =>
(value ?? '').replace(/\s+/g, ' ').trim().toLocaleLowerCase();
const wanted = normalize(expected);
return (
normalize(node.name_de) === wanted || normalize(node.name_en) === wanted
);
}
/** Mirrors `buildLevel`: a level shows its children and group grandchildren. */
private levelRendersNode(levelId: string, nodeId: string): boolean {
const level = this.idMap.get(levelId);
if (!level) return false;
if (level.id === nodeId) return true;
for (const child of level.children ?? []) {
if (child.id === nodeId) return true;
const isGroup = child.type === 'institutes' || child.type === 'chairs';
if (
isGroup &&
child.children?.some((grandchild) => grandchild.id === nodeId)
) {
return true;
}
}
return false;
}
private isNodeVisible(nodeId: string): boolean {
return this.levels().some((level) =>
this.levelRendersNode(level.id, nodeId),
);
}
/** Positional parent ids of a node, e.g. `root-2-0-5` -> `root`, `root-2`, `root-2-0`. */
private ancestorIds(nodeId: string): string[] {
const ids = ['root'];
const parts = nodeId.split('-');
for (let index = 2; index < parts.length; index++) {
ids.push(parts.slice(0, index).join('-'));
}
return ids;
}
/**
* Opens the levels that display the requested organization and highlights
* its node. Used by the person-page badge (`orgFocus` query param).
*/
private focusOrganization(
orgUrl: string,
expectedPath: string[] = [],
): boolean {
const nodeId = this.findNodeIdByUrl(orgUrl, expectedPath);
if (!nodeId) return false;
// Open the faculty level, not the group directly above the target: the
// faculty chart shows the organization inside the full faculty subtree.
// For deeper nodes, keep opening levels until the target is rendered.
const fullPath = [...this.ancestorIds(nodeId), nodeId];
let lastLevelIndex = fullPath.findIndex(
(id) => this.idMap.get(id)?.type === 'faculty',
);
if (lastLevelIndex < 0) {
lastLevelIndex = Math.max(0, fullPath.length - 2);
}
while (
lastLevelIndex < fullPath.length - 1 &&
!this.levelRendersNode(fullPath[lastLevelIndex], nodeId)
) {
lastLevelIndex++;
}
const levels = fullPath
.slice(0, lastLevelIndex + 1)
.map((id) => this.idMap.get(id))
.filter((node): node is RawNode => !!node)
.map((node) => this.buildLevel(node));
if (!levels.length) return false;
this.highlightedId.set(nodeId);
this.levels.set(levels);
this.updateQueryParams();
return true;
}
/** Keeps the analyzed organization highlighted after query-param navigation. */
private highlightAnalyzedOrganization(orgUrl: string | null): void {
const nodeId = this.findNodeIdByUrl(orgUrl, [], true);
if (!nodeId || nodeId === this.highlightedId()) return;
this.highlightedId.set(nodeId);
if (this.universityRoot) {
this.rebuildLevelsKeepingPath();
}
}
private setHighlightedNode(nodeId: string | null): void {
if (this.highlightedId() === nodeId) return;
this.highlightedId.set(nodeId);
if (this.universityRoot) {
this.rebuildLevelsKeepingPath();
}
}
/** Writes the current levels path + language into the URL as query params. */ /** Writes the current levels path + language into the URL as query params. */
private updateQueryParams(): void { private updateQueryParams(): void {
const path = this.levels() const path = this.levels()
@@ -351,9 +604,18 @@ export class HierarchyChartComponent implements OnInit {
if (hasChildren) { if (hasChildren) {
const newLevel = this.buildLevel(raw); const newLevel = this.buildLevel(raw);
// if the user clicks a different branch, drop any deeper levels first const currentLevels = this.levels();
const truncated = this.levels().slice(0, levelIndex + 1); const existingIndex = currentLevels.findIndex(
this.levels.set([...truncated, newLevel]); (level) => level.id === raw.id,
);
if (existingIndex >= 0) {
this.levels.set(currentLevels.slice(0, existingIndex + 1));
} else {
// If the user clicks a different branch, drop any deeper levels first.
const truncated = currentLevels.slice(0, levelIndex + 1);
this.levels.set([...truncated, newLevel]);
}
this.updateQueryParams(); this.updateQueryParams();
} else { } else {
this.onLeafSelect(raw); this.onLeafSelect(raw);
@@ -361,6 +623,7 @@ export class HierarchyChartComponent implements OnInit {
} }
private onLeafSelect(raw: RawNode): void { private onLeafSelect(raw: RawNode): void {
this.setHighlightedNode(raw.id);
this.analyzeOrgEvent.emit({ this.analyzeOrgEvent.emit({
name: raw.name_de ?? raw.name_en ?? '', name: raw.name_de ?? raw.name_en ?? '',
url: raw.link_de ?? raw.link_en ?? '', url: raw.link_de ?? raw.link_en ?? '',
@@ -369,6 +632,18 @@ export class HierarchyChartComponent implements OnInit {
/* ------------------------------ tree building ----------------------------- */ /* ------------------------------ tree building ----------------------------- */
/** Extra ECharts item style that marks the focused/analyzed node. */
private highlightStyle(nodeId: string): Record<string, unknown> {
if (this.highlightedId() !== nodeId) return {};
const warning = this.chartTheme.colors().warning;
return {
borderColor: warning,
borderWidth: 1,
shadowBlur: 10,
shadowColor: warning,
};
}
private getLink(raw: RawNode): string | null | undefined { private getLink(raw: RawNode): string | null | undefined {
return this.lang() === 'en' return this.lang() === 'en'
? (raw.link_en ?? raw.link_de) ? (raw.link_en ?? raw.link_de)
@@ -403,6 +678,7 @@ export class HierarchyChartComponent implements OnInit {
(isGroup (isGroup
? this.chartTheme.colors().blueHighlight ? this.chartTheme.colors().blueHighlight
: this.chartTheme.colors().success), : this.chartTheme.colors().success),
...this.highlightStyle(raw.id),
}, },
}; };
@@ -426,7 +702,13 @@ export class HierarchyChartComponent implements OnInit {
} }
private buildLevel(raw: RawNode): TreeLevel { private buildLevel(raw: RawNode): TreeLevel {
const children = (raw.children || []).map((c) => this.toChartNode(c, true)); // Leaves inherit the icon of the group that contains them, including the
// direct children of a group that is itself the root of this level.
const parentType =
raw.type === 'institutes' || raw.type === 'chairs' ? raw.type : undefined;
const children = (raw.children || []).map((c) =>
this.toChartNode(c, true, parentType),
);
const rootData = { const rootData = {
id: raw.id, id: raw.id,
@@ -434,7 +716,10 @@ export class HierarchyChartComponent implements OnInit {
nodeType: raw.type, nodeType: raw.type,
hasChildren: true, hasChildren: true,
link: this.getLink(raw), link: this.getLink(raw),
itemStyle: { color: raw['color'] || this.chartTheme.colors().primary }, itemStyle: {
color: raw['color'] || this.chartTheme.colors().primary,
...this.highlightStyle(raw.id),
},
children, children,
}; };
@@ -472,7 +757,7 @@ export class HierarchyChartComponent implements OnInit {
const colors = this.chartTheme.colors(); const colors = this.chartTheme.colors();
return { return {
backgroundColor: this.chartTheme.colors().backgroundColor, backgroundColor: '#ffffff',
tooltip: { tooltip: {
trigger: 'item', trigger: 'item',
triggerOn: 'mousemove', triggerOn: 'mousemove',
@@ -499,20 +784,29 @@ export class HierarchyChartComponent implements OnInit {
verticalAlign: 'middle', verticalAlign: 'middle',
align: 'right', align: 'right',
fontSize: 11, fontSize: 11,
color: colors.text, color: 'black',
formatter: (params: any) => { formatter: (params: any) => {
if (params.data.hasChildren) { const isHighlighted = params.data.id === this.highlightedId();
return '{bold|' + params.name + '}'; let style = 'normal';
if (isHighlighted) {
style = 'highlighted';
} else if (params.data.hasChildren) {
style = 'bold';
} }
return '{normal|' + params.name + '}';
return `{${style}|${params.name}}`;
}, },
rich: { rich: {
bold: { highlighted: {
fontWeight: 'bold', fontWeight: 'bold',
color: colors.warning,
}, },
normal: { normal: {
fontWeight: 'normal', fontWeight: 'normal',
}, },
bold: {
fontWeight: 'bold',
},
}, },
}, },
leaves: { leaves: {
@@ -539,6 +833,70 @@ export class HierarchyChartComponent implements OnInit {
}; };
} }
/* ------------------------------ chart instance ---------------------------- */
/**
* Owns the ECharts instance directly instead of delegating to ngx-echarts.
* This avoids two async `init()` calls racing when the options change while
* the chart is still being created (the "already initialized" warning).
*/
private syncChart(
host: HTMLDivElement | null,
level: TreeLevel | null,
): void {
if (!host || !level) {
this.disposeChart();
return;
}
if (this.chart && this.chartHostElement === host) {
this.chart.setOption(level.options, true);
return;
}
this.disposeChart();
this.chartHostElement = host;
const token = ++this.chartInitToken;
requestAnimationFrame(() => {
if (token !== this.chartInitToken || this.chartHostElement !== host) {
return;
}
void import('echarts').then(({ init }) => {
if (token !== this.chartInitToken || this.chartHostElement !== host) {
return;
}
const chart = init(host);
this.chart = chart;
chart.setOption(level.options, true);
chart.on('click', (params) => this.onChartNodeClick(params));
this.observeChartSize(host);
});
});
}
private onChartNodeClick(params: unknown): void {
const levelIndex = Math.max(0, this.levels().length - 1);
this.onNodeClick(params, levelIndex);
}
private observeChartSize(host: HTMLDivElement): void {
this.chartResizeObserver?.disconnect();
this.chartResizeObserver = new ResizeObserver(() => this.chart?.resize());
this.chartResizeObserver.observe(host);
}
private disposeChart(): void {
this.chartInitToken++;
this.chartResizeObserver?.disconnect();
this.chartResizeObserver = null;
this.chart?.dispose();
this.chart = null;
this.chartHostElement = null;
}
/* --------------------------------- saving -------------------------------- */ /* --------------------------------- saving -------------------------------- */
/** /**
@@ -551,7 +909,7 @@ export class HierarchyChartComponent implements OnInit {
this.orgminerService.saveHierarchy(children as any).subscribe({ this.orgminerService.saveHierarchy(children as any).subscribe({
next: (response) => { next: (response) => {
this.snackBar.open('Hierarchy saved successfully', 'Close', { this.snackBar.open('Hierarchie gespeichert.', 'OK', {
duration: 3000, duration: 3000,
}); });
@@ -573,9 +931,13 @@ export class HierarchyChartComponent implements OnInit {
} }
}, },
error: (error) => { error: (error) => {
this.snackBar.open('Error saving hierarchy', 'Close', { this.snackBar.open(
duration: 3000, 'Hierarchie konnte nicht gespeichert werden.',
}); 'OK',
{
duration: 4000,
},
);
console.error('[HierarchyChart] error saving hierarchy:', error); console.error('[HierarchyChart] error saving hierarchy:', error);
this.hierarchySaved.set(false); this.hierarchySaved.set(false);
}, },
@@ -25,9 +25,12 @@
</mat-expansion-panel-header> </mat-expansion-panel-header>
<app-hierarchy-chart <app-hierarchy-chart
[hierarchyData]="hierarchyData()" [hierarchyData]="hierarchyData()"
[expanded]="hierarchyExpanded()"
[pendingSuggestion]=" [pendingSuggestion]="
suggestions().find((suggestion) => suggestion.status === 'new') ?? null suggestions().find(
" (suggestion) => suggestion.status === 'new'
) ?? null
"
(analyzeOrgEvent)="analyzeOrg($event)" (analyzeOrgEvent)="analyzeOrg($event)"
(suggestionSaved)="reloadSuggestions()" /> (suggestionSaved)="reloadSuggestions()" />
</mat-expansion-panel> </mat-expansion-panel>
@@ -21,6 +21,8 @@ import { HierarchySuggestion } from '../../api/model/hierarchySuggestion';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
const ORGANIZATION_URL_PARAM = 'orgUrl'; const ORGANIZATION_URL_PARAM = 'orgUrl';
const ORGANIZATION_NAME_PARAM = 'orgName'; const ORGANIZATION_NAME_PARAM = 'orgName';
const ORGANIZATION_FOCUS_PARAM = 'orgFocus';
const ORGANIZATION_FOCUS_PATH_PARAM = 'orgFocusPath';
const ORGMINER_EXPANDED_PARAM = 'orgExpanded'; const ORGMINER_EXPANDED_PARAM = 'orgExpanded';
const ORGMINER_SELECTION_CATEGORY_PARAM = 'orgSelectionCategory'; const ORGMINER_SELECTION_CATEGORY_PARAM = 'orgSelectionCategory';
const ORGMINER_SELECTION_INDEX_PARAM = 'orgSelectionIndex'; const ORGMINER_SELECTION_INDEX_PARAM = 'orgSelectionIndex';
@@ -119,6 +121,8 @@ export class HierarchyComponent implements OnInit {
queryParams: { queryParams: {
[ORGANIZATION_URL_PARAM]: organizationUrl, [ORGANIZATION_URL_PARAM]: organizationUrl,
[ORGANIZATION_NAME_PARAM]: org.name, [ORGANIZATION_NAME_PARAM]: org.name,
[ORGANIZATION_FOCUS_PARAM]: null,
[ORGANIZATION_FOCUS_PATH_PARAM]: null,
[ORGMINER_EXPANDED_PARAM]: null, [ORGMINER_EXPANDED_PARAM]: null,
[ORGMINER_SELECTION_CATEGORY_PARAM]: null, [ORGMINER_SELECTION_CATEGORY_PARAM]: null,
[ORGMINER_SELECTION_INDEX_PARAM]: null, [ORGMINER_SELECTION_INDEX_PARAM]: null,
@@ -4,6 +4,7 @@
subtitle="Suche nach Hochschulen, Forschungszentren und weiteren Einrichtungen."> subtitle="Suche nach Hochschulen, Forschungszentren und weiteren Einrichtungen.">
<app-card-search <app-card-search
[page]="page()" [page]="page()"
[loading]="loading()"
[cardMinWidth]="550" [cardMinWidth]="550"
[cardTmp]="cardTmp" [cardTmp]="cardTmp"
[observers]="observers" [observers]="observers"
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core'; import { Component, computed, inject, input } from '@angular/core';
import { InstitutionPage } from '../../api'; import { InstitutionPage } from '../../api';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
@@ -14,6 +14,7 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter
import { AppInstitutionCardComponent } from '../../shared/ui/app-institution-card/app-institution-card.component'; import { AppInstitutionCardComponent } from '../../shared/ui/app-institution-card/app-institution-card.component';
import { SEARCH_ICON } from '../../shared/ui/icons'; import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({ @Component({
selector: 'app-institutions', selector: 'app-institutions',
@@ -32,6 +33,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class InstitutionsComponent { export class InstitutionsComponent {
institutionPage = input.required<InstitutionPage>(); institutionPage = input.required<InstitutionPage>();
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/institutions'),
);
observers: FilterObserver[] = [ observers: FilterObserver[] = [
{ {
id: 'name', id: 'name',
@@ -1,14 +1,5 @@
<app-page-container> <app-page-container>
<div class="detail-page"> <div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Nachrichten">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Alle Nachrichten
</button>
@if (loading) { @if (loading) {
<app-loading <app-loading
text="Nachricht wird geladen..." text="Nachricht wird geladen..."
@@ -3,29 +3,6 @@
min-width: 0; min-width: 0;
} }
.back-link {
display: inline-flex;
align-items: center;
gap: 6px;
background: none;
border: none;
cursor: pointer;
font-size: 14px;
color: var(--sg-text-muted);
padding: 0;
margin-bottom: 32px;
&:hover {
color: var(--sg-text);
}
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
.state { .state {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -20,7 +20,6 @@ import { WorksService } from '../../api';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { import {
ARROW_BACK_ICON,
CANCEL_ICON, CANCEL_ICON,
CHECK_CIRCLE_ICON, CHECK_CIRCLE_ICON,
CHEVRON_LEFT_ICON, CHEVRON_LEFT_ICON,
@@ -80,7 +79,6 @@ interface NewsArticleDetail {
styleUrl: './news-detail.component.scss', styleUrl: './news-detail.component.scss',
}) })
export class NewsDetailComponent implements OnInit { export class NewsDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly NEWS_ICON = NEWS_ICON; readonly NEWS_ICON = NEWS_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON; readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly CHECK_CIRCLE_ICON = CHECK_CIRCLE_ICON; readonly CHECK_CIRCLE_ICON = CHECK_CIRCLE_ICON;
@@ -182,10 +180,6 @@ export class NewsDetailComponent implements OnInit {
}); });
} }
navigateBack(): void {
this.router.navigate(['/news']);
}
formatDate(dateStr?: string | null): string { formatDate(dateStr?: string | null): string {
if (!dateStr) return '-'; if (!dateStr) return '-';
const date = new Date(dateStr); const date = new Date(dateStr);
@@ -1,14 +1,5 @@
<app-page-container> <app-page-container>
<div class="detail-page"> <div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Patenten">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Alle Patente
</button>
@if (loading) { @if (loading) {
<app-loading <app-loading
text="Patent wird geladen..." text="Patent wird geladen..."
@@ -8,27 +8,6 @@
min-width: 0; min-width: 0;
} }
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero { .hero {
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr) 420px; grid-template-columns: minmax(0, 1fr) 420px;
@@ -1,4 +1,3 @@
import { Location } from '@angular/common';
import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
@@ -16,7 +15,6 @@ import {
} from '../../resolvers/utils/topic-colors'; } from '../../resolvers/utils/topic-colors';
import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { import {
ARROW_BACK_ICON,
BUSINESS_ICON, BUSINESS_ICON,
CATEGORY_ICON, CATEGORY_ICON,
ENGINEERING_ICON, ENGINEERING_ICON,
@@ -58,7 +56,6 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
styleUrl: './patent-detail.component.scss', styleUrl: './patent-detail.component.scss',
}) })
export class PatentDetailComponent implements OnInit { export class PatentDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly PATENT_ICON = PATENT_ICON; readonly PATENT_ICON = PATENT_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON; readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON; readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
@@ -76,7 +73,6 @@ export class PatentDetailComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private readonly patentsService = inject(PatentsService); private readonly patentsService = inject(PatentsService);
private readonly location = inject(Location);
patent: PatentEntry | null = null; patent: PatentEntry | null = null;
loading = true; loading = true;
@@ -104,10 +100,6 @@ export class PatentDetailComponent implements OnInit {
}); });
} }
navigateBack(): void {
this.location.back();
}
formatDate(date: string | null | undefined): string { formatDate(date: string | null | undefined): string {
return formatPatentDate(date); return formatPatentDate(date);
} }
@@ -10,17 +10,6 @@
? null ? null
: 'Suche Patente aus EPO und USPTO und filtere nach Zeitraum, Themen und Klassifikationen.' : 'Suche Patente aus EPO und USPTO und filtere nach Zeitraum, Themen und Klassifikationen.'
"> ">
@if (showDetail && selectedPatent) {
<button
pageActions
mat-stroked-button
color="primary"
type="button"
(click)="closeDetail()">
← Zurück zu den Patenten
</button>
}
@if (error) { @if (error) {
<p class="state-message error">Fehler beim Laden der Patente.</p> <p class="state-message error">Fehler beim Laden der Patente.</p>
} @else if (showDetail && selectedPatent) { } @else if (showDetail && selectedPatent) {
@@ -24,6 +24,7 @@ import {
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component'; import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
import { HELP_ICON, PATENT_ICON } from '../../shared/ui/icons'; import { HELP_ICON, PATENT_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { BackNavigationService } from '../../shared/services/back-navigation.service';
type PatentSource = 'EPO' | 'USPTO'; type PatentSource = 'EPO' | 'USPTO';
@@ -69,6 +70,8 @@ export class PatentsComponent {
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private patentsApi = inject(PatentsService); private patentsApi = inject(PatentsService);
private destroyRef = inject(DestroyRef); private destroyRef = inject(DestroyRef);
private backNavigation = inject(BackNavigationService);
private unregisterLocalBack: (() => void) | null = null;
patents: PatentEntry[] = []; patents: PatentEntry[] = [];
total = 0; total = 0;
@@ -92,6 +95,8 @@ export class PatentsComponent {
readonly expandedClassificationKeys = new Set<string>(); readonly expandedClassificationKeys = new Set<string>();
constructor() { constructor() {
this.destroyRef.onDestroy(() => this.unregisterLocalBack?.());
this.route.queryParams this.route.queryParams
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((qp) => { .subscribe((qp) => {
@@ -181,12 +186,20 @@ export class PatentsComponent {
} }
selectPatent(patent: PatentEntry): void { selectPatent(patent: PatentEntry): void {
this.unregisterLocalBack?.();
this.unregisterLocalBack = this.backNavigation.registerLocalBack(() =>
this.closeDetail(),
);
this.selectedPatent = patent; this.selectedPatent = patent;
this.showDetail = true; this.showDetail = true;
this.expandedClassificationKeys.clear(); this.expandedClassificationKeys.clear();
} }
closeDetail(): void { closeDetail(): void {
this.unregisterLocalBack?.();
this.unregisterLocalBack = null;
this.showDetail = false; this.showDetail = false;
this.selectedPatent = null; this.selectedPatent = null;
this.expandedClassificationKeys.clear(); this.expandedClassificationKeys.clear();
@@ -53,6 +53,7 @@
<div class="institution-row"> <div class="institution-row">
<app-institution-chip <app-institution-chip
[institution]="inst" [institution]="inst"
[skText]="loading()"
size="mini" size="mini"
[showIcon]="true" [showIcon]="true"
[isClickable]="true" [isClickable]="true"
@@ -114,6 +114,8 @@
</div> </div>
} }
<app-live-region [text]="resultAnnouncement" />
<div class="toolbar"> <div class="toolbar">
<span [skText]="loading" class="result-count">{{ <span [skText]="loading" class="result-count">{{
resultRange() resultRange()
@@ -151,11 +153,15 @@
<!--><span>Sortiert nach Publikationen und Zitierungen</span>--> <!--><span>Sortiert nach Publikationen und Zitierungen</span>-->
</div> </div>
@if (getPersons().length) { @if (loading) {
<app-page-skeleton
variant="cards-plain"
[compact]="true"
[cardMinWidth]="280" />
} @else if (getPersons().length) {
<div class="person-grid"> <div class="person-grid">
@for (person of getPersons(); track person.id) { @for (person of getPersons(); track person.id) {
<app-person-card <app-person-card
[loading]="loading"
[person]="person" [person]="person"
[isBookmarked]="isBookmarked(person)" [isBookmarked]="isBookmarked(person)"
[selectedTopics]="selectedTopics()" [selectedTopics]="selectedTopics()"
@@ -12,8 +12,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRadioModule } from '@angular/material/radio'; import { MatRadioModule } from '@angular/material/radio';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { ResolverStateService } from '../../shared/services/resolver-state.service'; import { NavigationStateService } from '../../shared/services/navigation-state.service';
import { import {
CustomAuthor, CustomAuthor,
DehydratedInstitution, DehydratedInstitution,
@@ -48,6 +47,8 @@ import { BookmarkService } from '../../shared/services/bookmark.service';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component'; import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { LiveRegionComponent } from '../../shared/ui/live-region/live-region.component';
import { PageSkeletonComponent } from '../../shared/ui/page-skeleton/page-skeleton.component';
import { import {
CLOSE_ICON, CLOSE_ICON,
FILTER_ICON, FILTER_ICON,
@@ -81,6 +82,8 @@ type InstitutionYearFilterMode = 'in' | 'from' | 'between';
SkTextDirective, SkTextDirective,
ComponentTooltipDirective, ComponentTooltipDirective,
PageContainerComponent, PageContainerComponent,
LiveRegionComponent,
PageSkeletonComponent,
], ],
templateUrl: './person-list.component.html', templateUrl: './person-list.component.html',
styleUrl: './person-list.component.scss', styleUrl: './person-list.component.scss',
@@ -105,9 +108,9 @@ export class PersonListComponent {
private readonly bookmarkService = inject(BookmarkService); private readonly bookmarkService = inject(BookmarkService);
public readonly state = inject(SharedStateService); public readonly state = inject(SharedStateService);
public readonly paginationService = inject(PaginationService); public readonly paginationService = inject(PaginationService);
public readonly resolverStateService = inject(ResolverStateService); public readonly navigationState = inject(NavigationStateService);
readonly loadingState = computed(() => readonly loadingState = computed(() =>
this.resolverStateService.isResolvingInside('/persons'), this.navigationState.isResolvingInside('/persons'),
); );
persons: CustomAuthor[] = []; persons: CustomAuthor[] = [];
total = 0; total = 0;
@@ -600,6 +603,13 @@ export class PersonListComponent {
return `${start}-${end} von ${this.total} Personen`; return `${start}-${end} von ${this.total} Personen`;
} }
/** Announced to screen readers whenever a new result set is rendered. */
get resultAnnouncement(): string {
if (this.loading) return '';
if (!this.total) return 'Keine Personen gefunden';
return this.resultRange();
}
// Bookmarks // Bookmarks
toggleBookmark(person: CustomAuthor): void { toggleBookmark(person: CustomAuthor): void {
this.bookmarkService this.bookmarkService
@@ -34,7 +34,7 @@
<div class="toggle-group"> <div class="toggle-group">
<mat-button-toggle-group <mat-button-toggle-group
class="mat-button-toggle-group" class="mat-button-toggle-group"
aria-label="Select view" aria-label="Ansicht wählen"
(change)="onToggleChange($event)" (change)="onToggleChange($event)"
[value]="displayedTable()" [value]="displayedTable()"
style="width: 100%"> style="width: 100%">
@@ -9,7 +9,7 @@ import {
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ResolverStateService } from '../../shared/services/resolver-state.service'; import { NavigationStateService } from '../../shared/services/navigation-state.service';
import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver'; import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver';
import { import {
CardSearchComponent, CardSearchComponent,
@@ -27,7 +27,7 @@ import { SelectorOption } from '../../shared/ui/query-param-selector/query-param
export class PersonNewsComponent implements OnInit { export class PersonNewsComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private readonly resolverStateService = inject(ResolverStateService); private readonly navigationState = inject(NavigationStateService);
readonly sortingDirectionOptions: SelectorOption[] = [ readonly sortingDirectionOptions: SelectorOption[] = [
{ value: 'desc', display_name: 'Neueste zuerst' }, { value: 'desc', display_name: 'Neueste zuerst' },
@@ -40,7 +40,7 @@ export class PersonNewsComponent implements OnInit {
private currentSize = 10; private currentSize = 10;
get loading(): boolean { get loading(): boolean {
return this.resolverStateService.isResolving(); return this.navigationState.isResolving();
} }
readonly page = computed<Page>(() => ({ readonly page = computed<Page>(() => ({
@@ -33,10 +33,11 @@
(expandedChange)="onSubfieldLegendExpandedChange($event)"> (expandedChange)="onSubfieldLegendExpandedChange($event)">
</app-topic-legend> </app-topic-legend>
<div class="view-toggle" aria-label="Ansicht wechseln"> <div class="view-toggle" role="group" aria-label="Ansicht wechseln">
<button <button
type="button" type="button"
[class.active]="timelineViewMode === 'years'" [class.active]="timelineViewMode === 'years'"
[attr.aria-pressed]="timelineViewMode === 'years'"
(click)="setTimelineViewMode('years')"> (click)="setTimelineViewMode('years')">
Jahre Jahre
</button> </button>
@@ -44,6 +45,7 @@
<button <button
type="button" type="button"
[class.active]="timelineViewMode === 'compact'" [class.active]="timelineViewMode === 'compact'"
[attr.aria-pressed]="timelineViewMode === 'compact'"
(click)="setTimelineViewMode('compact')"> (click)="setTimelineViewMode('compact')">
Kompakt Kompakt
</button> </button>
@@ -51,6 +53,7 @@
<button <button
type="button" type="button"
[class.active]="timelineViewMode === 'wordcloud'" [class.active]="timelineViewMode === 'wordcloud'"
[attr.aria-pressed]="timelineViewMode === 'wordcloud'"
(click)="setTimelineViewMode('wordcloud')"> (click)="setTimelineViewMode('wordcloud')">
Wordcloud Wordcloud
</button> </button>
@@ -1,30 +0,0 @@
@if (loading) {
<div class="word-cloud-state">Forschungsthemen werden geladen ...</div>
} @else if (loadFailed) {
<div class="word-cloud-state">
Forschungsthemen konnten nicht geladen werden.
</div>
} @else if (words.length) {
<div class="word-cloud-chart">
@for (word of words; track word.name) {
<button
type="button"
class="word-cloud-word"
[class.word-cloud-word-active]="isWordActiveByLegend(word)"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[disabled]="!word.topicId"
[attr.aria-label]="wordAriaLabel(word)"
[appComponentTooltip]="AppTopicTooltipComponent"
[tooltipInputs]="tooltipInputsFor(word)"
[tooltipDisabled]="!word.rawTopicId"
[tooltipMaxWidth]="'500px'"
(click)="selectWord(word)">
{{ word.name }}
</button>
}
</div>
} @else {
<p class="word-cloud-state">Keine Forschungsthemen gefunden.</p>
}
@@ -1,59 +0,0 @@
:host {
display: block;
min-height: 420px;
}
.word-cloud-chart {
width: 100%;
min-height: 420px;
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 0.35em 1em;
padding: 1.5rem 1rem;
box-sizing: border-box;
}
.word-cloud-word {
appearance: none;
border: none;
background: none;
padding: 0.1em 0.3em;
margin: 0;
border-radius: 6px;
font-family: 'Open Sans', Arial, sans-serif;
line-height: 1.1;
cursor: pointer;
transition:
transform 0.15s ease,
background-color 0.15s ease,
box-shadow 0.15s ease;
&:hover:not(:disabled),
&:focus-visible {
transform: scale(1.08);
outline: none;
}
&:disabled {
cursor: default;
}
}
.word-cloud-word-active {
background: color-mix(in srgb, currentColor 14%, transparent);
box-shadow: inset 0 0 0 1.5px currentColor;
}
.word-cloud-state {
margin: 0;
min-height: 420px;
display: flex;
align-items: center;
justify-content: center;
color: var(--sg-text-muted);
font-size: 14px;
text-align: center;
}
@@ -1,305 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ComponentTooltipDirective } from '../../../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors';
import {
getTopicLegendFieldId,
getTopicLegendSubfieldId,
TopicLegendTopic,
} from '../../../../resolvers/utils/topic-legend';
import type {
TopicTimelineElement,
TopicTimelineTopic,
} from '../research-timeline/research-timeline.component';
import {
formatYearRange,
normalizeSelectedYears,
} from '../../../../resolvers/utils/year-range';
import { workQueryParamKeys } from '../../../../resolvers/work-page.resolver';
interface WordTooltipInputs {
topicId: string;
secondaryActionLabel: string | null;
secondaryActionLink: unknown[] | null;
secondaryActionQueryParams: Record<string, string | number | number[]>;
}
export interface WordCloudWord {
name: string;
topicId: string;
rawTopicId: string;
fieldLegendId: string;
subfieldLegendId: string;
color: string;
fontSize: number;
fontWeight: number;
}
export interface ResearchWordcloud {
words: WordCloudWord[];
legendTopics: TopicLegendTopic[];
}
const displayedWordLimit = 30;
const minimumFontSize = 12;
const maximumFontSize = 32;
interface AggregatedTopic {
name: string;
count: number;
legendTopic: TopicLegendTopic;
}
export function buildResearchWordcloud(
elements: readonly TopicTimelineElement[],
startYear: number | undefined,
endYear: number | undefined,
): ResearchWordcloud {
const yearsInRange = elements.filter((element) =>
isWithinYearRange(element.year, startYear, endYear),
);
const aggregated = aggregateTopics(yearsInRange);
if (aggregated.size === 0) {
return { words: [], legendTopics: [] };
}
const displayed = Array.from(aggregated.values())
.sort(
(left, right) =>
right.count - left.count || left.name.localeCompare(right.name),
)
.slice(0, displayedWordLimit);
const intensity = buildIntensityScale(displayed);
const words = displayed.map((topic): WordCloudWord => {
const legendTopic = topic.legendTopic;
const scale = intensity(topic.count);
return {
name: topic.name,
topicId: legendTopic.id ?? '',
rawTopicId: stripOpenAlexId(legendTopic.id),
fieldLegendId: getTopicLegendFieldId(legendTopic),
subfieldLegendId: getTopicLegendSubfieldId(legendTopic),
color: topicHierarchyColor(legendTopic),
fontSize: Math.round(
minimumFontSize + scale * (maximumFontSize - minimumFontSize),
),
fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400,
};
});
return {
words: centreWords(words),
legendTopics: displayed.map((topic) => topic.legendTopic),
};
}
function aggregateTopics(
elements: readonly TopicTimelineElement[],
): Map<string, AggregatedTopic> {
const aggregated = new Map<string, AggregatedTopic>();
for (const element of elements) {
for (const topic of element.primary_topics ?? []) {
if (!topic.name) {
continue;
}
const key = topic.id ?? topic.name;
const existing = aggregated.get(key);
if (existing) {
existing.count += topic.count;
continue;
}
aggregated.set(key, {
name: topic.name,
count: topic.count,
legendTopic: toLegendTopic(topic),
});
}
}
return aggregated;
}
function buildIntensityScale(
topics: readonly AggregatedTopic[],
): (count: number) => number {
const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0)));
const minimumWeight = Math.min(...weights);
const maximumWeight = Math.max(...weights);
if (maximumWeight === minimumWeight) {
return () => 0.5;
}
return (count) =>
(Math.sqrt(Math.max(count, 0)) - minimumWeight) /
(maximumWeight - minimumWeight);
}
function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic {
return {
id: topic.id,
name: topic.name,
field_id: topic.field_id,
field_name: topic.field_name,
field_description: topic.field_description,
domain_id: topic.domain_id,
domain_name: topic.domain_name,
domain_description: topic.domain_description,
subfield_id: topic.subfield_id,
subfield_name: topic.subfield_name,
subfield_description: topic.subfield_description,
};
}
function isWithinYearRange(
year: number | undefined,
startYear: number | undefined,
endYear: number | undefined,
): boolean {
if (startYear !== undefined && (year === undefined || year < startYear)) {
return false;
}
if (endYear !== undefined && (year === undefined || year > endYear)) {
return false;
}
return true;
}
function centreWords(words: WordCloudWord[]): WordCloudWord[] {
const centred: WordCloudWord[] = [];
words.forEach((word, index) => {
if (index % 2 === 0) {
centred.push(word);
return;
}
centred.unshift(word);
});
return centred;
}
function stripOpenAlexId(id: string | null | undefined): string {
return (id ?? '').replace('https://openalex.org/', '');
}
@Component({
selector: 'app-research-wordcloud',
standalone: true,
imports: [ComponentTooltipDirective],
templateUrl: './research-wordcloud.component.html',
styleUrl: './research-wordcloud.component.scss',
})
export class ResearchWordcloudComponent {
readonly AppTopicTooltipComponent = AppTopicTooltipComponent;
@Input() set words(value: WordCloudWord[]) {
this._words = value;
this.rebuildTooltipInputs();
}
get words(): WordCloudWord[] {
return this._words;
}
@Input() set personPublicationsLink(value: unknown[] | null) {
this._personPublicationsLink = value;
this.rebuildTooltipInputs();
}
@Input() set personName(value: string) {
this._personName = value;
this.rebuildTooltipInputs();
}
@Input() set selectedYears(value: number[]) {
this._selectedYears = normalizeSelectedYears(value);
this.rebuildTooltipInputs();
}
@Input() loading = false;
@Input() loadFailed = false;
@Input() activeFieldIds: ReadonlySet<string> = new Set();
@Input() activeSubfieldIds: ReadonlySet<string> = new Set();
@Output() wordSelect = new EventEmitter<WordCloudWord>();
private _words: WordCloudWord[] = [];
private _personPublicationsLink: unknown[] | null = null;
private _personName = '';
private _selectedYears: number[] = [];
private tooltipInputsByTopic = new Map<string, WordTooltipInputs>();
selectWord(word: WordCloudWord): void {
if (!word.topicId) {
return;
}
this.wordSelect.emit(word);
}
isWordActiveByLegend(word: WordCloudWord): boolean {
return (
this.activeFieldIds.has(word.fieldLegendId) ||
(word.subfieldLegendId.length > 0 &&
this.activeSubfieldIds.has(word.subfieldLegendId))
);
}
tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null {
return this.tooltipInputsByTopic.get(word.topicId) ?? null;
}
wordAriaLabel(word: WordCloudWord): string {
return `${this.publicationsLabel()} zum Thema ${word.name}${this.yearRangeSuffix()}`;
}
private publicationsLabel(): string {
return this._personName
? `Publikationen von ${this._personName}`
: 'Publikationen dieser Person';
}
private yearRangeSuffix(): string {
return this._selectedYears.length > 0
? ` ${formatYearRange(this._selectedYears)}`
: '';
}
private rebuildTooltipInputs(): void {
const label = `${this.publicationsLabel()}${this.yearRangeSuffix()}`;
const link = this._personPublicationsLink;
this.tooltipInputsByTopic = new Map(
this._words
.filter((word) => word.topicId)
.map((word) => [
word.topicId,
{
topicId: word.rawTopicId,
secondaryActionLabel: link ? label : null,
secondaryActionLink: link,
secondaryActionQueryParams: {
[workQueryParamKeys.page]: 0,
...(this._selectedYears.length > 0
? { [workQueryParamKeys.years]: this._selectedYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
},
},
]),
);
}
}
@@ -22,16 +22,22 @@
(yearSelect)="onTimelineYearSelect($event)" (yearSelect)="onTimelineYearSelect($event)"
(loadEarlierYears)="onTimelineLoadEarlierYears()" (loadEarlierYears)="onTimelineLoadEarlierYears()"
(legendSelectionChange)="onLegendSelectionChange($event)"> (legendSelectionChange)="onLegendSelectionChange($event)">
<app-research-wordcloud <app-keyword-wordcloud
timeline-wordcloud-content timeline-wordcloud-content
variant="bare"
[title]="null"
[words]="wordCloudWords" [words]="wordCloudWords"
[loading]="loadingWordCloud" [loading]="loadingWordCloud"
[loadFailed]="wordCloudLoadFailed" [loadFailed]="wordCloudLoadFailed"
[activeFieldIds]="activeLegendFieldIds" loadingMessage="Forschungsthemen werden geladen ..."
[activeSubfieldIds]="activeLegendSubfieldIds" loadFailedMessage="Forschungsthemen konnten nicht geladen werden."
[selectedYears]="wordCloudYears" emptyTitle="Keine Forschungsthemen gefunden."
[personName]="personName" emptyMessage=""
[personPublicationsLink]="personPublicationsLink" [interactive]="true"
(wordSelect)="onWordClick($event)" /> chartAriaLabel="Wordcloud der Forschungsthemen"
[isWordActive]="isWordActiveByLegend"
[wordAriaLabel]="wordCloudAriaLabel"
[wordTooltip]="wordCloudTooltip"
(wordClick)="onWordClick($event)" />
</app-research-timeline> </app-research-timeline>
</section> </section>
@@ -14,20 +14,33 @@ import {
} from './components/research-timeline/research-timeline.component'; } from './components/research-timeline/research-timeline.component';
import { import {
buildResearchWordcloud, buildResearchWordcloud,
ResearchWordcloudComponent,
WordCloudWord, WordCloudWord,
} from './components/research-wordcloud/research-wordcloud.component'; } from './research-wordcloud.utils';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import { import {
TopicLegendSelectionState, TopicLegendSelectionState,
TopicLegendTopic, TopicLegendTopic,
} from '../../resolvers/utils/topic-legend'; } from '../../resolvers/utils/topic-legend';
import { PersonDataResolved } from '../../resolvers/person.resolver'; import { PersonDataResolved } from '../../resolvers/person.resolver';
import { formatYearRange } from '../../resolvers/utils/year-range';
import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import {
KeywordWordcloudComponent,
WordCloudTooltipConfig,
WordCloudWordData,
} from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component';
type WordTooltipInputs = {
topicId: string;
secondaryActionLabel: string | null;
secondaryActionLink: unknown[] | null;
secondaryActionQueryParams: Record<string, string | number | number[]>;
};
@Component({ @Component({
selector: 'app-person-overview', selector: 'app-person-overview',
standalone: true, standalone: true,
imports: [ResearchTimelineComponent, ResearchWordcloudComponent], imports: [ResearchTimelineComponent, KeywordWordcloudComponent],
templateUrl: './person-overview.component.html', templateUrl: './person-overview.component.html',
styleUrl: './person-overview.component.scss', styleUrl: './person-overview.component.scss',
}) })
@@ -73,6 +86,27 @@ export class PersonOverviewComponent implements OnInit {
personName = ''; personName = '';
personPublicationsLink: unknown[] | null = null; personPublicationsLink: unknown[] | null = null;
readonly wordCloudTooltip: WordCloudTooltipConfig = {
component: AppTopicTooltipComponent,
inputs: (word) => this.tooltipInputsFor(word as WordCloudWord),
disabled: (word) => !(word as WordCloudWord).rawTopicId,
maxWidth: '500px',
};
readonly isWordActiveByLegend = (word: WordCloudWordData): boolean => {
const topicWord = word as WordCloudWord;
return (
this.activeLegendFieldIds.has(topicWord.fieldLegendId) ||
(topicWord.subfieldLegendId.length > 0 &&
this.activeLegendSubfieldIds.has(topicWord.subfieldLegendId))
);
};
readonly wordCloudAriaLabel = (word: WordCloudWordData): string => {
const topicWord = word as WordCloudWord;
return `${this.publicationsLabel()} zum Thema ${topicWord.name}${this.yearRangeSuffix()}`;
};
ngOnInit(): void { ngOnInit(): void {
combineLatest(this.route.pathFromRoot.map((route) => route.paramMap)) combineLatest(this.route.pathFromRoot.map((route) => route.paramMap))
.pipe( .pipe(
@@ -222,8 +256,9 @@ export class PersonOverviewComponent implements OnInit {
this.loadCompleteTopicTimeline(this.currentAuthorId); this.loadCompleteTopicTimeline(this.currentAuthorId);
} }
onWordClick(word: WordCloudWord): void { onWordClick(word: WordCloudWordData): void {
if (!word.topicId) return; const topicWord = word as WordCloudWord;
if (!topicWord.topicId) return;
void this.router.navigate(['../publications'], { void this.router.navigate(['../publications'], {
relativeTo: this.route, relativeTo: this.route,
queryParams: { queryParams: {
@@ -231,7 +266,7 @@ export class PersonOverviewComponent implements OnInit {
...(this.wordCloudYears.length > 0 ...(this.wordCloudYears.length > 0
? { [workQueryParamKeys.years]: this.wordCloudYears } ? { [workQueryParamKeys.years]: this.wordCloudYears }
: {}), : {}),
[workQueryParamKeys.topicId]: word.topicId, [workQueryParamKeys.topicId]: topicWord.topicId,
}, },
}); });
} }
@@ -241,6 +276,39 @@ export class PersonOverviewComponent implements OnInit {
this.activeLegendSubfieldIds = selection.subfieldIds; this.activeLegendSubfieldIds = selection.subfieldIds;
} }
private tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null {
if (!word.topicId) return null;
const link = this.personPublicationsLink;
return {
topicId: word.rawTopicId,
secondaryActionLabel: link
? `${this.publicationsLabel()}${this.yearRangeSuffix()}`
: null,
secondaryActionLink: link,
secondaryActionQueryParams: {
[workQueryParamKeys.page]: 0,
...(this.wordCloudYears.length > 0
? { [workQueryParamKeys.years]: this.wordCloudYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
},
};
}
private publicationsLabel(): string {
return this.personName
? `Publikationen von ${this.personName}`
: 'Publikationen dieser Person';
}
private yearRangeSuffix(): string {
return this.wordCloudYears.length > 0
? ` ${formatYearRange(this.wordCloudYears)}`
: '';
}
private findAuthorId(paramMaps: readonly ParamMap[]): string { private findAuthorId(paramMaps: readonly ParamMap[]): string {
return ( return (
paramMaps paramMaps
@@ -0,0 +1,166 @@
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import {
getTopicLegendFieldId,
getTopicLegendSubfieldId,
TopicLegendTopic,
} from '../../resolvers/utils/topic-legend';
import type { WordCloudWordData } from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component';
import type {
TopicTimelineElement,
TopicTimelineTopic,
} from './components/research-timeline/research-timeline.component';
export interface WordCloudWord extends WordCloudWordData {
topicId: string;
rawTopicId: string;
fieldLegendId: string;
subfieldLegendId: string;
color: string;
fontSize: number;
fontWeight: number;
}
export interface ResearchWordcloud {
words: WordCloudWord[];
legendTopics: TopicLegendTopic[];
}
const displayedWordLimit = 30;
const minimumFontSize = 12;
const maximumFontSize = 32;
interface AggregatedTopic {
name: string;
count: number;
legendTopic: TopicLegendTopic;
}
export function buildResearchWordcloud(
elements: readonly TopicTimelineElement[],
startYear: number | undefined,
endYear: number | undefined,
): ResearchWordcloud {
const yearsInRange = elements.filter((element) =>
isWithinYearRange(element.year, startYear, endYear),
);
const aggregated = aggregateTopics(yearsInRange);
if (aggregated.size === 0) {
return { words: [], legendTopics: [] };
}
const displayed = Array.from(aggregated.values())
.sort(
(left, right) =>
right.count - left.count || left.name.localeCompare(right.name),
)
.slice(0, displayedWordLimit);
const intensity = buildIntensityScale(displayed);
const words = displayed.map((topic): WordCloudWord => {
const legendTopic = topic.legendTopic;
const scale = intensity(topic.count);
return {
name: topic.name,
topicId: legendTopic.id ?? '',
rawTopicId: stripOpenAlexId(legendTopic.id),
fieldLegendId: getTopicLegendFieldId(legendTopic),
subfieldLegendId: getTopicLegendSubfieldId(legendTopic),
color: topicHierarchyColor(legendTopic),
fontSize: Math.round(
minimumFontSize + scale * (maximumFontSize - minimumFontSize),
),
fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400,
};
});
return {
words,
legendTopics: displayed.map((topic) => topic.legendTopic),
};
}
function aggregateTopics(
elements: readonly TopicTimelineElement[],
): Map<string, AggregatedTopic> {
const aggregated = new Map<string, AggregatedTopic>();
for (const element of elements) {
for (const topic of element.primary_topics ?? []) {
if (!topic.name) {
continue;
}
const key = topic.id ?? topic.name;
const existing = aggregated.get(key);
if (existing) {
existing.count += topic.count;
continue;
}
aggregated.set(key, {
name: topic.name,
count: topic.count,
legendTopic: toLegendTopic(topic),
});
}
}
return aggregated;
}
function buildIntensityScale(
topics: readonly AggregatedTopic[],
): (count: number) => number {
const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0)));
const minimumWeight = Math.min(...weights);
const maximumWeight = Math.max(...weights);
if (maximumWeight === minimumWeight) {
return () => 0.5;
}
return (count) =>
(Math.sqrt(Math.max(count, 0)) - minimumWeight) /
(maximumWeight - minimumWeight);
}
function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic {
return {
id: topic.id,
name: topic.name,
field_id: topic.field_id,
field_name: topic.field_name,
field_description: topic.field_description,
domain_id: topic.domain_id,
domain_name: topic.domain_name,
domain_description: topic.domain_description,
subfield_id: topic.subfield_id,
subfield_name: topic.subfield_name,
subfield_description: topic.subfield_description,
};
}
function isWithinYearRange(
year: number | undefined,
startYear: number | undefined,
endYear: number | undefined,
): boolean {
if (startYear !== undefined && (year === undefined || year < startYear)) {
return false;
}
if (endYear !== undefined && (year === undefined || year > endYear)) {
return false;
}
return true;
}
function stripOpenAlexId(id: string | null | undefined): string {
return (id ?? '').replace('https://openalex.org/', '');
}
@@ -1,183 +1,231 @@
<app-page-container> <app-page-container>
@if (!isPersonLoading()) { @if (!isPersonLoading()) {
<section class="person-hero"> <section class="person-hero">
<div class="profile-card"> <div class="profile-card">
<div class="profile-avatar">{{ initials() }}</div> <div class="profile-avatar">{{ initials() }}</div>
<div class="profile-main"> <div class="profile-main">
<div class="name-line"> <div class="name-line">
<span>Person</span> <span>Person</span>
<h1>{{ displayName() }}</h1> <h1>{{ displayName() }}</h1>
<button <button
type="button" type="button"
class="profile-bookmark-button" class="profile-bookmark-button"
[class.bookmarked]="bookmarkService.isBookmarked(person()?.id)" [class.bookmarked]="bookmarkService.isBookmarked(person()?.id)"
[attr.aria-label]=" [attr.aria-label]="
bookmarkService.isBookmarked(person()?.id) bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen' ? 'Bookmark entfernen'
: 'Person bookmarken' : 'Person bookmarken'
" "
[matTooltip]=" [matTooltip]="
bookmarkService.isBookmarked(person()?.id) bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen' ? 'Bookmark entfernen'
: 'Person bookmarken' : 'Person bookmarken'
" "
(click)="toggleBookmark()"> (click)="toggleBookmark()">
<mat-icon>{{ <mat-icon>{{
bookmarkService.isBookmarked(person()?.id) bookmarkService.isBookmarked(person()?.id)
? BOOKMARK_ICON ? BOOKMARK_ICON
: BOOKMARK_BORDER_ICON : BOOKMARK_BORDER_ICON
}}</mat-icon> }}</mat-icon>
</button> </button>
</div>
@if (resolvedInstitution(); as inst) {
<div class="institution-line">
<app-institution-chip
[institution]="inst"
size="normal"
[showIcon]="true"
[isClickable]="false" />
@if (secondaryInstitutions().length > 0) {
<button
type="button"
class="more-institutions-btn"
[appComponentTooltip]="PersonInstitutionTooltipListComponent"
[tooltipInputs]="{ institutions: secondaryInstitutions() }"
[attr.aria-label]="
secondaryInstitutions().length + ' weitere Institutionen'
">
<mat-icon class="more-info-icon">{{ MORE_INFO_ICON }}</mat-icon>
<span class="count-text"
>+{{ secondaryInstitutions().length }}</span
>
</button>
}
</div> </div>
} @if (
@if ( resolvedInstitution() ||
worksCount() !== null || citedByCount() !== null || h_index() !== null (canOpenVerifiedOrganizationHierarchy() &&
) { verifiedOrganizations().length > 0)
<span class="stats-line"> ) {
@if (worksCount() !== null) { <div class="institution-line">
<span class="stat-item"> @if (resolvedInstitution(); as inst) {
<mat-icon class="stat-icon">{{ PUBLICATION_ICON }}</mat-icon> <app-institution-chip
{{ worksCount() | number }} Publikationen [institution]="inst"
</span> size="normal"
} [showIcon]="true"
@if (worksCount() !== null && citedByCount() !== null) { [isClickable]="false" />
· @if (secondaryInstitutions().length > 0) {
} <button
@if (citedByCount() !== null) { type="button"
<span class="stat-item"> class="more-institutions-btn"
<mat-icon class="stat-icon">{{ CITATION_ICON }}</mat-icon> [appComponentTooltip]="
{{ citedByCount() | number }} Zitationen PersonInstitutionTooltipListComponent
</span> "
} [tooltipInputs]="{ institutions: secondaryInstitutions() }"
@if ( [attr.aria-label]="
(worksCount() !== null || citedByCount() !== null) && secondaryInstitutions().length + ' weitere Institutionen'
h_index() !== null ">
) { <mat-icon class="more-info-icon">{{
· MORE_INFO_ICON
} }}</mat-icon>
@if (h_index() !== null) { <span class="count-text"
<span >+{{ secondaryInstitutions().length }}</span
class="stat-item has-tooltip" >
[matTooltip]=" </button>
'Der h-Index beträgt ' + }
h_index() + }
': ' + @if (canOpenVerifiedOrganizationHierarchy()) {
h_index() + @for (org of verifiedOrganizations(); track $index) {
' Publikationen wurden jeweils mindestens ' + @if (canOpenOrganizationHierarchy(org)) {
h_index() + <button
'-mal zitiert.' type="button"
" class="verified-org-chip"
matTooltipPosition="right" [matTooltip]="
[matTooltipShowDelay]="250"> 'Verifizierte Organisation: ' +
<mat-icon class="stat-icon">{{ TRENDING_UP_ICON }}</mat-icon> org.org_name +
h-Index {{ h_index() }} ' – Hierarchie öffnen'
</span> "
} matTooltipPosition="right"
</span> [matTooltipShowDelay]="250"
} [attr.aria-label]="
@if (displayCareerStage() || orcid()) { 'Verifizierte Organisation: ' +
<div class="meta-line"> org.org_name +
<app-career-stage-chip '. Hierarchie öffnen.'
[careerStage]="displayCareerStage()" "
[activeYears]="person()?.career_metrics?.active_years" /> (click)="openOrganizationHierarchy(org)">
@if (orcid(); as orcidId) { <mat-icon>{{ VERIFIED_ICON }}</mat-icon>
<a <span>{{ org.org_name }}</span>
class="orcid-chip" </button>
[href]="orcidUrl()" } @else {
target="_blank" <span
rel="noopener" class="verified-org-chip static"
matTooltip="ORCID-Profil öffnen" [matTooltip]="
matTooltipPosition="right" 'Verifizierte Organisation: ' + org.org_name
[matTooltipShowDelay]="250"> "
<mat-icon>{{ VERIFIED_ICON }}</mat-icon> matTooltipPosition="right"
{{ orcidId }} [matTooltipShowDelay]="250">
</a> <mat-icon>{{ VERIFIED_ICON }}</mat-icon>
} <span>{{ org.org_name }}</span>
</div> </span>
} }
</div> }
</div> }
<aside class="sidebar"> </div>
<div class="bio-card"> }
@if (isBioLoading()) { @if (
<app-loading worksCount() !== null ||
text="Biografie wird geladen..." citedByCount() !== null ||
[icon]="DESCRIPTION_ICON" h_index() !== null
[size]="150" ) {
[diameter]="150"></app-loading> <span class="stats-line">
} @else if (personBio() != null) { @if (worksCount() !== null) {
<div class="bio-header"> <span class="stat-item">
<h3>Biografie</h3> <mat-icon class="stat-icon">{{ PUBLICATION_ICON }}</mat-icon>
<span {{ worksCount() | number }} Publikationen
class="ai-badge" </span>
matTooltip="Diese Biografie wurde automatisch mit KI erstellt und kann Fehler enthalten." }
matTooltipPosition="above" @if (worksCount() !== null && citedByCount() !== null) {
[matTooltipShowDelay]="250"> ·
<mat-icon>{{ AI_GENERATED_ICON }}</mat-icon> }
KI-generiert @if (citedByCount() !== null) {
<span class="stat-item">
<mat-icon class="stat-icon">{{ CITATION_ICON }}</mat-icon>
{{ citedByCount() | number }} Zitationen
</span>
}
@if (
(worksCount() !== null || citedByCount() !== null) &&
h_index() !== null
) {
·
}
@if (h_index() !== null) {
<span
class="stat-item has-tooltip"
[matTooltip]="
'Der h-Index beträgt ' +
h_index() +
': ' +
h_index() +
' Publikationen wurden jeweils mindestens ' +
h_index() +
'-mal zitiert.'
"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon class="stat-icon">{{ TRENDING_UP_ICON }}</mat-icon>
h-Index {{ h_index() }}
</span>
}
</span> </span>
</div> }
<p>{{ personBio() }}</p> @if (displayCareerStage() || orcid()) {
<div class="meta-line">
<app-career-stage-chip
[careerStage]="displayCareerStage()"
[activeYears]="person()?.career_metrics?.active_years" />
@if (orcid(); as orcidId) {
<a
class="orcid-chip"
[href]="orcidUrl()"
target="_blank"
rel="noopener"
matTooltip="ORCID-Profil öffnen"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon>{{ VERIFIED_ICON }}</mat-icon>
{{ orcidId }}
</a>
}
</div>
}
</div>
</div>
<aside class="sidebar">
<div class="bio-card">
@if (isBioLoading()) {
<app-loading
text="Biografie wird geladen..."
[icon]="DESCRIPTION_ICON"
[size]="150"
[diameter]="150"></app-loading>
} @else if (personBio() != null) {
<div class="bio-header">
<h3>Biografie</h3>
<span
class="ai-badge"
matTooltip="Diese Biografie wurde automatisch mit KI erstellt und kann Fehler enthalten."
matTooltipPosition="above"
[matTooltipShowDelay]="250">
<mat-icon>{{ AI_GENERATED_ICON }}</mat-icon>
KI-generiert
</span>
</div>
<p>{{ personBio() }}</p>
}
</div>
</aside>
<app-person-interesting
[topics]="primaryTopicCounts()"
[loading]="isTopicsLoading()"
[personName]="personName()"
[personPublicationsLink]="personPublicationsLink()"
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
</section>
@if (this.links()) {
<app-link-tab-nav-bar
#navBar
[links]="links()"
[tabPanel]="tabPanel"></app-link-tab-nav-bar>
}
} @else {
<app-loading
text="Person wird geladen..."
[icon]="PERSON_ICON"
[size]="150"
[diameter]="150"></app-loading>
}
<mat-tab-nav-panel #tabPanel class="person-panel">
@let activeLink = this.activeLink();
@if (activeLink) {
<div class="description-container">
@if (activeLink.label) {
<h5>{{ activeLink.label }}</h5>
}
@if (activeLink.description) {
<span class="description">{{ activeLink.description }}</span>
} }
</div> </div>
</aside> }
<app-person-interesting <div class="content">
[topics]="primaryTopicCounts()" <router-outlet></router-outlet>
[loading]="isTopicsLoading()"
[personName]="personName()"
[personPublicationsLink]="personPublicationsLink()"
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
</section>
@if (this.links()) {
<app-link-tab-nav-bar
#navBar
[links]="links()"
[tabPanel]="tabPanel"></app-link-tab-nav-bar>
}
} @else {
<app-loading
text="Person wird geladen..."
[icon]="PERSON_ICON"
[size]="150"
[diameter]="150"></app-loading>
}
<mat-tab-nav-panel #tabPanel class="person-panel">
@let activeLink = this.activeLink();
@if (activeLink) {
<div class="description-container">
@if (activeLink.label) {
<h5>{{ activeLink.label }}</h5>
}
@if (activeLink.description) {
<span class="description">{{ activeLink.description }}</span>
}
</div> </div>
} </mat-tab-nav-panel>
<div class="content">
<router-outlet></router-outlet>
</div>
</mat-tab-nav-panel>
</app-page-container> </app-page-container>
@@ -146,6 +146,55 @@
font-size: 13px; font-size: 13px;
} }
.verified-org-chip {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 24px;
max-width: 100%;
padding: 2px 10px;
border: 1px solid var(--sg-border);
border-radius: 999px;
background: var(--sg-surface-muted);
color: var(--sg-text);
font-size: 13px;
font-weight: 600;
line-height: 1.2;
text-decoration: none;
transition:
border-color 0.15s,
background 0.15s;
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
mat-icon {
flex: 0 0 auto;
width: 16px;
height: 16px;
font-size: 16px;
color: var(--sg-success);
}
&[type='button'] {
cursor: pointer;
}
&[type='button']:hover,
&[type='button']:focus-visible {
border-color: var(--sg-success);
background: var(--sg-primary-soft);
outline: none;
}
&.static {
cursor: default;
}
}
.stats-line { .stats-line {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -39,12 +39,17 @@ import { CareerStageChipComponent } from '../../shared/ui/career-stage-chip/care
import { AppInstitutionChipComponent } from '../../shared/ui/app-institution-chip/app-institution-chip.component'; import { AppInstitutionChipComponent } from '../../shared/ui/app-institution-chip/app-institution-chip.component';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { PersonInstitutionTooltipListComponent } from '../../shared/ui/person-institution-tooltip-list/person-institution-tooltip-list.component'; import { PersonInstitutionTooltipListComponent } from '../../shared/ui/person-institution-tooltip-list/person-institution-tooltip-list.component';
import { DehydratedInstitution, WorksService } from '../../api'; import {
DehydratedInstitution,
VerifiedOrganization,
WorksService,
} from '../../api';
import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PersonBioResolved } from '../../resolvers/person-bio.resolver'; import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
import { PersonDataResolved } from '../../resolvers/person.resolver'; import { PersonDataResolved } from '../../resolvers/person.resolver';
import { BookmarkService } from '../../shared/services/bookmark.service'; import { BookmarkService } from '../../shared/services/bookmark.service';
import { AuthorAffiliationService } from '../../shared/services/author-affiliation.service'; import { AuthorAffiliationService } from '../../shared/services/author-affiliation.service';
import { CredentialService } from '../../shared/services/credential.service';
import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver'; import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import { import {
@@ -73,6 +78,14 @@ import {
} from '../../shared/ui/icons'; } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
/** Accepts raw and full-URL OpenAlex IDs, e.g. `I123` or `.../I123`. */
const normalizeInstitutionId = (value: string | null | undefined): string =>
(value ?? '')
.trim()
.replace(/^https:\/\/openalex\.org\//i, '')
.replace(/\/+$/, '')
.toUpperCase();
@Component({ @Component({
selector: 'app-person', selector: 'app-person',
imports: [ imports: [
@@ -116,6 +129,7 @@ export class PersonComponent {
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
readonly bookmarkService = inject(BookmarkService); readonly bookmarkService = inject(BookmarkService);
private readonly authorAffiliationService = inject(AuthorAffiliationService); private readonly authorAffiliationService = inject(AuthorAffiliationService);
private readonly credentialService = inject(CredentialService);
canFetchGdprRelevantData = input.required<boolean>(); canFetchGdprRelevantData = input.required<boolean>();
@@ -206,6 +220,33 @@ export class PersonComponent {
.subscribe(); .subscribe();
} }
canOpenOrganizationHierarchy(organization: VerifiedOrganization): boolean {
return (
this.canOpenVerifiedOrganizationHierarchy() &&
!!organization.org_uri &&
(organization.org_hierarchy_path?.length ?? 0) > 0
);
}
openOrganizationHierarchy(organization: VerifiedOrganization): void {
if (!this.canOpenOrganizationHierarchy(organization)) return;
void this.router.navigate(['/hierarchy'], {
queryParams: {
orgFocus: organization.org_uri,
orgFocusPath: JSON.stringify(organization.org_hierarchy_path ?? []),
hierarchyExpanded: true,
organizationExpanded: false,
orgUrl: null,
orgName: null,
orgExpanded: null,
orgSelectionCategory: null,
orgSelectionIndex: null,
classifiedCategory: null,
classifiedPage: null,
},
});
}
readonly personBio = toSignal( readonly personBio = toSignal(
combineLatest([this.activatedRoute.data, toObservable(this.person)]).pipe( combineLatest([this.activatedRoute.data, toObservable(this.person)]).pipe(
switchMap(([data, person]) => { switchMap(([data, person]) => {
@@ -249,6 +290,35 @@ export class PersonComponent {
readonly secondaryInstitutions = computed<DehydratedInstitution[]>(() => readonly secondaryInstitutions = computed<DehydratedInstitution[]>(() =>
this.authorAffiliationService.resolveSecondaryInstitutions(this.person()), this.authorAffiliationService.resolveSecondaryInstitutions(this.person()),
); );
readonly verifiedOrganizationData = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
const resolved = data['personData'] as PersonDataResolved | undefined;
return resolved?.verifiedOrganizations$ ?? of(null);
}),
),
{ initialValue: null },
);
readonly verifiedOrganizations = computed(
() => this.verifiedOrganizationData()?.organizations ?? [],
);
/**
* Verified organizations come from one institution's OrgMiner data. Only
* users of that institution have a hierarchy where the nodes can be found.
*/
readonly canOpenVerifiedOrganizationHierarchy = computed(() => {
const userInstitutionId = normalizeInstitutionId(
this.credentialService.effectiveInstitutionId(),
);
const dataInstitutionId = normalizeInstitutionId(
this.verifiedOrganizationData()?.institution_id,
);
return (
!!userInstitutionId &&
!!dataInstitutionId &&
userInstitutionId === dataInstitutionId
);
});
readonly worksCount = computed(() => this.person()?.works_count ?? null); readonly worksCount = computed(() => this.person()?.works_count ?? null);
readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null); readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null);
readonly h_index = computed( readonly h_index = computed(
@@ -172,7 +172,4 @@ export class BundDetailsComponent implements OnInit {
return 'var(--sg-text-muted)'; return 'var(--sg-text-muted)';
} }
} }
goBack(): void {
window.history.back();
}
} }
@@ -279,8 +279,4 @@ export class DfgDetailsComponent implements OnInit {
queryParams: { search: institutionName }, queryParams: { search: institutionName },
}); });
} }
goBack(): void {
window.history.back();
}
} }
@@ -4,6 +4,7 @@
subtitle="Durchsuche geförderte Projekte aus DFG-, EU- und Bundesdatenquellen."> subtitle="Durchsuche geförderte Projekte aus DFG-, EU- und Bundesdatenquellen.">
<app-card-search <app-card-search
[page]="page()" [page]="page()"
[loading]="loading()"
[cardTmp]="cardTmp" [cardTmp]="cardTmp"
[additionalFiltersTmp]="additionalFiltersTmp" [additionalFiltersTmp]="additionalFiltersTmp"
[cardMinWidth]="380" [cardMinWidth]="380"
@@ -1,4 +1,4 @@
import { Component, computed, input, signal } from '@angular/core'; import { Component, computed, inject, input, signal } from '@angular/core';
import { FundingProjectPage, ProjectType } from '../../api'; import { FundingProjectPage, ProjectType } from '../../api';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
@@ -16,6 +16,7 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component'; import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
import { SEARCH_ICON } from '../../shared/ui/icons'; import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({ @Component({
selector: 'app-projects', selector: 'app-projects',
@@ -36,6 +37,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class ProjectsComponent { export class ProjectsComponent {
fundingProjectPage = input.required<FundingProjectPage>(); fundingProjectPage = input.required<FundingProjectPage>();
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/projects'),
);
page = computed<Page>(() => ({ page = computed<Page>(() => ({
page: this.fundingProjectPage().page || 0, page: this.fundingProjectPage().page || 0,
size: this.fundingProjectPage().size || 10, size: this.fundingProjectPage().size || 10,
@@ -1,14 +1,5 @@
<app-page-container> <app-page-container>
<div class="detail-page"> <div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
[attr.aria-label]="returnAriaLabel">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
{{ returnLabel }}
</button>
@if (loading) { @if (loading) {
<app-loading <app-loading
text="Publikation wird geladen..." text="Publikation wird geladen..."
@@ -8,27 +8,6 @@
min-width: 0; min-width: 0;
} }
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero { .hero {
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr) 420px; grid-template-columns: minmax(0, 1fr) 420px;
@@ -24,8 +24,8 @@ import { LanguageCodePipe } from '../../shared/pipes/language-code.pipe';
import { WorkPrimaryCategoryPipe } from '../../shared/pipes/work-primary-category.pipe'; import { WorkPrimaryCategoryPipe } from '../../shared/pipes/work-primary-category.pipe';
import { ResearchProfileComponent } from './research-profile/research-profile.component'; import { ResearchProfileComponent } from './research-profile/research-profile.component';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { BackNavigationService } from '../../shared/services/back-navigation.service';
import { import {
ARROW_BACK_ICON,
CHEVRON_LEFT_ICON, CHEVRON_LEFT_ICON,
CHEVRON_RIGHT_ICON, CHEVRON_RIGHT_ICON,
CITATION_ICON, CITATION_ICON,
@@ -82,7 +82,6 @@ interface InstitutionDetail {
styleUrl: './publication-detail.component.scss', styleUrl: './publication-detail.component.scss',
}) })
export class PublicationDetailComponent implements OnInit { export class PublicationDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly PUBLICATION_ICON = PUBLICATION_ICON; readonly PUBLICATION_ICON = PUBLICATION_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON; readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON; readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
@@ -109,6 +108,7 @@ export class PublicationDetailComponent implements OnInit {
private readonly httpClient = inject(HttpClient); private readonly httpClient = inject(HttpClient);
private readonly location = inject(Location); private readonly location = inject(Location);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly backNavigation = inject(BackNavigationService);
private readonly worksService = inject(WorksService); private readonly worksService = inject(WorksService);
workClassification = input.required<WorkClassification | null>(); workClassification = input.required<WorkClassification | null>();
@@ -130,20 +130,22 @@ export class PublicationDetailComponent implements OnInit {
readonly institutionsPageSize = 5; readonly institutionsPageSize = 5;
returnUrl: string | null = null; returnUrl: string | null = null;
returnLabel = 'Alle Publikationen';
returnAriaLabel = 'Zurück zu den Publikationen';
ngOnInit(): void { ngOnInit(): void {
this.loading = true; this.loading = true;
const navigationState = this.location.getState() as { const navigationState = this.location.getState() as {
returnUrl?: string; returnUrl?: string;
returnLabel?: string;
} | null; } | null;
if (navigationState?.returnUrl) { if (navigationState?.returnUrl) {
this.returnUrl = navigationState.returnUrl; this.returnUrl = navigationState.returnUrl;
this.returnLabel = navigationState.returnLabel ?? 'Zurück';
this.returnAriaLabel = `Zurück zu ${this.returnLabel}`; // The topbar back button should return to the page the user came from,
// not to an unrelated history entry.
const unregister = this.backNavigation.registerLocalBack(() =>
this.navigateBack(),
);
this.destroyRef.onDestroy(unregister);
} }
this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
@@ -4,6 +4,7 @@
subtitle="Durchsuche wissenschaftliche Publikationen nach Titel, Autor:innen, Themen oder Institutionen."> subtitle="Durchsuche wissenschaftliche Publikationen nach Titel, Autor:innen, Themen oder Institutionen.">
<app-card-search <app-card-search
[page]="page()" [page]="page()"
[loading]="loading()"
[cardMinWidth]="500" [cardMinWidth]="500"
[cardTmp]="cardTmp" [cardTmp]="cardTmp"
[additionalFiltersTmp]="additionalFiltersTmp" [additionalFiltersTmp]="additionalFiltersTmp"
@@ -19,6 +19,7 @@ import { PublicationFilterComponent } from '../../shared/ui/publication-filters/
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver'; import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({ @Component({
selector: 'app-publications', selector: 'app-publications',
@@ -34,6 +35,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class PublicationsComponent { export class PublicationsComponent {
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/publications'),
);
workPage = input.required<WorkPageV2>(); workPage = input.required<WorkPageV2>();
selectedAuthorsPage = input.required<AuthorPage>(); selectedAuthorsPage = input.required<AuthorPage>();
@@ -4,6 +4,7 @@
subtitle="Entdecke Forschungsfelder nach Namen, Publikationen und Zitierungen."> subtitle="Entdecke Forschungsfelder nach Namen, Publikationen und Zitierungen.">
<app-card-search <app-card-search
[page]="page()" [page]="page()"
[loading]="loading()"
[cardMinWidth]="550" [cardMinWidth]="550"
[cardTmp]="cardTmp" [cardTmp]="cardTmp"
[observers]="observers" [observers]="observers"
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core'; import { Component, computed, inject, input } from '@angular/core';
import { import {
CardSearchComponent, CardSearchComponent,
Page, Page,
@@ -10,20 +10,22 @@ import { topicQueryParamKeys } from '../../resolvers/topic-page.resolver';
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component'; import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
import { SEARCH_ICON } from '../../shared/ui/icons'; import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component'; import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({ @Component({
selector: 'app-topics', selector: 'app-topics',
imports: [ imports: [CardSearchComponent, AppTopicCardComponent, PageContainerComponent],
CardSearchComponent,
AppTopicCardComponent,
PageContainerComponent,
],
templateUrl: './topics.component.html', templateUrl: './topics.component.html',
styleUrl: './topics.component.scss', styleUrl: './topics.component.scss',
}) })
export class TopicsComponent { export class TopicsComponent {
topicPage = input.required<TopicPageV2>(); topicPage = input.required<TopicPageV2>();
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/topics'),
);
observers: FilterObserver[] = [ observers: FilterObserver[] = [
{ {
id: 'query', id: 'query',
@@ -1,6 +1,7 @@
import { ResolveFn } from '@angular/router'; import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core'; import { inject } from '@angular/core';
import { import {
CareerBucket,
FounderCandidatePage, FounderCandidatePage,
FounderSortBy, FounderSortBy,
MultiplicatorsService, MultiplicatorsService,
@@ -9,12 +10,19 @@ import {
const FOUNDER_SORT_FIELDS = Object.values(FounderSortBy); const FOUNDER_SORT_FIELDS = Object.values(FounderSortBy);
const SORT_DIRECTIONS = Object.values(SortDirection); const SORT_DIRECTIONS = Object.values(SortDirection);
const DEFAULT_THRESHOLD = 90; const VALID_CAREER_BUCKETS = Object.values(CareerBucket);
/** /**
* The founder-candidate list for the dashboard. Driven entirely by query * The founder-candidate list for the dashboard. Driven entirely by query
* params (threshold, screened, page, size, sort) so the page state stays in * params so the page state stays in the URL and re-resolves when any of them
* the URL and re-resolves when any of them change. * change.
*
* URL keys are the camelCase names used by the shared query-param controls and
* are mapped to the snake_case arguments of `searchFounderCandidates` here.
*
* Everyone is shown by default (`in_population` unset). The "Mindestwert" is
* opt-in: only when `threshold` is present is `min_external_percentile` sent.
* "Auffällige Profile ausblenden" sets `screened=true`.
*/ */
export const founderCandidatesResolver: ResolveFn<FounderCandidatePage> = ( export const founderCandidatesResolver: ResolveFn<FounderCandidatePage> = (
route, route,
@@ -24,11 +32,14 @@ export const founderCandidatesResolver: ResolveFn<FounderCandidatePage> = (
const page = Math.max(0, toInt(params.get('page'), 0)); const page = Math.max(0, toInt(params.get('page'), 0));
const size = clamp(toInt(params.get('size'), 25), 1, 100); const size = clamp(toInt(params.get('size'), 25), 1, 100);
const thresholdRaw = toNumber(params.get('threshold'));
const threshold = clamp(thresholdRaw ?? DEFAULT_THRESHOLD, 0, 100);
const screenedRaw = params.get('screened'); const thresholdRaw = toNumber(params.get('threshold'));
const screened = screenedRaw === null ? undefined : screenedRaw === 'true'; const minPercentile =
thresholdRaw === null ? undefined : clamp(thresholdRaw, 0, 100);
// `screened=true` keeps only profiles that pass the data-quality screen.
// `screened=false` would mean "only the rejects", so it is never sent.
const screened = params.get('screened') === 'true' ? true : undefined;
const sortBy = const sortBy =
asMember(params.get('sortBy'), FOUNDER_SORT_FIELDS) ?? asMember(params.get('sortBy'), FOUNDER_SORT_FIELDS) ??
@@ -36,19 +47,26 @@ export const founderCandidatesResolver: ResolveFn<FounderCandidatePage> = (
const sortOrder = const sortOrder =
asMember(params.get('sortOrder'), SORT_DIRECTIONS) ?? SortDirection.Desc; asMember(params.get('sortOrder'), SORT_DIRECTIONS) ?? SortDirection.Desc;
const careerBuckets = splitCommaSeparated(params.getAll('careerBucket')).filter(
(value): value is CareerBucket =>
(VALID_CAREER_BUCKETS as readonly string[]).includes(value),
);
const researchAreas = splitCommaSeparated(params.getAll('researchArea'));
const name = params.get('name')?.trim() || undefined;
return service.searchFounderCandidates( return service.searchFounderCandidates(
page, page,
size, size,
true, // in_population: only researchers the model can score undefined, // in_population: show everyone, scored and unscored
threshold, minPercentile,
undefined, // max_external_percentile undefined, // max_external_percentile
undefined, // career_bucket careerBuckets.length ? careerBuckets : undefined,
screened, screened,
undefined, // min_publications undefined, // min_publications
undefined, // has_patents undefined, // has_patents
undefined, // research_area researchAreas.length ? researchAreas : undefined,
undefined, // tags undefined, // tags
undefined, // name name,
undefined, // screen_min_publications undefined, // screen_min_publications
undefined, // screen_max_career_age undefined, // screen_max_career_age
sortBy, sortBy,
@@ -65,6 +83,13 @@ function asMember<T extends string>(
: null; : null;
} }
function splitCommaSeparated(values: string[]): string[] {
return values
.flatMap((value) => value.split(','))
.map((value) => value.trim())
.filter(Boolean);
}
function clamp(value: number, min: number, max: number): number { function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value)); return Math.max(min, Math.min(max, value));
} }
@@ -6,12 +6,15 @@ import { FounderStatistics, MultiplicatorsService } from '../api';
* Founder-potential statistics for the dashboard (KPIs, funnel, career-stage * Founder-potential statistics for the dashboard (KPIs, funnel, career-stage
* and research-area breakdowns). Re-resolved when the `threshold` query param * and research-area breakdowns). Re-resolved when the `threshold` query param
* changes, so the shortlist counts always match the slider in the URL. * changes, so the shortlist counts always match the slider in the URL.
*
* The threshold is opt-in. When the param is absent there is no shortlist cut,
* so 0 is used: every scored profile counts, matching the unfiltered list.
*/ */
export const founderStatisticsResolver: ResolveFn<FounderStatistics> = ( export const founderStatisticsResolver: ResolveFn<FounderStatistics> = (
route, route,
) => { ) => {
const service = inject(MultiplicatorsService); const service = inject(MultiplicatorsService);
const threshold = toNumber(route.queryParamMap.get('threshold')) ?? 90; const threshold = toNumber(route.queryParamMap.get('threshold')) ?? 0;
// Remaining cutoffs mirror the backend defaults; only the threshold is // Remaining cutoffs mirror the backend defaults; only the threshold is
// exposed to the user for now. // exposed to the user for now.
return service.getFounderStatistics(threshold, 7, 0.7, 40, 40); return service.getFounderStatistics(threshold, 7, 0.7, 40, 40);
+14 -1
View File
@@ -4,6 +4,7 @@ import {
CompanyConnectionsService, CompanyConnectionsService,
CustomAuthorsListResponse, CustomAuthorsListResponse,
PersonsService, PersonsService,
VerifiedOrganizationsResponse,
} from '../api'; } from '../api';
import { import {
Observable, Observable,
@@ -20,6 +21,7 @@ import { toObservable } from '@angular/core/rxjs-interop';
export interface PersonDataResolved { export interface PersonDataResolved {
personData$: Observable<CustomAuthorsListResponse | null>; personData$: Observable<CustomAuthorsListResponse | null>;
companyConnectionsAvailable$: Observable<boolean>; companyConnectionsAvailable$: Observable<boolean>;
verifiedOrganizations$: Observable<VerifiedOrganizationsResponse | null>;
} }
export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => { export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
@@ -38,6 +40,7 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
return { return {
personData$: of(null), personData$: of(null),
companyConnectionsAvailable$: of(false), companyConnectionsAvailable$: of(false),
verifiedOrganizations$: of(null),
}; };
} }
@@ -51,6 +54,16 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
shareReplay(1), shareReplay(1),
); );
const verifiedOrganizations$ = personsService
.getVerifiedOrganizations(authorId)
.pipe(
catchError((err) => {
console.error('Failed to load verified organizations:', err);
return of(null);
}),
shareReplay(1),
);
const companyConnectionsAvailable$ = toObservable( const companyConnectionsAvailable$ = toObservable(
credentialService.effectiveInstitutionId, credentialService.effectiveInstitutionId,
).pipe( ).pipe(
@@ -76,5 +89,5 @@ export const personResolver: ResolveFn<PersonDataResolved> = (route, state) => {
shareReplay({ bufferSize: 1, refCount: true }), shareReplay({ bufferSize: 1, refCount: true }),
); );
return { personData$, companyConnectionsAvailable$ }; return { personData$, companyConnectionsAvailable$, verifiedOrganizations$ };
}; };
@@ -0,0 +1,114 @@
import { Location } from '@angular/common';
import { Injectable, computed, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
type BackHandler = () => void;
const ROOT_PATHS = new Set([
'/dashboard',
'/compare',
'/multipliers',
'/founders',
'/bookmarks',
'/persons',
'/keywords',
'/hierarchy',
'/news',
'/account',
'/accounts',
'/organizations',
'/jobs',
'/publications',
'/topics',
'/projects',
'/patents',
'/institutions',
'/login',
'/forgot-password',
'/reset-password',
'/icons',
'/error',
]);
const FALLBACKS: ReadonlyArray<{ prefix: string; target: string }> = [
{ prefix: '/person/', target: '/persons' },
{ prefix: '/publication/', target: '/publications' },
{ prefix: '/patent/', target: '/patents' },
{ prefix: '/news/', target: '/news' },
{ prefix: '/institution/', target: '/institutions' },
{ prefix: '/topic/', target: '/topics' },
{ prefix: '/projects/', target: '/projects' },
{ prefix: '/founders/', target: '/multipliers' },
{ prefix: '/keywords/', target: '/keywords' },
{ prefix: '/error', target: '/dashboard' },
];
@Injectable({ providedIn: 'root' })
export class BackNavigationService {
private readonly router = inject(Router);
private readonly location = inject(Location);
// In-page detail views (e.g. the inline patent detail) own the back action
// while they are open. The topbar button executes the newest handler.
private readonly localHandlers = signal<readonly BackHandler[]>([]);
readonly hasLocalHandler = computed(() => this.localHandlers().length > 0);
/**
* Registers a back action for an in-page detail view. Returns an unregister
* function that the component calls when the view closes or is destroyed.
*/
registerLocalBack(handler: BackHandler): () => void {
this.localHandlers.update((handlers) => [...handlers, handler]);
return () => {
this.localHandlers.update((handlers) =>
handlers.filter((candidate) => candidate !== handler),
);
};
}
/** True when this tab has at least one earlier in-app navigation. */
canGoBack(): boolean {
const state = history.state as { navigationId?: number } | null;
return (state?.navigationId ?? 0) > 1;
}
/**
* Goes back in history when that is safe, otherwise navigates to the
* section that owns the current detail page.
*/
back(fallback?: string): void {
const handlers = this.localHandlers();
const localHandler = handlers[handlers.length - 1];
if (localHandler) {
localHandler();
return;
}
if (this.canGoBack()) {
this.location.back();
return;
}
void this.router.navigateByUrl(
fallback ?? this.fallbackFor(this.router.url),
);
}
/** Whether the current URL is a top-level section. */
isRoot(url: string): boolean {
return ROOT_PATHS.has(this.pathOf(url));
}
fallbackFor(url: string): string {
const path = this.pathOf(url);
const match = FALLBACKS.find(({ prefix }) => path.startsWith(prefix));
return match?.target ?? '/dashboard';
}
private pathOf(url: string): string {
return url.split('?')[0].split('#')[0] || '/';
}
}
@@ -0,0 +1,55 @@
import { inject, Injectable } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
import { navigationSectionFor, pathOf } from './navigation-sections';
/**
* Moves keyboard and screen-reader focus to the new page heading after a
* navigation between sections. In-section updates (tabs, filters, pagination)
* keep the focus where the user left it.
*/
@Injectable({ providedIn: 'root' })
export class NavigationFocusService {
private readonly router = inject(Router);
private lastPath: string | null = null;
constructor() {
this.router.events
.pipe(
filter(
(event): event is NavigationEnd => event instanceof NavigationEnd,
),
takeUntilDestroyed(),
)
.subscribe((event) => {
const path = pathOf(event.urlAfterRedirects);
const previousPath = this.lastPath;
this.lastPath = path;
// Skip the initial load and in-section updates.
if (previousPath === null) return;
const fromSection = navigationSectionFor(previousPath);
const toSection = navigationSectionFor(path);
if (fromSection?.id === toSection?.id) return;
this.focusPageHeading();
});
}
private focusPageHeading(): void {
// Wait for the activated component's view to be in the DOM.
requestAnimationFrame(() => {
const main = document.querySelector<HTMLElement>('main');
const heading = main?.querySelector<HTMLElement>('h1') ?? null;
const target = heading ?? main;
if (!target) return;
if (!target.hasAttribute('tabindex')) {
target.setAttribute('tabindex', '-1');
}
// The scroll service owns the scroll position; focusing must not move it.
target.focus({ preventScroll: true });
});
}
}
@@ -0,0 +1,331 @@
import {
ACCOUNT_CIRCLE_ICON,
BOOKMARKS_ICON,
DASHBOARD_ICON,
FOUNDER_ICON,
HIERARCHY_ICON,
INSTITUTION_ICON,
JOBS_ICON,
KEYWORDS_ICON,
NEWS_ICON,
ORGANIZATIONS_ICON,
PATENT_ICON,
PERSONS_ICON,
PERSON_ICON,
PROJECT_ICON,
PUBLICATION_ICON,
TOPIC_ICON,
} from '../ui/icons';
/**
* Shape of the page skeleton for a navigation target. The variants mirror the
* actual page layouts: card grids, data tables, master-detail pages, KPI
* dashboards, tree charts, forms and graphs.
*/
export type PageSkeletonVariant =
| 'cards'
| 'cards-plain'
| 'cards-sidebar'
| 'table'
| 'table-stats'
| 'detail'
| 'detail-table'
| 'detail-chart'
| 'dashboard'
| 'comparison'
| 'tree'
| 'form'
| 'graph';
export interface NavigationSection {
/** Stable identifier, used to detect navigations that stay inside a section. */
id: string;
/**
* URL prefix. A trailing slash means "any path below this prefix" and is
* used for detail routes that share their list's prefix (e.g. `/news/:id`).
*/
prefix: string;
label: string;
/** Announced and shown while the section's resolvers run. */
loadingText: string;
icon: string;
skeleton: PageSkeletonVariant;
}
/**
* Central map of the app's sections. Used for the navigation skeleton and to
* tell "from outside" navigations (show a skeleton) apart from in-section
* updates such as filters and pagination (keep the current content).
*/
export const NAVIGATION_SECTIONS: readonly NavigationSection[] = [
{
// Person list: card grid on the left, filter sidebar on the right.
id: 'persons',
prefix: '/persons',
label: 'Personen',
loadingText: 'Personen werden geladen …',
icon: PERSONS_ICON,
skeleton: 'cards-sidebar',
},
{
// Person detail: hero, tabs, timeline/wordcloud on the overview tab.
id: 'person',
prefix: '/person',
label: 'Person',
loadingText: 'Personendaten werden geladen …',
icon: PERSON_ICON,
skeleton: 'detail-chart',
},
{
id: 'publications',
prefix: '/publications',
label: 'Publikationen',
loadingText: 'Publikationen werden geladen …',
icon: PUBLICATION_ICON,
skeleton: 'cards',
},
{
id: 'publication',
prefix: '/publication',
label: 'Publikation',
loadingText: 'Publikationsdaten werden geladen …',
icon: PUBLICATION_ICON,
skeleton: 'detail',
},
{
id: 'project-detail',
prefix: '/projects/dfg/',
label: 'Projekt',
loadingText: 'Projektdaten werden geladen …',
icon: PROJECT_ICON,
skeleton: 'detail',
},
{
id: 'project-detail',
prefix: '/projects/bund/',
label: 'Projekt',
loadingText: 'Projektdaten werden geladen …',
icon: PROJECT_ICON,
skeleton: 'detail',
},
{
id: 'project-detail',
prefix: '/projects/eu/',
label: 'Projekt',
loadingText: 'Projektdaten werden geladen …',
icon: PROJECT_ICON,
skeleton: 'detail',
},
{
// Project list uses app-card-search, not a table.
id: 'projects',
prefix: '/projects',
label: 'Projekte',
loadingText: 'Projekte werden geladen …',
icon: PROJECT_ICON,
skeleton: 'cards',
},
{
id: 'institutions',
prefix: '/institutions',
label: 'Institutionen',
loadingText: 'Institutionen werden geladen …',
icon: INSTITUTION_ICON,
skeleton: 'cards',
},
{
// Institution detail tabs default to a publication table.
id: 'institution',
prefix: '/institution',
label: 'Institution',
loadingText: 'Institutionsdaten werden geladen …',
icon: INSTITUTION_ICON,
skeleton: 'detail-table',
},
{
// Patent list uses app-card-search; clicking a card opens a detail panel.
id: 'patents',
prefix: '/patents',
label: 'Patente',
loadingText: 'Patente werden geladen …',
icon: PATENT_ICON,
skeleton: 'cards',
},
{
id: 'patent',
prefix: '/patent',
label: 'Patent',
loadingText: 'Patentdaten werden geladen …',
icon: PATENT_ICON,
skeleton: 'detail',
},
{
id: 'news-detail',
prefix: '/news/',
label: 'Nachricht',
loadingText: 'Nachricht wird geladen …',
icon: NEWS_ICON,
skeleton: 'detail',
},
{
id: 'news',
prefix: '/news',
label: 'Nachrichten',
loadingText: 'Nachrichten werden geladen …',
icon: NEWS_ICON,
skeleton: 'cards',
},
{
// Topic list uses app-card-search, not a table.
id: 'topics',
prefix: '/topics',
label: 'Themen',
loadingText: 'Themen werden geladen …',
icon: TOPIC_ICON,
skeleton: 'cards',
},
{
// Topic detail tabs default to a publication table.
id: 'topic',
prefix: '/topic',
label: 'Thema',
loadingText: 'Themendaten werden geladen …',
icon: TOPIC_ICON,
skeleton: 'detail-table',
},
{
id: 'hierarchy',
prefix: '/hierarchy',
label: 'Hierarchie',
loadingText: 'Hierarchie wird geladen …',
icon: HIERARCHY_ICON,
skeleton: 'tree',
},
{
// KPI tiles plus several ECharts panels.
id: 'dashboard',
prefix: '/dashboard',
label: 'Dashboard',
loadingText: 'Dashboard wird geladen …',
icon: DASHBOARD_ICON,
skeleton: 'dashboard',
},
{
id: 'multipliers',
prefix: '/multipliers',
label: 'Multiplikatoren',
loadingText: 'Multiplikatoren werden geladen …',
icon: FOUNDER_ICON,
skeleton: 'table',
},
{
// KPI cards above a data table with expandable rows.
id: 'founders',
prefix: '/founders',
label: 'Gründungspotenzial',
loadingText: 'Gründungspotenzial wird geladen …',
icon: FOUNDER_ICON,
skeleton: 'table-stats',
},
{
id: 'collaboration-network',
prefix: '/collaboration-network',
label: 'Forschungsnetzwerk',
loadingText: 'Forschungsnetzwerk wird geladen …',
icon: PERSON_ICON,
skeleton: 'graph',
},
{
// Bookmarks are just a card grid, without search/sort/pagination.
id: 'bookmarks',
prefix: '/bookmarks',
label: 'Bookmarks',
loadingText: 'Bookmarks werden geladen …',
icon: BOOKMARKS_ICON,
skeleton: 'cards-plain',
},
{
// Two statistic tables, charts and a research-profile panel.
id: 'compare',
prefix: '/compare',
label: 'Autorenvergleich',
loadingText: 'Autorenvergleich wird geladen …',
icon: PERSON_ICON,
skeleton: 'comparison',
},
{
// Keyword extraction form with a four-column chip matrix.
id: 'keywords-results',
prefix: '/keywords/search-results',
label: 'Keyword-Suche',
loadingText: 'Ergebnisse werden geladen …',
icon: KEYWORDS_ICON,
skeleton: 'table',
},
{
id: 'keywords',
prefix: '/keywords',
label: 'Keywords',
loadingText: 'Keywords werden geladen …',
icon: KEYWORDS_ICON,
skeleton: 'form',
},
{
id: 'accounts',
prefix: '/accounts',
label: 'Accounts',
loadingText: 'Accounts werden geladen …',
icon: ACCOUNT_CIRCLE_ICON,
skeleton: 'table',
},
{
id: 'account',
prefix: '/account',
label: 'Mein Konto',
loadingText: 'Kontodaten werden geladen …',
icon: ACCOUNT_CIRCLE_ICON,
skeleton: 'detail',
},
{
id: 'organizations',
prefix: '/organizations',
label: 'Organisationen',
loadingText: 'Organisationen werden geladen …',
icon: ORGANIZATIONS_ICON,
skeleton: 'table',
},
{
// Health status cards above a data table.
id: 'jobs',
prefix: '/jobs',
label: 'Jobs',
loadingText: 'Jobs werden geladen …',
icon: JOBS_ICON,
skeleton: 'table-stats',
},
];
// Longest prefix first so `/persons` wins over `/person`.
const SECTIONS_BY_LENGTH = [...NAVIGATION_SECTIONS].sort(
(a, b) => b.prefix.length - a.prefix.length,
);
/** Resolve the section for a router URL (query string and hash are ignored). */
export function navigationSectionFor(
url: string | null | undefined,
): NavigationSection | null {
if (!url) return null;
const path = pathOf(url);
return SECTIONS_BY_LENGTH.find((section) => matchesPrefix(path, section.prefix)) ?? null;
}
function matchesPrefix(path: string, prefix: string): boolean {
return prefix.endsWith('/')
? path.startsWith(prefix)
: path === prefix || path.startsWith(`${prefix}/`);
}
/** Path part of a router URL. */
export function pathOf(url: string): string {
return url.split('?')[0].split('#')[0] || '/';
}
@@ -0,0 +1,111 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import {
ActivatedRouteSnapshot,
NavigationCancel,
NavigationEnd,
NavigationError,
ResolveStart,
Router,
RouterStateSnapshot,
} from '@angular/router';
import {
NavigationSection,
navigationSectionFor,
pathOf,
} from './navigation-sections';
export interface NavigationTarget {
/** URL the router is navigating to (including query string). */
url: string;
/** Section of the target URL, if it is one of the known sections. */
section: NavigationSection | null;
/** URL the user is coming from, captured when resolving starts. */
fromUrl: string | null;
/** Section of the origin URL. */
fromSection: NavigationSection | null;
/** True when the navigation switches to a different section. */
external: boolean;
}
/**
* Central navigation state for the whole app.
*
* Resolvers run between `ResolveStart` and `NavigationEnd`; while they do, the
* layout shows a section skeleton for navigations that come from outside a
* section. In-section updates (filters, pagination, tabs) keep the current
* content on screen and only clear when the navigation finishes.
*/
@Injectable({ providedIn: 'root' })
export class NavigationStateService {
private readonly router = inject(Router);
private readonly currentTarget = signal<NavigationTarget | null>(null);
readonly target = this.currentTarget.asReadonly();
readonly isResolving = computed(() => this.currentTarget() !== null);
/** Section whose skeleton should be shown, or null to keep the content. */
readonly skeleton = computed<NavigationSection | null>(() => {
const target = this.currentTarget();
return target?.external ? target.section : null;
});
constructor() {
this.router.events.subscribe((event) => {
if (event instanceof ResolveStart) {
// Angular emits ResolveStart for every activation, even when no
// resolver is configured. Without resolvers there is nothing to wait
// for, so showing a skeleton would only cause a flash.
if (!hasResolvers(event.state)) return;
const fromUrl = this.router.url;
const section = navigationSectionFor(event.url);
const fromSection = navigationSectionFor(fromUrl);
this.currentTarget.set({
url: event.url,
section,
fromUrl,
fromSection,
external: section?.id !== fromSection?.id,
});
return;
}
if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError
) {
this.currentTarget.set(null);
}
});
}
/** True while resolving a URL that starts with `path` from outside `path`. */
isResolvingFromOutside(path: string): boolean {
const target = this.currentTarget();
if (!target || !matchesPath(target.url, path)) return false;
return !matchesPath(target.fromUrl, path);
}
/** True while resolving a URL that stays inside `path`. */
isResolvingInside(path: string): boolean {
const target = this.currentTarget();
if (!target || !matchesPath(target.url, path)) return false;
return matchesPath(target.fromUrl, path);
}
}
function matchesPath(url: string | null, prefix: string): boolean {
if (!url) return false;
const path = pathOf(url);
return path === prefix || path.startsWith(`${prefix}/`);
}
function hasResolvers(state: RouterStateSnapshot): boolean {
let route: ActivatedRouteSnapshot | null = state.root;
while (route) {
if (Object.keys(route.routeConfig?.resolve ?? {}).length > 0) return true;
route = route.firstChild;
}
return false;
}
@@ -0,0 +1,71 @@
import { Injectable, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
const APP_NAME = 'AIIS';
const TITLES: ReadonlyArray<{ prefix: string; title: string }> = [
{ prefix: '/person/', title: 'Person' },
{ prefix: '/persons', title: 'Personen' },
{ prefix: '/publication/', title: 'Publikation' },
{ prefix: '/publications', title: 'Publikationen' },
{ prefix: '/patent/', title: 'Patent' },
{ prefix: '/patents', title: 'Patente' },
{ prefix: '/institution/', title: 'Institution' },
{ prefix: '/institutions', title: 'Institutionen' },
{ prefix: '/topic/', title: 'Thema' },
{ prefix: '/topics', title: 'Themen' },
{ prefix: '/news/', title: 'Nachricht' },
{ prefix: '/news', title: 'Nachrichten' },
{ prefix: '/projects/', title: 'Projekt' },
{ prefix: '/projects', title: 'Projekte' },
{ prefix: '/founders/', title: 'Multiplikator' },
{ prefix: '/founders', title: 'Gründungspotenzial' },
{ prefix: '/multipliers', title: 'Multiplikatoren' },
{ prefix: '/compare', title: 'Autorenvergleich' },
{ prefix: '/bookmarks', title: 'Bookmarks' },
{ prefix: '/keywords/', title: 'Keywords' },
{ prefix: '/keywords', title: 'Keywords' },
{ prefix: '/hierarchy', title: 'Hierarchie' },
{ prefix: '/account', title: 'Mein Konto' },
{ prefix: '/accounts', title: 'Accounts' },
{ prefix: '/organizations', title: 'Organisationen' },
{ prefix: '/jobs', title: 'Jobs' },
{ prefix: '/dashboard', title: 'Dashboard' },
{ prefix: '/login', title: 'Anmelden' },
{ prefix: '/forgot-password', title: 'Passwort vergessen' },
{ prefix: '/reset-password', title: 'Passwort zurücksetzen' },
{ prefix: '/error', title: 'Fehler' },
{ prefix: '/icons', title: 'Icons' },
];
@Injectable({ providedIn: 'root' })
export class PageTitleService {
private readonly router = inject(Router);
constructor() {
this.router.events
.pipe(
filter(
(event): event is NavigationEnd => event instanceof NavigationEnd,
),
takeUntilDestroyed(),
)
.subscribe((event) => this.update(event.urlAfterRedirects));
this.update(this.router.url);
}
private update(url: string): void {
document.title = `${this.titleFor(url)} · ${APP_NAME}`;
}
private titleFor(url: string): string {
const path = url.split('?')[0].split('#')[0] || '/';
if (path === '/' || path === '') return 'Start';
const match = TITLES.find(({ prefix }) => path.startsWith(prefix));
return match?.title ?? 'Übersicht';
}
}
@@ -1,49 +0,0 @@
import { Injectable, signal, inject, computed } from '@angular/core';
import { Router, RouterEvent, ActivatedRoute } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { ResolveEnd, ResolveStart } from '@angular/router';
import {
NavigationEnd,
NavigationError,
NavigationCancel,
} from '@angular/router';
@Injectable({ providedIn: 'root' })
export class ResolverStateService {
private readonly router = inject(Router);
readonly resolvingUrl = signal<string | null>(null);
readonly previousUrl = signal<string | null>(null);
readonly isResolving = computed(() => this.resolvingUrl() !== null);
constructor() {
this.router.events.subscribe((event) => {
if (event instanceof ResolveStart) {
this.previousUrl.set(this.router.url); // capture current before it changes
this.resolvingUrl.set(event.url);
}
if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError
) {
this.resolvingUrl.set(null);
}
});
}
isResolvingFromOutside(path: string) {
const from = this.previousUrl();
const to = this.resolvingUrl();
if (!to?.startsWith(path)) return false;
return !from?.startsWith(path); // came from outside
}
isResolvingInside(path: string) {
const from = this.previousUrl();
const to = this.resolvingUrl();
if (to?.startsWith(path) && from?.startsWith(path)) return true;
return false;
}
}
@@ -0,0 +1,181 @@
import { Injectable, inject } from '@angular/core';
import { NavigationEnd, NavigationStart, Router } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
const STORAGE_PREFIX = 'inse.scroll.';
const STATE_KEY = 'sgScrollId';
/**
* Restores the scroll position of the app's inner scroll container.
*
* Rules:
* - a path change starts at the top,
* - back/forward restores the position of that history entry,
* - a query-only change on the same page keeps the current position, so
* selection, filter and pagination updates do not make the page jump.
*
* The app scrolls inside `main.content` (not the window), so Angular's
* built-in `withInMemoryScrolling` cannot handle it.
*/
@Injectable({ providedIn: 'root' })
export class RouteScrollService {
private readonly router = inject(Router);
private scroller: HTMLElement | null = null;
private currentScrollId: string | null = null;
private scrollFrame: number | null = null;
private nextNavigationIsPopstate = false;
private currentPath = '';
constructor() {
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
this.currentPath = this.pathOf(this.router.url);
this.router.events.pipe(takeUntilDestroyed()).subscribe((event) => {
if (event instanceof NavigationStart) {
this.persistCurrent();
this.nextNavigationIsPopstate = event.navigationTrigger === 'popstate';
return;
}
if (event instanceof NavigationEnd) {
this.handleNavigationEnd(event, this.nextNavigationIsPopstate);
}
});
}
/** Connects the persistent scroll container of the app shell. */
attach(scroller: HTMLElement): void {
if (this.scroller === scroller) return;
this.scroller?.removeEventListener('scroll', this.onScroll);
this.scroller = scroller;
this.scroller.addEventListener('scroll', this.onScroll, { passive: true });
const storedId = this.readStateId();
this.currentScrollId = storedId ?? this.writeStateId(this.createScrollId());
this.restore(this.currentScrollId);
}
/** Connects the scroll container after the first render. */
attachWhenReady(getScroller: () => HTMLElement | null | undefined): void {
requestAnimationFrame(() => {
const scroller = getScroller();
if (scroller) this.attach(scroller);
});
}
private handleNavigationEnd(
event: NavigationEnd,
isBackForward: boolean,
): void {
const nextPath = this.pathOf(event.urlAfterRedirects);
if (isBackForward) {
const id = this.readStateId() ?? this.writeStateId(this.createScrollId());
this.currentScrollId = id;
this.scheduleRestore(id);
this.currentPath = nextPath;
return;
}
const isNewPage = nextPath !== this.currentPath;
const previousPosition = this.scroller?.scrollTop ?? 0;
const id = this.writeStateId(this.createScrollId());
this.currentScrollId = id;
if (isNewPage) {
this.scheduleScrollTop();
} else {
// Query-only update on the same page: keep the user's position.
this.writePosition(id, previousPosition);
}
this.currentPath = nextPath;
}
private scheduleRestore(scrollId: string): void {
this.scheduleFrame(() => this.restore(scrollId));
}
private scheduleScrollTop(): void {
this.scheduleFrame(() => this.setScrollTop(0));
}
private scheduleFrame(callback: () => void): void {
// Two frames: one for the new component tree, one for its layout.
requestAnimationFrame(() => {
requestAnimationFrame(callback);
});
}
private restore(scrollId: string | null): void {
if (!this.scroller || !scrollId) return;
const stored = this.readPosition(scrollId);
this.setScrollTop(stored);
}
private setScrollTop(value: number): void {
if (!this.scroller) return;
this.scroller.scrollTop = Math.max(0, value);
}
private persistCurrent(): void {
if (!this.scroller || !this.currentScrollId) return;
this.writePosition(this.currentScrollId, this.scroller.scrollTop);
}
private readonly onScroll = (): void => {
if (this.scrollFrame !== null) return;
this.scrollFrame = requestAnimationFrame(() => {
this.scrollFrame = null;
this.persistCurrent();
});
};
private createScrollId(): string {
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
private readStateId(): string | null {
const state = history.state as Record<string, unknown> | null;
const id = state?.[STATE_KEY];
return typeof id === 'string' && id.length > 0 ? id : null;
}
private writeStateId(id: string): string {
const state = (history.state ?? {}) as Record<string, unknown>;
history.replaceState({ ...state, [STATE_KEY]: id }, '');
return id;
}
private readPosition(scrollId: string): number {
try {
const raw = sessionStorage.getItem(STORAGE_PREFIX + scrollId);
const value = raw === null ? 0 : Number(raw);
return Number.isFinite(value) ? value : 0;
} catch {
return 0;
}
}
private writePosition(scrollId: string, position: number): void {
try {
sessionStorage.setItem(STORAGE_PREFIX + scrollId, String(position));
} catch {
// Storage can be unavailable (private mode/quota). Position restoration
// is an enhancement, never a hard requirement.
}
}
private pathOf(url: string): string {
return url.split('?')[0].split('#')[0] || '/';
}
}
@@ -38,10 +38,16 @@
<mat-icon>{{ MENU_ICON }}</mat-icon> <mat-icon>{{ MENU_ICON }}</mat-icon>
</button> </button>
} }
<button (click)="navigateBack()" class="back-link" type="button"> @if (showBack()) {
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon> <button
<span>Zurück</span> (click)="navigateBack()"
</button> class="back-link"
type="button"
aria-label="Zurück zur vorherigen Ansicht">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
<span>Zurück</span>
</button>
}
</div> </div>
<app-searchbar /> <app-searchbar />
<div class="topbar-actions"> <div class="topbar-actions">
@@ -50,62 +56,13 @@
</mat-toolbar> </mat-toolbar>
} }
<main class="content"> <main class="content" #contentScroller tabindex="-1">
<div class="main-content-body"> <div class="main-content-body">
@if (resolverState.isResolvingFromOutside('/persons')) { @if (navigationState.skeleton(); as skeleton) {
<app-loading <app-page-skeleton
text="Personenliste wird geladen..." [label]="skeleton.loadingText"
[icon]="PERSONS_ICON" [icon]="skeleton.icon"
[size]="200" [variant]="skeleton.skeleton" />
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/person')) {
<app-loading
text="Personendaten werden geladen..."
[icon]="PERSON_ICON"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/publications')) {
<app-loading
text="Publikationsdaten werden geladen..."
[icon]="PUBLICATION_ICON"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/projects')) {
<app-loading
text="Projektdaten werden geladen..."
[icon]="PROJECT_ICON"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/institutions')) {
<app-loading
text="Institutionen werden geladen..."
[icon]="INSTITUTION_ICON"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/patents')) {
<app-loading
text="Patente werden geladen..."
[icon]="PATENT_ICON"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/news')) {
<app-loading
text="Nachrichten werden geladen..."
[icon]="NEWS_ICON"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/topics')) {
<app-loading
text="Themen werden geladen..."
[icon]="TOPIC_ICON"
[size]="200"
[diameter]="200" />
} @else if (resolverState.isResolvingFromOutside('/hierarchy')) {
<app-loading
text="Hierarchie werden geladen..."
[icon]="HIERARCHY_ICON"
[size]="200"
[diameter]="200" />
} @else { } @else {
<ng-content></ng-content> <ng-content></ng-content>
} }
@@ -1,37 +1,40 @@
import { import {
afterNextRender,
ChangeDetectorRef, ChangeDetectorRef,
Component, Component,
DestroyRef,
ElementRef,
OnDestroy, OnDestroy,
OnInit, OnInit,
ViewChild, ViewChild,
computed,
inject, inject,
signal,
viewChild,
} from '@angular/core'; } from '@angular/core';
import { CommonModule, Location } from '@angular/common'; import { CommonModule } from '@angular/common';
import { MatToolbarModule } from '@angular/material/toolbar'; import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatDrawer, MatSidenavModule } from '@angular/material/sidenav'; import { MatDrawer, MatSidenavModule } from '@angular/material/sidenav';
import { Router } from '@angular/router'; import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MediaMatcher } from '@angular/cdk/layout'; import { MediaMatcher } from '@angular/cdk/layout';
import { AppMenuComponent } from '../app-menu/app-menu.component'; import { AppMenuComponent } from '../app-menu/app-menu.component';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { CredentialService } from '../../services/credential.service'; import { CredentialService } from '../../services/credential.service';
import { AppSearchbarComponent } from '../app-searchbar/app-searchbar.component'; import { AppSearchbarComponent } from '../app-searchbar/app-searchbar.component';
import { ResolverStateService } from '../../services/resolver-state.service'; import { NavigationStateService } from '../../services/navigation-state.service';
import { LoadingComponent } from '../loading/loading.component'; import { NavigationFocusService } from '../../services/navigation-focus.service';
import { BackNavigationService } from '../../services/back-navigation.service';
import { PageTitleService } from '../../services/page-title.service';
import { RouteScrollService } from '../../services/route-scroll.service';
import { PageSkeletonComponent } from '../page-skeleton/page-skeleton.component';
import { import {
ARROW_BACK_ICON, ARROW_BACK_ICON,
INSTITUTION_ICON,
MENU_ICON, MENU_ICON,
NEWS_ICON,
PATENT_ICON,
PERSONS_ICON,
PERSON_ICON,
PROJECT_ICON,
PUBLICATION_ICON,
SWITCH_ACCOUNT_ICON, SWITCH_ACCOUNT_ICON,
TOPIC_ICON,
HIERARCHY_ICON,
} from '../icons'; } from '../icons';
@Component({ @Component({
@@ -45,7 +48,7 @@ import {
AppMenuComponent, AppMenuComponent,
MatTooltipModule, MatTooltipModule,
AppSearchbarComponent, AppSearchbarComponent,
LoadingComponent, PageSkeletonComponent,
], ],
templateUrl: './app-layout.component.html', templateUrl: './app-layout.component.html',
styleUrl: './app-layout.component.scss', styleUrl: './app-layout.component.scss',
@@ -55,23 +58,31 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
readonly SWITCH_ACCOUNT_ICON = SWITCH_ACCOUNT_ICON; readonly SWITCH_ACCOUNT_ICON = SWITCH_ACCOUNT_ICON;
readonly MENU_ICON = MENU_ICON; readonly MENU_ICON = MENU_ICON;
readonly ARROW_BACK_ICON = ARROW_BACK_ICON; readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly PERSONS_ICON = PERSONS_ICON;
readonly PERSON_ICON = PERSON_ICON;
readonly PUBLICATION_ICON = PUBLICATION_ICON;
readonly PROJECT_ICON = PROJECT_ICON;
readonly INSTITUTION_ICON = INSTITUTION_ICON;
readonly PATENT_ICON = PATENT_ICON;
readonly NEWS_ICON = NEWS_ICON;
readonly HIERARCHY_ICON = HIERARCHY_ICON;
readonly TOPIC_ICON = TOPIC_ICON;
@ViewChild(MatDrawer, { static: false }) @ViewChild(MatDrawer, { static: false })
drawer?: MatDrawer; drawer?: MatDrawer;
mediaQuery: MediaQueryList; mediaQuery: MediaQueryList;
protected resolverState = inject(ResolverStateService); protected navigationState = inject(NavigationStateService);
mediaQueryListener: () => void; mediaQueryListener: () => void;
private readonly destroyRef = inject(DestroyRef);
private readonly backNavigation = inject(BackNavigationService);
private readonly scrollService = inject(RouteScrollService);
// Instantiated for their router subscriptions; keeps document.title in sync
// and moves focus to the new page heading after navigation.
private readonly pageTitle = inject(PageTitleService);
private readonly navigationFocus = inject(NavigationFocusService);
private readonly contentScroller =
viewChild<ElementRef<HTMLElement>>('contentScroller');
private readonly currentPath = signal('/');
readonly showBack = computed(
() =>
this.backNavigation.hasLocalHandler() ||
!this.backNavigation.isRoot(this.currentPath()),
);
private readonly sidebarCollapsedStorageKey = 'inse.sidebar.collapsed'; private readonly sidebarCollapsedStorageKey = 'inse.sidebar.collapsed';
sideNavOpen = false; sideNavOpen = false;
sideNavCollapsed = this.readSidebarCollapsedState(); sideNavCollapsed = this.readSidebarCollapsedState();
@@ -79,11 +90,11 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
constructor( constructor(
public credentialService: CredentialService, public credentialService: CredentialService,
public router: Router, public router: Router,
private readonly location: Location,
public changeDetector: ChangeDetectorRef, public changeDetector: ChangeDetectorRef,
media: MediaMatcher, media: MediaMatcher,
) { ) {
this.mediaQuery = media.matchMedia('(max-width: 600px)'); this.mediaQuery = media.matchMedia('(max-width: 600px)');
this.currentPath.set(this.pathOf(this.router.url));
this.mediaQueryListener = () => { this.mediaQueryListener = () => {
this.sideNavOpen = !this.mediaQuery.matches; this.sideNavOpen = !this.mediaQuery.matches;
@@ -93,6 +104,29 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
changeDetector.detectChanges(); changeDetector.detectChanges();
}; };
this.router.events
.pipe(
filter(
(event): event is NavigationEnd => event instanceof NavigationEnd,
),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((event) => {
this.currentPath.set(this.pathOf(event.urlAfterRedirects));
// On phones the drawer is an overlay; keep it from covering the
// freshly opened page.
if (this.mediaQuery.matches && this.sideNavOpen) {
this.sideNavOpen = false;
this.drawer?.close();
}
});
afterNextRender(() => {
const scroller = this.contentScroller()?.nativeElement;
if (scroller) this.scrollService.attach(scroller);
});
} }
toggle() { toggle() {
@@ -147,6 +181,10 @@ export class AppLayoutComponent implements OnInit, OnDestroy {
} }
navigateBack() { navigateBack() {
this.location.back(); this.backNavigation.back();
}
private pathOf(url: string): string {
return url.split('?')[0].split('#')[0] || '/';
} }
} }
@@ -237,7 +237,6 @@ export class AppMenuComponent {
route: '/founders', route: '/founders',
disabled: false, disabled: false,
queryParams: { queryParams: {
threshold: 90,
screened: 'true', screened: 'true',
page: 0, page: 0,
size: 10, size: 10,

Some files were not shown because too many files have changed in this diff Show More